diff --git a/.gitignore b/.gitignore index 417912d9..1431e7be 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +*.geany +*.cfg +*.cmd .project *.kdev4 latex @@ -5,3 +8,9 @@ html build*/ !game/server/database/build/ game/server/database/data/templates.sql +.codelite/ +.idea/ +build.log +*.phprj +*.project +*.workspace diff --git a/CMakeLists.txt b/CMakeLists.txt index cfe0cbfa..98680a83 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,12 +2,12 @@ cmake_policy(SET CMP0003 OLD) # or cmake_policy(VERSION 2.4) cmake_minimum_required(VERSION 2.8) -project(swgnge C CXX) +project(stellabellum C CXX) if(WIN32) -set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/win32") + set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/win32") elseif(UNIX) -set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/linux") + set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/linux") endif() set(SWG_ROOT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) @@ -16,13 +16,11 @@ set(SWG_EXTERNALS_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external) set(SWG_EXTERNALS_FIND ${CMAKE_CURRENT_SOURCE_DIR}/external/3rd/library) set(SWG_GAME_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/game) - include_directories(/usr/include/i386-linux-gnu) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) find_package(BISON REQUIRED) -find_package(Boost REQUIRED) find_package(FLEX REQUIRED) find_package(JNI REQUIRED) find_package(LibXml2 REQUIRED) @@ -31,29 +29,57 @@ find_package(PCRE REQUIRED) find_package(Perl REQUIRED) find_package(Threads) find_package(ZLIB REQUIRED) +find_package(CURL REQUIRED) if(WIN32) find_package(Iconv REQUIRED) - #Dont-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:libc.lib /SAFESEH:NO") + + #Dont-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:libc.lib /SAFESEH:NO") #################################### - #Do-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) + #Do-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) #set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DWIN32 -Dwin32 -DUDP_LIBRARY -DDEBUG_LEVEL=0 -DPRODUCTION=1 /Oi /Ot /Oy /O2 /GF /Gy /Zi /MT -D_USE_32BIT_TIME_T=1 -D_MBCS -DPLATFORM_BASE_SINGLE_THREAD -D_CRT_SECURE_NO_WARNINGS /MP /wd4244 /wd4996 /wd4018 /wd4351 /Zc:wchar_t- /Ob1 /FC") - #Dont-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) + #Dont-Build-PDB RELEASE build use the following (by either commenting---uncommenting the line as needed) set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DWIN32 -Dwin32 -DUDP_LIBRARY -DDEBUG_LEVEL=0 -DPRODUCTION=1 /Oi /Ot /Oy /O2 /GF /Gy /MT -D_USE_32BIT_TIME_T=1 -D_MBCS -DPLATFORM_BASE_SINGLE_THREAD -D_CRT_SECURE_NO_WARNINGS /MP /wd4244 /wd4996 /wd4018 /wd4351 /Zc:wchar_t- /Ob1 /FC") - + #################################### #Standard DEBUG build use the following (by either commenting---uncommenting the line as needed) set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DWIN32 -Dwin32 -D_DEBUG -DUDP_LIBRARY -DDEBUG_LEVEL=2 -DPRODUCTION=0 /MTd -D_USE_32BIT_TIME_T=1 -D_MBCS -DPLATFORM_BASE_SINGLE_THREAD -D_CRT_SECURE_NO_WARNINGS /MP /wd4244 /wd4996 /wd4018 /wd4351 /Zc:wchar_t- /Ob1 /FC") - elseif(UNIX) find_package(Curses REQUIRED) + #find_package(MULODI REQUIRED) + set(BUILD_MULODI_LIB FALSE) - set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -D_DEBUG -DDEBUG_LEVEL=2 -DPRODUCTION=0 -g3 -pipe -O0 -Wall -Wno-overloaded-virtual -Wno-missing-braces -Wno-format -Wno-write-strings -Wno-unknown-pragmas -Wno-uninitialized -Wno-reorder") - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DDEBUG_LEVEL=0 -DPRODUCTION=1 -pipe -march=native -mtune=native -O2 -Wno-overloaded-virtual -Wno-missing-braces -Wno-format -Wno-write-strings -Wno-unknown-pragmas -Wno-uninitialized -Wno-reorder") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0") + # linker flags + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-O1,--sort-common,--as-needed,-z,relro") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}") + # don't put anything too crazy in debug...and any common flags go into CMAKE_CXX_FLAGS + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -D_DEBUG -DDEBUG_LEVEL=2 -DPRODUCTION=0 -O0") + + # funroll loops and everything else potentially crazy for performance here + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DDEBUG_LEVEL=0 -DPRODUCTION=1 -Ofast -funroll-loops") + + # TODO: The below flags will enhance security but at the cost of performance, arguably... + # currently with them SWG cluster idles at ~17-18% of 24 cpus, and ata round ~14-17% without + # there is likely also a latency/speed impact as well + # not sure if needed or not - https://wiki.debian.org/Hardening + # ============================================================================================ + # -fstack-protector-all -Wstack-protector --param ssp-buffer-size=4 -fPIE -ftrapv + # -D_FORTIFY_SOURCE=2 is generally considered safe but crashes datatabletool when built with gcc + + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 \ + -m32 -pipe -march=native -mtune=native \ + -Wformat -Wno-overloaded-virtual -Wno-missing-braces -Wno-format \ + -Wno-write-strings -Wno-unknown-pragmas \ + -Wno-uninitialized -Wno-reorder") + + # we could use libc++ with gcc too but let's roll with default there + #if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + #endif() + add_definitions(-DLINUX -D_REENTRANT -Dlinux -D_USING_STL -D__STL_NO_BAD_ALLOC -D_GNU_SOURCE -D_XOPEN_SOURCE=500) endif() diff --git a/cmake/linux/FindJNI.cmake b/cmake/linux/FindJNI.cmake index fc15c9cc..57e63e3b 100644 --- a/cmake/linux/FindJNI.cmake +++ b/cmake/linux/FindJNI.cmake @@ -181,6 +181,7 @@ set(JAVA_AWT_INCLUDE_DIRECTORIES /usr/lib/jvm/java-8-oracle/include /usr/lib/jvm/java-7-oracle/include /usr/lib/jvm/java-6-oracle/include + /opt/java/include ) foreach(JAVA_PROG "${JAVA_RUNTIME}" "${JAVA_COMPILE}" "${JAVA_ARCHIVE}") diff --git a/cmake/linux/FindMULODI.cmake b/cmake/linux/FindMULODI.cmake new file mode 100644 index 00000000..6a46fdf1 --- /dev/null +++ b/cmake/linux/FindMULODI.cmake @@ -0,0 +1,26 @@ +# when using clang with m32, mulodi4 is missing...this checks for it/not +# if we're using linux/not + +include(CheckCXXSourceCompiles) +set(BUILD_MULODI_LIB FALSE) + +set(find_mulodi_test_program +"#include +#include +int main(int argc, char **argv) +{ + int64_t x = ((int64_t)atoi(argv[1])) * (int64_t)atoi(argv[2]) + * (int64_t)atoi(argv[3]); + return x == 9; +}") + +set(CMAKE_REQUIRED_FLAGS "-Wl,-O1,--sort-common,--as-needed,-z,relro,-flto -ftrapv -m32") +set(CMAKE_REQUIRED_LIBRARIES "") +CHECK_CXX_SOURCE_COMPILES( + "${find_mulodi_test_program}" + mulodi_found +) + +if(NOT mulodi_found) + set(BUILD_MULODI_LIB TRUE) +endif() diff --git a/engine/client/application/Miff/src/lex_yy.c b/engine/client/application/Miff/src/lex_yy.c index e9bd0436..df6de76d 100644 --- a/engine/client/application/Miff/src/lex_yy.c +++ b/engine/client/application/Miff/src/lex_yy.c @@ -271,7 +271,7 @@ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ - : NULL) + : nullptr) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. @@ -5779,7 +5779,7 @@ extern int isatty (int ); */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { - if (new_buffer == NULL) + if (new_buffer == nullptr) return; yyensure_buffer_stack(); @@ -5813,7 +5813,7 @@ void yypop_buffer_state (void) return; yy_delete_buffer(YY_CURRENT_BUFFER ); - YY_CURRENT_BUFFER_LVALUE = NULL; + YY_CURRENT_BUFFER_LVALUE = nullptr; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); @@ -6097,13 +6097,13 @@ int yylex_destroy (void) /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); - YY_CURRENT_BUFFER_LVALUE = NULL; + YY_CURRENT_BUFFER_LVALUE = nullptr; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); - (yy_buffer_stack) = NULL; + (yy_buffer_stack) = nullptr; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ diff --git a/engine/client/application/Miff/src/linux/InputFileHandler.cpp b/engine/client/application/Miff/src/linux/InputFileHandler.cpp index ead23d7c..0cb2d496 100755 --- a/engine/client/application/Miff/src/linux/InputFileHandler.cpp +++ b/engine/client/application/Miff/src/linux/InputFileHandler.cpp @@ -124,7 +124,7 @@ int InputFileHandler::deleteFile( if (deleteHandleFlag && file) { delete file; - file = NULL; + file = nullptr; } return(unlink(filename)); } diff --git a/engine/client/application/Miff/src/linux/OutputFileHandler.cpp b/engine/client/application/Miff/src/linux/OutputFileHandler.cpp index 1c8ffe96..82fa61a9 100755 --- a/engine/client/application/Miff/src/linux/OutputFileHandler.cpp +++ b/engine/client/application/Miff/src/linux/OutputFileHandler.cpp @@ -20,7 +20,7 @@ OutputFileHandler::OutputFileHandler(const char *filename) { outputIFF = new Iff(MAXIFFDATASIZE); - outFilename = NULL; + outFilename = nullptr; setCurrentFilename(filename); } @@ -45,7 +45,7 @@ OutputFileHandler::~OutputFileHandler(void) delete [] outFilename; } - outputIFF = NULL; + outputIFF = nullptr; } diff --git a/engine/client/application/Miff/src/linux/bison.simple b/engine/client/application/Miff/src/linux/bison.simple index 5f8f386e..27927e11 100644 --- a/engine/client/application/Miff/src/linux/bison.simple +++ b/engine/client/application/Miff/src/linux/bison.simple @@ -632,13 +632,6 @@ yyerrlab1: /* here on error raised explicitly by an action */ yyerrdefault: /* current state does not do anything special for the error token. */ -#if 0 - /* This is wrong; only states that explicitly want error tokens - should shift them. */ - yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/ - if (yyn) goto yydefault; -#endif - yyerrpop: /* pop the current state because it cannot handle the error token */ if (yyssp == yyss) YYABORT; diff --git a/engine/client/application/Miff/src/linux/miff.cpp b/engine/client/application/Miff/src/linux/miff.cpp index cd395ab5..8f62be65 100755 --- a/engine/client/application/Miff/src/linux/miff.cpp +++ b/engine/client/application/Miff/src/linux/miff.cpp @@ -53,9 +53,7 @@ #include // for tolower() //================================================= static vars assignment == -const int entryPointVersion = 1; // constantly check DataEntryPoint.h to see if this value has changed - -OutputFileHandler *outfileHandler = NULL; +OutputFileHandler *outfileHandler = nullptr; const int bufferSize = 16 * 1024 * 1024; const int maxStringSize = 256; const char version[] = "1.3 September 18, 2000"; @@ -242,7 +240,7 @@ int main( int argc, // number of args in commandline // static void callbackFunction(void) { - outfileHandler = NULL; + outfileHandler = nullptr; #ifdef WIN32 @@ -382,201 +380,6 @@ static errorType evaluateArgs(void) return retVal; return retVal; - -#if 0 - - errorType retVal = ERR_NONE; // assume no error has been found - bool outPathUsed = false; // flag to monitor if -o flag was used, if so, we can ignore -d, -p, -e, -f - bool inFileEntered = false; - int argc = CommandLine::getPlainCount(); - - // get default values from DOS - char currentDir[maxStringSize]; - if (NULL == getcwd(currentDir, maxStringSize)) // get current working directory - { - retVal = ERR_UNKNOWNDIR; - return(retVal); - } - drive[0] = currentDir[0]; // drive letter - drive[1] = 0; // and null terminate it - strcpy(extension, "IFF"); // default to uppercase .IFF - strcpy(directory, ¤tDir[2]); // get everything after the Drive: including the first backslash - filename[0] = 0; - - // see specs.txt for requests - // scan for any argv's that has '-' in the argv[n][0]'s character - for (int index = 0; index < argc; index++) // note: if using argv[] rather then CommandLine::getPlainString() then start with 1 rather then 0 - { - if ('-' == CommandLine::getPlainString(index)[0]) - { - // we've found a parameter switch - switch (tolower(CommandLine::getPlainString(index)[1])) // assume non case sensitive switches - { - case 'i': // install via #pragma - { - usePragma = true; - break; - } - - case 'c': // use CCCP instead of CPP - useCCCP = true; - break; - - case 'v': // don't show any debug message - verboseMode = true; - break; - - case '$': - debugMode = true; - break; - - case 'o': // target output file name and path (complete path) - { - index++; // next param - outPathUsed = true; - strcpy(outFileName, CommandLine::getPlainString(index)); - break; - - } - - case 'd': // target drive letter (-p must be present) - { - if (!outPathUsed) - { - index++; // next param - strcpy(drive, CommandLine::getPlainString(index)); - } - else - index++; // skip the drive letter arg that SHOULD follow the -d option - break; - } - - case 'p': // target pathname - { - if (!outPathUsed) - { - index++; // next param - strcpy(directory, CommandLine::getPlainString(index)); - } - else - index++; // skip the pathname arg that follows the -p option - break; - } - - case 'f': // target filename - { - if (!outPathUsed) - { - index++; // next param - strcpy(filename, CommandLine::getPlainString(index)); - } - else - index++; // skip the filename arg that follows the -f - break; - } - - case 'e': // target extension - { - if (!outPathUsed) - { - index++; // next param - strcpy(extension, CommandLine::getPlainString(index)); - } - else - index++; // skip the extension arg that follows the -e - break; - } - - case 'h': // help! - case '?': - { - help(); - index = argc; // force to exit - retVal = ERR_HELPREQUEST; - return(retVal); // special case, ONLY time I call return() in the middle of the function (because I check for argc < 2 at the end of the code) - break; - } - - default: - { - sprintf(err_msg, "\nUnknown parameter %s, use -h to seek help...\n", CommandLine::getPlainString(index)); - MIFFMessage(err_msg, 1); - index = argc; // force to exit - break; - } - } - } - else - { - // we found an arg that doesn't start with '-' so let's assume it's a filename - if (!inFileEntered) - { - strcpy(inFileName, CommandLine::getPlainString(index)); - inFileEntered = true; - } - else - { - retVal = ERR_MULTIPLEINFILE; - index = argc; - } - - // now construct the DEFAULT filename for this file by scanning backwards to front and only extracting the filename (no extension, no path) - if (ERR_NONE == retVal) - { - char sourceName[maxStringSize]; - strcpy(sourceName, inFileName); // make a duplicate for us to play with - for (int strIndex = strlen(sourceName); strIndex > 0; strIndex--) - { - if ('.' == sourceName[strIndex]) - sourceName[strIndex] = 0; // put a stopper here... we are assuming that '.' indicates extension! I'm going to assume that the person is just testing me if s/he decides to use filename like "foo.bar.psych" which will truncate to "foo" - if ('\\' == sourceName[strIndex]) - break; // get out, for we've reached the path name... - } - - // ok, by here, strIndex should point to either beginning of the string, or where the first '\' was found scanning backwards - strcpy(filename, &sourceName[strIndex]); // ta-da-! - } - } - } - - if (inFileEntered) - { - if (0 == preprocessSource(inFileName)) - { - if (verboseMode) - { - // using err_msg as my temp buffer... - sprintf(err_msg,"Now compiling %s\n", inFileName); - MIFFMessage(err_msg, 0); - } - - if (ERR_NONE == retVal) - retVal = loadInputToBuffer(sourceBuffer, bufferSize); - } - else // preprocessSource returned an error... - { - retVal = ERR_PREPROCESS; - } - } - else // inFileEntered == false - { - MIFFMessage("Missing input filename in command line!", 1); - } - - // construct a outFileName[] based on drive[], directory[], filename[], and extension[] - if (!outPathUsed && (ERR_NONE == retVal)) - { - if (inFileName[0]) // make sure the user has entered a input filename - sprintf(outFileName,"%s:%s\\%s.%s", drive, directory, filename, extension); - } - - if (argc < 1) - retVal = ERR_ARGSTOOFEW; // we can do this because we know -h was not entered... - - return(retVal); - -#endif - } @@ -619,7 +422,7 @@ static errorType loadInputToBuffer( // we've successfully read the file, now close it... delete inFileHandler; } - else // inFileName is NULL + else // inFileName is nullptr { retVal = ERR_FILENOTFOUND; } @@ -746,7 +549,7 @@ static void handleError(errorType error) // Revisions and History: // 1/07/99 [] - created // -extern "C" void MIFFMessage(char *message, // null terminated string to be displayed +extern "C" void MIFFMessage(char *message, // nullptr terminated string to be displayed int forceOutput) // if non-zero, it will print out even in quiet mode (for ERRORs) { if (forceOutput) diff --git a/engine/client/application/Miff/src/win32/BISON.HAI b/engine/client/application/Miff/src/win32/BISON.HAI new file mode 100644 index 00000000..999b5559 --- /dev/null +++ b/engine/client/application/Miff/src/win32/BISON.HAI @@ -0,0 +1,334 @@ + +extern int timeclock; + + +int yyerror; /* Yyerror and yycost are set by guards. */ +int yycost; /* If yyerror is set to a nonzero value by a */ + /* guard, the reduction with which the guard */ + /* is associated is not performed, and the */ + /* error recovery mechanism is invoked. */ + /* Yycost indicates the cost of performing */ + /* the reduction given the attributes of the */ + /* symbols. */ + + +/* YYMAXDEPTH indicates the size of the parser's state and value */ +/* stacks. */ + +#ifndef YYMAXDEPTH +#define YYMAXDEPTH 500 +#endif + +/* YYMAXRULES must be at least as large as the number of rules that */ +/* could be placed in the rule queue. That number could be determined */ +/* from the grammar and the size of the stack, but, as yet, it is not. */ + +#ifndef YYMAXRULES +#define YYMAXRULES 100 +#endif + +#ifndef YYMAXBACKUP +#define YYMAXBACKUP 100 +#endif + + +short yyss[YYMAXDEPTH]; /* the state stack */ +YYSTYPE yyvs[YYMAXDEPTH]; /* the semantic value stack */ +YYLTYPE yyls[YYMAXDEPTH]; /* the location stack */ +short yyrq[YYMAXRULES]; /* the rule queue */ +int yychar; /* the lookahead symbol */ + +YYSTYPE yylval; /* the semantic value of the */ + /* lookahead symbol */ + +YYSTYPE yytval; /* the semantic value for the state */ + /* at the top of the state stack. */ + +YYSTYPE yyval; /* the variable used to return */ + /* semantic values from the action */ + /* routines */ + +YYLTYPE yylloc; /* location data for the lookahead */ + /* symbol */ + +YYLTYPE yytloc; /* location data for the state at the */ + /* top of the state stack */ + + +int yynunlexed; +short yyunchar[YYMAXBACKUP]; +YYSTYPE yyunval[YYMAXBACKUP]; +YYLTYPE yyunloc[YYMAXBACKUP]; + +short *yygssp; /* a pointer to the top of the state */ + /* stack; only set during error */ + /* recovery. */ + +YYSTYPE *yygvsp; /* a pointer to the top of the value */ + /* stack; only set during error */ + /* recovery. */ + +YYLTYPE *yyglsp; /* a pointer to the top of the */ + /* location stack; only set during */ + /* error recovery. */ + + +/* Yyget is an interface between the parser and the lexical analyzer. */ +/* It is costly to provide such an interface, but it avoids requiring */ +/* the lexical analyzer to be able to back up the scan. */ + +yyget() +{ + if (yynunlexed > 0) + { + yynunlexed--; + yychar = yyunchar[yynunlexed]; + yylval = yyunval[yynunlexed]; + yylloc = yyunloc[yynunlexed]; + } + else if (yychar <= 0) + yychar = 0; + else + { + yychar = yylex(); + if (yychar < 0) + yychar = 0; + else yychar = YYTRANSLATE(yychar); + } +} + + + +yyunlex(chr, val, loc) +int chr; +YYSTYPE val; +YYLTYPE loc; +{ + yyunchar[yynunlexed] = chr; + yyunval[yynunlexed] = val; + yyunloc[yynunlexed] = loc; + yynunlexed++; +} + + + +yyrestore(first, last) +register short *first; +register short *last; +{ + register short *ssp; + register short *rp; + register int symbol; + register int state; + register int tvalsaved; + + ssp = yygssp; + yyunlex(yychar, yylval, yylloc); + + tvalsaved = 0; + while (first != last) + { + symbol = yystos[*ssp]; + if (symbol < YYNTBASE) + { + yyunlex(symbol, yytval, yytloc); + tvalsaved = 1; + ssp--; + } + + ssp--; + + if (first == yyrq) + first = yyrq + YYMAXRULES; + + first--; + + for (rp = yyrhs + yyprhs[*first]; symbol = *rp; rp++) + { + if (symbol < YYNTBASE) + state = yytable[yypact[*ssp] + symbol]; + else + { + state = yypgoto[symbol - YYNTBASE] + *ssp; + + if (state >= 0 && state <= YYLAST && yycheck[state] == *ssp) + state = yytable[state]; + else + state = yydefgoto[symbol - YYNTBASE]; + } + + *++ssp = state; + } + } + + if ( ! tvalsaved && ssp > yyss) + { + yyunlex(yystos[*ssp], yytval, yytloc); + ssp--; + } + + yygssp = ssp; +} + + + +int +yyparse() +{ + register int yystate; + register int yyn; + register short *yyssp; + register short *yyrq0; + register short *yyptr; + register YYSTYPE *yyvsp; + + int yylen; + YYLTYPE *yylsp; + short *yyrq1; + short *yyrq2; + + yystate = 0; + yyssp = yyss - 1; + yyvsp = yyvs - 1; + yylsp = yyls - 1; + yyrq0 = yyrq; + yyrq1 = yyrq0; + yyrq2 = yyrq0; + + yychar = yylex(); + if (yychar < 0) + yychar = 0; + else yychar = YYTRANSLATE(yychar); + +yynewstate: + + if (yyssp >= yyss + YYMAXDEPTH - 1) + { + yyabort("Parser Stack Overflow"); + YYABORT; + } + + *++yyssp = yystate; + +yyresume: + + yyn = yypact[yystate]; + if (yyn == YYFLAG) + goto yydefault; + + yyn += yychar; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar) + goto yydefault; + + yyn = yytable[yyn]; + if (yyn < 0) + { + yyn = -yyn; + goto yyreduce; + } + else if (yyn == 0) + goto yyerrlab; + + yystate = yyn; + + yyptr = yyrq2; + while (yyptr != yyrq1) + { + yyn = *yyptr++; + yylen = yyr2[yyn]; + yyvsp -= yylen; + yylsp -= yylen; + + yyguard(yyn, yyvsp, yylsp); + if (yyerror) + goto yysemerr; + + yyaction(yyn, yyvsp, yylsp); + *++yyvsp = yyval; + + yylsp++; + if (yylen == 0) + { + yylsp->timestamp = timeclock; + yylsp->first_line = yytloc.first_line; + yylsp->first_column = yytloc.first_column; + yylsp->last_line = (yylsp-1)->last_line; + yylsp->last_column = (yylsp-1)->last_column; + yylsp->text = 0; + } + else + { + yylsp->last_line = (yylsp+yylen-1)->last_line; + yylsp->last_column = (yylsp+yylen-1)->last_column; + } + + if (yyptr == yyrq + YYMAXRULES) + yyptr = yyrq; + } + + if (yystate == YYFINAL) + YYACCEPT; + + yyrq2 = yyptr; + yyrq1 = yyrq0; + + *++yyvsp = yytval; + *++yylsp = yytloc; + yytval = yylval; + yytloc = yylloc; + yyget(); + + goto yynewstate; + +yydefault: + + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + +yyreduce: + + *yyrq0++ = yyn; + + if (yyrq0 == yyrq + YYMAXRULES) + yyrq0 = yyrq; + + if (yyrq0 == yyrq2) + { + yyabort("Parser Rule Queue Overflow"); + YYABORT; + } + + yyssp -= yyr2[yyn]; + yyn = yyr1[yyn]; + + yystate = yypgoto[yyn - YYNTBASE] + *yyssp; + if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) + yystate = yytable[yystate]; + else + yystate = yydefgoto[yyn - YYNTBASE]; + + goto yynewstate; + +yysemerr: + *--yyptr = yyn; + yyrq2 = yyptr; + yyvsp += yyr2[yyn]; + +yyerrlab: + + yygssp = yyssp; + yygvsp = yyvsp; + yyglsp = yylsp; + yyrestore(yyrq0, yyrq2); + yyrecover(); + yystate = *yygssp; + yyssp = yygssp; + yyvsp = yygvsp; + yyrq0 = yyrq; + yyrq1 = yyrq0; + yyrq2 = yyrq0; + goto yyresume; +} + +$ diff --git a/engine/client/application/Miff/src/win32/InputFileHandler.cpp b/engine/client/application/Miff/src/win32/InputFileHandler.cpp new file mode 100644 index 00000000..b782e0cf --- /dev/null +++ b/engine/client/application/Miff/src/win32/InputFileHandler.cpp @@ -0,0 +1,136 @@ +//=========================================================================== +// +// FILENAME: InputFileHandler.cpp [C:\Projects\new\tools\src\miff\src\] +// COPYRIGHT: (C) 1999 BY Bootprint Entertainment +// +// DESCRIPTION: file handler for input files (standard flat text files) +// AUTHOR: Hideki Ikeda +// DATE: 1/13/99 4:53:31 PM +// +// HISTORY: 1/13/99 [HAI] - File created +// : +// +// FUNCTION: InputFileHandler() constructor +// : ~InputFileHandler() destructor +// : +// +//=========================================================================== + +//========================================================== include files == +#include "sharedFoundation/FirstSharedFoundation.h" +#include "InputFileHandler.h" + +#include "sharedFile/TreeFile.h" +//#include "sharedFile/Iff.h" + +//================================================= static vars assignment == + + + +//--------------------------------------------------------------------------- +// Constructor +// +// Remarks: +// +// +// See Also: +// +// +// Revisions and History: +// 1/13/99 [HAI] - created +// +InputFileHandler::InputFileHandler(const char *infilename) +{ + TreeFile::addSearchAbsolute(0); // search current working directory + + file = TreeFile::open(infilename, AbstractFile::PriorityData, true); + +} + + +//--------------------------------------------------------------------------- +// Destructor +// +// Remarks: +// +// +// See Also: +// +// +// Revisions and History: +// 1/13/99 [HAI] - created +// +InputFileHandler::~InputFileHandler(void) +{ + if(file) + delete file; +} + + +//--------------------------------------------------------------------------- +// reads a file stream into specified buffer of the size passed +// +// Return Value: +// actual size read (signed int) +// +// Remarks: +// +// +// See Also: +// Treefile::read() +// +// Revisions and History: +// 1/13/99 [HAI] - created +// +const int InputFileHandler::read( + void *sourceBuffer, // pointer to the buffer + int bufferSize // number of BYTES to be read + ) +{ + int retVal = -1; // assume fileHandle is NOT valid + + if (file) + retVal = file->read(sourceBuffer, bufferSize); + + return(retVal); +} + +//--------------------------------------------------------------------------- +// Deletes a file +// +// Return Value: +// whatever DeleteFile() returns +// if fileHandle != -1, it assumes that the fileHandle passed belonged to +// this filename, and therefore, it will attempt to close the file and +// set it to 0. +// +// Remarks: +// calls DeleteFile() found in windows.h +// InputFileHandler does NOT have any way to validate that the handle +// passed belongs to the filename that it wants to be deleted. So use +// it with caution +// +// See Also: +// windows.h +// +// Revisions and History: +// 1/13/99 [HAI] - created +// +int InputFileHandler::deleteFile( + const char *filename, + bool deleteHandleFlag + ) +{ + if (deleteHandleFlag && file) + { + delete file; + file = NULL; + } + return(DeleteFile(filename)); +} + + +//=========================================================================== +//============================================================ End-of-file == +//=========================================================================== + diff --git a/engine/client/application/Miff/src/win32/InputFileHandler.h b/engine/client/application/Miff/src/win32/InputFileHandler.h new file mode 100644 index 00000000..9e4734fe --- /dev/null +++ b/engine/client/application/Miff/src/win32/InputFileHandler.h @@ -0,0 +1,71 @@ +#ifndef __INPUTFILEHANDLER_H__ +#define __INPUTFILEHANDLER_H__ + +//=========================================================================== +// +// FILENAME: InputFileHandler.h [C:\Projects\new\tools\src\miff\src\] +// COPYRIGHT: (C) 1999 BY Bootprint Entertainment +// +// DESCRIPTION: file handler for input files (flat text files) +// AUTHOR: Hideki Ikeda +// DATE: 1/13/99 4:55:15 PM +// +// HISTORY: 1/13/99 [HAI] - File created +// : +// +//=========================================================================== + +//============================================================== #includes == + +//========================================================= class typedefs == + +//====================================================== class definitions == + +class AbstractFile; + +class InputFileHandler +{ +//------------------------------ +//--- public var & functions --- +//------------------------------ +public: // functions + InputFileHandler(const char *infilename); + ~InputFileHandler(void); + + const int read(void *sourceBuffer, int bufferSize); + int deleteFile(const char * filename, bool deleteHandleFlag = false); + +public: // vars + + + //------------------------------- + //--- member vars declaration --- + //------------------------------- +protected: // vars + AbstractFile *file; + +private: // vars + + //----------------------------------- + //--- member function declaration --- + //----------------------------------- +protected: // functions + +private: // functions + void close(void); // close the input file called by destructor + +}; + +//=========================================================================== +//========================================================= inline methods == +//=========================================================================== + + +//=========================================================================== +//============================================================ End-of-file == +//=========================================================================== +#else + #ifdef DEBUG + #pragma message("InputFileHandler.h included more then once!") + #endif +#endif // ifndef __H__ diff --git a/engine/client/application/Miff/src/win32/OutputFileHandler.cpp b/engine/client/application/Miff/src/win32/OutputFileHandler.cpp new file mode 100644 index 00000000..1c8ffe96 --- /dev/null +++ b/engine/client/application/Miff/src/win32/OutputFileHandler.cpp @@ -0,0 +1,164 @@ +//=========================================================================== +// +// FILENAME: OutputFileHandler.cpp +// COPYRIGHT: (C) 1999 BY Bootprint Entertainment +// +// DESCRIPTION: file handler for Output file (IFF file) +// AUTHOR: Hideki Ikeda +// DATE: 1/13/99 4:52:42 PM +// +//=========================================================================== + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "OutputFileHandler.h" + +#include "sharedFile/Iff.h" + +//=========================================================================== +// Constructor + +OutputFileHandler::OutputFileHandler(const char *filename) +{ + outputIFF = new Iff(MAXIFFDATASIZE); + outFilename = NULL; + + setCurrentFilename(filename); +} + +void OutputFileHandler::setCurrentFilename(const char *filename) +{ + if (outFilename) + delete [] outFilename; + + outFilename = new char[strlen(filename)+1]; + strcpy(outFilename, filename); +} + +//--------------------------------------------------------------------------- +// Destructor + +OutputFileHandler::~OutputFileHandler(void) +{ + if (outputIFF && outFilename) + { + delete outputIFF; + delete [] outFilename; + } + + outputIFF = NULL; +} + + +//--------------------------------------------------------------------------- +// begins a new FORM in the IFF +// +// Return Value: +// bool - true == success +// +// See Also: +// Iff::insertForm() + +void OutputFileHandler::insertForm( + const char *tag + ) +{ + Tag formTag = convertStrToTag(tag); + outputIFF->insertForm(formTag); +} + +//--------------------------------------------------------------------------- +// begins a new CHUNK in the IFF +// +// See Also: +// Iff::insertChunk() + +void OutputFileHandler::insertChunk( + const char *tag + ) +{ + Tag chunkTag = convertStrToTag(tag); + outputIFF->insertChunk(chunkTag); +} + + +//--------------------------------------------------------------------------- +// converts string (4 bytes) form into Tag format +// +// Return Value: +// Tag +// +// Remarks: +// currently, this code is machine dependant code (non portable) and it assumes little endian +// +// See Also: +// Tag + +Tag OutputFileHandler::convertStrToTag( + const char *str + ) +{ + // prepare for hack-o-rama. It is byte order dependant, thus not portable ^_^ + Tag retVal = str[3] + (str[2] * 0x100) + (str[1] * 0x10000) + (str[0] * 0x1000000); + + return(retVal); +} + + +//--------------------------------------------------------------------------- +// adds new chunk data into the current chunk it is in +// +// See Also: +// Iff::insertChunkData() +// + +void OutputFileHandler::insertChunkData( + void *data, + int length + ) +{ + outputIFF->insertChunkData(data, length); +} + +//--------------------------------------------------------------------------- +// exits current FORM section we are in +// +// See Also: +// Iff::exitForm() + +void OutputFileHandler::exitForm(void) +{ + outputIFF->exitForm(); +} + +//--------------------------------------------------------------------------- +// exits current CHUNK we are in +// +// See Also: +// Iff::exitChunk() + +void OutputFileHandler::exitChunk(void) +{ + outputIFF->exitChunk(); +} + + +//--------------------------------------------------------------------------- +// Calls Iff:write() +// +// Return Value: +// +// True if the Iff was successfully written, otherwise false +// +// See Also: +// Iff::write() + +bool OutputFileHandler::writeBuffer(void) +{ + if (outputIFF && outFilename) + return outputIFF->write(outFilename, true); + + return false; +} + +//=========================================================================== + diff --git a/engine/client/application/Miff/src/win32/OutputFileHandler.h b/engine/client/application/Miff/src/win32/OutputFileHandler.h new file mode 100644 index 00000000..5f4eaf58 --- /dev/null +++ b/engine/client/application/Miff/src/win32/OutputFileHandler.h @@ -0,0 +1,80 @@ +#ifndef __OUTPUTFILEHANDLER_H__ +#define __OUTPUTFILEHANDLER_H__ + +//=========================================================================== +// +// FILENAME: OutputFileHandler.h [C:\Projects\new\tools\src\miff\src\] +// COPYRIGHT: (C) 1999 BY Bootprint Entertainment +// +// DESCRIPTION: file handler for output files (IFF file format) +// AUTHOR: Hideki Ikeda +// DATE: 1/13/99 4:55:56 PM +// +// HISTORY: 1/13/99 [HAI] - File created +// : +// +//=========================================================================== + +//============================================================== #includes == + +//========================================================= class typedefs == +#include "sharedFile/Iff.h" + +//====================================================== class definitions == +class OutputFileHandler +{ +//------------------------------ +//--- public var & functions --- +//------------------------------ +public: // functions + OutputFileHandler(const char *filename); + ~OutputFileHandler(void); + bool writeBuffer(void); + + void insertForm(const char *tagName); + void insertChunk(const char *tagName); + void insertChunkData(void *data, int length); + void exitForm(void); + void exitChunk(void); + + void setCurrentFilename(const char *fname); + +public: // vars + + + //------------------------------- + //--- member vars declaration --- + //------------------------------- +protected: // vars + Iff * outputIFF; + char *outFilename; + +enum{ + MAXIFFDATASIZE = 8192 // allocate 8K of memory for a starter + }; + +private: // vars + + //----------------------------------- + //--- member function declaration --- + //----------------------------------- +protected: // functions + +private: // functions + Tag convertStrToTag(const char *str); + +}; + +//=========================================================================== +//========================================================= inline methods == +//=========================================================================== + + +//=========================================================================== +//============================================================ End-of-file == +//=========================================================================== +#else + #ifdef DEBUG + #pragma message("OutputFileHandler.h included more then once!") + #endif +#endif // ifndef __H__ diff --git a/engine/client/application/Miff/src/win32/bison.simple b/engine/client/application/Miff/src/win32/bison.simple new file mode 100644 index 00000000..5f8f386e --- /dev/null +++ b/engine/client/application/Miff/src/win32/bison.simple @@ -0,0 +1,698 @@ +/* -*-C-*- Note some compilers choke on comments on `#line' lines. */ +#line 3 "bison.simple" + +/* Skeleton output parser for bison, + Copyright (C) 1984, 1989, 1990 Free Software Foundation, 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 2, 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, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +/* As a special exception, when this file is copied by Bison into a + Bison output file, you may use that output file without restriction. + This special exception was added by the Free Software Foundation + in version 1.24 of Bison. */ + +#define MSDOS 1 + +#ifndef alloca +#ifdef __GNUC__ +#define alloca __builtin_alloca +#else /* not GNU C. */ +#if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) +#include +#else /* not sparc */ +#if defined (MSDOS) && !defined (__TURBOC__) +#include +#else /* not MSDOS, or __TURBOC__ */ +#if defined(_AIX) +#include + #pragma alloca +#else /* not MSDOS, __TURBOC__, or _AIX */ +#ifdef __hpux +#ifdef __cplusplus +extern "C" { +void *alloca (unsigned int); +}; +#else /* not __cplusplus */ +void *alloca (); +#endif /* not __cplusplus */ +#endif /* __hpux */ +#endif /* not _AIX */ +#endif /* not MSDOS, or __TURBOC__ */ +#endif /* not sparc. */ +#endif /* not GNU C. */ +#endif /* alloca not defined. */ + +#ifdef MSDOS +#define alloca(n) malloc(n) +#endif + +/* This is the parser code that is written into each bison parser + when the %semantic_parser declaration is not specified in the grammar. + It was written by Richard Stallman by simplifying the hairy parser + used when %semantic_parser is specified. */ + +/* Note: there must be only one dollar sign in this file. + It is replaced by the list of actions, each action + as one case of the switch. */ + +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) +#define YYEMPTY -2 +#define YYEOF 0 +#define YYACCEPT return(0) +#define YYABORT return(1) +#define YYERROR goto yyerrlab1 +/* Like YYERROR except do call yyerror. + This remains here temporarily to ease the + transition to the new meaning of YYERROR, for GCC. + Once GCC version 2 has supplanted version 1, this can go. */ +#define YYFAIL goto yyerrlab +#define YYRECOVERING() (!!yyerrstatus) +#define YYBACKUP(token, value) \ +do \ + if (yychar == YYEMPTY && yylen == 1) \ + { yychar = (token), yylval = (value); \ + yychar1 = YYTRANSLATE (yychar); \ + YYPOPSTACK; \ + goto yybackup; \ + } \ + else \ + { yyerror ("syntax error: cannot back up"); YYERROR; } \ +while (0) + +#define YYTERROR 1 +#define YYERRCODE 256 + +#ifndef YYPURE +#define YYLEX yylex() +#endif + +#ifdef YYPURE +#ifdef YYLSP_NEEDED +#ifdef YYLEX_PARAM +#define YYLEX yylex(&yylval, &yylloc, YYLEX_PARAM) +#else +#define YYLEX yylex(&yylval, &yylloc) +#endif +#else /* not YYLSP_NEEDED */ +#ifdef YYLEX_PARAM +#define YYLEX yylex(&yylval, YYLEX_PARAM) +#else +#define YYLEX yylex(&yylval) +#endif +#endif /* not YYLSP_NEEDED */ +#endif + +/* If nonreentrant, generate the variables here */ + +#ifndef YYPURE + +int yychar; /* the lookahead symbol */ +YYSTYPE yylval; /* the semantic value of the */ + /* lookahead symbol */ + +#ifdef YYLSP_NEEDED +YYLTYPE yylloc; /* location data for the lookahead */ + /* symbol */ +#endif + +int yynerrs; /* number of parse errors so far */ +#endif /* not YYPURE */ + +#if YYDEBUG != 0 +int yydebug = 1; /* nonzero means print parse trace */ +/* Since this is uninitialized, it does not stop multiple parsers + from coexisting. */ +#endif + +/* YYINITDEPTH indicates the initial size of the parser's stacks */ + +#ifndef YYINITDEPTH +#define YYINITDEPTH 200 +#endif + +/* YYMAXDEPTH is the maximum size the stacks can grow to + (effective only if the built-in stack extension method is used). */ + +#if YYMAXDEPTH == 0 +#undef YYMAXDEPTH +#endif + +#ifndef YYMAXDEPTH +#define YYMAXDEPTH 10000 +#endif + +/* Prevent warning if -Wstrict-prototypes. */ +#ifdef __GNUC__ +int yyparse (void); +#endif + +#if __GNUC__ > 1 /* GNU C and GNU C++ define this. */ +#define __yy_memcpy(TO,FROM,COUNT) __builtin_memcpy(TO,FROM,COUNT) +#else /* not GNU C or C++ */ +#ifndef __cplusplus + +/* This is the most reliable way to avoid incompatibilities + in available built-in functions on various systems. */ +static void +__yy_memcpy (to, from, count) + char *to; + char *from; + int count; +{ + register char *f = from; + register char *t = to; + register int i = count; + + while (i-- > 0) + *t++ = *f++; +} + +#else /* __cplusplus */ + +/* This is the most reliable way to avoid incompatibilities + in available built-in functions on various systems. */ +static void +__yy_memcpy (char *to, char *from, int count) +{ + register char *f = from; + register char *t = to; + register int i = count; + + while (i-- > 0) + *t++ = *f++; +} + +#endif +#endif + +#line 196 "bison.simple" + +/* The user can define YYPARSE_PARAM as the name of an argument to be passed + into yyparse. The argument should have type void *. + It should actually point to an object. + Grammar actions can access the variable by casting it + to the proper pointer type. */ + +#ifdef YYPARSE_PARAM +#ifdef __cplusplus +#define YYPARSE_PARAM_ARG void *YYPARSE_PARAM +#define YYPARSE_PARAM_DECL +#else /* not __cplusplus */ +#define YYPARSE_PARAM_ARG YYPARSE_PARAM +#define YYPARSE_PARAM_DECL void *YYPARSE_PARAM; +#endif /* not __cplusplus */ +#else /* not YYPARSE_PARAM */ +#define YYPARSE_PARAM_ARG +#define YYPARSE_PARAM_DECL +#endif /* not YYPARSE_PARAM */ + +int +yyparse(YYPARSE_PARAM_ARG) + YYPARSE_PARAM_DECL +{ + register int yystate; + register int yyn; + register short *yyssp; + register YYSTYPE *yyvsp; + int yyerrstatus; /* number of tokens to shift before error messages enabled */ + int yychar1 = 0; /* lookahead token as an internal (translated) token number */ + + short yyssa[YYINITDEPTH]; /* the state stack */ + YYSTYPE yyvsa[YYINITDEPTH]; /* the semantic value stack */ + + short *yyss = yyssa; /* refer to the stacks thru separate pointers */ + YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */ + +#ifdef YYLSP_NEEDED + YYLTYPE yylsa[YYINITDEPTH]; /* the location stack */ + YYLTYPE *yyls = yylsa; + YYLTYPE *yylsp; + +#define YYPOPSTACK (yyvsp--, yyssp--, yylsp--) +#else +#define YYPOPSTACK (yyvsp--, yyssp--) +#endif + + int yystacksize = YYINITDEPTH; + +#ifdef YYPURE + int yychar; + YYSTYPE yylval; + int yynerrs; +#ifdef YYLSP_NEEDED + YYLTYPE yylloc; +#endif +#endif + + YYSTYPE yyval; /* the variable used to return */ + /* semantic values from the action */ + /* routines */ + + int yylen; + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Starting parse\n"); +#endif + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + + /* Initialize stack pointers. + Waste one element of value and location stack + so that they stay on the same level as the state stack. + The wasted elements are never initialized. */ + + yyssp = yyss - 1; + yyvsp = yyvs; +#ifdef YYLSP_NEEDED + yylsp = yyls; +#endif + +/* Push a new state, which is found in yystate . */ +/* In all cases, when you get here, the value and location stacks + have just been pushed. so pushing a state here evens the stacks. */ +yynewstate: + + *++yyssp = yystate; + + if (yyssp >= yyss + yystacksize - 1) + { + /* Give user a chance to reallocate the stack */ + /* Use copies of these so that the &'s don't force the real ones into memory. */ + YYSTYPE *yyvs1 = yyvs; + short *yyss1 = yyss; +#ifdef YYLSP_NEEDED + YYLTYPE *yyls1 = yyls; +#endif + + /* Get the current used size of the three stacks, in elements. */ + int size = yyssp - yyss + 1; + +#ifdef yyoverflow + /* Each stack pointer address is followed by the size of + the data in use in that stack, in bytes. */ +#ifdef YYLSP_NEEDED + /* This used to be a conditional around just the two extra args, + but that might be undefined if yyoverflow is a macro. */ + yyoverflow("parser stack overflow", + &yyss1, size * sizeof (*yyssp), + &yyvs1, size * sizeof (*yyvsp), + &yyls1, size * sizeof (*yylsp), + &yystacksize); +#else + yyoverflow("parser stack overflow", + &yyss1, size * sizeof (*yyssp), + &yyvs1, size * sizeof (*yyvsp), + &yystacksize); +#endif + + yyss = yyss1; yyvs = yyvs1; +#ifdef YYLSP_NEEDED + yyls = yyls1; +#endif +#else /* no yyoverflow */ + /* Extend the stack our own way. */ + if (yystacksize >= YYMAXDEPTH) + { + yyerror("parser stack overflow"); + return 2; + } + yystacksize *= 2; + if (yystacksize > YYMAXDEPTH) + yystacksize = YYMAXDEPTH; + yyss = (short *) alloca (yystacksize * sizeof (*yyssp)); + __yy_memcpy ((char *)yyss, (char *)yyss1, size * sizeof (*yyssp)); + yyvs = (YYSTYPE *) alloca (yystacksize * sizeof (*yyvsp)); + __yy_memcpy ((char *)yyvs, (char *)yyvs1, size * sizeof (*yyvsp)); +#ifdef YYLSP_NEEDED + yyls = (YYLTYPE *) alloca (yystacksize * sizeof (*yylsp)); + __yy_memcpy ((char *)yyls, (char *)yyls1, size * sizeof (*yylsp)); +#endif +#endif /* no yyoverflow */ + + yyssp = yyss + size - 1; + yyvsp = yyvs + size - 1; +#ifdef YYLSP_NEEDED + yylsp = yyls + size - 1; +#endif + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Stack size increased to %d\n", yystacksize); +#endif + + if (yyssp >= yyss + yystacksize - 1) + YYABORT; + } + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Entering state %d\n", yystate); +#endif + + goto yybackup; + yybackup: + +/* Do appropriate processing given the current state. */ +/* Read a lookahead token if we need one and don't already have one. */ +/* yyresume: */ + + /* First try to decide what to do without reference to lookahead token. */ + + yyn = yypact[yystate]; + if (yyn == YYFLAG) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* yychar is either YYEMPTY or YYEOF + or a valid token in external form. */ + + if (yychar == YYEMPTY) + { +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Reading a token: "); +#endif + yychar = YYLEX; + } + + /* Convert token to internal form (in yychar1) for indexing tables with */ + + if (yychar <= 0) /* This means end of input. */ + { + yychar1 = 0; + yychar = YYEOF; /* Don't call YYLEX any more */ + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Now at end of input.\n"); +#endif + } + else + { + yychar1 = YYTRANSLATE(yychar); + +#if YYDEBUG != 0 + if (yydebug) + { + fprintf (stderr, "Next token is %d (%s", yychar, yytname[yychar1]); + /* Give the individual parser a way to print the precise meaning + of a token, for further debugging info. */ +#ifdef YYPRINT + YYPRINT (stderr, yychar, yylval); +#endif + fprintf (stderr, ")\n"); + } +#endif + } + + yyn += yychar1; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) + goto yydefault; + + yyn = yytable[yyn]; + + /* yyn is what to do for this token type in this state. + Negative => reduce, -yyn is rule number. + Positive => shift, yyn is new state. + New state is final state => don't bother to shift, + just return success. + 0, or most negative number => error. */ + + if (yyn < 0) + { + if (yyn == YYFLAG) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + else if (yyn == 0) + goto yyerrlab; + + if (yyn == YYFINAL) + YYACCEPT; + + /* Shift the lookahead token. */ + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]); +#endif + + /* Discard the token being shifted unless it is eof. */ + if (yychar != YYEOF) + yychar = YYEMPTY; + + *++yyvsp = yylval; +#ifdef YYLSP_NEEDED + *++yylsp = yylloc; +#endif + + /* count tokens shifted since error; after three, turn off error status. */ + if (yyerrstatus) yyerrstatus--; + + yystate = yyn; + goto yynewstate; + +/* Do the default action for the current state. */ +yydefault: + + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + +/* Do a reduction. yyn is the number of a rule to reduce with. */ +yyreduce: + yylen = yyr2[yyn]; + if (yylen > 0) + yyval = yyvsp[1-yylen]; /* implement default value of the action */ + +#if YYDEBUG != 0 + if (yydebug) + { + int i; + + fprintf (stderr, "Reducing via rule %d (line %d), ", + yyn, yyrline[yyn]); + + /* Print the symbols being reduced, and their result. */ + for (i = yyprhs[yyn]; yyrhs[i] > 0; i++) + fprintf (stderr, "%s ", yytname[yyrhs[i]]); + fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]); + } +#endif + +$ /* the action file gets copied in in place of this dollarsign */ +#line 498 "bison.simple" + + yyvsp -= yylen; + yyssp -= yylen; +#ifdef YYLSP_NEEDED + yylsp -= yylen; +#endif + +#if YYDEBUG != 0 + if (yydebug) + { + short *ssp1 = yyss - 1; + fprintf (stderr, "state stack now"); + while (ssp1 != yyssp) + fprintf (stderr, " %d", *++ssp1); + fprintf (stderr, "\n"); + } +#endif + + *++yyvsp = yyval; + +#ifdef YYLSP_NEEDED + yylsp++; + if (yylen == 0) + { + yylsp->first_line = yylloc.first_line; + yylsp->first_column = yylloc.first_column; + yylsp->last_line = (yylsp-1)->last_line; + yylsp->last_column = (yylsp-1)->last_column; + yylsp->text = 0; + } + else + { + yylsp->last_line = (yylsp+yylen-1)->last_line; + yylsp->last_column = (yylsp+yylen-1)->last_column; + } +#endif + + /* Now "shift" the result of the reduction. + Determine what state that goes to, + based on the state we popped back to + and the rule number reduced by. */ + + yyn = yyr1[yyn]; + + yystate = yypgoto[yyn - YYNTBASE] + *yyssp; + if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) + yystate = yytable[yystate]; + else + yystate = yydefgoto[yyn - YYNTBASE]; + + goto yynewstate; + +yyerrlab: /* here on detecting error */ + + if (! yyerrstatus) + /* If not already recovering from an error, report this error. */ + { + ++yynerrs; + +#ifdef YYERROR_VERBOSE + yyn = yypact[yystate]; + + if (yyn > YYFLAG && yyn < YYLAST) + { + int size = 0; + char *msg; + int x, count; + + count = 0; + /* Start X at -yyn if nec to avoid negative indexes in yycheck. */ + for (x = (yyn < 0 ? -yyn : 0); + x < (sizeof(yytname) / sizeof(char *)); x++) + if (yycheck[x + yyn] == x) + size += strlen(yytname[x]) + 15, count++; + msg = (char *) malloc(size + 15); + if (msg != 0) + { + strcpy(msg, "parse error"); + + if (count < 5) + { + count = 0; + for (x = (yyn < 0 ? -yyn : 0); + x < (sizeof(yytname) / sizeof(char *)); x++) + if (yycheck[x + yyn] == x) + { + strcat(msg, count == 0 ? ", expecting `" : " or `"); + strcat(msg, yytname[x]); + strcat(msg, "'"); + count++; + } + } + yyerror(msg); + free(msg); + } + else + yyerror ("parse error; also virtual memory exceeded"); + } + else +#endif /* YYERROR_VERBOSE */ + yyerror("parse error"); + } + + goto yyerrlab1; +yyerrlab1: /* here on error raised explicitly by an action */ + + if (yyerrstatus == 3) + { + /* if just tried and failed to reuse lookahead token after an error, discard it. */ + + /* return failure if at end of input */ + if (yychar == YYEOF) + YYABORT; + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]); +#endif + + yychar = YYEMPTY; + } + + /* Else will try to reuse lookahead token + after shifting the error token. */ + + yyerrstatus = 3; /* Each real token shifted decrements this */ + + goto yyerrhandle; + +yyerrdefault: /* current state does not do anything special for the error token. */ + +#if 0 + /* This is wrong; only states that explicitly want error tokens + should shift them. */ + yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/ + if (yyn) goto yydefault; +#endif + +yyerrpop: /* pop the current state because it cannot handle the error token */ + + if (yyssp == yyss) YYABORT; + yyvsp--; + yystate = *--yyssp; +#ifdef YYLSP_NEEDED + yylsp--; +#endif + +#if YYDEBUG != 0 + if (yydebug) + { + short *ssp1 = yyss - 1; + fprintf (stderr, "Error: state stack now"); + while (ssp1 != yyssp) + fprintf (stderr, " %d", *++ssp1); + fprintf (stderr, "\n"); + } +#endif + +yyerrhandle: + + yyn = yypact[yystate]; + if (yyn == YYFLAG) + goto yyerrdefault; + + yyn += YYTERROR; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) + goto yyerrdefault; + + yyn = yytable[yyn]; + if (yyn < 0) + { + if (yyn == YYFLAG) + goto yyerrpop; + yyn = -yyn; + goto yyreduce; + } + else if (yyn == 0) + goto yyerrpop; + + if (yyn == YYFINAL) + YYACCEPT; + +#if YYDEBUG != 0 + if (yydebug) + fprintf(stderr, "Shifting error token, "); +#endif + + *++yyvsp = yylval; +#ifdef YYLSP_NEEDED + *++yylsp = yylloc; +#endif + + yystate = yyn; + goto yynewstate; +} diff --git a/engine/client/application/Miff/src/win32/mIFF.dox b/engine/client/application/Miff/src/win32/mIFF.dox new file mode 100644 index 00000000..4c46d600 --- /dev/null +++ b/engine/client/application/Miff/src/win32/mIFF.dox @@ -0,0 +1,62 @@ +// NOTE: this makes it more convinient for me to make the help screen fancier... +// blah... not that anybody cares... + +printf("\ +Usage:\n\ + mIFF {-%c |--%s=}\n\ + [{-%c |--%s=} | {-%c|--%s}]\n\ + [{-%c|--%s}] [{-%c|--%s}] [{-%c|--%s}]\n\n", + SNAME_INPUT_FILE, LNAME_INPUT_FILE, + SNAME_OUTPUT_FILE, LNAME_OUTPUT_FILE, + SNAME_PRAGMA_TARGET, LNAME_PRAGMA_TARGET, + SNAME_CCCP, LNAME_CCCP, + SNAME_VERBOSE, LNAME_VERBOSE, + SNAME_DEBUG, LNAME_DEBUG); +printf("\ + mIFF {-%c|--%s}\n\n", SNAME_HELP, LNAME_HELP); + +printf("\ +Parameters:\n\ + -%c ,--%s=\n\ + [required] specifies the input path for IFF source file.\n", SNAME_INPUT_FILE, LNAME_INPUT_FILE); +printf("\ + -%c ,--%s=\n\ + [optional] specifies the pathname for the generated \n\ + IFF data file. Note that if neither this nor the following \n\ + option are specified, a default output filename of the source\n\ + file's base name with extension \".iff\" will be used.\n", SNAME_OUTPUT_FILE, LNAME_OUTPUT_FILE); +printf("\ + -%c,--%s\n\ + [optional] specifies the generated output filename should be \n\ + taken from the #pragma options within the source file. \n\ + Allowable #pragma options are: \n\ + #pragma drive \":\"\n\ + #pragma directory \"\"\n\ + #pragma filename \"\"\n\ + #pragma extension \"\"\n", SNAME_PRAGMA_TARGET, LNAME_PRAGMA_TARGET); +printf("\ + -%c,--%s\n\ + [optional] use CCCP rather than CPP.\n", SNAME_CCCP, LNAME_CCCP); +printf("\ + -%c,--%s\n\ + [optional] display more information during execution.\n", SNAME_VERBOSE, LNAME_VERBOSE); +printf("\ + -%c,--%s\n\ + [optional] enable debug mode (save intermediate files).\n", SNAME_DEBUG, LNAME_DEBUG); +printf("\ + -%c,--%s\n\ + [very optional] this help screen.\n", SNAME_HELP, LNAME_HELP); +printf("\ +Examples:\n\ + mIFF -%c foo.bar\n\ + this will generate an iff file foo.iff (default if no parm specified)\n\ + in the current working directory. Even if foo.bar contains #pragma, \n\ + it will create foo.iff because -%c was not specified.\n", SNAME_INPUT_FILE, SNAME_PRAGMA_TARGET); +printf("\ + mIFF -%c \"C:\\my project\\myData\\foo.iff\" --%s=foo.bar\n\ + notice that if you have space in your dirname, use \" to encapsulate \n\ + it.\n", SNAME_OUTPUT_FILE, LNAME_INPUT_FILE); +printf("\ + mIFF -%c foo.bar --%s\n\ + will generate output file specified by #pragma statements \n\ + within file foo.bar.\n", SNAME_INPUT_FILE, LNAME_PRAGMA_TARGET); diff --git a/engine/client/application/Miff/src/win32/miff.cpp b/engine/client/application/Miff/src/win32/miff.cpp new file mode 100644 index 00000000..89535216 --- /dev/null +++ b/engine/client/application/Miff/src/win32/miff.cpp @@ -0,0 +1,961 @@ +//=========================================================================== +// +// FILENAME: mIFF.cpp [C:\Projects\new\tools\src\miff\src\] +// COPYRIGHT: (C) 1999 BY Bootprint Entertainment +// +// DESCRIPTION: make IFF (Console version) +// AUTHOR: Hideki Ikeda +// DATE: 1/07/99 12:57:20 PM +// +// HISTORY: 1/07/99 [HAI] - File created +// : 1/07/99 [HAI] - v1.0 introductory version +// : 1/12/99 [HAI] - v1.1 switched from DOS to Engine library +// : - first attempt was to setup the main entry +// : point via ConsoleEntryPoint() via callback +// : 1/29/99 [HAI] - changed the parameter in MIFFMessage to allow +// : output even in non-verbose mode (for error +// : message purpose. +// : 05/07/99 [HAI]- added MIFFallocString() and MIFFfreeString() +// : to work with memory manager. they are allocated +// : in the lexical analyzer for IDENTIFIERS and STR_LIT +// : deleted after parser parses the rule. +// +// FUNCTION: main() +// : evaluateArgs() +// : help() +// : handleError() +// : preprocessSource() +// : MIFFMessage() +// : callbackFunction() +// +//=========================================================================== + +//========================================================== include files == +#include "sharedFoundation/FirstSharedFoundation.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/CommandLine.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedMemoryManager/MemoryManager.h" +#include "sharedThread/SetupSharedThread.h" + +#include "InputFileHandler.h" +#include "OutputFileHandler.h" + +#include // for memset() +#include // FILE stuff +#include // for getcwd() +#include // for tolower() +#include // for system() + +//================================================= static vars assignment == +const int entryPointVersion = 1; // constantly check DataEntryPoint.h to see if this value has changed + +OutputFileHandler *outfileHandler = NULL; +const int bufferSize = 16 * 1024 * 1024; +const int maxStringSize = 256; +const char version[] = "1.3 September 18, 2000"; + +// vars set by pragmas or via command line +char drive[4]; // should be no more then 2 char "C:" +char directory[maxStringSize]; +char filename[maxStringSize]; +char extension[8]; // we'll truncate if the extension is more then 8 chars... +char inFileName[maxStringSize]; + +// switches to be sent to mIFF Compiler +char sourceBuffer[bufferSize]; +char outFileName[(maxStringSize * 2) + 8]; // x2 to combine filename, dir, and ext +bool usePragma = false; +bool useCCCP = false; +bool verboseMode = false; // default to non-verbose mode +bool debugMode = false; // set this on and the preprocessed source file (mIFF.$$$) won't be deleted + +static bool runningUnderNT; + +enum errorType { + ERR_FILENOTFOUND = -1, + ERR_ARGSTOOFEW = -2, + ERR_BUFFERTOOSMALL = -3, + ERR_UNKNOWNDIR = -4, + ERR_PREPROCESS = -5, + ERR_MULTIPLEINFILE = -6, + ERR_PARSER = -7, + ERR_ENGINE = -8, + + ERR_HELPREQUEST = -9, + ERR_OPTIONS = -10, + + ERR_WRITEERROR = -11, + + ERR_NONE = 0 + }; +char err_msg[512]; +errorType errorFlag = ERR_NONE; // assume no error (default) + + +// long and short name definitions for command line options + +static const char * const LNAME_HELP = "help"; +static const char * const LNAME_INPUT_FILE = "inputfile"; +static const char * const LNAME_OUTPUT_FILE = "outputfile"; +static const char * const LNAME_PRAGMA_TARGET = "pragmatarget"; +static const char * const LNAME_CCCP = "cccp"; +static const char * const LNAME_VERBOSE = "verbose"; +static const char * const LNAME_DEBUG = "debug"; + +static const char SNAME_HELP = 'h'; +static const char SNAME_INPUT_FILE = 'i'; +static const char SNAME_OUTPUT_FILE = 'o'; +static const char SNAME_PRAGMA_TARGET = 'p'; +static const char SNAME_CCCP = 'c'; +static const char SNAME_VERBOSE = 'v'; +static const char SNAME_DEBUG = 'd'; + +// following is the command line option spec tree needed for command line processing +static CommandLine::OptionSpec optionSpecArray[] = +{ + OP_BEGIN_SWITCH(OP_NODE_REQUIRED), + + // help + OP_SINGLE_SWITCH_NODE(SNAME_HELP, LNAME_HELP, OP_ARG_NONE, OP_MULTIPLE_DENIED), + + // real options + OP_BEGIN_SWITCH_NODE(OP_MULTIPLE_DENIED), + OP_BEGIN_LIST(), + // input filename required + OP_SINGLE_LIST_NODE(SNAME_INPUT_FILE, LNAME_INPUT_FILE, OP_ARG_REQUIRED, OP_MULTIPLE_DENIED, OP_NODE_REQUIRED), + + // optional, mutually exclusive output file specification options + // if none specified, generate derive output filename from input filename + OP_BEGIN_LIST_NODE(OP_MULTIPLE_DENIED, OP_NODE_OPTIONAL), + OP_BEGIN_SWITCH(OP_NODE_OPTIONAL), + // specify output filename on command line + OP_SINGLE_SWITCH_NODE(SNAME_OUTPUT_FILE, LNAME_OUTPUT_FILE, OP_ARG_REQUIRED, OP_MULTIPLE_DENIED), + + // use pragma target for output filename + OP_SINGLE_SWITCH_NODE(SNAME_PRAGMA_TARGET, LNAME_PRAGMA_TARGET, OP_ARG_NONE, OP_MULTIPLE_DENIED), + OP_END_SWITCH(), + OP_END_LIST_NODE(), + + // if specified, use cccp instead of cpp + OP_SINGLE_LIST_NODE(SNAME_CCCP, LNAME_CCCP, OP_ARG_NONE, OP_MULTIPLE_DENIED, OP_NODE_OPTIONAL), + + // if specified, be verbose + OP_SINGLE_LIST_NODE(SNAME_VERBOSE, LNAME_VERBOSE, OP_ARG_NONE, OP_MULTIPLE_DENIED, OP_NODE_OPTIONAL), + + // if specified, enter debug info + OP_SINGLE_LIST_NODE(SNAME_DEBUG, LNAME_DEBUG, OP_ARG_NONE, OP_MULTIPLE_DENIED, OP_NODE_OPTIONAL), + OP_END_LIST(), + OP_END_SWITCH_NODE(), + + OP_END_SWITCH() +}; +static const int optionSpecCount = sizeof(optionSpecArray) / sizeof(optionSpecArray[0]); + +//================================================= function prototypes == +int main(int argc, char *argv[]); +static errorType evaluateArgs(void); +static void help(void); +static void handleError(errorType error); +static int preprocessSource(char *sourceName); +static void callbackFunction(void); +static errorType loadInputToBuffer(void *destAddr, int maxBufferSize); + +// functions called by parser.yac and parser.lex +extern "C" void MIFFMessage(char *msg, int forceOut); +extern "C" void MIFFSetError(void); +extern "C" void MIFFSetIFFName(const char *newFileName); +extern "C" void MIFFinsertForm(const char *formName); +extern "C" void MIFFinsertChunk(const char *chunkName); +extern "C" void MIFFinsertChunkData(void * buffer, unsigned bufferSize); +extern "C" int MIFFloadRawData(char *fname, void * buffer, unsigned maxBufferSize); +extern "C" void MIFFexitChunk(void); +extern "C" void MIFFexitForm(void); +extern "C" unsigned long MIFFgetLabelHash(char *inputStream); + +// external functions found in parser.lex file +extern "C" void MIFFCompile(char *inputStream, char *inputFname); +extern "C" void MIFFCompileInit(char *inputStream, char *inputFname); + +//--------------------------------------------------------------------------- +// main entry point from console call +// +// Return Value: +// errorType - see enumeration; 0 if no errors +// +// Remarks: +// +// +// See Also: +// +// +// Revisions and History: +// 1/07/99 [HAI] - created +// +int main( int argc, // number of args in commandline + char * argv[] // list of pointers to strings + ) +{ + memset(sourceBuffer, 0, bufferSize); + + SetupSharedThread::install(); + SetupSharedDebug::install(4096); + + SetupSharedFoundation::Data SetupSharedFoundationData (SetupSharedFoundation::Data::D_console); + SetupSharedFoundationData.useWindowHandle = false; + SetupSharedFoundationData.argc = argc; + SetupSharedFoundationData.argv = argv; + SetupSharedFoundationData.demoMode = true; + SetupSharedFoundation::install (SetupSharedFoundationData); + + SetupSharedCompression::install(); + + SetupSharedFile::install(false); + + TreeFile::addSearchAbsolute(0); + TreeFile::addSearchPath (".", 0); + + SetupSharedFoundation::callbackWithExceptionHandling(callbackFunction); + SetupSharedFoundation::remove(); + + SetupSharedThread::remove(); + return static_cast (errorFlag); +} + +//--------------------------------------------------------------------------- +// callback function for Engine's console entry point +// +// Return Value: +// none +// +// Remarks: +// this is like a substitute of main() +// +// See Also: +// +// +// Revisions and History: +// 1/12/99 [HAI] - created +// +static void callbackFunction(void) +{ + outfileHandler = NULL; + +#ifdef WIN32 + + // check if we're running under NT + OSVERSIONINFO osInfo; + Zero(osInfo); + + osInfo.dwOSVersionInfoSize = sizeof(osInfo); + const BOOL getVersionResult = GetVersionEx(&osInfo); + if (getVersionResult) + runningUnderNT = (osInfo.dwPlatformId == VER_PLATFORM_WIN32_NT); + if (runningUnderNT) + DEBUG_REPORT_LOG(true, ("MIFF: running under Windows NT platform\n")); + else + DEBUG_REPORT_LOG(true, ("MIFF: running under non-NT Windows platform\n")); + +#endif + + errorFlag = evaluateArgs(); + if (ERR_NONE == errorFlag) + { + outfileHandler = new OutputFileHandler(outFileName); + MIFFCompile(sourceBuffer, inFileName); + } + else + handleError(errorFlag); + + if (outfileHandler) + { + // only write output IF there was no error + if (ERR_NONE == errorFlag) + { + if (!outfileHandler->writeBuffer()) + { + fprintf(stderr, "MIFF: failed to write output file \"%s\"\n", outFileName); + errorFlag = ERR_WRITEERROR; + } + } + delete outfileHandler; + } +} + +//--------------------------------------------------------------------------- +// Evaluates the command line and sets up the environment variables required for mIFF to function +// +// Return Value: +// errorType +// +// Remarks: +// argc's and argv's are substituted with CommandLine::functions() +// +// See Also: +// +// +// Revisions and History: +// 1/07/99 [HAI] - created +// +static errorType evaluateArgs(void) +{ + errorType retVal = ERR_NONE; + + // parse the commandline + const CommandLine::MatchCode mc = CommandLine::parseOptions(optionSpecArray, optionSpecCount); + if (mc != CommandLine::MC_MATCH) + { + // -TF- add call to retrieve command line error buffer for display (as soon as it is written!) + printf("WARNING: usage error detected, printing help.\n"); + help(); + return ERR_OPTIONS; + } + else if (CommandLine::getOccurrenceCount(SNAME_HELP)) + { + // user specified help + help(); + retVal = ERR_HELPREQUEST; + return(retVal); + } + + // at this point, we can assume a valid combination of options has been specified on the commandline + + + // setup input filename + strcpy(inFileName, CommandLine::getOptionString(SNAME_INPUT_FILE)); + + + // handle output filename spec + if (CommandLine::getOccurrenceCount(SNAME_OUTPUT_FILE)) + { + strcpy(outFileName, CommandLine::getOptionString(SNAME_OUTPUT_FILE)); + } + else if (CommandLine::getOccurrenceCount(SNAME_PRAGMA_TARGET)) + { + // use pragma target within iff source for output filename + usePragma = true; + } + else + { + // no output option specified on commandline, derive from input filename + char *terminator; + + // start with input file pathname + strcpy(outFileName, inFileName); + + // try to terminate at rightmost '.' + terminator = strrchr(outFileName, '.'); + if (terminator) + *terminator = 0; + + // append the default iff extension + strcat(outFileName, ".iff"); + } + + + // handle options (get them out of the way, as we use them later) + useCCCP = (CommandLine::getOccurrenceCount(SNAME_CCCP) != 0); + verboseMode = (CommandLine::getOccurrenceCount(SNAME_VERBOSE) != 0); + debugMode = (CommandLine::getOccurrenceCount(SNAME_DEBUG) != 0); + + + // preprocess the input file + if (0 == preprocessSource(inFileName)) + { + if (verboseMode) + { + sprintf(err_msg,"Now compiling %s...\n", inFileName); + MIFFMessage(err_msg, 0); + } + if (ERR_NONE == retVal) + retVal = loadInputToBuffer(sourceBuffer, bufferSize); + } + else + { + // preprocessSource returned an error... + retVal = ERR_PREPROCESS; + } + if (retVal != ERR_NONE) + return retVal; + + return retVal; + +#if 0 + + errorType retVal = ERR_NONE; // assume no error has been found + bool outPathUsed = false; // flag to monitor if -o flag was used, if so, we can ignore -d, -p, -e, -f + bool inFileEntered = false; + int argc = CommandLine::getPlainCount(); + + // get default values from DOS + char currentDir[maxStringSize]; + if (NULL == getcwd(currentDir, maxStringSize)) // get current working directory + { + retVal = ERR_UNKNOWNDIR; + return(retVal); + } + drive[0] = currentDir[0]; // drive letter + drive[1] = 0; // and null terminate it + strcpy(extension, "IFF"); // default to uppercase .IFF + strcpy(directory, ¤tDir[2]); // get everything after the Drive: including the first backslash + filename[0] = 0; + + // see specs.txt for requests + // scan for any argv's that has '-' in the argv[n][0]'s character + for (int index = 0; index < argc; index++) // note: if using argv[] rather then CommandLine::getPlainString() then start with 1 rather then 0 + { + if ('-' == CommandLine::getPlainString(index)[0]) + { + // we've found a parameter switch + switch (tolower(CommandLine::getPlainString(index)[1])) // assume non case sensitive switches + { + case 'i': // install via #pragma + { + usePragma = true; + break; + } + + case 'c': // use CCCP instead of CPP + useCCCP = true; + break; + + case 'v': // don't show any debug message + verboseMode = true; + break; + + case '$': + debugMode = true; + break; + + case 'o': // target output file name and path (complete path) + { + index++; // next param + outPathUsed = true; + strcpy(outFileName, CommandLine::getPlainString(index)); + break; + + } + + case 'd': // target drive letter (-p must be present) + { + if (!outPathUsed) + { + index++; // next param + strcpy(drive, CommandLine::getPlainString(index)); + } + else + index++; // skip the drive letter arg that SHOULD follow the -d option + break; + } + + case 'p': // target pathname + { + if (!outPathUsed) + { + index++; // next param + strcpy(directory, CommandLine::getPlainString(index)); + } + else + index++; // skip the pathname arg that follows the -p option + break; + } + + case 'f': // target filename + { + if (!outPathUsed) + { + index++; // next param + strcpy(filename, CommandLine::getPlainString(index)); + } + else + index++; // skip the filename arg that follows the -f + break; + } + + case 'e': // target extension + { + if (!outPathUsed) + { + index++; // next param + strcpy(extension, CommandLine::getPlainString(index)); + } + else + index++; // skip the extension arg that follows the -e + break; + } + + case 'h': // help! + case '?': + { + help(); + index = argc; // force to exit + retVal = ERR_HELPREQUEST; + return(retVal); // special case, ONLY time I call return() in the middle of the function (because I check for argc < 2 at the end of the code) + break; + } + + default: + { + sprintf(err_msg, "\nUnknown parameter %s, use -h to seek help...\n", CommandLine::getPlainString(index)); + MIFFMessage(err_msg, 1); + index = argc; // force to exit + break; + } + } + } + else + { + // we found an arg that doesn't start with '-' so let's assume it's a filename + if (!inFileEntered) + { + strcpy(inFileName, CommandLine::getPlainString(index)); + inFileEntered = true; + } + else + { + retVal = ERR_MULTIPLEINFILE; + index = argc; + } + + // now construct the DEFAULT filename for this file by scanning backwards to front and only extracting the filename (no extension, no path) + if (ERR_NONE == retVal) + { + char sourceName[maxStringSize]; + strcpy(sourceName, inFileName); // make a duplicate for us to play with + for (int strIndex = strlen(sourceName); strIndex > 0; strIndex--) + { + if ('.' == sourceName[strIndex]) + sourceName[strIndex] = 0; // put a stopper here... we are assuming that '.' indicates extension! I'm going to assume that the person is just testing me if s/he decides to use filename like "foo.bar.psych" which will truncate to "foo" + if ('\\' == sourceName[strIndex]) + break; // get out, for we've reached the path name... + } + + // ok, by here, strIndex should point to either beginning of the string, or where the first '\' was found scanning backwards + strcpy(filename, &sourceName[strIndex]); // ta-da-! + } + } + } + + if (inFileEntered) + { + if (0 == preprocessSource(inFileName)) + { + if (verboseMode) + { + // using err_msg as my temp buffer... + sprintf(err_msg,"Now compiling %s\n", inFileName); + MIFFMessage(err_msg, 0); + } + + if (ERR_NONE == retVal) + retVal = loadInputToBuffer(sourceBuffer, bufferSize); + } + else // preprocessSource returned an error... + { + retVal = ERR_PREPROCESS; + } + } + else // inFileEntered == false + { + MIFFMessage("Missing input filename in command line!", 1); + } + + // construct a outFileName[] based on drive[], directory[], filename[], and extension[] + if (!outPathUsed && (ERR_NONE == retVal)) + { + if (inFileName[0]) // make sure the user has entered a input filename + sprintf(outFileName,"%s:%s\\%s.%s", drive, directory, filename, extension); + } + + if (argc < 1) + retVal = ERR_ARGSTOOFEW; // we can do this because we know -h was not entered... + + return(retVal); + +#endif + +} + + +//--------------------------------------------------------------------------- +// reads the tmeporary files spit out by CCCP and stuffs the plain text into source buffer +// +// Return Value: +// errorType +// +// Remarks: +// +// +// See Also: +// +// +// Revisions and History: +// 1/14/99 [HAI] - created +// +static errorType loadInputToBuffer( + void * dest, // destination address of where you want the date to be read + int maxBufferSize // maximum destination data pool size + ) +{ + errorType retVal = ERR_NONE; + InputFileHandler *inFileHandler = new InputFileHandler("mIFF.$$$"); + if (inFileHandler) + { + int sizeRead = inFileHandler->read(dest, maxBufferSize); + if (sizeRead >= maxBufferSize) + { + retVal = ERR_BUFFERTOOSMALL; + } + else + { + reinterpret_cast(dest)[sizeRead] = 0; // so stupid... but if you don't zero-terminate at exact spot, YYInput may chokes because of extra grammer that may exist... + } + if (!debugMode) + inFileHandler->deleteFile("mIFF.$$$", true); // no need for temp file now... + + // we've successfully read the file, now close it... + delete inFileHandler; + } + else // inFileName is NULL + { + retVal = ERR_FILENOTFOUND; + } + + return(retVal); +} + +//--------------------------------------------------------------------------- +// help function called by main upon -h switch +// +// Return Value: +// none +// +// Remarks: +// #include's mIFF.dox +// make sure to update the version when modified. +// Notice that help() does NOT go thru MIFFMessage() because we want it to +// print out whether it's verbose mode or not... +// +// See Also: +// mIFF.dox +// +// Revisions and History: +// 1/07/99 [HAI] - created +// +static void help(void) +{ + printf("\nmIFF v%s (DOS version) - Bootprint Ent. (c) 1999\n", version); + printf("Hideki Ikeda\n"); +#include "mIFF.dox" +} + + +//--------------------------------------------------------------------------- +// upon exit from main(), if error has been found, it calls here to inform the user of the type of errors it has encounted. +// +// Return Value: +// none +// +// Remarks: +// use -q switch to suppress error messages - but in shell, return value can be used to determine the handling +// +// See Also: +// +// +// Revisions and History: +// 1/07/99 [HAI] - created +// +static void handleError(errorType error) +{ + if (ERR_NONE == error) + return; + + switch (error) + { + case ERR_NONE: + break; + + case ERR_FILENOTFOUND: + MIFFMessage("ERROR: INPUT File not found!\n", 1); + break; + + case ERR_ARGSTOOFEW: + MIFFMessage("ERROR: Not enough arguments. Use -h for help.\n", 1); + break; + + case ERR_BUFFERTOOSMALL: + MIFFMessage("ERROR: Internally allocated buffer for reading\nsource code is too small, increase buffer and re-compile\n", 1); + break; + + case ERR_UNKNOWNDIR: + MIFFMessage("ERROR: Directory unknown...\n", 1); + break; + + case ERR_PREPROCESS: + MIFFMessage("ERROR: Possible problems running the GNU C Preprocessor.\n", 1); + break; + + case ERR_MULTIPLEINFILE: + MIFFMessage("ERROR: There can only be ONE inputfile name.\nPerhaps you've forgotten the -o option flag\n", 1); + break; + + case ERR_ENGINE: + MIFFMessage("ERROR: Engine returned a non-zero value...\n", 1); + break; + + case ERR_PARSER: + MIFFMessage("ERROR: Parser error\n", 1); + break; + + case ERR_HELPREQUEST: + break; + + case ERR_OPTIONS: + MIFFMessage("ERROR: Failed to handle command line options\n", 1); + break; + + default: + MIFFMessage("ERROR: Unknown error, you suck!\n", 1); + break; + } +} + + +///////////////////////////////////////////////////////////////////////////// +// gotta write all these externs because you can't call C++ class based non-static +// functions from C... So we will use here as the bridge between the two +// languages + + +//--------------------------------------------------------------------------- +// Message output handler called by ALL external "C" functions +// +// Return Value: +// none +// +// Remarks: +// all the messages that are displayed are channeled thru this function. Note the -q quiet mode suppresses all messages. +// this is an extern "C" function +// +// See Also: +// yyerror() +// +// Revisions and History: +// 1/07/99 [] - created +// +extern "C" void MIFFMessage(char *message, // null terminated string to be displayed + int forceOutput) // if non-zero, it will print out even in quiet mode (for ERRORs) +{ + if (forceOutput) + fprintf(stdout, "%s\n", message); + else if (verboseMode) + fprintf(stdout, "%s\n", message); + OutputDebugString(message); + OutputDebugString("\n"); +} + +// Only call this via parser!!! +extern "C" void MIFFSetError(void) +{ + errorFlag = ERR_PARSER; +} + +//--------------------------------------------------------------------------- +// validation of the filename passed are legal. +// +// Return Value: +// bool usePragma - whether #pragma is ignored or not +// +// Remarks: +// if -i switch is used then #pragma's are expected +// this is an extern "C" function +// +// See Also: +// +// +// Revisions and History: +// 1/07/99 [ ] - created +// +extern "C" int validateTargetFilename( char *targetFileName, // pointer to where we can store the string filename + unsigned maxTargetBufSize // size of the filename string buffer + ) +{ + if (strlen(outFileName) > maxTargetBufSize) + MIFFMessage("Internal error, increase string buffer size in parser.yac and recompile!", 1); + + strcpy(targetFileName, outFileName); + + return(usePragma); +} + + +//--------------------------------------------------------------------------- +// function calls CCCP or CPP via shell to preprocess the source code for #include's and #define's via C-Compatible Compiler Preprocessor +// +// Return Value: +// shell return value (4DOS is very generous on returning different values, while DOS just returns 0 all the time) +// +// Remarks: +// use -c switch to use CCCP rather then CPP in your search path +// +// See Also: +// +// +// Revisions and History: +// 1/07/99 [ ] - created +// +static int preprocessSource(char *sourceName) +{ + char shellCommand[512]; + int retVal = 0; + + memset(shellCommand, 0, sizeof(shellCommand)); + +// if (!runningUnderNT) + { + + if (verboseMode) + MIFFMessage("Preprocessing... via CCCP", 0); + + // CCCP parameters: + // -nostdinc -nostdinc++ - do NOT search for standard include directory; without this, your + // puter would be just twiddling its thumb because CCCP can't find it... + // -pedantic - issue warnings (use pedantic-errors if you want it as errors) + // required by the ANSI C standard in certain cases such as comments that + // follow the #else/#endif + // -dD - output #defines (for the purpose of error msg I parse) + // -H - display the name of the header/included files (verbose mode) + // -P - originally, I had this... so it won't show the # line_num "filename" ??? + if (!useCCCP && verboseMode) + { + sprintf(shellCommand, "cpp.exe -nostdinc -nostdinc++ -pedantic -Wall -dD -H %s mIFF.$$$", sourceName); + } + else if (!useCCCP && !verboseMode) + { + sprintf(shellCommand, "cpp.exe -nostdinc -nostdinc++ -pedantic -Wall -dD %s mIFF.$$$", sourceName); + } + else if (useCCCP && verboseMode) + { + sprintf(shellCommand, "cccp.exe -nostdinc -nostdinc++ -pedantic -Wall -dD -H %s mIFF.$$$", sourceName); + } + else + sprintf(shellCommand, "cccp.exe -nostdinc -nostdinc++ -pedantic -Wall -dD %s mIFF.$$$", sourceName); + } +// else + { + // running under NT. Use the MSVC cl since it deals with long filenames on fat16/fat32 partitions correctly + // and ccp and cccp don't +// sprintf(shellCommand, "cl /nologo /W4 /EP %s > mIFF.$$$", sourceName); + } + + retVal = system(shellCommand); + if (2 == retVal) // actually, I think 4DOS reports 2 for cannot find file, but DOS returns a 0... + { + REPORT_LOG(true, ("failed to execute following shell command (%d):\n", retVal)); + REPORT_LOG(true, (" %s\n", shellCommand)); + MIFFMessage("\n\nERROR: Cannot find preprocessor (either CCCP.EXE, CPP.EXE or CL.EXE (under NT) in the search path...\n", 1); + MIFFMessage("Please make sure the preprocessor is in your search path!\n", 1); + } + return(retVal); +} + +extern "C" void MIFFSetIFFName(const char *newFileName) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->setCurrentFilename(newFileName); +} + +extern "C" void MIFFinsertForm(const char *formName) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->insertForm(formName); +} + +extern "C" void MIFFinsertChunk(const char *chunkName) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->insertChunk(chunkName); +} + +extern "C" void MIFFinsertChunkData(void * buffer, unsigned bufferSize) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->insertChunkData(buffer, bufferSize); +} + +extern "C" int MIFFloadRawData(char *fname, void * buffer, unsigned maxBufferSize) +{ + int sizeRead = -1; + + if (ERR_NONE != errorFlag) + return(sizeRead); // should be -1 + + InputFileHandler * inFileName = new InputFileHandler(fname); + if (inFileName) + { + sizeRead = inFileName->read(buffer, maxBufferSize); + if (static_cast(sizeRead) >= maxBufferSize) + { + handleError(ERR_BUFFERTOOSMALL); + sizeRead = -1; + } + delete inFileName; + } + + return(sizeRead); +} + +extern "C" void MIFFexitChunk(void) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->exitChunk(); +} +extern "C" void MIFFexitForm(void) +{ + if (ERR_NONE != errorFlag) + return; + + if (outfileHandler) + outfileHandler->exitForm(); +} + +extern "C" char * MIFFallocString(int sizeOfString) +{ + return(new char[sizeOfString]); +} + +extern "C" void MIFFfreeString(char * pointer) +{ + delete [] pointer; +} + +extern "C" unsigned long MIFFgetLabelHash(char * inputStream) +{ + return (unsigned long)Crc::calculate(inputStream); +} + +//=========================================================================== +//============================================================ End-of-file == +//=========================================================================== + diff --git a/engine/client/application/Miff/src/win32/parser.lex b/engine/client/application/Miff/src/win32/parser.lex new file mode 100644 index 00000000..b2996a07 --- /dev/null +++ b/engine/client/application/Miff/src/win32/parser.lex @@ -0,0 +1,517 @@ +%option full + +%{ +/*-----------------------------------------------------------------------------** +** FILE: parser.lex ** +** (c) 1998 - Bootprint GTInteractive ** +** ** +** DESCRIPTION: lexical analyzer for mIFF ** +** ** +** AUTHOR: Hideki Ikeda ** +** ** +** HISTORY: ** +** ** +** Notes: companion to parser.yac ** +**-----------------------------------------------------------------------------*/ +/* Disable compiler warnings (we want warning level 4) for anything that flex spits out */ +#pragma warning (disable: 4127) /* conditional expression is constant - ie. while(1) */ +#pragma warning (disable: 4131) /* usage of old-style declarator */ +#pragma warning (disable: 4098) /* void function returning a vlue - this is because yyterminate() is defined as return() */ +#pragma warning (disable: 4505) /* unreferenced local function has been removed (to be direct: yyunput()) */ + +/* include files */ +#include "parser.h" /* NOTE: make sure this matches what Bison/yacc spits out */ + +#include +#include + +/*--------------------------------** +** exteranl prototype declaration ** +**--------------------------------*/ +void MIFFMessage(char *message, int forceOutput); +void MIFFSetError(void); +char * MIFFallocString(int sizeOfString); +void MIFFfreeString(char * pointer); + +int yyparse(); + +/* prototype declaration */ +int MIFFYYInput(char *buf,int max_size); +void initParser(void); +void count(void); +void yyerror(char *err); +void open_brace(void); +void close_brace(void); +int count_brace(void); + +void printString(char *str); + +/* global vars that has to be pre-declared because it's referenced by the lexical analyzer */ +int initialCompile = 0; +int globalErrorFlag = 0; +char inFileName[512]; /* keep track of source file name for error message */ + +#undef YY_INPUT +#define YY_INPUT(buf,result,max_size) (result = MIFFYYInput(buf,max_size)) + +#define SPACE_COUNT_FOR_TAB (8) + +%} + +DIGIT [0-9] +HEXDIGIT [0-9a-fA-F] +LETTER [A-z_] +FLOATSYM (f|F|l|L) +INTSYM (u|U|l|L)* +EXP (e|E)(\+|-)? + +%% +"//"[^\n]*\n { + /* don't do count(); */ + } + +"#define"[^\n]*\n { + /* don't you love regular expression? [^\n]* everything but \n, and then end with \n */ + /* don't do count(); just like comments */ + /* return(DEFINE); <-- note: #define's are ignored in parser for they are handled via preprocessors CCCP */ + } + +\"([^\"]|(\\\"))*\" { + /* start with " then ( [^\"] | (\\\") )* which means either anything but " OR \" of multiple encounter, and then close with " */ + /* case for "string" literals */ + char *s; // allocate space for string and pass the string pointer rather then yytext + + count(); + s = MIFFallocString(strlen(yytext) + 1); + strcpy(s, yytext+1); /* strip off the double quotes */ + s[strlen(yytext+1)-1] = 0; /* strip off the ending double quotes */ + yylval.stype = s; + return(STR_LIT); + } + +"form" | +"FORM" { + count(); + return(FORM); + } + +"chunk" | +"CHUNK" { + count(); + return(CHUNK); + } + +"int32" { + count(); + return(INT32); + } +"int16" { + count(); + return(INT16); + } +"int8" { + count(); + return(INT8); + } +"uint32" { + count(); + return(UINT32); + } +"uint16" { + count(); + return(UINT16); + } +"uint8" { + count(); + return(UINT8); + } +"float" { + count(); + return(FLOAT); + } +"double" { + count(); + return(DOUBLE); + } +"string" | +"cstring" | +"CString" { + count(); + return(STRING); + } +"wstring" | +"WString" { + count(); + return(WSTRING); + } +"labelhash" { + count(); + return(LABELHASH); + } + +"sin" { + count(); + return(SIN); + } +"cos" { + count(); + return(COS); + } +"tan" { + count(); + return(TAN); + } +"asin" { + count(); + return(ASIN); + } +"acos" { + count(); + return(ACOS); + } +"atan" { + count(); + return(ATAN); + } + +"enum" { + count(); + return(ENUMSTRUCT); + } + +"includeIFF" | +"includeiff" { + count(); + return(INCLUDEIFF); + } +"include" { + count(); + return(INCLUDEBIN); + } +"#include" { + count(); + return(INCLUDESOURCE); + } +"#pragma" { + count(); + return(PRAGMA); + } +"drive" { + count(); + return(PRAGMA_DRIVE); + } +"directory" { + count(); + return(PRAGMA_DIR); + } +"filename" { + count(); + return(PRAGMA_FNAME); + } +"extension" { + count(); + return(PRAGMA_EXT); + } + +{LETTER}({LETTER}|{DIGIT})* { + /* label identifiers */ + char *s; // allocate space for string and pass the string pointer rather then yytext + + count(); + s = MIFFallocString(strlen(yytext) + 1); + strcpy(s, yytext); + yylval.stype = s; + return(IDENTIFIER); + } + +{DIGIT}*"."{DIGIT}+{FLOATSYM}? { + /* handle numericals (floats) */ + /* + * {DIGIT}*"."{DIGIT}+{FLOATSYM}? means zero or more digits . one or more digit and with/without f at the end + */ + count(); + /* make sure to store it to dtype, and use strtod to convert to double */ + yylval.dtype = strtod((char *) yytext, (char **) 0); + return(FLOAT_LIT); + } + +0[xX]{HEXDIGIT}+{INTSYM}? | +0{DIGIT}+{INTSYM}? | +{DIGIT}+{INTSYM}? { + /* handle numericals ( hex, ints) */ + /* + * 0[xX]{HEXDIGIT}+{INTSYM}? means start with 0, then X one or more digit and you can put int symbol if you want + * 0{DIGIT}+{INTSYM}? means start with 0, one ore more digit and w/or w/o int symbol + * {DIGIT}+{INTSYM}? means one or more digit and w/or w/o int symbol + */ + count(); + /* make sure to store it to ltype (long), and use strtod to convert to unsigned long */ + yylval.ltype = strtoul((char *) yytext, (char **) 0, 0); + return(LIT); + } + +'(\\.|[^\\'])+' { + /* handle 'x' - single character */ + count(); + yylval.chtype = yytext[1]; + return(CHAR_LIT); + } + +"#" { + /* #'s are used for informing the parser which file and line number it is processing (debug purpose) */ + count(); + return(POUND); + } + +">>" { + count(); + return(SHIFTRIGHT); + } +"<<" { + count(); + return(SHIFTLEFT); + } +"^^" { + count(); + return(RAISEDPOWER); + } + +"[" | +"]" | +"^" | +";" | +"," | +":" | +"=" | +"(" | +")" | +"." | +"&" | +"!" | +"~" | +"-" | +"+" | +"*" | +"/" | +"%" | +"<" | +">" | +"|" | +"?" { + /* valid operators */ + count(); + yylval.stype = yytext; + return(* yylval.stype); + } + +"{" { + count(); + open_brace(); + yylval.stype = yytext; + return(* yylval.stype); + } +"}" { + count(); + close_brace(); + yylval.stype = yytext; + return(* yylval.stype); + } + +[ \t\n\r]+ { + /* white spaces and newlines are ignored */ + count(); + } + +<> { + /* do a count on bracket matching... */ + if (0 == count_brace()) + { + if (!initialCompile && !globalErrorFlag) + MIFFMessage("mIFF successfully compiled!\n", 0); + } + + yyterminate(); /* tell yyparse() it's time to quit! DO NOT comment or delete this line! */ + } + +. { + /* anything that's not a rule from above goes here */ + count(); + yyerror((char *) yytext); + } +%% + +/*--------------------** +** C supporting codes ** +**--------------------*/ + +/*------------------** +** static variables ** +**------------------*/ +static char *MIFFInputStream; +int column = 0; +int line_num = 1; +int line_num2 = 1; +char error_line_buffer[4096]; +long brace_counter = 0; + + +/*---------------------------------------------------------------------** +** Initialize all the static variables before all calls to MIFFCompile ** +**---------------------------------------------------------------------*/ +void initParser(void) +{ + line_num = 1; + column = 0; + + brace_counter = 0; + error_line_buffer[0] = 0; + + globalErrorFlag = 0; + + memset(inFileName, 0, 512); /* make sure to change this size if the char array gets bigger... */ +} + +/*-------------------------------------------------** +** generate a dialog box to MFC to report an error ** +**-------------------------------------------------*/ +void yyerror(char *err) /* called by yyparse() */ +{ + char myString[256]; + + if (!initialCompile) + { + /* spit it out in MSDev error format */ + sprintf(myString, "\n%s(%d) : yyERROR : %s\n>>%s<<", inFileName, line_num, err, error_line_buffer); + MIFFMessage(myString, 1); + globalErrorFlag = 1; + MIFFSetError(); /* set global error flag for shell as well */ + yyterminate(); + } + +} + +/*-------------------------** +** our version of YY_INPUT ** +**-------------------------*/ +int MIFFYYInput(char *buf,int max_size) +{ + int len = strlen(MIFFInputStream); + int n = max_size < len ? max_size : len; + if (n > 0) + { + memcpy(buf,MIFFInputStream,n); + MIFFInputStream += n; + } + return(n); +} + +/*------------------------------------------------------------** +** line and column counter for error searching during compile ** +**------------------------------------------------------------*/ +void count() +{ + int i; + static char *elb = error_line_buffer; + for (i = 0; yytext[i] != '\0'; i++) + { + if (yytext[i] == '\n') + { + column = 0; + line_num++; + elb = error_line_buffer; + } + else + { + *elb++ = yytext[i]; + if (yytext[i] == '\t') + column += SPACE_COUNT_FOR_TAB - (column & (SPACE_COUNT_FOR_TAB - 1)); + else + column++; + } + *elb = 0; + } +} + +/*--------------------------------------------------------------** +** sets up current line number and filename the error came from ** +**--------------------------------------------------------------*/ +void setCurrentLineNumber(int lineNum, char * fileName, int mysteryNum) +{ + line_num = lineNum; + strcpy(inFileName, fileName); + line_num2 = mysteryNum; +} + +/*----------------------------------------------** +** MIFFCompile called by CMIFFView::OnCompile() ** +**----------------------------------------------*/ +void MIFFCompile(char *inputStream, char *inputFileName) +{ + MIFFInputStream = inputStream; + yyrestart(0); + initParser(); + initialCompile = 0; + strcpy(inFileName, inputFileName); + yyparse(); +} + +void MIFFCompileInit(char *inputStream, char *inputFileName) +{ + MIFFInputStream = inputStream; + yyrestart(0); + initParser(); + initialCompile = 1; + strcpy(inFileName, inputFileName); + yyparse(); +} + +/*---------------------------------------** +** matching of open/close brace checking ** +**---------------------------------------*/ +void open_brace(void) +{ + brace_counter++; +} + +void close_brace(void) +{ + brace_counter--; +} + +/* + * what: count_brace(): + * return: 0 == all braces matched + */ +int count_brace(void) +{ + if (0 == brace_counter) /* things are fine... */ + return(0); + + /* if this is called, we should have 0 brace counter if not, we have a mis-match*/ + if (brace_counter > 0) + { + /* a mismatch */ + yyerror("There are more OPEN brackets then closed"); + } + else if (brace_counter < 0) + { + yyerror("There are more CLOSED brackets then open"); + } + + return(-1); +} + +/*-----------------------------------------------------------------------** +** FLEX.SLK requires this prototype function so I'm forced to do this... ** +**-----------------------------------------------------------------------*/ +int yywrap() +{ + return(1); +} + +void printString(char *str) +{ + char ts[256]; + sprintf(ts, "%s - %s", str, yytext); + MIFFMessage(ts, 0); +} diff --git a/engine/client/application/Miff/src/win32/parser.yac b/engine/client/application/Miff/src/win32/parser.yac new file mode 100644 index 00000000..1bfec252 --- /dev/null +++ b/engine/client/application/Miff/src/win32/parser.yac @@ -0,0 +1,1004 @@ +%expect 1 +%{ +/*-----------------------------------------------------------------------------** +** FILE: parser.yac ** +** (c) 1998 - Bootprint GTInteractive ** +** ** +** DESCRIPTION: parser for mIFF ** +** ** +** AUTHOR: Hideki Ikeda ** +** HISTORY: ** +** ** +** Notes: companion to parser.lex ** +**-----------------------------------------------------------------------------*/ + +/*---------------** +** C declaration ** +**---------------*/ +#pragma warning (disable: 4005) /* macro redefinition - bision.simple redefines alloca() */ +#pragma warning (disable: 4127) /* conditional expression is constant - in bison.simple */ +#pragma warning (disable: 4131) /* uses old-style declarator - mostly in bison.simple */ +#pragma warning (disable: 4244) /* possible loss of data due to conversion from one type to another - bision.simple */ +#pragma warning (disable: 4701) /* local variable ('yyval' in first case) may be used without having been initialed */ +// #pragma warning (disable: 6311) /* compiler malloc.h: see previous definition of alloca() */ + +/* include files */ +#include /* for pow() and stuff */ +#include +#include /* for toupper() */ +#include /* for wide character (16bit) strings */ + +#include +#include + +/*----------------------------------------------------------------** +** debug options, turn these on to TEST ONLY! don't leave these ** +** switch on, it's annoying as hell in console mode! ** +** NOTE: if you turn YYERROR_VERBOSE on, you MUST have YYDEBUG! ** +** IMHO, it's better off using primitive printf() method to debug ** +**----------------------------------------------------------------*/ +#define YYERROR_VERBOSE 1 +#define YYDEBUG 1 + +#undef YYERROR_VERBOSE +#undef YYDEBUG + +/* external prototype declaration */ +extern void MIFFMessage(char *message); /* found in mIFF.CPP */ +extern char * MIFFallocString(int sizeOfString); +extern void MIFFfreeString(char * pointer); +extern int validateTargetFilename(char *fname, int fnameSize); /* found mIFF.CPP */ +extern void yyerror(char *); +extern int yylex(void); +extern void setCurrentLineNumber(int lineNum, char * fileName, int mysteryNum); +extern void MIFFSetIFFName(const char *newFileName); +extern void MIFFinsertForm(const char *formName); +extern void MIFFinsertChunk(const char *chunkName); +extern void MIFFinsertChunkData(void * buffer, unsigned bufferSize); +extern int MIFFloadRawData(char *fname, void * buffer, unsigned maxBufferSize); +extern void MIFFexitChunk(void); +extern void MIFFexitForm(void); +extern unsigned long MIFFgetLabelHash(char *inputStream); + +/* local prototype declaration */ +void initGlobalVars(void); +void checkArgs(void); +void checkPragmas(void); + +void includeBinary(char *fname); + +void write32(long i32); +void write16(short i16); +void write8(char i8); +void writeU32(unsigned long ui32); +void writeU16(unsigned short ui16); +void writeU8(unsigned char u8); +void writeDouble(double d); +void writeFloat(float f); +void writeString(char *s); +void writeString16(char *s); +void writeLabelHash(char *s); +void writeTag(char *tag); +void writeSize(unsigned long size); +void writeData(void *dataPtr, unsigned dataSize); + +void initSymTable(void); +long searchEnumSymbolTable(char *symString); +long getEnumValue(long index); +void addEnumSymbol(char *symString, long value); +void parseESCstring(char *str, char *targetBuffer, int sizeOfTarget); + +/*----------------------------------------------** +** Global vars used by all functions and parser ** +**----------------------------------------------*/ +char err_msg[256]; +int errorFlag; + +/*-----------------------------------------------------------------------------** +** NOTE: this symbol table is ONLY used to construct symbols for enum table!!! ** +**-----------------------------------------------------------------------------*/ +#define MAX_SYMBOLS (1024) /* total number of symbols it can grow to... */ +#define MAX_SYMCHARS (128) /* I label thee insane if you have more the 128 char for your variable! */ +struct structEnumSymTableType +{ + char symbol[MAX_SYMCHARS]; + long value; +}; + +struct structEnumSymTableType symbolEnumTable[MAX_SYMBOLS]; +unsigned currSymIndex = 0; +long lastValue = -1; +char id[MAX_SYMCHARS]; + +/* vars set by pragmas */ +#define MAX_BUFFER_SIZE (16 * 1024 * 1024) +#define MAX_STRING_SIZE (512) +char drive[8]; +char directory[MAX_STRING_SIZE/2]; +char filename[MAX_STRING_SIZE/2]; +char extension[8]; +char outFileName[MAX_STRING_SIZE]; +int usePragmas; + +/*------------------------------------------------------------------------** +** The IRONY of these so-called temp-data's that are GLOBAL is ** +** that they aren't temp if functions called within are also using it ** +** This really gives me the creeps and goosbumps! DOWN with GLOBAL VARS! ** +**------------------------------------------------------------------------*/ +int iTemp, jTemp; +char byteTemp; +short wordTemp; +char tempStr[MAX_STRING_SIZE]; + +%} + +/*--------------------** +** Bison declarations ** +**--------------------*/ +%union { + long ltype; + double dtype; + char *stype; + char chtype; + + int tokentype; +} + +/*------------------------------------------------** +** define tokens defined in lex file ** +** NOTE: all LITERALs are treated as signed long ** +** all FLOAT_LITERALs are treated as double ** +**------------------------------------------------*/ +%token CHAR_LIT +%token STR_LIT +%token IDENTIFIER +%token LIT +%token FLOAT_LIT + +/* all command tokens are type */ +%token INT32 +%token INT16 +%token INT8 +%token UINT32 +%token UINT16 +%token UINT8 +%token FLOAT +%token DOUBLE +%token STRING +%token WSTRING +%token LABELHASH + +%token FORM +%token CHUNK +%token PRAGMA +%token PRAGMA_DRIVE PRAGMA_DIR PRAGMA_FNAME PRAGMA_EXT +%token ENUMSTRUCT +%token INCLUDESOURCE +%token INCLUDEBIN +%token INCLUDEIFF +%token SIN +%token COS +%token TAN +%token ACOS +%token ASIN +%token ATAN +%token POUND +%token SHIFTRIGHT +%token SHIFTLEFT +%token RAISEDPOWER + +%% + +/*------------------------------------------------------------------------** +** Begin Grammar rules ** +** ** +** Note: if possible, always try to use left recurrsion rather then right ** +** to save stack depth... ** +**------------------------------------------------------------------------*/ +mIFFSource: + { + /* initialize some global varibles before we start */ + initGlobalVars(); + checkArgs(); + } + preprocessor + { + /* take care of any mIFF related preprocessors that we might encounter */ + checkPragmas(); + } + body + ; + +/*----------------------** +** Preprocessor handler ** +**----------------------*/ +preprocessor: { /* we don't really have to have preprocessor */} + | preprocessor pragma + | preprocessor debugInfo /* we have to have debugInfo or else pragma gets confused when it finds a # line */ + ; + +pragma: PRAGMA PRAGMA_DRIVE STR_LIT { + if (usePragmas) + { + strcpy(drive, $3); + if (strlen(drive) > 2) + { + sprintf(err_msg, "Drive [%s] is not a valid drive [must be in C: format]", drive); + yyerror(err_msg); + } + drive[1] = ':'; + drive[2] = 0; + } + MIFFfreeString($3); + } + | PRAGMA PRAGMA_DIR STR_LIT { + if (usePragmas) + { + strcpy(directory, $3); + if (directory[strlen(directory)] != '\\') + directory[strlen(directory)] = '\\'; + directory[strlen(directory) + 1] = 0; + } + MIFFfreeString($3); + } + | PRAGMA PRAGMA_FNAME STR_LIT { + if (usePragmas) + strcpy(filename, $3); + MIFFfreeString($3); + } + | PRAGMA PRAGMA_EXT STR_LIT { + if (usePragmas) + strcpy(extension, $3); + MIFFfreeString($3); + } + | PRAGMA IDENTIFIER STR_LIT { + sprintf(err_msg, "Unknown PRAGMA identifier [%s]", $2); + yyerror(err_msg); + MIFFfreeString($2); + MIFFfreeString($3); + } + ; + +/*-------------------------------------------------------** +** This is the #line pragmas in a format of: ** +** # lineNum "FileName" mysteryNumber ** +** We call setCurrentLineNumber so when an error occurs, ** +** it will be sync'd to correct filename and linenumber ** +**-------------------------------------------------------*/ +debugInfo: POUND LIT STR_LIT { setCurrentLineNumber($2, $3, 0); MIFFfreeString($3);} + | POUND LIT STR_LIT LIT { setCurrentLineNumber($2, $3, $4); MIFFfreeString($3);} + ; + +/*-----------------------** +** The main body section ** +**-----------------------*/ +body: /* body can be empty */ + | body form formbody + | body chunk chunkbody + | body enumSection + | body includesource { /* do nothing... should not exist if went thru the preprocessor */ } + | body includeIFF + | body debugInfo + ; + +/*------------------------** +** Enumeration definition ** +**------------------------*/ +enumSection: ENUMSTRUCT enumDeclare '{' enumBody '}' enumType ';' { /* enumSection */ } + ; + +enumDeclare: { /* could have no declaration */ lastValue = -1; } + | IDENTIFIER { /* enumDeclare: ID */ lastValue = -1; MIFFfreeString($1);} + ; + +enumBody: { /* enumBody: can be empty list */ } + | enumAssign { /* enumAssign */ } + | enumBody ',' enumAssign { /* enumAssign, enumBody */ } + ; + +enumAssign: IDENTIFIER '=' exprL { + addEnumSymbol($1, $3); + MIFFfreeString($1); + } + | IDENTIFIER { /* in this case, inc 1 from last count */ + addEnumSymbol($1, ++lastValue); + MIFFfreeString($1); + } + ; + +enumType: /* type declaration can be empty */ + | enumList + ; + +enumList: IDENTIFIER { /* enumList: just ID */ MIFFfreeString($1);} + | enumList ',' IDENTIFIER { /* enumList: ID, enumList */ MIFFfreeString($3);} + ; + +/*----------------------------** +** different types of include ** +**----------------------------*/ +includesource: INCLUDESOURCE STR_LIT { /* do nothing... because CCCP/preprocessor takes care of this*/ MIFFfreeString($2);} + ; + +includebin: INCLUDEBIN STR_LIT { includeBinary($2); MIFFfreeString($2);} + ; + +includeIFF: INCLUDEIFF STR_LIT { includeBinary($2); MIFFfreeString($2);} + ; + +/*------------------** +** the FORM section ** +**------------------*/ +form: FORM STR_LIT { + /* first make sure we have 4 char for FORM name */ + if (strlen($2) > 4) + { + sprintf(err_msg, "FORM name %s greater then 4 char", $2); + yyerror(err_msg); + } + else if (!errorFlag) + { + /* pack the string with ' ' (spaces) if less then 4 chars */ + strcpy(tempStr, $2); + if (strlen(tempStr) < 4) + { + /* pack the string */ + for (iTemp = strlen(tempStr);iTemp < 4; iTemp++) + { + tempStr[iTemp] = ' '; /* pack it with space */ + } + } + + /* let's make sure we don't have a smart ass who wants to do form "FORM" */ + if ((toupper(tempStr[0]) == 'F') && + (toupper(tempStr[1]) == 'O') && + (toupper(tempStr[2]) == 'R') && + (toupper(tempStr[3]) == 'M')) + { + yyerror("FORM name CANNOT BE 'FORM'... nice try bozo!"); + } + + /* FORM */ + MIFFinsertForm(tempStr); + } + MIFFfreeString($2); + } + ; + +formbody: '{' formelements '}' { if (!errorFlag) MIFFexitForm(); }; + +formelements: body { /* recursion of multiple depth in form is allowed */ } + | INCLUDEBIN STR_LIT { + yyerror("Found attempt to include binary file inside FORM\nBinary file inclusion ONLY allowed inside a CHUNK!\nError"); + MIFFfreeString($2); + } + ; + +/*-------------------** +** the CHUNK section ** +**-------------------*/ +chunk: CHUNK STR_LIT { + /* first make sure we have 4 char for CHUNK name */ + if (strlen($2) > 4) + { + sprintf(err_msg, "CHUNK name %s greater then 4 char", $2); + yyerror(err_msg); + } + else if (!errorFlag) + { + /* pack the string with ' ' (spaces) if less then 4 chars */ + strcpy(tempStr, $2); + if (strlen(tempStr) < 4) + { + /* pack the string */ + for (iTemp = strlen(tempStr);iTemp < 4; iTemp++) + { + tempStr[iTemp] = ' '; /* pack it with space */ + } + } + + /* let's make sure we don't have a smart ass who wants to do chunk "FORM" */ + if ((toupper(tempStr[0]) == 'F') && + (toupper(tempStr[1]) == 'O') && + (toupper(tempStr[2]) == 'R') && + (toupper(tempStr[3]) == 'M')) + { + yyerror("CHUNK name CANNOT BE 'FORM'... nice try bozo!"); + } + + MIFFinsertChunk(tempStr); + } + MIFFfreeString($2); + } + ; + +chunkbody: '{' chunkelements '}' { if (!errorFlag) MIFFexitChunk(); }; + +chunkelements: /* can be empty */ + | chunkelements memalloc + | chunkelements includebin + | chunkelements debugInfo + | chunkelements includeIFF { yyerror("Found attempt to include IFF (binary) file inside CHUNK\nIFF inclusion ONLY allowed outside a CHUNK!\nError"); } + ; + +memalloc: INT32 l32AllocExpr { } + | INT16 l16AllocExpr { } + | INT8 l8AllocExpr { } + | UINT32 lU32AllocExpr { } + | UINT16 lU16AllocExpr { } + | UINT8 lU8AllocExpr { } + | FLOAT fAllocExpr { } + | DOUBLE dAllocExpr { } + | LABELHASH STR_LIT { + writeLabelHash($2); + } + | STRING STR_LIT { writeString($2); + /* now, add a NULL termination for this string */ + byteTemp = 0; write8(byteTemp); + MIFFfreeString($2); + } + | WSTRING STR_LIT { writeString16($2); + /* now, add a NULL termination for this string */ + wordTemp = 0; write16(wordTemp); + MIFFfreeString($2); + } + ; + +l32AllocExpr: exprL { write32($1); } + | l32AllocExpr ',' exprL { write32($3); } + ; + +l16AllocExpr: exprL { write16((short) $1); } + | l16AllocExpr ',' exprL { write16((short) $3); } + ; + +l8AllocExpr: exprL { write8((char) $1); } + | l8AllocExpr ',' exprL { write8((char) $3); } + ; + +lU32AllocExpr: exprL { writeU32($1); } + | lU32AllocExpr ',' exprL { writeU32($3); } + ; + +lU16AllocExpr: exprL { writeU16((unsigned short) $1); } + | lU16AllocExpr ',' exprL { writeU16((unsigned short) $3); } + ; + +lU8AllocExpr: exprL { writeU8((unsigned char) $1); } + | lU8AllocExpr ',' exprL { writeU8((unsigned char) $3); } + ; + +fAllocExpr: exprD { writeFloat((float) $1); } + | fAllocExpr ',' exprD { writeFloat((float) $3); } + ; + +dAllocExpr: exprD { writeDouble($1); } + | dAllocExpr ',' exprD { writeDouble($3); } + ; + + +/*-------------------------** +** expression for integers ** +**-------------------------*/ +exprL: exprL '+' factorL { $$ = $1 + $3; } + | exprL '-' factorL { $$ = $1 - $3; } + | exprL SHIFTLEFT factorL { $$ = $1 << $3; } + | exprL SHIFTRIGHT factorL { $$ = $1 >> $3; } + | exprL '&' factorL { $$ = $1 & $3; } + | exprL '|' factorL { $$ = $1 | $3; } + | exprL '^' factorL { $$ = $1 ^ $3; } + | factorL { $$ = ($1); } + ; + +factorL: factorL '*' termL { $$ = $1 * $3; } + | factorL '/' termL { $$ = $1 / $3; } + | factorL '%' termL { $$ = $1 % $3; } + | termL { $$ = ($1); } + ; + +termL: LIT { $$ = $1; } + | '~' termL { $$ = ~$2; } /* bitwise NOT */ + | '-' termL { $$ = -$2; } /* Unary minus */ + | '+' termL { $$ = $2; } /* Unary plus */ + | '(' exprL ')' { $$ = ($2); } + | IDENTIFIER { /* assume it's enum symbol */ + $$ = (signed long) getEnumValue(searchEnumSymbolTable($1)); + MIFFfreeString($1); + } + ; + +/*-----------------------** +** expression for floats ** +**-----------------------*/ +exprD: exprD '+' factorD { $$ = $1 + $3; } + | exprD '-' factorD { $$ = $1 - $3; } + | exprD RAISEDPOWER factorD { $$ = pow($1, $3);} /* exponentiation */ + | factorD { $$ = ($1); } + ; + +factorD: factorD '*' termD { $$ = $1 * $3; } + | factorD '/' termD { $$ = $1 / $3; } + | termD { $$ = ($1); } + ; + +termD: FLOAT_LIT { $$ = $1; } + | LIT { $$ = (double) $1; } /* we should be able to handle values that are integer and treat it as float */ + | '-' termD { $$ = -$2; } /* Unary minus */ + | '+' termD { $$ = $2; } /* Unary plus */ + | '(' exprD ')' { $$ = ($2); } + | SIN '(' exprD ')' { $$ = sin( $3 ); } + | COS '(' exprD ')' { $$ = cos( $3 ); } + | TAN '(' exprD ')' { $$ = tan( $3 ); } + | ACOS '(' exprD ')' { $$ = acos( $3 ); } + | ASIN '(' exprD ')' { $$ = asin( $3 ); } + | ATAN '(' exprD ')' { $$ = atan( $3 ); } + | IDENTIFIER { /* assume it's enum symbol */ + $$ = (signed long) getEnumValue(searchEnumSymbolTable($1)); + MIFFfreeString($1); + } + ; + +%% + +/*-------------------------------------------** +** and now... the supporting C functions... ** +**-------------------------------------------*/ +void initGlobalVars(void) +{ + /* assign defaults */ + drive[0] = 0; + directory[0] = 0; + filename[0] = 0; + extension[0] = 0; + err_msg[0] = 0; + usePragmas = 1; /* default to #pragmas enabled because as a stand-alone .YAC, we have no knowledge of outFileName */ + + errorFlag = 0; + + initSymTable(); +} + +void checkPragmas(void) +{ + int indexOriginal, indexDest; + char _tempStr[512]; + + if (usePragmas) + { + /* check after pre processor if output target is still NULL */ + if (!drive[0] && !errorFlag) + { + yyerror("Drive pragma not defined"); + errorFlag = 1; + } + if (!directory[0] && !errorFlag) + { + yyerror("Directory pragma not defined"); + errorFlag = 1; + } + if (!filename[0] && !errorFlag) + { + yyerror("Filename pragma not defined"); + errorFlag = 1; + } + if (!extension[0] && !errorFlag) + { + yyerror("Extension pragma not defined"); + errorFlag = 1; + } + + if (!errorFlag) + { + /* create an output file */ + strcpy(_tempStr, directory); /* copy directory to _tempStr because we'll be messing with directory */ + for (indexOriginal = 0, indexDest = 0; indexOriginal < (int) strlen(_tempStr); indexOriginal++) + { + /* search for double-slashes and convert it to single slash */ + if ((_tempStr[indexOriginal] == '\\') && (_tempStr[indexOriginal+1] == '\\')) + { + directory[indexDest] = '\\'; + indexOriginal++; + } + else + directory[indexDest] = _tempStr[indexOriginal]; /* copy current position of _tempStr to directory */ + indexDest++; + directory[indexDest] = 0; /* force NULL termination */ + } + sprintf(outFileName, "%s%s%s%s", drive, directory, filename, extension); + } + } /* if usePragmas */ + + MIFFSetIFFName(outFileName); /* tell mIFF we want to use this filename instead of whatever it has! */ +} + +/*--------------------------------------------------------------------------------------** +** This function is called early in the process to find out if usePragma flag was set ** +** in the command line or not. If it was, mIFF already has the outfile and will stuff ** +** it into the outFileName data pool. Even if mIFF had an idea of what the output file ** +** name is, if usePragma flag returned said it is true, then #pragas in the mIFF source ** +** is used instead and overrides whatever file name it has returned. ** +** see usePragmas() for more details. ** +**--------------------------------------------------------------------------------------*/ +void checkArgs(void) +{ + /* request an external function (found in either mIFF.CPP or mIFFView.CPP) to see if pragmas and filename was set... */ + usePragmas = validateTargetFilename(outFileName, sizeof(outFileName)); +} + +/*----------------------------** +** Write to FILE functions... ** +**----------------------------*/ +void write32(long i32) +{ + MIFFinsertChunkData(&i32, sizeof(long)); +} + +void write16(short i16) +{ + MIFFinsertChunkData(&i16, sizeof(short)); +} + +void write8(char i8) +{ + MIFFinsertChunkData(&i8, sizeof(char)); +} + +void writeU32(unsigned long ui32) +{ + MIFFinsertChunkData(&ui32, sizeof(long)); +} + +void writeU16(unsigned short ui16) +{ + MIFFinsertChunkData(&ui16, sizeof(short)); +} + +void writeU8(unsigned char ui8) +{ + MIFFinsertChunkData(&ui8, sizeof(char)); +} + +void writeDouble(double d) +{ + MIFFinsertChunkData(&d, sizeof(double)); +} + +void writeFloat(float f) +{ + MIFFinsertChunkData(&f, sizeof(float)); +} + +void writeString(char *s) +{ + char tempS[MAX_STRING_SIZE]; + parseESCstring(s, tempS, MAX_STRING_SIZE); + + MIFFinsertChunkData(tempS, strlen(tempS)); +} + +void writeString16(char *s) +{ + char tempS[MAX_STRING_SIZE]; + int charCount = 0; + wchar_t wtempStr[512]; /* just to be on the safe side, allocating huge array... */ + + parseESCstring(s, tempS, MAX_STRING_SIZE); + + /* make sure string length is less then the allocated wchar size */ + if ((strlen(tempS) * sizeof(wchar_t)) > (512* sizeof(wchar_t))) + yyerror("wstring: 16bit string too long to handle in buffer!\n"); + else + { + /* call MultiByteString to WideCharString function */ + charCount = mbstowcs(wtempStr, tempS, strlen(tempS)); + writeData(wtempStr, charCount * sizeof(wchar_t)); + } +} + +void writeLabelHash(char *s) +{ + writeU32(MIFFgetLabelHash(s)); +} + +/* search from escape string such as \n and convert it to actual byte */ +void parseESCstring(char *str, char *targetBuffer, int sizeOfTarget) +{ + char *sPtr = str; + int strIndex = 0; + char numString[32]; /* hopefully, never go over 3 char i.e. \x0FF */ + int numIndex = 0; + int tempNum = 0; + int exitParser = 0; + int loopFlag = 0; + + /* memory hog but cute way to convert ascii hex to number */ + int hexTable[256]; + memset(hexTable, 0xFF, 256); + hexTable['0'] = 0x00; + hexTable['1'] = 0x01; + hexTable['2'] = 0x02; + hexTable['3'] = 0x03; + hexTable['4'] = 0x04; + hexTable['5'] = 0x05; + hexTable['6'] = 0x06; + hexTable['7'] = 0x07; + hexTable['8'] = 0x08; + hexTable['9'] = 0x09; + hexTable['A'] = 0x0A; hexTable['a'] = 0x0A; + hexTable['B'] = 0x0B; hexTable['b'] = 0x0B; + hexTable['C'] = 0x0C; hexTable['c'] = 0x0C; + hexTable['D'] = 0x0D; hexTable['d'] = 0x0D; + hexTable['E'] = 0x0E; hexTable['e'] = 0x0E; + hexTable['F'] = 0x0F; hexTable['f'] = 0x0F; + + memset(targetBuffer, 0, sizeOfTarget); + while ((*sPtr) && !exitParser) /* assume we can go until NULL termination */ + { + /* check for escape sequences */ + if (*sPtr == '\\') + { + sPtr++; /* check out next character */ + switch (tolower(*sPtr)) + { + case 'a': /* BELL */ + { + targetBuffer[strIndex++] = '\a'; + break; + } + + case 'b': /* BACKSPACE */ + { + targetBuffer[strIndex++] = '\b'; + break; + } + + case 'f': /* FORMFEED */ + { + targetBuffer[strIndex++] = '\a'; + break; + } + + case 'n': /* NEWLINE */ + { + targetBuffer[strIndex++] = '\n'; + break; + } + + case 'r': /* CARRIAGE RETURN */ + { + targetBuffer[strIndex++] = '\r'; + break; + } + + case 't': /* TAB */ + { + targetBuffer[strIndex++] = '\t'; + break; + } + + case 'v': /* VERTICAL TAB */ + { + targetBuffer[strIndex++] = '\v'; + break; + } + + case '\'': /* SINGLE QUOTE */ + { + targetBuffer[strIndex++] = '\''; + break; + } + + case '\"': /* DOUBLE QUOTE */ + { + targetBuffer[strIndex++] = '\"'; + break; + } + + case '\\': /* BACKSLASH */ + { + targetBuffer[strIndex++] = '\\'; + break; + } + + case '?': /* LITERAL QUESTION MARK */ + { + targetBuffer[strIndex++] = '\?'; + break; + } + + case '0': /* ASCII octal */ + case '1': /* ASCII octal */ + case '2': /* ASCII octal */ + case '3': /* ASCII octal */ + case '4': /* ASCII octal */ + case '5': /* ASCII octal */ + case '6': /* ASCII octal */ + case '7': /* ASCII octal */ + { + /* read until non-digit encountered - if octal value is greater then \377 (400 or more) it is bigger the 255! */ + numIndex = 0; + + while ((*sPtr >= '0') && (*sPtr <= '7') && (*sPtr)) + { + numString[numIndex++] = *sPtr; + sPtr++; + if (numIndex > 3) + { + sprintf(err_msg, "Escape sequence Octal numbers greater then\noctal o400 (256 decimal)! [more then 3 digits]", *sPtr); + yyerror(err_msg); + exitParser = 1; + } + } + + /* now we should have string of octal number in numString */ + if (!exitParser) + { + if (numIndex == 3) + tempNum = (hexTable[numString[0]] * 64) + (hexTable[numString[1]] * 8) + hexTable[numString[2]]; + else if (numIndex == 2) + tempNum = (hexTable[numString[0]] * 8) + hexTable[numString[1]]; + else + tempNum = hexTable[numString[0]]; + + if (tempNum > 255) + { + sprintf(err_msg, "Escape sequence Octal numbers greater then\noctal o400 (256 decimal)!", tempNum); + yyerror(err_msg); + exitParser = 1; + } + + if (!exitParser) + targetBuffer[strIndex++] = tempNum; + } + break; + } + + case 'x': /* ASCII hex */ + { + /* we have to make sure the hex value is less then 256! */ + numIndex = 0; + loopFlag = 1; + sPtr++; /* skip the 'x' */ + + while ((0xFF != hexTable[*sPtr]) && (*sPtr)) + { + numString[numIndex++] = *sPtr; + sPtr++; + if (numIndex > 3) + { + sprintf(err_msg, "Escape sequence HEX numbers greater then 0x100\n(256 decimal)! [more then 3 digits]", *sPtr); + yyerror(err_msg); + exitParser = 1; + } + } + + if (!exitParser) + { + if (numIndex == 3) + tempNum = (hexTable[numString[0]] * 0x100) + (hexTable[numString[1]] * 0x10) + hexTable[numString[2]]; + else if (numIndex == 2) + tempNum = (hexTable[numString[0]] * 0x10) + hexTable[numString[1]]; + else + tempNum = hexTable[numString[0]]; + } + + if (tempNum > 255) + { + sprintf(err_msg, "Escape sequence HEX numbers greater then 0x100\n(256 decimal)!", *sPtr); + yyerror(err_msg); + exitParser = 1; + } + + if (!exitParser) + targetBuffer[strIndex++] = tempNum; + + break; + } + + case '8': + case '9': + { + /* they tried to do octal mode, but 8 and 9 is not in the definition of octal */ + yyerror("Attempted to enter escape sequence with non-octal value"); + exitParser = 1; + break; + } + + default: + sprintf(err_msg, "Unknown ESCape sequence \\%c found in string.\n", *sPtr); + yyerror(err_msg); + exitParser = 1; + break; + } + } + else + targetBuffer[strIndex++] = *sPtr; + sPtr++; + } +} + + +void writeData(void *dataPtr, unsigned dataSize) +{ + MIFFinsertChunkData(dataPtr, dataSize); +} + + +/* NOTE: includeBinary modifies fsize for the caller to access for adjusting the chunk size */ +void includeBinary(char *fname) +{ + char buffer[MAX_BUFFER_SIZE+1]; + int fsize = 0; + + fsize = MIFFloadRawData(fname, buffer, MAX_BUFFER_SIZE); + MIFFinsertChunkData(buffer, fsize); +} + +/*--------------------------------------------------------------------------------** +** Following functions below are all used for constructing, adding, and searching ** +** the symbol table created by enum keyword. It is at this moment, set in a way ** +** that if two identical symbols are added to the list, it will use the first ** +** symbol added to the list and ignores the rest (because of forward search) ** +**--------------------------------------------------------------------------------*/ +void initSymTable(void) +{ + memset(symbolEnumTable, 0, sizeof(struct structEnumSymTableType) * MAX_SYMBOLS); + currSymIndex = 0; + lastValue = -1; +} + +/* Searches thru the symbol table and returns the index */ +long searchEnumSymbolTable(char *symString) +{ + long index = 0; + int found = 0; + while ((0 != symbolEnumTable[index].symbol[0]) && !found) + { + + if (0 == strcmp(symbolEnumTable[index].symbol, symString)) + { + found = 1; + break; + } + else + index++; + } + + if (!found) + { + index = -1; + sprintf(err_msg, "Undefined symbol %s", symString); + yyerror(err_msg); + } + + return(index); +} + +long getEnumValue(long index) +{ + if (index >= 0) + return(symbolEnumTable[index].value); + return(-1); +} + +void addEnumSymbol(char *symString, long value) +{ + if (MAX_SYMCHARS < strlen(symString)) + { + /* somebody insane decided to use variable longer then max size! */ + sprintf(err_msg, "%s is longer then %d characters! [value: %d]", symString, MAX_SYMCHARS, value); + yyerror(err_msg); + } + else + { + strcpy(symbolEnumTable[currSymIndex].symbol, symString); + symbolEnumTable[currSymIndex].value = value; + lastValue = value; + currSymIndex++; + if (MAX_SYMBOLS < currSymIndex) + { + sprintf(err_msg, "Symbol table reached maximum size of %d", MAX_SYMBOLS); + yyerror(err_msg); + } + } +} diff --git a/engine/server/application/CentralServer/src/CMakeLists.txt b/engine/server/application/CentralServer/src/CMakeLists.txt old mode 100644 new mode 100755 index 338554da..1bfd4dd6 --- a/engine/server/application/CentralServer/src/CMakeLists.txt +++ b/engine/server/application/CentralServer/src/CMakeLists.txt @@ -154,6 +154,7 @@ include_directories( ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/platform/projects ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/platform/utils ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/udplibrary + ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/webAPI ) add_executable(CentralServer @@ -190,5 +191,7 @@ target_link_libraries(CentralServer localizationArchive unicode unicodeArchive + webAPI + ${CURL_LIBRARIES} ${CMAKE_DL_LIBS} ) diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferClient.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferClient.cpp index eb67f237..c7ddebeb 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferClient.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferClient.cpp @@ -35,7 +35,7 @@ void AuctionTransferClient::addCoinToAuction( const ExchangeListCreditsMessage& // 2bi. if user connected: send VeAuctionCoinReply (with result code) to user's ES // 2bii. if user not connected: send immediate abort back to auction service - const unsigned uTrack = getNewTransactionID( NULL ); + const unsigned uTrack = getNewTransactionID( nullptr ); AuctionAssetDetails &details = m_mPendingRequestDetails[ uTrack ]; details.u8Type = AuctionAssetDetails::TYPE_COIN; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericApiCore.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericApiCore.cpp index 6c412225..d4b0941d 100644 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericApiCore.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericApiCore.cpp @@ -13,260 +13,255 @@ using namespace std; #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { - #endif -//---------------------------------------- -ServerTrackObject::ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con) -: m_mappedTrack(mapped_track), m_realTrack(real_track), m_connection(con) -//---------------------------------------- -{ -} + //---------------------------------------- + ServerTrackObject::ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con) + : m_mappedTrack(mapped_track), m_realTrack(real_track), m_connection(con) + //---------------------------------------- + { + } -//---------------------------------------- -GenericAPICore::GenericAPICore(const char *host, - short port, - unsigned reqTimeout, - unsigned reconnectTimeout, - unsigned noDataTimeoutSecs, - unsigned noAckTimeoutSecs, - unsigned incomingBufSizeInKB, - unsigned outgoingBufSizeInKB, - unsigned keepAlive, - unsigned maxRecvMessageSizeInKB) -: m_currTrack(0), - m_reconnectTimeout(0), - m_outCount(0), - m_pendingCount(0), - m_requestTimeout(reqTimeout), - m_currentConnections(0), m_maxConnections(0), - m_suspended(false), - m_nextConnectionIndex(0) -//---------------------------------------- -{ - GenericConnection *con = new GenericConnection(host, port, this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB); - m_serverConnections.push_back(con); -} - -//---------------------------------------- -GenericAPICore::GenericAPICore(const char *game, const char *hosts[], - const short port[], - unsigned arraySize, - unsigned reqTimeout, - unsigned reconnectTimeout, - unsigned noDataTimeoutSecs, - unsigned noAckTimeoutSecs, - unsigned incomingBufSizeInKB, - unsigned outgoingBufSizeInKB, - unsigned keepAlive, - unsigned maxRecvMessageSizeInKB) -: m_currTrack(0), - m_reconnectTimeout(0), - m_outCount(0), - m_pendingCount(0), - m_requestTimeout(reqTimeout), - m_currentConnections(0), m_maxConnections(0), - m_suspended(false), - m_nextConnectionIndex(0), - m_game(game) -//---------------------------------------- -{ - for (unsigned i=0; i::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) - { - GenericConnection *con = *conIter; - delete con; - } - m_serverConnections.clear(); - - for(map::iterator iter = m_pending.begin(); iter != m_pending.end(); ++iter) - { - delete (*iter).second; } - m_pending.empty(); - - while(m_outCount > 0) + //---------------------------------------- + GenericAPICore::GenericAPICore(const char *game, const char *hosts[], + const short port[], + unsigned arraySize, + unsigned reqTimeout, + unsigned reconnectTimeout, + unsigned noDataTimeoutSecs, + unsigned noAckTimeoutSecs, + unsigned incomingBufSizeInKB, + unsigned outgoingBufSizeInKB, + unsigned keepAlive, + unsigned maxRecvMessageSizeInKB) + : m_currTrack(0), + m_reconnectTimeout(0), + m_outCount(0), + m_pendingCount(0), + m_requestTimeout(reqTimeout), + m_currentConnections(0), m_maxConnections(0), + m_suspended(false), + m_nextConnectionIndex(0), + m_game(game) + //---------------------------------------- { - delete m_outboundQueue.front().second; - delete m_outboundQueue.front().first; - m_outboundQueue.pop(); - --m_outCount; - } -} - -//---------------------------------------- -unsigned GenericAPICore::submitRequest(GenericRequest *req, GenericResponse *res) -//---------------------------------------- -{ - ++m_outCount; - if(m_currTrack == 0) - { - m_currTrack++; - } - req->setTrack(m_currTrack); - res->setTrack(m_currTrack); - time_t timeout = time(NULL) + m_requestTimeout; - - req->setTimeout(timeout); - res->setTimeout(timeout); - - m_outboundQueue.push(pair(req, res)); - return(m_currTrack++); -} - -//---------------------------------------- -void GenericAPICore::process() -//---------------------------------------- -{ - GenericRequest *req; - GenericResponse *res; - - if (!m_suspended) - { - // Process timeout on pending requests - while((m_outCount > 0) && ((req = m_outboundQueue.front().first)->getTimeout() <= time(NULL))) + for (unsigned i = 0; i < arraySize; i++) { - --m_outCount; - res = m_outboundQueue.front().second; + GenericConnection *con = new GenericConnection(hosts[i], port[i], this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB); + m_serverConnections.push_back(con); + } + } + + //---------------------------------------- + GenericAPICore::~GenericAPICore() + //---------------------------------------- + { + for (std::vector::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) + { + GenericConnection *con = *conIter; + delete con; + } + m_serverConnections.clear(); + + for (map::iterator iter = m_pending.begin(); iter != m_pending.end(); ++iter) + { + delete (*iter).second; + } + + m_pending.clear(); + + while (m_outCount > 0) + { + delete m_outboundQueue.front().second; + delete m_outboundQueue.front().first; m_outboundQueue.pop(); - - responseCallback(res); - delete res; - delete req; + --m_outCount; } + } - // Process timeout on pending responses - while((m_pendingCount > 0) && ((res = (*m_pending.begin()).second)->getTimeout() <= time(NULL))) + //---------------------------------------- + unsigned GenericAPICore::submitRequest(GenericRequest *req, GenericResponse *res) + //---------------------------------------- + { + ++m_outCount; + if (m_currTrack == 0) { - --m_pendingCount; - m_pending.erase(m_pending.begin()); - responseCallback(res); - delete res; + m_currTrack++; } + req->setTrack(m_currTrack); + res->setTrack(m_currTrack); + time_t timeout = time(nullptr) + m_requestTimeout; - while(m_outCount > 0) + req->setTimeout(timeout); + res->setTimeout(timeout); + + m_outboundQueue.push(pair(req, res)); + return(m_currTrack++); + } + + //---------------------------------------- + void GenericAPICore::process() + //---------------------------------------- + { + GenericRequest *req; + GenericResponse *res; + + if (!m_suspended) { - pair out_pair = m_outboundQueue.front(); - req = out_pair.first; - res = out_pair.second; - GenericConnection *con = NULL; - if (req->getMappedServerTrack() == 0) // request has no originating "owner" server + // Process timeout on pending requests + while ((m_outCount > 0) && ((req = m_outboundQueue.front().first)->getTimeout() <= time(nullptr))) { - con = getNextActiveConnection(); // it does not matter which server we send this to + --m_outCount; + res = m_outboundQueue.front().second; + m_outboundQueue.pop(); + + responseCallback(res); + delete res; + delete req; } - else + + // Process timeout on pending responses + while ((m_pendingCount > 0) && ((res = (*m_pending.begin()).second)->getTimeout() <= time(nullptr))) { - ServerTrackObject *stobj = findServer(req->getMappedServerTrack()); - if (stobj) + --m_pendingCount; + m_pending.erase(m_pending.begin()); + responseCallback(res); + delete res; + } + + while (m_outCount > 0) + { + pair out_pair = m_outboundQueue.front(); + req = out_pair.first; + res = out_pair.second; + GenericConnection *con = nullptr; + if (req->getMappedServerTrack() == 0) // request has no originating "owner" server { - con = stobj->getConnection(); // the server connection to respond to - req->setServerTrack(stobj->getRealServerTrack()); // map server track back to REAL server track - //printf("\nUnmapping %d to %d", stobj->getMappedServerTrack(), req->getMappedServerTrack()); //debug - delete stobj; + con = getNextActiveConnection(); // it does not matter which server we send this to + } + else + { + ServerTrackObject *stobj = findServer(req->getMappedServerTrack()); + if (stobj) + { + con = stobj->getConnection(); // the server connection to respond to + req->setServerTrack(stobj->getRealServerTrack()); // map server track back to REAL server track + //printf("\nUnmapping %d to %d", stobj->getMappedServerTrack(), req->getMappedServerTrack()); //debug + delete stobj; + } + } + + if (con != nullptr) + { + Base::ByteStream msg; + req->pack(msg); + con->Send(msg); + m_pending.insert(pair(res->getTrack(), res)); + --m_outCount; + ++m_pendingCount; + m_outboundQueue.pop(); + delete req; + } + else + { + //no active connections + break; //from while loop } } + } - if (con != NULL) - { - Base::ByteStream msg; - req->pack(msg); - con->Send(msg); - m_pending.insert(pair(res->getTrack(), res)); - --m_outCount; - ++m_pendingCount; - m_outboundQueue.pop(); - delete req; - } - else - { - //no active connections - break; //from while loop - } - + for (std::vector::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) + { + GenericConnection *con = *conIter; + con->process(); } } - for (std::vector::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) - { - GenericConnection *con = *conIter; - con->process(); - } -} + //---------------------------------------- + GenericConnection *GenericAPICore::getNextActiveConnection() + //---------------------------------------- + { + unsigned startIndex = m_nextConnectionIndex; + unsigned maxIndex = m_serverConnections.size() - 1; + GenericConnection *con = nullptr; -//---------------------------------------- -GenericConnection *GenericAPICore::getNextActiveConnection() -//---------------------------------------- -{ - unsigned startIndex = m_nextConnectionIndex; - unsigned maxIndex = m_serverConnections.size() - 1; + //loop until we find an active connection, or until we get back + // to where we started + do + { + if (m_serverConnections[m_nextConnectionIndex]->isConnected()) + { + con = m_serverConnections[m_nextConnectionIndex]; + if (m_nextConnectionIndex == maxIndex) + m_nextConnectionIndex = 0; + else + m_nextConnectionIndex++; + } + else if (++m_nextConnectionIndex > maxIndex) + { + //went past end of vector, start back at 0 + m_nextConnectionIndex = 0; + } + } while (con == nullptr && m_nextConnectionIndex != startIndex); - GenericConnection *con = NULL; + return con; + } - //loop until we find an active connection, or until we get back - // to where we started - do - { - if (m_serverConnections[m_nextConnectionIndex]->isConnected()) - { - con = m_serverConnections[m_nextConnectionIndex]; - if (m_nextConnectionIndex == maxIndex) - m_nextConnectionIndex = 0; - else - m_nextConnectionIndex++; - - } - else if (++m_nextConnectionIndex > maxIndex) - { - //went past end of vector, start back at 0 - m_nextConnectionIndex = 0; - } - }while (con == NULL && m_nextConnectionIndex != startIndex); + //---------------------------------------- + void GenericAPICore::countOpenConnections() + //---------------------------------------- + { + m_currentConnections = 0; + m_maxConnections = m_serverConnections.size(); - return con; -} + for (std::vector::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) + { + GenericConnection *con = *conIter; + if (con->isConnected()) + ++m_currentConnections; + } + } -//---------------------------------------- -void GenericAPICore::countOpenConnections() -//---------------------------------------- -{ - m_currentConnections = 0; - m_maxConnections = m_serverConnections.size(); - - for (std::vector::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++) - { - GenericConnection *con = *conIter; - if (con->isConnected()) - ++m_currentConnections; - } -} - -//---------------------------------------- -ServerTrackObject *GenericAPICore::findServer(unsigned server_track) -//---------------------------------------- -{ - std::map::iterator iter = m_serverTracks.find(server_track); - if (iter == m_serverTracks.end()) - return NULL; - ServerTrackObject *stobj = (*iter).second; - m_serverTracks.erase(server_track); - return stobj; -} + //---------------------------------------- + ServerTrackObject *GenericAPICore::findServer(unsigned server_track) + //---------------------------------------- + { + std::map::iterator iter = m_serverTracks.find(server_track); + if (iter == m_serverTracks.end()) + return nullptr; + ServerTrackObject *stobj = (*iter).second; + m_serverTracks.erase(server_track); + return stobj; + } #ifdef EXTERNAL_DISTRO }; -#endif +#endif \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.cpp index 318f5c20..88aa786b 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.cpp @@ -15,204 +15,188 @@ #define GAME_RESOURCE 1 #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { #endif -using namespace std; -using namespace Base; + using namespace std; + using namespace Base; -GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB) -: m_bConnected(CON_NONE), - m_apiCore(apiCore), - m_con(NULL), - m_host(host), - m_port(port), - m_lastTrack(123455), //random choice != 1 - m_conState(CON_DISCONNECT), - m_reconnectTimeout(reconnectTimeout) -{ - TcpManager::TcpParams params; - - params.incomingBufferSize = incomingBufSizeInKB * 1024; - params.outgoingBufferSize = outgoingBufSizeInKB * 1024; - params.maxConnections = 1; - params.port = 0; - params.maxRecvMessageSize = maxRecvMessageSizeInKB*1024; - params.keepAliveDelay = keepAlive * 1000; - params.noDataTimeout = noDataTimeoutSecs * 1000; - //params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000; - - m_manager = new TcpManager(params); -} - -GenericConnection::~GenericConnection() -{ - if(m_con) + GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB) + : m_bConnected(CON_NONE), + m_apiCore(apiCore), + m_con(nullptr), + m_host(host), + m_port(port), + m_conState(CON_DISCONNECT), + m_reconnectTimeout(reconnectTimeout), + m_conTimeout(0) { - m_con->SetHandler(NULL); - m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to null, so it wont - m_con->Release(); + TcpManager::TcpParams params; + + params.incomingBufferSize = incomingBufSizeInKB * 1024; + params.outgoingBufferSize = outgoingBufSizeInKB * 1024; + params.maxConnections = 1; + params.port = 0; + params.maxRecvMessageSize = maxRecvMessageSizeInKB * 1024; + params.keepAliveDelay = keepAlive * 1000; + params.noDataTimeout = noDataTimeoutSecs * 1000; + //params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000; + + m_manager = new TcpManager(params); } - m_manager->Release(); -} - -void GenericConnection::disconnect() -{ - if (m_con) + GenericConnection::~GenericConnection() { - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = NULL; + if (m_con) + { + m_con->SetHandler(nullptr); + m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont + m_con->Release(); + } + + m_manager->Release(); } - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; -} -void GenericConnection::OnTerminated(TcpConnection *) -{ -// m_apiCore->OnDisconnect(m_host.c_str(), m_port); - m_apiCore->OnDisconnect(this); - if(m_con) + void GenericConnection::disconnect() { - m_con->Release(); - m_con = NULL; + if (m_con) + { + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + } + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; } - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; -} -void GenericConnection::OnRoutePacket(TcpConnection *, const unsigned char *data, int dataLen) -{ - short type; - unsigned track; - - ByteStream msg(data, dataLen); - ByteStream::ReadIterator iter = msg.begin(); - - get(iter, type); - get(iter, track); - GenericResponse *res = NULL; - - // the following if block is a temporary fix that prevents - // a crash with a game team in which they occasionally find - // themselves receiving a dupe track in consecutive calls to - // OnRoutePacket (which then leads to a callback being called - // twice and data being invalid on the second call -> crash!). - // TODO: resolve this BK -/* if (track != 0 && - track == m_lastTrack) + void GenericConnection::OnTerminated(TcpConnection *) { - printf("!!! ERROR !!! Got a duplicate track ID %u\n", track); - return; + // m_apiCore->OnDisconnect(m_host.c_str(), m_port); + m_apiCore->OnDisconnect(this); + if (m_con) + { + m_con->Release(); + m_con = nullptr; + } + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; } - m_lastTrack = track; -*/ - // end temporary fix. - if(track == 0) // notification message from the server, not as a response to a request from this API + void GenericConnection::OnRoutePacket(TcpConnection *, const unsigned char *data, int dataLen) { - if (type == ATGAME_REQUEST_CONNECT) - { // this is a special case, for when we have identified our game code to server - m_bConnected = CON_IDENTIFIED; - m_apiCore->OnConnect(this); + short type; + unsigned track; + + ByteStream msg(data, dataLen); + ByteStream::ReadIterator iter = msg.begin(); + + get(iter, type); + get(iter, track); + GenericResponse *res = nullptr; + + if (track == 0) // notification message from the server, not as a response to a request from this API + { + if (type == ATGAME_REQUEST_CONNECT) + { // this is a special case, for when we have identified our game code to server + m_bConnected = CON_IDENTIFIED; + m_apiCore->OnConnect(this); + } + else + { + m_apiCore->responseCallback(type, iter, this); + } } else { - m_apiCore->responseCallback(type, iter, this); + map::iterator mapIter = m_apiCore->m_pending.find(track); + + if (mapIter != m_apiCore->m_pending.end()) + { + res = (*mapIter).second; + iter = msg.begin(); + res->unpack(iter); + m_apiCore->responseCallback(res); + m_apiCore->m_pendingCount--; + m_apiCore->m_pending.erase(mapIter); + delete res; + } } } - else + + void GenericConnection::process() { - map::iterator mapIter = m_apiCore->m_pending.find(track); - - if(mapIter != m_apiCore->m_pending.end()) + switch (m_conState) { - res = (*mapIter).second; - iter = msg.begin(); - res->unpack(iter); - m_apiCore->responseCallback(res); - m_apiCore->m_pendingCount--; - m_apiCore->m_pending.erase(mapIter); - delete res; - } - } -} + case CON_DISCONNECT: + // create connection object, attempting to connect and + // checking for connection in next state, CON_NEGOTIATE + m_con = m_manager->EstablishConnection(m_host.c_str(), m_port); + if (m_con) + { + m_con->SetHandler(this); + m_conState = CON_NEGOTIATE; + m_conTimeout = time(nullptr) + m_reconnectTimeout; + } + break; + case CON_NEGOTIATE: + // check for connection -void GenericConnection::process() -{ - switch(m_conState) - { - case CON_DISCONNECT: - // create connection object, attempting to connect and - // checking for connection in next state, CON_NEGOTIATE - m_con = m_manager->EstablishConnection(m_host.c_str(), m_port); - if(m_con) - { - m_con->SetHandler(this); - m_conState = CON_NEGOTIATE; - m_conTimeout = time(NULL) + m_reconnectTimeout; - } - break; - case CON_NEGOTIATE: - // check for connection + if (m_con->GetStatus() == TcpConnection::StatusConnected) + { + // we're connected + m_conState = CON_CONNECT; + m_bConnected = CON_CONNECTED; + // instead of calling OnConnect() right now, we are going to submit a connection packet + // identifying us + // m_apiCore->OnConnect(this); + Base::ByteStream msg; + put(msg, (short)REQUEST_SET_API); + put(msg, (unsigned)0); // track + put(msg, (unsigned)API_VERSION_CODE); + put(msg, GAME_RESOURCE); // identify us as a game connection resource - if(m_con->GetStatus() == TcpConnection::StatusConnected) - { - // we're connected - m_conState = CON_CONNECT; - m_bConnected = CON_CONNECTED; - // instead of calling OnConnect() right now, we are going to submit a connection packet - // identifying us -// m_apiCore->OnConnect(this); - Base::ByteStream msg; - put(msg, (short)REQUEST_SET_API); - put(msg, (unsigned)0); // track - put(msg, (unsigned)API_VERSION_CODE); - put(msg, GAME_RESOURCE); // identify us as a game connection resource - - // now add in the game identifiers - put(msg, (unsigned)m_apiCore->m_gameIdentifiers.size()); // number of strings to read - for(unsigned index = 0; index < m_apiCore->m_gameIdentifiers.size(); index++) - put(msg, std::string(m_apiCore->m_gameIdentifiers[index])); - Send(msg); - } - else if(time(NULL) > m_conTimeout) - { - // we did not connect - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = NULL; + // now add in the game identifiers + put(msg, (unsigned)m_apiCore->m_gameIdentifiers.size()); // number of strings to read + for (unsigned index = 0; index < m_apiCore->m_gameIdentifiers.size(); index++) + put(msg, std::string(m_apiCore->m_gameIdentifiers[index])); + Send(msg); + } + else if (time(nullptr) > m_conTimeout) + { + // we did not connect + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + m_conState = CON_DISCONNECT; + m_bConnected = CON_NONE; + } + break; + case CON_CONNECT: + // do nothing + break; + default: + // this should not occur, but we revert to CON_DISCONNECT if it does m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; - } - break; - case CON_CONNECT: - // do nothing - break; - default: - // this should not occur, but we revert to CON_DISCONNECT if it does - m_conState = CON_DISCONNECT; - m_bConnected = CON_NONE; - if (m_con) - { - m_con->Disconnect(); - //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); - m_con = NULL; + m_bConnected = CON_NONE; + if (m_con) + { + m_con->Disconnect(); + //no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release(); + m_con = nullptr; + } } + m_manager->GiveTime(); } - m_manager->GiveTime(); -} -void GenericConnection::Send(Base::ByteStream &msg) -{ - if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected) + void GenericConnection::Send(Base::ByteStream &msg) { - m_con->Send((const char *)msg.getBuffer(), msg.getSize()); + if (m_con && m_con->GetStatus() == TcpConnection::StatusConnected) + { + m_con->Send((const char *)msg.getBuffer(), msg.getSize()); + } } -} #ifdef EXTERNAL_DISTRO }; -#endif +#endif \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.h index 28852377..f9b23586 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericConnection.h @@ -75,7 +75,6 @@ private: TcpConnection *m_con; std::string m_host; short m_port; - unsigned m_lastTrack; eConState m_conState; time_t m_conTimeout; unsigned m_reconnectTimeout; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericMessage.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericMessage.cpp index c01729d8..e97312fd 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericMessage.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/ATGenericAPI/GenericMessage.cpp @@ -9,36 +9,35 @@ //---------------------------------------- #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { - #endif -using namespace Base; + using namespace Base; -//------------------------------------------- -GenericRequest::GenericRequest(short type, unsigned server_track) -: m_type(type), m_server_track(server_track) -//------------------------------------------- -{ -} + //------------------------------------------- + GenericRequest::GenericRequest(short type, unsigned server_track) + : m_type(type), m_server_track(server_track), m_track(0), m_timeout(0) + //------------------------------------------- + { + } -//------------------------------------------- -GenericResponse::GenericResponse(short type, unsigned result, void *user) -: m_type(type), m_result(result), m_user(user) -//------------------------------------------- -{ -} + //------------------------------------------- + GenericResponse::GenericResponse(short type, unsigned result, void *user) + : m_type(type), m_result(result), m_user(user), m_track(0), m_timeout(0) + //------------------------------------------- + { + } -//----------------------------------------- -void GenericResponse::unpack(ByteStream::ReadIterator &iter) -//----------------------------------------- -{ - get(iter, m_type); - get(iter, m_track); - get(iter, m_result); -} + //----------------------------------------- + void GenericResponse::unpack(ByteStream::ReadIterator &iter) + //----------------------------------------- + { + get(iter, m_type); + get(iter, m_track); + get(iter, m_result); + } #ifdef EXTERNAL_DISTRO }; -#endif +#endif \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/AuctionTransferAPI.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/AuctionTransferAPI.cpp index 872eff5e..7e716a00 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/AuctionTransferAPI.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/AuctionTransferAPI.cpp @@ -25,9 +25,9 @@ AuctionTransferAPI::AuctionTransferAPI(const char *hostNames, const char *identi std::vector portArray; char hostConfig[4096]; char identifierConfig[4096]; - if (hostNames == NULL) + if (hostNames == nullptr) hostNames = DEFAULT_HOST; - if(identifiers == NULL) + if(identifiers == nullptr) identifiers = DEFAULT_IDENTIFIER; // parse the hosts and ports out : @@ -52,7 +52,7 @@ AuctionTransferAPI::AuctionTransferAPI(const char *hostNames, const char *identi portArray.push_back(port); } } - while ((ptr = strtok(NULL, " ")) != NULL); + while ((ptr = strtok(nullptr, " ")) != nullptr); } strncpy(identifierConfig, identifiers, 4096); identifierConfig[4095] = 0; @@ -67,7 +67,7 @@ AuctionTransferAPI::AuctionTransferAPI(const char *hostNames, const char *identi identifierArray.push_back(identifier); } } - while ((ptr = strtok(NULL, ";")) != NULL); + while ((ptr = strtok(nullptr, ";")) != nullptr); } if (hostArray.empty()) @@ -134,7 +134,7 @@ unsigned AuctionTransferAPI::sendCommitTransaction(long long transactionID, void unsigned AuctionTransferAPI::sendPrepareTransaction(const char *serverIdentifier, long long transactionID, unsigned stationID, unsigned characterID, long long assetID, const char *xmlAsset, void *user, bool compress) { RequestTypes requestEnum = GAME_REQUEST_SEND_PREPARE_TRANSACTION; - GenericRequest *req = NULL; + GenericRequest *req = nullptr; if( compress ) { requestEnum = GAME_REQUEST_SEND_PREPARE_TRANSACTION_COMPRESSED; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/Archive.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/Archive.cpp index e3400df0..8ad45428 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/Archive.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/Archive.cpp @@ -91,7 +91,7 @@ namespace Base ByteStream::ByteStream() : allocatedSize(0), beginReadIterator(), - data(NULL), + data(nullptr), size(0), lastPutSize(0) { @@ -208,7 +208,7 @@ namespace Base if(data->size < allocatedSize) { unsigned char * tmp = new unsigned char[newSize]; - if(data->buffer != NULL) + if(data->buffer != nullptr) memcpy(tmp, data->buffer, size); delete[] data->buffer; data->buffer = tmp; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Archive.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Archive.h new file mode 100755 index 00000000..30ddce43 --- /dev/null +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Archive.h @@ -0,0 +1,42 @@ +#ifndef BASE_WIN32_ARCHIVE_H +#define BASE_WIN32_ARCHIVE_H + +#ifdef EXTERNAL_DISTRO +namespace NAMESPACE +{ + +#endif +namespace Base +{ + + +#ifdef PACK_BIG_ENDIAN + + inline double byteSwap(double value) { byteReverse64(&value); return value; } + inline float byteSwap(float value) { byteReverse32(&value); return value; } + inline uint64 byteSwap(uint64 value) { byteReverse64(&value); return value; } + inline int64 byteSwap(int64 value) { byteReverse64(&value); return value; } + inline uint32 byteSwap(uint32 value) { byteReverse32(&value); return value; } + inline int32 byteSwap(int32 value) { byteReverse32(&value); return value; } + inline uint16 byteSwap(uint16 value) { byteReverse16(&value); return value; } + inline int16 byteSwap(int16 value) { byteReverse16(&value); return value; } + +#else + + inline double byteSwap(double value) { return value; } + inline float byteSwap(float value) { return value; } + inline uint64 byteSwap(uint64 value) { return value; } + inline int64 byteSwap(int64 value) { return value; } + inline uint32 byteSwap(uint32 value) { return value; } + inline int32 byteSwap(int32 value) { return value; } + inline uint16 byteSwap(uint16 value) { return value; } + inline int16 byteSwap(int16 value) { return value; } + +#endif + +}; +#ifdef EXTERNAL_DISTRO +}; +#endif + +#endif diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.cpp new file mode 100755 index 00000000..3b52563e --- /dev/null +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.cpp @@ -0,0 +1,31 @@ +//////////////////////////////////////// +// Platform.cpp +// +// Purpose: +// 1. Implementation of the global functionality declaired in Platform.h. +// +// Revisions: +// 07/10/2001 Created +// + +#include "Platform.h" + +#ifdef EXTERNAL_DISTRO +namespace NAMESPACE +{ + +#endif +namespace Base +{ + + + CTimer::CTimer() : + mTimer(0) + { + } + + +}; +#ifdef EXTERNAL_DISTRO +}; +#endif diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.h new file mode 100755 index 00000000..aaee37b7 --- /dev/null +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Platform.h @@ -0,0 +1,98 @@ +//////////////////////////////////////// +// Platform.h +// +// Purpose: +// 1. Include relevent system headers that are platform specific. +// 2. Declair global platform specific functionality. +// 3. Include primative type definitions +// +// Global Functions: +// getTimer() : Return the current high resolution clock count. +// getTimerFrequency() : Return the frequency of the high resolution clock. +// sleep() : Voluntarily relinquish timeslice of the calling thread for a +// specified number of milliseconds. +// +// Revisions: +// 07/10/2001 Created +// + +#ifndef BASE_WIN32_PLATFORM_H +#define BASE_WIN32_PLATFORM_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Types.h" + +#ifdef EXTERNAL_DISTRO +namespace NAMESPACE +{ + +#endif +namespace Base +{ + + uint64 getTimer(void); + uint64 getTimerFrequency(void); + + inline uint64 getTimer(void) + { + uint64 result; + if (!QueryPerformanceCounter(reinterpret_cast(&result))) + result = 0; + return result; + } + + inline uint64 getTimerFrequency(void) + { + uint64 result; + if (!QueryPerformanceFrequency(reinterpret_cast(&result))) + result = 0; + return result; + } + + inline void sleep(uint32 ms) + { + Sleep(ms); + } + + + class CTimer + { + public: + CTimer(); + + void Set(uint32 seconds); + void Signal(); + bool Expired(); + + private: + uint32 mTimer; + }; + + inline void CTimer::Set(uint32 interval) + { + mTimer = (uint32)time(0) + interval; + } + + inline void CTimer::Signal() + { + mTimer = 0; + } + + inline bool CTimer::Expired() + { + return (mTimer <= (uint32)time(0)); + } +}; +#ifdef EXTERNAL_DISTRO +}; +#endif + + +#endif BASE_WIN32_PLATFORM_H \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Types.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Types.h new file mode 100755 index 00000000..0c64cb2c --- /dev/null +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Base/win32/Types.h @@ -0,0 +1,42 @@ +//////////////////////////////////////// +// Types.h +// +// Purpose: +// 1. Define integer types that are unambiguous with respect to size +// +// Revisions: +// 07/10/2001 Created +// + +#ifndef BASE_WIN32_TYPES_H +#define BASE_WIN32_TYPES_H + +#ifdef EXTERNAL_DISTRO +namespace NAMESPACE +{ + +#endif +namespace Base +{ + +#define INT32_MAX 0x7FFFFFFF +#define INT32_MIN 0x80000000 +#define UINT32_MAX 0xFFFFFFFF + +typedef signed char int8; +typedef unsigned char uint8; +typedef short int16; +typedef unsigned short uint16; + +typedef int int32; +typedef unsigned uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; + +}; +#ifdef EXTERNAL_DISTRO +}; +#endif + +#endif // BASE_WIN32_TYPES_H + diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Request.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Request.cpp index 13291373..ed2e0ad3 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Request.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/Request.cpp @@ -7,7 +7,7 @@ void put(Base::ByteStream &msg, const Blob &source); ////////////////////////////////////////////////////////////////////////////////////// Blob::Blob(const unsigned char *data, unsigned len) - : m_data(NULL), + : m_data(nullptr), m_len(len) { if (m_len > 0) @@ -20,7 +20,7 @@ void put(Base::ByteStream &msg, const Blob &source); ////////////////////////////////////////////////////////////////////////////////////// Blob::Blob(const Blob &cpy) - : m_data(NULL), + : m_data(nullptr), m_len(cpy.m_len) { if (m_len > 0) @@ -45,7 +45,7 @@ void put(Base::ByteStream &msg, const Blob &source); if (m_data) { delete [] m_data; - m_data = NULL; + m_data = nullptr; } m_len = cpy.m_len; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/IPAddress.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/IPAddress.h index f6d5f886..03b59e8d 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/IPAddress.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/IPAddress.h @@ -32,7 +32,7 @@ public: * @brief Used to retreive the the dot-notation represenatatiion of this address. * * @param buffer A pointer to the buffer to place the ip address into. - * Must be at least 17 characters long, will be null terminated. + * Must be at least 17 characters long, will be nullptr terminated. * * @return A pointer to the buffer the address was placed into. */ diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpBlockAllocator.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpBlockAllocator.cpp index 6d476d78..b7da0f27 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpBlockAllocator.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpBlockAllocator.cpp @@ -6,7 +6,7 @@ namespace NAMESPACE #endif TcpBlockAllocator::TcpBlockAllocator(const unsigned initSize, const unsigned initCount) -: m_freeHead(NULL), m_blockCount(initCount), m_blockSize(initSize), m_numAvailBlocks(0) +: m_freeHead(nullptr), m_blockCount(initCount), m_blockSize(initSize), m_numAvailBlocks(0) { realloc(); } @@ -33,7 +33,7 @@ data_block *TcpBlockAllocator::getBlock() tmp = m_freeHead; m_freeHead = m_freeHead->m_next; - tmp->m_next = NULL; + tmp->m_next = nullptr; m_numAvailBlocks--; return(tmp); } @@ -56,7 +56,7 @@ void TcpBlockAllocator::returnBlock(data_block *b) void TcpBlockAllocator::realloc() { - data_block *tmp = NULL, *cursor = NULL; + data_block *tmp = nullptr, *cursor = nullptr; tmp = new data_block; m_numAvailBlocks++; cursor = tmp; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.cpp index 41f75157..20fdad78 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.cpp @@ -11,28 +11,28 @@ namespace NAMESPACE //used when want to open new connection with this socket TcpConnection::TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, const IPAddress &destIP, short destPort, unsigned timeout) -: m_nextConnection(NULL), - m_prevConnection(NULL), +: m_nextConnection(nullptr), + m_prevConnection(nullptr), m_socket(INVALID_SOCKET), - m_nextKeepAliveConnection(NULL), - m_prevKeepAliveConnection(NULL), + m_nextKeepAliveConnection(nullptr), + m_prevKeepAliveConnection(nullptr), m_aliveListId(tcpManager->m_aliveList.m_listID), - m_nextRecvDataConnection(NULL), - m_prevRecvDataConnection(NULL), + m_nextRecvDataConnection(nullptr), + m_prevRecvDataConnection(nullptr), m_recvDataListId(tcpManager->m_dataList.m_listID), m_manager(tcpManager), m_status(StatusNegotiating), - m_handler(NULL), + m_handler(nullptr), m_destIP(destIP), m_destPort(destPort), m_refCount(0), m_sendAllocator(sendAlloc), - m_head(NULL), - m_tail(NULL), + m_head(nullptr), + m_tail(nullptr), m_bytesRead(0), m_bytesNeeded(0), m_params(params), - m_recvBuff(NULL), + m_recvBuff(nullptr), m_connectTimeout(timeout), m_connectTimer(), m_wasConRemovedFromMgr(false) @@ -94,28 +94,28 @@ TcpConnection::TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAllo //used when server mode creates new connection object representing a connect request TcpConnection::TcpConnection(TcpManager *tcpManager, TcpBlockAllocator *sendAlloc, TcpManager::TcpParams ¶ms, SOCKET socket, const IPAddress &destIP, short destPort) -: m_nextConnection(NULL), - m_prevConnection(NULL), +: m_nextConnection(nullptr), + m_prevConnection(nullptr), m_socket(socket), - m_nextKeepAliveConnection(NULL), - m_prevKeepAliveConnection(NULL), + m_nextKeepAliveConnection(nullptr), + m_prevKeepAliveConnection(nullptr), m_aliveListId(tcpManager->m_aliveList.m_listID), - m_nextRecvDataConnection(NULL), - m_prevRecvDataConnection(NULL), + m_nextRecvDataConnection(nullptr), + m_prevRecvDataConnection(nullptr), m_recvDataListId(tcpManager->m_dataList.m_listID), m_manager(tcpManager), m_status(StatusConnected), - m_handler(NULL), + m_handler(nullptr), m_destIP(destIP), m_destPort(destPort), m_refCount(0), m_sendAllocator(sendAlloc), - m_head(NULL), - m_tail(NULL), + m_head(nullptr), + m_tail(nullptr), m_bytesRead(0), m_bytesNeeded(0), m_params(params), - m_recvBuff(NULL), + m_recvBuff(nullptr), m_connectTimeout(0), m_connectTimer(), m_wasConRemovedFromMgr(false) @@ -208,7 +208,7 @@ int TcpConnection::finishConnect() t.tv_sec = 0; t.tv_usec = 0; - int err = select(m_socket + 1, NULL, &wrSet, NULL, &t); + int err = select(m_socket + 1, nullptr, &wrSet, nullptr, &t); if (err == 0) { @@ -303,7 +303,7 @@ TcpConnection::~TcpConnection() { delete [] m_recvBuff; - while(m_head != NULL) + while(m_head != nullptr) { data_block *tmp = m_head; m_head = m_head->m_next; @@ -327,22 +327,22 @@ void TcpConnection::Send(const char *data, unsigned int dataLen) { m_aliveListId = m_manager->m_keepAliveList.m_listID; - if (m_prevKeepAliveConnection != NULL) + if (m_prevKeepAliveConnection != nullptr) m_prevKeepAliveConnection->m_nextKeepAliveConnection = m_nextKeepAliveConnection; - if (m_nextKeepAliveConnection != NULL) + if (m_nextKeepAliveConnection != nullptr) m_nextKeepAliveConnection->m_prevKeepAliveConnection = m_prevKeepAliveConnection; if (m_manager->m_keepAliveList.m_beginList == this) m_manager->m_keepAliveList.m_beginList = m_nextKeepAliveConnection; m_nextKeepAliveConnection = m_manager->m_aliveList.m_beginList; - m_prevKeepAliveConnection = NULL; - if (m_manager->m_aliveList.m_beginList != NULL) + m_prevKeepAliveConnection = nullptr; + if (m_manager->m_aliveList.m_beginList != nullptr) m_manager->m_aliveList.m_beginList->m_prevKeepAliveConnection = this; m_manager->m_aliveList.m_beginList = this; } - data_block *work = NULL; + data_block *work = nullptr; // this connection has no send buffer. Get a block if(!m_tail) @@ -467,16 +467,16 @@ int TcpConnection::processIncoming() { m_recvDataListId = m_manager->m_noDataList.m_listID; - if (m_prevRecvDataConnection != NULL) + if (m_prevRecvDataConnection != nullptr) m_prevRecvDataConnection->m_nextRecvDataConnection = m_nextRecvDataConnection; - if (m_nextRecvDataConnection != NULL) + if (m_nextRecvDataConnection != nullptr) m_nextRecvDataConnection->m_prevRecvDataConnection = m_prevRecvDataConnection; if (m_manager->m_noDataList.m_beginList == this) m_manager->m_noDataList.m_beginList = m_nextRecvDataConnection; m_nextRecvDataConnection = m_manager->m_dataList.m_beginList; - m_prevRecvDataConnection = NULL; - if (m_manager->m_dataList.m_beginList != NULL) + m_prevRecvDataConnection = nullptr; + if (m_manager->m_dataList.m_beginList != nullptr) m_manager->m_dataList.m_beginList->m_prevRecvDataConnection = this; m_manager->m_dataList.m_beginList = this; } @@ -622,7 +622,7 @@ int TcpConnection::processOutgoing() int sendError = 1; - // If m_head is not null, then this connection has something to send + // If m_head is not nullptr, then this connection has something to send if(m_head) diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.h index 07eb4f42..92d631d1 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpConnection.h @@ -50,7 +50,7 @@ public: * connection is disconnected, you simply need to derive your class * (multiply if necessary) from TcpConnectionHandler, then you can use * this method to set the object the TcpConnection will call as appropriate. - * default = NULL (no callbacks made) + * default = nullptr (no callbacks made) * * @param handler The object which will be called for notifications. */ diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.cpp b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.cpp index a89065a6..7202f4a3 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.cpp +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.cpp @@ -4,743 +4,719 @@ #include "TcpConnection.h" #ifndef WIN32 - #include +#include #endif - #ifdef EXTERNAL_DISTRO -namespace NAMESPACE +namespace NAMESPACE { #endif -TcpManager::TcpParams::TcpParams() -: port(0), - maxConnections(10), - incomingBufferSize(64*1024), - outgoingBufferSize(64*1024), - allocatorBlockSize(8*1024), - allocatorBlockCount(16), - maxRecvMessageSize(0), - keepAliveDelay(0), - noDataTimeout(0) -{ - memset(bindAddress, 0, sizeof(bindAddress)); -} + TcpManager::TcpParams::TcpParams() + : port(0), + maxConnections(10), + incomingBufferSize(64 * 1024), + outgoingBufferSize(64 * 1024), + allocatorBlockSize(8 * 1024), + allocatorBlockCount(16), + maxRecvMessageSize(0), + keepAliveDelay(0), + noDataTimeout(0) + { + memset(bindAddress, 0, sizeof(bindAddress)); + } -TcpManager::TcpParams::TcpParams(const TcpParams &cpy) -: port(cpy.port), - maxConnections(cpy.maxConnections), - incomingBufferSize(cpy.incomingBufferSize), - outgoingBufferSize(cpy.outgoingBufferSize), - allocatorBlockSize(cpy.allocatorBlockSize), - allocatorBlockCount(cpy.allocatorBlockCount), - maxRecvMessageSize(cpy.maxRecvMessageSize), - keepAliveDelay(cpy.keepAliveDelay), - noDataTimeout(cpy.noDataTimeout) -{ -} + TcpManager::TcpParams::TcpParams(const TcpParams &cpy) + : port(cpy.port), + maxConnections(cpy.maxConnections), + incomingBufferSize(cpy.incomingBufferSize), + outgoingBufferSize(cpy.outgoingBufferSize), + allocatorBlockSize(cpy.allocatorBlockSize), + allocatorBlockCount(cpy.allocatorBlockCount), + maxRecvMessageSize(cpy.maxRecvMessageSize), + keepAliveDelay(cpy.keepAliveDelay), + noDataTimeout(cpy.noDataTimeout) + { + } -TcpManager::TcpManager(const TcpParams ¶ms) -: m_handler(NULL), - m_keepAliveList(NULL, 1), - m_aliveList(NULL, 2), - m_noDataList(NULL, 1), - m_dataList(NULL, 2), - m_params(params), - m_refCount(1), - m_connectionList(NULL), - m_connectionListCount(0), - m_socket(INVALID_SOCKET), - m_boundAsServer(false), - m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), - m_keepAliveTimer(), - m_noDataTimer() -{ - if (params.keepAliveDelay > 0) - m_keepAliveTimer.start(); + TcpManager::TcpManager(const TcpParams ¶ms) + : m_handler(nullptr), + m_keepAliveList(nullptr, 1), + m_aliveList(nullptr, 2), + m_noDataList(nullptr, 1), + m_dataList(nullptr, 2), + m_params(params), + m_refCount(1), + m_connectionList(nullptr), + m_connectionListCount(0), + m_socket(INVALID_SOCKET), + m_boundAsServer(false), + m_allocator(params.allocatorBlockSize, params.allocatorBlockCount), + m_keepAliveTimer(), + m_noDataTimer() +#if defined(WIN32) + , m_permfds() +#endif + { + if (params.keepAliveDelay > 0) + m_keepAliveTimer.start(); - if (params.noDataTimeout > 0) - m_noDataTimer.start(); + if (params.noDataTimeout > 0) + m_noDataTimer.start(); #if defined(WIN32) - WSADATA wsaData; - WSAStartup(MAKEWORD(1,1), &wsaData); + WSADATA wsaData; + WSAStartup(MAKEWORD(1, 1), &wsaData); - FD_ZERO(&m_permfds);//select only used on win32 + FD_ZERO(&m_permfds);//select only used on win32 +#endif + } + + TcpManager::~TcpManager() + { +#if defined(WIN32) + WSACleanup(); #endif -} - - -TcpManager::~TcpManager() -{ + if (m_boundAsServer) + { #if defined(WIN32) - WSACleanup(); -#endif - - if (m_boundAsServer) - { -#if defined(WIN32) - closesocket(m_socket); + closesocket(m_socket); #else - close(m_socket); + close(m_socket); #endif - } - while (m_connectionList != NULL) - { - TcpConnection *con = m_connectionList; - m_connectionList = m_connectionList->m_nextConnection; - con->Release(); - m_connectionListCount--; - } -} + } + while (m_connectionList != nullptr) + { + TcpConnection *con = m_connectionList; + m_connectionList = m_connectionList->m_nextConnection; + con->Release(); + m_connectionListCount--; + } + } + bool TcpManager::BindAsServer() + { + m_socket = socket(AF_INET, SOCK_STREAM, 0); -bool TcpManager::BindAsServer() -{ - - m_socket = socket(AF_INET, SOCK_STREAM, 0); - - if (m_socket != INVALID_SOCKET) - { + if (m_socket != INVALID_SOCKET) + { #if defined(WIN32) #pragma warning(push) #pragma warning(disable : 4127) - FD_SET(m_socket, &m_permfds);//the socket this server is listening on + FD_SET(m_socket, &m_permfds);//the socket this server is listening on #pragma warning(pop) - unsigned long isNonBlocking = 1; - int outBufSize = m_params.outgoingBufferSize; - int inBufSize = m_params.incomingBufferSize; - int keepAlive = 1; - int reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; + unsigned long isNonBlocking = 1; + int outBufSize = m_params.outgoingBufferSize; + int inBufSize = m_params.incomingBufferSize; + int keepAlive = 1; + int reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; - if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0 ) - { - return false; - } + if (ioctlsocket(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char *)&outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char *)&inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) != 0) + { + return false; + } #else // linux is to remain the default compile mode - unsigned long isNonBlocking = 1; - unsigned long keepAlive = 1; - unsigned long outBufSize = m_params.outgoingBufferSize; - unsigned long inBufSize = m_params.incomingBufferSize; - unsigned long reuseAddr = 1; - struct linger ld; - ld.l_onoff = 0; - ld.l_linger = 0; + unsigned long isNonBlocking = 1; + unsigned long keepAlive = 1; + unsigned long outBufSize = m_params.outgoingBufferSize; + unsigned long inBufSize = m_params.incomingBufferSize; + unsigned long reuseAddr = 1; + struct linger ld; + ld.l_onoff = 0; + ld.l_linger = 0; - if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 - || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) - { - return false; - } + if (ioctl(m_socket, FIONBIO, &isNonBlocking) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, &outBufSize, sizeof(outBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, &inBufSize, sizeof(inBufSize)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) != 0 + || setsockopt(m_socket, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) != 0) + { + return false; + } #endif - } - else - { - return false; - } + } + else + { + return false; + } + struct sockaddr_in addr_loc; + addr_loc.sin_family = AF_INET; + addr_loc.sin_port = htons(m_params.port); + addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); + if (m_params.bindAddress[0] != 0) + { + unsigned long address = inet_addr(m_params.bindAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(m_params.bindAddress); + if (lphp != nullptr) + addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + else + { + addr_loc.sin_addr.s_addr = address; + } + } - struct sockaddr_in addr_loc; - addr_loc.sin_family = AF_INET; - addr_loc.sin_port = htons(m_params.port); - addr_loc.sin_addr.s_addr = htonl(INADDR_ANY); - if (m_params.bindAddress[0] != 0) - { - unsigned long address = inet_addr(m_params.bindAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(m_params.bindAddress); - if (lphp != NULL) - addr_loc.sin_addr.s_addr = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - else - { - addr_loc.sin_addr.s_addr = address; - } - } + if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) + { + return false; + } - if (bind(m_socket, (struct sockaddr *)&addr_loc, sizeof(addr_loc)) != 0) - { - return false; - } + if (listen(m_socket, 1000) != 0) + { + return false; + } - if (listen(m_socket, 1000) != 0) - { - return false; - } + m_boundAsServer = true; + return true; + } - m_boundAsServer = true; - return true; -} + TcpConnection *TcpManager::acceptClient() + { + TcpConnection *newConn = nullptr; -TcpConnection *TcpManager::acceptClient() -{ - TcpConnection *newConn = NULL; - - if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) - { + if (m_boundAsServer && m_connectionListCount < m_params.maxConnections) + { + sockaddr_in addr; + int addrLength = sizeof(addr); + SOCKET sock = ::accept(m_socket, (sockaddr *)&addr, (socklen_t *)&addrLength); - sockaddr_in addr; - int addrLength = sizeof(addr); - SOCKET sock = ::accept(m_socket, (sockaddr *) &addr, (socklen_t *) &addrLength); + if (sock != INVALID_SOCKET) + { + newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); + addNewConnection(newConn); + if (m_handler != nullptr) + { + m_handler->OnConnectRequest(newConn); + } + } + } + return newConn; + } - if (sock != INVALID_SOCKET) - { - newConn = new TcpConnection(this, &m_allocator, m_params, sock, IPAddress(addr.sin_addr.s_addr), ntohs(addr.sin_port)); - addNewConnection(newConn); - if (m_handler != NULL) - { - m_handler->OnConnectRequest(newConn); - } - } - } + void TcpManager::SetHandler(TcpManagerHandler *handler) + { + m_handler = handler; + } - return newConn; -} - -void TcpManager::SetHandler(TcpManagerHandler *handler) -{ - m_handler = handler; -} - -SOCKET TcpManager::getMaxFD() -{ + SOCKET TcpManager::getMaxFD() + { #ifdef WIN32 - return 0;//this param is not used on win32 for select, only on unix + return 0;//this param is not used on win32 for select, only on unix #else - SOCKET maxfd = 0; - - if (m_boundAsServer) - maxfd = m_socket+1; - - TcpConnection *next = NULL; - for (TcpConnection *con = m_connectionList ; con != NULL ; con = next) - { - next = con->m_nextConnection; - if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) - { - maxfd = con->m_socket + 1; - } - } - return maxfd; + SOCKET maxfd = 0; + + if (m_boundAsServer) + maxfd = m_socket + 1; + + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->GetStatus() != TcpConnection::StatusDisconnected && con->m_socket > maxfd) + { + maxfd = con->m_socket + 1; + } + } + return maxfd; #endif -} + } -TcpConnection *TcpManager::getConnection(SOCKET fd) -{ - TcpConnection *next = NULL; - for (TcpConnection *con = m_connectionList ; con != NULL ; con = next) - { - next = con->m_nextConnection; - if (con->m_socket == fd) - { - return con; - } - } - //if get here ,couldn't find it - return NULL; -} + TcpConnection *TcpManager::getConnection(SOCKET fd) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + next = con->m_nextConnection; + if (con->m_socket == fd) + { + return con; + } + } + //if get here ,couldn't find it + return nullptr; + } -bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections,unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) -{ - bool processedIncoming = false; + bool TcpManager::GiveTime(unsigned maxTimeAcceptingConnections, unsigned maxSendTimePerConnection, unsigned maxRecvTimePerConnection) + { + bool processedIncoming = false; - if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection==0 && maxRecvTimePerConnection==0) - { - //they don't want to do anything now - return processedIncoming; - } + if (maxTimeAcceptingConnections == 0 && maxSendTimePerConnection == 0 && maxRecvTimePerConnection == 0) + { + //they don't want to do anything now + return processedIncoming; + } - AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + AddRef(); //keep a reference to ourself in case we callback to the application and the application releases us. + //first process outgoing on each connection, and finish establishing connections, if params say to + if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) + { + // Send output from last heartbeat + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + if (con->GetStatus() == TcpConnection::StatusConnected) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxSendTimePerConnection)) + { + int err = con->processOutgoing(); - - //first process outgoing on each connection, and finish establishing connections, if params say to - if (m_connectionListCount != 0 && maxSendTimePerConnection != 0) - { - - // Send output from last heartbeat - TcpConnection *next = NULL; - for (TcpConnection *con = m_connectionList ; con != NULL ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - if(con->GetStatus() == TcpConnection::StatusConnected) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxSendTimePerConnection)) - { - int err = con->processOutgoing(); - - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - } - con->Release(); - } - else if (con->GetStatus() == TcpConnection::StatusNegotiating) - { - if (con->finishConnect() < 0) - { + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + } con->Release(); - continue; - } - con->Release(); - } - else //inactive client in client list???? - { - removeConnection(con); - con->Release(); - continue; - } - } - - } - - //process incoming messages (including connect requests) - if (( - m_boundAsServer //if in server mode and want to spend time accepting clients - && maxTimeAcceptingConnections != 0 - ) - || - ( - m_connectionListCount != 0 //if there are connections and want to spend time receiving on them - && maxRecvTimePerConnection != 0 - ) - ) - { -#ifdef WIN32 - SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 - - //select on all fd's - struct timeval timeout; - - fd_set tmpfds; - tmpfds = m_permfds; - timeout.tv_sec = 0; - timeout.tv_usec = 0; - int cnt = select(maxfd, &tmpfds, NULL, NULL, &timeout); // blocks for timeout - - - if (cnt > 0) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0) - {//activity on our socket means connect requests - - //see if are new incoming clients - if (FD_ISSET(m_socket, &tmpfds)) - { - //yep - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } - } - } - - - - //process incoming client messages - if (maxRecvTimePerConnection != 0) - { - TcpConnection *next = NULL; - for (TcpConnection *con = m_connectionList ; con != NULL ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextConnection; - if (next) next->AddRef(); - - SOCKET fd = con->m_socket; - if (fd == INVALID_SOCKET) - { - //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard - if (con->GetStatus() != TcpConnection::StatusNegotiating) - { - removeConnection(con); - con->Release(); - continue; - } - } - - if (FD_ISSET(fd, &tmpfds)) - { - Clock timer; - timer.start(); - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } - - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } - - }//while(!timer...) - }//if (FD_ISSET...) + } + else if (con->GetStatus() == TcpConnection::StatusNegotiating) + { + if (con->finishConnect() < 0) + { + con->Release(); + continue; + } con->Release(); - }//for (...) - } //maxRecvTimePerConnection != 0 - }//cnt > 0 + } + else //inactive client in client list???? + { + removeConnection(con); + con->Release(); + continue; + } + } + } + + //process incoming messages (including connect requests) + if (( + m_boundAsServer //if in server mode and want to spend time accepting clients + && maxTimeAcceptingConnections != 0 + ) + || + ( + m_connectionListCount != 0 //if there are connections and want to spend time receiving on them + && maxRecvTimePerConnection != 0 + ) + ) + { +#ifdef WIN32 + SOCKET maxfd = getMaxFD(); //re-calc maxfd every time select on WIN32 + + //select on all fd's + struct timeval timeout; + + fd_set tmpfds; + tmpfds = m_permfds; + timeout.tv_sec = 0; + timeout.tv_usec = 0; + int cnt = select(maxfd, &tmpfds, nullptr, nullptr, &timeout); // blocks for timeout + + if (cnt > 0) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0) + {//activity on our socket means connect requests + //see if are new incoming clients + if (FD_ISSET(m_socket, &tmpfds)) + { + //yep + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } + } + } + + //process incoming client messages + if (maxRecvTimePerConnection != 0) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextConnection; + if (next) next->AddRef(); + + SOCKET fd = con->m_socket; + if (fd == INVALID_SOCKET) + { + //invalid socket in list?, check if is connecting, otherwise, Disconnect and discard + if (con->GetStatus() != TcpConnection::StatusNegotiating) + { + removeConnection(con); + con->Release(); + continue; + } + } + + if (FD_ISSET(fd, &tmpfds)) + { + Clock timer; + timer.start(); + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } + + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer...) + }//if (FD_ISSET...) + con->Release(); + }//for (...) + } //maxRecvTimePerConnection != 0 + }//cnt > 0 #else //on UNIX use poll - int numfds = m_connectionListCount; - int idx = 0; - if (m_boundAsServer) - { - numfds++; - idx++; - } + int numfds = m_connectionListCount; + int idx = 0; + if (m_boundAsServer) + { + numfds++; + idx++; + } - struct pollfd pollfds[numfds]; + struct pollfd pollfds[numfds]; - if (m_boundAsServer) - { - pollfds[0].fd = m_socket; - pollfds[0].events |= POLLIN; - } + if (m_boundAsServer) + { + pollfds[0].fd = m_socket; + pollfds[0].events |= POLLIN; + } - TcpConnection *next = NULL; - for (TcpConnection *con = m_connectionList ; con != NULL ; con = next, idx++) - { - next = con->m_nextConnection; - pollfds[idx].fd = con->m_socket; - pollfds[idx].events |= POLLIN; - pollfds[idx].events |= POLLHUP; - } - + TcpConnection *next = nullptr; + for (TcpConnection *con = m_connectionList; con != nullptr; con = next, idx++) + { + next = con->m_nextConnection; + pollfds[idx].fd = con->m_socket; + pollfds[idx].events |= POLLIN; + pollfds[idx].events |= POLLHUP; + } - int cnt = poll(pollfds, numfds, 1); + int cnt = poll(pollfds, numfds, 1); - if(cnt == SOCKET_ERROR) - { - //poll not working? - //TODO: need to notify client somehow, don't think we can assume a fatal error here - } - else if (cnt > 0) - { - for (idx = 0; idx < numfds; idx++) - { - //find corresponding TcpConnection - //TODO: optimize, seriously, this is takes linear time, every time - TcpConnection *con = getConnection(pollfds[idx].fd); + if (cnt == SOCKET_ERROR) + { + //poll not working? + //TODO: need to notify client somehow, don't think we can assume a fatal error here + } + else if (cnt > 0) + { + for (idx = 0; idx < numfds; idx++) + { + //find corresponding TcpConnection + //TODO: optimize, seriously, this is takes linear time, every time + TcpConnection *con = getConnection(pollfds[idx].fd); - if (pollfds[idx].revents & POLLIN) - { - if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) - { - //new incoming clients - Clock timer; - timer.start(); - while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) - { - //loop - } + if (pollfds[idx].revents & POLLIN) + { + if (m_boundAsServer && maxTimeAcceptingConnections != 0 && pollfds[idx].fd == m_socket) + { + //new incoming clients + Clock timer; + timer.start(); + while (acceptClient() && !timer.isDone(maxTimeAcceptingConnections)) + { + //loop + } - continue;//don't try to readmsgs from listening fd - } - - //process regular msg(s) - if (con == NULL) - { - close(pollfds[idx].fd); - continue; - } + continue;//don't try to readmsgs from listening fd + } - Clock timer; - timer.start(); - con->AddRef();//so it can't get deleted while we are checking it's status - while(!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) - { - int err = con->processIncoming(); - if (err >= 0) - { - processedIncoming = true; - } + //process regular msg(s) + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - if (err > 0) - { - //couldn't finish processing last request, don't try more - break; - } - else if (err < 0) - { - break; - } + Clock timer; + timer.start(); + con->AddRef();//so it can't get deleted while we are checking it's status + while (!timer.isDone(maxRecvTimePerConnection) && con->GetStatus() == TcpConnection::StatusConnected) + { + int err = con->processIncoming(); + if (err >= 0) + { + processedIncoming = true; + } - }//while(!timer....) - con->Release(); - }//if(pollfds[... - else if (pollfds[idx].revents & POLLHUP) - { - if (con == NULL) - { - close(pollfds[idx].fd); - continue; - } + if (err > 0) + { + //couldn't finish processing last request, don't try more + break; + } + else if (err < 0) + { + break; + } + }//while(!timer....) + con->Release(); + }//if(pollfds[... + else if (pollfds[idx].revents & POLLHUP) + { + if (con == nullptr) + { + close(pollfds[idx].fd); + continue; + } - //Disconnect client - con->Disconnect(); - } - }//for (idx=0.... - }//else if (cnt > 0) + //Disconnect client + con->Disconnect(); + } + }//for (idx=0.... + }//else if (cnt > 0) #endif - }//wanted to process incoming messages or connect requests + }//wanted to process incoming messages or connect requests - //now process any keepalives, if time to do that - if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) - { - TcpConnection *next = NULL; - for (TcpConnection *con = m_keepAliveList.m_beginList ; con != NULL ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextKeepAliveConnection; - if (next) next->AddRef(); - - con->Send(NULL, 0); //note: this request will move the connection from the keepAliveList to the aliveList - con->Release(); - } + //now process any keepalives, if time to do that + if (m_params.keepAliveDelay > 0 && m_keepAliveTimer.isDone(m_params.keepAliveDelay)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_keepAliveList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextKeepAliveConnection; + if (next) next->AddRef(); - //now move the complete alive list over to the keepalive list to reset those timers - m_keepAliveList.m_beginList = m_aliveList.m_beginList; - m_aliveList.m_beginList = NULL; + con->Send(nullptr, 0); //note: this request will move the connection from the keepAliveList to the aliveList + con->Release(); + } - //switch id's for those connections that were in the alive list last go - around - int tmpID = m_aliveList.m_listID; - m_aliveList.m_listID = m_keepAliveList.m_listID; - m_keepAliveList.m_listID = tmpID; + //now move the complete alive list over to the keepalive list to reset those timers + m_keepAliveList.m_beginList = m_aliveList.m_beginList; + m_aliveList.m_beginList = nullptr; - m_keepAliveTimer.reset(); - m_keepAliveTimer.start(); - } + //switch id's for those connections that were in the alive list last go - around + int tmpID = m_aliveList.m_listID; + m_aliveList.m_listID = m_keepAliveList.m_listID; + m_keepAliveList.m_listID = tmpID; - //now process any noDataCons, if time to do that - if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) - { - TcpConnection *next = NULL; - for (TcpConnection *con = m_noDataList.m_beginList ; con != NULL ; con = next) - { - con->AddRef(); - if (next) next->Release(); - next = con->m_nextRecvDataConnection; - if (next) next->AddRef(); + m_keepAliveTimer.reset(); + m_keepAliveTimer.start(); + } - //time to disconnect this guy - con->Disconnect(); - con->Release(); - } + //now process any noDataCons, if time to do that + if (m_params.noDataTimeout > 0 && m_noDataTimer.isDone(m_params.noDataTimeout)) + { + TcpConnection *next = nullptr; + for (TcpConnection *con = m_noDataList.m_beginList; con != nullptr; con = next) + { + con->AddRef(); + if (next) next->Release(); + next = con->m_nextRecvDataConnection; + if (next) next->AddRef(); - //now move the complete data list over to the nodata list to reset those timers - m_noDataList.m_beginList = m_dataList.m_beginList; - m_dataList.m_beginList = NULL; + //time to disconnect this guy + con->Disconnect(); + con->Release(); + } - //switch id's for those connections that were in the data list last go - around - int tmpID = m_dataList.m_listID; - m_dataList.m_listID = m_noDataList.m_listID; - m_noDataList.m_listID = tmpID; + //now move the complete data list over to the nodata list to reset those timers + m_noDataList.m_beginList = m_dataList.m_beginList; + m_dataList.m_beginList = nullptr; - m_noDataTimer.reset(); - m_noDataTimer.start(); - } + //switch id's for those connections that were in the data list last go - around + int tmpID = m_dataList.m_listID; + m_dataList.m_listID = m_noDataList.m_listID; + m_noDataList.m_listID = tmpID; - Release(); + m_noDataTimer.reset(); + m_noDataTimer.start(); + } - return processedIncoming; -} + Release(); -TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) -{ - if (m_boundAsServer) - { - //can't open outgoing connections when in server mode - // use a different TcpManager to do that - return NULL; - } + return processedIncoming; + } - if (m_connectionListCount >= m_params.maxConnections) - return(NULL); + TcpConnection *TcpManager::EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout) + { + if (m_boundAsServer) + { + //can't open outgoing connections when in server mode + // use a different TcpManager to do that + return nullptr; + } - // get server address - unsigned long address = inet_addr(serverAddress); - if (address == INADDR_NONE) - { - struct hostent * lphp; - lphp = gethostbyname(serverAddress); - if (lphp == NULL) - return(NULL); - address = ((struct in_addr *)(lphp->h_addr))->s_addr; - } - IPAddress destIP(address); + if (m_connectionListCount >= m_params.maxConnections) + return(nullptr); - TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); - con->AddRef();//for the client - to conform to UdpLibrary method - addNewConnection(con); + // get server address + unsigned long address = inet_addr(serverAddress); + if (address == INADDR_NONE) + { + struct hostent * lphp; + lphp = gethostbyname(serverAddress); + if (lphp == nullptr) + return(nullptr); + address = ((struct in_addr *)(lphp->h_addr))->s_addr; + } + IPAddress destIP(address); - return con; -} + TcpConnection *con = new TcpConnection(this, &m_allocator, m_params, destIP, serverPort, timeout); + con->AddRef();//for the client - to conform to UdpLibrary method + addNewConnection(con); -void TcpManager::addNewConnection(TcpConnection *con) -{ - con->AddRef(); + return con; + } + + void TcpManager::addNewConnection(TcpConnection *con) + { + con->AddRef(); #ifdef WIN32 //uses select - if (con->m_socket != INVALID_SOCKET) - { + if (con->m_socket != INVALID_SOCKET) + { #pragma warning(push) #pragma warning(disable : 4127) - FD_SET(con->m_socket, &m_permfds); + FD_SET(con->m_socket, &m_permfds); #pragma warning(pop) - } + } #endif - con->m_nextConnection = m_connectionList; - con->m_prevConnection = NULL; - if (m_connectionList != NULL) - m_connectionList->m_prevConnection = con; - m_connectionList = con; - m_connectionListCount++; + con->m_nextConnection = m_connectionList; + con->m_prevConnection = nullptr; + if (m_connectionList != nullptr) + m_connectionList->m_prevConnection = con; + m_connectionList = con; + m_connectionListCount++; - con->m_nextKeepAliveConnection = m_aliveList.m_beginList; - con->m_prevKeepAliveConnection = NULL; - if (m_aliveList.m_beginList != NULL) - m_aliveList.m_beginList->m_prevKeepAliveConnection = con; - m_aliveList.m_beginList = con; - con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is + con->m_nextKeepAliveConnection = m_aliveList.m_beginList; + con->m_prevKeepAliveConnection = nullptr; + if (m_aliveList.m_beginList != nullptr) + m_aliveList.m_beginList->m_prevKeepAliveConnection = con; + m_aliveList.m_beginList = con; + con->m_aliveListId = m_keepAliveList.m_listID;//start it out thinking it's already in the alive list, since it is - con->m_nextRecvDataConnection = m_dataList.m_beginList; - con->m_prevRecvDataConnection = NULL; - if (m_dataList.m_beginList != NULL) - m_dataList.m_beginList->m_prevRecvDataConnection = con; - m_dataList.m_beginList = con; - con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is -} + con->m_nextRecvDataConnection = m_dataList.m_beginList; + con->m_prevRecvDataConnection = nullptr; + if (m_dataList.m_beginList != nullptr) + m_dataList.m_beginList->m_prevRecvDataConnection = con; + m_dataList.m_beginList = con; + con->m_recvDataListId = m_noDataList.m_listID;//start it out thinking it's already in the data list, since it is + } -void TcpManager::removeConnection(TcpConnection *con) -{ - if (!con->wasRemovedFromMgr()) - { - con->setRemovedFromMgr(); - m_connectionListCount--; - #ifdef WIN32 //select only used on win32 - if (con->m_socket != INVALID_SOCKET) - { + void TcpManager::removeConnection(TcpConnection *con) + { + if (!con->wasRemovedFromMgr()) + { + con->setRemovedFromMgr(); + m_connectionListCount--; +#ifdef WIN32 //select only used on win32 + if (con->m_socket != INVALID_SOCKET) + { #pragma warning(push) #pragma warning(disable : 4127) - FD_CLR(con->m_socket, &m_permfds); + FD_CLR(con->m_socket, &m_permfds); #pragma warning(pop) - } - #endif - if (con->m_prevConnection != NULL) - con->m_prevConnection->m_nextConnection = con->m_nextConnection; - if (con->m_nextConnection != NULL) - con->m_nextConnection->m_prevConnection = con->m_prevConnection; - if (m_connectionList == con) - m_connectionList = con->m_nextConnection; - con->m_nextConnection = NULL; - con->m_prevConnection = NULL; + } +#endif + if (con->m_prevConnection != nullptr) + con->m_prevConnection->m_nextConnection = con->m_nextConnection; + if (con->m_nextConnection != nullptr) + con->m_nextConnection->m_prevConnection = con->m_prevConnection; + if (m_connectionList == con) + m_connectionList = con->m_nextConnection; + con->m_nextConnection = nullptr; + con->m_prevConnection = nullptr; - if (con->m_prevKeepAliveConnection != NULL) - con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; - if (con->m_nextKeepAliveConnection != NULL) - con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; + if (con->m_prevKeepAliveConnection != nullptr) + con->m_prevKeepAliveConnection->m_nextKeepAliveConnection = con->m_nextKeepAliveConnection; + if (con->m_nextKeepAliveConnection != nullptr) + con->m_nextKeepAliveConnection->m_prevKeepAliveConnection = con->m_prevKeepAliveConnection; - if (m_aliveList.m_beginList == con) - m_aliveList.m_beginList = con->m_nextKeepAliveConnection; - else if (m_keepAliveList.m_beginList == con) - m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; - con->m_nextKeepAliveConnection = NULL; - con->m_prevKeepAliveConnection = NULL; + if (m_aliveList.m_beginList == con) + m_aliveList.m_beginList = con->m_nextKeepAliveConnection; + else if (m_keepAliveList.m_beginList == con) + m_keepAliveList.m_beginList = con->m_nextKeepAliveConnection; + con->m_nextKeepAliveConnection = nullptr; + con->m_prevKeepAliveConnection = nullptr; + if (con->m_prevRecvDataConnection != nullptr) + con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; + if (con->m_nextRecvDataConnection != nullptr) + con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + if (m_dataList.m_beginList == con) + m_dataList.m_beginList = con->m_nextRecvDataConnection; + else if (m_noDataList.m_beginList == con) + m_noDataList.m_beginList = con->m_nextRecvDataConnection; + con->m_nextRecvDataConnection = nullptr; + con->m_prevRecvDataConnection = nullptr; - if (con->m_prevRecvDataConnection != NULL) - con->m_prevRecvDataConnection->m_nextRecvDataConnection = con->m_nextRecvDataConnection; - if (con->m_nextRecvDataConnection != NULL) - con->m_nextRecvDataConnection->m_prevRecvDataConnection = con->m_prevRecvDataConnection; + con->Release(); + } + } - if (m_dataList.m_beginList == con) - m_dataList.m_beginList = con->m_nextRecvDataConnection; - else if (m_noDataList.m_beginList == con) - m_noDataList.m_beginList = con->m_nextRecvDataConnection; - con->m_nextRecvDataConnection = NULL; - con->m_prevRecvDataConnection = NULL; + void TcpManager::AddRef() + { + m_refCount++; + } + void TcpManager::Release() + { + if (--m_refCount == 0) + delete this; + } + IPAddress TcpManager::GetLocalIp() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(IPAddress(addr_self.sin_addr.s_addr)); + } - con->Release(); - } -} - -void TcpManager::AddRef() -{ - m_refCount++; -} - -void TcpManager::Release() -{ - if (--m_refCount == 0) - delete this; -} - -IPAddress TcpManager::GetLocalIp() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(IPAddress(addr_self.sin_addr.s_addr)); - -} - -unsigned int TcpManager::GetLocalPort() const -{ - struct sockaddr_in addr_self; - memset(&addr_self, 0, sizeof(addr_self)); - socklen_t len = sizeof(addr_self); - getsockname(m_socket, (struct sockaddr *)&addr_self, &len); - return(ntohs(addr_self.sin_port)); -} - + unsigned int TcpManager::GetLocalPort() const + { + struct sockaddr_in addr_self; + memset(&addr_self, 0, sizeof(addr_self)); + socklen_t len = sizeof(addr_self); + getsockname(m_socket, (struct sockaddr *)&addr_self, &len); + return(ntohs(addr_self.sin_port)); + } #ifdef EXTERNAL_DISTRO }; -#endif - - +#endif \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.h index 75eb6df4..c4e8b1cf 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/TcpLibrary/TcpManager.h @@ -156,7 +156,7 @@ public: * simply need to derive your class (multiply if necessary) from TcpManagerHandler, then you can use * this method to set the object the TcpManager will call as appropriate. The TcpConnection object * also has a handler mechanism that replaces the other callback functions below, see TcpConnection::SetHandler - * default = NULL (no callbacks made) + * default = nullptr (no callbacks made) * * @param handler The object which will be called for manager related notifications. */ @@ -211,7 +211,7 @@ public: * the connect-complete callback to be called if the connection is succesfull. * * @return A pointer to a TcpConnection object. - * NULL if the manager object has exceeded its maximum number of connections + * nullptr if the manager object has exceeded its maximum number of connections * or if the serverAddress cannot be resolved to an IP address. */ TcpConnection *EstablishConnection(const char *serverAddress, unsigned short serverPort, unsigned timeout = 0); diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/GZipHelper.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/GZipHelper.h index a01bf682..dab0f9b3 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/GZipHelper.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/GZipHelper.h @@ -187,7 +187,7 @@ class CA2GZIPT int destroy() { int err = Z_OK; - if (m_zstream.state != NULL) { + if (m_zstream.state != nullptr) { err = deflateEnd(&(m_zstream)); } if (m_z_err < 0) err = m_z_err; @@ -459,7 +459,7 @@ class CGZIP2AT int destroy() { int err = Z_OK; - if (m_zstream.state != NULL) { + if (m_zstream.state != nullptr) { err = inflateEnd(&(m_zstream)); } if (m_z_err < 0) err = m_z_err; diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zlib.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zlib.h index 52cb529f..fb425a3b 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zlib.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zlib.h @@ -74,7 +74,7 @@ typedef struct z_stream_s { uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total nb of bytes output so far */ - char *msg; /* last error message, NULL if no error */ + char *msg; /* last error message, nullptr if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ @@ -193,7 +193,7 @@ ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); enough memory, Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not + msg is set to nullptr if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ @@ -271,7 +271,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + if next_in or next_out was nullptr), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). */ @@ -304,7 +304,7 @@ ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error + version assumed by the caller. msg is set to nullptr if there is no error message. inflateInit does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.) @@ -372,7 +372,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent - (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not + (for example if next_in or next_out was nullptr), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR case, the application may then call inflateSync to look for a good @@ -437,7 +437,7 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does + method). msg is set to nullptr if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ @@ -471,7 +471,7 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, actually used by the compressor.) deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is + parameter is invalid (such as nullptr dictionary) or the stream state is inconsistent (for example if deflate has already been called for this stream or if the compression method is bsort). deflateSetDictionary does not perform any compression: this will be done by deflate(). @@ -491,7 +491,7 @@ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and + (such as zalloc being nullptr). msg is left unchanged in both source and destination. */ @@ -503,7 +503,7 @@ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); that may have been set by deflateInit2. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). + stream state was inconsistent (such as zalloc or state being nullptr). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, @@ -544,7 +544,7 @@ ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative - memLevel). msg is set to null if there is no error message. inflateInit2 + memLevel). msg is set to nullptr if there is no error message. inflateInit2 does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.) @@ -562,7 +562,7 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, dictionary (see deflateSetDictionary). inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is + parameter is invalid (such as nullptr dictionary) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of @@ -591,7 +591,7 @@ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). + stream state was inconsistent (such as zalloc or state being nullptr). */ @@ -667,7 +667,7 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. - gzopen returns NULL if the file could not be opened or if there was + gzopen returns nullptr if the file could not be opened or if there was insufficient memory to allocate the (de)compression state; errno can be checked to distinguish the two cases (if errno is zero, the zlib error is Z_MEM_ERROR). */ @@ -681,7 +681,7 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd), mode) closes the file descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate + gzdopen returns nullptr if there was insufficient memory to allocate the (de)compression state. */ @@ -718,8 +718,8 @@ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. + Writes the given nullptr-terminated string to the compressed file, excluding + the terminating nullptr character. gzputs returns the number of characters written, or -1 in case of error. */ @@ -727,7 +727,7 @@ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null + condition is encountered. The string is then terminated with a nullptr character. gzgets returns buf, or Z_NULL in case of error. */ @@ -822,7 +822,7 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns + return the updated checksum. If buf is nullptr, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much faster. Usage example: @@ -838,7 +838,7 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running crc with the bytes buf[0..len-1] and return the updated - crc. If buf is NULL, this function returns the required initial value + crc. If buf is nullptr, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: diff --git a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zutil.h b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zutil.h index 718ebc15..fecd535d 100755 --- a/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zutil.h +++ b/engine/server/application/CentralServer/src/shared/AuctionTransferGameAPI/zip/Zip/zutil.h @@ -116,7 +116,7 @@ extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */ # include /* for fdopen */ # else # ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ +# define fdopen(fd,mode) nullptr /* No fdopen() */ # endif # endif #endif @@ -130,7 +130,7 @@ extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */ #endif #if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ +# define fdopen(fd,mode) nullptr /* No fdopen() */ #endif #if (defined(_MSC_VER) && (_MSC_VER > 600)) diff --git a/engine/server/application/CentralServer/src/shared/CentralCSHandler.h b/engine/server/application/CentralServer/src/shared/CentralCSHandler.h index e2b5fd0b..09e7c5f3 100755 --- a/engine/server/application/CentralServer/src/shared/CentralCSHandler.h +++ b/engine/server/application/CentralServer/src/shared/CentralCSHandler.h @@ -16,28 +16,27 @@ class StructureListMessage; #define DECLARE_CS_CMD( _name ) void handle_##_name( GameServerCSRequestMessage & message ); - class CentralCSHandler { public: static void install(); static void remove(); static CentralCSHandler & getInstance(); - void handle( const CSToolRequest& msg, uint32 loginServerId ); + void handle(const CSToolRequest& msg, uint32 loginServerId); ~CentralCSHandler(); - - void handleFindObjectResponse( int iIndex, bool bFound ); - void handleStructureListResponse( StructureListMessage& msg ); - + + void handleFindObjectResponse(int iIndex, bool bFound); + void handleStructureListResponse(StructureListMessage& msg); + // only need to DECLARE_CS_CMD for commands handled at the CentralServer. - - DECLARE_CS_CMD( list_structures ); - DECLARE_CS_CMD( login_character ); - DECLARE_CS_CMD( warp_player ); - + + DECLARE_CS_CMD(list_structures); + DECLARE_CS_CMD(login_character); + DECLARE_CS_CMD(warp_player); + protected: static CentralCSHandler * smp_instance; - typedef void( CentralCSHandler::*CentralCSHandlerFunc )( GameServerCSRequestMessage & ); + typedef void(CentralCSHandler::*CentralCSHandlerFunc)(GameServerCSRequestMessage &); class HandlerEntry { @@ -52,75 +51,70 @@ protected: TYPE_ARBITRARY_GAME_SERVER // send to a game server, we don't care which one. This is used // if all game servers have what we're looking for, so we don't care who gets it. }; - - - HandlerEntry( const std::string & in_name, CentralCSHandlerFunc in_func, EntryType in_type ) : - name( in_name ), - type( in_type ), - func( in_func ) + + HandlerEntry(const std::string & in_name, CentralCSHandlerFunc in_func, EntryType in_type) : + name(in_name), + type(in_type), + func(in_func) { } - - HandlerEntry( const std::string & in_name, EntryType in_type ) : - name(in_name), - type( in_type ) + + HandlerEntry(const std::string & in_name, EntryType in_type) : + name(in_name), + type(in_type), + func(nullptr) { } - + std::string name; EntryType type; - CentralCSHandlerFunc func; // will be null unless it's of TYPE_CENTRAL. - - + CentralCSHandlerFunc func; // will be nullptr unless it's of TYPE_CENTRAL. }; - + class CSCharacterFindInfo { public: - CSCharacterFindInfo( NetworkId & id, int numServers, GameServerCSRequestMessage &req, bool bHandleAtCentral ) : - commandLine( req.getCommandString() ), - command( req.getCommandName() ), - iAccessLevel( req.getAccessLevel() ), - user(req.getUserName() ), - iToolId( req.getToolId() ), - iAccount( req.getAccountId() ), - responsesWaiting( numServers ), - iLoginServerId( req.getLoginServerID() ), - bCentral( bHandleAtCentral ) - + CSCharacterFindInfo(NetworkId & id, int numServers, GameServerCSRequestMessage &req, bool bHandleAtCentral) : + commandLine(req.getCommandString()), + command(req.getCommandName()), + iAccessLevel(req.getAccessLevel()), + user(req.getUserName()), + iToolId(req.getToolId()), + iAccount(req.getAccountId()), + responsesWaiting(numServers), + iLoginServerId(req.getLoginServerID()), + bCentral(bHandleAtCentral) + { - } - + std::string commandLine; std::string command; - + uint32 iAccessLevel; std::string user; - + uint32 iToolId; int iAccount; - - - int responsesWaiting; + + int responsesWaiting; int iLoginServerId; bool bCentral; // if offline, should we handle this at the Central Server or the DB? protected: - }; - + typedef std::map< int, CSCharacterFindInfo * > CentralCharFindMap; - + CentralCharFindMap m_findMap; - + typedef std::map< std::string, HandlerEntry * > CentralCSHandlerMap; - + CentralCSHandlerMap m_entries; - + private: CentralCSHandler() : - m_findMap(), - m_entries() + m_findMap(), + m_entries() { }; }; diff --git a/engine/server/application/CentralServer/src/shared/CentralServer.cpp b/engine/server/application/CentralServer/src/shared/CentralServer.cpp index 35d9e51c..8e39542c 100755 --- a/engine/server/application/CentralServer/src/shared/CentralServer.cpp +++ b/engine/server/application/CentralServer/src/shared/CentralServer.cpp @@ -122,6 +122,11 @@ #include "unicodeArchive/UnicodeArchive.h" #include +#include "sharedFoundation/CrcConstexpr.hpp" + +#include "webAPI.h" + +using namespace StellaBellum; namespace CentralServerNamespace { @@ -587,7 +592,7 @@ void CentralServer::getReadyGameServers(std::vector &theList) GameServerConnection * CentralServer::getRandomGameServer(void) { if (m_gameServerConnectionsList.empty()) - return NULL; + return nullptr; // m_gameServerConnectionsList ***DOES NOT*** contain the DB server so // we don't have to worry about checking for and excluding the DB server @@ -611,7 +616,7 @@ GameServerConnection * CentralServer::getRandomGameServer(void) indexNextGameServer = 0; } - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -695,13 +700,9 @@ void CentralServer::launchStartingProcesses() const // TaskManager *AND* have received our cluster id from the LoginServer if (!m_taskManager || !m_taskManager->isConnected() || (m_clusterId == 0)) { - if (!m_taskManager) - REPORT_LOG(true, ("CentralServer not launching starting processes because m_taskManager is NULL\n")); - else if (!m_taskManager->isConnected()) - REPORT_LOG(true, ("CentralServer not launching starting processes because m_taskManager->isConnected() is false\n")); - - if (m_clusterId == 0) - REPORT_LOG(true, ("CentralServer not launching starting processes because m_clusterId is 0, meaning hasn't received the cluster Id from the LoginServer yet\n")); + REPORT_LOG(!m_taskManager, ("CentralServer not launching starting processes because m_taskManager is null\n")); + REPORT_LOG(!m_taskManager->isConnected(), ("CentralServer not launching starting processes because m_taskManager->isConnected() is false\n")); + REPORT_LOG((m_clusterId==0), ("CentralServer not launching starting processes because m_clusterId is 0 - not received from the LoginServer yet\n")); return; } @@ -820,7 +821,7 @@ void CentralServer::launchStartingPlanetServers() char const * const p = ConfigCentralServer::getStartPlanet(i); if (p) { - FATAL(!*p, ("CentralServer::launchStartingPlanetServers: ConfigCentralServer::getStartPlanet(%d) specified a non-null but empty planet name", i)); + FATAL(!*p, ("CentralServer::launchStartingPlanetServers: ConfigCentralServer::getStartPlanet(%d) specified a non-nullptr but empty planet name", i)); std::string planetName; std::string hostName; @@ -865,1655 +866,1686 @@ void CentralServer::launchCommoditiesServer() void CentralServer::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { - if(message.isType("LoginKeyPush")) - { - // receiving another key - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const LoginKeyPush k(ri); - m_loginServerKeys->pushKey(k.getKey()); - DEBUG_REPORT_LOG(true, ("Received session key.\n")); - ConnectionServerConnectionList::iterator i = m_connectionServerConnections.begin(); - for (;i != m_connectionServerConnections.end(); ++i) - { - (*i)->send(k, true); - } - } - else if (message.isType("RequestClusterShutdown")) - { - REPORT_LOG(true, ("An admin requested we shutdown the entire cluster\n")); - m_done = true; - } - else if (message.isType("ClientConnectionClosed")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const msg(ri); + const uint32 messageType = message.getType(); - ConnectionServerSUIDMap::iterator i = m_accountConnectionMap.find(msg.getValue()); - if ((i != m_accountConnectionMap.end()) && (i->second == &source)) - { - // Erase the entry - m_accountConnectionMap.erase(i); - } - } - else if(message.isType("ConnectionOpened")) - { - if (!dynamic_cast(&source)) - { - ServerConnection *newServer = const_cast(safe_cast(&source)); - uint32 pid = newServer->getProcessId(); - - CentralGameServerSetProcessId pidMessage(pid, ServerClock::getInstance().getSubtractInterval(), ConfigCentralServer::getClusterName()); - newServer->send(pidMessage, true); - } - } - else if(message.isType("ConnectionServerConnectionClosed")) - { - DEBUG_REPORT_LOG(true,("Handling connection server crash.\n")); - ConnectionServerConnection const *c = safe_cast(&source); - removeFromAccountConnectionMap(c->getId()); - } - else if(message.isType("GameConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Game server closed connection\n")); - GameServerConnection const *g = safe_cast(&source); - removeGameServer(g); - } - - else if (message.isType("LoginConnectionOpened")) - { - LoginServerConnection *l = const_cast(safe_cast(&source)); - m_loginServerConnectionMap[l->getProcessId()] = l; - //Send connection server data - ConnectionServerConnectionList::iterator i = m_connectionServerConnections.begin(); - for(; i != m_connectionServerConnections.end(); ++i) - { - const ConnectionServerConnection * const csc = *i; - if ( (csc->getClientServicePortPrivate() != 0) || (csc->getClientServicePortPublic() != 0) ) - { - const LoginConnectionServerAddress csa(csc->getId(), csc->getClientServiceAddress(), csc->getClientServicePortPrivate(), csc->getClientServicePortPublic(), csc->getPlayerCount(), csc->getPingPort ()); - l->send(csa, true); + switch (messageType) { + case constcrc("LoginKeyPush") : { + // receiving another key + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const LoginKeyPush k(ri); + m_loginServerKeys->pushKey(k.getKey()); + DEBUG_REPORT_LOG(true, ("Received session key.\n")); + ConnectionServerConnectionList::iterator i = m_connectionServerConnections.begin(); + for (; i != m_connectionServerConnections.end(); ++i) { + (*i)->send(k, true); } + break; } - - // send preload is finished, if it is - PreloadFinishedMessage msg(isPreloadFinished()); - l->send(msg, true); - - CharacterCreationTracker::getInstance().retryLoginServerCreates(); - } - - else if(message.isType("LoginConnectionClosed")) - { - LoginServerConnection const *l = safe_cast(&source); - LoginServerConnectionMapType::iterator i=m_loginServerConnectionMap.find(l->getProcessId()); - if (i!=m_loginServerConnectionMap.end()) - m_loginServerConnectionMap.erase(i); - - // In development mode, try to reconnect to the login server if we aren't shutting down - if (ConfigCentralServer::getDevelopmentMode() && !m_done) - connectToLoginServer(); - - CharacterCreationTracker::getInstance().onLoginServerDisconnect(l->getProcessId()); - } - - else if(message.isType("ClusterId")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const msg(ri); - - if (m_clusterId == 0) - { - FATAL(((msg.getValue() < 1) || (msg.getValue() > 255)),("Cluster Id (%lu) must be between 1 and 255 inclusive", msg.getValue())); - - m_clusterId = static_cast(msg.getValue()); - - // start launching processes - launchStartingProcesses(); + case constcrc("RequestClusterShutdown") : { + REPORT_LOG(true, ("An admin requested we shutdown the entire cluster\n")); + m_done = true; + break; } - } + case constcrc("ClientConnectionClosed") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage const msg(ri); - else if(message.isType("CentralGameServerConnect")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CentralGameServerConnect c(ri); - - GameServerConnection *g = const_cast(safe_cast(&source)); - - if (g != nullptr) { - - FATAL(ConfigCentralServer::getValidateBuildVersionNumber() && strcmp(ApplicationVersion::getInternalVersion(), c.getBuildVersionNumber().c_str()), - ("Build version number mismatch: central server (%s), remote server %s (%s)", - ApplicationVersion::getInternalVersion(), g->getRemoteAddress().c_str(), c.getBuildVersionNumber().c_str())); - - // a game server (or db process) has connected... - addGameServer(g); + ConnectionServerSUIDMap::iterator i = m_accountConnectionMap.find(msg.getValue()); + if ((i != m_accountConnectionMap.end()) && (i->second == &source)) { + // Erase the entry + m_accountConnectionMap.erase(i); + } + break; + } + case constcrc("ConnectionOpened") : { + if (!dynamic_cast(&source)) { + ServerConnection * newServer = const_cast(safe_cast < ServerConnection const * > + (&source)); + uint32 pid = newServer->getProcessId(); + CentralGameServerSetProcessId pidMessage(pid, ServerClock::getInstance() + .getSubtractInterval(), ConfigCentralServer::getClusterName()); + newServer->send(pidMessage, true); + } + break; + } + case constcrc("ConnectionServerConnectionClosed") : { + DEBUG_REPORT_LOG(true, ("Handling connection server crash.\n")); + ConnectionServerConnection const *c = safe_cast < ConnectionServerConnection const * > (&source); + removeFromAccountConnectionMap(c->getId()); + break; + } + case constcrc("GameConnectionClosed") : { + DEBUG_REPORT_LOG(true, ("Game server closed connection\n")); + GameServerConnection const *g = safe_cast < GameServerConnection const * > (&source); + removeGameServer(g); + break; + } + case constcrc("LoginConnectionOpened") : { + LoginServerConnection *l = const_cast(safe_cast < LoginServerConnection const * > + (&source)); + m_loginServerConnectionMap[l->getProcessId()] = l; //Send connection server data ConnectionServerConnectionList::iterator i = m_connectionServerConnections.begin(); - for (; i != m_connectionServerConnections.end(); ++i) - { - if ((*i)->getGameServicePort() != 0) - { - ConnectionServerAddress csa((*i)->getGameServiceAddress(), (*i)->getGameServicePort()); - g->send(csa, true); + for (; i != m_connectionServerConnections.end(); ++i) { + const ConnectionServerConnection *const csc = *i; + if ((csc->getClientServicePortPrivate() != 0) || (csc->getClientServicePortPublic() != 0)) { + const LoginConnectionServerAddress csa(csc->getId(), csc->getClientServiceAddress(), csc + ->getClientServicePortPrivate(), csc->getClientServicePortPublic(), csc + ->getPlayerCount(), csc->getPingPort()); + l->send(csa, true); } } + // send preload is finished, if it is + PreloadFinishedMessage msg(isPreloadFinished()); + l->send(msg, true); + + CharacterCreationTracker::getInstance().retryLoginServerCreates(); + break; + } + case constcrc("LoginConnectionClosed") : { + LoginServerConnection const *l = safe_cast(&source); + LoginServerConnectionMapType::iterator i = m_loginServerConnectionMap.find(l->getProcessId()); + if (i != m_loginServerConnectionMap.end()) { + m_loginServerConnectionMap.erase(i); + } + + // In development mode, try to reconnect to the login server if we aren't shutting down + if (ConfigCentralServer::getDevelopmentMode() && !m_done) { + connectToLoginServer(); + } + + CharacterCreationTracker::getInstance().onLoginServerDisconnect(l->getProcessId()); + break; + } + case constcrc("ClusterId") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage const msg(ri); + + if (m_clusterId == 0) { + FATAL(((msg.getValue() < 1) || + (msg.getValue() > 255)), ("Cluster Id (%lu) must be between 1 and 255 inclusive", msg + .getValue())); + + m_clusterId = static_cast(msg.getValue()); + + // start launching processes + launchStartingProcesses(); + } + break; + } + case constcrc("CentralGameServerConnect") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CentralGameServerConnect c(ri); + + GameServerConnection *g = const_cast(safe_cast < GameServerConnection const * > + (&source)); + + if (g != nullptr) { + + FATAL(ConfigCentralServer::getValidateBuildVersionNumber() && + strcmp(ApplicationVersion::getInternalVersion(), c.getBuildVersionNumber().c_str()), + ("Build version number mismatch: central server (%s), remote server %s (%s)", + ApplicationVersion::getInternalVersion(), g->getRemoteAddress().c_str(), c + .getBuildVersionNumber().c_str())); + + // a game server (or db process) has connected... + addGameServer(g); + + //Send connection server data + ConnectionServerConnectionList::iterator i = m_connectionServerConnections.begin(); + for (; i != m_connectionServerConnections.end(); ++i) { + if ((*i)->getGameServicePort() != 0) { + ConnectionServerAddress csa((*i)->getGameServiceAddress(), (*i)->getGameServicePort()); + g->send(csa, true); + } + } + + std::set::const_iterator chatIter; + for (chatIter = m_chatServerConnections.begin(); + chatIter != m_chatServerConnections.end(); ++chatIter) { + if ((*chatIter)->getGameServicePort()) { + ChatServerOnline cso((*chatIter)->getRemoteAddress(), (*chatIter)->getGameServicePort()); + g->send(cso, true); + } + } + + const GenericValueTypeMessage > address("CustomerServiceServerGameServerServiceAddress", std::make_pair(s_customerServiceServerGameServerServiceAddress + .first, s_customerServiceServerGameServerServiceAddress.second)); + g->send(address, true); + } + break; + } + case constcrc("ChatClosedConnectionWithGameServer") : { + GameServerConnection *g = const_cast(safe_cast < GameServerConnection const * > + (&source)); std::set::const_iterator chatIter; - for (chatIter = m_chatServerConnections.begin(); chatIter != m_chatServerConnections.end(); ++chatIter) - { - if ((*chatIter)->getGameServicePort()) - { + for (chatIter = m_chatServerConnections.begin(); chatIter != m_chatServerConnections.end(); ++chatIter) { + if ((*chatIter)->getGameServicePort()) { ChatServerOnline cso((*chatIter)->getRemoteAddress(), (*chatIter)->getGameServicePort()); g->send(cso, true); } } - - const GenericValueTypeMessage > address("CustomerServiceServerGameServerServiceAddress", std::make_pair(s_customerServiceServerGameServerServiceAddress.first, s_customerServiceServerGameServerServiceAddress.second)); - g->send(address, true); + break; } - } - else if (message.isType("ChatClosedConnectionWithGameServer")) - { - GameServerConnection *g = const_cast(safe_cast(&source)); - std::set::const_iterator chatIter; - for(chatIter = m_chatServerConnections.begin(); chatIter != m_chatServerConnections.end(); ++chatIter) - { - if((*chatIter)->getGameServicePort()) - { - ChatServerOnline cso((*chatIter)->getRemoteAddress(), (*chatIter)->getGameServicePort()); - g->send(cso, true); - } + case constcrc("CustomerServiceServerGameServerServiceAddress") : { + //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(CustomerServiceServerGameServerServiceAddress)\n")); + + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GenericValueTypeMessage > address(ri); + s_customerServiceServerGameServerServiceAddress.first = address.getValue().first; + s_customerServiceServerGameServerServiceAddress.second = address.getValue().second; + + broadcastToGameServers(address); + break; } - } - else if (message.isType("CustomerServiceServerGameServerServiceAddress")) - { - //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(CustomerServiceServerGameServerServiceAddress)\n")); - - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GenericValueTypeMessage > address(ri); - s_customerServiceServerGameServerServiceAddress.first = address.getValue().first; - s_customerServiceServerGameServerServiceAddress.second = address.getValue().second; - - broadcastToGameServers(address); - } - else if(message.isType("TaskConnectionClosed")) - { - // Net::getInstance().connect(Network::Address("127.0.0.1", ConfigCentralServer::getTaskManagerPort()), TaskConnection()); - } - else if(message.isType("TaskConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Task manager connection opened\n")); - } - - else if(message.isType("CentralGameServerDbProcessServerProcessId")) - { - DEBUG_REPORT_LOG(true, ("dbProcess connected\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CentralGameServerDbProcessServerProcessId d(ri); - m_dbProcessServerProcessId = d.getServerProcessId(); - ServerClock::getInstance().setSubtractInterval(d.getSubtractInterval()); - - launchCommoditiesServer(); - launchStartingPlanetServers(); - } - - else if(message.isType("RequestChunkMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestChunkMessage t(ri); - - // Forward this message to the dbProcess - sendToGameServer(m_dbProcessServerProcessId, t, true); - } - else if(message.isType("ChunkObjectListMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ChunkObjectListMessage t(ri); - - DEBUG_FATAL(true,("Got ChunkObjectListMessage. Thought it was deprecated.\n")); - // handleChunkList(t.getProcess(), t.getIds()); - } - else if(message.isType("LocateStructureMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LocateStructureMessage t(ri); - sendToPlanetServer(t.getSceneId(), t, true); - } - else if(message.isType("RequestObjectMessage")) - { - DEBUG_FATAL(true,("Got RequestObjectMessage. Thought this went away.")); - - // Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - // RequestObjectMessage t(ri); - // // tell the authoritative object to create a proxy - // const GameServerConnection *gameServer = getGameServer(t.getProcess()); - // NOT_NULL(gameServer); - // uint32 authId = sendToAuthoritativeServer(t.getId(), - // LoadObjectMessage(t.getId(), t.getProcess(), gameServer->getGameServiceAddress(), gameServer->getGameServicePort(), false), - // true); - // // if we sent the message to the database process, mark it as being - // // authoritative for this object - // if (authId == m_dbProcessServerProcessId) - // { - // addObjectToMap(t.getId(), authId, gameServer->getSceneId(), true); - // m_pendingLoadingObjects[t.getId()] = t.getProcess(); - // } - } - else if(message.isType("CreateNewObjectMessage")) - { - DEBUG_FATAL(true,("Ain't this supposed to be deprecated or something?")); - } - else if(message.isType("SetObjectPositionMessage")) - { - //@todo remove this message from the library - DEBUG_FATAL(true,("Got SetObjectPositionMessage. Thought this went away")); - } - else if(message.isType("FailedToLoadObjectMessage")) - { - //@todo remove this message from the library - DEBUG_FATAL(true,("Received Failed To Load Object Message. Thought it was depricated\n")); - } - else if(message.isType("ReleaseAuthoritativeMessage")) - { - //@todo remove this message from the library - DEBUG_FATAL(true, ("Received ReleaseAuthoritative for. Thought it was deprecated.")); - } - else if(message.isType("ForceUnloadObjectMessage")) - { - //N.B. This message can come from a game server or from the planet server. - DEBUG_WARNING(true, ("Received ForceUnloadObject. Need to implement this\n")); - - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ForceUnloadObjectMessage t(ri); - - //@todo: figure out some way to handle this (such as forwarding to PlanetServers), or remove every case where it's sent - // forceUnload(t.getId(),t.getPermaDelete()); - } - //Character Creation Messages - else if(message.isType("ConnectionCreateCharacter")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ConnectionCreateCharacter c(ri); - - LOG("TraceCharacterCreation", ("%d received ConnectionCreateCharacter", c.getStationId())); - CharacterCreationTracker::getInstance().handleCreateNewCharacter(c); - } - else if(message.isType("GameCreateCharacterFailed")) - { - DEBUG_REPORT_LOG(true, ("Game server advises central that character creation failed\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameCreateCharacterFailed f(ri); - CharacterCreationTracker::getInstance().handleGameCreateCharacterFailed(f.getStationId(), f.getName(), f.getErrorMessage(), f.getOptionalDetailedErrorMessage()); - } - else if(message.isType("DatabaseCreateCharacterSuccess")) - { - DEBUG_REPORT_LOG(true, ("Database Process advises central that character creation succeeded\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - DatabaseCreateCharacterSuccess s(ri); - CharacterCreationTracker::getInstance().handleDatabaseCreateCharacterSuccess(s.getStationId(), s.getCharacterName(), s.getObjectId(), s.getTemplateId(), s.getJedi()); - } - else if(message.isType("LoginCreateCharacterAckMessage")) - { - DEBUG_REPORT_LOG(true, ("Login Server advises central that character creation succeeded\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginCreateCharacterAckMessage s(ri); - CharacterCreationTracker::getInstance().handleLoginCreateCharacterAck(s.getStationId()); - } - else if(message.isType("LoginRestoreCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginRestoreCharacterMessage msg(ri); - - IGNORE_RETURN(sendToArbitraryLoginServer(msg)); - } - else if(message.isType("NewCharacterCreated")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const ncc(ri); - - CentralServer::getInstance().sendToAllConnectionServers(ncc, true); - } - else if(message.isType("DatabaseConsoleReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - IGNORE_RETURN(sendToRandomGameServer(msg)); - } - else if(message.isType("LoginUpgradeAccountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginUpgradeAccountMessage msg(ri); - - if (msg.getIsAck()) - { - MessageToMessage const reply( - MessageToPayload(msg.getReplyToObject(), NetworkId::cms_invalid, msg.getReplyMessage(), msg.getPackedMessageData(), 0, false, MessageToPayload::DT_c,NetworkId::cms_invalid,std::string(), 0), - 0); - sendToAllGameServers (reply,true); + case constcrc("TaskConnectionClosed") : { + // Net::getInstance().connect(Network::Address("127.0.0.1", ConfigCentralServer::getTaskManagerPort()), TaskConnection()); + break; } - else - { + case constcrc("TaskConnectionOpened") : { + DEBUG_REPORT_LOG(true, ("Task manager connection opened\n")); + break; + } + case constcrc("CentralGameServerDbProcessServerProcessId") : { + DEBUG_REPORT_LOG(true, ("dbProcess connected\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CentralGameServerDbProcessServerProcessId d(ri); + m_dbProcessServerProcessId = d.getServerProcessId(); + ServerClock::getInstance().setSubtractInterval(d.getSubtractInterval()); + + launchCommoditiesServer(); + launchStartingPlanetServers(); + break; + } + + case constcrc("RequestChunkMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestChunkMessage t(ri); + + // Forward this message to the dbProcess + sendToGameServer(m_dbProcessServerProcessId, t, true); + break; + } + case constcrc("LocateStructureMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LocateStructureMessage t(ri); + sendToPlanetServer(t.getSceneId(), t, true); + break; + } + case constcrc("ForceUnloadObjectMessage") : { + //N.B. This message can come from a game server or from the planet server. + DEBUG_WARNING(true, ("Received ForceUnloadObject. Need to implement this\n")); + + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ForceUnloadObjectMessage t(ri); + + //@todo: figure out some way to handle this (such as forwarding to PlanetServers), or remove every case where it's sent + //forceUnload(t.getId(),t.getPermaDelete()); + break; + } + //Character Creation Messages + case constcrc("ConnectionCreateCharacter") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ConnectionCreateCharacter c(ri); + + LOG("TraceCharacterCreation", ("%d received ConnectionCreateCharacter", c.getStationId())); + CharacterCreationTracker::getInstance().handleCreateNewCharacter(c); + break; + } + case constcrc("GameCreateCharacterFailed") : { + DEBUG_REPORT_LOG(true, ("Game server advises central that character creation failed\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameCreateCharacterFailed f(ri); + CharacterCreationTracker::getInstance() + .handleGameCreateCharacterFailed(f.getStationId(), f.getName(), f.getErrorMessage(), f + .getOptionalDetailedErrorMessage()); + break; + } + case constcrc("DatabaseCreateCharacterSuccess") : { + DEBUG_REPORT_LOG(true, ("Database Process advises central that character creation succeeded\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + DatabaseCreateCharacterSuccess s(ri); + CharacterCreationTracker::getInstance() + .handleDatabaseCreateCharacterSuccess(s.getStationId(), s.getCharacterName(), s.getObjectId(), s + .getTemplateId(), s.getJedi()); + break; + } + case constcrc("LoginCreateCharacterAckMessage") : { + DEBUG_REPORT_LOG(true, ("Login Server advises central that character creation succeeded\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginCreateCharacterAckMessage s(ri); + CharacterCreationTracker::getInstance().handleLoginCreateCharacterAck(s.getStationId()); + break; + } + case constcrc("LoginRestoreCharacterMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginRestoreCharacterMessage msg(ri); + IGNORE_RETURN(sendToArbitraryLoginServer(msg)); + break; } - } - else if (message.isType("RandomNameRequest")) - { - GameServerConnection * gameServer = getRandomGameServer(); - if(gameServer) - { + case constcrc("NewCharacterCreated") : { Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RandomNameRequest crnr(ri); - gameServer->send(crnr, true); + GenericValueTypeMessage const ncc(ri); + + CentralServer::getInstance().sendToAllConnectionServers(ncc, true); + break; } - } - else if (message.isType("RandomNameResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RandomNameResponse crnr(ri); - ConnectionServerConnection * conn = getConnectionServerForAccount(crnr.getStationId()); - if (conn) - { - conn->send(crnr, true); - } - else - { - DEBUG_REPORT_LOG(true,("Could not send name to client because unable to determine which connection server to use.\n")); - } - } - else if (message.isType("VerifyAndLockNameRequest")) - { - GameServerConnection * gameServer = getRandomGameServer(); - if(gameServer) - { + case constcrc("DatabaseConsoleReplyMessage") : { Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - VerifyAndLockNameRequest valnr(ri); - gameServer->send(valnr, true); + ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + IGNORE_RETURN(sendToRandomGameServer(msg)); + break; } - } - else if (message.isType("VerifyAndLockNameResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - VerifyAndLockNameResponse valnr(ri); - ConnectionServerConnection * conn = getConnectionServerForAccount(valnr.getStationId()); - if (conn) - { - conn->send(valnr, true); - } - else - { - DEBUG_REPORT_LOG(true,("Could not send name lock response to client because unable to determine which connection server to use.\n")); - } - } - else if (message.isType("RequestOIDsMessage")) - { - DEBUG_REPORT_LOG(true,("Got RequestOIDsMessage.\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestOIDsMessage m(ri); + case constcrc("LoginUpgradeAccountMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginUpgradeAccountMessage msg(ri); - if (m.getLogRequest()) - LOG("ObjectIdManager", ("Requesting %lu more object ids for pid %lu", m.getHowMany(), m.getServerId())); - - sendToGameServer(m_dbProcessServerProcessId, m, true); - } - else if (message.isType("AddOIDBlockMessage")) - { - DEBUG_REPORT_LOG(true,("Got AddOIDBlockMessage.\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AddOIDBlockMessage m(ri); - - if (m.getLogRequest()) - LOG("ObjectIdManager", ("Returning object ids (%s - %s) for pid %lu", m.getStart().getValueString().c_str(), m.getEnd().getValueString().c_str(), m.getServerId())); - - sendToGameServer(m.getServerId(), m, true); - } - else if (message.isType("LoggedInMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoggedInMessage m (ri); - DEBUG_REPORT_LOG(true, ("Pending character %lu is logging in or dropping\n", m.getAccountNumber())); - - // Once they're logged in, Central doesn't need to know about them anymore: - removeFromAccountConnectionMap(m.getAccountNumber()); - } - - else if (message.isType("CharacterListMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CharacterListMessage m(ri); - - // Find the client connection and send the character to it. - DEBUG_REPORT_LOG(true,("Got CharacterListMessage for %lu.\n",m.getAccountNumber())); - ConnectionServerConnection *conn = getConnectionServerForAccount(m.getAccountNumber()); - - if (conn) - { - conn->send(m, true); - } - else - { - DEBUG_REPORT_LOG(true,("Warning: received CharacterListMessage for client that is not connected.")); - } - } - else if (message.isType("ValidateCharacterForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateCharacterForLoginMessage m(ri); - - // ask DBProcess to check whether the character is valid - //pendingCharactersLogin[m.getSuid()] = safe_cast(&source); - if (hasDBConnection()) - sendToDBProcess(m, true); - } - else if (message.isType("ValidateCharacterForLoginReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateCharacterForLoginReplyMessage msg(ri); - - ConnectionServerConnection *conn = getConnectionServerForAccount(msg.getSuid()); - if(conn) - conn->send(msg,true); - else - DEBUG_REPORT_LOG(true,("Trying to handle ValidateCharacterForLoginReplyMessage for account %lu, but could not determine which connection server to use.\n",msg.getSuid())); - } - else if (message.isType("EnableCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::string> > msg(ri); - - LOG("CustomerService", ("EnableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - // forward this request to LoginServer - IGNORE_RETURN(sendToArbitraryLoginServer(msg)); - } - else if (message.isType("EnableCharacterReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - GenericValueTypeMessage > reply("DatabaseConsoleReplyMessage", std::make_pair(msg.getValue().first, msg.getValue().second)); - getRandomGameServer()->send(reply, true); - } - else if (message.isType("DisableCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::string> > msg(ri); - - LOG("CustomerService", ("DisableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - // forward this request to LoginServer - IGNORE_RETURN(sendToArbitraryLoginServer(msg)); - } - else if (message.isType("DisableCharacterReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - GenericValueTypeMessage > reply("DatabaseConsoleReplyMessage", std::make_pair(msg.getValue().first, msg.getValue().second)); - getRandomGameServer()->send(reply, true); - } - else if(message.isType("TransferReplyLoginLocationData")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage reply(ri); - // If this request has a CS Tool Id associated with it, it is an admin request for the CSTool, - // and so we should send it directly to the connection server, and not depend on a - // transfer server existing. - - if(reply.getValue().getCSToolId() > 0) - { - GenericValueTypeMessage loginMessage("TransferLoginCharacterToSourceServer", reply.getValue()); - ConnectionServerConnection * conn = getAnyConnectionServer(); - if(conn) - { - conn->send(loginMessage, true); + if (msg.getIsAck()) { + MessageToMessage const reply( + MessageToPayload(msg.getReplyToObject(), NetworkId::cms_invalid, msg.getReplyMessage(), msg + .getPackedMessageData(), 0, false, MessageToPayload::DT_c, NetworkId::cms_invalid, std::string(), 0), + 0); + sendToAllGameServers(reply, true); } - return; + else { + IGNORE_RETURN(sendToArbitraryLoginServer(msg)); + } + break; } - - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyLoginLocationData from database for character %s\n", reply.getValue().getSourceCharacterName().c_str())); - - if(reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) - { - CentralServer::getInstance().sendToTransferServer(reply); + case constcrc("RandomNameRequest") : { + GameServerConnection *gameServer = getRandomGameServer(); + if (gameServer) { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RandomNameRequest crnr(ri); + gameServer->send(crnr, true); + } + break; } - else - { - // send character to ConnectionServer for login to a game server - ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); - if(connectionServer) - { - const GenericValueTypeMessage login("TransferLoginCharacterToSourceServer", reply.getValue()); - connectionServer->send(login, true); - - LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToSourceServer to ConnectionServer : %s", login.getValue().toString().c_str())); - } + case constcrc("RandomNameResponse") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RandomNameResponse crnr(ri); + ConnectionServerConnection *conn = getConnectionServerForAccount(crnr.getStationId()); + if (conn) { + conn->send(crnr, true); + } + else { + DEBUG_REPORT_LOG(true, ("Could not send name to client because unable to determine which connection server to use.\n")); + } + break; } - } - else if (message.isType("CentralPlanetServerConnect")) - { - PlanetServerConnection *g = const_cast(safe_cast(&source)); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CentralPlanetServerConnect msg(ri); - g->setGameServerConnectionData(msg.getConnectionAddress(), msg.getGameServerPort()); - PlanetManager::addServer(msg.getSceneId(), g); + case constcrc("VerifyAndLockNameRequest") : { + GameServerConnection *gameServer = getRandomGameServer(); + if (gameServer) { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + VerifyAndLockNameRequest valnr(ri); + gameServer->send(valnr, true); + } + break; + } + case constcrc("VerifyAndLockNameResponse") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + VerifyAndLockNameResponse valnr(ri); + ConnectionServerConnection *conn = getConnectionServerForAccount(valnr.getStationId()); + if (conn) { + conn->send(valnr, true); + } + else { + DEBUG_REPORT_LOG(true, ("Could not send name lock response to client because unable to determine which connection server to use.\n")); + } + break; + } + case constcrc("RequestOIDsMessage") : { + DEBUG_REPORT_LOG(true, ("Got RequestOIDsMessage.\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestOIDsMessage m(ri); - std::map, time_t> >::iterator f = m_pendingPlanetServers.find(msg.getSceneId()); - if(f != m_pendingPlanetServers.end()) - m_pendingPlanetServers.erase(f); + if (m.getLogRequest()) { + LOG("ObjectIdManager", ("Requesting %lu more object ids for pid %lu", m.getHowMany(), m.getServerId())); + } - IGNORE_RETURN(m_planetServers.insert(std::make_pair(msg.getSceneId(), g))); + sendToGameServer(m_dbProcessServerProcessId, m, true); + break; + } + case constcrc("AddOIDBlockMessage") : { + DEBUG_REPORT_LOG(true, ("Got AddOIDBlockMessage.\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AddOIDBlockMessage m(ri); - if (isPreloadFinished()) - m_timeClusterWentIntoLoadingState = 0; - else if (m_timeClusterWentIntoLoadingState <= 0) - m_timeClusterWentIntoLoadingState = time(0); + if (m.getLogRequest()) { + LOG("ObjectIdManager", ("Returning object ids (%s - %s) for pid %lu", m.getStart().getValueString() + .c_str(), m.getEnd() + .getValueString() + .c_str(), m + .getServerId())); + } - // handle planet transfers and logins for planet server that aren't up yet - std::vector::iterator t; - for(t = m_messagesWaitingForPlanetServer.begin(); t != m_messagesWaitingForPlanetServer.end();) - { - Archive::ReadIterator tri = t->begin(); - const GameNetworkMessage gnm(tri); - tri = t->begin(); - if(gnm.isType("RequestGameServerForLoginMessage")) - { - const RequestGameServerForLoginMessage loginMessage(tri); - if (loginMessage.getScene() == msg.getSceneId()) - { - t = m_messagesWaitingForPlanetServer.erase(t); - handleRequestGameServerForLoginMessage(loginMessage); + sendToGameServer(m.getServerId(), m, true); + break; + } + case constcrc("LoggedInMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoggedInMessage m(ri); + DEBUG_REPORT_LOG(true, ("Pending character %lu is logging in or dropping\n", m.getAccountNumber())); + + // Once they're logged in, Central doesn't need to know about them anymore: + removeFromAccountConnectionMap(m.getAccountNumber()); + break; + } + case constcrc("CharacterListMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CharacterListMessage m(ri); + + // Find the client connection and send the character to it. + DEBUG_REPORT_LOG(true, ("Got CharacterListMessage for %lu.\n", m.getAccountNumber())); + ConnectionServerConnection *conn = getConnectionServerForAccount(m.getAccountNumber()); + + if (conn) { + conn->send(m, true); + } + else { + DEBUG_REPORT_LOG(true, ("Warning: received CharacterListMessage for client that is not connected.")); + } + break; + } + case constcrc("ValidateCharacterForLoginMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateCharacterForLoginMessage m(ri); + + // ask DBProcess to check whether the character is valid + //pendingCharactersLogin[m.getSuid()] = safe_cast(&source); + if (hasDBConnection()) { + sendToDBProcess(m, true); + } + break; + } + case constcrc("ValidateCharacterForLoginReplyMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateCharacterForLoginReplyMessage msg(ri); + + ConnectionServerConnection *conn = getConnectionServerForAccount(msg.getSuid()); + if (conn) { + conn->send(msg, true); + } + else { + DEBUG_REPORT_LOG(true, ("Trying to handle ValidateCharacterForLoginReplyMessage for account %lu, but could not determine which connection server to use.\n", msg + .getSuid())); + } + break; + } + case constcrc("EnableCharacterMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::pair < StationId, NetworkId >, std::string > > msg(ri); + + LOG("CustomerService", ("EnableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg + .getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); + // forward this request to LoginServer + IGNORE_RETURN(sendToArbitraryLoginServer(msg)); + break; + } + case constcrc("EnableCharacterReplyMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + GenericValueTypeMessage > reply("DatabaseConsoleReplyMessage", std::make_pair(msg + .getValue().first, msg.getValue().second)); + getRandomGameServer()->send(reply, true); + break; + } + case constcrc("DisableCharacterMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::pair < StationId, NetworkId >, std::string > > msg(ri); + + LOG("CustomerService", ("DisableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg + .getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); + // forward this request to LoginServer + IGNORE_RETURN(sendToArbitraryLoginServer(msg)); + break; + } + case constcrc("DisableCharacterReplyMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + GenericValueTypeMessage > reply("DatabaseConsoleReplyMessage", std::make_pair(msg + .getValue().first, msg.getValue().second)); + getRandomGameServer()->send(reply, true); + break; + } + case constcrc("TransferReplyLoginLocationData") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage reply(ri); + // If this request has a CS Tool Id associated with it, it is an admin request for the CSTool, + // and so we should send it directly to the connection server, and not depend on a + // transfer server existing. + + if (reply.getValue().getCSToolId() > 0) { + GenericValueTypeMessage loginMessage("TransferLoginCharacterToSourceServer", reply + .getValue()); + ConnectionServerConnection *conn = getAnyConnectionServer(); + if (conn) { + conn->send(loginMessage, true); + } + return; + } + + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyLoginLocationData from database for character %s\n", reply + .getValue().getSourceCharacterName().c_str())); + + if (reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) { + CentralServer::getInstance().sendToTransferServer(reply); + } + else { + // send character to ConnectionServer for login to a game server + ConnectionServerConnection *connectionServer = CentralServer::getInstance().getAnyConnectionServer(); + if (connectionServer) { + const GenericValueTypeMessage login("TransferLoginCharacterToSourceServer", reply + .getValue()); + connectionServer->send(login, true); + + LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToSourceServer to ConnectionServer : %s", login + .getValue().toString().c_str())); } } - else if(gnm.isType("RequestSceneTransfer")) - { - const RequestSceneTransfer sceneMessage(tri); - if (sceneMessage.getSceneName() == msg.getSceneId()) - { - t = m_messagesWaitingForPlanetServer.erase(t); - handleRequestSceneTransfer(sceneMessage); + break; + } + case constcrc("CentralPlanetServerConnect") : { + PlanetServerConnection *g = const_cast(safe_cast < PlanetServerConnection + const + * > (&source)); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CentralPlanetServerConnect msg(ri); + g->setGameServerConnectionData(msg.getConnectionAddress(), msg.getGameServerPort()); + PlanetManager::addServer(msg.getSceneId(), g); + + std::map < std::string, std::pair < std::pair < std::string, std::string >, time_t > > ::iterator + f = m_pendingPlanetServers.find(msg.getSceneId()); + if (f != m_pendingPlanetServers.end()) { + m_pendingPlanetServers.erase(f); + } + + IGNORE_RETURN(m_planetServers.insert(std::make_pair(msg.getSceneId(), g))); + + if (isPreloadFinished()) { + m_timeClusterWentIntoLoadingState = 0; + } + else if (m_timeClusterWentIntoLoadingState <= 0) { + m_timeClusterWentIntoLoadingState = time(0); + } + + // handle planet transfers and logins for planet server that aren't up yet + std::vector::iterator t; + for (t = m_messagesWaitingForPlanetServer.begin(); t != m_messagesWaitingForPlanetServer.end();) { + Archive::ReadIterator tri = t->begin(); + const GameNetworkMessage gnm(tri); + const uint32 mt = gnm.getType(); + + tri = t->begin(); + switch (mt) { + case constcrc("RequestGameServerForLoginMessage") : { + const RequestGameServerForLoginMessage loginMessage(tri); + if (loginMessage.getScene() == msg.getSceneId()) { + t = m_messagesWaitingForPlanetServer.erase(t); + handleRequestGameServerForLoginMessage(loginMessage); + } + break; + } + case constcrc("RequestSceneTransfer") : { + const RequestSceneTransfer sceneMessage(tri); + if (sceneMessage.getSceneName() == msg.getSceneId()) { + t = m_messagesWaitingForPlanetServer.erase(t); + handleRequestSceneTransfer(sceneMessage); + } + break; + } + default : { + t = m_messagesWaitingForPlanetServer.erase(t); + WARNING_STRICT_FATAL(true, ("Unknown message type waiting for planet server")); + break; + } } } - else - { - t = m_messagesWaitingForPlanetServer.erase(t); - WARNING_STRICT_FATAL(true, ("Unknown message type waiting for planet server")); + break; + } + case constcrc("RequestSceneTransfer") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const RequestSceneTransfer msg(ri); + + handleRequestSceneTransfer(msg); + break; + } + case constcrc("SceneTransferMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + SceneTransferMessage msg(ri); + + sendToGameServer(msg.getSourceGameServer(), msg, true); + break; + } + case constcrc("GameServerReadyMessage") : { + GameServerConnection const *g = safe_cast < GameServerConnection const * > (&source); + UniverseManager::getInstance().onGameServerReady(*g); + break; + } + case constcrc("GameServerUniverseLoadedMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GameServerUniverseLoadedMessage msg(ri); + + // forward to the universe game server as ack that + // the game server who sent this message has received + // its UniverseCompleteMessage from the universe game server + if (msg.getSourceOfUniverseDataProcessId() != getDbProcessServerProcessId()) { + sendToGameServer(msg.getSourceOfUniverseDataProcessId(), msg, true); } + + CharacterCreationTracker::getInstance().retryGameServerCreates(); + break; } - } - else if (message.isType("RequestSceneTransfer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const RequestSceneTransfer msg (ri); + case constcrc("MessageToMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + MessageToMessage msg(ri); - handleRequestSceneTransfer(msg); - } - else if (message.isType("SceneTransferMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - SceneTransferMessage msg (ri); + WARNING_STRICT_FATAL(true, ("CentralServer receieved a messageTo. These should not go to Central anymore. Sender was server %u\n", + safe_cast < GameServerConnection const * > (&source)->getProcessId())); + break; + } + case constcrc("MessageToAckMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + MessageToAckMessage msg(ri); - sendToGameServer(msg.getSourceGameServer(), msg, true); - } - else if (message.isType("GameServerReadyMessage")) - { - GameServerConnection const *g = safe_cast(&source); - UniverseManager::getInstance().onGameServerReady(*g); - } - else if (message.isType("GameServerUniverseLoadedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GameServerUniverseLoadedMessage msg(ri); + WARNING_STRICT_FATAL(true, ("CentralServer receieved a MessageToAckMessage. These should not go to Central anymore. Sender was server %u\n", + safe_cast < GameServerConnection const * > (&source)->getProcessId())); + break; + } + case constcrc("ChatServerConnectionOpened") : { + // enumerate servers + ChatServerConnection *chatServer = const_cast(safe_cast < ChatServerConnection + const + * > (&source)); + IGNORE_RETURN(m_chatServerConnections.insert(chatServer)); + const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); + for (ConnectionServerConnectionList::const_iterator ci = m_connectionServerConnections.begin(); + ci != m_connectionServerConnections.end(); ++ci) { + ConnectionServerConnection *c = (*ci); - // forward to the universe game server as ack that - // the game server who sent this message has received - // its UniverseCompleteMessage from the universe game server - if (msg.getSourceOfUniverseDataProcessId() != getDbProcessServerProcessId()) - sendToGameServer(msg.getSourceOfUniverseDataProcessId(), msg, true); - - CharacterCreationTracker::getInstance().retryGameServerCreates(); - } - else if (message.isType("MessageToMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - MessageToMessage msg(ri); - - WARNING_STRICT_FATAL(true,("CentralServer receieved a messageTo. These should not go to Central anymore. Sender was server %u\n", safe_cast(&source)->getProcessId())); - } - else if (message.isType("MessageToAckMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - MessageToAckMessage msg(ri); - - WARNING_STRICT_FATAL(true,("CentralServer receieved a MessageToAckMessage. These should not go to Central anymore. Sender was server %u\n",safe_cast(&source)->getProcessId())); - } - else if(message.isType("ChatServerConnectionOpened")) - { - // enumerate servers - ChatServerConnection *chatServer = const_cast(safe_cast(&source)); - IGNORE_RETURN(m_chatServerConnections.insert(chatServer)); - const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); - for (ConnectionServerConnectionList::const_iterator ci = m_connectionServerConnections.begin(); ci != m_connectionServerConnections.end(); ++ci) - { - ConnectionServerConnection * c = (*ci); - - if ( (c != NULL) - && !c->getChatServiceAddress().empty() - && (c->getChatServicePort() != 0)) - { - EnumerateServers e(true, c->getChatServiceAddress(), c->getChatServicePort(), ct); - chatServer->send(e, true); + if ((c != nullptr) + && !c->getChatServiceAddress().empty() + && (c->getChatServicePort() != 0)) { + EnumerateServers e(true, c->getChatServiceAddress(), c->getChatServicePort(), ct); + chatServer->send(e, true); + } + else { + LOG("ChatServer", ("receiveMessage() ChatServerConnectionOpened - Invalid connection address in m_connectionServerConnections, skipping entry")); + } } - else - { - LOG("ChatServer", ("receiveMessage() ChatServerConnectionOpened - Invalid connection address in m_connectionServerConnections, skipping entry")); + + // Tell the single chat server the address to communicate with the customer service server + + if (!s_customerServiceServerChatServerServiceAddress.first.empty()) { + //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(ChatServerConnectionOpened)\n")); + + const GenericValueTypeMessage > msg("CustomerServiceServerChatServerServiceAddress", std::make_pair(s_customerServiceServerChatServerServiceAddress + .first, s_customerServiceServerChatServerServiceAddress.second)); + + chatServer->send(msg, true); } + break; } + case constcrc("CustomerServiceServerChatServerServiceAddress") : { + //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(CustomerServiceServerChatServerServiceAddress)\n")); - // Tell the single chat server the address to communicate with the customer service server + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GenericValueTypeMessage > address(ri); - if (!s_customerServiceServerChatServerServiceAddress.first.empty()) - { - //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(ChatServerConnectionOpened)\n")); + s_customerServiceServerChatServerServiceAddress.first = address.getValue().first; + s_customerServiceServerChatServerServiceAddress.second = address.getValue().second; - const GenericValueTypeMessage > msg("CustomerServiceServerChatServerServiceAddress", std::make_pair(s_customerServiceServerChatServerServiceAddress.first, s_customerServiceServerChatServerServiceAddress.second)); + // Tell the chat servers the address to communicate with the customer service server - chatServer->send(msg, true); - } - } - else if (message.isType("CustomerServiceServerChatServerServiceAddress")) - { - //DEBUG_REPORT_LOG(true, ("CentralServer::receiveMessage(CustomerServiceServerChatServerServiceAddress)\n")); + std::set::iterator iterChatServerConnections = m_chatServerConnections.begin(); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GenericValueTypeMessage > address(ri); + for (; iterChatServerConnections != m_chatServerConnections.end(); ++iterChatServerConnections) { + ChatServerConnection *connection = (*iterChatServerConnections); - s_customerServiceServerChatServerServiceAddress.first = address.getValue().first; - s_customerServiceServerChatServerServiceAddress.second = address.getValue().second; - - // Tell the chat servers the address to communicate with the customer service server - - std::set::iterator iterChatServerConnections = m_chatServerConnections.begin(); - - for (; iterChatServerConnections != m_chatServerConnections.end(); ++iterChatServerConnections) - { - ChatServerConnection *connection = (*iterChatServerConnections); - - if (connection != NULL) - { - connection->send(address, true); + if (connection != nullptr) { + connection->send(address, true); + } + else { + REPORT_LOG(true, ("Trying to send the customer service server: chat server service address to a nullptr chat server\n")); + } } - else - { - REPORT_LOG(true, ("Trying to send the customer service server: chat server service address to a NULL chat server\n")); + break; + } + case constcrc("CustomerServiceConnectionOpened") : { + CustomerServiceConnection *csServer = const_cast(safe_cast < + CustomerServiceConnection const + * > (&source)); + IGNORE_RETURN(m_csServerConnections.insert(csServer)); + const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); + for (ConnectionServerConnectionList::const_iterator ci = m_connectionServerConnections.begin(); + ci != m_connectionServerConnections.end(); ++ci) { + ConnectionServerConnection *c = (*ci); + + if ((c != nullptr) + && !c->getCustomerServiceAddress().empty() + && (c->getCustomerServicePort() != 0)) { + EnumerateServers e(true, c->getCustomerServiceAddress(), c->getCustomerServicePort(), ct); + csServer->send(e, true); + } + else { + LOG("CustServ", ("receiveMessage() CustomerServiceConnectionOpened - Invalid connection address in m_connectionServerConnections, skipping entry")); + } } + break; } - } - else if (message.isType("CustomerServiceConnectionOpened")) - { - CustomerServiceConnection *csServer = const_cast(safe_cast(&source)); - IGNORE_RETURN(m_csServerConnections.insert(csServer)); - const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); - for (ConnectionServerConnectionList::const_iterator ci = m_connectionServerConnections.begin(); ci != m_connectionServerConnections.end(); ++ci) - { - ConnectionServerConnection * c = (*ci); + case constcrc("ChatServerConnectionClosed") : { + ChatServerConnection *chatServer = const_cast(safe_cast < ChatServerConnection + const + * > (&source)); + IGNORE_RETURN(m_chatServerConnections.erase(chatServer)); - if ( (c != NULL) - && !c->getCustomerServiceAddress().empty() - && (c->getCustomerServicePort() != 0)) - { - EnumerateServers e(true, c->getCustomerServiceAddress(), c->getCustomerServicePort(), ct); - csServer->send(e, true); + // spawn a new chat server! + std::string options = "-s ChatServer centralServerAddress="; + if (CentralServer::getInstance().getChatService()) { + options += CentralServer::getInstance().getChatService()->getBindAddress(); } - else - { - LOG("CustServ", ("receiveMessage() CustomerServiceConnectionOpened - Invalid connection address in m_connectionServerConnections, skipping entry")); + else { + options += NetworkHandler::getHostName(); } - } - } - else if(message.isType("ChatServerConnectionClosed")) - { - ChatServerConnection *chatServer = const_cast(safe_cast(&source)); - IGNORE_RETURN(m_chatServerConnections.erase(chatServer)); - // spawn a new chat server! - std::string options = "-s ChatServer centralServerAddress="; - if(CentralServer::getInstance().getChatService()) - { - options += CentralServer::getInstance().getChatService()->getBindAddress(); - } - else - { - options += NetworkHandler::getHostName(); - } + options += " clusterName="; + options += ConfigCentralServer::getClusterName(); + TaskSpawnProcess pc(ConfigCentralServer::getChatServerHost(), "ChatServer", options, ConfigCentralServer::getChatServerRestartDelayTimeSeconds()); + CentralServer::getInstance().sendTaskMessage(pc); - options += " clusterName="; - options += ConfigCentralServer::getClusterName(); - TaskSpawnProcess pc(ConfigCentralServer::getChatServerHost(), "ChatServer", options, ConfigCentralServer::getChatServerRestartDelayTimeSeconds()); - CentralServer::getInstance().sendTaskMessage(pc); - - } - else if (message.isType("CustomerServiceConnectionClosed")) - { - CustomerServiceConnection *csServer = const_cast(safe_cast(&source)); - IGNORE_RETURN(m_csServerConnections.erase(csServer)); - - // spawn a new cs server! - std::string options = "-s CustomerServiceServer centralServerAddress="; - if(CentralServer::getInstance().getCustomerService()) - { - options += CentralServer::getInstance().getCustomerService()->getBindAddress(); - } - else - { - options += NetworkHandler::getHostName(); + break; } + case constcrc("CustomerServiceConnectionClosed") : { + CustomerServiceConnection *csServer = const_cast(safe_cast < + CustomerServiceConnection const + * > (&source)); + IGNORE_RETURN(m_csServerConnections.erase(csServer)); - options += " clusterName="; - options += ConfigCentralServer::getClusterName(); - TaskSpawnProcess pc("any", "CustomerServiceServer", options); - CentralServer::getInstance().sendTaskMessage(pc); - } - else if(message.isType("ChatServerOnline")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ChatServerOnline cso (ri); - ChatServerConnection *csc = const_cast(safe_cast(&source)); - csc->setGameServicePort(cso.getPort()); - SceneGameMap::const_iterator iter; - for(iter = m_gameServers.begin(); iter != m_gameServers.end(); ++iter) - { - GameServerConnection * conn = (*iter).second; - conn->send(cso, true); - } - - } - else if (message.isType("RequestGameServerForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const RequestGameServerForLoginMessage msg(ri); - - time_t const timeNow = ::time(NULL); - PlayerSceneMapType::const_iterator i = m_playerSceneMap.find(msg.getCharacterId()); - if ((i != m_playerSceneMap.end()) && (i->second.second > timeNow)) - { - ServerConnection * c = const_cast(safe_cast(&source)); - GenericValueTypeMessage > const loginDeniedRecentCTS("LoginDeniedRecentCTS", std::make_pair(msg.getCharacterId(), msg.getStationId())); - c->send(loginDeniedRecentCTS, true); - } - else - { - std::map >::const_iterator const iterFind = s_pendingRenameCharacter.find(msg.getCharacterId()); - if ((iterFind != s_pendingRenameCharacter.end()) && (iterFind->second.first > timeNow)) - { - ServerConnection * c = const_cast(safe_cast(&source)); - GenericValueTypeMessage > const loginDeniedPendingPlayerRenameRequest("LoginDeniedPendingPlayerRenameRequest", std::make_pair(msg.getCharacterId(), msg.getStationId())); - c->send(loginDeniedPendingPlayerRenameRequest, true); + // spawn a new cs server! + std::string options = "-s CustomerServiceServer centralServerAddress="; + if (CentralServer::getInstance().getCustomerService()) { + options += CentralServer::getInstance().getCustomerService()->getBindAddress(); } - else - { - handleRequestGameServerForLoginMessage(msg); + else { + options += NetworkHandler::getHostName(); } + + options += " clusterName="; + options += ConfigCentralServer::getClusterName(); + TaskSpawnProcess pc("any", "CustomerServiceServer", options); + CentralServer::getInstance().sendTaskMessage(pc); + break; } - } - else if (message.isType("GameServerForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameServerForLoginMessage msg(ri); - - handleGameServerForLoginMessage(msg); - } - - - - else if (message.isType("ExchangeListCreditsMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ExchangeListCreditsMessage msg(ri); - - handleExchangeListCreditsMessage(msg); - } - - - - else if (message.isType("PlanetLoadCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PlanetLoadCharacterMessage msg(ri); - - // let all the game servers know we are about to load a character from the DB - GenericValueTypeMessage > const aboutToLoadCharacterFromDB("AboutToLoadCharacterFromDB", std::make_pair(msg.getCharacterId(), msg.getGameServerId())); - sendToAllGameServersExceptDBProcess(aboutToLoadCharacterFromDB, true); - - sendToDBProcess(msg,true); - } - else if (message.isType("ConnSrvDropDupeConns")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - // A ConnectionServer has received and validated a new connection from the client - - // request that all other ConnectionServers drop any existing connection(s) for the account - std::string galaxyConnectionInfo = "("; - galaxyConnectionInfo += ConfigCentralServer::getClusterName(); - - if (!msg.getValue().second.empty()) - { - galaxyConnectionInfo += ", "; - galaxyConnectionInfo += msg.getValue().second; - } - - galaxyConnectionInfo += ")"; - - GenericValueTypeMessage > const dropDuplicateConnections("CntrlSrvDropDupeConns", std::make_pair(msg.getValue().first, galaxyConnectionInfo)); - sendToAllConnectionServers(dropDuplicateConnections, true, dynamic_cast(&source)); - - // request (via LoginServer) that all ConnectionServers on all other galaxies drop any existing connection(s) for the account - if (ConfigCentralServer::getDisconnectDuplicateConnectionsOnOtherGalaxies()) - IGNORE_RETURN(sendToArbitraryLoginServer(dropDuplicateConnections)); - } - else if (message.isType("CntrlSrvDropDupeConns")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - // request that all ConnectionServers drop any existing connection(s) for the account - sendToAllConnectionServers(msg, true); - } - else if (message.isType("PlayerDroppedFromGameServerCrash")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const m(ri); - - std::set::const_iterator const end = m.getValue().end(); - for (std::set::const_iterator iter = m.getValue().begin(); iter != end; ++iter) - { - IGNORE_RETURN(m_playerSceneMap.erase(*iter)); - LOG("TRACE_LOGIN", ("Forgetting sceneId (because of game server crash) for character (%s) -- will query the database on next login", iter->getValueString().c_str())); - } - } - else if (message.isType("ServerDeleteCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginServerConnection const *l = safe_cast(&source); - ServerDeleteCharacterMessage msg(ri); - msg.setLoginServerId(l->getProcessId()); - - if (hasDBConnection()) - { - LOG("CustomerService", ("Player:deleted character %s for stationId %u", msg.getCharacterId().getValueString().c_str(), msg.getStationId())); - sendToDBProcess(msg,true); - - // let the game servers know that the character is being deleted - GenericValueTypeMessage const msg2("DeleteCharacterNotificationMessage", msg.getCharacterId()); - IGNORE_RETURN(sendToRandomGameServer(msg2)); - } - } - else if (message.isType("UpdatePlayerCountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UpdatePlayerCountMessage msg(ri); - - ConnectionServerConnection * csc = const_cast(dynamic_cast(&source)); - if (csc) - { - // Update our stored values for the connection server - csc->setPlayerCount(msg.getCount()); - csc->setFreeTrialCount(msg.getFreeTrialCount()); - csc->setEmptySceneCount(msg.getEmptySceneCount()); - csc->setTutorialSceneCount(msg.getTutorialSceneCount()); - csc->setFalconSceneCount(msg.getFalconSceneCount()); - - // Update the login server with the new values - UpdateLoginConnectionServerStatus ulc(csc->getId(), csc->getClientServicePortPublic(), csc->getClientServicePortPrivate(), msg.getCount()); - sendToAllLoginServers(ulc); - - // Update the login servers with new population values - sendPopulationUpdateToLoginServer(); - } - else - { - WARNING_STRICT_FATAL(true,("Got UpdatePlayerCountMessage from something that wasn't a ConnectionServer.\n")); - } - } - else if (message.isType("ValidateAccountMessage")) - { - DEBUG_REPORT_LOG(true,("ValidateAccountMessage\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateAccountMessage msg(ri); - - // Store the connection information for the account - addToAccountConnectionMap(msg.getStationId(), const_cast(dynamic_cast(&source)), msg.getSubscriptionBits()); - - // Pass the validation to a LoginServer - IGNORE_RETURN(sendToArbitraryLoginServer(msg)); - } - else if (message.isType("ValidateAccountReplyMessage")) - { - DEBUG_REPORT_LOG(true,("ValidateAccountReplyMessage\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateAccountReplyMessage msg(ri); - - ConnectionServerConnection *conn=getConnectionServerForAccount(msg.getStationId()); - if (conn) - { - conn->send(msg,true); - } - } - else if (message.isType("PreloadRequestCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PreloadRequestCompleteMessage msg(ri); - - sendToDBProcess(msg,true); - } - else if (message.isType("ReconnectToTransferServer")) - { - if(ConfigCentralServer::getTransferServerPort()) - { - if(! getInstance().m_transferServerConnection) - { - getInstance().m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); - s_retryTransferServerConnection = true; + case constcrc("ChatServerOnline") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ChatServerOnline cso(ri); + ChatServerConnection *csc = const_cast(safe_cast < ChatServerConnection const * > + (&source)); + csc->setGameServicePort(cso.getPort()); + SceneGameMap::const_iterator iter; + for (iter = m_gameServers.begin(); iter != m_gameServers.end(); ++iter) { + GameServerConnection *conn = (*iter).second; + conn->send(cso, true); } + + break; } - } - else if (message.isType("ReconnectToStationPlayersCollector")) - { - if(ConfigCentralServer::getStationPlayersCollectorPort()) - { - if(! getInstance().m_stationPlayersCollectorConnection) - { - getInstance().m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); - s_retryStationPlayersCollectorConnection = true; + case constcrc("RequestGameServerForLoginMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const RequestGameServerForLoginMessage msg(ri); + + time_t const timeNow = ::time(nullptr); + PlayerSceneMapType::const_iterator i = m_playerSceneMap.find(msg.getCharacterId()); + if ((i != m_playerSceneMap.end()) && (i->second.second > timeNow)) { + ServerConnection * c = const_cast(safe_cast < ServerConnection const * > (&source)); + GenericValueTypeMessage > const loginDeniedRecentCTS("LoginDeniedRecentCTS", std::make_pair(msg + .getCharacterId(), msg.getStationId())); + c->send(loginDeniedRecentCTS, true); } + else { + std::map < NetworkId, std::pair < time_t, int > > ::const_iterator + const iterFind = s_pendingRenameCharacter.find(msg.getCharacterId()); + if ((iterFind != s_pendingRenameCharacter.end()) && (iterFind->second.first > timeNow)) { + ServerConnection * c = const_cast(safe_cast < ServerConnection const * > + (&source)); + GenericValueTypeMessage > const loginDeniedPendingPlayerRenameRequest("LoginDeniedPendingPlayerRenameRequest", std::make_pair(msg + .getCharacterId(), msg.getStationId())); + c->send(loginDeniedPendingPlayerRenameRequest, true); + } + else { + handleRequestGameServerForLoginMessage(msg); + } + } + break; } - } - else if (message.isType("PreloadFinishedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PreloadFinishedMessage msg(ri); + case constcrc("GameServerForLoginMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameServerForLoginMessage msg(ri); - const PlanetServerConnection *conn=dynamic_cast(&source); - WARNING_STRICT_FATAL(!conn,("Programmer bug: got PreloadFinishedMessaage from something that wasn't a PlanetServer.\n")); - if (conn) - { - if (msg.getFinished()) - { - IGNORE_RETURN(m_planetsWaitingForPreload.erase(conn->getSceneId())); - if (isPreloadFinished()) - { - m_timeClusterWentIntoLoadingState = 0; + handleGameServerForLoginMessage(msg); + break; + } - DEBUG_REPORT_LOG(true,("Preload finished on all planets.\n")); - // record how long it took the cluster to come up - if (m_clusterStartupTime == -1) - { - m_clusterStartupTime = static_cast(time(0) - m_timeClusterStarted) / 60; + case constcrc("ExchangeListCreditsMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ExchangeListCreditsMessage msg(ri); - // let all the game servers know that the cluster has completed its initial startup - GenericValueTypeMessage clusterStartComplete("ClusterStartComplete", true); - sendToAllGameServersExceptDBProcess(clusterStartComplete, true); + handleExchangeListCreditsMessage(msg); + break; + } + + + case constcrc("PlanetLoadCharacterMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PlanetLoadCharacterMessage msg(ri); + + // let all the game servers know we are about to load a character from the DB + GenericValueTypeMessage > const aboutToLoadCharacterFromDB("AboutToLoadCharacterFromDB", std::make_pair(msg + .getCharacterId(), msg.getGameServerId())); + sendToAllGameServersExceptDBProcess(aboutToLoadCharacterFromDB, true); + + sendToDBProcess(msg, true); + break; + } + case constcrc("ConnSrvDropDupeConns") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + // A ConnectionServer has received and validated a new connection from the client + + // request that all other ConnectionServers drop any existing connection(s) for the account + std::string galaxyConnectionInfo = "("; + galaxyConnectionInfo += ConfigCentralServer::getClusterName(); + + if (!msg.getValue().second.empty()) { + galaxyConnectionInfo += ", "; + galaxyConnectionInfo += msg.getValue().second; + } + + galaxyConnectionInfo += ")"; + + GenericValueTypeMessage > const dropDuplicateConnections("CntrlSrvDropDupeConns", std::make_pair(msg + .getValue().first, galaxyConnectionInfo)); + sendToAllConnectionServers(dropDuplicateConnections, true, dynamic_cast(&source)); + + // request (via LoginServer) that all ConnectionServers on all other galaxies drop any existing connection(s) for the account + if (ConfigCentralServer::getDisconnectDuplicateConnectionsOnOtherGalaxies()) { + IGNORE_RETURN(sendToArbitraryLoginServer(dropDuplicateConnections)); + } + break; + } + case constcrc("CntrlSrvDropDupeConns") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + // request that all ConnectionServers drop any existing connection(s) for the account + sendToAllConnectionServers(msg, true); + break; + } + case constcrc("PlayerDroppedFromGameServerCrash") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const m(ri); + + std::set::const_iterator const end = m.getValue().end(); + for (std::set::const_iterator iter = m.getValue().begin(); iter != end; ++iter) { + IGNORE_RETURN(m_playerSceneMap.erase(*iter)); + LOG("TRACE_LOGIN", ("Forgetting sceneId (because of game server crash) for character (%s) -- will query the database on next login", iter + ->getValueString().c_str())); + } + break; + } + case constcrc("ServerDeleteCharacterMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginServerConnection const *l = safe_cast < LoginServerConnection const * > (&source); + ServerDeleteCharacterMessage msg(ri); + msg.setLoginServerId(l->getProcessId()); + + if (hasDBConnection()) { + LOG("CustomerService", ("Player:deleted character %s for stationId %u", msg.getCharacterId() + .getValueString() + .c_str(), msg + .getStationId())); + sendToDBProcess(msg, true); + + // let the game servers know that the character is being deleted + GenericValueTypeMessage const msg2("DeleteCharacterNotificationMessage", msg + .getCharacterId()); + IGNORE_RETURN(sendToRandomGameServer(msg2)); + } + break; + } + case constcrc("UpdatePlayerCountMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UpdatePlayerCountMessage msg(ri); + + ConnectionServerConnection *csc = const_cast(dynamic_cast(&source)); + if (csc) { + // Update our stored values for the connection server + csc->setPlayerCount(msg.getCount()); + csc->setFreeTrialCount(msg.getFreeTrialCount()); + csc->setEmptySceneCount(msg.getEmptySceneCount()); + csc->setTutorialSceneCount(msg.getTutorialSceneCount()); + csc->setFalconSceneCount(msg.getFalconSceneCount()); + + // Update the login server with the new values + UpdateLoginConnectionServerStatus ulc(csc->getId(), csc->getClientServicePortPublic(), csc + ->getClientServicePortPrivate(), msg.getCount()); + sendToAllLoginServers(ulc); + + // Update the login servers with new population values + sendPopulationUpdateToLoginServer(); + } + else { + WARNING_STRICT_FATAL(true, ("Got UpdatePlayerCountMessage from something that wasn't a ConnectionServer.\n")); + } + break; + } + case constcrc("ValidateAccountMessage") : { + DEBUG_REPORT_LOG(true, ("ValidateAccountMessage\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateAccountMessage msg(ri); + + // Store the connection information for the account + addToAccountConnectionMap(msg + .getStationId(), const_cast(dynamic_cast(&source)), msg + .getSubscriptionBits()); + + // Pass the validation to a LoginServer + IGNORE_RETURN(sendToArbitraryLoginServer(msg)); + break; + } + case constcrc("ValidateAccountReplyMessage") : { + DEBUG_REPORT_LOG(true, ("ValidateAccountReplyMessage\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateAccountReplyMessage msg(ri); + + ConnectionServerConnection *conn = getConnectionServerForAccount(msg.getStationId()); + if (conn) { + conn->send(msg, true); + } + break; + } + case constcrc("PreloadRequestCompleteMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PreloadRequestCompleteMessage msg(ri); + + sendToDBProcess(msg, true); + break; + } + case constcrc("ReconnectToTransferServer") : { + if (ConfigCentralServer::getTransferServerPort()) { + if (!getInstance().m_transferServerConnection) { + getInstance() + .m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); + s_retryTransferServerConnection = true; + } + } + break; + } + case constcrc("ReconnectToStationPlayersCollector") : { + if (ConfigCentralServer::getStationPlayersCollectorPort()) { + if (!getInstance().m_stationPlayersCollectorConnection) { + getInstance() + .m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); + s_retryStationPlayersCollectorConnection = true; + } + } + break; + } + case constcrc("PreloadFinishedMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PreloadFinishedMessage msg(ri); + + const PlanetServerConnection *conn = dynamic_cast(&source); + WARNING_STRICT_FATAL(!conn, ("Programmer bug: got PreloadFinishedMessaage from something that wasn't a PlanetServer.\n")); + if (conn) { + if (msg.getFinished()) { + IGNORE_RETURN(m_planetsWaitingForPreload.erase(conn->getSceneId())); + if (isPreloadFinished()) { + m_timeClusterWentIntoLoadingState = 0; + + DEBUG_REPORT_LOG(true, ("Preload finished on all planets.\n")); + + // record how long it took the cluster to come up + if (m_clusterStartupTime == -1) { + m_clusterStartupTime = static_cast(time(0) - m_timeClusterStarted) / 60; + + // let all the game servers know that the cluster has completed its initial startup + GenericValueTypeMessage clusterStartComplete("ClusterStartComplete", true); + sendToAllGameServersExceptDBProcess(clusterStartComplete, true); + } + else { + // let all the game servers know that the cluster has recovered from a crash + GenericValueTypeMessage clusterStartComplete("ClusterStartComplete", false); + sendToAllGameServersExceptDBProcess(clusterStartComplete, true); + } + + sendToAllLoginServers(msg); + sendTaskMessage(msg); + m_lastLoadingStateTime = time(0); + // connect to the character transfer server + if (ConfigCentralServer::getTransferServerPort()) { + if (!getInstance().m_transferServerConnection) { + getInstance() + .m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); + s_retryTransferServerConnection = true; + } + } + + // connect to the station players collector + if (ConfigCentralServer::getStationPlayersCollectorPort()) { + if (!getInstance().m_stationPlayersCollectorConnection) { + getInstance() + .m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); + s_retryStationPlayersCollectorConnection = true; + } + } } - else - { - // let all the game servers know that the cluster has recovered from a crash - GenericValueTypeMessage clusterStartComplete("ClusterStartComplete", false); - sendToAllGameServersExceptDBProcess(clusterStartComplete, true); + else if (m_timeClusterWentIntoLoadingState <= 0) { + m_timeClusterWentIntoLoadingState = time(0); } + } + else { + if (getInstance().m_transferServerConnection != nullptr) { + getInstance().m_transferServerConnection->disconnect(); + getInstance().m_transferServerConnection = 0; + s_retryTransferServerConnection = false; + } + + if (getInstance().m_stationPlayersCollectorConnection != nullptr) { + getInstance().m_stationPlayersCollectorConnection->disconnect(); + getInstance().m_stationPlayersCollectorConnection = 0; + s_retryStationPlayersCollectorConnection = false; + } + + + IGNORE_RETURN(m_planetsWaitingForPreload.insert(conn->getSceneId())); + + if (isPreloadFinished()) { + m_timeClusterWentIntoLoadingState = 0; + } + else if (m_timeClusterWentIntoLoadingState <= 0) { + m_timeClusterWentIntoLoadingState = time(0); + } + sendToAllLoginServers(msg); sendTaskMessage(msg); - m_lastLoadingStateTime=time(0); - // connect to the character transfer server - if(ConfigCentralServer::getTransferServerPort()) - { - if(! getInstance().m_transferServerConnection) - { - getInstance().m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); - s_retryTransferServerConnection = true; - } - } - - // connect to the station players collector - if(ConfigCentralServer::getStationPlayersCollectorPort()) - { - if(! getInstance().m_stationPlayersCollectorConnection) - { - getInstance().m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); - s_retryStationPlayersCollectorConnection = true; - } - } - } - else if (m_timeClusterWentIntoLoadingState <= 0) - { - m_timeClusterWentIntoLoadingState = time(0); } } - else - { - if(getInstance().m_transferServerConnection != NULL) - { - getInstance().m_transferServerConnection->disconnect(); - getInstance().m_transferServerConnection = 0; - s_retryTransferServerConnection = false; + break; + } + case constcrc("RenameCharacterMessageEx") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RenameCharacterMessageEx msg(ri); + + IGNORE_RETURN(sendToArbitraryLoginServer(RenameCharacterMessage(msg.getCharacterId(), msg.getNewName(), msg + .getRequestedBy()))); + + // if the player requested the rename, also rename the chat avatar, so mail, friends list, and ignore list will migrate + if ((msg.getRenameCharacterMessageSource() == RenameCharacterMessageEx::RCMS_player_request) && + !msg.getLastNameChangeOnly() && + !ConfigFile::getKeyBool("CharacterRename", "disableRenameChatAvatar", false)) { + broadcastToChatServers(msg); + } + break; + } + case constcrc("PlayerRenameRequestSubmitted") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < unsigned + int, std::pair < NetworkId, std::pair < std::string, bool > > > > + const msg(ri); + + GenericValueTypeMessage kick("TransferKickConnectedClients", msg.getValue().first); + CentralServer::getInstance().sendToAllLoginServers(kick); + CentralServer::getInstance().sendToAllConnectionServers(kick, true); + + // update the list of pending rename requests, to prevent a character with a pending rename request from logging in + std::map < NetworkId, std::pair < time_t, int > > ::iterator + const iterFind = s_pendingRenameCharacter.find(msg.getValue().second.first); + if (iterFind != s_pendingRenameCharacter.end()) { + ++(iterFind->second.second); + iterFind->second.first = ::time(nullptr) + 3600; // 1 hour timeout + } + else { + s_pendingRenameCharacter + .insert(std::make_pair(msg.getValue().second.first, std::make_pair((::time(nullptr) + + 3600), 1))); // 1 hour timeout + } + + // tell the chat server to destroy any avatar with the new name, but only if the first name changed + if (!msg.getValue().second.second.second) { + GenericValueTypeMessage const chatDestroyAvatar("ChatDestroyAvatar", msg.getValue().second + .second.first); + broadcastToChatServers(chatDestroyAvatar); + } + break; + } + case constcrc("PlayerRenameRequestCompleted") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + // update the list of pending rename requests, to prevent a character with a pending rename request from logging in + std::map < NetworkId, std::pair < time_t, int > > ::iterator + const iterFind = s_pendingRenameCharacter.find(msg.getValue().second); + if (iterFind != s_pendingRenameCharacter.end()) { + if (iterFind->second.second <= 1) { + s_pendingRenameCharacter.erase(iterFind); } - - if(getInstance().m_stationPlayersCollectorConnection != NULL) - { - getInstance().m_stationPlayersCollectorConnection->disconnect(); - getInstance().m_stationPlayersCollectorConnection = 0; - s_retryStationPlayersCollectorConnection = false; - } - - - IGNORE_RETURN(m_planetsWaitingForPreload.insert(conn->getSceneId())); - - if (isPreloadFinished()) - m_timeClusterWentIntoLoadingState = 0; - else if (m_timeClusterWentIntoLoadingState <= 0) - m_timeClusterWentIntoLoadingState = time(0); - - - sendToAllLoginServers(msg); - sendTaskMessage(msg); - } - } - } - else if (message.isType("RenameCharacterMessageEx")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RenameCharacterMessageEx msg(ri); - - IGNORE_RETURN(sendToArbitraryLoginServer(RenameCharacterMessage(msg.getCharacterId(), msg.getNewName(), msg.getRequestedBy()))); - - // if the player requested the rename, also rename the chat avatar, so mail, friends list, and ignore list will migrate - if ((msg.getRenameCharacterMessageSource() == RenameCharacterMessageEx::RCMS_player_request) && !msg.getLastNameChangeOnly() && !ConfigFile::getKeyBool("CharacterRename", "disableRenameChatAvatar", false)) - { - broadcastToChatServers(msg); - } - } - else if (message.isType("PlayerRenameRequestSubmitted")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > > > const msg(ri); - - GenericValueTypeMessage kick("TransferKickConnectedClients", msg.getValue().first); - CentralServer::getInstance().sendToAllLoginServers(kick); - CentralServer::getInstance().sendToAllConnectionServers(kick, true); - - // update the list of pending rename requests, to prevent a character with a pending rename request from logging in - std::map >::iterator const iterFind = s_pendingRenameCharacter.find(msg.getValue().second.first); - if (iterFind != s_pendingRenameCharacter.end()) - { - ++(iterFind->second.second); - iterFind->second.first = ::time(NULL) + 3600; // 1 hour timeout - } - else - { - s_pendingRenameCharacter.insert(std::make_pair(msg.getValue().second.first, std::make_pair((::time(NULL) + 3600), 1))); // 1 hour timeout - } - - // tell the chat server to destroy any avatar with the new name, but only if the first name changed - if (!msg.getValue().second.second.second) - { - GenericValueTypeMessage const chatDestroyAvatar("ChatDestroyAvatar", msg.getValue().second.second.first); - broadcastToChatServers(chatDestroyAvatar); - } - } - else if (message.isType("PlayerRenameRequestCompleted")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - // update the list of pending rename requests, to prevent a character with a pending rename request from logging in - std::map >::iterator const iterFind = s_pendingRenameCharacter.find(msg.getValue().second); - if (iterFind != s_pendingRenameCharacter.end()) - { - if (iterFind->second.second <= 1) - s_pendingRenameCharacter.erase(iterFind); - else - --(iterFind->second.second); - } - } - else if(message.isType("SetConnectionServerPublic")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - SetConnectionServerPublic msg(ri); - if(msg.getIsPublic()) - gs_connectionServersPublic = true; - else - gs_connectionServersPublic = false; - - sendToAllConnectionServers(msg, true); - } - else if(message.isType("ProfilerOperationMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ProfilerOperationMessage msg(ri); - sendToAllGameServers(msg, true); - sendToAllPlanetServers(msg, true); - sendToAllConnectionServers(msg, true); - } - else if (message.isType("PopulationListMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PopulationListMessage msg(ri); - sendToAllGameServers(msg, true); - } - else if (message.isType("CentralPingMessage")) - { - GameServerConnection const *g = safe_cast(&source); - NOT_NULL(g); - LOG("CentralServerPings",("Got reply from %lu",g->getProcessId())); - IGNORE_RETURN(m_serverPings.erase(g->getProcessId())); - } - else if (message.isType("DatabaseBackloggedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage dbbacklog(ri); - - m_databaseBacklogged = dbbacklog.getValue(); - bool const preloadFinished = isPreloadFinished(); - - if (preloadFinished) - m_timeClusterWentIntoLoadingState = 0; - else if (m_timeClusterWentIntoLoadingState <= 0) - m_timeClusterWentIntoLoadingState = time(0); - - PreloadFinishedMessage msg(preloadFinished); - sendToAllLoginServers(msg); - sendTaskMessage(msg); - } - - else if (message.isType("DatabaseSaveStart")) - { - LOG("CentralServer",("Received DatabaseSaveStart network message.")); - if( m_shutdownPhase == 4 ) - { - LOG("CentralServerShutdown",("Shutdown Phase %d: Setting indicator for receipt of DatabaseSaveStart.", m_shutdownPhase)); - m_shutdownHaveDatabaseSaveStart = true; - checkShutdownProcess(); - } - else if( m_shutdownPhase == 5 && m_shutdownHaveDatabaseSaveStart) - { - LOG("CentralServerShutdown",("Shutdown Phase %d: Setting indicator that final database save cycle is complete.", m_shutdownPhase)); - m_shutdownHaveDatabaseComplete = true; - checkShutdownProcess(); - } - } - else if (message.isType("DatabaseSaveComplete")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - LOG("CentralServer",("Received DatabaseSaveComplete network message.")); - - // tell all the Planet Servers that the save finished - sendToAllPlanetServers(msg,true); - - // don't want to indicate this yet until we are at the beginning of a full cycle - if( m_shutdownPhase == 5 && m_shutdownHaveDatabaseSaveStart) - { - LOG("CentralServerShutdown",("Shutdown Phase %d: Setting indicator that final database save cycle is complete.", m_shutdownPhase)); - m_shutdownHaveDatabaseComplete = true; - checkShutdownProcess(); - } - } - else if (message.isType("PlanetRequestSave")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameNetworkMessage msg(ri); - - sendToDBProcess(msg,true); - } - else if (message.isType("ShutdownCluster")) - { - LOG("CentralServerShutdown",("Received ShutdownCluster network message.")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ShutdownCluster m(ri); - startShutdownProcess(m.getTimeToShutdown(), m.getMaxTime(), m.getSystemMessage()); - } - else if (message.isType("AbortShutdown")) - { - LOG("CentralServerShutdown",("Received AbortShutdown network message.")); - abortShutdownProcess(); - } - - - else if (message.isType("SetSceneForPlayer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > > ssfp(ri); - - if (ssfp.getValue().second.first.empty()) - { - static const std::string loginTrace("TRACE_LOGIN"); - - IGNORE_RETURN(m_playerSceneMap.erase(ssfp.getValue().first)); - LOG(loginTrace, ("Forgetting sceneId for character (%s) -- will query the database on next login", ssfp.getValue().first.getValueString().c_str())); - } - else - { - PlayerSceneMapType::iterator i = m_playerSceneMap.find(ssfp.getValue().first); - if (i != m_playerSceneMap.end()) - { - i->second.first = ssfp.getValue().second.first; - if (ssfp.getValue().second.second) - i->second.second = ::time(NULL) + static_cast(ConfigCentralServer::getCtsDenyLoginThresholdSeconds()); - } - else - { - m_playerSceneMap[ssfp.getValue().first]=std::make_pair(ssfp.getValue().second.first, (ssfp.getValue().second.second ? (::time(NULL) + static_cast(ConfigCentralServer::getCtsDenyLoginThresholdSeconds())) : 0)); - } - } - } - - else if (message.isType("TaskProcessDiedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - TaskProcessDiedMessage died(ri); - LOG("TaskProcessDied", ("received TaskProcessDied for %s:%i", died.getProcessName().c_str(), died.getProcessId()));; - if(died.getProcessName().find("SwgGameServer") != std::string::npos) - { - LOG("TaskProcessDied", ("Dead process %i is a game server", died.getProcessId())); - // extract sceneId - size_t pos = died.getProcessName().find("sceneID="); - if(pos != std::string::npos) - { - pos += std::string("sceneID=").length(); - size_t end = died.getProcessName().find_first_of(' ', pos); - if(end != std::string::npos) - { - std::string scene = died.getProcessName().substr(pos, end - pos); - LOG("TaskProcessDied", ("Dead game server process %i was running sceneID %s, advising planet server", died.getProcessId(), scene.c_str())); - std::map::iterator f = m_planetServers.find(scene); - if(f != m_planetServers.end()) - { - f->second->send(died, true); - } + else { + --(iterFind->second.second); } } + break; } - } - else if (message.isType("SystemTimeMismatchNotification")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - - m_lastTimeSystemTimeMismatchNotification = time(0); - m_lastTimeSystemTimeMismatchNotificationDescription = msg.getValue(); - } - else if (message.isType("DisconnectedTaskManagerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - - m_disconnectedTaskManagerList = msg.getValue(); - } - else if(message.isType("TransferServerConnectionClosed")) - { - // connect to the character transfer server - if(ConfigCentralServer::getTransferServerPort()) - { - if(s_retryTransferServerConnection) - { - getInstance().m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); + case constcrc("SetConnectionServerPublic") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + SetConnectionServerPublic msg(ri); + if (msg.getIsPublic()) { + gs_connectionServersPublic = true; } - } - } - else if(message.isType("StationPlayersCollectorConnectionClosed")) - { - // connect to the station players collector - if(ConfigCentralServer::getStationPlayersCollectorPort()) - { - if(s_retryStationPlayersCollectorConnection) - { - getInstance().m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); + else { + gs_connectionServersPublic = false; } + + sendToAllConnectionServers(msg, true); + break; } - } - else if(message.isType("ClaimRewardsMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ClaimRewardsMessage msg(ri); - sendToArbitraryLoginServer(msg); - } - else if(message.isType("ClaimRewardsReplyMessage")) - { - DEBUG_REPORT_LOG(true,("Central got ClaimRewardsReplyMessage\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ClaimRewardsReplyMessage msg(ri); - sendToGameServer(msg.getGameServer(), msg, true); - } - else if (message.isType("PurgeStructuresForAccountMessage") || message.isType("WarnStructuresAboutPurgeMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - LoginServerConnection const * l = dynamic_cast(&source); - if (l) - { - m_purgeAccountToLoginServerMap[msg.getValue()]= l->getProcessId(); // remember which login server is handling this purge + case constcrc("ProfilerOperationMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ProfilerOperationMessage msg(ri); + sendToAllGameServers(msg, true); + sendToAllPlanetServers(msg, true); + sendToAllConnectionServers(msg, true); + break; + } + case constcrc("PopulationListMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PopulationListMessage msg(ri); + sendToAllGameServers(msg, true); + break; + } + case constcrc("CentralPingMessage") : { + GameServerConnection const *g = safe_cast < GameServerConnection const * > (&source); + NOT_NULL(g); + LOG("CentralServerPings", ("Got reply from %lu", g->getProcessId())); + IGNORE_RETURN(m_serverPings.erase(g->getProcessId())); + break; + } + case constcrc("DatabaseBackloggedMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage dbbacklog(ri); + + m_databaseBacklogged = dbbacklog.getValue(); + bool const preloadFinished = isPreloadFinished(); + + if (preloadFinished) { + m_timeClusterWentIntoLoadingState = 0; + } + else if (m_timeClusterWentIntoLoadingState <= 0) { + m_timeClusterWentIntoLoadingState = time(0); + } + + PreloadFinishedMessage msg(preloadFinished); + sendToAllLoginServers(msg); + sendTaskMessage(msg); + break; + } + case constcrc("DatabaseSaveStart") : { + LOG("CentralServer", ("Received DatabaseSaveStart network message.")); + if (m_shutdownPhase == 4) { + LOG("CentralServerShutdown", ("Shutdown Phase %d: Setting indicator for receipt of DatabaseSaveStart.", m_shutdownPhase)); + m_shutdownHaveDatabaseSaveStart = true; + checkShutdownProcess(); + } + else if (m_shutdownPhase == 5 && m_shutdownHaveDatabaseSaveStart) { + LOG("CentralServerShutdown", ("Shutdown Phase %d: Setting indicator that final database save cycle is complete.", m_shutdownPhase)); + m_shutdownHaveDatabaseComplete = true; + checkShutdownProcess(); + } + break; + } + case constcrc("DatabaseSaveComplete") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + LOG("CentralServer", ("Received DatabaseSaveComplete network message.")); + + // tell all the Planet Servers that the save finished + sendToAllPlanetServers(msg, true); + + // don't want to indicate this yet until we are at the beginning of a full cycle + if (m_shutdownPhase == 5 && m_shutdownHaveDatabaseSaveStart) { + LOG("CentralServerShutdown", ("Shutdown Phase %d: Setting indicator that final database save cycle is complete.", m_shutdownPhase)); + m_shutdownHaveDatabaseComplete = true; + checkShutdownProcess(); + } + break; + } + case constcrc("PlanetRequestSave") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameNetworkMessage msg(ri); + sendToDBProcess(msg, true); + break; } - } - else if (message.isType("PurgeCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - - std::map::iterator i=m_purgeAccountToLoginServerMap.find(msg.getValue()); - if (i!=m_purgeAccountToLoginServerMap.end()) - { - sendToLoginServer(i->second,msg); - m_purgeAccountToLoginServerMap.erase(i); + case constcrc("ShutdownCluster") : { + LOG("CentralServerShutdown", ("Received ShutdownCluster network message.")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ShutdownCluster m(ri); + startShutdownProcess(m.getTimeToShutdown(), m.getMaxTime(), m.getSystemMessage()); + break; + } + case constcrc("AbortShutdown") : { + LOG("CentralServerShutdown", ("Received AbortShutdown network message.")); + abortShutdownProcess(); + break; } - } - else if (message.isType("RestartServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RestartServerMessage msg(ri); - sendToPlanetServer(msg.getScene(), msg, true); - } - else if (message.isType("RestartServerByRoleMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - sendToPlanetServer(msg.getValue().first, msg, true); - } - else if (message.isType("ExcommunicateGameServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ExcommunicateGameServerMessage msg(ri); + case constcrc("SetSceneForPlayer") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < NetworkId, std::pair < std::string, bool > > > ssfp(ri); - excommunicateServer(msg); - } - else if (message.isType("RestartPlanetMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); + if (ssfp.getValue().second.first.empty()) { + static const std::string loginTrace("TRACE_LOGIN"); - GenericValueTypeMessage const shutdownMsg("ShutdownMessage", 0); - sendToPlanetServer(msg.getValue(),shutdownMsg, true); - } - else if (message.isType("UpdateClusterLockedAndSecretState")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - gs_clusterIsLocked = msg.getValue().first; - gs_clusterIsSecret = msg.getValue().second; - } - else if (message.isType("PopStatRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - m_timePopulationStatisticsRefresh = ::time(NULL); - m_populationStatistics = msg.getValue(); - } - else if (message.isType("GcwScoreStatRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::pair >, std::map > > > > const msg(ri); - - m_timeGcwScoreStatisticsRefresh = ::time(NULL); - std::string const timeGcwScoreStatisticsRefreshStr = CalendarTime::convertEpochToTimeStringLocal(m_timeGcwScoreStatisticsRefresh); - - std::map const & gcwImperialScorePercentile = msg.getValue().first; - std::map > const & gcwImperialScore = msg.getValue().second.first; - std::map > const & gcwRebelScore = msg.getValue().second.second; - std::map >::const_iterator iterFind; - std::map::const_iterator iterFindImperialScorePercentile; - std::pair > >::iterator, bool> iterInsertion; - int imperialScorePercentile; - std::string scoreText, scoreTextDesc; - - for (std::map >::const_iterator iterImp = gcwImperialScore.begin(); iterImp != gcwImperialScore.end(); ++iterImp) - { - iterFindImperialScorePercentile = gcwImperialScorePercentile.find(iterImp->first); - if (iterFindImperialScorePercentile != gcwImperialScorePercentile.end()) - imperialScorePercentile = iterFindImperialScorePercentile->second; - else - imperialScorePercentile = 0; - - iterFind = gcwRebelScore.find(iterImp->first); - if (iterFind != gcwRebelScore.end()) - scoreText = FormattedString<1024>().sprintf("Imp (%s, %s) Reb (%s, %s) - ", NetworkId(iterImp->second.first).getValueString().c_str(), NetworkId(iterImp->second.second).getValueString().c_str(), NetworkId(iterFind->second.first).getValueString().c_str(), NetworkId(iterFind->second.second).getValueString().c_str()); - else - scoreText = FormattedString<1024>().sprintf("Imp (%s, %s) Reb (0, 0) - ", NetworkId(iterImp->second.first).getValueString().c_str(), NetworkId(iterImp->second.second).getValueString().c_str()); - - scoreTextDesc = scoreText + timeGcwScoreStatisticsRefreshStr; - - iterInsertion = m_gcwScoreStatistics.insert(std::make_pair("gcwScore." + iterImp->first, std::make_pair(imperialScorePercentile, std::make_pair(scoreText, scoreTextDesc)))); - if (!iterInsertion.second) - { - if (iterInsertion.first->second.second.first != scoreText) - { - iterInsertion.first->second.first = imperialScorePercentile; - iterInsertion.first->second.second.first = scoreText; - iterInsertion.first->second.second.second = scoreTextDesc; + IGNORE_RETURN(m_playerSceneMap.erase(ssfp.getValue().first)); + LOG(loginTrace, ("Forgetting sceneId for character (%s) -- will query the database on next login", ssfp + .getValue().first.getValueString().c_str())); + } + else { + PlayerSceneMapType::iterator i = m_playerSceneMap.find(ssfp.getValue().first); + if (i != m_playerSceneMap.end()) { + i->second.first = ssfp.getValue().second.first; + if (ssfp.getValue().second.second) { + i->second.second = ::time(nullptr) + + static_cast(ConfigCentralServer::getCtsDenyLoginThresholdSeconds()); + } + } + else { + m_playerSceneMap[ssfp.getValue().first] = std::make_pair(ssfp.getValue().second + .first, (ssfp.getValue().second.second + ? (::time(nullptr) + + static_cast(ConfigCentralServer::getCtsDenyLoginThresholdSeconds())) + : 0)); } } + break; } + case constcrc("TaskProcessDiedMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + TaskProcessDiedMessage died(ri); + LOG("TaskProcessDied", ("received TaskProcessDied for %s:%i", died.getProcessName().c_str(), died + .getProcessId()));; + if (died.getProcessName().find("SwgGameServer") != std::string::npos) { + LOG("TaskProcessDied", ("Dead process %i is a game server", died.getProcessId())); + // extract sceneId + size_t pos = died.getProcessName().find("sceneID="); + if (pos != std::string::npos) { + pos += std::string("sceneID=").length(); + size_t end = died.getProcessName().find_first_of(' ', pos); + if (end != std::string::npos) { + std::string scene = died.getProcessName().substr(pos, end - pos); + LOG("TaskProcessDied", ("Dead game server process %i was running sceneID %s, advising planet server", died + .getProcessId(), scene.c_str())); + std::map::iterator f = m_planetServers.find(scene); + if (f != m_planetServers.end()) { + f->second->send(died, true); + } + } + } + } + break; + } + case constcrc("SystemTimeMismatchNotification") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); - for (std::map >::const_iterator iterReb = gcwRebelScore.begin(); iterReb != gcwRebelScore.end(); ++iterReb) - { - iterFind = gcwImperialScore.find(iterReb->first); - if (iterFind == gcwImperialScore.end()) + m_lastTimeSystemTimeMismatchNotification = time(0); + m_lastTimeSystemTimeMismatchNotificationDescription = msg.getValue(); + break; + } + case constcrc("DisconnectedTaskManagerMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + + m_disconnectedTaskManagerList = msg.getValue(); + break; + } + case constcrc("TransferServerConnectionClosed") : { + // connect to the character transfer server + if (ConfigCentralServer::getTransferServerPort()) { + if (s_retryTransferServerConnection) { + getInstance() + .m_transferServerConnection = new TransferServerConnection(ConfigCentralServer::getTransferServerAddress(), ConfigCentralServer::getTransferServerPort()); + } + } + break; + } + case constcrc("StationPlayersCollectorConnectionClosed") : { + // connect to the station players collector + if (ConfigCentralServer::getStationPlayersCollectorPort()) { + if (s_retryStationPlayersCollectorConnection) { + getInstance() + .m_stationPlayersCollectorConnection = new StationPlayersCollectorConnection(ConfigCentralServer::getStationPlayersCollectorAddress(), ConfigCentralServer::getStationPlayersCollectorPort()); + } + } + break; + } + case constcrc("ClaimRewardsMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ClaimRewardsMessage msg(ri); + sendToArbitraryLoginServer(msg); + break; + } + case constcrc("ClaimRewardsReplyMessage") : { + DEBUG_REPORT_LOG(true, ("Central got ClaimRewardsReplyMessage\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ClaimRewardsReplyMessage msg(ri); + sendToGameServer(msg.getGameServer(), msg, true); + break; + } + case constcrc("PurgeStructuresForAccountMessage") : + case constcrc("WarnStructuresAboutPurgeMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + LoginServerConnection const *l = dynamic_cast(&source); + if (l) { + m_purgeAccountToLoginServerMap[msg.getValue()] = l + ->getProcessId(); // remember which login server is handling this purge + sendToDBProcess(msg, true); + } + break; + } + case constcrc("PurgeCompleteMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + + std::map::iterator i = m_purgeAccountToLoginServerMap.find(msg.getValue()); + if (i != m_purgeAccountToLoginServerMap.end()) { + sendToLoginServer(i->second, msg); + m_purgeAccountToLoginServerMap.erase(i); + } + break; + } + case constcrc("RestartServerMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RestartServerMessage msg(ri); + + sendToPlanetServer(msg.getScene(), msg, true); + break; + } + case constcrc("RestartServerByRoleMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + sendToPlanetServer(msg.getValue().first, msg, true); + break; + } + case constcrc("ExcommunicateGameServerMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ExcommunicateGameServerMessage msg(ri); + + excommunicateServer(msg); + break; + } + case constcrc("RestartPlanetMessage") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + + GenericValueTypeMessage const shutdownMsg("ShutdownMessage", 0); + sendToPlanetServer(msg.getValue(), shutdownMsg, true); + break; + } + case constcrc("UpdateClusterLockedAndSecretState") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + gs_clusterIsLocked = msg.getValue().first; + gs_clusterIsSecret = msg.getValue().second; + break; + } + case constcrc("PopStatRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + m_timePopulationStatisticsRefresh = ::time(nullptr); + m_populationStatistics = msg.getValue(); + break; + } + case constcrc("GcwScoreStatRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::map < std::string, int >, std::pair < std::map < std::string, + std::pair < int64, int64 > >, std::map < std::string, std::pair < int64, int64 > > > > > + const msg(ri); + + m_timeGcwScoreStatisticsRefresh = ::time(nullptr); + std::string const timeGcwScoreStatisticsRefreshStr = CalendarTime::convertEpochToTimeStringLocal(m_timeGcwScoreStatisticsRefresh); + + std::map const &gcwImperialScorePercentile = msg.getValue().first; + std::map > const &gcwImperialScore = msg.getValue().second.first; + std::map > const &gcwRebelScore = msg.getValue().second.second; + std::map < std::string, std::pair < int64, int64 > > ::const_iterator + iterFind; + std::map::const_iterator iterFindImperialScorePercentile; + std::pair < std::map < std::string, std::pair < int, std::pair < std::string, std::string > > > ::iterator, + bool > iterInsertion; + int imperialScorePercentile; + std::string scoreText, scoreTextDesc; + + for (std::map < std::string, std::pair < int64, int64 > > ::const_iterator iterImp = gcwImperialScore + .begin(); iterImp != gcwImperialScore.end(); + ++iterImp) { - iterFindImperialScorePercentile = gcwImperialScorePercentile.find(iterReb->first); - if (iterFindImperialScorePercentile != gcwImperialScorePercentile.end()) + iterFindImperialScorePercentile = gcwImperialScorePercentile.find(iterImp->first); + if (iterFindImperialScorePercentile != gcwImperialScorePercentile.end()) { imperialScorePercentile = iterFindImperialScorePercentile->second; - else + } + else { imperialScorePercentile = 0; + } + + iterFind = gcwRebelScore.find(iterImp->first); + if (iterFind != gcwRebelScore.end()) { + scoreText = FormattedString<1024>() + .sprintf("Imp (%s, %s) Reb (%s, %s) - ", NetworkId(iterImp->second.first).getValueString() + .c_str(), NetworkId(iterImp + ->second.second).getValueString().c_str(), NetworkId(iterFind->second.first) + .getValueString().c_str(), NetworkId(iterFind->second.second).getValueString() + .c_str()); + } + else { + scoreText = FormattedString<1024>() + .sprintf("Imp (%s, %s) Reb (0, 0) - ", NetworkId(iterImp->second.first).getValueString() + .c_str(), NetworkId(iterImp + ->second.second).getValueString().c_str()); + } - scoreText = FormattedString<1024>().sprintf("Imp (0, 0) Reb (%s, %s) - ", NetworkId(iterReb->second.first).getValueString().c_str(), NetworkId(iterReb->second.second).getValueString().c_str()); scoreTextDesc = scoreText + timeGcwScoreStatisticsRefreshStr; - iterInsertion = m_gcwScoreStatistics.insert(std::make_pair("gcwScore." + iterReb->first, std::make_pair(imperialScorePercentile, std::make_pair(scoreText, scoreTextDesc)))); - if (!iterInsertion.second) - { - if (iterInsertion.first->second.second.first != scoreText) - { + iterInsertion = m_gcwScoreStatistics.insert(std::make_pair("gcwScore." + + iterImp->first, std::make_pair(imperialScorePercentile, std::make_pair(scoreText, scoreTextDesc)))); + if (!iterInsertion.second) { + if (iterInsertion.first->second.second.first != scoreText) { iterInsertion.first->second.first = imperialScorePercentile; iterInsertion.first->second.second.first = scoreText; iterInsertion.first->second.second.second = scoreTextDesc; } } } - } - } - else if (message.isType("LLTStatRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage >, std::map > > > const msg(ri); - m_timeLastLoginTimeStatisticsRefresh = ::time(NULL); - m_lastLoginTimeStatistics = msg.getValue().first; - m_createTimeStatistics = msg.getValue().second; - } - else if (message.isType("LfgStatRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > > const msg(ri); + for (std::map < std::string, std::pair < int64, int64 > > ::const_iterator iterReb = gcwRebelScore.begin(); + iterReb != gcwRebelScore.end(); + ++iterReb) + { + iterFind = gcwImperialScore.find(iterReb->first); + if (iterFind == gcwImperialScore.end()) { + iterFindImperialScorePercentile = gcwImperialScorePercentile.find(iterReb->first); + if (iterFindImperialScorePercentile != gcwImperialScorePercentile.end()) { + imperialScorePercentile = iterFindImperialScorePercentile->second; + } + else { + imperialScorePercentile = 0; + } - m_numberOfCharacterMatchRequests += msg.getValue().first; - m_numberOfCharacterMatchResults += msg.getValue().second.first; - m_timeSpentOnCharacterMatchRequestsMs += msg.getValue().second.second; - } - else if (message.isType("OccupyUnlockedSlotRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, uint32> > const occupyUnlockedSlotRsp(ri); + scoreText = FormattedString<1024>() + .sprintf("Imp (0, 0) Reb (%s, %s) - ", NetworkId(iterReb->second.first).getValueString() + .c_str(), NetworkId(iterReb + ->second.second).getValueString().c_str()); + scoreTextDesc = scoreText + timeGcwScoreStatisticsRefreshStr; - // CS log the response - LoginUpgradeAccountMessage::OccupyUnlockedSlotResponse const response = static_cast(occupyUnlockedSlotRsp.getValue().first.first); - if (response == LoginUpgradeAccountMessage::OUSR_success) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request SUCCESS", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::OUSR_db_error) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - internal db error", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::OUSR_account_has_no_unlocked_slot) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - account doesn't have an unlocked slot", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::OUSR_account_has_no_unoccupied_unlocked_slot) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - account has no unoccupied unlocked slot", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::OUSR_cluster_already_has_unlocked_slot_character) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - cluster already has an unlocked slot character", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else - { - LOG("CustomerService",("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - unknown result code (%d)", occupyUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), occupyUnlockedSlotRsp.getValue().first.first)); + iterInsertion = m_gcwScoreStatistics.insert(std::make_pair("gcwScore." + + iterReb->first, std::make_pair(imperialScorePercentile, std::make_pair(scoreText, scoreTextDesc)))); + if (!iterInsertion.second) { + if (iterInsertion.first->second.second.first != scoreText) { + iterInsertion.first->second.first = imperialScorePercentile; + iterInsertion.first->second.second.first = scoreText; + iterInsertion.first->second.second.second = scoreTextDesc; + } + } + } + } + break; } + case constcrc("LLTStatRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::map < int, std::pair < std::string, int > >, std::map < int, + std::pair < std::string, int > > > > + const msg(ri); - GameServerConnection * gs = getGameServer(occupyUnlockedSlotRsp.getValue().second); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(occupyUnlockedSlotRsp, true); - } - else if (message.isType("VacateUnlockedSlotRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::pair > > const vacateUnlockedSlotRsp(ri); - - // CS log the response - LoginUpgradeAccountMessage::VacateUnlockedSlotResponse const response = static_cast(vacateUnlockedSlotRsp.getValue().first.first); - if (response == LoginUpgradeAccountMessage::VUSR_success) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request SUCCESS", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - - // to safeguard against any sort of timing exploit to create another normal - // slot character while this one is being converted to normal, thus allowing - // the account to have more normal slot characters on this cluster than is - // allowed, make it look like a normal character has been created on this - // account on this cluster, and that mechanism will prevent such an exploit - - // let all connection servers know that a new character has been created for the station account - GenericValueTypeMessage const ncc("NewCharacterCreated", static_cast(vacateUnlockedSlotRsp.getValue().second.first)); - CentralServer::getInstance().sendToAllConnectionServers(ncc, true); - } - else if (response == LoginUpgradeAccountMessage::VUSR_db_error) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - internal db error", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::VUSR_account_has_no_unlocked_slot) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - account doesn't have an unlocked slot", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::VUSR_not_unlocked_slot_character) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - character is not an unlocked slot character", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else if (response == LoginUpgradeAccountMessage::VUSR_no_available_normal_character_slot) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - no available normal character slot for the account on this galaxy", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str())); - } - else - { - LOG("CustomerService",("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - unknown result code (%d)", vacateUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), vacateUnlockedSlotRsp.getValue().first.first)); + m_timeLastLoginTimeStatisticsRefresh = ::time(nullptr); + m_lastLoginTimeStatistics = msg.getValue().first; + m_createTimeStatistics = msg.getValue().second; + break; } + case constcrc("LfgStatRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage >> const msg(ri); - GameServerConnection * gs = getGameServer(vacateUnlockedSlotRsp.getValue().second.second); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(vacateUnlockedSlotRsp, true); - } - else if (message.isType("SwapUnlockedSlotRsp")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::pair > > > const swapUnlockedSlotRsp(ri); - - // CS log the response - LoginUpgradeAccountMessage::SwapUnlockedSlotResponse const response = static_cast(swapUnlockedSlotRsp.getValue().first.first); - if (response == LoginUpgradeAccountMessage::SUSR_success) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s (%s) request SUCCESS", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.second.c_str())); + m_numberOfCharacterMatchRequests += msg.getValue().first; + m_numberOfCharacterMatchResults += msg.getValue().second.first; + m_timeSpentOnCharacterMatchRequestsMs += msg.getValue().second.second; + break; } - else if (response == LoginUpgradeAccountMessage::SUSR_db_error) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - internal db error", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str())); + case constcrc("OccupyUnlockedSlotRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::pair < int, NetworkId >, uint32 > > + const occupyUnlockedSlotRsp(ri); + + // CS log the response + LoginUpgradeAccountMessage::OccupyUnlockedSlotResponse const response = static_cast(occupyUnlockedSlotRsp + .getValue().first.first); + if (response == LoginUpgradeAccountMessage::OUSR_success) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request SUCCESS", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::OUSR_db_error) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - internal db error", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::OUSR_account_has_no_unlocked_slot) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - account doesn't have an unlocked slot", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::OUSR_account_has_no_unoccupied_unlocked_slot) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - account has no unoccupied unlocked slot", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::OUSR_cluster_already_has_unlocked_slot_character) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - cluster already has an unlocked slot character", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else { + LOG("CustomerService", ("JediUnlockedSlot:Player %s OccupyUnlockedSlot request FAILED - unknown result code (%d)", occupyUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), occupyUnlockedSlotRsp.getValue().first + .first)); + } + + GameServerConnection *gs = getGameServer(occupyUnlockedSlotRsp.getValue().second); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(occupyUnlockedSlotRsp, true); + } + break; } - else if (response == LoginUpgradeAccountMessage::SUSR_account_has_no_unlocked_slot) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - account doesn't have an unlocked slot", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str())); + case constcrc("VacateUnlockedSlotRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::pair < int, NetworkId >, std::pair < uint32, uint32 > > > + const vacateUnlockedSlotRsp(ri); + + // CS log the response + LoginUpgradeAccountMessage::VacateUnlockedSlotResponse const response = static_cast(vacateUnlockedSlotRsp + .getValue().first.first); + if (response == LoginUpgradeAccountMessage::VUSR_success) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request SUCCESS", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + + // to safeguard against any sort of timing exploit to create another normal + // slot character while this one is being converted to normal, thus allowing + // the account to have more normal slot characters on this cluster than is + // allowed, make it look like a normal character has been created on this + // account on this cluster, and that mechanism will prevent such an exploit + + // let all connection servers know that a new character has been created for the station account + GenericValueTypeMessage const ncc("NewCharacterCreated", static_cast(vacateUnlockedSlotRsp + .getValue().second.first)); + CentralServer::getInstance().sendToAllConnectionServers(ncc, true); + } + else if (response == LoginUpgradeAccountMessage::VUSR_db_error) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - internal db error", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::VUSR_account_has_no_unlocked_slot) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - account doesn't have an unlocked slot", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::VUSR_not_unlocked_slot_character) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - character is not an unlocked slot character", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else if (response == LoginUpgradeAccountMessage::VUSR_no_available_normal_character_slot) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - no available normal character slot for the account on this galaxy", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str())); + } + else { + LOG("CustomerService", ("JediUnlockedSlot:Player %s VacateUnlockedSlot request FAILED - unknown result code (%d)", vacateUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), vacateUnlockedSlotRsp.getValue().first + .first)); + } + + GameServerConnection *gs = getGameServer(vacateUnlockedSlotRsp.getValue().second.second); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(vacateUnlockedSlotRsp, true); + } + break; } - else if (response == LoginUpgradeAccountMessage::SUSR_not_unlocked_slot_character) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - source character is not an unlocked slot character", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str())); + case constcrc("SwapUnlockedSlotRsp") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage < std::pair < std::pair < int, NetworkId >, std::pair < uint32, std::pair < + NetworkId, + std::string > > > > + const swapUnlockedSlotRsp(ri); + + // CS log the response + LoginUpgradeAccountMessage::SwapUnlockedSlotResponse const response = static_cast(swapUnlockedSlotRsp + .getValue().first.first); + if (response == LoginUpgradeAccountMessage::SUSR_success) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s (%s) request SUCCESS", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str(), swapUnlockedSlotRsp + .getValue().second.second.second.c_str())); + } + else if (response == LoginUpgradeAccountMessage::SUSR_db_error) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - internal db error", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str())); + } + else if (response == LoginUpgradeAccountMessage::SUSR_account_has_no_unlocked_slot) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - account doesn't have an unlocked slot", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str())); + } + else if (response == LoginUpgradeAccountMessage::SUSR_not_unlocked_slot_character) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - source character is not an unlocked slot character", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str())); + } + else if (response == LoginUpgradeAccountMessage::SUSR_invalid_target_character) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - target character is either not valid, not on the same account, or not on this galaxy", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str())); + } + else if (response == LoginUpgradeAccountMessage::SUSR_target_character_already_unlocked_slot_character) { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - target character is already an unlocked slot character", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str())); + } + else { + LOG("CustomerService", ("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - unknown result code (%d)", swapUnlockedSlotRsp + .getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second + .first.getValueString() + .c_str(), swapUnlockedSlotRsp + .getValue().first.first)); + } + + GameServerConnection *gs = getGameServer(swapUnlockedSlotRsp.getValue().second.first); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(swapUnlockedSlotRsp, true); + } + break; } - else if (response == LoginUpgradeAccountMessage::SUSR_invalid_target_character) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - target character is either not valid, not on the same account, or not on this galaxy", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str())); + case constcrc("AdjustAccountFeatureIdResponse") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AdjustAccountFeatureIdResponse const msg(ri); + + GameServerConnection *gs = getGameServer(msg.getGameServer()); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(msg, true); + } + break; } - else if (response == LoginUpgradeAccountMessage::SUSR_target_character_already_unlocked_slot_character) - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - target character is already an unlocked slot character", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str())); + case constcrc("AccountFeatureIdResponse") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AccountFeatureIdResponse const msg(ri); + + GameServerConnection *gs = getGameServer(msg.getGameServer()); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(msg, true); + } + break; } - else - { - LOG("CustomerService",("JediUnlockedSlot:Player %s SwapUnlockedSlot with %s request FAILED - unknown result code (%d)", swapUnlockedSlotRsp.getValue().first.second.getValueString().c_str(), swapUnlockedSlotRsp.getValue().second.second.first.getValueString().c_str(), swapUnlockedSlotRsp.getValue().first.first)); + case constcrc("FeatureIdTransactionResponse") : { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FeatureIdTransactionResponse const msg(ri); + + GameServerConnection *gs = getGameServer(msg.getGameServer()); + if (!gs) { + gs = getRandomGameServer(); + } + + if (gs) { + gs->send(msg, true); + } + + break; } - - GameServerConnection * gs = getGameServer(swapUnlockedSlotRsp.getValue().second.first); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(swapUnlockedSlotRsp, true); - } - else if (message.isType("AdjustAccountFeatureIdResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AdjustAccountFeatureIdResponse const msg(ri); - - GameServerConnection * gs = getGameServer(msg.getGameServer()); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(msg, true); - } - else if (message.isType("AccountFeatureIdResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AccountFeatureIdResponse const msg(ri); - - GameServerConnection * gs = getGameServer(msg.getGameServer()); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(msg, true); - } - else if (message.isType("FeatureIdTransactionResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FeatureIdTransactionResponse const msg(ri); - - GameServerConnection * gs = getGameServer(msg.getGameServer()); - if (!gs) - gs = getRandomGameServer(); - - if (gs) - gs->send(msg, true); - } - else if(ClusterWideDataManagerList::handleMessage(source, message)) - { - // nothing else to do with the message since it was - // handled by the Cluster wide data manager + default : + if (ClusterWideDataManagerList::handleMessage(source, message)) { + // nothing else to do with the message since it was + // handled by the Cluster wide data manager + } + break; } } @@ -2606,7 +2638,7 @@ void CentralServer::removeGameServer(GameServerConnection const *gameServer) } else { - DEBUG_WARNING(true, ("A game server crashed but our process ID ptr is null.")); + DEBUG_WARNING(true, ("A game server crashed but our process ID ptr is nullptr.")); } } @@ -2812,23 +2844,37 @@ void CentralServer::run(void) */ void CentralServer::update() { - static int loopCount=0; - m_curTime = static_cast(time(0)); + static int loopCount = 0; + static int apiLoopCount = 0; + static int shutdownCheckLoopCount = 0; + m_curTime = static_cast(time(0)); + // Tell the LoginServers if necessary if ((++loopCount > ConfigCentralServer::getUpdatePlayerCountFrequency())) { - loopCount=0; + loopCount = 0; // Update the population on the server sendPopulationUpdateToLoginServer(); } + // update the webAPI if specified + int webUpdateIntervalSeconds = ConfigCentralServer::getWebUpdateIntervalSeconds(); + + // assuming that every 5th frame is ~1 second, we can multiply and then check + if (webUpdateIntervalSeconds && (++apiLoopCount > (webUpdateIntervalSeconds*1000)) ) + { + apiLoopCount = 0; + + // update the web api + sendMetricsToWebAPI(); + } if ( ConfigCentralServer::getAuctionEnabled() ) // allow auctions? { - if ( m_pAuctionTransferClient == NULL ) + if ( m_pAuctionTransferClient == nullptr ) { const char* hostName[1] = { ConfigCentralServer::getAuctionServer() }; const short port[1] = { (short)ConfigCentralServer::getAuctionPort() }; @@ -2849,11 +2895,11 @@ void CentralServer::update() m_pAuctionTransferClient = 0; } - - // check every 5th frame (one second roughly?) - if( loopCount%5 ) + if ( ++shutdownCheckLoopCount > 5 ) { + shutdownCheckLoopCount = 0; + checkShutdownProcess(); } @@ -2871,6 +2917,7 @@ void CentralServer::sendPopulationUpdateToLoginServer() m_totalTutorialSceneCount = 0; m_totalFalconSceneCount = 0; + ConnectionServerConnectionList::const_iterator i; for (i=m_connectionServerConnections.begin(); i!=m_connectionServerConnections.end(); ++i) { @@ -2892,6 +2939,49 @@ void CentralServer::sendPopulationUpdateToLoginServer() sendToAllLoginServers(upm); } +void CentralServer::sendMetricsToWebAPI() +{ + static const std::string metricsURL(ConfigCentralServer::getMetricsDataURL()); + + if (!metricsURL.empty()) + { + // create the object + webAPI api(metricsURL); + + // add our data + api.addJsonData("totalPlayerCount", m_totalPlayerCount); + api.addJsonData("totalGameServers", (m_gameServers.size() - 1)); + api.addJsonData("totalPlanetServers", m_planetServers.size()); + api.addJsonData("totalTutorialSceneCount", m_totalTutorialSceneCount); + +#ifdef _DEBUG + if (api.submit()) { + bool status = api.getNullableValue("status"); + + if (status) + { + std::string message = api.getString("message"); + + if (message.empty()) + { + message = "No message returned."; + } + + WARNING(true, ("Error sending stats: %s", message.c_str())); + } + + WARNING(true, ("Success sending server stats to API.")); + } + else + { + WARNING(true, ("Error sending stats.")); + } +#else + api.submit(); +#endif + } +} + //----------------------------------------------------------------------- void CentralServer::sendTaskMessage(const GameNetworkMessage & source) @@ -2975,7 +3065,7 @@ void CentralServer::sendToPlanetServer(const std::string &sceneId, const GameNet // ---------------------------------------------------------------------- -void CentralServer::sendToAllConnectionServers(const GameNetworkMessage & message, const bool reliable, Connection const * exclude /*= NULL*/) +void CentralServer::sendToAllConnectionServers(const GameNetworkMessage & message, const bool reliable, Connection const * exclude /*= nullptr*/) { // send to all connection servers for (ConnectionServerConnectionList::const_iterator i = m_connectionServerConnections.begin(); i != m_connectionServerConnections.end(); ++i) @@ -3005,7 +3095,7 @@ void CentralServer::sendToDBProcess(const GameNetworkMessage & message, const bo bool CentralServer::hasDBConnection() const { const GameServerConnection * g = getGameServer(getDbProcessServerProcessId()); - return (g != NULL); + return (g != nullptr); } //----------------------------------------------------------------------- @@ -3024,12 +3114,12 @@ void CentralServer::setTaskManager(TaskConnection * newTaskManager) void CentralServer::removePlanetServer(const PlanetServerConnection * p) { - for (std::map::iterator i = m_planetServers.begin(); i != m_planetServers.end(); ++i) + for (std::map::iterator i = m_planetServers.begin(); i != m_planetServers.end();) { if ((*i).second == p) { DEBUG_REPORT_LOG(true,("Central lost connection to Planet Server %s\n",p->getSceneId().c_str())); - m_planetServers.erase(i); + i = m_planetServers.erase(i); if (isPreloadFinished()) m_timeClusterWentIntoLoadingState = 0; @@ -3038,6 +3128,10 @@ void CentralServer::removePlanetServer(const PlanetServerConnection * p) return; } + else + { + ++i; + } } } @@ -3110,7 +3204,7 @@ void CentralServer::startPlanetServer(const std::string & host, const std::strin TaskSpawnProcess spawn(host.empty() ? std::string("any") : host, "PlanetServer", options, spawnDelay); CentralServer::getInstance().sendTaskMessage(spawn); - m_pendingPlanetServers[sceneId] = std::make_pair(std::make_pair(host, options), ::time(NULL)); + m_pendingPlanetServers[sceneId] = std::make_pair(std::make_pair(host, options), ::time(nullptr)); IGNORE_RETURN(m_planetsWaitingForPreload.insert(sceneId)); bool const preloadFinished = isPreloadFinished(); @@ -3119,14 +3213,14 @@ void CentralServer::startPlanetServer(const std::string & host, const std::strin else if (m_timeClusterWentIntoLoadingState <= 0) m_timeClusterWentIntoLoadingState = time(0); - if(getInstance().m_transferServerConnection != NULL && !preloadFinished) + if(getInstance().m_transferServerConnection != nullptr && !preloadFinished) { getInstance().m_transferServerConnection->disconnect(); getInstance().m_transferServerConnection = 0; s_retryTransferServerConnection = false; } - if(getInstance().m_stationPlayersCollectorConnection != NULL && ! isPreloadFinished()) + if(getInstance().m_stationPlayersCollectorConnection != nullptr && ! isPreloadFinished()) { getInstance().m_stationPlayersCollectorConnection->disconnect(); getInstance().m_stationPlayersCollectorConnection = 0; @@ -3263,7 +3357,7 @@ void CentralServer::handleGameServerForLoginMessage(const GameServerForLoginMess void CentralServer::handleExchangeListCreditsMessage(const ExchangeListCreditsMessage &msg) { LOG("Exchange", ("Central Server got exchange list credits %d.",msg.getCredits())); - if ( m_pAuctionTransferClient == NULL ) + if ( m_pAuctionTransferClient == nullptr ) { // send failure packet } @@ -3299,7 +3393,7 @@ ConnectionServerConnection * CentralServer::getAnyConnectionServer() ConnectionServerConnection * CentralServer::getConnectionServerForAccount(StationId suid) { - ConnectionServerConnection * result = NULL; + ConnectionServerConnection * result = nullptr; ConnectionServerSUIDMap::iterator i=m_accountConnectionMap.find(suid); if (i!=m_accountConnectionMap.end()) { @@ -3707,7 +3801,7 @@ void CentralServer::checkShutdownProcess() { // if it's been "awhile" since we requested to restart the PlanetServer, // then assume that something has gone wrong, and try the restart again - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); if ((iterPendingPlanetServer->second.second + static_cast(ConfigCentralServer::getMaxTimeToWaitForPlanetServerStartSeconds())) < timeNow) { @@ -3982,7 +4076,7 @@ int CentralServer::getSecondsClusterHasBeenInLoadingState() const const std::map & CentralServer::getPopulationStatistics(time_t & refreshTime) { // periodically request updated statistics from the game server - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); if (m_timePopulationStatisticsNextRefresh <= timeNow) { GameServerConnection * universeGameServerConnection = getGameServer(UniverseManager::getInstance().getUniverseProcess()); @@ -4004,7 +4098,7 @@ const std::map & CentralServer::getPopulationStatistics(time_t const std::map > > & CentralServer::getGcwScoreStatistics(time_t & refreshTime) { // periodically request updated statistics from the game server - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); if (m_timeGcwScoreStatisticsNextRefresh <= timeNow) { GameServerConnection * universeGameServerConnection = getGameServer(UniverseManager::getInstance().getUniverseProcess()); @@ -4026,7 +4120,7 @@ const std::map > std::pair > const *, std::map > const *> CentralServer::getLastLoginTimeStatistics(time_t & refreshTime) { // periodically request updated statistics from the game server - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); if (m_timeLastLoginTimeStatisticsNextRefresh <= timeNow) { GameServerConnection * universeGameServerConnection = getGameServer(UniverseManager::getInstance().getUniverseProcess()); @@ -4049,7 +4143,7 @@ std::pair > const *, std::map characterMatchStatisticsRequest("LfgStatReq", 0); diff --git a/engine/server/application/CentralServer/src/shared/CentralServer.h b/engine/server/application/CentralServer/src/shared/CentralServer.h index d628b2fa..22e6a7de 100755 --- a/engine/server/application/CentralServer/src/shared/CentralServer.h +++ b/engine/server/application/CentralServer/src/shared/CentralServer.h @@ -121,7 +121,7 @@ public: void sendToAllGameServersExceptDBProcess(const GameNetworkMessage & message, const bool reliable); void sendToAllPlanetServers(const GameNetworkMessage & message, const bool reliable); void sendToPlanetServer(const std::string &sceneId, const GameNetworkMessage & message, const bool reliable); - void sendToAllConnectionServers(const GameNetworkMessage & message, const bool reliable, Connection const * exclude = NULL); + void sendToAllConnectionServers(const GameNetworkMessage & message, const bool reliable, Connection const * exclude = nullptr); void sendToConnectionServerForAccount(StationId account, const GameNetworkMessage & message, const bool reliable); void sendToDBProcess(const GameNetworkMessage & message, const bool reliable) const; void sendToLoginServer(uint32 loginServerId, const GameNetworkMessage &message); @@ -182,6 +182,7 @@ private: size_t getGameServerCount (void) const; void update(); void sendPopulationUpdateToLoginServer(); + void sendMetricsToWebAPI(); ConnectionServerConnection * getConnectionServerForAccount(StationId suid); void addToAccountConnectionMap(StationId suid, ConnectionServerConnection * cconn, uint32 subscriptionBits); void removeFromAccountConnectionMap(int connectionServerConnectionId); diff --git a/engine/server/application/CentralServer/src/shared/CentralServerMetricsData.cpp b/engine/server/application/CentralServer/src/shared/CentralServerMetricsData.cpp index 19307914..b34c0174 100755 --- a/engine/server/application/CentralServer/src/shared/CentralServerMetricsData.cpp +++ b/engine/server/application/CentralServer/src/shared/CentralServerMetricsData.cpp @@ -148,7 +148,7 @@ void CentralServerMetricsData::updateData() // appear yellow to draw attention) for some amount of time // after detecting a system time mismatch issue #ifndef WIN32 - if ((lastTimeSystemTimeMismatchNotification + ConfigCentralServer::getSystemTimeMismatchAlertIntervalSeconds()) > ::time(NULL)) + if ((lastTimeSystemTimeMismatchNotification + ConfigCentralServer::getSystemTimeMismatchAlertIntervalSeconds()) > ::time(nullptr)) m_data[m_systemTimeMismatch].m_value = STATUS_LOADING; else m_data[m_systemTimeMismatch].m_value = 1; @@ -202,7 +202,7 @@ void CentralServerMetricsData::updateData() std::string label("population."); label += iter->first; - m_mapPopulationStatisticsIndex[iter->first] = addMetric(label.c_str(), 0, NULL, false, false); + m_mapPopulationStatisticsIndex[iter->first] = addMetric(label.c_str(), 0, nullptr, false, false); } } } @@ -235,7 +235,7 @@ void CentralServerMetricsData::updateData() } else { - gcwScoreStatisticsIndex = addMetric(iter->first.c_str(), 0, NULL, false, false); + gcwScoreStatisticsIndex = addMetric(iter->first.c_str(), 0, nullptr, false, false); IGNORE_RETURN(m_mapGcwScoreStatisticsIndex.insert(std::make_pair(iter->first, gcwScoreStatisticsIndex))); } @@ -263,7 +263,7 @@ void CentralServerMetricsData::updateData() std::string label("population."); label += secondIter.first; - m_mapLastLoginTimeStatisticsIndex[secondIter.first] = addMetric(label.c_str(), 0, NULL, false, false); + m_mapLastLoginTimeStatisticsIndex[secondIter.first] = addMetric(label.c_str(), 0, nullptr, false, false); } } } @@ -288,7 +288,7 @@ void CentralServerMetricsData::updateData() std::string label("population."); label += iter->second.first; - m_mapCreateTimeStatisticsIndex[iter->second.first] = addMetric(label.c_str(), 0, NULL, false, false); + m_mapCreateTimeStatisticsIndex[iter->second.first] = addMetric(label.c_str(), 0, nullptr, false, false); } } } diff --git a/engine/server/application/CentralServer/src/shared/CharacterCreationTracker.cpp b/engine/server/application/CentralServer/src/shared/CharacterCreationTracker.cpp index 5cbdb5c9..b56ee398 100755 --- a/engine/server/application/CentralServer/src/shared/CharacterCreationTracker.cpp +++ b/engine/server/application/CentralServer/src/shared/CharacterCreationTracker.cpp @@ -26,13 +26,13 @@ // ====================================================================== -CharacterCreationTracker * CharacterCreationTracker::ms_instance = NULL; +CharacterCreationTracker * CharacterCreationTracker::ms_instance = nullptr; // ====================================================================== void CharacterCreationTracker::install() { - DEBUG_FATAL(ms_instance != NULL,("Called install() twice.\n")); + DEBUG_FATAL(ms_instance != nullptr,("Called install() twice.\n")); ms_instance = new CharacterCreationTracker; ExitChain::add(CharacterCreationTracker::remove,"CharacterCreationTracker::remove"); } @@ -354,8 +354,8 @@ void CharacterCreationTracker::setFastCreationLock(StationId account) CharacterCreationTracker::CreationRecord::CreationRecord() : m_stage(S_queuedForGameServer), - m_gameCreationRequest(NULL), - m_loginCreationRequest(NULL), + m_gameCreationRequest(nullptr), + m_loginCreationRequest(nullptr), m_creationTime(ServerClock::getInstance().getGameTimeSeconds()), m_gameServerId(0), m_loginServerId(0), diff --git a/engine/server/application/CentralServer/src/shared/ConfigCentralServer.cpp b/engine/server/application/CentralServer/src/shared/ConfigCentralServer.cpp index a13bd448..dd5fd6d6 100755 --- a/engine/server/application/CentralServer/src/shared/ConfigCentralServer.cpp +++ b/engine/server/application/CentralServer/src/shared/ConfigCentralServer.cpp @@ -74,7 +74,7 @@ void ConfigCentralServer::install(void) KEY_INT (chatServicePort, 61232); KEY_INT (connectionServicePort, 0); - KEY_INT (customerServicePort, 61242); + KEY_INT (customerServicePort, 0); KEY_INT (gameServicePort, 44451); KEY_STRING (loginServerAddress, "127.0.0.1"); KEY_INT (loginServerPort, 44452); @@ -127,6 +127,8 @@ void ConfigCentralServer::install(void) KEY_BOOL (disconnectDuplicateConnectionsOnOtherGalaxies, false); KEY_BOOL (requestDbSaveOnPlanetServerCrash, true); KEY_INT (maxTimeToWaitForPlanetServerStartSeconds, 5*60); // seconds + KEY_STRING (metricsDataURL, ""); + KEY_INT (webUpdateIntervalSeconds, 0); int index = 0; char const * result = 0; diff --git a/engine/server/application/CentralServer/src/shared/ConfigCentralServer.h b/engine/server/application/CentralServer/src/shared/ConfigCentralServer.h index fdc5b131..79e08d55 100755 --- a/engine/server/application/CentralServer/src/shared/ConfigCentralServer.h +++ b/engine/server/application/CentralServer/src/shared/ConfigCentralServer.h @@ -71,6 +71,9 @@ public: bool requestDbSaveOnPlanetServerCrash; int maxTimeToWaitForPlanetServerStartSeconds; + + const char * metricsDataURL; + int webUpdateIntervalSeconds; }; static const unsigned short getChatServicePort (); @@ -141,6 +144,8 @@ public: static int getMaxTimeToWaitForPlanetServerStartSeconds(); + static const char * getMetricsDataURL(); + static int getWebUpdateIntervalSeconds(); private: static Data * data; }; @@ -510,6 +515,20 @@ inline int ConfigCentralServer::getMaxTimeToWaitForPlanetServerStartSeconds() return data->maxTimeToWaitForPlanetServerStartSeconds; } +// ---------------------------------------------------------------------- + +inline const char * ConfigCentralServer::getMetricsDataURL() +{ + return data->metricsDataURL; +} + +// ---------------------------------------------------------------------- + +inline int ConfigCentralServer::getWebUpdateIntervalSeconds() +{ + return data->webUpdateIntervalSeconds; +} + // ====================================================================== #endif // _ConfigCentralServer_H diff --git a/engine/server/application/CentralServer/src/shared/ConnectionServerConnection.cpp b/engine/server/application/CentralServer/src/shared/ConnectionServerConnection.cpp index 3ef1d338..196f5a18 100755 --- a/engine/server/application/CentralServer/src/shared/ConnectionServerConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/ConnectionServerConnection.cpp @@ -1,8 +1,6 @@ // ConnectionServerConnection.cpp // copyright 2001 Verant Interactive - - //----------------------------------------------------------------------- #include "FirstCentralServer.h" @@ -25,6 +23,8 @@ #include "sharedNetwork/NetworkSetupData.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace ConnectionServerConnectionNamespace @@ -40,48 +40,50 @@ struct OnConnectionServerConnectionClosed {}; //----------------------------------------------------------------------- ConnectionServerConnection::ConnectionServerConnection(const std::string & a, const uint16 p) : -ServerConnection (a, p, NetworkSetupData()), -m_chatServicePort (0), -m_csServicePort (0), -m_clientServicePortPrivate (0), -m_clientServicePortPublic (0), -m_gameServicePort (0), -m_id (0), -m_pingPort (0), -m_connectionServerNumber (0), -m_gameServiceAddress (), -m_playerCount (0), -m_freeTrialCount (0), -m_emptySceneCount (0), -m_tutorialSceneCount (0), -m_falconSceneCount (0), -m_clientServiceAddress (), -m_chatServiceAddress (), -m_customerServiceAddress () + ServerConnection(a, p, NetworkSetupData()), + m_chatServicePort(0), + m_csServicePort(0), + m_clientServicePortPrivate(0), + m_clientServicePortPublic(0), + m_gameServicePort(0), + m_id(0), + m_pingPort(0), + m_connectionServerNumber(0), + m_gameServiceAddress(), + m_playerCount(0), + m_freeTrialCount(0), + m_emptySceneCount(0), + m_tutorialSceneCount(0), + m_falconSceneCount(0), + m_clientServiceAddress(), + m_chatServiceAddress(), + m_customerServiceAddress(), + m_voiceChatServicePort(0) { } //----------------------------------------------------------------------- ConnectionServerConnection::ConnectionServerConnection(UdpConnectionMT * u, TcpClient * t) : -ServerConnection (u, t), -m_chatServicePort (0), -m_csServicePort (0), -m_clientServicePortPrivate (0), -m_clientServicePortPublic (0), -m_gameServicePort (0), -m_id (0), -m_pingPort (0), -m_connectionServerNumber (0), -m_gameServiceAddress (), -m_playerCount (0), -m_freeTrialCount (0), -m_emptySceneCount (0), -m_tutorialSceneCount (0), -m_falconSceneCount (0), -m_clientServiceAddress (), -m_chatServiceAddress (), -m_customerServiceAddress () + ServerConnection(u, t), + m_chatServicePort(0), + m_csServicePort(0), + m_clientServicePortPrivate(0), + m_clientServicePortPublic(0), + m_gameServicePort(0), + m_id(0), + m_pingPort(0), + m_connectionServerNumber(0), + m_gameServiceAddress(), + m_playerCount(0), + m_freeTrialCount(0), + m_emptySceneCount(0), + m_tutorialSceneCount(0), + m_falconSceneCount(0), + m_clientServiceAddress(), + m_chatServiceAddress(), + m_customerServiceAddress(), + m_voiceChatServicePort(0) { } @@ -89,12 +91,12 @@ m_customerServiceAddress () ConnectionServerConnection::~ConnectionServerConnection() { - // remove ConnectionServerConnection *'s from the + // remove ConnectionServerConnection *'s from the // s_pseudoClientConnectionMap std::map >::iterator i; - for(i = s_pseudoClientConnectionMap.begin(); i != s_pseudoClientConnectionMap.end();) + for (i = s_pseudoClientConnectionMap.begin(); i != s_pseudoClientConnectionMap.end();) { - if(i->second.second == this) + if (i->second.second == this) { if (i->second.first == TransferRequestMoveValidation::TRS_transfer_server) { @@ -121,7 +123,7 @@ bool ConnectionServerConnection::sendToPseudoClientConnection(unsigned int stati { bool result = false; std::map >::iterator f = s_pseudoClientConnectionMap.find(stationId); - if(f != s_pseudoClientConnectionMap.end()) + if (f != s_pseudoClientConnectionMap.end()) { result = true; f->second.second->send(message, true); @@ -166,239 +168,256 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message) { Archive::ReadIterator ri = message.begin(); GameNetworkMessage m(ri); - ri = message.begin(); + ri = message.begin(); + + const uint32 messageType = m.getType(); - if(m.isType("NewCentralConnectionServer")) - { - const NewCentralConnectionServer ncs(ri); - - m_chatServicePort = ncs.getChatServicePort(); - m_csServicePort = ncs.getCustomerServicePort(); - - m_clientServicePortPrivate = ncs.getClientServicePortPrivate(); - m_clientServicePortPublic = ncs.getClientServicePortPublic(); - m_gameServicePort = ncs.getGameServicePort(); - m_pingPort = ncs.getPingPort (); - m_connectionServerNumber = ncs.getConnectionServerNumber(); - m_gameServiceAddress = ncs.getGameServiceAddress(); - m_clientServiceAddress = ncs.getClientServiceAddress(); - m_chatServiceAddress = ncs.getChatServiceAddress(); - m_customerServiceAddress = ncs.getCustomerServiceAddress(); - - CentralServer::getInstance().addConnectionServerConnection(this); - - //Now broadcast to gameservers - ConnectionServerAddress const addressMessage(m_gameServiceAddress, m_gameServicePort); - CentralServer::getInstance().broadcastToGameServers(addressMessage); - - //Send to chat server - const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); - EnumerateServers e(true, getChatServiceAddress(), getChatServicePort(), ct); - - if (!getChatServiceAddress().empty() && (getChatServicePort() != 0)) + switch(messageType) { + case constcrc("NewCentralConnectionServer") : { - CentralServer::getInstance().broadcastToChatServers(e); + const NewCentralConnectionServer ncs(ri); + + m_chatServicePort = ncs.getChatServicePort(); + m_csServicePort = ncs.getCustomerServicePort(); + + m_clientServicePortPrivate = ncs.getClientServicePortPrivate(); + m_clientServicePortPublic = ncs.getClientServicePortPublic(); + m_gameServicePort = ncs.getGameServicePort(); + m_pingPort = ncs.getPingPort(); + m_connectionServerNumber = ncs.getConnectionServerNumber(); + m_gameServiceAddress = ncs.getGameServiceAddress(); + m_clientServiceAddress = ncs.getClientServiceAddress(); + m_chatServiceAddress = ncs.getChatServiceAddress(); + m_customerServiceAddress = ncs.getCustomerServiceAddress(); + + CentralServer::getInstance().addConnectionServerConnection(this); + + //Now broadcast to gameservers + ConnectionServerAddress const addressMessage(m_gameServiceAddress, m_gameServicePort); + CentralServer::getInstance().broadcastToGameServers(addressMessage); + + //Send to chat server + const int ct = static_cast(EnumerateServers::CONNECTION_SERVER); + EnumerateServers e(true, getChatServiceAddress(), getChatServicePort(), ct); + + if (!getChatServiceAddress().empty() && (getChatServicePort() != 0)) + { + CentralServer::getInstance().broadcastToChatServers(e); + } + else + { + LOG("ChatServ", ("ConnectionServerConnection::onReceive() Chat service address and port are invalid, unable to CentralServer::getInstance().broadcastToChatServers()")); + } + + //Send to CS servers + const EnumerateServers e2(true, getCustomerServiceAddress(), getCustomerServicePort(), ct); + + if (!getCustomerServiceAddress().empty() + && (getCustomerServicePort() != 0)) + { + CentralServer::getInstance().broadcastToCustomerServiceServers(e2); + } + else + { + LOG("ChatServ", ("ConnectionServerConnection::onReceive() Customer service address and port are invalid, unable to CentralServer::getInstance().broadcastToCustomerServiceServers()")); + } + + //Send to login Servers + if ((getClientServicePortPrivate() != 0) || (getClientServicePortPublic() != 0)) + { + const LoginConnectionServerAddress csa(m_id, getClientServiceAddress(), getClientServicePortPrivate(), + getClientServicePortPublic(), getPlayerCount(), getPingPort()); + CentralServer::getInstance().sendToAllLoginServers(csa); + } + break; } - else + case constcrc("UpdateConnectionServerStatus") : { - LOG("ChatServ", ("ConnectionServerConnection::onReceive() Chat service address and port are invalid, unable to CentralServer::getInstance().broadcastToChatServers()")); + DEBUG_REPORT_LOG(true, ("Got update status for connection server\n")); + const UpdateConnectionServerStatus ucs(ri); + m_clientServicePortPublic = ucs.getPublicPort(); + m_clientServicePortPrivate = ucs.getPrivatePort(); + UpdateLoginConnectionServerStatus ulc(getId(), m_clientServicePortPublic, m_clientServicePortPrivate, getPlayerCount()); + CentralServer::getInstance().sendToAllLoginServers(ulc); + break; } - //Send to CS servers - const EnumerateServers e2(true, getCustomerServiceAddress(), getCustomerServicePort(), ct); - - if ( !getCustomerServiceAddress().empty() - && (getCustomerServicePort() != 0)) + case constcrc("TaskSpawnProcess") : { - CentralServer::getInstance().broadcastToCustomerServiceServers(e2); + const TaskSpawnProcess spawn(ri); + CentralServer::getInstance().sendTaskMessage(spawn); + break; } - else + case constcrc("NewPseudoClientConnection") : { - LOG("ChatServ", ("ConnectionServerConnection::onReceive() Customer service address and port are invalid, unable to CentralServer::getInstance().broadcastToCustomerServiceServers()")); - } + const GenericValueTypeMessage > info(ri); + s_pseudoClientConnectionMap[info.getValue().first] = std::make_pair(static_cast(info.getValue().second), this); - //Send to login Servers - if ( (getClientServicePortPrivate() != 0) || (getClientServicePortPublic() != 0) ) + // remove corresponding "non pseudo client connection" + CentralServer::getInstance().removeFromAccountConnectionMap(static_cast(info.getValue().first)); + break; + } + case constcrc("DestroyPseudoClientConnection") : { - const LoginConnectionServerAddress csa(m_id, getClientServiceAddress(), getClientServicePortPrivate(), - getClientServicePortPublic(), getPlayerCount(), getPingPort ()); - CentralServer::getInstance().sendToAllLoginServers(csa); + const GenericValueTypeMessage info(ri); + std::map >::iterator f = s_pseudoClientConnectionMap.find(info.getValue()); + if (f != s_pseudoClientConnectionMap.end()) + { + s_pseudoClientConnectionMap.erase(f); + } + break; } - } - else if (m.isType("UpdateConnectionServerStatus")) - { - DEBUG_REPORT_LOG(true, ("Got update status for connection server\n")); - const UpdateConnectionServerStatus ucs(ri); - m_clientServicePortPublic = ucs.getPublicPort(); - m_clientServicePortPrivate = ucs.getPrivatePort(); - UpdateLoginConnectionServerStatus ulc(getId(), m_clientServicePortPublic, m_clientServicePortPrivate, getPlayerCount()); - CentralServer::getInstance().sendToAllLoginServers(ulc); - } - - else if(m.isType("TaskSpawnProcess")) - { - const TaskSpawnProcess spawn(ri); - CentralServer::getInstance().sendTaskMessage(spawn); - } - else if(m.isType("NewPseudoClientConnection")) - { - const GenericValueTypeMessage > info(ri); - s_pseudoClientConnectionMap[info.getValue().first] = std::make_pair(static_cast(info.getValue().second), this); - - // remove corresponding "non pseudo client connection" - CentralServer::getInstance().removeFromAccountConnectionMap(static_cast(info.getValue().first)); - } - else if(m.isType("DestroyPseudoClientConnection")) - { - const GenericValueTypeMessage info(ri); - std::map >::iterator f = s_pseudoClientConnectionMap.find(info.getValue()); - if(f != s_pseudoClientConnectionMap.end()) + case constcrc("TransferReceiveDataFromGameServer") : { - s_pseudoClientConnectionMap.erase(f); - } - } - else if(m.isType("TransferReceiveDataFromGameServer")) - { - const GenericValueTypeMessage transferReply(ri); + const GenericValueTypeMessage transferReply(ri); - if(transferReply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + if (transferReply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(transferReply); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Got TransferReceiveDataFromGameServer: %s", transferReply.getValue().toString().c_str())); + + // send character to ConnectionServer for creation on the destination server + GenericValueTypeMessage login("TransferLoginCharacterToDestinationServer", transferReply.getValue()); + CentralServer::getInstance().sendToArbitraryLoginServer(login); + LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToDestinationServer to CentralServer (via LoginServer) (%s) for (%s)", transferReply.getValue().getDestinationGalaxy().c_str(), login.getValue().toString().c_str())); + } + break; + } + case constcrc("ApplyTransferDataSuccess") : { - CentralServer::getInstance().sendToTransferServer(transferReply); + const GenericValueTypeMessage success(ri); + + // send message to source galaxy (via LoginServer) to mark + // the source character as having been transferred to prevent + // all future login of the character + { + const GenericValueTypeMessage > msg("CtsCompletedForcharacter", std::make_pair(success.getValue().getSourceGalaxy(), success.getValue().getCharacterId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); + } + + // send the message back to the transfer server, which then + // sends a disable login request to the source central server, + // "removing" the account on the source galaxy. + if (success.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(success); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from ConnectionServer. %s", success.getValue().toString().c_str())); + LOG("CustomerService", ("CharacterTransfer: Sending ToggleAvatarLoginStatus request to LoginServer")); + + const ToggleAvatarLoginStatus toggleLoginStatus(success.getValue().getSourceGalaxy(), success.getValue().getSourceStationId(), success.getValue().getCharacterId(), false); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(toggleLoginStatus)); + } + break; } - else + case constcrc("ApplyTransferDataFail") : { - LOG("CustomerService", ("CharacterTransfer: Got TransferReceiveDataFromGameServer: %s", transferReply.getValue().toString().c_str())); + const GenericValueTypeMessage fail(ri); - // send character to ConnectionServer for creation on the destination server - GenericValueTypeMessage login("TransferLoginCharacterToDestinationServer", transferReply.getValue()); - CentralServer::getInstance().sendToArbitraryLoginServer(login); - LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToDestinationServer to CentralServer (via LoginServer) (%s) for (%s)", transferReply.getValue().getDestinationGalaxy().c_str(), login.getValue().toString().c_str())); + // send the message back to the transfer server, which then + // sends a delete request to the destination central server, + // "removing" the account on the destination galaxy. + if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(fail); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from ConnectionServer. %s", fail.getValue().toString().c_str())); + LOG("CustomerService", ("CharacterTransfer: failed to apply transfer data. Deleting character on destination server. %s", fail.getValue().toString().c_str())); + + GenericValueTypeMessage const deleteCharacter("DeleteFailedTransfer", fail.getValue()); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(deleteCharacter)); + + GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); + + GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); + } + break; } - } - else if(m.isType("ApplyTransferDataSuccess")) - { - const GenericValueTypeMessage success(ri); - - // send message to source galaxy (via LoginServer) to mark - // the source character as having been transferred to prevent - // all future login of the character + case constcrc("TransferCreateCharacterFailed") : { - const GenericValueTypeMessage > msg("CtsCompletedForcharacter", std::make_pair(success.getValue().getSourceGalaxy(), success.getValue().getCharacterId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); - } + const GenericValueTypeMessage fail(ri); - // send the message back to the transfer server, which then - // sends a disable login request to the source central server, - // "removing" the account on the source galaxy. - if(success.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(fail); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Received TransferCreateCharacterFailed. %s", fail.getValue().toString().c_str())); + + GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); + + GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); + } + break; + } + case constcrc("ReplyTransferDataFail") : { - CentralServer::getInstance().sendToTransferServer(success); + const GenericValueTypeMessage reply(ri); + + if (reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(reply); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Transfer failed: Failed to retrieve character data. %s", reply.getValue().toString().c_str())); + + GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(reply.getValue().getSourceGalaxy(), reply.getValue().getSourceStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); + + GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(reply.getValue().getDestinationGalaxy(), reply.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); + } + break; } - else + case constcrc("TransferFailGameServerClosedConnectionWithConnectionServer") : { - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from ConnectionServer. %s", success.getValue().toString().c_str())); - LOG("CustomerService", ("CharacterTransfer: Sending ToggleAvatarLoginStatus request to LoginServer")); + const GenericValueTypeMessage fail(ri); - const ToggleAvatarLoginStatus toggleLoginStatus(success.getValue().getSourceGalaxy(), success.getValue().getSourceStationId(), success.getValue().getCharacterId(), false); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(toggleLoginStatus)); + if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + CentralServer::getInstance().sendToTransferServer(fail); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Transfer failed: GameServer connection closed while transfer was in progress. %s", fail.getValue().toString().c_str())); + + GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); + + GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); + } + break; } - } - else if(m.isType("ApplyTransferDataFail")) - { - const GenericValueTypeMessage fail(ri); - - // send the message back to the transfer server, which then - // sends a delete request to the destination central server, - // "removing" the account on the destination galaxy. - if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + case constcrc("AccountFeatureIdRequest") : { - CentralServer::getInstance().sendToTransferServer(fail); + const AccountFeatureIdRequest msg(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(msg); + break; } - else + case constcrc("AdjustAccountFeatureIdRequest") : { - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from ConnectionServer. %s", fail.getValue().toString().c_str())); - LOG("CustomerService", ("CharacterTransfer: failed to apply transfer data. Deleting character on destination server. %s", fail.getValue().toString().c_str())); - - GenericValueTypeMessage const deleteCharacter("DeleteFailedTransfer", fail.getValue()); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(deleteCharacter)); - - GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); - - GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); + const AdjustAccountFeatureIdRequest msg(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(msg); + break; } - } - else if(m.isType("TransferCreateCharacterFailed")) - { - const GenericValueTypeMessage fail(ri); - - if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + default : { - CentralServer::getInstance().sendToTransferServer(fail); + ServerConnection::onReceive(message); } - else - { - LOG("CustomerService", ("CharacterTransfer: Received TransferCreateCharacterFailed. %s", fail.getValue().toString().c_str())); - - GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); - - GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); - } - } - else if(m.isType("ReplyTransferDataFail")) - { - const GenericValueTypeMessage reply(ri); - - if(reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) - { - CentralServer::getInstance().sendToTransferServer(reply); - } - else - { - LOG("CustomerService", ("CharacterTransfer: Transfer failed: Failed to retrieve character data. %s", reply.getValue().toString().c_str())); - - GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(reply.getValue().getSourceGalaxy(), reply.getValue().getSourceStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); - - GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(reply.getValue().getDestinationGalaxy(), reply.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); - } - } - else if(m.isType("TransferFailGameServerClosedConnectionWithConnectionServer")) - { - const GenericValueTypeMessage fail(ri); - - if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) - { - CentralServer::getInstance().sendToTransferServer(fail); - } - else - { - LOG("CustomerService", ("CharacterTransfer: Transfer failed: GameServer connection closed while transfer was in progress. %s", fail.getValue().toString().c_str())); - - GenericValueTypeMessage > const closeRequestSource("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getSourceGalaxy(), fail.getValue().getSourceStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestSource)); - - GenericValueTypeMessage > const closeRequestTarget("RequestTransferClosePseudoClientConnection", std::make_pair(fail.getValue().getDestinationGalaxy(), fail.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget)); - } - } - else if(m.isType("AccountFeatureIdRequest")) - { - const AccountFeatureIdRequest msg(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(msg); - } - else if(m.isType("AdjustAccountFeatureIdRequest")) - { - const AdjustAccountFeatureIdRequest msg(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(msg); - } - else - { - ServerConnection::onReceive(message); } } @@ -408,7 +427,7 @@ ConnectionServerConnection * ConnectionServerConnection::getConnectionForAccount { ConnectionServerConnection * result = 0; std::map >::iterator f = s_pseudoClientConnectionMap.find(stationId); - if(f != s_pseudoClientConnectionMap.end()) + if (f != s_pseudoClientConnectionMap.end()) { result = f->second.second; } @@ -424,4 +443,4 @@ void ConnectionServerConnection::removeFromAccountConnectionMap(unsigned int sta { s_pseudoClientConnectionMap.erase(f); } -} +} \ No newline at end of file diff --git a/engine/server/application/CentralServer/src/shared/ConsoleCommandParserGame.cpp b/engine/server/application/CentralServer/src/shared/ConsoleCommandParserGame.cpp index 3231ecff..5c5f351d 100755 --- a/engine/server/application/CentralServer/src/shared/ConsoleCommandParserGame.cpp +++ b/engine/server/application/CentralServer/src/shared/ConsoleCommandParserGame.cpp @@ -117,8 +117,8 @@ bool ConsoleCommandParserGame::performParsing(const NetworkId & track, const Str if( argv.size() > 4 ) { LOG("ServerConsole", ("Received command to shutdown the cluster.")); - uint32 timeToShutdown = strtoul(Unicode::wideToNarrow(argv[2]).c_str(), NULL, 10); - uint32 maxTime = strtoul(Unicode::wideToNarrow(argv[3]).c_str(), NULL, 10); + uint32 timeToShutdown = strtoul(Unicode::wideToNarrow(argv[2]).c_str(), nullptr, 10); + uint32 maxTime = strtoul(Unicode::wideToNarrow(argv[3]).c_str(), nullptr, 10); Unicode::String systemMessage = Unicode::narrowToWide(""); for(unsigned int i = 4; i < argv.size(); ++i) { @@ -141,7 +141,7 @@ bool ConsoleCommandParserGame::performParsing(const NetworkId & track, const Str { if(argv.size() > 1) { - unsigned int stationId = strtoul(Unicode::wideToNarrow(argv[2]).c_str(), NULL, 10); + unsigned int stationId = strtoul(Unicode::wideToNarrow(argv[2]).c_str(), nullptr, 10); if(stationId > 0) { GenericValueTypeMessage auth("AuthorizeDownload", stationId); diff --git a/engine/server/application/CentralServer/src/shared/ConsoleManager.cpp b/engine/server/application/CentralServer/src/shared/ConsoleManager.cpp index d162fbb3..6535d3db 100755 --- a/engine/server/application/CentralServer/src/shared/ConsoleManager.cpp +++ b/engine/server/application/CentralServer/src/shared/ConsoleManager.cpp @@ -16,7 +16,7 @@ namespace ConsoleManagerNamespace { - ConsoleCommandParser * s_consoleCommandParserRoot = NULL; + ConsoleCommandParser * s_consoleCommandParserRoot = nullptr; } using namespace ConsoleManagerNamespace; diff --git a/engine/server/application/CentralServer/src/shared/GameServerConnection.cpp b/engine/server/application/CentralServer/src/shared/GameServerConnection.cpp index f3194b97..ac6edcb8 100755 --- a/engine/server/application/CentralServer/src/shared/GameServerConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/GameServerConnection.cpp @@ -36,6 +36,8 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "unicodeArchive/UnicodeArchive.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== GameServerConnection::GameServerConnection(UdpConnectionMT *u, TcpClient *t) : @@ -88,289 +90,331 @@ void GameServerConnection::onReceive(Archive::ByteStream const &message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage const m(ri); ri = message.begin(); + + const uint32 messageType = m.getType(); - if (m.isType("CentralGameServerConnect")) - { - CentralGameServerConnect const c(ri); - setClientServiceAddress(c.getClientServiceAddress()); - setClientServicePort(c.getClientServicePort()); - setGameServiceAddress(c.getGameServiceAddress()); - setGameServicePort(c.getGameServicePort()); - setSceneId(c.getVolumeName()); - } - else if (m.isType("GameServerUniverseLoadedMessage")) - { - m_ready = true; - - if (ConfigCentralServer::getGameServerConnectionPendingAllocatedSizeLimit() != 0) - setTcpClientPendingSendAllocatedSizeLimit(0); - } - else if (m.isType("TaskSpawnProcess")) - { - TaskSpawnProcess const spawn(ri); - CentralServer::getInstance().sendTaskMessage(spawn); - } - else if (m.isType("ConGenericMessage")) - { - ConGenericMessage const con(ri); - ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); - } - else if (m.isType("TransferReplyNameValidation")) - { - GenericValueTypeMessage > const replyNameValidation(ri); - - if (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + switch(messageType) { + case constcrc("CentralGameServerConnect") : { - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from GameServer, forwarding to TransferServer : %s", replyNameValidation.getValue().second.toString().c_str())); - CentralServer::getInstance().sendToTransferServer(replyNameValidation); + CentralGameServerConnect const c(ri); + setClientServiceAddress(c.getClientServiceAddress()); + setClientServicePort(c.getClientServicePort()); + setGameServiceAddress(c.getGameServiceAddress()); + setGameServicePort(c.getGameServicePort()); + setSceneId(c.getVolumeName()); + break; } - else + case constcrc("GameServerUniverseLoadedMessage") : { - // pass reply back to the source galaxy for handling, which is to - // either display an error message to the user if the request failed, - // or to start the transfer process if the request succeeds - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from GameServer, forwarding to source galaxy CentralServer : %s", replyNameValidation.getValue().second.toString().c_str())); - CentralServer::getInstance().sendToArbitraryLoginServer(replyNameValidation); + m_ready = true; - // if the request succeeded, also disconnect any clients with a connection to SWG services on this (the target) galaxy - if (replyNameValidation.getValue().second.getIsValidName() && (replyNameValidation.getValue().second.getTransferRequestSource() != TransferRequestMoveValidation::TRS_ingame_freects_command_validate) && (replyNameValidation.getValue().second.getTransferRequestSource() != TransferRequestMoveValidation::TRS_ingame_cts_command_validate)) + if (ConfigCentralServer::getGameServerConnectionPendingAllocatedSizeLimit() != 0) + setTcpClientPendingSendAllocatedSizeLimit(0); + break; + } + case constcrc("TaskSpawnProcess") : + { + TaskSpawnProcess const spawn(ri); + CentralServer::getInstance().sendTaskMessage(spawn); + break; + } + case constcrc("ConGenericMessage") : + { + ConGenericMessage const con(ri); + ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + break; + } + case constcrc("TransferReplyNameValidation") : + { + GenericValueTypeMessage > const replyNameValidation(ri); + + if (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) { - GenericValueTypeMessage kickSource("TransferKickConnectedClients", replyNameValidation.getValue().second.getSourceStationId()); - GenericValueTypeMessage kickDestination("TransferKickConnectedClients", replyNameValidation.getValue().second.getDestinationStationId()); - CentralServer::getInstance().sendToAllLoginServers(kickSource); - CentralServer::getInstance().sendToAllLoginServers(kickDestination); - CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); - CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from GameServer, forwarding to TransferServer : %s", replyNameValidation.getValue().second.toString().c_str())); + CentralServer::getInstance().sendToTransferServer(replyNameValidation); } + else + { + // pass reply back to the source galaxy for handling, which is to + // either display an error message to the user if the request failed, + // or to start the transfer process if the request succeeds + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from GameServer, forwarding to source galaxy CentralServer : %s", replyNameValidation.getValue().second.toString().c_str())); + CentralServer::getInstance().sendToArbitraryLoginServer(replyNameValidation); + + // if the request succeeded, also disconnect any clients with a connection to SWG services on this (the target) galaxy + if (replyNameValidation.getValue().second.getIsValidName() && (replyNameValidation.getValue().second.getTransferRequestSource() != TransferRequestMoveValidation::TRS_ingame_freects_command_validate) && (replyNameValidation.getValue().second.getTransferRequestSource() != TransferRequestMoveValidation::TRS_ingame_cts_command_validate)) + { + GenericValueTypeMessage kickSource("TransferKickConnectedClients", replyNameValidation.getValue().second.getSourceStationId()); + GenericValueTypeMessage kickDestination("TransferKickConnectedClients", replyNameValidation.getValue().second.getDestinationStationId()); + CentralServer::getInstance().sendToAllLoginServers(kickSource); + CentralServer::getInstance().sendToAllLoginServers(kickDestination); + CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); + CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); + } + } + break; } - } - else if (m.isType("TransferReplyCharacterList")) - { - // forward the message to the TransferServer - TransferReplyCharacterList const reply(ri); - CentralServer::getInstance().sendToTransferServer(reply); - } - else if (m.isType("TransferRenameCharacterReplyFromDatabase")) - { - GenericValueTypeMessage const renameReplyFromDatabase(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReplyFromDatabase %s", renameReplyFromDatabase.getValue().toString().c_str())); - if (renameReplyFromDatabase.getValue().getIsValidName()) + case constcrc("TransferReplyCharacterList") : { - // forward to LoginServer - LOG("CustomerService", ("CharacterTransfer: Sending TransferRenameCharacterInLoginDatabase request to Login Database")); - GenericValueTypeMessage const request("TransferRenameCharacterInLoginDatabase", renameReplyFromDatabase.getValue()); - CentralServer::getInstance().sendToArbitraryLoginServer(request); + // forward the message to the TransferServer + TransferReplyCharacterList const reply(ri); + CentralServer::getInstance().sendToTransferServer(reply); + break; } - else + case constcrc("TransferRenameCharacterReplyFromDatabase") : { - // send failure back to TransferServer - LOG("CustomerService", ("CharacterTransfer: Character rename request failed in the game database. %s", renameReplyFromDatabase.getValue().toString().c_str())); - GenericValueTypeMessage const transferRenameCharacterReply("TransferRenameCharacterReply", renameReplyFromDatabase.getValue()); + GenericValueTypeMessage const renameReplyFromDatabase(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReplyFromDatabase %s", renameReplyFromDatabase.getValue().toString().c_str())); + if (renameReplyFromDatabase.getValue().getIsValidName()) + { + // forward to LoginServer + LOG("CustomerService", ("CharacterTransfer: Sending TransferRenameCharacterInLoginDatabase request to Login Database")); + GenericValueTypeMessage const request("TransferRenameCharacterInLoginDatabase", renameReplyFromDatabase.getValue()); + CentralServer::getInstance().sendToArbitraryLoginServer(request); + } + else + { + // send failure back to TransferServer + LOG("CustomerService", ("CharacterTransfer: Character rename request failed in the game database. %s", renameReplyFromDatabase.getValue().toString().c_str())); + GenericValueTypeMessage const transferRenameCharacterReply("TransferRenameCharacterReply", renameReplyFromDatabase.getValue()); + } + break; } - } - else if (m.isType("LocateObject")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LocateObjectByTemplateName")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LocateObjectResponseMessage")) - { - LocateObjectResponseMessage const msg(ri); - CentralServer::getInstance().sendToGameServer(msg.getResponsePid(), msg, true); - } - else if (m.isType("LocatePlayerByPartialName")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LocateWarden")) - { - GenericValueTypeMessage > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LocateCreatureByCreatureName")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LocatePlayerResponseMessage")) - { - LocatePlayerResponseMessage const msg(ri); - CentralServer::getInstance().sendToGameServer(msg.getResponsePid(), msg, true); - } - else if (m.isType("LSBOIReq")) - { - GenericValueTypeMessage, std::pair, NetworkId> > > const locateStructureByOwnerIdReq(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(locateStructureByOwnerIdReq, true); - } - else if (m.isType("LSBOIRsp")) - { - GenericValueTypeMessage, std::vector > > const locateStructureByOwnerIdRsp(ri); - CentralServer::getInstance().sendToGameServer(locateStructureByOwnerIdRsp.getValue().first.first, locateStructureByOwnerIdRsp, true); - } - else if (m.isType("ReportSystemClockTime")) - { - GenericValueTypeMessage > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("ReportSystemClockTimeResponse")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToGameServer(msg.getValue().first, msg, true); - } - else if (m.isType("ReportPlanetaryTime")) - { - GenericValueTypeMessage > const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("ReportPlanetaryTimeResponse")) - { - GenericValueTypeMessage > > const msg(ri); - CentralServer::getInstance().sendToGameServer(msg.getValue().first, msg, true); - } - else if (m.isType("TeleportToMessage")) - { - TeleportToMessage const msg(ri); - CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); - } - else if (m.isType("LoginToggleCompletedTutorial")) - { - GenericValueTypeMessage< std::pair > const msg(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(msg); - } - else if( m.isType( "GameServerCSResponse" ) ) - { - GameServerCSResponseMessage const msg( ri ); - CSToolResponse rmsg( msg.getAccountId(), - msg.getResponse(), - msg.getToolId() ); - CentralServer::getInstance().sendToLoginServer( msg.getLoginServerID(), rmsg ); - } - else if( m.isType( "GetCharactersForAccountCSReplyMsg" ) ) - { - GetCharactersForAccountCSReplyMsg const msg( ri ); - // send repsonse to tool. - char buf[ 256 ]; - snprintf( buf, 255, "Character search for %lu\r\n", msg.getTargetAccountId() ); - std::string response = buf; - response = response + msg.getResponse(); - - CSToolResponse rmsg( msg.getAccountId(), - response, - msg.getToolId() ); - CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); - } - else if( m.isType( "GetDeletedItemsReplyMessage" ) ) - { - GetDeletedItemsReplyMessage const msg( ri ); - char buf[ 256 ]; - snprintf( buf, 255, "Deleted items for %s\r\n", msg.getCharacterId().getValueString().c_str() ); - std::string response = buf; - response = response + msg.getResponse(); - CSToolResponse rmsg( msg.getAccountId(), - response, - msg.getToolId() ); - CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); - - } - else if( m.isType( "GetCharacterIdReplyMessage" ) ) - { - GetCharacterIdReplyMessage const msg( ri ); - std::string response = "Character id for "; - response = response + msg.getCharacterName() + "\r\n"; - response = response + "character id:" + msg.getCharacterId().getValueString() + "\r\n"; - char buf[ 64 ]; - - snprintf( buf, 64, "%lu", msg.getAccountId() ); - - response = response + "account id:" + buf + "\r\n"; - - CSToolResponse rmsg( msg.getAccountId(), response, msg.getToolId() ); - CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); - - } - else if( m.isType( "CSFindAuthObjectReply" ) ) - { - GenericValueTypeMessage< std::pair< unsigned int, bool > > const msg( ri ); - CentralCSHandler::getInstance().handleFindObjectResponse( msg.getValue().first, msg.getValue().second ); - } - else if(m.isType("StructureListMessage")) - { - StructureListMessage msg(ri); - CentralCSHandler::getInstance().handleStructureListResponse(msg); - } - else if (m.isType("SPCharacterProfileMessage")) - { - SPCharacterProfileMessage const msg(ri); - CentralServer::getInstance().sendToStationPlayersCollector(msg); - } - else if (m.isType("OccupyUnlockedSlotReq")) - { - GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(occupyUnlockedSlotReq); - } - else if (m.isType("VacateUnlockedSlotReq")) - { - GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(vacateUnlockedSlotReq); + case constcrc("LocateObject") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LocateObjectByTemplateName") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LocateObjectResponseMessage") : + { + LocateObjectResponseMessage const msg(ri); + CentralServer::getInstance().sendToGameServer(msg.getResponsePid(), msg, true); + break; + } + case constcrc("LocatePlayerByPartialName") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LocateWarden") : + { + GenericValueTypeMessage > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LocateCreatureByCreatureName") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LocatePlayerResponseMessage") : + { + LocatePlayerResponseMessage const msg(ri); + CentralServer::getInstance().sendToGameServer(msg.getResponsePid(), msg, true); + break; + } + case constcrc("LSBOIReq") : + { + GenericValueTypeMessage, std::pair, NetworkId> > > const locateStructureByOwnerIdReq(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(locateStructureByOwnerIdReq, true); + break; + } + case constcrc("LSBOIRsp") : + { + GenericValueTypeMessage, std::vector > > const locateStructureByOwnerIdRsp(ri); + CentralServer::getInstance().sendToGameServer(locateStructureByOwnerIdRsp.getValue().first.first, locateStructureByOwnerIdRsp, true); + break; + } + case constcrc("ReportSystemClockTime") : + { + GenericValueTypeMessage > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("ReportSystemClockTimeResponse") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToGameServer(msg.getValue().first, msg, true); + break; + } + case constcrc("ReportPlanetaryTime") : + { + GenericValueTypeMessage > const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("ReportPlanetaryTimeResponse") : + { + GenericValueTypeMessage > > const msg(ri); + CentralServer::getInstance().sendToGameServer(msg.getValue().first, msg, true); + break; + } + case constcrc("TeleportToMessage") : + { + TeleportToMessage const msg(ri); + CentralServer::getInstance().sendToAllGameServersExceptDBProcess(msg, true); + break; + } + case constcrc("LoginToggleCompletedTutorial") : + { + GenericValueTypeMessage< std::pair > const msg(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(msg); + break; + } + case constcrc("GameServerCSResponse" ) : + { + GameServerCSResponseMessage const msg( ri ); + CSToolResponse rmsg( msg.getAccountId(), + msg.getResponse(), + msg.getToolId() ); + CentralServer::getInstance().sendToLoginServer( msg.getLoginServerID(), rmsg ); + break; + } + case constcrc("GetCharactersForAccountCSReplyMsg" ) : + { + GetCharactersForAccountCSReplyMsg const msg( ri ); + // send repsonse to tool. + char buf[ 256 ]; + snprintf( buf, 255, "Character search for %lu\r\n", msg.getTargetAccountId() ); + std::string response = buf; + response = response + msg.getResponse(); + + CSToolResponse rmsg( msg.getAccountId(), + response, + msg.getToolId() ); + CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); + break; + } + case constcrc("GetDeletedItemsReplyMessage" ) : + { + GetDeletedItemsReplyMessage const msg( ri ); + char buf[ 256 ]; + snprintf( buf, 255, "Deleted items for %s\r\n", msg.getCharacterId().getValueString().c_str() ); + std::string response = buf; + response = response + msg.getResponse(); + CSToolResponse rmsg( msg.getAccountId(), + response, + msg.getToolId() ); + CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); + break; + + } + case constcrc("GetCharacterIdReplyMessage" ) : + { + GetCharacterIdReplyMessage const msg( ri ); + std::string response = "Character id for "; + response = response + msg.getCharacterName() + "\r\n"; + response = response + "character id:" + msg.getCharacterId().getValueString() + "\r\n"; + char buf[ 64 ]; + + snprintf( buf, 64, "%lu", msg.getAccountId() ); + + response = response + "account id:" + buf + "\r\n"; + + CSToolResponse rmsg( msg.getAccountId(), response, msg.getToolId() ); + CentralServer::getInstance().sendToLoginServer( msg.getLoginServerId(), rmsg ); + break; + + } + case constcrc("CSFindAuthObjectReply" ) : + { + GenericValueTypeMessage< std::pair< unsigned int, bool > > const msg( ri ); + CentralCSHandler::getInstance().handleFindObjectResponse( msg.getValue().first, msg.getValue().second ); + break; + } + case constcrc("StructureListMessage") : + { + StructureListMessage msg(ri); + CentralCSHandler::getInstance().handleStructureListResponse(msg); + break; + } + case constcrc("SPCharacterProfileMessage") : + { + SPCharacterProfileMessage const msg(ri); + CentralServer::getInstance().sendToStationPlayersCollector(msg); + break; + } + case constcrc("OccupyUnlockedSlotReq") : + { + GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(occupyUnlockedSlotReq); + break; + } + case constcrc("VacateUnlockedSlotReq") : + { + GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(vacateUnlockedSlotReq); - // to safeguard against any sort of timing exploit to create another normal - // slot character while this one is being converted to normal, thus allowing - // the account to have more normal slot characters on this cluster than is - // allowed, set the "creating characters too rapidly" flag to prevent any - // character creation on the account on this cluster for a while - CharacterCreationTracker::getInstance().setFastCreationLock(vacateUnlockedSlotReq.getValue().first.first); - } - else if (m.isType("SwapUnlockedSlotReq")) - { - GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(swapUnlockedSlotReq); - } - else if (m.isType("FeatureIdTransactionRequest")) - { - FeatureIdTransactionRequest const fitr(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(fitr); - } - else if (m.isType("FeatureIdTransactionSyncUpdate")) - { - FeatureIdTransactionSyncUpdate const fitsu(ri); - CentralServer::getInstance().sendToArbitraryLoginServer(fitsu); - } - else if (m.isType("AllCluserGlobalChannel")) - { - typedef std::pair, bool> PayloadType; - GenericValueTypeMessage msg(ri); + // to safeguard against any sort of timing exploit to create another normal + // slot character while this one is being converted to normal, thus allowing + // the account to have more normal slot characters on this cluster than is + // allowed, set the "creating characters too rapidly" flag to prevent any + // character creation on the account on this cluster for a while + CharacterCreationTracker::getInstance().setFastCreationLock(vacateUnlockedSlotReq.getValue().first.first); + break; + } + case constcrc("SwapUnlockedSlotReq") : + { + GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(swapUnlockedSlotReq); + break; + } + case constcrc("FeatureIdTransactionRequest") : + { + FeatureIdTransactionRequest const fitr(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(fitr); + break; + } + case constcrc("FeatureIdTransactionSyncUpdate") : + { + FeatureIdTransactionSyncUpdate const fitsu(ri); + CentralServer::getInstance().sendToArbitraryLoginServer(fitsu); + break; + } + case constcrc("AllCluserGlobalChannel") : + { + typedef std::pair, bool> PayloadType; + GenericValueTypeMessage msg(ri); - PayloadType const & payload = msg.getValue(); - std::string const & channelName = payload.first.first; - std::string const & messageText = payload.first.second; - bool const & isRemove = payload.second; + PayloadType const & payload = msg.getValue(); + std::string const & channelName = payload.first.first; + std::string const & messageText = payload.first.second; + bool const & isRemove = payload.second; - LOG("CustomerService", ("BroadcastVoiceChannel: CentralServer got AllCluserGlobalChannel from GameServer, sending to LoginServer chan(%s) text(%s) remove(%d)", - channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); + LOG("CustomerService", ("BroadcastVoiceChannel: CentralServer got AllCluserGlobalChannel from GameServer, sending to LoginServer chan(%s) text(%s) remove(%d)", + channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); - CentralServer::getInstance().sendToArbitraryLoginServer(msg); - } - else if (m.isType("TransferRequestMoveValidation")) - { - TransferRequestMoveValidation const request(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); - LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation from GameServer (%u) : [%u, %s, %s (%s)] to [%u, %s, %s]. Forwarding request to LoginServer.", request.getTrack(), request.getSourceStationId(), request.getSourceGalaxy().c_str(), request.getSourceCharacter().c_str(), request.getSourceCharacterId().getValueString().c_str(), request.getDestinationStationId(), request.getDestinationGalaxy().c_str(), request.getDestinationCharacter().c_str())); - } - else if (m.isType("GcwScoreStatRaw")) - { - GenericValueTypeMessage >, std::map > > > > const msg(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); - } - else if (m.isType("GcwScoreStatPct")) - { - GenericValueTypeMessage, std::map > > > const msg(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); + CentralServer::getInstance().sendToArbitraryLoginServer(msg); + break; + } + case constcrc("TransferRequestMoveValidation") : + { + TransferRequestMoveValidation const request(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); + LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation from GameServer (%u) : [%u, %s, %s (%s)] to [%u, %s, %s]. Forwarding request to LoginServer.", request.getTrack(), request.getSourceStationId(), request.getSourceGalaxy().c_str(), request.getSourceCharacter().c_str(), request.getSourceCharacterId().getValueString().c_str(), request.getDestinationStationId(), request.getDestinationGalaxy().c_str(), request.getDestinationCharacter().c_str())); + break; + } + case constcrc("GcwScoreStatRaw") : + { + GenericValueTypeMessage >, std::map > > > > const msg(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); + break; + } + case constcrc("GcwScoreStatPct") : + { + GenericValueTypeMessage, std::map > > > const msg(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(msg)); + break; + } } ServerConnection::onReceive(message); diff --git a/engine/server/application/CentralServer/src/shared/LoginServerConnection.cpp b/engine/server/application/CentralServer/src/shared/LoginServerConnection.cpp index bd0821b9..968c8ecd 100755 --- a/engine/server/application/CentralServer/src/shared/LoginServerConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/LoginServerConnection.cpp @@ -36,6 +36,8 @@ #include "sharedNetworkMessages/ConsoleChannelMessages.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- LoginServerConnection::LoginServerConnection(const std::string & a, const unsigned short p) : @@ -87,238 +89,265 @@ void LoginServerConnection::onReceive(const Archive::ByteStream & message) GameNetworkMessage m(ri); ri = message.begin(); - if(m.isType("TransferReplyCharacterList")) - { - // if this is not a free CTS galaxy, immediately forward the message to the TransferServer, - // else if this is a free CTS galaxy, forward the message to a game server so that characters - // in the list that qualifies for free CTS are removed from the list; characters that qualify - // for free CTS should/must use the in-game free CTS to transfer the character; - TransferReplyCharacterList reply(ri); - if (!FreeCtsDataTable::isFreeCtsSourceCluster(ConfigCentralServer::getClusterName())) - CentralServer::getInstance().sendToTransferServer(reply); - else - IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(reply)); - } - else if(m.isType("TransferReplyCharacterDataFromLoginServer")) - { - GenericValueTypeMessage reply(ri); - // see if we need to send to transfer or connection server. - if(reply.getValue().getCSToolId() > 0) + const uint32 messageType = m.getType(); + + switch (messageType) { + case constcrc("TransferReplyCharacterList") : { - // for CS admin login. send to DB. This just shortcuts what would normally - // happen at the transfer server. - GenericValueTypeMessage login("TransferGetLoginLocationData", reply.getValue()); - CentralServer::getInstance().sendToDBProcess(login, true); - } - else if (reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) - { - // for CTS. Send to transfer. - CentralServer::getInstance().sendToTransferServer(reply); - } - } - else if(m.isType("TransferReplyMoveValidation")) - { - TransferReplyMoveValidation const reply(ri); - - if (reply.getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) - { - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyMoveValidation for %s on %s to %s on %s from LoginServer. Forwarding reply to TransferServer.", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); - CentralServer::getInstance().sendToTransferServer(reply); - } - else if (reply.getResult() != TransferReplyMoveValidation::TRMVR_can_create_regular_character) - { - LOG("CustomerService", ("CharacterTransfer: Received ***FAILED*** TransferReplyMoveValidation for [%u, %s, %s (%s)] to [%u, %s, %s] from LoginServer. Forwarding ***FAILED*** reply to GameServer (%u).", reply.getSourceStationId(), reply.getSourceGalaxy().c_str(), reply.getSourceCharacter().c_str(), reply.getSourceCharacterId().getValueString().c_str(), reply.getDestinationStationId(), reply.getDestinationGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getTrack())); - GameServerConnection * gs = CentralServer::getInstance().getGameServer(reply.getTrack()); - if (!gs) - gs = CentralServer::getInstance().getRandomGameServer(); - - if (gs) - gs->send(reply, true); - } - else - { - LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyMoveValidation for [%u, %s, %s (%s)] to [%u, %s, %s] from LoginServer. Sending TransferRequestNameValidation to a random game server.", reply.getSourceStationId(), reply.getSourceGalaxy().c_str(), reply.getSourceCharacter().c_str(), reply.getSourceCharacterId().getValueString().c_str(), reply.getDestinationStationId(), reply.getDestinationGalaxy().c_str(), reply.getDestinationCharacter().c_str())); - - TransferCharacterData requestData(reply.getTransferRequestSource()); - requestData.setTrack(reply.getTrack()); - requestData.setCustomerLocalizedLanguage(reply.getCustomerLocalizedLanguage()); - requestData.setSourceGalaxy(reply.getSourceGalaxy()); - requestData.setDestinationGalaxy(reply.getDestinationGalaxy()); - requestData.setSourceCharacterName(reply.getSourceCharacter()); - requestData.setCharacterId(reply.getSourceCharacterId()); - requestData.setObjectTemplateCrc(reply.getSourceCharacterTemplateId()); - requestData.setDestinationCharacterName(reply.getDestinationCharacter()); - requestData.setSourceStationId(reply.getSourceStationId()); - requestData.setDestinationStationId(reply.getDestinationStationId()); - const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", requestData); - IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(requestNameValidation)); - } - } - else if(m.isType("TransferReplyNameValidation")) - { - GenericValueTypeMessage > const replyNameValidation(ri); - if (!replyNameValidation.getValue().second.getIsValidName() || (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_ingame_freects_command_validate) || (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_ingame_cts_command_validate)) - { - if (!replyNameValidation.getValue().second.getIsValidName()) - LOG("CustomerService", ("CharacterTransfer: Received ***FAILED*** TransferReplyNameValidation from target galaxy CentralServer : (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); + // if this is not a free CTS galaxy, immediately forward the message to the TransferServer, + // else if this is a free CTS galaxy, forward the message to a game server so that characters + // in the list that qualifies for free CTS are removed from the list; characters that qualify + // for free CTS should/must use the in-game free CTS to transfer the character; + TransferReplyCharacterList reply(ri); + if (!FreeCtsDataTable::isFreeCtsSourceCluster(ConfigCentralServer::getClusterName())) + CentralServer::getInstance().sendToTransferServer(reply); else - LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyNameValidation from target galaxy CentralServer. Forwarding reply to GameServer (%u). %s", replyNameValidation.getValue().second.getTrack(), replyNameValidation.getValue().second.toString().c_str())); - - GameServerConnection * gs = CentralServer::getInstance().getGameServer(replyNameValidation.getValue().second.getTrack()); - if (!gs) - gs = CentralServer::getInstance().getRandomGameServer(); - - if (gs) - gs->send(replyNameValidation, true); + IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(reply)); + + break; } - else + case constcrc("TransferReplyCharacterDataFromLoginServer") : { - LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyNameValidation from target galaxy CentralServer. Starting transfer process : %s", replyNameValidation.getValue().second.toString().c_str())); - - // disconnect any clients with a connection to SWG services on this (the source) galaxy - GenericValueTypeMessage kickSource("TransferKickConnectedClients", replyNameValidation.getValue().second.getSourceStationId()); - GenericValueTypeMessage kickDestination("TransferKickConnectedClients", replyNameValidation.getValue().second.getDestinationStationId()); - CentralServer::getInstance().sendToAllLoginServers(kickSource); - CentralServer::getInstance().sendToAllLoginServers(kickDestination); - CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); - CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); - - TransferCharacterData characterData(replyNameValidation.getValue().second); - characterData.setIsMoveRequest(true); - characterData.setWithItems(true); - characterData.setAllowOverride(true); - - LOG("CustomerService", ("CharacterTransfer: Sending TransferGetLoginLocationData for %s\n", characterData.getSourceCharacterName().c_str())); - - const GenericValueTypeMessage getLoginLocation("TransferGetLoginLocationData", characterData); - CentralServer::getInstance().sendToDBProcess(getLoginLocation, true); - } - } - else if(m.isType("TransferLoginCharacterToDestinationServer")) - { - GenericValueTypeMessage const loginCharacter(ri); - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToDestinationServer request from Login Server for %s\n", loginCharacter.getValue().toString().c_str())); - ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); - if(connectionServer) - { - connectionServer->send(loginCharacter, true); - } - } - else if(m.isType("TransferClosePseudoClientConnection")) - { - GenericValueTypeMessage const closeRequest(ri); - CentralServer::getInstance().sendToAllConnectionServers(closeRequest, true); - } - else if(m.isType("TransferCloseClientConnection")) - { - GenericValueTypeMessage const closeRequest(ri); - - GenericValueTypeMessage const kick("TransferKickConnectedClients", closeRequest.getValue()); - CentralServer::getInstance().sendToAllLoginServers(kick); - CentralServer::getInstance().sendToAllConnectionServers(kick, true); - } - else if(m.isType("CtsCompletedForcharacter")) - { - GenericValueTypeMessage > const msg(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(msg)); - } - else if(m.isType("TransferRenameCharacterReplyFromLoginServer")) - { - GenericValueTypeMessage replyFromLoginServer(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReplyFromLoginServer : %s", replyFromLoginServer.getValue().toString().c_str())); - - GenericValueTypeMessage reply("TransferRenameCharacterReply", replyFromLoginServer.getValue()); - CentralServer::getInstance().sendToTransferServer(reply); - } - else if(m.isType("TransferAccountRequestCentralDatabase")) - { - // got message back from loginServer - have to transfer to DBProcess to update the game database - GenericValueTypeMessage accountTransferRequest(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestCentralDatabase from station ID %d to station ID %d", accountTransferRequest.getValue().getSourceStationId(), accountTransferRequest.getValue().getDestinationStationId())); - CentralServer::getInstance().sendToDBProcess(accountTransferRequest, true); - } - else if(m.isType("TransferAccountReplySuccessTransferServer")) - { - // got reply back from login server - fwd to transfer server - GenericValueTypeMessage replyToTransferServer(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountReplySuccessTransferServer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); - } - else if(m.isType("TransferAccountFailedToUpdateGameDatabase")) - { - // got failure message back from login server - fwd to transfer server - GenericValueTypeMessage replyToTransferServer(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedToUpdateGameDatabase for transfer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); - } - else if(m.isType("TransferAccountFailedDestinationNotEmpty")) - { - // got failure message back from login server - fwd to transfer server - GenericValueTypeMessage replyToTransferServer(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedDestinationNotEmpty for transfer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); - } - else if(m.isType("CSToolRequest")) - { - // for now, just parse the command through the command queue. - // TODO: implement command processor for this, specifically. Or, at least, make sure we're - // specifying access levels. - CSToolRequest const req(ri); - - // Doesn't appear to be too much that we can really do with the Central Server. - // So, for now, we'll just implement a 'central' command here and spam the GameServers with - // the original message otherwise. - - unsigned pos = req.getCommandString().find( " " ); - pos = pos == std::string::npos ? req.getCommandString().length() : pos; - - CentralCSHandler::getInstance().handle( req, getProcessId() ); - - - } - else if(m.isType("ConGenericMessage")) - { - ConGenericMessage con(ri); - ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); - } - else if(m.isType("AllCluserGlobalChannel")) - { - //TODO: Route to connection server directly if there is no channel? - typedef std::pair, bool> PayloadType; - GenericValueTypeMessage msg(ri); - - PayloadType const & payload = msg.getValue(); - std::string const & channelName = payload.first.first; - std::string const & messageText = payload.first.second; - bool const & isRemove = payload.second; - - LOG("CustomerService", ("BroadcastVoiceChannel: CentralServer got AllCluserGlobalChannel from LoginServer, sending to all ChatServers chan(%s) text(%s) remove(%d)", - channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); - - CentralServer::getInstance().broadcastToChatServers(msg); - } - else if(m.isType("GcwScoreStatRaw")) - { - GenericValueTypeMessage >, std::map > > > > const msg(ri); - if (_stricmp(msg.getValue().first.c_str(), ConfigCentralServer::getClusterName())) - { - GameServerConnection * universeGameServerConnection = CentralServer::getInstance().getGameServer(UniverseManager::getInstance().getUniverseProcess()); - if (universeGameServerConnection) + GenericValueTypeMessage reply(ri); + // see if we need to send to transfer or connection server. + if(reply.getValue().getCSToolId() > 0) { - universeGameServerConnection->send(msg, true); + // for CS admin login. send to DB. This just shortcuts what would normally + // happen at the transfer server. + GenericValueTypeMessage login("TransferGetLoginLocationData", reply.getValue()); + CentralServer::getInstance().sendToDBProcess(login, true); } - } - } - else if(m.isType("GcwScoreStatPct")) - { - GenericValueTypeMessage, std::map > > > const msg(ri); - if (_stricmp(msg.getValue().first.c_str(), ConfigCentralServer::getClusterName())) - { - GameServerConnection * universeGameServerConnection = CentralServer::getInstance().getGameServer(UniverseManager::getInstance().getUniverseProcess()); - if (universeGameServerConnection) + else if (reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) { - universeGameServerConnection->send(msg, true); + // for CTS. Send to transfer. + CentralServer::getInstance().sendToTransferServer(reply); } + break; + } + case constcrc("TransferReplyMoveValidation") : + { + TransferReplyMoveValidation const reply(ri); + + if (reply.getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server) + { + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyMoveValidation for %s on %s to %s on %s from LoginServer. Forwarding reply to TransferServer.", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); + CentralServer::getInstance().sendToTransferServer(reply); + } + else if (reply.getResult() != TransferReplyMoveValidation::TRMVR_can_create_regular_character) + { + LOG("CustomerService", ("CharacterTransfer: Received ***FAILED*** TransferReplyMoveValidation for [%u, %s, %s (%s)] to [%u, %s, %s] from LoginServer. Forwarding ***FAILED*** reply to GameServer (%u).", reply.getSourceStationId(), reply.getSourceGalaxy().c_str(), reply.getSourceCharacter().c_str(), reply.getSourceCharacterId().getValueString().c_str(), reply.getDestinationStationId(), reply.getDestinationGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getTrack())); + GameServerConnection * gs = CentralServer::getInstance().getGameServer(reply.getTrack()); + if (!gs) + gs = CentralServer::getInstance().getRandomGameServer(); + + if (gs) + gs->send(reply, true); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyMoveValidation for [%u, %s, %s (%s)] to [%u, %s, %s] from LoginServer. Sending TransferRequestNameValidation to a random game server.", reply.getSourceStationId(), reply.getSourceGalaxy().c_str(), reply.getSourceCharacter().c_str(), reply.getSourceCharacterId().getValueString().c_str(), reply.getDestinationStationId(), reply.getDestinationGalaxy().c_str(), reply.getDestinationCharacter().c_str())); + + TransferCharacterData requestData(reply.getTransferRequestSource()); + requestData.setTrack(reply.getTrack()); + requestData.setCustomerLocalizedLanguage(reply.getCustomerLocalizedLanguage()); + requestData.setSourceGalaxy(reply.getSourceGalaxy()); + requestData.setDestinationGalaxy(reply.getDestinationGalaxy()); + requestData.setSourceCharacterName(reply.getSourceCharacter()); + requestData.setCharacterId(reply.getSourceCharacterId()); + requestData.setObjectTemplateCrc(reply.getSourceCharacterTemplateId()); + requestData.setDestinationCharacterName(reply.getDestinationCharacter()); + requestData.setSourceStationId(reply.getSourceStationId()); + requestData.setDestinationStationId(reply.getDestinationStationId()); + const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", requestData); + IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(requestNameValidation)); + } + + break; + } + case constcrc("TransferReplyNameValidation") : + { + GenericValueTypeMessage > const replyNameValidation(ri); + if (!replyNameValidation.getValue().second.getIsValidName() || (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_ingame_freects_command_validate) || (replyNameValidation.getValue().second.getTransferRequestSource() == TransferRequestMoveValidation::TRS_ingame_cts_command_validate)) + { + if (!replyNameValidation.getValue().second.getIsValidName()) + LOG("CustomerService", ("CharacterTransfer: Received ***FAILED*** TransferReplyNameValidation from target galaxy CentralServer : (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); + else + LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyNameValidation from target galaxy CentralServer. Forwarding reply to GameServer (%u). %s", replyNameValidation.getValue().second.getTrack(), replyNameValidation.getValue().second.toString().c_str())); + + GameServerConnection * gs = CentralServer::getInstance().getGameServer(replyNameValidation.getValue().second.getTrack()); + if (!gs) + gs = CentralServer::getInstance().getRandomGameServer(); + + if (gs) + gs->send(replyNameValidation, true); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Received ***SUCCESS*** TransferReplyNameValidation from target galaxy CentralServer. Starting transfer process : %s", replyNameValidation.getValue().second.toString().c_str())); + + // disconnect any clients with a connection to SWG services on this (the source) galaxy + GenericValueTypeMessage kickSource("TransferKickConnectedClients", replyNameValidation.getValue().second.getSourceStationId()); + GenericValueTypeMessage kickDestination("TransferKickConnectedClients", replyNameValidation.getValue().second.getDestinationStationId()); + CentralServer::getInstance().sendToAllLoginServers(kickSource); + CentralServer::getInstance().sendToAllLoginServers(kickDestination); + CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); + CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); + + TransferCharacterData characterData(replyNameValidation.getValue().second); + characterData.setIsMoveRequest(true); + characterData.setWithItems(true); + characterData.setAllowOverride(true); + + LOG("CustomerService", ("CharacterTransfer: Sending TransferGetLoginLocationData for %s\n", characterData.getSourceCharacterName().c_str())); + + const GenericValueTypeMessage getLoginLocation("TransferGetLoginLocationData", characterData); + CentralServer::getInstance().sendToDBProcess(getLoginLocation, true); + } + break; + } + case constcrc("TransferLoginCharacterToDestinationServer") : + { + GenericValueTypeMessage const loginCharacter(ri); + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToDestinationServer request from Login Server for %s\n", loginCharacter.getValue().toString().c_str())); + ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); + if(connectionServer) + { + connectionServer->send(loginCharacter, true); + } + break; + } + case constcrc("TransferClosePseudoClientConnection") : + { + GenericValueTypeMessage const closeRequest(ri); + CentralServer::getInstance().sendToAllConnectionServers(closeRequest, true); + break; + } + case constcrc("TransferCloseClientConnection") : + { + GenericValueTypeMessage const closeRequest(ri); + + GenericValueTypeMessage const kick("TransferKickConnectedClients", closeRequest.getValue()); + CentralServer::getInstance().sendToAllLoginServers(kick); + CentralServer::getInstance().sendToAllConnectionServers(kick, true); + break; + } + case constcrc("CtsCompletedForcharacter") : + { + GenericValueTypeMessage > const msg(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(msg)); + break; + } + case constcrc("TransferRenameCharacterReplyFromLoginServer") : + { + GenericValueTypeMessage replyFromLoginServer(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReplyFromLoginServer : %s", replyFromLoginServer.getValue().toString().c_str())); + + GenericValueTypeMessage reply("TransferRenameCharacterReply", replyFromLoginServer.getValue()); + CentralServer::getInstance().sendToTransferServer(reply); + + break; + } + case constcrc("TransferAccountRequestCentralDatabase") : + { + // got message back from loginServer - have to transfer to DBProcess to update the game database + GenericValueTypeMessage accountTransferRequest(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestCentralDatabase from station ID %d to station ID %d", accountTransferRequest.getValue().getSourceStationId(), accountTransferRequest.getValue().getDestinationStationId())); + CentralServer::getInstance().sendToDBProcess(accountTransferRequest, true); + break; + } + case constcrc("TransferAccountReplySuccessTransferServer") : + { + // got reply back from login server - fwd to transfer server + GenericValueTypeMessage replyToTransferServer(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountReplySuccessTransferServer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); + + break; + } + case constcrc("TransferAccountFailedToUpdateGameDatabase") : + { + // got failure message back from login server - fwd to transfer server + GenericValueTypeMessage replyToTransferServer(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedToUpdateGameDatabase for transfer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); + break; + } + case constcrc("TransferAccountFailedDestinationNotEmpty") : + { + // got failure message back from login server - fwd to transfer server + GenericValueTypeMessage replyToTransferServer(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedDestinationNotEmpty for transfer from station ID %d to station ID %d", replyToTransferServer.getValue().getSourceStationId(), replyToTransferServer.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToTransferServer(replyToTransferServer)); + break; + } + case constcrc("CSToolRequest") : + { + // for now, just parse the command through the command queue. + // TODO: implement command processor for this, specifically. Or, at least, make sure we're + // specifying access levels. + CSToolRequest const req(ri); + + // Doesn't appear to be too much that we can really do with the Central Server. + // So, for now, we'll just implement a 'central' command here and spam the GameServers with + // the original message otherwise. + + unsigned pos = req.getCommandString().find( " " ); + pos = pos == std::string::npos ? req.getCommandString().length() : pos; + + CentralCSHandler::getInstance().handle( req, getProcessId() ); + + break; + } + case constcrc("ConGenericMessage") : + { + ConGenericMessage con(ri); + ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + + break; + } + case constcrc("AllCluserGlobalChannel") : + { + //TODO: Route to connection server directly if there is no channel? + typedef std::pair, bool> PayloadType; + GenericValueTypeMessage msg(ri); + + PayloadType const & payload = msg.getValue(); + std::string const & channelName = payload.first.first; + std::string const & messageText = payload.first.second; + bool const & isRemove = payload.second; + + LOG("CustomerService", ("BroadcastVoiceChannel: CentralServer got AllCluserGlobalChannel from LoginServer, sending to all ChatServers chan(%s) text(%s) remove(%d)", + channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); + + CentralServer::getInstance().broadcastToChatServers(msg); + + break; + } + case constcrc("GcwScoreStatRaw") : + { + GenericValueTypeMessage >, std::map > > > > const msg(ri); + if (_stricmp(msg.getValue().first.c_str(), ConfigCentralServer::getClusterName())) + { + GameServerConnection * universeGameServerConnection = CentralServer::getInstance().getGameServer(UniverseManager::getInstance().getUniverseProcess()); + if (universeGameServerConnection) + { + universeGameServerConnection->send(msg, true); + } + } + break; + } + case constcrc("GcwScoreStatPct") : + { + GenericValueTypeMessage, std::map > > > const msg(ri); + if (_stricmp(msg.getValue().first.c_str(), ConfigCentralServer::getClusterName())) + { + GameServerConnection * universeGameServerConnection = CentralServer::getInstance().getGameServer(UniverseManager::getInstance().getUniverseProcess()); + if (universeGameServerConnection) + { + universeGameServerConnection->send(msg, true); + } + } + break; } } diff --git a/engine/server/application/CentralServer/src/shared/PlanetManager.cpp b/engine/server/application/CentralServer/src/shared/PlanetManager.cpp index f9912dde..27e0b398 100755 --- a/engine/server/application/CentralServer/src/shared/PlanetManager.cpp +++ b/engine/server/application/CentralServer/src/shared/PlanetManager.cpp @@ -17,6 +17,8 @@ #include "serverNetworkMessages/TaskSpawnProcess.h" #include "sharedNetwork/NetworkHandler.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== PlanetManager::PlanetRec::PlanetRec() : @@ -85,48 +87,55 @@ void PlanetManager::addGameServerForScene(const std::string &sceneId, GameServer void PlanetManager::receiveMessage(const MessageDispatch::Emitter &source , const MessageDispatch::MessageBase & message) { - if(message.isType("PlanetObjectIdMessage")) //@todo: Is this message actually used anymore? - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PlanetObjectIdMessage msg(ri); - - // Message identifies the PlanetObject that belongs to a particular planet - ServerListType::iterator i=m_servers.find(msg.getSceneId()); - if (i==m_servers.end()) + const uint32 messageType = message.getType(); + + switch (messageType) { + case constcrc("PlanetObjectIdMessage") : //@todo: Is this message actually used anymore? { - WARNING_STRICT_FATAL(true,("Got unexpected PlanetObjectIdMessage for %s.\n",msg.getSceneId().c_str())); - return; - } + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PlanetObjectIdMessage msg(ri); - (*i).second.m_planetObjectId=msg.getPlanetObject(); - - // Not needed because all UniverseObjects are proxied. -// CentralServer::getInstance().proxyOnAllServersForScene(msg.getPlanetObject(),msg.getSceneId()); - } - else if(message.isType("PlanetServerConnectionClosed")) - { - const PlanetServerConnection * c = static_cast(&source); //lint !e826 Suspiscious pointer-to-pointer conversion (area too small) - ServerListType::iterator i = m_servers.begin(); - for (; i != m_servers.end(); ++i) - { - if (i->second.m_connection == c) + // Message identifies the PlanetObject that belongs to a particular planet + ServerListType::iterator i=m_servers.find(msg.getSceneId()); + if (i==m_servers.end()) { - m_servers.erase(i); - break; + WARNING_STRICT_FATAL(true,("Got unexpected PlanetObjectIdMessage for %s.\n",msg.getSceneId().c_str())); + return; } - } - if (ConfigCentralServer::getRequestDbSaveOnPlanetServerCrash()) + (*i).second.m_planetObjectId=msg.getPlanetObject(); + + // Not needed because all UniverseObjects are proxied. + // CentralServer::getInstance().proxyOnAllServersForScene(msg.getPlanetObject(),msg.getSceneId()); + break; + } + case constcrc("PlanetServerConnectionClosed") : { - GameNetworkMessage const msg("CentralRequestSave"); - CentralServer::getInstance().sendToDBProcess(msg, true); - } + const PlanetServerConnection * c = static_cast(&source); //lint !e826 Suspiscious pointer-to-pointer conversion (area too small) + ServerListType::iterator i = m_servers.begin(); + for (; i != m_servers.end(); ++i) + { + if (i->second.m_connection == c) + { + m_servers.erase(i); + break; + } + } - CentralServer::getInstance().startPlanetServer(CentralServer::getInstance().getHostForScene(c->getSceneId()), c->getSceneId(), ConfigCentralServer::getPlanetServerRestartDelayTimeSeconds()); - } - else - { - WARNING_STRICT_FATAL(true,("Planet Manager got unexpected message.\n")); + if (ConfigCentralServer::getRequestDbSaveOnPlanetServerCrash()) + { + GameNetworkMessage const msg("CentralRequestSave"); + CentralServer::getInstance().sendToDBProcess(msg, true); + } + + CentralServer::getInstance().startPlanetServer(CentralServer::getInstance().getHostForScene(c->getSceneId()), c->getSceneId(), ConfigCentralServer::getPlanetServerRestartDelayTimeSeconds()); + break; + } + default : + { + WARNING_STRICT_FATAL(true,("Planet Manager got unexpected message.\n")); + break; + } } } @@ -138,7 +147,7 @@ PlanetServerConnection *PlanetManager::getPlanetServerForScene(const std::string if (i!=instance().m_servers.end()) return (*i).second.m_connection; else - return NULL; + return nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/application/CentralServer/src/shared/PlanetServerConnection.cpp b/engine/server/application/CentralServer/src/shared/PlanetServerConnection.cpp index 3444c068..a5930b86 100755 --- a/engine/server/application/CentralServer/src/shared/PlanetServerConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/PlanetServerConnection.cpp @@ -15,6 +15,8 @@ #include "sharedNetworkMessages/ConsoleChannelMessages.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== PlanetServerConnection::PlanetServerConnection(UdpConnectionMT *u, TcpClient *t) : @@ -69,39 +71,42 @@ void PlanetServerConnection::onReceive(Archive::ByteStream const &message) GameNetworkMessage const msg(ri); ri = message.begin(); + const uint32 msgType = msg.getType(); + if (!m_forwardDestinationServers.empty()) { - if (isMessageForwardable(msg.getType())) + if (isMessageForwardable(msgType)) { m_forwardMessages.push_back(std::make_pair(message, m_forwardDestinationServers.back())); return; - } - else if (msg.isType("EndForward")) - { - if (--m_forwardCounts.back() == 0) - { - m_forwardCounts.pop_back(); - m_forwardDestinationServers.pop_back(); - if (m_forwardDestinationServers.empty()) - pushAndClearObjectForwarding(); + } else { + switch (msgType) { + case constcrc("EndForward"): { + if (--m_forwardCounts.back() == 0) { + m_forwardCounts.pop_back(); + m_forwardDestinationServers.pop_back(); + + if (m_forwardDestinationServers.empty()) { + pushAndClearObjectForwarding(); + } + } + return; + } + case constcrc("BeginForward") : { + GenericValueTypeMessage > const beginForwardMessage(ri); + if (beginForwardMessage.getValue() == m_forwardDestinationServers.back()) + ++m_forwardCounts.back(); + else { + m_forwardCounts.push_back(1); + m_forwardDestinationServers.push_back(beginForwardMessage.getValue()); + } + return; + } } - return; - } - else if (msg.isType("BeginForward")) - { - GenericValueTypeMessage > const beginForwardMessage(ri); - if (beginForwardMessage.getValue() == m_forwardDestinationServers.back()) - ++m_forwardCounts.back(); - else - { - m_forwardCounts.push_back(1); - m_forwardDestinationServers.push_back(beginForwardMessage.getValue()); - } - return; } } - if (msg.isType("BeginForward")) + if (msgType == constcrc("BeginForward")) { GenericValueTypeMessage > const beginForwardMessage(ri); @@ -112,20 +117,22 @@ void PlanetServerConnection::onReceive(Archive::ByteStream const &message) ServerConnection::onReceive(message); - if (msg.isType("CentralPlanetServerConnect")) - { - CentralPlanetServerConnect const id(ri); - sceneId = id.getSceneId(); - } - else if (msg.isType("TaskSpawnProcess")) - { - TaskSpawnProcess const spawn(ri); - CentralServer::getInstance().sendTaskMessage(spawn); - } - else if (msg.isType("ConGenericMessage")) - { - ConGenericMessage const con(ri); - ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + switch (msgType) { + case constcrc("CentralPlanetServerConnect") : { + CentralPlanetServerConnect const id(ri); + sceneId = id.getSceneId(); + break; + } + case constcrc("TaskSpawnProcess") : { + TaskSpawnProcess const spawn(ri); + CentralServer::getInstance().sendTaskMessage(spawn); + break; + } + case constcrc("ConGenericMessage") : { + ConGenericMessage const con(ri); + ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + break; + } } } diff --git a/engine/server/application/CentralServer/src/shared/StationPlayersCollectorConnection.cpp b/engine/server/application/CentralServer/src/shared/StationPlayersCollectorConnection.cpp index 2a9c88a9..ee5b5a01 100755 --- a/engine/server/application/CentralServer/src/shared/StationPlayersCollectorConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/StationPlayersCollectorConnection.cpp @@ -15,6 +15,8 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "StationPlayersCollectorConnection.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- StationPlayersCollectorConnection::StationPlayersCollectorConnection(const std::string & a, const unsigned short p) : @@ -55,13 +57,19 @@ void StationPlayersCollectorConnection::onReceive(const Archive::ByteStream & me const GameNetworkMessage msg(ri); ri = message.begin(); - if(msg.isType("OnSPCharacterProfileMessage")) - { - } - else if(msg.isType("ConGenericMessage")) + const uint32 messageType = msg.getType(); + + if(messageType == constcrc("ConGenericMessage")) { ConGenericMessage con(ri); ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + } else { + if(messageType == constcrc("OnSPCharacterProfileMessage")) + { + DEBUG_WARNING(true, ("StationPlayersCollectorConnection called with unimplemented message type OnSPCharacterProfileMessage.")); + } else { + DEBUG_WARNING(true, ("StationPlayersCollectorConnection called with unknown/unused message type.")); + } } } diff --git a/engine/server/application/CentralServer/src/shared/TransferServerConnection.cpp b/engine/server/application/CentralServer/src/shared/TransferServerConnection.cpp index 0c8b7998..a1999823 100755 --- a/engine/server/application/CentralServer/src/shared/TransferServerConnection.cpp +++ b/engine/server/application/CentralServer/src/shared/TransferServerConnection.cpp @@ -24,6 +24,8 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "TransferServerConnection.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- TransferServerConnection::TransferServerConnection(const std::string & a, const unsigned short p) : @@ -65,132 +67,153 @@ void TransferServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); const GameNetworkMessage msg(ri); ri = message.begin(); + + const uint32 messageType = msg.getType(); - if(msg.isType("UploadCharacterMessage")) - { - const UploadCharacterMessage ucm(ri); - CentralServer::getInstance().sendToGameServer(ucm.getFromGameServerId(), ucm, true); - LOG("TransferServerConnection", ("Received character data for SUID %lu for character object %s on game server %d", ucm.getStationId(), ucm.getFromCharacterId().getValueString().c_str(), ucm.getFromGameServerId())); - } - else if(msg.isType("CharacterTransferStatusMessage")) - { - const CharacterTransferStatusMessage ctsm(ri); - CentralServer::getInstance().sendToGameServer(ctsm.getGameServerId(), ctsm, true); - } - else if(msg.isType("TransferRequestCharacterList")) - { - // simply forward the request to any available login server - const GenericValueTypeMessage request(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); - } - else if(msg.isType("TransferRequestMoveValidation")) - { - const TransferRequestMoveValidation request(ri); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); - LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation : %s on %s to %s on %s. Forwarding request to LoginServer.", request.getSourceCharacter().c_str(), request.getSourceGalaxy().c_str(), request.getDestinationCharacter().c_str(), request.getDestinationGalaxy().c_str())); - } - else if(msg.isType("TransferRequestKickConnectedClients")) - { - GenericValueTypeMessage > const request(ri); - // disconnect any clients with a connection to SWG services - GenericValueTypeMessage kickSource("TransferKickConnectedClients", request.getValue().first); - GenericValueTypeMessage kickDestination("TransferKickConnectedClients", request.getValue().second); - CentralServer::getInstance().sendToAllLoginServers(kickSource); - CentralServer::getInstance().sendToAllLoginServers(kickDestination); - CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); - CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); - } - else if(msg.isType("TransferGetCharacterDataFromLoginServer")) - { - const GenericValueTypeMessage getCharacterData(ri); - - // The transfer server has received a move request. The request doesn't - // contain the source id of the character, character's container or scene - // information. The LoginServer can retrieve the character ID for the - // source station id + character name contained in character data. - // Forward the request to the login server. It will respond and the - // message can be routed back to the transfer server for further - // processing - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(getCharacterData)); - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: received TransferGetCharacterDataFromLoginServer : %s)", getCharacterData.getValue().toString().c_str())); - } - else if(msg.isType("TransferGetLoginLocationData")) - { - GenericValueTypeMessage getLoginData(ri); - CentralServer::getInstance().sendToDBProcess(getLoginData, true); - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferGetLoginLocationData for %s\n", getLoginData.getValue().getSourceCharacterName().c_str())); - } - else if(msg.isType("TransferLoginCharacterToSourceServer")) - { - const GenericValueTypeMessage loginCharacter(ri); - ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); - if(connectionServer) + switch(messageType) { + case constcrc("UploadCharacterMessage") : { - connectionServer->send(loginCharacter, true); - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToSourceServer request from Transfer Server. Sendint request to ConnectionServer : %s\n", loginCharacter.getValue().toString().c_str())); + const UploadCharacterMessage ucm(ri); + CentralServer::getInstance().sendToGameServer(ucm.getFromGameServerId(), ucm, true); + LOG("TransferServerConnection", ("Received character data for SUID %lu for character object %s on game server %d", ucm.getStationId(), ucm.getFromCharacterId().getValueString().c_str(), ucm.getFromGameServerId())); + break; } - else + case constcrc("CharacterTransferStatusMessage") : { - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Couldn't find a connection server to satisfy the transfer request for %s\n", loginCharacter.getValue().toString().c_str())); + const CharacterTransferStatusMessage ctsm(ri); + CentralServer::getInstance().sendToGameServer(ctsm.getGameServerId(), ctsm, true); + break; } - } - else if(msg.isType("TransferLoginCharacterToDestinationServer")) - { - const GenericValueTypeMessage loginCharacter(ri); - LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToDestinationServer request from Transfer Server for %s\n", loginCharacter.getValue().toString().c_str())); - ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); - if(connectionServer) + case constcrc("TransferRequestCharacterList") : { - connectionServer->send(loginCharacter, true); + // simply forward the request to any available login server + const GenericValueTypeMessage request(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); + break; + } + case constcrc("TransferRequestMoveValidation") : + { + const TransferRequestMoveValidation request(ri); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(request)); + LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation : %s on %s to %s on %s. Forwarding request to LoginServer.", request.getSourceCharacter().c_str(), request.getSourceGalaxy().c_str(), request.getDestinationCharacter().c_str(), request.getDestinationGalaxy().c_str())); + break; + } + case constcrc("TransferRequestKickConnectedClients") : + { + GenericValueTypeMessage > const request(ri); + // disconnect any clients with a connection to SWG services + GenericValueTypeMessage kickSource("TransferKickConnectedClients", request.getValue().first); + GenericValueTypeMessage kickDestination("TransferKickConnectedClients", request.getValue().second); + CentralServer::getInstance().sendToAllLoginServers(kickSource); + CentralServer::getInstance().sendToAllLoginServers(kickDestination); + CentralServer::getInstance().sendToAllConnectionServers(kickSource, true); + CentralServer::getInstance().sendToAllConnectionServers(kickDestination, true); + break; + } + case constcrc("TransferGetCharacterDataFromLoginServer") : + { + const GenericValueTypeMessage getCharacterData(ri); + + // The transfer server has received a move request. The request doesn't + // contain the source id of the character, character's container or scene + // information. The LoginServer can retrieve the character ID for the + // source station id + character name contained in character data. + // Forward the request to the login server. It will respond and the + // message can be routed back to the transfer server for further + // processing + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(getCharacterData)); + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: received TransferGetCharacterDataFromLoginServer : %s)", getCharacterData.getValue().toString().c_str())); + break; + } + case constcrc("TransferGetLoginLocationData") : + { + GenericValueTypeMessage getLoginData(ri); + CentralServer::getInstance().sendToDBProcess(getLoginData, true); + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferGetLoginLocationData for %s\n", getLoginData.getValue().getSourceCharacterName().c_str())); + break; + } + case constcrc("TransferLoginCharacterToSourceServer") : + { + const GenericValueTypeMessage loginCharacter(ri); + ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); + if(connectionServer) + { + connectionServer->send(loginCharacter, true); + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToSourceServer request from Transfer Server. Sendint request to ConnectionServer : %s\n", loginCharacter.getValue().toString().c_str())); + } + else + { + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Couldn't find a connection server to satisfy the transfer request for %s\n", loginCharacter.getValue().toString().c_str())); + } + break; + } + case constcrc("TransferLoginCharacterToDestinationServer") : + { + const GenericValueTypeMessage loginCharacter(ri); + LOG("CustomerService", ("CharacterTransfer: ***CentralServer: Received TransferLoginCharacterToDestinationServer request from Transfer Server for %s\n", loginCharacter.getValue().toString().c_str())); + ConnectionServerConnection * connectionServer = CentralServer::getInstance().getAnyConnectionServer(); + if(connectionServer) + { + connectionServer->send(loginCharacter, true); + } + break; + } + case constcrc("ToggleAvatarLoginStatus") : + { + ToggleAvatarLoginStatus toggle(ri); + LOG("CustomerService", ("CharacterTransfer: Received ToggleAvatarLoginStatus for station ID %d, Character Object %s", toggle.getStationId(), toggle.getCharacterId().getValueString().c_str())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(toggle)); + break; + } + case constcrc("TransferRequestNameValidation") : + { + GenericValueTypeMessage request(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRequestNameValidation from TransferServer. Forwarding request to a random GameServer. %s", request.getValue().toString().c_str())); + IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(request)); + break; + } + case constcrc("TransferRenameCharacter") : + { + GenericValueTypeMessage renameRequest(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacter. Sending rename request to game database. %s", renameRequest.getValue().toString().c_str())); + // send first portion of request to DBProcess , wait for response + CentralServer::getInstance().sendToDBProcess(renameRequest, true); + break; + } + case constcrc("TransferAccountRequestLoginServer") : + { + // got message to transfer a character from one account to another - have to update in loginServer + GenericValueTypeMessage accountTransferRequest(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestLoginServer from station ID %d to station ID %d", accountTransferRequest.getValue().getSourceStationId(), accountTransferRequest.getValue().getDestinationStationId())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(accountTransferRequest)); + break; + } + case constcrc("RequestChatTransferAvatar") : + { + GenericValueTypeMessage chatTransferAvatar(ri); + LOG("CustomerService", ("CharacterTransfer: Received RequestChatTransferAvatar from TransferServer. Forward request to ChatServer. %s", chatTransferAvatar.getValue().toString().c_str())); + CentralServer::getInstance().broadcastToChatServers(chatTransferAvatar); + break; + } + case constcrc("DeleteFailedTransfer") : + { + GenericValueTypeMessage deleteCharacter(ri); + LOG("CustomerService", ("CharacterTransfer: received request to delete a character for a failed transfer. %s", deleteCharacter.getValue().toString().c_str())); + IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(deleteCharacter)); + break; + } + case constcrc("TransferClosePseudoClientConnection") : + { + GenericValueTypeMessage closeRequest(ri); + CentralServer::getInstance().sendToAllConnectionServers(closeRequest, true); + break; + } + case constcrc("ConGenericMessage") : + { + ConGenericMessage con(ri); + ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); + break; } - } - else if(msg.isType("ToggleAvatarLoginStatus")) - { - ToggleAvatarLoginStatus toggle(ri); - LOG("CustomerService", ("CharacterTransfer: Received ToggleAvatarLoginStatus for station ID %d, Character Object %s", toggle.getStationId(), toggle.getCharacterId().getValueString().c_str())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(toggle)); - } - else if(msg.isType("TransferRequestNameValidation")) - { - GenericValueTypeMessage request(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRequestNameValidation from TransferServer. Forwarding request to a random GameServer. %s", request.getValue().toString().c_str())); - IGNORE_RETURN(CentralServer::getInstance().sendToRandomGameServer(request)); - } - else if(msg.isType("TransferRenameCharacter")) - { - GenericValueTypeMessage renameRequest(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacter. Sending rename request to game database. %s", renameRequest.getValue().toString().c_str())); - // send first portion of request to DBProcess , wait for response - CentralServer::getInstance().sendToDBProcess(renameRequest, true); - } - else if(msg.isType("TransferAccountRequestLoginServer")) - { - // got message to transfer a character from one account to another - have to update in loginServer - GenericValueTypeMessage accountTransferRequest(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestLoginServer from station ID %d to station ID %d", accountTransferRequest.getValue().getSourceStationId(), accountTransferRequest.getValue().getDestinationStationId())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(accountTransferRequest)); - } - else if(msg.isType("RequestChatTransferAvatar")) - { - GenericValueTypeMessage chatTransferAvatar(ri); - LOG("CustomerService", ("CharacterTransfer: Received RequestChatTransferAvatar from TransferServer. Forward request to ChatServer. %s", chatTransferAvatar.getValue().toString().c_str())); - CentralServer::getInstance().broadcastToChatServers(chatTransferAvatar); - } - else if(msg.isType("DeleteFailedTransfer")) - { - GenericValueTypeMessage deleteCharacter(ri); - LOG("CustomerService", ("CharacterTransfer: received request to delete a character for a failed transfer. %s", deleteCharacter.getValue().toString().c_str())); - IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(deleteCharacter)); - } - else if(msg.isType("TransferClosePseudoClientConnection")) - { - GenericValueTypeMessage closeRequest(ri); - CentralServer::getInstance().sendToAllConnectionServers(closeRequest, true); - } - else if(msg.isType("ConGenericMessage")) - { - ConGenericMessage con(ri); - ConsoleConnection::onCommandComplete(con.getMsg(), static_cast(con.getMsgId())); } } diff --git a/engine/server/application/CentralServer/src/shared/UniverseManager.cpp b/engine/server/application/CentralServer/src/shared/UniverseManager.cpp index f298a7e4..244630c0 100755 --- a/engine/server/application/CentralServer/src/shared/UniverseManager.cpp +++ b/engine/server/application/CentralServer/src/shared/UniverseManager.cpp @@ -18,6 +18,8 @@ #include "serverNetworkMessages/SetUniverseAuthoritativeMessage.h" #include "sharedLog/Log.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== UniverseManager::UniverseManager() : @@ -47,62 +49,72 @@ UniverseManager::~UniverseManager() void UniverseManager::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { - if(message.isType("CentralGameServerDbProcessServerProcessId")) - { - DEBUG_REPORT_LOG(true, ("dbProcess connected\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CentralGameServerDbProcessServerProcessId d(ri); - - const GameServerConnection * g = static_cast(&source); //lint !e826 Suspicious pointer-to-pointer conversion - NOT_NULL(g); - onDatabaseProcessConnect(*g); - } - else if (message.isType("CreateDynamicRegionCircleMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CreateDynamicRegionCircleMessage msg(ri); - if (!m_databaseAuthoritative) - CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); - } - else if (message.isType("CreateDynamicRegionRectangleMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CreateDynamicRegionRectangleMessage msg(ri); - if (!m_databaseAuthoritative) - CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); - } - else if (message.isType("CreateGroupMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CreateGroupMessage msg(ri); - if (!m_databaseAuthoritative) - CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); - } - else if (message.isType("ChangeUniverseProcessMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ChangeUniverseProcessMessage msg(ri); - uint32 processId = static_cast(msg.getId()); - if (!m_databaseAuthoritative && CentralServer::getInstance().getGameServer(processId)) + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("CentralGameServerDbProcessServerProcessId") : { - m_universeProcess = processId; - DEBUG_REPORT_LOG(true, ("Changing our Universe process to %lu\n",m_universeProcess)); - LOG("Universe", ("Changing our Universe process to %i\n",m_universeProcess)); + DEBUG_REPORT_LOG(true, ("dbProcess connected\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CentralGameServerDbProcessServerProcessId d(ri); - SetUniverseAuthoritativeMessage authMsg(m_universeProcess); - CentralServer::getInstance().sendToAllGameServers(authMsg,true); + const GameServerConnection * g = static_cast(&source); //lint !e826 Suspicious pointer-to-pointer conversion + NOT_NULL(g); + onDatabaseProcessConnect(*g); + break; } - } - else if (message.isType("GameServerUniverseLoadedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameServerUniverseLoadedMessage d(ri); - UNREF(d); + case constcrc("CreateDynamicRegionCircleMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CreateDynamicRegionCircleMessage msg(ri); + if (!m_databaseAuthoritative) + CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); + break; + } + case constcrc("CreateDynamicRegionRectangleMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CreateDynamicRegionRectangleMessage msg(ri); + if (!m_databaseAuthoritative) + CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); + break; + } + case constcrc("CreateGroupMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CreateGroupMessage msg(ri); + if (!m_databaseAuthoritative) + CentralServer::getInstance().sendToGameServer(m_universeProcess, msg, true); + break; + } + case constcrc("ChangeUniverseProcessMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ChangeUniverseProcessMessage msg(ri); + uint32 processId = static_cast(msg.getId()); + if (!m_databaseAuthoritative && CentralServer::getInstance().getGameServer(processId)) + { + m_universeProcess = processId; + DEBUG_REPORT_LOG(true, ("Changing our Universe process to %lu\n",m_universeProcess)); + LOG("Universe", ("Changing our Universe process to %i\n",m_universeProcess)); - const GameServerConnection * g = static_cast(&source); //lint !e826 Suspicious pointer-to-pointer conversion - NOT_NULL(g); -// DEBUG_REPORT_LOG(true,("m_serversLoadingUniverse->erase(%lu);\n",g->getProcessId())); - IGNORE_RETURN(m_serversLoadingUniverse->erase(g->getProcessId())); + SetUniverseAuthoritativeMessage authMsg(m_universeProcess); + CentralServer::getInstance().sendToAllGameServers(authMsg,true); + } + break; + } + case constcrc("GameServerUniverseLoadedMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameServerUniverseLoadedMessage d(ri); + UNREF(d); + + const GameServerConnection * g = static_cast(&source); //lint !e826 Suspicious pointer-to-pointer conversion + NOT_NULL(g); + // DEBUG_REPORT_LOG(true,("m_serversLoadingUniverse->erase(%lu);\n",g->getProcessId())); + IGNORE_RETURN(m_serversLoadingUniverse->erase(g->getProcessId())); + break; + } } } diff --git a/engine/server/application/CentralServer/src/win32/FirstCentralServer.cpp b/engine/server/application/CentralServer/src/win32/FirstCentralServer.cpp new file mode 100644 index 00000000..509e7da9 --- /dev/null +++ b/engine/server/application/CentralServer/src/win32/FirstCentralServer.cpp @@ -0,0 +1,5 @@ +// CentralServerPrecompiledHeader.cpp +// copyright 2001 Verant Interactive +// Author: Justin Randall + +#include "FirstCentralServer.h" diff --git a/engine/server/application/CentralServer/src/win32/WinMain.cpp b/engine/server/application/CentralServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..6c760f37 --- /dev/null +++ b/engine/server/application/CentralServer/src/win32/WinMain.cpp @@ -0,0 +1,84 @@ +#include "FirstCentralServer.h" +#include "ConfigCentralServer.h" +#include "CentralServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" + +#include +#include + +//_____________________________________________________________________ +/* +int WINAPI WinMain( + HINSTANCE hInstance, // handle to current instance + HINSTANCE hPrevInstance, // handle to previous instance + LPSTR lpCmdLine, // pointer to command line + int nCmdShow // show state of window + ) + */ +int main(int argc, char ** argv) +{ //lint !e1065 //WinMain conflicts with clib + int i = 0; + +// UNREF(hPrevInstance); +// UNREF(nCmdShow); + + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + // command line hack + std::string cmdLine; + for(i = 1; i < argc; ++i) + { + cmdLine += argv[i]; + if(i + 1 < argc) + { + cmdLine += " "; + } + } +// setupFoundationData.hInstance = hInstance; + setupFoundationData.commandLine = cmdLine.c_str(); + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + + SetupSharedFile::install(false); + + SetupSharedNetworkMessages::install(); + + ConfigCentralServer::install(); + + cmdLine = ""; + // now, the real command line + for(i = 0; i < argc; ++i) + { + cmdLine += argv[i]; + if(i + 1 < argc) + { + cmdLine += " "; + } + } + + CentralServer::getInstance().setCommandLine(cmdLine); + + //-- run game + SetupSharedFoundation::callbackWithExceptionHandling(CentralServer::run); + + SetupSharedFoundation::remove(); + + return 0; +} + +//_____________________________________________________________________ diff --git a/engine/server/application/ChatServer/src/linux/main.cpp b/engine/server/application/ChatServer/src/linux/main.cpp index eecd0c24..295c53f2 100755 --- a/engine/server/application/ChatServer/src/linux/main.cpp +++ b/engine/server/application/ChatServer/src/linux/main.cpp @@ -29,7 +29,7 @@ int main(int argc, char ** argv) SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + SetupSharedRandom::install(static_cast(time(nullptr))); //lint !e1924 !e64 // nullptr is a C-Style cast? Os::setProgramName("ChatServer"); //setup the server diff --git a/engine/server/application/ChatServer/src/shared/CentralServerConnection.cpp b/engine/server/application/ChatServer/src/shared/CentralServerConnection.cpp index b9fa2835..7b9c86a0 100755 --- a/engine/server/application/ChatServer/src/shared/CentralServerConnection.cpp +++ b/engine/server/application/ChatServer/src/shared/CentralServerConnection.cpp @@ -23,6 +23,8 @@ #include "sharedNetwork/Service.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- CentralServerConnection::CentralServerConnection(const std::string & a, const unsigned short p) : @@ -62,63 +64,73 @@ void CentralServerConnection::onReceive(const Archive::ByteStream & message) GameNetworkMessage m(ri); ri = message.begin(); + + const uint32 messageType = m.getType(); - if(m.isType("EnumerateServers")) - { - static MessageDispatch::Transceiver emitter; - - EnumerateServers e(ri); - emitter.emitMessage(e); - } - else if (m.isType("CustomerServiceServerChatServerServiceAddress")) - { - GenericValueTypeMessage > msg(ri); - - ChatServer::instance().connectToCustomerServiceServer(msg.getValue().first, msg.getValue().second); - } - else if(m.isType("RequestChatTransferAvatar")) - { - GenericValueTypeMessage request(ri); - LOG("CustomerService", ("CharacterTransfer: Received RequestChatTransferAvatar from CentralServer. Forwarding request to ChatAPI. %s", request.getValue().toString().c_str())); - ChatServer::requestTransferAvatar(request.getValue()); - } - else if (m.isType("RenameCharacterMessageEx")) - { - RenameCharacterMessageEx const msg(ri); - - // if the player requested the rename, also rename the chat - // avatar, so mail, friends list, and ignore list will migrate - if ((msg.getRenameCharacterMessageSource() == RenameCharacterMessageEx::RCMS_player_request) && !msg.getLastNameChangeOnly() && !ConfigFile::getKeyBool("CharacterRename", "disableRenameChatAvatar", false)) + switch(messageType) { + case constcrc("EnumerateServers") : { - std::string const oldName(Unicode::toLower(Unicode::wideToNarrow(msg.getOldName()))); - std::string const oldNameNormalized(oldName, 0, oldName.find(' ')); - ChatAvatarId const oldAvatar("SWG", ConfigChatServer::getClusterName(), oldNameNormalized); + static MessageDispatch::Transceiver emitter; - std::string const newName(Unicode::toLower(Unicode::wideToNarrow(msg.getNewName()))); - std::string const newNameNormalized(newName, 0, newName.find(' ')); - ChatAvatarId const newAvatar("SWG", ConfigChatServer::getClusterName(), newNameNormalized); - - IGNORE_RETURN(ChatServer::getChatInterface()->RequestTransferAvatar(msg.getStationId(), oldAvatar.getName(), oldAvatar.getAPIAddress(), msg.getStationId(), newAvatar.getName(), newAvatar.getAPIAddress(), true, NULL)); + EnumerateServers e(ri); + emitter.emitMessage(e); + break; } - } - else if (m.isType("ChatDestroyAvatar")) - { - GenericValueTypeMessage const msg(ri); - ChatServer::getChatInterface()->DestroyAvatar(msg.getValue()); - } - else if(m.isType("AllCluserGlobalChannel")) - { - typedef std::pair, bool> PayloadType; - GenericValueTypeMessage msg(ri); + case constcrc("CustomerServiceServerChatServerServiceAddress") : + { + GenericValueTypeMessage > msg(ri); - PayloadType const & payload = msg.getValue(); - std::string const & channelName = payload.first.first; - std::string const & messageText = payload.first.second; - bool const & isRemove = payload.second; + ChatServer::instance().connectToCustomerServiceServer(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("RequestChatTransferAvatar") : + { + GenericValueTypeMessage request(ri); + LOG("CustomerService", ("CharacterTransfer: Received RequestChatTransferAvatar from CentralServer. Forwarding request to ChatAPI. %s", request.getValue().toString().c_str())); + ChatServer::requestTransferAvatar(request.getValue()); + break; + } + case constcrc("RenameCharacterMessageEx") : + { + RenameCharacterMessageEx const msg(ri); - LOG("CustomerService", ("BroadcastVoiceChannel: ChatServer got AllCluserGlobalChannel on CentralServerConnection chan(%s) text(%s) remove(%d)", - channelName.c_str(), messageText.c_str(), (isRemove?1:0))); - ChatServer::requestBroadcastChannelMessage(channelName, messageText, isRemove); + // if the player requested the rename, also rename the chat + // avatar, so mail, friends list, and ignore list will migrate + if ((msg.getRenameCharacterMessageSource() == RenameCharacterMessageEx::RCMS_player_request) && !msg.getLastNameChangeOnly() && !ConfigFile::getKeyBool("CharacterRename", "disableRenameChatAvatar", false)) + { + std::string const oldName(Unicode::toLower(Unicode::wideToNarrow(msg.getOldName()))); + std::string const oldNameNormalized(oldName, 0, oldName.find(' ')); + ChatAvatarId const oldAvatar("SWG", ConfigChatServer::getClusterName(), oldNameNormalized); + + std::string const newName(Unicode::toLower(Unicode::wideToNarrow(msg.getNewName()))); + std::string const newNameNormalized(newName, 0, newName.find(' ')); + ChatAvatarId const newAvatar("SWG", ConfigChatServer::getClusterName(), newNameNormalized); + + IGNORE_RETURN(ChatServer::getChatInterface()->RequestTransferAvatar(msg.getStationId(), oldAvatar.getName(), oldAvatar.getAPIAddress(), msg.getStationId(), newAvatar.getName(), newAvatar.getAPIAddress(), true, nullptr)); + } + break; + } + case constcrc("ChatDestroyAvatar") : + { + GenericValueTypeMessage const msg(ri); + ChatServer::getChatInterface()->DestroyAvatar(msg.getValue()); + break; + } + case constcrc("AllCluserGlobalChannel") : + { + typedef std::pair, bool> PayloadType; + GenericValueTypeMessage msg(ri); + + PayloadType const & payload = msg.getValue(); + std::string const & channelName = payload.first.first; + std::string const & messageText = payload.first.second; + bool const & isRemove = payload.second; + + LOG("CustomerService", ("BroadcastVoiceChannel: ChatServer got AllCluserGlobalChannel on CentralServerConnection chan(%s) text(%s) remove(%d)", + channelName.c_str(), messageText.c_str(), (isRemove?1:0))); + ChatServer::requestBroadcastChannelMessage(channelName, messageText, isRemove); + break; + } } } diff --git a/engine/server/application/ChatServer/src/shared/ChatInterface.cpp b/engine/server/application/ChatServer/src/shared/ChatInterface.cpp index 1ad72571..c52044b8 100755 --- a/engine/server/application/ChatServer/src/shared/ChatInterface.cpp +++ b/engine/server/application/ChatServer/src/shared/ChatInterface.cpp @@ -350,7 +350,7 @@ void ChatInterface::OnGetRoom(unsigned track, unsigned result, const ChatRoom *r if (room) makeRoomName(room, roomName); //printf("!!!!!!!!!!!!got room %s\n", roomName.c_str()); - if (strstr(roomName.c_str(), "group") == NULL) + if (strstr(roomName.c_str(), "group") == nullptr) { ChatServer::putSystemAvatarInRoom(roomName); } @@ -373,7 +373,7 @@ void ChatInterface::OnGetRoom(unsigned track, unsigned result, const ChatRoom *r } } - ChatServerRoomOwner *owner = NULL; + ChatServerRoomOwner *owner = nullptr; if (room) owner = getRoomOwner(room->getRoomID()); @@ -709,12 +709,12 @@ std::string makeCanonicalName(const std::string &characterName) { retVal = toUpper(tmp); } - tmp = strtok(NULL, "."); + tmp = strtok(nullptr, "."); if (tmp) { retVal += (dot + tmp); } - tmp = strtok(NULL, "."); + tmp = strtok(nullptr, "."); if (tmp) { retVal += (dot + tmp); @@ -796,7 +796,7 @@ void ChatInterface::DestroyAvatar(const std::string & characterName) // track how many times we have called RequestGetAnyAvatar() for this particular DestroyAvatar // operation, so that we can stop if we somehow get stuck in an infinite loop - unsigned const trackID = RequestGetAnyAvatar(ChatUnicodeString(avatar.getName()), ChatUnicodeString(avatar.getAPIAddress()), NULL); + unsigned const trackID = RequestGetAnyAvatar(ChatUnicodeString(avatar.getName()), ChatUnicodeString(avatar.getAPIAddress()), nullptr); trackingRequestGetAnyAvatarForDestroy[trackID] = std::make_pair(std::make_pair(ChatUnicodeString(avatar.getName()), ChatUnicodeString(avatar.getAPIAddress())), 1); } @@ -848,7 +848,7 @@ void ChatInterface::sendQueuedHeadersToClient() const unsigned long queuedHeadersSendTime = currentTime + static_cast(s_intervalToSendHeadersToClientSeconds); int numberHeadersSent = 0; - const ChatPersistentMessageToClient * header = NULL; + const ChatPersistentMessageToClient * header = nullptr; for (std::map > >::iterator iter = queuedHeaders.begin(); iter != queuedHeaders.end();) { @@ -900,7 +900,7 @@ void ChatInterface::clearQueuedHeadersForAvatar(const ChatAvatarId & avatarId) void ChatInterface::addQueuedHeaderForAvatar(const ChatAvatarId & avatarId, const ChatPersistentMessageToClient * header, unsigned long sendTime) { - if (header == NULL) + if (header == nullptr) return; std::pair > & queuedHeader = queuedHeaders[avatarId]; @@ -923,7 +923,7 @@ ChatServerAvatarOwner *ChatInterface::getAvatarOwner(const ChatAvatar *avatar) return (*f).second; } } - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -944,7 +944,7 @@ void ChatInterface::OnAddModerator(unsigned track, unsigned result, const ChatAv sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } ChatAvatarId srcId; @@ -1057,7 +1057,7 @@ void ChatInterface::OnRemoveModerator(unsigned track, unsigned result, const Cha sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } ChatAvatarId srcId; @@ -1178,7 +1178,7 @@ void ChatInterface::OnAddFriend(unsigned track, unsigned result, const ChatAvata ChatAvatarId d; makeAvatarId(destName, destAddress, d); - ChatServerAvatarOwner * mo = NULL; + ChatServerAvatarOwner * mo = nullptr; if (srcAvatar) mo = getAvatarOwner(srcAvatar); @@ -1206,7 +1206,7 @@ void ChatInterface::OnRemoveFriend(unsigned track, unsigned result, const ChatAv ChatAvatarId d; makeAvatarId(destName, destAddress, d); - ChatServerAvatarOwner * mo = NULL; + ChatServerAvatarOwner * mo = nullptr; if (srcAvatar) mo = getAvatarOwner(srcAvatar); @@ -1245,7 +1245,7 @@ void ChatInterface::OnIgnoreStatus(unsigned track, unsigned result, const ChatAv } } - ChatServerAvatarOwner * mo = NULL; + ChatServerAvatarOwner * mo = nullptr; if (srcAvatar) mo = getAvatarOwner(srcAvatar); if(mo) @@ -1281,7 +1281,7 @@ void ChatInterface::OnFriendStatus(unsigned track, unsigned result, const ChatAv idList.push_back(id); } } - ChatServerAvatarOwner * mo = NULL; + ChatServerAvatarOwner * mo = nullptr; if (srcAvatar) mo = getAvatarOwner(srcAvatar); if(mo) @@ -1304,7 +1304,7 @@ void ChatInterface::OnReceiveFriendLogin(const ChatAvatar *srcAvatar, const Chat PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceiveFriendLogin"); UNREF(srcAddress); - ChatServerAvatarOwner * owner = NULL; + ChatServerAvatarOwner * owner = nullptr; if (destAvatar) owner = getAvatarOwner(destAvatar); if(owner) @@ -1332,7 +1332,7 @@ void ChatInterface::OnReceiveFriendLogout(const ChatAvatar *srcAvatar, const Cha PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceiveFriendLogout"); UNREF(srcAddress); - ChatServerAvatarOwner * owner = NULL; + ChatServerAvatarOwner * owner = nullptr; if (destAvatar) owner = getAvatarOwner(destAvatar); if(owner) @@ -1395,7 +1395,7 @@ void ChatInterface::OnRemoveIgnore(unsigned track, unsigned result, const ChatAv ChatAvatarId d; makeAvatarId(destName, destAddress, d); - ChatServerAvatarOwner * mo = NULL; + ChatServerAvatarOwner * mo = nullptr; if (srcAvatar) mo = getAvatarOwner(srcAvatar); if(mo) @@ -1435,7 +1435,7 @@ void ChatInterface::OnLoginAvatar(unsigned track, unsigned result, const ChatAva if ((result == CHATRESULT_SUCCESS) && newAvatar) { // destroy chat avatar - unsigned const trackID = RequestDestroyAvatar(newAvatar, NULL); + unsigned const trackID = RequestDestroyAvatar(newAvatar, nullptr); trackingRequestGetAnyAvatarForDestroy[trackID] = iterFind->second; } @@ -1504,7 +1504,7 @@ void ChatInterface::OnLoginAvatar(unsigned track, unsigned result, const ChatAva static Unicode::String wideFilter = Unicode::narrowToWide(""); static ChatUnicodeString swgNode(wideSWG.data(), wideSWG.size()); static ChatUnicodeString filter(wideFilter.data(), wideFilter.size()); - IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, NULL)); + IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, nullptr)); } } else @@ -1525,11 +1525,11 @@ void ChatInterface::OnLoginAvatar(unsigned track, unsigned result, const ChatAva if(ChatServer::isGod(f->second)) { - RequestSetAvatarAttributes(newAvatar, AVATARATTR_GM, NULL); + RequestSetAvatarAttributes(newAvatar, AVATARATTR_GM, nullptr); } else { - RequestSetAvatarAttributes(newAvatar, 0, NULL); + RequestSetAvatarAttributes(newAvatar, 0, nullptr); } ChatServer::chatConnectedAvatar((*f).second, *newAvatar); @@ -1549,7 +1549,7 @@ void ChatInterface::OnLoginAvatar(unsigned track, unsigned result, const ChatAva //ChatServer::getFriendsList(id); clearQueuedHeadersForAvatar(avId); - IGNORE_RETURN(RequestGetPersistentHeaders(newAvatar, NULL)); + IGNORE_RETURN(RequestGetPersistentHeaders(newAvatar, nullptr)); //REPORT_LOG(true, ("Connection to chat system for %s.%s.%s confirmed\n", avatar.GetGameCode().c_str(), avatar.GetGameServerName().c_str(), avatar.GetCharacterName().c_str())); }//lint !e429 Custodial pointer 'owner' has not been freed or returned // jrandall avatar owns it pendingAvatars.erase(f); @@ -1560,7 +1560,7 @@ void ChatInterface::OnLoginAvatar(unsigned track, unsigned result, const ChatAva // the time they connected to the connection server and the time // this message arrived from the chat backend. if (newAvatar) - IGNORE_RETURN(RequestLogoutAvatar(newAvatar, NULL)); + IGNORE_RETURN(RequestLogoutAvatar(newAvatar, nullptr)); } } ChatOnConnectAvatar const connect; @@ -1585,7 +1585,7 @@ void ChatInterface::OnCreateRoom(unsigned track,unsigned result, const ChatRoom static ChatUnicodeString swgNode(wideSWG.data(), wideSWG.size()); static ChatUnicodeString filter(wideFilter.data(), wideFilter.size()); //printf("!!!!Calling GetRoomSummaries from OnCreateRoom\n"); - //IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, NULL)); + //IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, nullptr)); ChatRoomData roomData; @@ -1598,7 +1598,7 @@ void ChatInterface::OnCreateRoom(unsigned track,unsigned result, const ChatRoom //Unicode::String wideRoomName(newRoom->getRoomName().string_data, newRoom->getRoomName().string_length); std::string roomName; makeRoomName(newRoom, roomName); - if (strstr(roomName.c_str(), "group") == NULL) + if (strstr(roomName.c_str(), "group") == nullptr) { ChatServer::putSystemAvatarInRoom(roomName); } @@ -1644,7 +1644,7 @@ void ChatInterface::OnGetRoomSummaries(unsigned track, unsigned result, unsigned std::unordered_map::const_iterator f = roomList.find(lowerRoomName); if(f == roomList.end()) { - RequestGetRoom(foundRooms[i].getRoomAddress(), NULL); + RequestGetRoom(foundRooms[i].getRoomAddress(), nullptr); //ChatServerRoomOwner * o = new ChatServerRoomOwner((*i)); //(*i)->SetRoomOwnerPtr(o); //IGNORE_RETURN(roomList.insert(std::make_pair(lowerRoomName, *o))); @@ -1664,7 +1664,7 @@ const ChatServerRoomOwner *ChatInterface::getRoomOwner(const std::string & roomN { return &((*f).second); } - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -1680,7 +1680,7 @@ ChatServerRoomOwner *ChatInterface::getRoomOwner(unsigned roomId) } ++f; } - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -1727,13 +1727,13 @@ void ChatInterface::OnDestroyRoom(unsigned track, unsigned result, void *user) static Unicode::String wideFilter = Unicode::narrowToWide(""); static ChatUnicodeString swgNode(wideSWG.data(), wideSWG.size()); static ChatUnicodeString filter(wideFilter.data(), wideFilter.size()); - //IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, NULL)); + //IGNORE_RETURN(RequestGetRoomSummaries(swgNode, filter, nullptr)); ChatAvatarId destroyer; RoomOwnerSequencePair *pair = (RoomOwnerSequencePair *)user; - const ChatServerRoomOwner * owner = NULL; + const ChatServerRoomOwner * owner = nullptr; unsigned sequence = 0; if (pair) { @@ -1805,7 +1805,7 @@ void ChatInterface::OnDestroyAvatar(unsigned track, unsigned result, const ChatA // stop if it looks like we're in an infinite loop if (iterFind->second.second <= 25) { - unsigned const trackID = RequestGetAnyAvatar(iterFind->second.first.first, iterFind->second.first.second, NULL); + unsigned const trackID = RequestGetAnyAvatar(iterFind->second.first.first, iterFind->second.first.second, nullptr); trackingRequestGetAnyAvatarForDestroy[trackID] = std::make_pair(iterFind->second.first, (iterFind->second.second + 1)); } } @@ -1828,13 +1828,13 @@ void ChatInterface::OnGetAnyAvatar(unsigned track, unsigned result, const ChatAv // can only destroy the avatar if he is logged in if (loggedIn) { - unsigned const trackID = RequestDestroyAvatar(foundAvatar, NULL); + unsigned const trackID = RequestDestroyAvatar(foundAvatar, nullptr); trackingRequestGetAnyAvatarForDestroy[trackID] = iterFind->second; } // log in the chat avatar so we can destroy him else { - unsigned const trackID = RequestLoginAvatar(foundAvatar->getUserID(), foundAvatar->getName(), foundAvatar->getAddress(), NULL); + unsigned const trackID = RequestLoginAvatar(foundAvatar->getUserID(), foundAvatar->getName(), foundAvatar->getAddress(), nullptr); trackingRequestGetAnyAvatarForDestroy[trackID] = iterFind->second; } } @@ -1850,9 +1850,9 @@ void ChatInterface::OnReceiveForcedLogout(const ChatAvatar *oldAvatar) ChatServer::fileLog(false, "ChatInterface", "OnReceiveForcedLogout() oldAvatar(%s)", ChatServer::getFullChatAvatarName(oldAvatar).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceiveForcedLogout"); - if (oldAvatar == NULL) + if (oldAvatar == nullptr) { - DEBUG_WARNING(true, ("We received an OnReceiveForcedLogout with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnReceiveForcedLogout with a success result code but nullptr data. This is an error that the API should never give.")); return; } ChatAvatarId id; @@ -1876,9 +1876,9 @@ void ChatInterface::OnEnterRoom(unsigned track, unsigned result, const ChatAvata PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnEnterRoom"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnEnterRoom with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnEnterRoom with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2097,9 +2097,9 @@ void ChatInterface::OnAddBan(unsigned track, unsigned result, const ChatAvatar * PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnAddBan"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnAddBan with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnAddBan with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2113,7 +2113,7 @@ void ChatInterface::OnAddBan(unsigned track, unsigned result, const ChatAvatar * sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } ChatAvatarId srcId; @@ -2218,9 +2218,9 @@ void ChatInterface::OnRemoveBan(unsigned track, unsigned result, const ChatAvata PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnRemoveBan"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnRemoveBan with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnRemoveBan with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2234,7 +2234,7 @@ void ChatInterface::OnRemoveBan(unsigned track, unsigned result, const ChatAvata sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } ChatAvatarId srcId; @@ -2337,23 +2337,21 @@ void ChatInterface::OnAddInvite(unsigned track, unsigned result, const ChatAvata PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnAddInvite"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnAddInvite with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnAddInvite with a success result code but nullptr data. This is an error that the API should never give.")); return; } AvatarIdSequencePair *pair = (AvatarIdSequencePair *)user; - unsigned sequence = 0; ChatAvatarId destId; if (pair) { destId = pair->avatar; - sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } ChatAvatarId srcId; @@ -2378,7 +2376,7 @@ void ChatInterface::OnAddInvite(unsigned track, unsigned result, const ChatAvata { // Calling this on a room will cause the API to cache the room // and to receive room updates for the room. - RequestGetRoom(destRoom->getAddress(), NULL); + RequestGetRoom(destRoom->getAddress(), nullptr); // Send the room data for the room the avatar was invited to join // since the room may be private and may be unknown to the player @@ -2455,9 +2453,9 @@ void ChatInterface::OnRemoveInvite(unsigned track, unsigned result, const ChatAv PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnRemoveInvite"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnRemoveInvite with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnRemoveInvite with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2471,7 +2469,7 @@ void ChatInterface::OnRemoveInvite(unsigned track, unsigned result, const ChatAv sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } std::string roomName; @@ -2555,9 +2553,9 @@ void ChatInterface::OnLeaveRoom(unsigned track, unsigned result, const ChatAvata PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnLeaveRoom"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnLeaveRoom with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnLeaveRoom with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2645,15 +2643,13 @@ void ChatInterface::OnKickAvatar(unsigned track, unsigned result, const ChatAvat AvatarIdSequencePair *pair = (AvatarIdSequencePair *)user; - unsigned sequence = 0; ChatAvatarId kickedId; if (pair) { kickedId = pair->avatar; - sequence = pair->sequence; delete pair; - pair = NULL; + pair = nullptr; } std::string roomName; @@ -2755,9 +2751,9 @@ void ChatInterface::OnGetPersistentMessage(unsigned track, unsigned result, Chat ChatServer::fileLog(false, "ChatInterface", "OnGetPersistentMessage() track(%u) result(%u) destAvatar(%s)", track, result, ChatServer::getFullChatAvatarName(destAvatar).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnGetPersistentMessage"); - if (result == CHATRESULT_SUCCESS && (destAvatar == NULL)) + if (result == CHATRESULT_SUCCESS && (destAvatar == nullptr)) { - DEBUG_WARNING(true, ("We received an OnGetPersistentMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnGetPersistentMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } UNREF(user); @@ -2807,9 +2803,9 @@ void ChatInterface::OnGetPersistentHeaders(unsigned track, unsigned result, Chat ChatServer::fileLog(false, "ChatInterface", "OnGetPersistentHeaders() track(%u) result(%u) destAvatar(%s)", track, result, ChatServer::getFullChatAvatarName(destAvatar).c_str(), listLength); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnGetPersistentHeaders"); - if (result == CHATRESULT_SUCCESS && (destAvatar == NULL)) + if (result == CHATRESULT_SUCCESS && (destAvatar == nullptr)) { - DEBUG_WARNING(true, ("We received an OnGetPersistentHeaders with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnGetPersistentHeaders with a success result code but nullptr data. This is an error that the API should never give.")); return; } UNREF(track); @@ -2876,9 +2872,9 @@ void ChatInterface::OnReceivePersistentMessage(const ChatAvatar *destAvatar, con ChatServer::fileLog(false, "ChatInterface", "OnReceivePersistentMessage() destAvatar(%s)", ChatServer::getFullChatAvatarName(destAvatar).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceivePersistentMessage"); - if (destAvatar == NULL) + if (destAvatar == nullptr) { - DEBUG_WARNING(true, ("We received an OnREceivePersistentMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnREceivePersistentMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } if (!header) @@ -2910,9 +2906,9 @@ void ChatInterface::OnSendRoomMessage(unsigned track, unsigned result, const Cha ChatServer::fileLog(false, "ChatInterface", "OnSendRoomMessage() track(%u) result(%u) srcAvatar(%s) destRoom(%s)", track, result, ChatServer::getFullChatAvatarName(srcAvatar).c_str(), ChatServer::getChatRoomNameNarrow(destRoom).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnSendRoomMessage"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL || destRoom == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr || destRoom == nullptr)) { - DEBUG_WARNING(true, ("We received an OnsendRoomMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnsendRoomMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } UNREF(srcAvatar); @@ -2931,7 +2927,7 @@ void ChatInterface::OnReceiveRoomMessage(const ChatAvatar *srcAvatar, const Chat PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceiveRoomMessage"); if(! srcAvatar || ! destAvatar || ! destRoom) { - DEBUG_WARNING(true, ("We received an OnREceiveRoomMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnREceiveRoomMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } @@ -2995,9 +2991,9 @@ void ChatInterface::OnSendInstantMessage(unsigned track, unsigned result, const PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnSendInstantMessage"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr)) { - DEBUG_WARNING(true, ("We received an OnSendInstantMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnSendInstantMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } UNREF(srcAvatar); @@ -3015,9 +3011,9 @@ void ChatInterface::OnReceiveInstantMessage(const ChatAvatar *srcAvatar, const C ChatServer::fileLog(false, "ChatInterface", "OnReceiveInstantMessage() srcAvatar(%s) destAvatar(%s)", ChatServer::getFullChatAvatarName(srcAvatar).c_str(), ChatServer::getFullChatAvatarName(destAvatar).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnReceiveInstantMessage"); - if ((srcAvatar == NULL || destAvatar == NULL)) + if ((srcAvatar == nullptr || destAvatar == nullptr)) { - DEBUG_WARNING(true, ("We received an OnReceiveInstantMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnReceiveInstantMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } ChatAvatarId fromId; @@ -3052,9 +3048,9 @@ void ChatInterface::OnSendPersistentMessage(unsigned track, unsigned result, con ChatServer::fileLog(false, "ChatInterface", "OnSendPersistentMessage() track(%u) result(%u) srcAvatar(%s)", track, result, ChatServer::getFullChatAvatarName(srcAvatar).c_str()); PROFILER_AUTO_BLOCK_DEFINE("ChatInterface - OnSendPersistentMessage"); - if (result == CHATRESULT_SUCCESS && (srcAvatar == NULL)) + if (result == CHATRESULT_SUCCESS && (srcAvatar == nullptr)) { - DEBUG_WARNING(true, ("We received an OnSendPersistentMessage with a success result code but NULL data. This is an error that the API should never give.")); + DEBUG_WARNING(true, ("We received an OnSendPersistentMessage with a success result code but nullptr data. This is an error that the API should never give.")); return; } unsigned sequence = (unsigned)user; @@ -3120,7 +3116,7 @@ void ChatInterface::OnUpdatePersistentMessages(unsigned track, unsigned result, ChatAvatarId targetChatAvatarId; - if (targetAvatar != NULL) + if (targetAvatar != nullptr) { makeAvatarId(*targetAvatar, targetChatAvatarId); } @@ -3130,17 +3126,17 @@ void ChatInterface::OnUpdatePersistentMessages(unsigned track, unsigned result, ChatAvatarId sourceChatAvatarId; NetworkId const *tmpNetworkId = reinterpret_cast(user); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { ChatAvatar const *sourceAvatar = ChatServer::getAvatarByNetworkId(*tmpNetworkId); - if (sourceAvatar != NULL) + if (sourceAvatar != nullptr) { makeAvatarId(*sourceAvatar, sourceChatAvatarId); } delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } ChatServer::fileLog(false, "ChatInterface", "OnUpdatePersistentMessage() track(%u) result(%u) sourceAvatar(%s) targetAvatar(%s)", track, result, sourceChatAvatarId.getFullName().c_str(), targetChatAvatarId.getFullName().c_str()); diff --git a/engine/server/application/ChatServer/src/shared/ChatInterface.h b/engine/server/application/ChatServer/src/shared/ChatInterface.h index a42a6ecf..31c3bed6 100755 --- a/engine/server/application/ChatServer/src/shared/ChatInterface.h +++ b/engine/server/application/ChatServer/src/shared/ChatInterface.h @@ -166,87 +166,6 @@ private: std::map, int> > trackingRequestGetAnyAvatarForDestroy; }; -#if 0 - -//----------------------------------------------------------------------- - -class ChatInterface : public ChatAPI -{ -public: - ChatInterface (const std::string & strGameCode, - const std::string & strGatewayServerIP, - const unsigned short sGatewayServerPort, - const std::string & strBackupGatewayServerIP, - const unsigned short sBackupGatewayServerPort - ); - - virtual ~ChatInterface (); //lint !e1510 base class 'ChatAPI' has no destructor // jrandall - this is beyond my control - - - void checkRoomExpirations (); - void ConnectPlayer (const unsigned int suid, const std::string & characterName, const NetworkId & networkId); - void deferChatMessageFor (const NetworkId & id, const Archive::ByteStream & bs); - void destroyRoomByName (const std::string & roomName); - - const std::hash_map & getRoomList () const; - const ChatServerAvatarOwner *findAvatar(const ChatAvatarId & avatarId); - - void leaveRoom (const ChatAvatarId & avatarId, const std::string & roomName); - - //--- ChatAPI virtual overrides - virtual void OnConnectAvatar (const std::string & track, const unsigned int resultCode, const ChatAvatar & avatar); - virtual void OnAddFriend (const unsigned int sequence, const std::string & track, const unsigned int nResultCode, const ChatAvatar & requestingAvatar, const ChatAvatar & friendAvatar); - virtual void OnRemoveFriend (const unsigned int sequence, const std::string & track, const unsigned int nResultCode, const ChatAvatar & requestingAvatar, const ChatAvatar & friendAvatar); - virtual void OnAddIgnore (const unsigned int sequence, const std::string & track, const unsigned int nResultCode, const ChatAvatar & requestingAvatar, const ChatAvatar & ignoreAvatar); - virtual void OnRemoveIgnore (const unsigned int sequence, const std::string & track, const unsigned int nResultCode, const ChatAvatar & requestingAvatar, const ChatAvatar & ignoreAvatar); - virtual void OnAddRoomModerator (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatRoom & room, const unsigned int nRequestingAvatarUID, const ChatAvatar & moderator); - virtual void OnCreateRoom (const unsigned int sequence, const std::string & track, const unsigned int nResultCode, const ChatRoom & room); - virtual void OnDestroyRoom (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatRoom & room, const std::string & strCharacterName, const std::string & strGameServerName, const std::string & strGameCode); - virtual void OnDisconnectAvatar (const std::string & track, const unsigned int nResultCode, const ChatAvatar & toAvatar); - virtual void OnDisconnectAvatarNotify (const ChatAvatar & toAvatar); - virtual void OnEnterRoom (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatRoom & room, const ChatAvatar & avatar); - virtual void OnLeaveRoom (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatRoom & room, const ChatAvatar & avatar); - virtual void OnReceiveInstantMessage (const ChatAvatar & toAvatar, const ChatAvatar & fromAvatar, const Unicode::String & ustrMessage, const Unicode::String & oob); - virtual void OnReceivePersistentMessage (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatPersistentMessage & message); - virtual void OnReceivePersistentMessageHeader (const ChatPersistentMessageHeader & header); - virtual void OnReceivePersistentMessageHeaders (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatAvatar & toAvatar, const std::vector & headers); - virtual void OnReceiveRoomMessage (const unsigned int nSequenceID, const ChatRoom & room, const std::string & strFromCharacterName, const std::string & strFromGameServerName, const std::string & strFromGameCode, const Unicode::String & ustrMessage, const Unicode::String & outOfBand, unsigned messageID); - virtual void OnConnect (const unsigned int resultCode); - virtual void OnReceiveRooms (const std::string & track, const unsigned int nResultCode, const std::vector & rooms); - virtual void OnRemoveRoomModerator (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatRoom & room, const unsigned int nRequestingAvatarUID, const ChatAvatar & moderator); - virtual void OnSendInstantMessage (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatAvatar & sendingAvatar); - virtual void OnSendPersistentMessage (const unsigned int nSequenceID, const std::string & track, const unsigned int nResultCode, const ChatAvatar& sendingAvatar); - virtual void OnSendRoomMessage (const unsigned int sequence, const std::string & track, const unsigned int resultCode); - virtual void OnUpdateFriendStatus (const ChatAvatar & toAvatar, const ChatAvatar & fromAvatar, const bool bIsConnected); - virtual void OnReceiveRoomInvitation (const std::string & strRoomName, const ChatAvatar & invitorAvatar, const ChatAvatar & inviteeAvatar); - virtual void OnSendRoomInvitation (const unsigned int sequence, const std::string & track, const unsigned int resultCode, const ChatRoom & room, const bool isOnline, const ChatAvatar & invitor, const ChatAvatar & invitee); - - const ChatServerRoomOwner * getRoomByName (const std::string & roomName) const; - - void disconnectPlayer (const ChatAvatarId & avatarId); - void queryRoom (const NetworkId & id, ConnectionServerConnection * connection, const unsigned int sequenceId, const std::string & roomName); - void queryRoom (const NetworkId & id, ConnectionServerConnection * connection, const unsigned int sequenceId, const unsigned int roomId); - void requestRoomList (const NetworkId & id, ConnectionServerConnection * connection); - void sendMessageToAllAvatars (const GameNetworkMessage & message); - bool sendMessageToPendingAvatar(const ChatAvatarId &id, const GameNetworkMessage &message); - -private: - void sendMessageToAvatar (const ChatAvatar & avatar, const GameNetworkMessage & message); - void sendMessageToAvatar (const ChatAvatarId & avatar, const GameNetworkMessage & message); - -private: - ChatInterface & operator = (const ChatInterface & rhs); - ChatInterface(const ChatInterface & source); - std::hash_map pendingAvatars; - std::hash_map, NetworkId::Hash > deferredChatMessages; - std::hash_map roomList; - std::map avatarMap; - time_t lastRoomCheck; - -}; //lint !e1712 default constructor not defined for class - -#endif - std::string toLower(const std::string & source); std::string toUpper(const std::string & source); void makeRoomData(const ChatRoom & room, ChatRoomData & roomData); diff --git a/engine/server/application/ChatServer/src/shared/ChatServer.cpp b/engine/server/application/ChatServer/src/shared/ChatServer.cpp index 76d47a9c..c8e12a6d 100755 --- a/engine/server/application/ChatServer/src/shared/ChatServer.cpp +++ b/engine/server/application/ChatServer/src/shared/ChatServer.cpp @@ -162,7 +162,7 @@ void ChatServerNamespace::cleanChatLog() //----------------------------------------------------------------------- -ChatServer *ChatServer::m_instance = NULL; +ChatServer *ChatServer::m_instance = nullptr; #include @@ -250,7 +250,7 @@ if ((t3 - t2) > (1000 * 5)) static Unicode::String wideFilter = Unicode::narrowToWide(""); static ChatUnicodeString swgNode(wideSWG.data(), wideSWG.size()); static ChatUnicodeString filter(wideFilter.data(), wideFilter.size()); - instance().chatInterface->RequestGetRoomSummaries(swgNode, filter, NULL); + instance().chatInterface->RequestGetRoomSummaries(swgNode, filter, nullptr); } ++i; @@ -286,7 +286,7 @@ gameService(0), planetService(), ownerSystem(0), systemAvatarId("SWG", ConfigChatServer::getClusterName(), "SYSTEM"), -customerServiceServerConnection(NULL), +customerServiceServerConnection(nullptr), m_gameServerConnectionRegistry(), m_voiceChatIdMap() { @@ -452,7 +452,7 @@ void ChatServer::setOwnerSystem(const ChatAvatar * o) Connection *connection = safe_cast(instance().centralServerConnection); - if (connection != NULL) + if (connection != nullptr) { connection->send(bs, true); } @@ -618,7 +618,7 @@ const ChatAvatar * ChatServer::getAvatarByNetworkId(const NetworkId & id) { if (id.getValue() == 0) { - return NULL; + return nullptr; } const ChatAvatar * result = 0; ChatAvatarList::const_iterator f = instance().chatAvatars.find(id); @@ -635,7 +635,7 @@ ChatServer::AvatarExtendedData * ChatServer::getAvatarExtendedDataByNetworkId(co { if (id.getValue() == 0) { - return NULL; + return nullptr; } ChatServer::AvatarExtendedData * result = 0; ChatAvatarList::iterator f = instance().chatAvatars.find(id); @@ -783,7 +783,7 @@ void ChatServer::addFriend(const NetworkId & id, const unsigned int sequence, co unsigned track = instance().chatInterface->RequestAddFriend(from, ChatUnicodeString(friendName.data(), friendName.length()), ChatUnicodeString(friendAddress.data(), friendAddress.length()), - false, NULL); + false, nullptr); instance().pendingRequests[track] = id; } else @@ -810,7 +810,7 @@ void ChatServer::removeFriend(const NetworkId & id, const unsigned int sequence, splitChatAvatarId(friendId, friendName, friendAddress); unsigned track = instance().chatInterface->RequestRemoveFriend(from, ChatUnicodeString(friendName.data(), friendName.length()), - ChatUnicodeString(friendAddress.data(), friendAddress.length()), NULL); + ChatUnicodeString(friendAddress.data(), friendAddress.length()), nullptr); instance().pendingRequests[track] = id; } else @@ -829,7 +829,7 @@ void ChatServer::getFriendsList(const ChatAvatarId &characterName) const ChatAvatar *avatar = getAvatarByNetworkId(id); if (avatar) { - unsigned track = instance().chatInterface->RequestFriendStatus(avatar, NULL); + unsigned track = instance().chatInterface->RequestFriendStatus(avatar, nullptr); instance().pendingRequests[track] = id; } else @@ -857,7 +857,7 @@ void ChatServer::addIgnore(const NetworkId & id, const unsigned int sequence, co unsigned track = instance().chatInterface->RequestAddIgnore(from, ChatUnicodeString(ignoreName.data(), ignoreName.length()), ChatUnicodeString(ignoreAddress.data(), ignoreAddress.length()), - NULL); + nullptr); instance().pendingRequests[track] = id; } else @@ -884,7 +884,7 @@ void ChatServer::removeIgnore(const NetworkId & id, const unsigned int sequence, splitChatAvatarId(ignoreId, ignoreName, ignoreAddress); unsigned track = instance().chatInterface->RequestRemoveIgnore(from, ChatUnicodeString(ignoreName.data(), ignoreName.length()), - ChatUnicodeString(ignoreAddress.data(), ignoreAddress.length()), NULL); + ChatUnicodeString(ignoreAddress.data(), ignoreAddress.length()), nullptr); instance().pendingRequests[track] = id; } else @@ -905,7 +905,7 @@ void ChatServer::getIgnoreList(const ChatAvatarId &characterName) if (avatar) { - unsigned track = instance().chatInterface->RequestIgnoreStatus(avatar, NULL); + unsigned track = instance().chatInterface->RequestIgnoreStatus(avatar, nullptr); instance().pendingRequests[track] = id; } else @@ -1160,7 +1160,7 @@ void ChatServer::createRoom(const NetworkId & id, const unsigned int sequence, c { roomAttr |= ROOMATTR_PRIVATE; } - if (isSystemOwner && (strstr(roomName.c_str(), "system") != NULL)) + if (isSystemOwner && (strstr(roomName.c_str(), "system") != nullptr)) { roomAttr |= ROOMATTR_PERSISTENT; } @@ -1193,7 +1193,7 @@ void ChatServer::deleteAllPersistentMessages(const NetworkId &sourceNetworkId, c ChatAvatar const *avatar = getAvatarByNetworkId(targetNetworkId); - if (avatar != NULL) + if (avatar != nullptr) { { NetworkId *tmpNetworkId = new NetworkId(sourceNetworkId); @@ -1225,7 +1225,7 @@ void ChatServer::deletePersistentMessage(const NetworkId &id, const unsigned int const ChatAvatar *avatar = getAvatarByNetworkId(id); if (avatar) { - instance().chatInterface->RequestUpdatePersistentMessage(avatar, messageId, PERSISTENT_DELETED, NULL); + instance().chatInterface->RequestUpdatePersistentMessage(avatar, messageId, PERSISTENT_DELETED, nullptr); } } @@ -1290,10 +1290,10 @@ void ChatServer::destroyRoom(const std::string & roomName) { ChatServer::fileLog(s_enableChatRoomLogs, "ChatServer", "destroyRoom() roomName(%s)", roomName.c_str()); - if ((strstr(roomName.c_str(), ConfigChatServer::getClusterName()) != NULL) || + if ((strstr(roomName.c_str(), ConfigChatServer::getClusterName()) != nullptr) || (strstr(roomName.c_str(), toLower(std::string(ConfigChatServer::getClusterName() ) ).c_str() ) )) { - if ((strstr(roomName.c_str(), "GroupChat") != NULL) || (strstr(roomName.c_str(), "groupchat") != NULL)) + if ((strstr(roomName.c_str(), "GroupChat") != nullptr) || (strstr(roomName.c_str(), "groupchat") != nullptr)) { size_t pos = roomName.rfind("."); if (pos != roomName.npos) @@ -1311,7 +1311,7 @@ void ChatServer::destroyRoom(const std::string & roomName) const ChatServerRoomOwner *owner = instance().chatInterface->getRoomOwner(roomName); if (!instance().ownerSystem) { - DEBUG_WARNING(true, ("Chat ownerSystem is NULL")); + DEBUG_WARNING(true, ("Chat ownerSystem is nullptr")); return; } if (owner) @@ -1331,7 +1331,7 @@ void ChatServer::disconnectAvatar(const ChatAvatar & avatar) if (&avatar == instance().ownerSystem) { - instance().ownerSystem = NULL; + instance().ownerSystem = nullptr; } ChatAvatarList::iterator i; for(i = instance().chatAvatars.begin(); i != instance().chatAvatars.end(); ++i) @@ -1423,7 +1423,7 @@ void ChatServer::enterRoom(const ChatAvatarId & id, const std::string & roomName const ChatAvatar *avatar = getAvatarByNetworkId(getNetworkIdByAvatarId(id)); if (room && avatar) { - instance().chatInterface->RequestEnterRoom(avatar, room->getAddress(), NULL); + instance().chatInterface->RequestEnterRoom(avatar, room->getAddress(), nullptr); } else { @@ -1450,7 +1450,7 @@ void ChatServer::putSystemAvatarInRoom(const std::string & roomName) const ChatServerRoomOwner *room = instance().chatInterface->getRoomOwner(roomName); if (room && instance().ownerSystem) { - instance().chatInterface->RequestEnterRoom(instance().ownerSystem, room->getAddress(), NULL); + instance().chatInterface->RequestEnterRoom(instance().ownerSystem, room->getAddress(), nullptr); } } @@ -1619,7 +1619,7 @@ void ChatServer::invite(const NetworkId & id, const ChatAvatarId & avatarId, con ChatServer::fileLog(s_enableChatRoomLogs, "ChatServer", "invite() id(%s) avatar(%s) roomName(%s)", id.getValueString().c_str(), avatarId.getFullName().c_str(), roomName.c_str()); // Try to get an invitor - ChatAvatar const * invitor = NULL; + ChatAvatar const * invitor = nullptr; if (id != NetworkId::cms_invalid) { invitor = getAvatarByNetworkId(id); @@ -1738,7 +1738,7 @@ void ChatServer::inviteGroupMembers(const NetworkId & id, const ChatAvatarId & a void ChatServer::removeSystemAvatarFromRoom(const ChatRoom *room) { - ChatServer::fileLog(s_enableChatRoomLogs, "ChatServer", "removeSystemAvatarFromRoom() room(%s)", (room != NULL) ? toNarrowString(room->getRoomName()).c_str() : "NULL"); + ChatServer::fileLog(s_enableChatRoomLogs, "ChatServer", "removeSystemAvatarFromRoom() room(%s)", (room != nullptr) ? toNarrowString(room->getRoomName()).c_str() : "nullptr"); if (!room || !instance().ownerSystem) { @@ -1754,7 +1754,7 @@ void ChatServer::removeSystemAvatarFromRoom(const ChatRoom *room) } } - instance().chatInterface->RequestLeaveRoom(instance().ownerSystem, room->getAddress(), NULL); + instance().chatInterface->RequestLeaveRoom(instance().ownerSystem, room->getAddress(), nullptr); } //----------------------------------------------------------------------- @@ -1991,7 +1991,7 @@ void ChatServer::sendInstantMessage(const ChatAvatarId & from, const ChatAvatarI const NetworkId &toNetworkId = getNetworkIdByAvatarId(to); const ChatAvatar * toAvatar = getAvatarByNetworkId(toNetworkId); - if (toAvatar != NULL) + if (toAvatar != nullptr) { ChatServer::fileLog(false, "ChatServer", "sendInstantMessage() resolved tell locally"); @@ -2022,7 +2022,7 @@ void ChatServer::sendInstantMessage(const ChatAvatarId & from, const ChatAvatarI IGNORE_RETURN(instance().chatInterface->RequestSendInstantMessage(fromAvatar, ChatUnicodeString(friendName.data(), friendName.size()), ChatUnicodeString(friendAddress.data(), friendAddress.size()), - ChatUnicodeString(message.data(), message.size()), ChatUnicodeString(outOfBand.data(), outOfBand.size()), NULL)); + ChatUnicodeString(message.data(), message.size()), ChatUnicodeString(outOfBand.data(), outOfBand.size()), nullptr)); } } } @@ -2054,7 +2054,7 @@ void ChatServer::sendInstantMessage(const NetworkId & fromId, const unsigned int { return; } - else if (::time(NULL) < aed->unsquelchTime) // still in squelch period + else if (::time(nullptr) < aed->unsquelchTime) // still in squelch period { return; } @@ -2076,14 +2076,14 @@ void ChatServer::sendInstantMessage(const NetworkId & fromId, const unsigned int Unicode::String wideFrom; Unicode::String wideTo; - if (from != NULL) + if (from != nullptr) { makeAvatarId(*from, fromAvatarId); wideFrom = (Unicode::narrowToWide(fromAvatarId.getFullName())); } ChatAvatarId toAvatarId; - if (toAvatar != NULL) + if (toAvatar != nullptr) { ChatServer::fileLog(false, "ChatServer", "sendInstantMessage() resolved tell locally"); @@ -2158,7 +2158,7 @@ void ChatServer::sendPersistentMessage(const ChatAvatarId & from, const ChatAvat ChatUnicodeString(subject.data(), subject.size()), ChatUnicodeString(message.data(), message.size()), ChatUnicodeString(oob.data(), oob.size()), - NULL + nullptr ); Unicode::String log; @@ -2187,7 +2187,7 @@ void ChatServer::sendPersistentMessage(const NetworkId & fromId, const unsigned // to.cluster.c_str(), to.name.c_str()); UNREF(sequenceId); ChatServer::AvatarExtendedData * aed = getAvatarExtendedDataByNetworkId(fromId); - const ChatAvatar * from = (aed ? &(aed->chatAvatar) : NULL); + const ChatAvatar * from = (aed ? &(aed->chatAvatar) : nullptr); if(from) { // see if player is squelched @@ -2197,7 +2197,7 @@ void ChatServer::sendPersistentMessage(const NetworkId & fromId, const unsigned { return; } - else if (::time(NULL) < aed->unsquelchTime) // still in squelch period + else if (::time(nullptr) < aed->unsquelchTime) // still in squelch period { return; } @@ -2225,7 +2225,7 @@ void ChatServer::sendPersistentMessage(const NetworkId & fromId, const unsigned ChatAvatarId fromAvatarId; - if (from != NULL) + if (from != nullptr) { makeAvatarId(*from, fromAvatarId); } @@ -2255,7 +2255,7 @@ void ChatServer::sendRoomMessage(const ChatAvatarId &id, const std::string & roo if (!instance().ownerSystem) { - DEBUG_WARNING(true, ("Chat ownerSystem is NULL")); + DEBUG_WARNING(true, ("Chat ownerSystem is nullptr")); return; } // get room id @@ -2265,7 +2265,7 @@ void ChatServer::sendRoomMessage(const ChatAvatarId &id, const std::string & roo { const ChatAvatar *sender = instance().ownerSystem; - IGNORE_RETURN(instance().chatInterface->RequestSendRoomMessage(sender, (*f).second.getAddress(), ChatUnicodeString(msg.data(), msg.size()), ChatUnicodeString(oob.data(), oob.size()), NULL)); + IGNORE_RETURN(instance().chatInterface->RequestSendRoomMessage(sender, (*f).second.getAddress(), ChatUnicodeString(msg.data(), msg.size()), ChatUnicodeString(oob.data(), oob.size()), nullptr)); } } } @@ -2280,7 +2280,7 @@ void ChatServer::sendRoomMessage(const NetworkId & id, const unsigned int sequen UNREF(sequence); ChatServer::AvatarExtendedData * aed = getAvatarExtendedDataByNetworkId(id); - const ChatAvatar * sender = (aed ? &(aed->chatAvatar) : NULL); + const ChatAvatar * sender = (aed ? &(aed->chatAvatar) : nullptr); const ChatServerRoomOwner *room = instance().chatInterface->getRoomOwner(roomId); if(sender && room) { @@ -2296,7 +2296,7 @@ void ChatServer::sendRoomMessage(const NetworkId & id, const unsigned int sequen aed->nonSpatialCharCount += msg.size(); // sync chat character count with game server - timeNow = ::time(NULL); + timeNow = ::time(nullptr); if ((timeNow > aed->chatSpamNextTimeToSyncWithGameServer) || (timeNow > aed->chatSpamTimeEndInterval)) { GenericValueTypeMessage, std::pair > > chatStatistics("ChatStatisticsCS", std::make_pair(std::make_pair(id, static_cast(aed->chatSpamTimeEndInterval)), std::make_pair(aed->spatialCharCount, aed->nonSpatialCharCount))); @@ -2322,7 +2322,7 @@ void ChatServer::sendRoomMessage(const NetworkId & id, const unsigned int sequen allowToSpeak = false; squelched = true; } - else if (::time(NULL) < aed->unsquelchTime) // still in squelch period + else if (::time(nullptr) < aed->unsquelchTime) // still in squelch period { allowToSpeak = false; squelched = true; @@ -2393,7 +2393,7 @@ void ChatServer::sendStandardRoomMessage(const ChatAvatarId &senderId, const std } if (sender) { - IGNORE_RETURN(instance().chatInterface->RequestSendRoomMessage(sender, (*f).second.getAddress(), ChatUnicodeString(msg.data(), msg.size()), ChatUnicodeString(oob.data(), oob.size()), NULL)); + IGNORE_RETURN(instance().chatInterface->RequestSendRoomMessage(sender, (*f).second.getAddress(), ChatUnicodeString(msg.data(), msg.size()), ChatUnicodeString(oob.data(), oob.size()), nullptr)); } } } @@ -2505,7 +2505,7 @@ std::string ChatServer::getFullChatAvatarName(ChatAvatar const *chatAvatar) { std::string result; - if (chatAvatar != NULL) + if (chatAvatar != nullptr) { result += toNarrowString(chatAvatar->getName()); result += '.'; @@ -2513,7 +2513,7 @@ std::string ChatServer::getFullChatAvatarName(ChatAvatar const *chatAvatar) } else { - result = "NULL"; + result = "nullptr"; } return result; @@ -2539,7 +2539,7 @@ std::string ChatServer::getConnectionAddress(Connection const *connection) { std::string result; - if (connection != NULL) + if (connection != nullptr) { char text[256]; snprintf(text, sizeof(text), "%s:%d", connection->getRemoteAddress().c_str(), connection->getRemotePort()); @@ -2547,7 +2547,7 @@ std::string ChatServer::getConnectionAddress(Connection const *connection) } else { - result = "NULL"; + result = "nullptr"; } return result; @@ -2566,13 +2566,13 @@ Unicode::String ChatServer::getChatRoomName(ChatRoom const *chatRoom) { Unicode::String result; - if (chatRoom != NULL) + if (chatRoom != nullptr) { result = toUnicodeString(chatRoom->getRoomName()); } else { - result = Unicode::narrowToWide("NULL"); + result = Unicode::narrowToWide("nullptr"); } return result; @@ -2582,12 +2582,12 @@ Unicode::String ChatServer::getChatRoomName(ChatRoom const *chatRoom) void ChatServer::clearCustomerServiceServerConnection() { - if (instance().customerServiceServerConnection != NULL) + if (instance().customerServiceServerConnection != nullptr) { instance().customerServiceServerConnection->disconnect(); } - instance().customerServiceServerConnection = NULL; + instance().customerServiceServerConnection = nullptr; } // ---------------------------------------------------------------------- @@ -2596,7 +2596,7 @@ void ChatServer::connectToCustomerServiceServer(const std::string &address, cons { //DEBUG_REPORT_LOG(true, ("***ChatServer::connectToCustomerServiceServer() address(%s) port(%d)\n", address.c_str(), port)); - if (instance().customerServiceServerConnection != NULL) + if (instance().customerServiceServerConnection != nullptr) { instance().customerServiceServerConnection->disconnect(); } @@ -2670,7 +2670,7 @@ bool ChatServer::isValidChatAvatarName(Unicode::String const &chatAvatarName) void ChatServer::logChatMessage(Unicode::String const &logPlayer, Unicode::String const &fromPlayer, Unicode::String const &toPlayer, Unicode::String const &text, Unicode::String const &channel) { - DEBUG_WARNING(toPlayer.empty(), ("toPlayer is NULL")); + DEBUG_WARNING(toPlayer.empty(), ("toPlayer is nullptr")); Unicode::String lowerLogPlayer(Unicode::toLower(logPlayer)); Unicode::String lowerFromPlayer(Unicode::toLower(fromPlayer)); @@ -2760,7 +2760,7 @@ void ChatServer::requestTransferAvatar(const TransferCharacterData & request) ChatAvatarId destinationAvatar("SWG", destination, request.getDestinationCharacterName()); - instance().chatInterface->RequestTransferAvatar(request.getSourceStationId(), makeChatUnicodeString(sourceAvatar.getName()), makeChatUnicodeString(sourceAvatar.getAPIAddress()), request.getDestinationStationId(), makeChatUnicodeString(destinationAvatar.getName()), makeChatUnicodeString(destinationAvatar.getAPIAddress()), true, NULL); + instance().chatInterface->RequestTransferAvatar(request.getSourceStationId(), makeChatUnicodeString(sourceAvatar.getName()), makeChatUnicodeString(sourceAvatar.getAPIAddress()), request.getDestinationStationId(), makeChatUnicodeString(destinationAvatar.getName()), makeChatUnicodeString(destinationAvatar.getAPIAddress()), true, nullptr); } } @@ -2845,7 +2845,7 @@ void ChatServer::handleChatStatisticsFromGameServer(NetworkId const & character, // non-spatial chat to report to the game server else if (aed->nonSpatialCharCount != nonSpatialNumCharacters) { - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); if (timeNow > aed->chatSpamNextTimeToSyncWithGameServer) { GenericValueTypeMessage, std::pair > > chatStatistics("ChatStatisticsCS", std::make_pair(std::make_pair(character, static_cast(aed->chatSpamTimeEndInterval)), std::make_pair(aed->spatialCharCount, aed->nonSpatialCharCount))); @@ -2904,7 +2904,7 @@ void ChatServer::sendToGameServerById(unsigned const connectionId, GameNetworkMe GameServerConnection *ChatServer::getGameServerConnectionFromId(unsigned int sequence) { - GameServerConnection * result = NULL; + GameServerConnection * result = nullptr; std::unordered_map::iterator f = m_gameServerConnectionRegistry.find(sequence); if(f != m_gameServerConnectionRegistry.end()) { diff --git a/engine/server/application/ChatServer/src/shared/ChatServerRoomOwner.cpp b/engine/server/application/ChatServer/src/shared/ChatServerRoomOwner.cpp index 091a78ac..dc8cd1a3 100755 --- a/engine/server/application/ChatServer/src/shared/ChatServerRoomOwner.cpp +++ b/engine/server/application/ChatServer/src/shared/ChatServerRoomOwner.cpp @@ -86,7 +86,7 @@ const ChatRoom * ChatServerRoomOwner::getRoom() const if (chatInterface) return chatInterface->getRoom(roomID); - return NULL; + return nullptr; } //----------------------------------------------------------------------- diff --git a/engine/server/application/ChatServer/src/shared/ConnectionServerConnection.cpp b/engine/server/application/ChatServer/src/shared/ConnectionServerConnection.cpp index f6215393..4eb676ec 100755 --- a/engine/server/application/ChatServer/src/shared/ConnectionServerConnection.cpp +++ b/engine/server/application/ChatServer/src/shared/ConnectionServerConnection.cpp @@ -44,9 +44,10 @@ #include "sharedNetworkMessages/ChatUninviteFromRoom.h" #include "sharedNetworkMessages/VerifyPlayerNameMessage.h" #include "sharedNetworkMessages/VerifyPlayerNameResponseMessage.h" -#include "sharedNetworkMessages/VoiceChatMiscMessages.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- ConnectionServerConnection::ConnectionServerConnection(const std::string & a, const unsigned short p) : @@ -100,49 +101,54 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message) ++count; ri = message.begin(); + + const uint32 messageType = m.getType(); //LOG("ConnectionServerConnection", ("onReceive() message(%s)", m.getCmdName().c_str())); - if(m.isType("ChatConnectAvatar")) - { - //printf("ConnectionServerConnection -- ChatConnectAvatar\n"); - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatConnectAvatar"); - ChatConnectAvatar c(ri); - // break surname from last name - std::string name = c.getCharacterName(); - size_t pos = name.find_first_of(" "); - if(pos != std::string::npos) - name = name.substr(0, pos); - ChatServer::connectPlayer(this, c.getStationId(), name, c.getCharacterId(), c.getIsSecure(), c.getIsSubscribed()); - } - else if(m.isType("ChatDisconnectAvatar")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDisconnectAvatar"); - //printf("ConnectionServerConnection -- ChatDisconnectAvatar\n"); - static MessageDispatch::Transceiver disconn; - ChatDisconnectAvatar d(ri); - disconn.emitMessage(d); - ChatServer::disconnectPlayer(d.getCharacterId()); - } - else if(m.isType("GameClientMessage")) - { - // chat message forwarded by the connection server - GameClientMessage c(ri); - //deliverMessageToClientObject(c.getNetworkId(), c.getByteStream()); - Archive::ReadIterator cri = c.getByteStream().begin(); - GameNetworkMessage cm(cri); - std::vector::const_iterator i; - for(i = c.getDistributionList().begin(); i != c.getDistributionList().end(); ++i) + switch(messageType) { + case constcrc("ChatConnectAvatar") : { - const ChatAvatar * avatar = ChatServer::getAvatarByNetworkId(*i); - if (!avatar && cm.isType("ChatInstantMessageToCharacter")) + //printf("ConnectionServerConnection -- ChatConnectAvatar\n"); + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatConnectAvatar"); + ChatConnectAvatar c(ri); + // break surname from last name + std::string name = c.getCharacterName(); + size_t pos = name.find_first_of(" "); + if(pos != std::string::npos) + name = name.substr(0, pos); + ChatServer::connectPlayer(this, c.getStationId(), name, c.getCharacterId(), c.getIsSecure(), c.getIsSubscribed()); + break; + } + case constcrc("ChatDisconnectAvatar") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDisconnectAvatar"); + //printf("ConnectionServerConnection -- ChatDisconnectAvatar\n"); + static MessageDispatch::Transceiver disconn; + ChatDisconnectAvatar d(ri); + disconn.emitMessage(d); + ChatServer::disconnectPlayer(d.getCharacterId()); + break; + } + case constcrc("GameClientMessage") : + { + // chat message forwarded by the connection server + GameClientMessage c(ri); + //deliverMessageToClientObject(c.getNetworkId(), c.getByteStream()); + Archive::ReadIterator cri = c.getByteStream().begin(); + GameNetworkMessage cm(cri); + std::vector::const_iterator i; + for(i = c.getDistributionList().begin(); i != c.getDistributionList().end(); ++i) { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInstantMessageToCharacter"); - //printf("!Sending via the shortcut\n"); - cri = c.getByteStream().begin(); - - if(cm.isType("ChatInstantMessageToCharacter")) + const ChatAvatar * avatar = ChatServer::getAvatarByNetworkId(*i); + const uint32 cmtype = cm.getType(); + + if (!avatar && cmtype == constcrc("ChatInstantMessageToCharacter")) { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInstantMessageToCharacter"); + //printf("!Sending via the shortcut\n"); + cri = c.getByteStream().begin(); + // deliver IM to character ChatInstantMessageToCharacter chat(cri); ChatAvatarId characterName = chat.getCharacterName(); @@ -167,279 +173,246 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message) ChatServer::getChatInterface()->sendMessageToPendingAvatar(fromName, response); return; } + + if(avatar) + { + cri = c.getByteStream().begin(); + + switch(cmtype) { + case constcrc("ChatDeleteAllPersistentMessages") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDeleteAllPersistentMessages"); + ChatDeleteAllPersistentMessages chatDeleteAllPersistentMessages(cri); + ChatServer::deleteAllPersistentMessages(chatDeleteAllPersistentMessages.getSourceNetworkId(), chatDeleteAllPersistentMessages.getTargetNetworkId()); + break; + } + case constcrc("ChatInstantMessageToCharacter") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInstantMessageToCharacter"); + //printf("ConnectionServerConnection -- ChatInstantMessageToCharacter\n"); + // deliver IM to character + ChatInstantMessageToCharacter chat(cri); + ChatAvatarId characterName = chat.getCharacterName(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + + ChatServer::sendInstantMessage(*i, chat.getSequence(), characterName, chat.getMessage(), chat.getOutOfBand()); + break; + } + case constcrc("ChatQueryRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatQueryRoom"); + //printf("ConnectionServerConnection -- ChatQueryRoom\n"); + ChatQueryRoom chat(cri); + ChatServer::queryRoom((*i), this, chat.getSequence(), chat.getRoomName()); + break; + } + case constcrc("ChatPersistentMessageToServer") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatPeristentMessageToServer"); + //printf("ConnectionServerConnection -- ChatPersistentMessageToServer\n"); + ChatPersistentMessageToServer chat(cri); + ChatAvatarId characterName = chat.getToCharacterName(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + + ChatServer::sendPersistentMessage((*i), chat.getSequence(), characterName, chat.getSubject(), chat.getMessage(), chat.getOutOfBand()); + break; + } + case constcrc("ChatRequestPersistentMessage") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRequestPersistentMessage"); + //printf("ConnectionServerConnection -- ChatRequestPersistentMessage\n"); + ChatRequestPersistentMessage chat(cri); + ChatServer::requestPersistentMessage((*i), chat.getSequence(), chat.getMessageId()); + break; + } + case constcrc("ChatDeletePersistentMessage") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDeletePersistentMessage"); + //printf("ConnectionServerConnection -- ChatDeletePersistentMessage\n"); + ChatDeletePersistentMessage chat(cri); + ChatServer::deletePersistentMessage((*i), chat.getMessageId()); + break; + } + case constcrc("ChatCreateRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatCreateRoom"); + //printf("ConnectionServerConnection -- ChatCreateRoom\n"); + ChatCreateRoom chat(cri); + ChatServer::createRoom((*i), chat.getSequence(), chat.getRoomName(), chat.getIsModerated(), chat.getIsPublic(), chat.getRoomTitle()); + break; + } + case constcrc("ChatEnterRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatEnterRoom"); + //printf("ConnectionServerConnection -- ChatEnterRoom\n"); + // entering a room by name + ChatEnterRoom chat(cri); + ChatServer::enterRoom((*i), chat.getSequence(), chat.getRoomName()); + break; + } + case constcrc("ChatEnterRoomById") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatEnterRoomById"); + //printf("ConnectionServerConnection -- ChatEnterRoomById\n"); + // entering a room by room id + ChatEnterRoomById chat(cri); + ChatServer::enterRoom((*i), chat.getSequence(), chat.getRoomId()); + break; + + } + case constcrc("ChatSendToRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatSendToRoom"); + //printf("ConnectionServerConnection -- ChatSendToRoom\n"); + ChatSendToRoom chat(cri); + ChatServer::sendRoomMessage((*i), chat.getSequence(), chat.getRoomId(), chat.getMessage(), chat.getOutOfBand()); + break; + } + case constcrc("ChatRequestRoomList") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRequestRoomList"); + //printf("ConnectionServerConnection -- ChatRequestRoomList\n"); + ChatServer::requestRoomList((*i), this); + break; + } + case constcrc("ChatDestroyRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDestroyRoom"); + //printf("ConnectionServerConnection -- ChatDestroyRoom\n"); + ChatDestroyRoom chat(cri); + ChatServer::destroyRoom((*i), chat.getSequence(), chat.getRoomId()); + break; + } + case constcrc("ChatAddModeratorToRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatAddModeratorToRoom"); + //printf("ConnectionServerConnection -- ChatAddModeratorToRoom\n"); + ChatAddModeratorToRoom chat(cri); + ChatServer::addModeratorToRoom(chat.getSequenceId(), (*i), chat.getAvatarId(), chat.getRoomName()); + break; + } + case constcrc("ChatRemoveModeratorFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRemoveModeratorFromRoom"); + //printf("ConnectionServerConnection -- ChatREmoveModeratorFromRoom\n"); + ChatRemoveModeratorFromRoom chat(cri); + ChatAvatarId characterName = chat.getAvatarId(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::removeModeratorFromRoom(chat.getSequenceId(), (*i), characterName, chat.getRoomName()); + break; + } + case constcrc("ChatRemoveAvatarFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRemoveAvatarFromRoom"); + //printf("ConnectionServerConnection -- ChatREmoveAvatarFromRoom\n"); + ChatRemoveAvatarFromRoom chat(cri); + ChatServer::removeAvatarFromRoom((*i), chat.getAvatarId(), chat.getRoomName()); + break; + } + case constcrc("ChatKickAvatarFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatKickAvatarFromRoom"); + //printf("ConnectionServerConnection -- ChatKickAvatarFromRoom\n"); + ChatKickAvatarFromRoom chat(cri); + ChatServer::kickAvatarFromRoom((*i), chat.getAvatarId(), chat.getRoomName()); + break; + } + case constcrc("ChatAddFriend") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatAddFriend"); + //printf("ConnectionServerConnection -- ChatAddFriend\n"); + ChatAddFriend chat(ri); + ChatServer::addFriend((*i), chat.getSequence(), chat.getCharacterName()); + break; + } + case constcrc("ChatInviteAvatarToRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInviteAvatarToRoom"); + //printf("ConnectionServerConnection -- ChatInviteAvatarToRoom\n"); + ChatInviteAvatarToRoom chat(cri); + ChatAvatarId characterName = chat.getAvatarId(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::invite((*i), characterName, chat.getRoomName()); + break; + } + case constcrc("ChatUninviteFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatUninviteFromRoom"); + //printf("ConnectionServerConnection -- ChatUninviteAvatarToRoom\n"); + ChatUninviteFromRoom chat(cri); + ChatAvatarId characterName = chat.getAvatar(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::uninvite((*i), chat.getSequence(), characterName, chat.getRoomName()); + break; + } + case constcrc("ChatBanAvatarFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatBanAvatarFromRoom"); + //printf("ConnectionServerConnection -- ChatBanAvatarFromRoom\n"); + ChatBanAvatarFromRoom chat(cri); + ChatAvatarId characterName = chat.getAvatarId(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::banFromRoom(chat.getSequence(), (*i), characterName, chat.getRoomName()); + break; + } + case constcrc("ChatUnbanAvatarFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatUnbanAvatarFromRoom"); + //printf("ConnectionServerConnection -- ChatUnbanAvatarFromRoom\n"); + ChatUnbanAvatarFromRoom chat(cri); + ChatAvatarId characterName = chat.getAvatarId(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::unbanFromRoom(chat.getSequence(), (*i), characterName, chat.getRoomName()); + break; + } + case constcrc("VerifyPlayerNameMessage") : + { + PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - VerifyPlayerNameMessage"); + VerifyPlayerNameMessage message(cri); + + bool const valid = ChatServer::isValidChatAvatarName(message.getPlayerName()); + + VerifyPlayerNameResponseMessage response(valid, message.getPlayerName()); + + ChatServer::fileLog(true, "ConnectionServerConnection", "onReceive() message(VerifyPlayerNameMessage) name(%s) valid(%s)", Unicode::wideToNarrow(message.getPlayerName()).c_str(), (valid ? "yes" : "no")); + + sendToClient(message.getSourceNetworkId(), response); + break; + } + } + } + + // @todo : how is a message sent to anyone with a station account? + + else + { + // defer until avatar is connected to chat backend + ChatServer::deferChatMessageFor((*i), message); + } + } - if(avatar) - { - cri = c.getByteStream().begin(); - - if(cm.isType("ChatDeleteAllPersistentMessages")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDeleteAllPersistentMessages"); - ChatDeleteAllPersistentMessages chatDeleteAllPersistentMessages(cri); - ChatServer::deleteAllPersistentMessages(chatDeleteAllPersistentMessages.getSourceNetworkId(), chatDeleteAllPersistentMessages.getTargetNetworkId()); - } - else if(cm.isType("ChatInstantMessageToCharacter")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInstantMessageToCharacter"); -//printf("ConnectionServerConnection -- ChatInstantMessageToCharacter\n"); - // deliver IM to character - ChatInstantMessageToCharacter chat(cri); - ChatAvatarId characterName = chat.getCharacterName(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - - ChatServer::sendInstantMessage(*i, chat.getSequence(), characterName, chat.getMessage(), chat.getOutOfBand()); - } - else if(cm.isType("ChatQueryRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatQueryRoom"); -//printf("ConnectionServerConnection -- ChatQueryRoom\n"); - ChatQueryRoom chat(cri); - ChatServer::queryRoom((*i), this, chat.getSequence(), chat.getRoomName()); - } - else if(cm.isType("ChatPersistentMessageToServer")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatPeristentMessageToServer"); -//printf("ConnectionServerConnection -- ChatPersistentMessageToServer\n"); - ChatPersistentMessageToServer chat(cri); - ChatAvatarId characterName = chat.getToCharacterName(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - - ChatServer::sendPersistentMessage((*i), chat.getSequence(), characterName, chat.getSubject(), chat.getMessage(), chat.getOutOfBand()); - } - else if(cm.isType("ChatRequestPersistentMessage")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRequestPersistentMessage"); -//printf("ConnectionServerConnection -- ChatRequestPersistentMessage\n"); - ChatRequestPersistentMessage chat(cri); - ChatServer::requestPersistentMessage((*i), chat.getSequence(), chat.getMessageId()); - } - else if(cm.isType("ChatDeletePersistentMessage")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDeletePersistentMessage"); -//printf("ConnectionServerConnection -- ChatDeletePersistentMessage\n"); - ChatDeletePersistentMessage chat(cri); - ChatServer::deletePersistentMessage((*i), chat.getMessageId()); - } - else if(cm.isType("ChatCreateRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatCreateRoom"); -//printf("ConnectionServerConnection -- ChatCreateRoom\n"); - ChatCreateRoom chat(cri); - ChatServer::createRoom((*i), chat.getSequence(), chat.getRoomName(), chat.getIsModerated(), chat.getIsPublic(), chat.getRoomTitle()); - } - else if(cm.isType("ChatEnterRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatEnterRoom"); -//printf("ConnectionServerConnection -- ChatEnterRoom\n"); - // entering a room by name - ChatEnterRoom chat(cri); - ChatServer::enterRoom((*i), chat.getSequence(), chat.getRoomName()); - } - else if(cm.isType("ChatEnterRoomById")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatEnterRoomById"); -//printf("ConnectionServerConnection -- ChatEnterRoomById\n"); - // entering a room by room id - ChatEnterRoomById chat(cri); - ChatServer::enterRoom((*i), chat.getSequence(), chat.getRoomId()); - - } - else if(cm.isType("ChatSendToRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatSendToRoom"); -//printf("ConnectionServerConnection -- ChatSendToRoom\n"); - ChatSendToRoom chat(cri); - ChatServer::sendRoomMessage((*i), chat.getSequence(), chat.getRoomId(), chat.getMessage(), chat.getOutOfBand()); - } - else if(cm.isType("ChatRequestRoomList")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRequestRoomList"); -//printf("ConnectionServerConnection -- ChatRequestRoomList\n"); - ChatServer::requestRoomList((*i), this); - } - else if(cm.isType("ChatDestroyRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatDestroyRoom"); -//printf("ConnectionServerConnection -- ChatDestroyRoom\n"); - ChatDestroyRoom chat(cri); - ChatServer::destroyRoom((*i), chat.getSequence(), chat.getRoomId()); - } - else if(cm.isType("ChatAddModeratorToRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatAddModeratorToRoom"); -//printf("ConnectionServerConnection -- ChatAddModeratorToRoom\n"); - ChatAddModeratorToRoom chat(cri); - ChatServer::addModeratorToRoom(chat.getSequenceId(), (*i), chat.getAvatarId(), chat.getRoomName()); - } - else if(cm.isType("ChatRemoveModeratorFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRemoveModeratorFromRoom"); -//printf("ConnectionServerConnection -- ChatREmoveModeratorFromRoom\n"); - ChatRemoveModeratorFromRoom chat(cri); - ChatAvatarId characterName = chat.getAvatarId(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::removeModeratorFromRoom(chat.getSequenceId(), (*i), characterName, chat.getRoomName()); - } - else if(cm.isType("ChatRemoveAvatarFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatRemoveAvatarFromRoom"); -//printf("ConnectionServerConnection -- ChatREmoveAvatarFromRoom\n"); - ChatRemoveAvatarFromRoom chat(cri); - ChatServer::removeAvatarFromRoom((*i), chat.getAvatarId(), chat.getRoomName()); - } - else if(cm.isType("ChatKickAvatarFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatKickAvatarFromRoom"); -//printf("ConnectionServerConnection -- ChatKickAvatarFromRoom\n"); - ChatKickAvatarFromRoom chat(cri); - ChatServer::kickAvatarFromRoom((*i), chat.getAvatarId(), chat.getRoomName()); - } - else if(cm.isType("ChatAddFriend")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatAddFriend"); -//printf("ConnectionServerConnection -- ChatAddFriend\n"); - ChatAddFriend chat(ri); - ChatServer::addFriend((*i), chat.getSequence(), chat.getCharacterName()); - } - else if(cm.isType("ChatInviteAvatarToRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatInviteAvatarToRoom"); -//printf("ConnectionServerConnection -- ChatInviteAvatarToRoom\n"); - ChatInviteAvatarToRoom chat(cri); - ChatAvatarId characterName = chat.getAvatarId(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::invite((*i), characterName, chat.getRoomName()); - } - else if(cm.isType("ChatUninviteFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatUninviteFromRoom"); -//printf("ConnectionServerConnection -- ChatUninviteAvatarToRoom\n"); - ChatUninviteFromRoom chat(cri); - ChatAvatarId characterName = chat.getAvatar(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::uninvite((*i), chat.getSequence(), characterName, chat.getRoomName()); - } - else if(cm.isType("ChatBanAvatarFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatBanAvatarFromRoom"); -//printf("ConnectionServerConnection -- ChatBanAvatarFromRoom\n"); - ChatBanAvatarFromRoom chat(cri); - ChatAvatarId characterName = chat.getAvatarId(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::banFromRoom(chat.getSequence(), (*i), characterName, chat.getRoomName()); - } - else if(cm.isType("ChatUnbanAvatarFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - ChatUnbanAvatarFromRoom"); -//printf("ConnectionServerConnection -- ChatUnbanAvatarFromRoom\n"); - ChatUnbanAvatarFromRoom chat(cri); - ChatAvatarId characterName = chat.getAvatarId(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::unbanFromRoom(chat.getSequence(), (*i), characterName, chat.getRoomName()); - } - else if(cm.isType("VerifyPlayerNameMessage")) - { - PROFILER_AUTO_BLOCK_DEFINE("ConnectionServer - VerifyPlayerNameMessage"); - VerifyPlayerNameMessage message(cri); - - bool const valid = ChatServer::isValidChatAvatarName(message.getPlayerName()); - - VerifyPlayerNameResponseMessage response(valid, message.getPlayerName()); - - ChatServer::fileLog(true, "ConnectionServerConnection", "onReceive() message(VerifyPlayerNameMessage) name(%s) valid(%s)", Unicode::wideToNarrow(message.getPlayerName()).c_str(), (valid ? "yes" : "no")); - - sendToClient(message.getSourceNetworkId(), response); - } - - //messages to allow personal channels - else if (cm.isType(VoiceChatRequestPersonalChannel::cms_name)) - { - VoiceChatRequestPersonalChannel message(cri); - - std::string userName, playerName; - if(ChatServer::getVoiceChatLoginInfoFromId(message.getOwner(), userName, playerName)) - { - std::list modlist; - modlist.push_back(userName); - - if(message.getShouldCreate()) - { - // 400 is the current vivox channel size limit when this was written - ChatServer::requestGetChannel(message.getOwner(), ChatServer::getVChatInterface()->buildPersonalChannelName(message.getOwner()), false, false, 400, modlist); - } - else - { - ChatServer::getVChatInterface()->sendChannelData(message.getOwner(), ChatServer::getVChatInterface()->buildPersonalChannelName(message.getOwner()), "", true, true); - } - } - //@TODO: error message? - } - else if (cm.isType(VoiceChatInvite::cms_name)) - { - VoiceChatInvite message(cri); - if(message.getChannelName() == ChatServer::getVChatInterface()->buildPersonalChannelName(message.getRequester())) - { - NetworkId targetId = message.getInviteeId(); - std::string const & targetName = message.getInviteeName(); - if(targetId.isValid() || - (!targetName.empty() && ChatServer::getVoiceChatLoginInfoFromName(targetName, targetId))) - { - ChatServer::requestInvitePlayerToChannel(message.getRequester(), targetId, message.getChannelName()); - } - } - //@TODO: error message? - } - else if (cm.isType(VoiceChatKick::cms_name)) - { - VoiceChatKick message(cri); - if(message.getChannelName() == ChatServer::getVChatInterface()->buildPersonalChannelName(message.getRequester())) - { - NetworkId targetId = message.getKickeeId(); - std::string const & targetName = message.getKickeeName(); - if(targetId.isValid() || - (!targetName.empty() && (ChatServer::getVoiceChatLoginInfoFromName(targetName, targetId)))) - { - ChatServer::requestKickPlayerFromChannel(message.getRequester(), targetId, message.getChannelName()); - } - } - //@TODO: error message? - } - else if (cm.isType(VoiceChatRequestChannelInfo::cms_name)) - { - VoiceChatRequestChannelInfo message(cri); - ChatServer::requestChannelInfo(message.getRequester(), message.getChannelName()); - } - } - - // @todo : how is a message sent to anyone with a station account? - - else - { - // defer until avatar is connected to chat backend - ChatServer::deferChatMessageFor((*i), message); - } - + break; } } diff --git a/engine/server/application/ChatServer/src/shared/GameServerConnection.cpp b/engine/server/application/ChatServer/src/shared/GameServerConnection.cpp index bb6a435f..7c39b665 100755 --- a/engine/server/application/ChatServer/src/shared/GameServerConnection.cpp +++ b/engine/server/application/ChatServer/src/shared/GameServerConnection.cpp @@ -34,8 +34,7 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "UnicodeUtils.h" -#include "sharedNetworkMessages/VoiceChatChannelInfo.h" -#include "sharedNetworkMessages/VoiceChatMiscMessages.h" +#include "sharedFoundation/CrcConstexpr.hpp" #include #include @@ -109,287 +108,275 @@ void GameServerConnection::onReceive(const Archive::ByteStream & message) //LOG("GameServerConnection", ("onReceive - %s", gameNetworkMessage.getCmdName().c_str())); //DEBUG_REPORT_LOG(true, ("***ChatServ: GameServerConnection::onReceive() message(%s)\n", gameNetworkMessage.getCmdName().c_str())); - if(gameNetworkMessage.isType("ChatDeleteAllPersistentMessages")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatDeleteAllPersistentMessages"); - ChatDeleteAllPersistentMessages chatDeleteAllPersistentMessages(ri); - ChatServer::deleteAllPersistentMessages(chatDeleteAllPersistentMessages.getSourceNetworkId(), chatDeleteAllPersistentMessages.getTargetNetworkId()); - } - else if(gameNetworkMessage.isType("ChatCreateRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatCreateRoom"); -//printf("GameServerConnection -- ChatCreateRoom\n"); - ChatCreateRoom chat(ri); - unsigned int sequence = chat.getSequence(); - ChatServer::addGameServerConnection(sequence, this); - ChatServer::createRoom(NetworkId::cms_invalid, sequence, chat.getRoomName(), chat.getIsModerated(), chat.getIsPublic(), chat.getRoomTitle()); - } - else if(gameNetworkMessage.isType("ChatRequestLog")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatRequestLog"); - ChatRequestLog chatRequestLog(ri); - std::vector chatLog; - ChatServer::getChatLog(chatRequestLog.getPlayer(), chatLog); - - ChatOnRequestLog chatOnRequestLog(chatRequestLog.getSequence(), chatLog); - - static Archive::ByteStream a; - a.clear(); - chatOnRequestLog.pack(a); - - (static_cast(this))->send(a, true); - } - else if(gameNetworkMessage.isType("ChatDestroyRoomByName")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatDestroyRoomByName"); -//printf("GameServerConnection -- ChatDestroyRoomByName\n"); - ChatDestroyRoomByName chat(ri); - ChatServer::destroyRoom(chat.getRoomPath()); - } - else if(gameNetworkMessage.isType("ChatPutAvatarInRoom")) - { -//printf("GameServerConnection -- ChatPutAvatarInRoom\n"); - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatPutAvatarInRoom"); - ChatPutAvatarInRoom chat(ri); - ChatAvatarId id; - id.cluster = ConfigChatServer::getClusterName(); - id.gameCode = m_gameCode; - id.name = chat.getAvatarName(); - size_t pos = id.name.find(" "); - if(pos != std::string::npos) - id.name = id.name.substr(0, pos); - ChatServer::enterRoom(id, chat.getRoomName(), chat.getForceCreate(), chat.getCreatePrivate()); - - } - else if(gameNetworkMessage.isType("ChatInviteAvatarToRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatInviteAvatarToRoom"); -//printf("GameServerConnection -- ChatInviteAvatarToRoom\n"); - ChatInviteAvatarToRoom chat(ri); - ChatAvatarId characterName = chat.getAvatarId(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::invite(NetworkId::cms_invalid, characterName, chat.getRoomName()); - } - else if(gameNetworkMessage.isType("ChatInviteGroupMembersToRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatInviteGroupMembersToRoom"); -//printf("GameServerConnection -- ChatInviteGroupMembersToRoom\n"); - ChatInviteGroupMembersToRoom chat(ri); - ChatServer::inviteGroupMembers(chat.getInvitorNetworkId(), chat.getGroupLeaderId(), chat.getRoomName(), chat.getInvitedMembers()); - } - else if(gameNetworkMessage.isType("ChatUninviteFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatUninviteAvatarToRoom"); -//printf("GameServerConnection -- ChatUninviteAvatarFromRoom\n"); - ChatUninviteFromRoom chat(ri); - ChatAvatarId characterName = chat.getAvatar(); - if(characterName.gameCode.empty()) - characterName.gameCode = "SWG"; - if(characterName.cluster.empty()) - characterName.cluster = ConfigChatServer::getClusterName(); - ChatServer::uninvite(ChatServer::getNetworkIdByAvatarId(characterName), chat.getSequence(), characterName, chat.getRoomName()); - } - else if (gameNetworkMessage.isType("ChatChangeFriendStatus")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatChangeFriendStatus"); -//printf("GameServerConnection -- ChatChangeFriendStatus\n"); - ChatChangeFriendStatus chat(ri); - - if (chat.getAdd()) + const uint32 messageType = gameNetworkMessage.getType(); + + switch(messageType) { + case constcrc("ChatDeleteAllPersistentMessages") : { - ChatServer::addFriend( - ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), - chat.getSequence(), chat.getFriendName()); - } - else - { - ChatServer::removeFriend( - ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), - chat.getSequence(), chat.getFriendName()); + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatDeleteAllPersistentMessages"); + ChatDeleteAllPersistentMessages chatDeleteAllPersistentMessages(ri); + ChatServer::deleteAllPersistentMessages(chatDeleteAllPersistentMessages.getSourceNetworkId(), chatDeleteAllPersistentMessages.getTargetNetworkId()); + break; } - - } - else if (gameNetworkMessage.isType("ChatGetFriendsList")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatGetFriendsList"); -//printf("GameServerConnection -- ChatGetFriendsList\n"); - ChatGetFriendsList chat(ri); - - ChatServer::getFriendsList(chat.getCharacterName()); - } - else if (gameNetworkMessage.isType("ChatChangeIgnoreStatus")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatChangeIgnoreStatus"); -//printf("GameServerConnection -- ChatChangeIgnoreStatus\n"); - ChatChangeIgnoreStatus chat(ri); - - if (chat.getIgnore()) + case constcrc("ChatCreateRoom") : { - ChatServer::addIgnore( - ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), - chat.getSequence(), chat.getIgnoreName()); - } - else - { - ChatServer::removeIgnore( - ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), - chat.getSequence(), chat.getIgnoreName()); + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatCreateRoom"); + //printf("GameServerConnection -- ChatCreateRoom\n"); + ChatCreateRoom chat(ri); + unsigned int sequence = chat.getSequence(); + ChatServer::addGameServerConnection(sequence, this); + ChatServer::createRoom(NetworkId::cms_invalid, sequence, chat.getRoomName(), chat.getIsModerated(), chat.getIsPublic(), chat.getRoomTitle()); + break; } - - } - else if (gameNetworkMessage.isType("ChatGetIgnoreList")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatGetIgnoreList"); -//printf("GameServerConnection -- ChatGetIgnoreList\n"); - ChatGetIgnoreList chat(ri); - - ChatServer::getIgnoreList(chat.getCharacterName()); - } - else if(gameNetworkMessage.isType("ChatRemoveAvatarFromRoom")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatRemoveAvatarFromRoom"); -//printf("GameServerConnection -- ChatRemoveAvatarFromRoom\n"); - ChatRemoveAvatarFromRoom chat(ri); - ChatAvatarId id = chat.getAvatarId(); - size_t pos = id.name.find(" "); - if(pos != std::string::npos) - id.name = id.name.substr(0, pos); - ChatServer::removeAvatarFromRoom(id, chat.getRoomName()); - } - else if(gameNetworkMessage.isType("ChatMessageFromGame")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatMessageFromGame"); -//printf("GameServerConnection -- ChatMessageFromGame\n"); - ChatMessageFromGame chat(ri); - std::string recipient = chat.getTo(); - size_t pos = recipient.find(" "); - if (pos != std::string::npos) + case constcrc("ChatRequestLog") : { - recipient = recipient.substr(0, pos); + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatRequestLog"); + ChatRequestLog chatRequestLog(ri); + std::vector chatLog; + ChatServer::getChatLog(chatRequestLog.getPlayer(), chatLog); + + ChatOnRequestLog chatOnRequestLog(chatRequestLog.getSequence(), chatLog); + + static Archive::ByteStream a; + a.clear(); + chatOnRequestLog.pack(a); + + (static_cast(this))->send(a, true); + break; } - switch(chat.getMessageType()) + case constcrc("ChatDestroyRoomByName") : { - case ChatMessageFromGame::INSTANT: + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatDestroyRoomByName"); + //printf("GameServerConnection -- ChatDestroyRoomByName\n"); + ChatDestroyRoomByName chat(ri); + ChatServer::destroyRoom(chat.getRoomPath()); + break; + } + case constcrc("ChatPutAvatarInRoom") : + { + //printf("GameServerConnection -- ChatPutAvatarInRoom\n"); + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatPutAvatarInRoom"); + ChatPutAvatarInRoom chat(ri); + ChatAvatarId id; + id.cluster = ConfigChatServer::getClusterName(); + id.gameCode = m_gameCode; + id.name = chat.getAvatarName(); + size_t pos = id.name.find(" "); + if(pos != std::string::npos) + id.name = id.name.substr(0, pos); + ChatServer::enterRoom(id, chat.getRoomName(), chat.getForceCreate(), chat.getCreatePrivate()); + break; + } + case constcrc("ChatInviteAvatarToRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatInviteAvatarToRoom"); + //printf("GameServerConnection -- ChatInviteAvatarToRoom\n"); + ChatInviteAvatarToRoom chat(ri); + ChatAvatarId characterName = chat.getAvatarId(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::invite(NetworkId::cms_invalid, characterName, chat.getRoomName()); + break; + } + case constcrc("ChatInviteGroupMembersToRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatInviteGroupMembersToRoom"); + //printf("GameServerConnection -- ChatInviteGroupMembersToRoom\n"); + ChatInviteGroupMembersToRoom chat(ri); + ChatServer::inviteGroupMembers(chat.getInvitorNetworkId(), chat.getGroupLeaderId(), chat.getRoomName(), chat.getInvitedMembers()); + break; + } + case constcrc("ChatUninviteFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatUninviteAvatarToRoom"); + //printf("GameServerConnection -- ChatUninviteAvatarFromRoom\n"); + ChatUninviteFromRoom chat(ri); + ChatAvatarId characterName = chat.getAvatar(); + if(characterName.gameCode.empty()) + characterName.gameCode = "SWG"; + if(characterName.cluster.empty()) + characterName.cluster = ConfigChatServer::getClusterName(); + ChatServer::uninvite(ChatServer::getNetworkIdByAvatarId(characterName), chat.getSequence(), characterName, chat.getRoomName()); + break; + } + case constcrc("ChatChangeFriendStatus") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatChangeFriendStatus"); + //printf("GameServerConnection -- ChatChangeFriendStatus\n"); + ChatChangeFriendStatus chat(ri); + + if (chat.getAdd()) { - ChatAvatarId from(chat.getFrom()); - if (from.cluster.empty()) - from.cluster = ConfigChatServer::getClusterName(); - if (from.gameCode.empty()) - from.gameCode = m_gameCode; + ChatServer::addFriend( + ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), + chat.getSequence(), chat.getFriendName()); + } + else + { + ChatServer::removeFriend( + ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), + chat.getSequence(), chat.getFriendName()); + } + + break; + } + case constcrc("ChatGetFriendsList") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatGetFriendsList"); + //printf("GameServerConnection -- ChatGetFriendsList\n"); + ChatGetFriendsList chat(ri); - ChatAvatarId to(recipient); - if (to.cluster.empty()) - to.cluster = ConfigChatServer::getClusterName(); - if (to.gameCode.empty()) - to.gameCode = m_gameCode; + ChatServer::getFriendsList(chat.getCharacterName()); + break; + } + case constcrc("ChatChangeIgnoreStatus") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatChangeIgnoreStatus"); + //printf("GameServerConnection -- ChatChangeIgnoreStatus\n"); + ChatChangeIgnoreStatus chat(ri); - ChatServer::sendInstantMessage(from, to, chat.getMessage(), chat.getOutOfBand()); + if (chat.getIgnore()) + { + ChatServer::addIgnore( + ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), + chat.getSequence(), chat.getIgnoreName()); + } + else + { + ChatServer::removeIgnore( + ChatServer::getNetworkIdByAvatarId(chat.getCharacterName()), + chat.getSequence(), chat.getIgnoreName()); } break; - case ChatMessageFromGame::PERSISTENT: - { - ChatAvatarId from(chat.getFrom()); - if (from.cluster.empty()) - from.cluster = ConfigChatServer::getClusterName(); - if (from.gameCode.empty()) - from.gameCode = m_gameCode; - - ChatAvatarId to(recipient); - if (to.cluster.empty()) - to.cluster = ConfigChatServer::getClusterName(); - if (to.gameCode.empty()) - to.gameCode = m_gameCode; - - ChatServer::sendPersistentMessage(from, to, chat.getSubject(), chat.getMessage(), chat.getOutOfBand()); - } - break; - case ChatMessageFromGame::ROOM: - { - ChatAvatarId from(chat.getFrom()); - if (from.cluster.empty()) - from.cluster = ConfigChatServer::getClusterName(); - if (from.gameCode.empty()) - from.gameCode = m_gameCode; + } + case constcrc("ChatGetIgnoreList") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatGetIgnoreList"); + //printf("GameServerConnection -- ChatGetIgnoreList\n"); + ChatGetIgnoreList chat(ri); - ChatServer::sendStandardRoomMessage(from, chat.getRoom(), chat.getMessage(), chat.getOutOfBand()); - } - break; - default: - REPORT_LOG(true, ("Unkown Game Chat Message type\n")); + ChatServer::getIgnoreList(chat.getCharacterName()); break; } - } - else if (gameNetworkMessage.isType("SetUnsquelchTime")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - SetUnsquelchTime"); -//printf("GameServerConnection -- SetUnsquelchTime\n"); - GenericValueTypeMessage > setUnsquelchTime(ri); + case constcrc("ChatRemoveAvatarFromRoom") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatRemoveAvatarFromRoom"); + //printf("GameServerConnection -- ChatRemoveAvatarFromRoom\n"); + ChatRemoveAvatarFromRoom chat(ri); + ChatAvatarId id = chat.getAvatarId(); + size_t pos = id.name.find(" "); + if(pos != std::string::npos) + id.name = id.name.substr(0, pos); + ChatServer::removeAvatarFromRoom(id, chat.getRoomName()); + break; + } + case constcrc("ChatMessageFromGame") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatMessageFromGame"); + //printf("GameServerConnection -- ChatMessageFromGame\n"); + ChatMessageFromGame chat(ri); + std::string recipient = chat.getTo(); + size_t pos = recipient.find(" "); + if (pos != std::string::npos) + { + recipient = recipient.substr(0, pos); + } + switch(chat.getMessageType()) + { + case ChatMessageFromGame::INSTANT: + { + ChatAvatarId from(chat.getFrom()); + if (from.cluster.empty()) + from.cluster = ConfigChatServer::getClusterName(); + if (from.gameCode.empty()) + from.gameCode = m_gameCode; - ChatServer::setUnsquelchTime(setUnsquelchTime.getValue().first, static_cast(setUnsquelchTime.getValue().second)); - } - else if (gameNetworkMessage.isType("ChatStatisticsGS")) - { - PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatStatisticsGS"); -//printf("GameServerConnection -- ChatStatisticsGS\n"); - GenericValueTypeMessage, int>, std::pair > > chatStatistics(ri); + ChatAvatarId to(recipient); + if (to.cluster.empty()) + to.cluster = ConfigChatServer::getClusterName(); + if (to.gameCode.empty()) + to.gameCode = m_gameCode; - ChatServer::handleChatStatisticsFromGameServer(chatStatistics.getValue().first.first.first, static_cast(chatStatistics.getValue().first.first.second), static_cast(chatStatistics.getValue().first.second), chatStatistics.getValue().second.first, chatStatistics.getValue().second.second); - } - //it eats at my soul to participate in this elseif chain - else if (gameNetworkMessage.isType(VoiceChatGetChannel::cms_name)) - { - Archive::ReadIterator ri = message.begin(); - VoiceChatGetChannel createRoomMessage(ri); - std::list mods; - ChatServer::instance().requestGetChannel(ReturnAddress(m_connectionId),createRoomMessage.getRoomName(), createRoomMessage.getIsPublic(), createRoomMessage.getIsPersistant(), createRoomMessage.getLimit(), mods); - } - else if (gameNetworkMessage.isType(VoiceChatDeleteChannel::cms_name)) - { - Archive::ReadIterator ri = message.begin(); - VoiceChatDeleteChannel destroyRoomMessage(ri); - ChatServer::instance().requestDeleteChannel(ReturnAddress(m_connectionId),destroyRoomMessage.getRoomName()); - } - else if (gameNetworkMessage.isType(VoiceChatAddClientToChannel::cms_name)) - { - Archive::ReadIterator ri = message.begin(); - VoiceChatAddClientToChannel addMessage(ri); - ChatServer::instance().requestAddClientToChannel(addMessage.getClientId(), addMessage.getClientName(), addMessage.getChannelName(), addMessage.getForceShortlist()); - } - else if (gameNetworkMessage.isType(VoiceChatRemoveClientFromChannel::cms_name)) - { - Archive::ReadIterator ri = message.begin(); - VoiceChatRemoveClientFromChannel msg(ri); - ChatServer::instance().requestRemoveClientFromChannel(msg.getClientId(), msg.getClientName(), msg.getChannelName()); - } - else if (gameNetworkMessage.isType(VoiceChatChannelCommand::cms_name)) - { - Archive::ReadIterator ri = message.begin(); - VoiceChatChannelCommand msg(ri); - ChatServer::instance().requestChannelCommand(ReturnAddress(m_connectionId), msg.getSourceUserName(),msg.getTargetUserName(),msg.getChannelName(),msg.getCommandType(),msg.getBanTimeout()); - } - else if (gameNetworkMessage.isType("BroadcastGlobalChannel")) - { - Archive::ReadIterator ri = message.begin(); + ChatServer::sendInstantMessage(from, to, chat.getMessage(), chat.getOutOfBand()); + } + break; + case ChatMessageFromGame::PERSISTENT: + { + ChatAvatarId from(chat.getFrom()); + if (from.cluster.empty()) + from.cluster = ConfigChatServer::getClusterName(); + if (from.gameCode.empty()) + from.gameCode = m_gameCode; + + ChatAvatarId to(recipient); + if (to.cluster.empty()) + to.cluster = ConfigChatServer::getClusterName(); + if (to.gameCode.empty()) + to.gameCode = m_gameCode; + + ChatServer::sendPersistentMessage(from, to, chat.getSubject(), chat.getMessage(), chat.getOutOfBand()); + } + break; + case ChatMessageFromGame::ROOM: + { + ChatAvatarId from(chat.getFrom()); + if (from.cluster.empty()) + from.cluster = ConfigChatServer::getClusterName(); + if (from.gameCode.empty()) + from.gameCode = m_gameCode; - typedef std::pair, bool> PayloadType; - GenericValueTypeMessage msg(ri); + ChatServer::sendStandardRoomMessage(from, chat.getRoom(), chat.getMessage(), chat.getOutOfBand()); + } + break; + default: + REPORT_LOG(true, ("Unkown Game Chat Message type\n")); + break; + } + break; + } + case constcrc("SetUnsquelchTime") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - SetUnsquelchTime"); + //printf("GameServerConnection -- SetUnsquelchTime\n"); + GenericValueTypeMessage > setUnsquelchTime(ri); - PayloadType const & payload = msg.getValue(); - std::string const & channelName = payload.first.first; - std::string const & messageText = payload.first.second; - bool const & isRemove = payload.second; + ChatServer::setUnsquelchTime(setUnsquelchTime.getValue().first, static_cast(setUnsquelchTime.getValue().second)); + break; + } + case constcrc("ChatStatisticsGS") : + { + PROFILER_AUTO_BLOCK_DEFINE("GameServerConnection - ChatStatisticsGS"); + //printf("GameServerConnection -- ChatStatisticsGS\n"); + GenericValueTypeMessage, int>, std::pair > > chatStatistics(ri); - LOG("CustomerService", ("BroadcastVoiceChannel: ChatServer got BroadcastGlobalChannel on GameServerConnection chan(%s) text(%s) remove(%d)", - channelName.c_str(), messageText.c_str(), (isRemove?1:0))); - ChatServer::requestBroadcastChannelMessage(channelName, messageText, isRemove); - } - else if (gameNetworkMessage.isType("ChatDestroyAvatar")) - { - GenericValueTypeMessage const msg(ri); - ChatServer::getChatInterface()->DestroyAvatar(msg.getValue()); + ChatServer::handleChatStatisticsFromGameServer(chatStatistics.getValue().first.first.first, static_cast(chatStatistics.getValue().first.first.second), static_cast(chatStatistics.getValue().first.second), chatStatistics.getValue().second.first, chatStatistics.getValue().second.second); + break; + } + case constcrc("BroadcastGlobalChannel") : + { + Archive::ReadIterator ri = message.begin(); + + typedef std::pair, bool> PayloadType; + GenericValueTypeMessage msg(ri); + + PayloadType const & payload = msg.getValue(); + std::string const & channelName = payload.first.first; + std::string const & messageText = payload.first.second; + bool const & isRemove = payload.second; + + LOG("CustomerService", ("ChatServer got BroadcastGlobalChannel on GameServerConnection chan(%s) text(%s) remove(%d)", + channelName.c_str(), messageText.c_str(), (isRemove?1:0))); + ChatServer::requestBroadcastChannelMessage(channelName, messageText, isRemove); + break; + } + case constcrc("ChatDestroyAvatar") : + { + GenericValueTypeMessage const msg(ri); + ChatServer::getChatInterface()->DestroyAvatar(msg.getValue()); + break; + } } } diff --git a/engine/server/application/ChatServer/src/shared/VChatInterface.cpp b/engine/server/application/ChatServer/src/shared/VChatInterface.cpp index 6e7e257c..b98704bc 100755 --- a/engine/server/application/ChatServer/src/shared/VChatInterface.cpp +++ b/engine/server/application/ChatServer/src/shared/VChatInterface.cpp @@ -435,7 +435,7 @@ void VChatInterface::OnConnectionOpened( const char * address ) ChatServer::fileLog(ms_voiceLoggingEnabled, ms_logLable, "OnConnectionOpened: %s", address); - uint32 track = VChatAPI::GetAccount(ms_systemAvatarName, ConfigChatServer::getGameCode(), ConfigChatServer::getClusterName(), 0, 0, NULL); + uint32 track = VChatAPI::GetAccount(ms_systemAvatarName, ConfigChatServer::getGameCode(), ConfigChatServer::getClusterName(), 0, 0, nullptr); ChatServer::fileLog(ms_voiceLoggingEnabled, ms_logLable, "Creating system avatar: %s track(%u)", getSystemLoginName().c_str(), track); } @@ -477,7 +477,7 @@ void VChatInterface::OnGetAccount(unsigned track, unsigned result, unsigned user { requestConnectPlayer(info->suid,info->avatarName,info->id, info->failedAttempts+1); delete info; - info = NULL; + info = nullptr; return; } } @@ -501,7 +501,7 @@ void VChatInterface::OnGetAccount(unsigned track, unsigned result, unsigned user } delete info; - info = NULL; + info = nullptr; } void VChatInterface::OnGetChannelV2(unsigned track, unsigned result, @@ -639,7 +639,7 @@ void VChatInterface::OnGetAllChannels(unsigned track, unsigned result, const VCh if(shouldRetry) { - GetAllChannels(NULL); + GetAllChannels(nullptr); } } @@ -832,7 +832,7 @@ void VChatInterface::checkForCharacterChannelAdd(std::string const & name, std:: data.m_channelPassword, data.m_channelURI, "en_US", - NULL); + nullptr); (*iter).second.push_back(playerOID); @@ -877,7 +877,7 @@ void VChatInterface::checkForCharacterChannelRemove(std::string const & name, st parseWorldName(std::string(avatar->getServer().c_str())), "SWG", "guild", - NULL); + nullptr); } iter = (*chanIter).second.erase(iter); diff --git a/engine/server/application/ChatServer/src/win32/WinMain.cpp b/engine/server/application/ChatServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..8d0ac8fc --- /dev/null +++ b/engine/server/application/ChatServer/src/win32/WinMain.cpp @@ -0,0 +1,42 @@ +#include "FirstChatServer.h" +#include "ConfigChatServer.h" +#include "ChatServer.h" +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedThread/SetupSharedThread.h" + +#include +#include + +int main( int argc, char ** argv ) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + //setupFoundationData.hInstance = hInstance; + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + + SetupSharedNetworkMessages::install(); + + //-- setup game server + ConfigChatServer::install (); + + //-- run game + SetupSharedFoundation::callbackWithExceptionHandling(ChatServer::run); + + SetupSharedFoundation::remove(); + + return 0; +} diff --git a/engine/server/application/CommoditiesServer/src/linux/main.cpp b/engine/server/application/CommoditiesServer/src/linux/main.cpp index b93208f5..ce3735d1 100755 --- a/engine/server/application/CommoditiesServer/src/linux/main.cpp +++ b/engine/server/application/CommoditiesServer/src/linux/main.cpp @@ -61,7 +61,7 @@ int main(int argc, char ** argv) Unicode::UnicodeNarrowStringVector localeVector; localeVector.push_back(defaultLocale); - LocalizationManager::install (new TreeFile::TreeFileFactory, localeVector, debugStringIds, NULL, displayBadStringIds); + LocalizationManager::install (new TreeFile::TreeFileFactory, localeVector, debugStringIds, nullptr, displayBadStringIds); ExitChain::add(LocalizationManager::remove, "LocalizationManager::remove"); DataTableManager::install(); diff --git a/engine/server/application/CommoditiesServer/src/shared/Auction.cpp b/engine/server/application/CommoditiesServer/src/shared/Auction.cpp index 0d1edd7f..9fcc7264 100755 --- a/engine/server/application/CommoditiesServer/src/shared/Auction.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/Auction.cpp @@ -27,6 +27,8 @@ #include "sharedUtility/DataTable.h" #include "sharedUtility/DataTableManager.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include // src/engine/client/library/clientGame/src/shared/core/AuctionManagerClient.cpp (s_maxBid) @@ -208,7 +210,7 @@ namespace AuctionNamespace if (iterAttr != searchableAttributeString->end()) { applicableSearchCondition = true; - return (NULL != strstr(iterAttr->second.c_str(), searchCondition.stringValue.c_str())); // lowercase is assumed (and required) + return (nullptr != strstr(iterAttr->second.c_str(), searchCondition.stringValue.c_str())); // lowercase is assumed (and required) } } @@ -242,7 +244,7 @@ namespace AuctionNamespace if (iterAttr != searchableAttributeString->end()) { applicableSearchCondition = true; - return (NULL == strstr(iterAttr->second.c_str(), searchCondition.stringValue.c_str())); // lowercase is assumed (and required) + return (nullptr == strstr(iterAttr->second.c_str(), searchCondition.stringValue.c_str())); // lowercase is assumed (and required) } } @@ -293,10 +295,10 @@ m_userDescription(userDescription), m_oobLength(oobLength), m_oobData(oobData), m_attributes(), -m_searchableAttributeInt(NULL), -m_searchableAttributeFloat(NULL), -m_searchableAttributeString(NULL), -m_highBid(NULL), +m_searchableAttributeInt(nullptr), +m_searchableAttributeFloat(nullptr), +m_searchableAttributeString(nullptr), +m_highBid(nullptr), m_item(new AuctionItem(itemId, itemType, itemTemplateId, itemTimer, itemNameLength, itemName, creatorId, itemSize)), m_sold(false), m_active(true), @@ -395,10 +397,10 @@ m_userDescription(userDescription), m_oobLength(oobLength), m_oobData(oobData), m_attributes(), -m_searchableAttributeInt(NULL), -m_searchableAttributeFloat(NULL), -m_searchableAttributeString(NULL), -m_highBid(NULL), +m_searchableAttributeInt(nullptr), +m_searchableAttributeFloat(nullptr), +m_searchableAttributeString(nullptr), +m_highBid(nullptr), m_item(new AuctionItem(itemId, itemType, itemTemplateId, itemTimer, itemNameLength, itemName, creatorId, itemSize)), m_sold(isSold), m_active(isActive), @@ -488,7 +490,7 @@ void Auction::Initialization() #ifdef _DEBUG for (int i = 0; i < static_cast(AuctionQueryHeadersMessage::SCC_LAST); ++i) { - s_searchConditionComparisonFn[i] = NULL; + s_searchConditionComparisonFn[i] = nullptr; } #endif @@ -502,7 +504,7 @@ void Auction::Initialization() #ifdef _DEBUG for (int j = 0; j < static_cast(AuctionQueryHeadersMessage::SCC_LAST); ++j) { - DEBUG_FATAL((s_searchConditionComparisonFn[j] == NULL), ("s_searchConditionComparisonFn array is NULL at index (%d)", j)); + DEBUG_FATAL((s_searchConditionComparisonFn[j] == nullptr), ("s_searchConditionComparisonFn array is nullptr at index (%d)", j)); } #endif @@ -659,7 +661,7 @@ const AuctionBid *Auction::GetPreviousBid() const { if (m_bids.size() <= 1) { - return NULL; + return nullptr; } else { @@ -677,9 +679,9 @@ const AuctionBid *Auction::GetPreviousBid() const */ int Auction::GetActualBid(AuctionBid *bid) { - assert(bid != NULL); + assert(bid != nullptr); int bidNeeded = std::max(m_minBid, bid->GetBid()); - if (m_highBid != NULL) + if (m_highBid != nullptr) { bidNeeded = m_highBid->GetBid(); if (*bid > *m_highBid) @@ -765,7 +767,7 @@ AuctionResultCode Auction::AddBid( AuctionBid *auctionBid = new AuctionBid(bidderId, bid, maxProxyBid); int newBidForHighBidder = GetActualBid(auctionBid); - if (m_highBid != NULL) + if (m_highBid != nullptr) { if (*auctionBid <= *m_highBid) { @@ -810,7 +812,7 @@ const AuctionBid *Auction::GetPlayerBid(const NetworkId & playerId) const } ++iter; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- @@ -826,7 +828,7 @@ bool Auction::Update(int gameTime) //immediate sale DEBUG_REPORT_LOG(true, ("[Commodities Server Auction::Update] : Expiring immediate sale - Auction is active and sold.\n")); - if ((m_trackId != -1) && (CommodityServer::getInstance().getGameServer(m_trackId) != NULL)) + if ((m_trackId != -1) && (CommodityServer::getInstance().getGameServer(m_trackId) != nullptr)) { Expire(true, false, m_trackId); m_trackId = -1; @@ -840,14 +842,14 @@ bool Auction::Update(int gameTime) { DEBUG_REPORT_LOG(true, ("[Commodities Server Auction::Update] : Auction expiring based on timer.\n")); - if ((m_trackId != -1) && (CommodityServer::getInstance().getGameServer(m_trackId) != NULL)) + if ((m_trackId != -1) && (CommodityServer::getInstance().getGameServer(m_trackId) != nullptr)) { - Expire(m_highBid != NULL, true, m_trackId); + Expire(m_highBid != nullptr, true, m_trackId); m_trackId = -1; } else { - Expire(m_highBid != NULL, true); + Expire(m_highBid != nullptr, true); } } @@ -862,7 +864,7 @@ void Auction::Expire(bool sold, bool expiredBasedOnTimer, int track_id) m_auctionTimer = 0; m_active = false; - if (sold && m_highBid != NULL) + if (sold && m_highBid != nullptr) { m_sold = true; } @@ -934,7 +936,7 @@ void Auction::Expire(bool sold, bool expiredBasedOnTimer, int track_id) m_location.SetVendorFirstTimerExpiredAuctionDate(time(0)); } - DEBUG_REPORT_LOG(true, ("[Commodities Server Auction::Expire] : Sending OnAuctionExpired for non-sold auction and null high bid obj .\n")); + DEBUG_REPORT_LOG(true, ("[Commodities Server Auction::Expire] : Sending OnAuctionExpired for non-sold auction and nullptr high bid obj .\n")); AuctionMarket::getInstance().OnAuctionExpired( GetCreatorId(), m_sold, m_flags, NetworkId::cms_invalid, 0, m_item->GetItemId(), 0, @@ -1107,8 +1109,8 @@ void Auction::BuildSearchableAttributeList() std::map const & saAlias = CommoditiesAdvancedSearchAttribute::getSearchAttributeNameAliasesForGameObjectType(m_item->GetCategory()); // for factory crates, also include the attributes of the item inside the crate - std::map const * saItemInsideFactoryCrate = NULL; - std::map const * saAliasItemInsideFactoryCrate = NULL; + std::map const * saItemInsideFactoryCrate = nullptr; + std::map const * saAliasItemInsideFactoryCrate = nullptr; int gotItemInsideFactoryCrate = 0; if (m_item->GetCategory() == SharedObjectTemplate::GOT_misc_factory_crate) @@ -1134,10 +1136,10 @@ void Auction::BuildSearchableAttributeList() saAliasItemInsideFactoryCrate = &(CommoditiesAdvancedSearchAttribute::getSearchAttributeNameAliasesForGameObjectType(gotItemInsideFactoryCrate)); if (saItemInsideFactoryCrate->empty()) - saItemInsideFactoryCrate = NULL; + saItemInsideFactoryCrate = nullptr; if (saAliasItemInsideFactoryCrate->empty()) - saAliasItemInsideFactoryCrate = NULL; + saAliasItemInsideFactoryCrate = nullptr; } } @@ -1360,8 +1362,8 @@ void Auction::BuildSearchableAttributeList() if (!m_searchableAttributeString) m_searchableAttributeString = new std::map; - static uint32 const shipCertAttributeCrc = Crc::calculate("ship_equipment_certification_search_attribute"); - static uint32 const astromechCertAttributeCrc = Crc::calculate("astromech_certification_search_attribute"); + static uint32 const shipCertAttributeCrc = constcrc("ship_equipment_certification_search_attribute"); + static uint32 const astromechCertAttributeCrc = constcrc("astromech_certification_search_attribute"); if (itemIsShipComponentOrShipFlightComputer) { diff --git a/engine/server/application/CommoditiesServer/src/shared/AuctionLocation.cpp b/engine/server/application/CommoditiesServer/src/shared/AuctionLocation.cpp index df458ef0..d692840d 100755 --- a/engine/server/application/CommoditiesServer/src/shared/AuctionLocation.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/AuctionLocation.cpp @@ -137,7 +137,7 @@ AuctionLocation::~AuctionLocation() bool AuctionLocation::AddAuction(Auction *auction) { - assert(auction != NULL); + assert(auction != nullptr); if (IsVendorMarket() && (!auction->IsActive() || !IsOwner(auction->GetCreatorId()))) { @@ -189,7 +189,7 @@ void AuctionLocation::CancelVendorSale(Auction *auction) bool AuctionLocation::RemoveAuction(Auction *auction) { - assert(auction != NULL); + assert(auction != nullptr); return RemoveAuction(auction->GetItem().GetItemId()); } @@ -265,7 +265,7 @@ Auction *AuctionLocation::GetAuction(const NetworkId & itemId) return((*i).second); } } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/application/CommoditiesServer/src/shared/AuctionMarket.cpp b/engine/server/application/CommoditiesServer/src/shared/AuctionMarket.cpp index a07b0864..328f189e 100644 --- a/engine/server/application/CommoditiesServer/src/shared/AuctionMarket.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/AuctionMarket.cpp @@ -121,7 +121,7 @@ namespace AuctionMarketNamespace Auction const * const auction, int const type, int const entranceCharge, - AuctionBid const * const playerBid = NULL + AuctionBid const * const playerBid = nullptr ) { AuctionDataHeader *header = new AuctionDataHeader; @@ -301,7 +301,7 @@ namespace AuctionMarketNamespace std::map attributeValue; }; - GetItemAttributeDataRequest * getItemAttributeDataRequest = NULL; + GetItemAttributeDataRequest * getItemAttributeDataRequest = nullptr; void processItemAttributeData(std::map const & auctions); @@ -394,8 +394,8 @@ void AuctionMarketNamespace::processItemAttributeData(std::map const * skipAttribute = NULL; - std::map const * skipAttributeAlias = NULL; + std::map const * skipAttribute = nullptr; + std::map const * skipAttributeAlias = nullptr; if (getItemAttributeDataRequest->ignoreSearchableAttribute) { std::map const & sa = CommoditiesAdvancedSearchAttribute::getSearchAttributeForGameObjectType(iterAuction->second->GetItem().GetCategory()); @@ -590,7 +590,7 @@ void AuctionMarketNamespace::processItemAttributeData(std::mapGetLocation(); if (!location.IsOwner(auction->GetItem().GetOwnerId())) @@ -1979,7 +1979,7 @@ void AuctionMarket::AcceptHighBid(const AcceptHighBidMessage &message) DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server AcceptHighBidMessage] : ResponseId : %d.\n", message.GetResponseId())); DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server AcceptHighBidMessage] : TrackId : %d.\n", message.GetTrackId())); - Auction *auction = NULL; + Auction *auction = nullptr; AuctionResultCode result = ARC_Success; std::map::iterator iter = m_auctions.find( message.GetAuctionId()); @@ -1994,7 +1994,7 @@ void AuctionMarket::AcceptHighBid(const AcceptHighBidMessage &message) { result = ARC_NotItemOwner; } - else if (auction->GetHighBid() == NULL) + else if (auction->GetHighBid() == nullptr) { result = ARC_NoBids; } @@ -2525,19 +2525,19 @@ void AuctionMarket::QueryAuctionHeaders( int debugNumberLocationsMatched = 0; int debugNumberAuctionsTested = 0; - std::map *auctionsPtr = NULL; + std::map *auctionsPtr = nullptr; int entranceCharge = 0; - AuctionLocation *locationPtr = NULL; - Auction *auctionPtr = NULL; + AuctionLocation *locationPtr = nullptr; + Auction *auctionPtr = nullptr; std::map::const_iterator auctionIterator; - AuctionDataHeader *header = NULL; + AuctionDataHeader *header = nullptr; bool checkItemTemplate; while (locationIter != locationIterEnd) { ++debugNumberLocationsTested; checkItemTemplate = false; - auctionsPtr = NULL; + auctionsPtr = nullptr; entranceCharge = 0; locationPtr = (*locationIter).second; @@ -2606,7 +2606,7 @@ void AuctionMarket::QueryAuctionHeaders( auctionPtr = (*auctionIterator).second; const AuctionItem &item = auctionPtr->GetItem(); - header = NULL; + header = nullptr; // Check to see if the item template matches if (searchForResourceContainer && (itemTemplateId != 0)) @@ -4977,7 +4977,7 @@ void AuctionMarket::getAuctionLocationPriorityQueue(int requestingGameServerId, { std::string output; char buffer[2048]; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); for (std::set >::const_iterator iterPQ = m_priorityQueueAuctionLocation.begin(); iterPQ != m_priorityQueueAuctionLocation.end(); ++iterPQ) { if (count <= 0) diff --git a/engine/server/application/CommoditiesServer/src/shared/CommodityServer.cpp b/engine/server/application/CommoditiesServer/src/shared/CommodityServer.cpp index 1e2671be..6e00a019 100755 --- a/engine/server/application/CommoditiesServer/src/shared/CommodityServer.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/CommodityServer.cpp @@ -29,6 +29,9 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "sharedLog/Log.h" #include "sharedLog/SetupSharedLog.h" + +#include "sharedFoundation/CrcConstexpr.hpp" + #include //----------------------------------------------------------------------- @@ -68,7 +71,9 @@ CommodityServer::~CommodityServer() void CommodityServer::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { - if(message.isType("CommoditiesLoadDone")) + const uint32 messageType = message.getType(); + + if(messageType == constcrc("CommoditiesLoadDone")) { m_commoditiesServerLoadDone = 1; @@ -76,7 +81,7 @@ void CommodityServer::receiveMessage(const MessageDispatch::Emitter & source, co if (m_commoditiesServerLoadTime == -1) m_commoditiesServerLoadTime = (time(0) - m_timeCommoditiesServerStarted) / 60; } - else if (message.isType("DatabaseServerConnectionClosed")) + else if (messageType == constcrc("DatabaseServerConnectionClosed")) { WARNING(true, ("[Commodities Server] : No connection to the database server. Shutting down.\n")); exit(0); @@ -191,7 +196,7 @@ void CommodityServer::run() s_commodityServerMetricsData = new CommodityServerMetricsData; MetricsManager::install(s_commodityServerMetricsData, false, "CommoditiesServer", "", 0); - time_t timePrevious = ::time(NULL); + time_t timePrevious = ::time(nullptr); time_t timeCurrent = timePrevious; while (true) @@ -202,7 +207,7 @@ void CommodityServer::run() break; NetworkHandler::update(); - timeCurrent = ::time(NULL); + timeCurrent = ::time(nullptr); MetricsManager::update(static_cast((timeCurrent - timePrevious) * 1000)); timePrevious = timeCurrent; @@ -229,18 +234,18 @@ void CommodityServer::run() // this is not a high priority thing, so wait until // the cluster has started and "stabilized" before // doing this; 3 hours should be adequate - time_t timeToRequestExcludedType = ::time(NULL) + 10800; + time_t timeToRequestExcludedType = ::time(nullptr) + 10800; // one time request from the game server (any game server) // to receive the resource tree hierarchy to support // searching for resource container - time_t timeToRequestResourceTree = ::time(NULL); + time_t timeToRequestResourceTree = ::time(nullptr); while(true) { NetworkHandler::update(); - timeCurrent = ::time(NULL); + timeCurrent = ::time(nullptr); MetricsManager::update(static_cast((timeCurrent - timePrevious) * 1000)); timePrevious = timeCurrent; diff --git a/engine/server/application/CommoditiesServer/src/shared/CommodityServerMetricsData.cpp b/engine/server/application/CommoditiesServer/src/shared/CommodityServerMetricsData.cpp index 4b1ff37e..90594e07 100755 --- a/engine/server/application/CommoditiesServer/src/shared/CommodityServerMetricsData.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/CommodityServerMetricsData.cpp @@ -74,7 +74,7 @@ void CommodityServerMetricsData::updateData() buffer[sizeof(buffer)-1] = '\0'; } - m_mapAuctionsCountByGameObjectTypeIndex[iterGameObjectType->first] = addMetric(buffer, 0, NULL, false, false); + m_mapAuctionsCountByGameObjectTypeIndex[iterGameObjectType->first] = addMetric(buffer, 0, nullptr, false, false); } } } diff --git a/engine/server/application/CommoditiesServer/src/shared/DatabaseServerConnection.cpp b/engine/server/application/CommoditiesServer/src/shared/DatabaseServerConnection.cpp index 25b6029e..20b9a9cd 100755 --- a/engine/server/application/CommoditiesServer/src/shared/DatabaseServerConnection.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/DatabaseServerConnection.cpp @@ -21,6 +21,8 @@ #include "serverNetworkMessages/GetMarketAuctionBidsMessage.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- DatabaseServerConnection::DatabaseServerConnection(const std::string & a, const unsigned short p) : @@ -65,151 +67,161 @@ void DatabaseServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage msg(ri); ri = message.begin(); + + const uint32 messageType = msg.getType(); - if (msg.isType("CommoditiesLoadDone")) - { - if (currentLocationCount != lastLocationCount) + switch(messageType) { + case constcrc("CommoditiesLoadDone") : { - DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); - LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); - lastLocationCount = currentLocationCount; - } - if (currentAuctionCount != lastAuctionCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); - LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); - lastAuctionCount = currentAuctionCount; - } - if (currentAuctionAttributeCount != lastAuctionAttributeCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); - LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); - lastAuctionAttributeCount = currentAuctionAttributeCount; - } - if (currentBidCount != lastBidCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionBids record received\n", currentBidCount)); - LOG("CommoditiesServer", ("%d MarketAuctionBids record received", currentBidCount)); - lastBidCount = currentBidCount; - } - REPORT_LOG("DatabaseServerConnection", ("CommoditiesLoadDone Message received on connection with the database server\n")); - CommoditiesLoadDoneMessage m(ri); - REPORT_LOG("DatabaseServerConnection", ("%d rows received on Auction_Locations\n", m.getAuctionLocationsCount())); - REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auctions\n", m.getMarketAuctionsCount())); - REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auction_Attributes\n", m.getMarketAuctionAttributesCount())); - REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auction_Bids\n", m.getMarketAuctionBidsCount())); - LOG("CommoditiesServer", ("CommoditiesLoadDone Message received, %d rows Auction_Locations, %d rows Market_Auctions, %d rows Market_Auction_Attributes, %d rows Market_Auction_Bids", m.getAuctionLocationsCount(), m.getMarketAuctionsCount(), m.getMarketAuctionAttributesCount(), m.getMarketAuctionBidsCount())); - - LOG("CommoditiesServer", ("Start build index for attribute search")); - AuctionMarket::getInstance().BuildAuctionsSearchableAttributeList(); - LOG("CommoditiesServer", ("End build index for attribute search")); - - emitMessage(m); - } - else if (msg.isType("GetAuctionLocationsMessage")) - { - GetAuctionLocationsMessage m(ri); - const std::list & auctionLocations = m.getAuctionLocations(); - for (std::list::const_iterator iter = auctionLocations.begin(); iter != auctionLocations.end(); ++iter) - { - AuctionMarket::getInstance().onReceiveAuctionLocations(iter->locationId, iter->locationName, iter->ownerId, iter->salesTax, iter->salesTaxBankId, iter->emptyDate, iter->lastAccessDate, iter->inactiveDate, iter->status, iter->searchEnabled, iter->entranceCharge); - currentLocationCount++; - if (currentLocationCount - lastLocationCount >= 1000) + if (currentLocationCount != lastLocationCount) { DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); - LOG("CommoditiesServer", ("%d AuctionLocations record received", currentLocationCount)); + LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); lastLocationCount = currentLocationCount; } - } - } - else if (msg.isType("GetMarketAuctionsMessage")) - { - if (currentLocationCount != lastLocationCount) - { - DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); - LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); - lastLocationCount = currentLocationCount; - } - GetMarketAuctionsMessage m(ri); - const std::list & auctions = m.getAuctions(); - for (std::list::const_iterator iter = auctions.begin(); iter != auctions.end(); ++iter) - { - AuctionMarket::getInstance().onReceiveMarketAuctions(iter->itemId, iter->ownerId, iter->creatorId, iter->locationId, iter->minBid, iter->buyNowPrice, iter->auctionTimer, iter->oob, iter->userDescription, iter->category, iter->itemTemplateId, iter->itemName, iter->itemTimer, iter->active, iter->itemSize); - currentAuctionCount++; - if (currentAuctionCount - lastAuctionCount >= 10000) + if (currentAuctionCount != lastAuctionCount) { DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); - LOG("CommoditiesServer", ("%d MarketAuctions record received", currentAuctionCount)); + LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); lastAuctionCount = currentAuctionCount; } - } - } - else if (msg.isType("GetMarketAuctionAttributesMessage")) - { - if (currentLocationCount != lastLocationCount) - { - DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); - LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); - lastLocationCount = currentLocationCount; - } - if (currentAuctionCount != lastAuctionCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); - LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); - lastAuctionCount = currentAuctionCount; - } - GetMarketAuctionAttributesMessage m(ri); - const std::list & attributes = m.getAttributes(); - for (std::list::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) - { - AuctionMarket::getInstance().onReceiveMarketAuctionAttributes(iter->itemId, iter->attributeName, iter->attributeValue); - currentAuctionAttributeCount++; - if (currentAuctionAttributeCount - lastAuctionAttributeCount >= 10000) + if (currentAuctionAttributeCount != lastAuctionAttributeCount) { DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); - LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received", currentAuctionAttributeCount)); + LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); lastAuctionAttributeCount = currentAuctionAttributeCount; } - } - } - else if (msg.isType("GetMarketAuctionBidsMessage")) - { - if (currentLocationCount != lastLocationCount) - { - DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); - LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); - lastLocationCount = currentLocationCount; - } - if (currentAuctionCount != lastAuctionCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); - LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); - lastAuctionCount = currentAuctionCount; - } - if (currentAuctionAttributeCount != lastAuctionAttributeCount) - { - DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); - LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); - lastAuctionAttributeCount = currentAuctionAttributeCount; - } - GetMarketAuctionBidsMessage m(ri); - const std::list & bids = m.getMarketAuctionBids(); - for (std::list::const_iterator iter = bids.begin(); iter != bids.end(); ++iter) - { - AuctionMarket::getInstance().onReceiveMarketAuctionBids(iter->itemId, iter->bidderId, iter->bid, iter->maxProxyBid); - currentBidCount++; - if (currentBidCount - lastBidCount >= 1000) + if (currentBidCount != lastBidCount) { DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionBids record received\n", currentBidCount)); - LOG("CommoditiesServer", ("%d MarketAuctionBids record received\n", currentBidCount)); + LOG("CommoditiesServer", ("%d MarketAuctionBids record received", currentBidCount)); lastBidCount = currentBidCount; } + REPORT_LOG("DatabaseServerConnection", ("CommoditiesLoadDone Message received on connection with the database server\n")); + CommoditiesLoadDoneMessage m(ri); + REPORT_LOG("DatabaseServerConnection", ("%d rows received on Auction_Locations\n", m.getAuctionLocationsCount())); + REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auctions\n", m.getMarketAuctionsCount())); + REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auction_Attributes\n", m.getMarketAuctionAttributesCount())); + REPORT_LOG("DatabaseServerConnection", ("%d rows received on Market_Auction_Bids\n", m.getMarketAuctionBidsCount())); + LOG("CommoditiesServer", ("CommoditiesLoadDone Message received, %d rows Auction_Locations, %d rows Market_Auctions, %d rows Market_Auction_Attributes, %d rows Market_Auction_Bids", m.getAuctionLocationsCount(), m.getMarketAuctionsCount(), m.getMarketAuctionAttributesCount(), m.getMarketAuctionBidsCount())); + + LOG("CommoditiesServer", ("Start build index for attribute search")); + AuctionMarket::getInstance().BuildAuctionsSearchableAttributeList(); + LOG("CommoditiesServer", ("End build index for attribute search")); + + emitMessage(m); + break; + } + case constcrc("GetAuctionLocationsMessage") : + { + GetAuctionLocationsMessage m(ri); + const std::list & auctionLocations = m.getAuctionLocations(); + for (std::list::const_iterator iter = auctionLocations.begin(); iter != auctionLocations.end(); ++iter) + { + AuctionMarket::getInstance().onReceiveAuctionLocations(iter->locationId, iter->locationName, iter->ownerId, iter->salesTax, iter->salesTaxBankId, iter->emptyDate, iter->lastAccessDate, iter->inactiveDate, iter->status, iter->searchEnabled, iter->entranceCharge); + currentLocationCount++; + if (currentLocationCount - lastLocationCount >= 1000) + { + DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); + LOG("CommoditiesServer", ("%d AuctionLocations record received", currentLocationCount)); + lastLocationCount = currentLocationCount; + } + } + break; + } + case constcrc("GetMarketAuctionsMessage") : + { + if (currentLocationCount != lastLocationCount) + { + DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); + LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); + lastLocationCount = currentLocationCount; + } + GetMarketAuctionsMessage m(ri); + const std::list & auctions = m.getAuctions(); + for (std::list::const_iterator iter = auctions.begin(); iter != auctions.end(); ++iter) + { + AuctionMarket::getInstance().onReceiveMarketAuctions(iter->itemId, iter->ownerId, iter->creatorId, iter->locationId, iter->minBid, iter->buyNowPrice, iter->auctionTimer, iter->oob, iter->userDescription, iter->category, iter->itemTemplateId, iter->itemName, iter->itemTimer, iter->active, iter->itemSize); + currentAuctionCount++; + if (currentAuctionCount - lastAuctionCount >= 10000) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); + LOG("CommoditiesServer", ("%d MarketAuctions record received", currentAuctionCount)); + lastAuctionCount = currentAuctionCount; + } + } + break; + } + case constcrc("GetMarketAuctionAttributesMessage") : + { + if (currentLocationCount != lastLocationCount) + { + DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); + LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); + lastLocationCount = currentLocationCount; + } + if (currentAuctionCount != lastAuctionCount) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); + LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); + lastAuctionCount = currentAuctionCount; + } + GetMarketAuctionAttributesMessage m(ri); + const std::list & attributes = m.getAttributes(); + for (std::list::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) + { + AuctionMarket::getInstance().onReceiveMarketAuctionAttributes(iter->itemId, iter->attributeName, iter->attributeValue); + currentAuctionAttributeCount++; + if (currentAuctionAttributeCount - lastAuctionAttributeCount >= 10000) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); + LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received", currentAuctionAttributeCount)); + lastAuctionAttributeCount = currentAuctionAttributeCount; + } + } + break; + } + case constcrc("GetMarketAuctionBidsMessage") : + { + if (currentLocationCount != lastLocationCount) + { + DEBUG_REPORT_LOG(true, (" -- %d AuctionLocations record received\n", currentLocationCount)); + LOG("CommoditiesServer", ("%d AuctionLocations record received\n", currentLocationCount)); + lastLocationCount = currentLocationCount; + } + if (currentAuctionCount != lastAuctionCount) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctions record received\n", currentAuctionCount)); + LOG("CommoditiesServer", ("%d MarketAuctions record received\n", currentAuctionCount)); + lastAuctionCount = currentAuctionCount; + } + if (currentAuctionAttributeCount != lastAuctionAttributeCount) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); + LOG("CommoditiesServer", ("%d MarketAuctionAttributes record received\n", currentAuctionAttributeCount)); + lastAuctionAttributeCount = currentAuctionAttributeCount; + } + GetMarketAuctionBidsMessage m(ri); + const std::list & bids = m.getMarketAuctionBids(); + for (std::list::const_iterator iter = bids.begin(); iter != bids.end(); ++iter) + { + AuctionMarket::getInstance().onReceiveMarketAuctionBids(iter->itemId, iter->bidderId, iter->bid, iter->maxProxyBid); + currentBidCount++; + if (currentBidCount - lastBidCount >= 1000) + { + DEBUG_REPORT_LOG(true, (" -- %d MarketAuctionBids record received\n", currentBidCount)); + LOG("CommoditiesServer", ("%d MarketAuctionBids record received\n", currentBidCount)); + lastBidCount = currentBidCount; + } + } + break; + } + case constcrc("DeleteCharacterMessage") : + { + DeleteCharacterMessage message(ri); + AuctionMarket::getInstance().DeleteCharacter(message); + break; } - } - else if(msg.isType("DeleteCharacterMessage")) - { - DeleteCharacterMessage message(ri); - AuctionMarket::getInstance().DeleteCharacter(message); } } diff --git a/engine/server/application/CommoditiesServer/src/shared/GameServerConnection.cpp b/engine/server/application/CommoditiesServer/src/shared/GameServerConnection.cpp index 21b13a20..ab4ea76e 100755 --- a/engine/server/application/CommoditiesServer/src/shared/GameServerConnection.cpp +++ b/engine/server/application/CommoditiesServer/src/shared/GameServerConnection.cpp @@ -36,6 +36,8 @@ #include "serverNetworkMessages/QueryVendorItemCountMessage.h" #include "serverNetworkMessages/UpdateVendorStatusMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace GameServerConnectionNamespace @@ -88,201 +90,235 @@ void GameServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage msg(ri); ri = message.begin(); + + const uint32 messageType = msg.getType(); - if(msg.isType("AcceptHighBidMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AcceptHighBidMessage from game server id: %d.\n", m_gameServerId )); - AcceptHighBidMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().AcceptHighBid(message); - } - else if(msg.isType("AddAuctionMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddAuctionMessage from game server id: %d.\n", m_gameServerId )); - AddAuctionMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().AddAuction(message); - } - else if(msg.isType("AddBidMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddBidMessage from game server id: %d.\n", m_gameServerId )); - AddBidMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().AddBid(message); - } - else if(msg.isType("AddImmediateAuctionMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddImmediateAuctionMessage from game server id: %d.\n", m_gameServerId )); - AddImmediateAuctionMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().AddImmediateAuction(message); - } - else if(msg.isType("CancelAuctionMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CancelAuctionMessage from game server id: %d.\n", m_gameServerId )); - CancelAuctionMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().CancelAuction(message); - } - else if(msg.isType("CreateVendorMarketMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CreateVendorMarketMessage from game server id: %d.\n", m_gameServerId )); - CreateVendorMarketMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().CreateVendorMarket(message); - } - else if(msg.isType("DestroyVendorMarketMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message DestroyVendorMarketMessage from game server id: %d.\n", m_gameServerId )); - DestroyVendorMarketMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().DestroyVendorMarket(message); - } - else if(msg.isType("DeleteAuctionLocationMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message DeleteAuctionLocationMessage from game server id: %d.\n", m_gameServerId )); - DeleteAuctionLocationMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().DeleteAuctionLocation(message); - } - else if(msg.isType("GetItemDetailsMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetItemDetailsMessage from game server id: %d.\n", m_gameServerId )); - GetItemDetailsMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().GetItemDetails(message); - } - else if(msg.isType("GetItemMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetItemMessage from game server id: %d.\n", m_gameServerId )); - GetItemMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().GetItem(message); - } - else if(msg.isType("SetSalesTaxMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message SetSalesTaxMessage from game server id: %d.\n", m_gameServerId )); - SetSalesTaxMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().SetSalesTax(message); - } - else if(msg.isType("GetVendorOwnerMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetVendorOwnerMessage from game server id: %d.\n", m_gameServerId )); - GetVendorOwnerMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().GetVendorOwner(message); - } - else if(msg.isType("GetVendorValueMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetVendorValueMessage from game server id: %d.\n", m_gameServerId )); - GetVendorValueMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().GetVendorValue(message); - } - else if(msg.isType("QueryAuctionHeadersMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message QueryAuctionHeadersMessage from game server id: %d.\n", m_gameServerId )); - QueryAuctionHeadersMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().QueryAuctionHeaders(message); - } - else if(msg.isType("SetGameTimeMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message SetGameTimeMessage from game server id: %d.\n", m_gameServerId )); - SetGameTimeMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().SetGameTime(message); - } - else if(msg.isType("CleanupInvalidItemRetrievalMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CleanupInvalidItemRetrievalMessage from game server id: %d.\n", m_gameServerId )); - CleanupInvalidItemRetrievalMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().CleanupInvalidItemRetrieval(message); - } - else if(msg.isType("QueryVendorItemCountMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message QueryVendorItemCountMessage from game server id: %d.\n", m_gameServerId )); - QueryVendorItemCountMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().QueryVendorItemCount(message); - } - else if(msg.isType("GetPlayerVendorCountMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetPlayerVendorCountMessage from game server id: %d.\n", m_gameServerId )); - GetPlayerVendorCountMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().GetPlayerVendorCount(message); - } - else if(msg.isType("UpdateVendorSearchOptionMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorSearchOptionMessage from game server id: %d.\n", m_gameServerId )); - UpdateVendorSearchOptionMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().UpdateVendorSearchOption(message); - } - else if(msg.isType("SetEntranceChargeMessage")) - { - DEBUG_REPORT_LOG(/*m_showAllDebugInfo*/ true, ("[Commodities Server] : Received message SetEntranceChargeMessage from game server id: %d.\n", m_gameServerId )); - SetEntranceChargeMessage message(ri); - message.SetTrackId(m_gameServerId); - AuctionMarket::getInstance().SetEntranceCharge(message); - } - else if(msg.isType("ResponseCommoditiesExcludedGotTypes")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseCommoditiesExcludedGotTypes from game server id: %d.\n", m_gameServerId )); - GenericValueTypeMessage > message(ri); - AuctionMarket::getInstance().VerifyExcludedGotTypes(message.getValue()); - } - else if(msg.isType("ResponseCommoditiesExcludedResourceClasses")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseCommoditiesExcludedResourceClasses from game server id: %d.\n", m_gameServerId )); - GenericValueTypeMessage > message(ri); - AuctionMarket::getInstance().VerifyExcludedResourceClasses(message.getValue()); - } - else if(msg.isType("ResponseResourceTreeHierarchy")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseResourceTreeHierarchy from game server id: %d.\n", m_gameServerId )); - GenericValueTypeMessage > > message(ri); - AuctionMarket::getInstance().SetResourceTreeHierarchy(message.getValue()); - } - else if(msg.isType("UpdateVendorStatusMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorStatusMessage from game server id: %d.\n", m_gameServerId)); - UpdateVendorStatusMessage message(ri); - AuctionMarket::getInstance().UpdateVendorStatus(message); - } - else if(msg.isType("UpdateVendorLocationMessage")) - { - DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorLocationMessage from game server id: %d.\n", m_gameServerId)); - GenericValueTypeMessage > const message(ri); - AuctionMarket::getInstance().UpdateVendorLocation(message.getValue().first, message.getValue().second); - } - else if(msg.isType("GetItemAttributeData")) - { - GenericValueTypeMessage, std::pair, std::pair > > > const message(ri); - AuctionMarket::getInstance().getItemAttributeData(m_gameServerId, message.getValue().first.first, message.getValue().first.second, message.getValue().second.first.first, message.getValue().second.first.second, message.getValue().second.second.first, message.getValue().second.second.second); - } - else if(msg.isType("GetItemAttributeDataValues")) - { - GenericValueTypeMessage >, std::pair > > const message(ri); - AuctionMarket::getInstance().getItemAttributeDataValues(m_gameServerId, message.getValue().first.first, message.getValue().first.second.first, message.getValue().first.second.second, message.getValue().second.first, message.getValue().second.second); - } - else if(msg.isType("GetItemAttribute")) - { - GenericValueTypeMessage > const message(ri); - AuctionMarket::getInstance().getItemAttribute(m_gameServerId, message.getValue().first, message.getValue().second); - } - else if(msg.isType("GetVendorInfoForPlayer")) - { - GenericValueTypeMessage, bool> > const message(ri); - AuctionMarket::getInstance().getVendorInfoForPlayer(m_gameServerId, message.getValue().first.first, message.getValue().first.second, message.getValue().second); - } - else if(msg.isType("GetALPQ")) - { - GenericValueTypeMessage > const message(ri); - AuctionMarket::getInstance().getAuctionLocationPriorityQueue(m_gameServerId, message.getValue().first, message.getValue().second); + switch(messageType) { + case constcrc("AcceptHighBidMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AcceptHighBidMessage from game server id: %d.\n", m_gameServerId )); + AcceptHighBidMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().AcceptHighBid(message); + break; + } + case constcrc("AddAuctionMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddAuctionMessage from game server id: %d.\n", m_gameServerId )); + AddAuctionMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().AddAuction(message); + break; + } + case constcrc("AddBidMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddBidMessage from game server id: %d.\n", m_gameServerId )); + AddBidMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().AddBid(message); + break; + } + case constcrc("AddImmediateAuctionMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message AddImmediateAuctionMessage from game server id: %d.\n", m_gameServerId )); + AddImmediateAuctionMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().AddImmediateAuction(message); + break; + } + case constcrc("CancelAuctionMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CancelAuctionMessage from game server id: %d.\n", m_gameServerId )); + CancelAuctionMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().CancelAuction(message); + break; + } + case constcrc("CreateVendorMarketMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CreateVendorMarketMessage from game server id: %d.\n", m_gameServerId )); + CreateVendorMarketMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().CreateVendorMarket(message); + break; + } + case constcrc("DestroyVendorMarketMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message DestroyVendorMarketMessage from game server id: %d.\n", m_gameServerId )); + DestroyVendorMarketMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().DestroyVendorMarket(message); + break; + } + case constcrc("DeleteAuctionLocationMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message DeleteAuctionLocationMessage from game server id: %d.\n", m_gameServerId )); + DeleteAuctionLocationMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().DeleteAuctionLocation(message); + break; + } + case constcrc("GetItemDetailsMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetItemDetailsMessage from game server id: %d.\n", m_gameServerId )); + GetItemDetailsMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().GetItemDetails(message); + break; + } + case constcrc("GetItemMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetItemMessage from game server id: %d.\n", m_gameServerId )); + GetItemMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().GetItem(message); + break; + } + case constcrc("SetSalesTaxMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message SetSalesTaxMessage from game server id: %d.\n", m_gameServerId )); + SetSalesTaxMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().SetSalesTax(message); + break; + } + case constcrc("GetVendorOwnerMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetVendorOwnerMessage from game server id: %d.\n", m_gameServerId )); + GetVendorOwnerMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().GetVendorOwner(message); + break; + } + case constcrc("GetVendorValueMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetVendorValueMessage from game server id: %d.\n", m_gameServerId )); + GetVendorValueMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().GetVendorValue(message); + break; + } + case constcrc("QueryAuctionHeadersMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message QueryAuctionHeadersMessage from game server id: %d.\n", m_gameServerId )); + QueryAuctionHeadersMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().QueryAuctionHeaders(message); + break; + } + case constcrc("SetGameTimeMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message SetGameTimeMessage from game server id: %d.\n", m_gameServerId )); + SetGameTimeMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().SetGameTime(message); + break; + } + case constcrc("CleanupInvalidItemRetrievalMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message CleanupInvalidItemRetrievalMessage from game server id: %d.\n", m_gameServerId )); + CleanupInvalidItemRetrievalMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().CleanupInvalidItemRetrieval(message); + break; + } + case constcrc("QueryVendorItemCountMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message QueryVendorItemCountMessage from game server id: %d.\n", m_gameServerId )); + QueryVendorItemCountMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().QueryVendorItemCount(message); + break; + } + case constcrc("GetPlayerVendorCountMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message GetPlayerVendorCountMessage from game server id: %d.\n", m_gameServerId )); + GetPlayerVendorCountMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().GetPlayerVendorCount(message); + break; + } + case constcrc("UpdateVendorSearchOptionMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorSearchOptionMessage from game server id: %d.\n", m_gameServerId )); + UpdateVendorSearchOptionMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().UpdateVendorSearchOption(message); + break; + } + case constcrc("SetEntranceChargeMessage") : + { + DEBUG_REPORT_LOG(/*m_showAllDebugInfo*/ true, ("[Commodities Server] : Received message SetEntranceChargeMessage from game server id: %d.\n", m_gameServerId )); + SetEntranceChargeMessage message(ri); + message.SetTrackId(m_gameServerId); + AuctionMarket::getInstance().SetEntranceCharge(message); + break; + } + case constcrc("ResponseCommoditiesExcludedGotTypes") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseCommoditiesExcludedGotTypes from game server id: %d.\n", m_gameServerId )); + GenericValueTypeMessage > message(ri); + AuctionMarket::getInstance().VerifyExcludedGotTypes(message.getValue()); + break; + } + case constcrc("ResponseCommoditiesExcludedResourceClasses") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseCommoditiesExcludedResourceClasses from game server id: %d.\n", m_gameServerId )); + GenericValueTypeMessage > message(ri); + AuctionMarket::getInstance().VerifyExcludedResourceClasses(message.getValue()); + break; + } + case constcrc("ResponseResourceTreeHierarchy") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message ResponseResourceTreeHierarchy from game server id: %d.\n", m_gameServerId )); + GenericValueTypeMessage > > message(ri); + AuctionMarket::getInstance().SetResourceTreeHierarchy(message.getValue()); + break; + } + case constcrc("UpdateVendorStatusMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorStatusMessage from game server id: %d.\n", m_gameServerId)); + UpdateVendorStatusMessage message(ri); + AuctionMarket::getInstance().UpdateVendorStatus(message); + break; + } + case constcrc("UpdateVendorLocationMessage") : + { + DEBUG_REPORT_LOG(m_showAllDebugInfo, ("[Commodities Server] : Received message UpdateVendorLocationMessage from game server id: %d.\n", m_gameServerId)); + GenericValueTypeMessage > const message(ri); + AuctionMarket::getInstance().UpdateVendorLocation(message.getValue().first, message.getValue().second); + break; + } + case constcrc("GetItemAttributeData") : + { + GenericValueTypeMessage, std::pair, std::pair > > > const message(ri); + AuctionMarket::getInstance().getItemAttributeData(m_gameServerId, message.getValue().first.first, message.getValue().first.second, message.getValue().second.first.first, message.getValue().second.first.second, message.getValue().second.second.first, message.getValue().second.second.second); + break; + } + case constcrc("GetItemAttributeDataValues") : + { + GenericValueTypeMessage >, std::pair > > const message(ri); + AuctionMarket::getInstance().getItemAttributeDataValues(m_gameServerId, message.getValue().first.first, message.getValue().first.second.first, message.getValue().first.second.second, message.getValue().second.first, message.getValue().second.second); + break; + } + case constcrc("GetItemAttribute") : + { + GenericValueTypeMessage > const message(ri); + AuctionMarket::getInstance().getItemAttribute(m_gameServerId, message.getValue().first, message.getValue().second); + break; + } + case constcrc("GetVendorInfoForPlayer") : + { + GenericValueTypeMessage, bool> > const message(ri); + AuctionMarket::getInstance().getVendorInfoForPlayer(m_gameServerId, message.getValue().first.first, message.getValue().first.second, message.getValue().second); + break; + } + case constcrc("GetALPQ") : + { + GenericValueTypeMessage > const message(ri); + AuctionMarket::getInstance().getAuctionLocationPriorityQueue(m_gameServerId, message.getValue().first, message.getValue().second); + break; + } } } diff --git a/engine/server/application/CommoditiesServer/src/win32/WinMain.cpp b/engine/server/application/CommoditiesServer/src/win32/WinMain.cpp new file mode 100755 index 00000000..5051cfa4 --- /dev/null +++ b/engine/server/application/CommoditiesServer/src/win32/WinMain.cpp @@ -0,0 +1,70 @@ +#include "FirstCommodityServer.h" + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/TreeFile.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedGame/CommoditiesAdvancedSearchAttribute.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedNetwork/SetupSharedNetwork.h" +#include "sharedNetwork/NetworkHandler.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedThread/SetupSharedThread.h" +#include "sharedUtility/DataTableManager.h" +#include "CommodityServer.h" +#include "ConfigCommodityServer.h" +#include "LocalizationManager.h" +#include "UnicodeUtils.h" + +int main(int argc, char ** argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + SetupSharedFoundation::install (setupFoundationData); + + ConfigSharedGame::install(); + SetupSharedCompression::install(); + SetupSharedFile::install(false); + SetupSharedNetworkMessages::install(); + + SetupSharedNetwork::SetupData networkSetupData; + SetupSharedNetwork::getDefaultServerSetupData(networkSetupData); + SetupSharedNetwork::install(networkSetupData); + NetworkHandler::install(); + + ConfigCommodityServer::install(); + + const bool displayBadStringIds = ConfigSharedGame::getDisplayBadStringIds (); + const bool debugStringIds = ConfigSharedGame::getDebugStringIds (); + Unicode::NarrowString defaultLocale(ConfigSharedGame::getDefaultLocale ()); + Unicode::UnicodeNarrowStringVector localeVector; + localeVector.push_back(defaultLocale); + + LocalizationManager::install (new TreeFile::TreeFileFactory, localeVector, debugStringIds, NULL, displayBadStringIds); + ExitChain::add(LocalizationManager::remove, "LocalizationManager::remove"); + + DataTableManager::install(); + CommoditiesAdvancedSearchAttribute::install(); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(CommodityServer::run); + + SetupSharedFoundation::remove(); + + return 0; +} + +//----------------------------------------------------------------------- diff --git a/engine/server/application/ConnectionServer/src/linux/main.cpp b/engine/server/application/ConnectionServer/src/linux/main.cpp index 24c76421..5984dd4c 100755 --- a/engine/server/application/ConnectionServer/src/linux/main.cpp +++ b/engine/server/application/ConnectionServer/src/linux/main.cpp @@ -37,7 +37,7 @@ int main(int argc, char ** argv) SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(time(NULL)); + SetupSharedRandom::install(time(nullptr)); //setup the server NetworkHandler::install(); diff --git a/engine/server/application/ConnectionServer/src/shared/CentralConnection.cpp b/engine/server/application/ConnectionServer/src/shared/CentralConnection.cpp index 07c3b71f..5ca0cca1 100755 --- a/engine/server/application/ConnectionServer/src/shared/CentralConnection.cpp +++ b/engine/server/application/ConnectionServer/src/shared/CentralConnection.cpp @@ -1,8 +1,3 @@ -// CentralConnection.cpp -// copyright 2001 Verant Interactive - -//----------------------------------------------------------------------- - #include "FirstConnectionServer.h" #include "CentralConnection.h" @@ -19,6 +14,8 @@ #include "sharedNetworkMessages/ErrorMessage.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- CentralConnection::CentralConnection(const std::string & address, const unsigned short port) : @@ -67,68 +64,79 @@ void CentralConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); const GameNetworkMessage msg(ri); ri = message.begin(); - - if(msg.isType("TransferLoginCharacterToSourceServer")) + + switch(msg.getType()) { - GenericValueTypeMessage login(ri); - // received a request to create a pseudoclient and connect it - // to a game server. - LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received TransferLoginCharacterToSourceServer request from CentralServer for %s\n", login.getValue().toString().c_str())); - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(login.getValue().getSourceStationId(), message)); - } - else if(msg.isType("TransferLoginCharacterToDestinationServer")) - { - GenericValueTypeMessage login(ri); - LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received TransferLoginCharacterToDestinationServer request from CentralServer for %s", login.getValue().toString().c_str())); - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(login.getValue().getDestinationStationId(), message)); - } - else if(msg.isType("CtsSrcCharWrongPlanet")) - { - GenericValueTypeMessage > const failureMsg(ri); - LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received CtsSrcCharWrongPlanet error from CentralServer for character (%s) stationId (%u) because character is not one of the 10 original ground planets", failureMsg.getValue().first.getValueString().c_str(), failureMsg.getValue().second)); - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(failureMsg.getValue().second, message)); - } - else if(msg.isType("TransferKickConnectedClients")) - { - GenericValueTypeMessage kick(ri); - ClientConnection * clientConnection = ConnectionServer::getClientConnection(kick.getValue()); - if(clientConnection) - { - ConnectionServer::dropClient(clientConnection, "TransferServer requests client drop"); - } - } - else if(msg.isType("TransferClosePseudoClientConnection")) - { - GenericValueTypeMessage closeRequest(ri); - PseudoClientConnection * pseudoClient = PseudoClientConnection::getPseudoClientConnection(closeRequest.getValue()); - delete pseudoClient; - } - else if(msg.isType("LoginDeniedRecentCTS")) - { - GenericValueTypeMessage > loginDeniedRecentCTS(ri); - ClientConnection * clientConnection = ConnectionServer::getClientConnection(loginDeniedRecentCTS.getValue().second); - if (clientConnection) - { - LOG("CustomerService", ("Login:%s, character %s (%s) is a recent CTS that has not been persisted yet.", ClientConnection::describeAccount(clientConnection).c_str(), clientConnection->getCharacterName().c_str(), clientConnection->getCharacterId().getValueString().c_str())); - ErrorMessage err("Login Failed", "The selected character has just been recently transferred and has not been completely initialized. In most cases, it takes about 15 minutes (but in some cases can take up to 2 hours) to complete initialization. Please try again later."); - clientConnection->send(err, true); - } - } - else if(msg.isType("LoginDeniedPendingPlayerRenameRequest")) - { - GenericValueTypeMessage > loginDeniedPendingPlayerRenameRequest(ri); - ClientConnection * clientConnection = ConnectionServer::getClientConnection(loginDeniedPendingPlayerRenameRequest.getValue().second); - if (clientConnection) - { - LOG("CustomerService", ("Login:%s, character %s (%s) has a pending player requested character rename request.", ClientConnection::describeAccount(clientConnection).c_str(), clientConnection->getCharacterName().c_str(), clientConnection->getCharacterId().getValueString().c_str())); - ErrorMessage err("Login Failed", "The selected character currently has a pending character rename request. It can take up to 30 minutes for the rename request to complete."); - clientConnection->send(err, true); - } - } - else - { - ServerConnection::onReceive(message); + case constcrc("TransferLoginCharacterToSourceServer") : + { + GenericValueTypeMessage login(ri); + // received a request to create a pseudoclient and connect it + // to a game server. + LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received TransferLoginCharacterToSourceServer request from CentralServer for %s\n", login.getValue().toString().c_str())); + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(login.getValue().getSourceStationId(), message)); + break; + } + case constcrc("TransferLoginCharacterToDestinationServer") : + { + GenericValueTypeMessage login(ri); + LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received TransferLoginCharacterToDestinationServer request from CentralServer for %s", login.getValue().toString().c_str())); + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(login.getValue().getDestinationStationId(), message)); + break; + } + case constcrc("CtsSrcCharWrongPlanet") : + { + GenericValueTypeMessage > const failureMsg(ri); + LOG("CustomerService", ("CharacterTransfer: ***ConnectionServer: Received CtsSrcCharWrongPlanet error from CentralServer for character (%s) stationId (%u) because character is not one of the 10 original ground planets", failureMsg.getValue().first.getValueString().c_str(), failureMsg.getValue().second)); + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(failureMsg.getValue().second, message)); + break; + } + case constcrc("TransferKickConnectedClients") : + { + GenericValueTypeMessage kick(ri); + ClientConnection * clientConnection = ConnectionServer::getClientConnection(kick.getValue()); + if(clientConnection) + { + ConnectionServer::dropClient(clientConnection, "TransferServer requests client drop"); + } + break; + } + case constcrc("TransferClosePseudoClientConnection") : + { + GenericValueTypeMessage closeRequest(ri); + PseudoClientConnection * pseudoClient = PseudoClientConnection::getPseudoClientConnection(closeRequest.getValue()); + delete pseudoClient; + break; + } + case constcrc("LoginDeniedRecentCTS") : + { + GenericValueTypeMessage > loginDeniedRecentCTS(ri); + ClientConnection * clientConnection = ConnectionServer::getClientConnection(loginDeniedRecentCTS.getValue().second); + if (clientConnection) + { + LOG("CustomerService", ("Login:%s, character %s (%s) is a recent CTS that has not been persisted yet.", ClientConnection::describeAccount(clientConnection).c_str(), clientConnection->getCharacterName().c_str(), clientConnection->getCharacterId().getValueString().c_str())); + ErrorMessage err("Login Failed", "The selected character has just been recently transferred and has not been completely initialized. In most cases, it takes about 15 minutes (but in some cases can take up to 2 hours) to complete initialization. Please try again later."); + clientConnection->send(err, true); + } + break; + } + case constcrc("LoginDeniedPendingPlayerRenameRequest") : + { + GenericValueTypeMessage > loginDeniedPendingPlayerRenameRequest(ri); + ClientConnection * clientConnection = ConnectionServer::getClientConnection(loginDeniedPendingPlayerRenameRequest.getValue().second); + if (clientConnection) + { + LOG("CustomerService", ("Login:%s, character %s (%s) has a pending player requested character rename request.", ClientConnection::describeAccount(clientConnection).c_str(), clientConnection->getCharacterName().c_str(), clientConnection->getCharacterId().getValueString().c_str())); + ErrorMessage err("Login Failed", "The selected character currently has a pending character rename request. It can take up to 30 minutes for the rename request to complete."); + clientConnection->send(err, true); + } + break; + } + default: + ServerConnection::onReceive(message); + break; } } //----------------------------------------------------------------------- + + diff --git a/engine/server/application/ConnectionServer/src/shared/ChatServerConnection.cpp b/engine/server/application/ConnectionServer/src/shared/ChatServerConnection.cpp index 76cdc21c..3a83d710 100755 --- a/engine/server/application/ConnectionServer/src/shared/ChatServerConnection.cpp +++ b/engine/server/application/ConnectionServer/src/shared/ChatServerConnection.cpp @@ -17,38 +17,7 @@ #include "sharedNetworkMessages/ChatOnLeaveRoom.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" -//----------------------------------------------------------------------- -/* -void putClientsInRoom(const unsigned int roomId, const std::vector & clients) -{ - std::vector::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++i) - { - - Client* client = ConnectionServer::getClient((*i)); - DEBUG_REPORT_LOG(!client, ("Error, could not map %s to a client\n", (*i).getValueString().c_str())); - if (client) - client->enterRoom(roomId); - } -} -*/ - -//----------------------------------------------------------------------- -/* -void removeClientsFromRoom(const unsigned int roomId, const std::vector & clients) -{ - std::vector::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++i) - { - - Client* client = ConnectionServer::getClient((*i)); - DEBUG_REPORT_LOG(!client, ("Error, could not map %s to a client\n", (*i).getValueString().c_str())); - if (client) - client->leaveRoom(roomId); - } -} -*/ -//----------------------------------------------------------------------- +#include "sharedFoundation/CrcConstexpr.hpp" ChatServerConnection::ChatServerConnection(UdpConnectionMT * u, TcpClient * t) : ServerConnection(u, t), @@ -104,41 +73,17 @@ void ChatServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage m(ri); ri = message.begin(); - - if (m.isType("GameClientMessage")) - { - //we're receiving a message to forward to the client. - //it is prefixed with NetworkId and reliable. - const GameClientMessage msg(ri); + + if (m.getType() == constcrc("GameClientMessage")) { + //we're receiving a message to forward to the client. + //it is prefixed with NetworkId and reliable. + + const GameClientMessage msg(ri); Archive::ReadIterator mri(msg.getByteStream()); GameNetworkMessage gnm(mri); mri = msg.getByteStream().begin(); - - // The connection server wants to trap room - // enter/leave messages to cache clients - // in particular rooms for autorecovery when - // a chat server process is stopped then later - // restarted - // - // ************ THIS CODE DOES NOT WORK *********** - // The following code has been commented out since - // everyone in the group is sent these messages but - // the logic assumes that only the person entering - // or leaving a chat room is sent the message. - /* - if(gnm.isType("ChatOnEnteredRoom")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnEnteredRoom chat(cri); - putClientsInRoom(chat.getRoomId(), msg.getDistributionList()); - } - else if(gnm.isType("ChatOnLeaveRoom")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnLeaveRoom chat(cri); - removeClientsFromRoom(chat.getRoomId(), msg.getDistributionList()); - } - */ + + const uint32 messageType = gnm.getType(); const std::vector & d = msg.getDistributionList(); std::vector::const_iterator i; @@ -167,46 +112,55 @@ void ChatServerConnection::onReceive(const Archive::ByteStream & message) DEBUG_REPORT_LOG(!client, ("Error, could not map %s to a client\n", (*i).getValueString().c_str())); if (client) { - if (!gnm.isType("ChatStatisticsCS")) + if (messageType != constcrc("ChatStatisticsCS")) { client->getClientConnection()->sendByteStream(msg.getByteStream(), msg.getReliable()); - + } + GameConnection *gc = client->getGameConnection(); + if (gc) { - if (gnm.isType("ChatOnGetFriendsList")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnGetFriendsList c(cri); - gc->send(c, true); - //DEBUG_REPORT_LOG(true, ("Sending a ChatOnGetFriendsList msg to game server\n")); - } - else if (gnm.isType("ChatOnChangeIgnoreStatus")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnChangeIgnoreStatus c(cri); - gc->send(c, true); - //DEBUG_REPORT_LOG(true, ("Sending a ChatOnChangeIgnoreStatus msg to game server\n")); - } - else if (gnm.isType("ChatOnChangeFriendStatus")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnChangeFriendStatus c(cri); - gc->send(c, true); - //DEBUG_REPORT_LOG(true, ("Sending a ChatOnChangeFriendStatus msg to game server\n")); - } - else if (gnm.isType("ChatOnGetIgnoreList")) - { - Archive::ReadIterator cri(msg.getByteStream()); - ChatOnGetIgnoreList c(cri); - gc->send(c, true); - //DEBUG_REPORT_LOG(true, ("Sending a ChatOnGetIgnoreList msg to game server\n")); - } - else if (gnm.isType("ChatStatisticsCS")) - { - Archive::ReadIterator cri(msg.getByteStream()); - GenericValueTypeMessage, std::pair > > chatStatistics(cri); - gc->send(chatStatistics, true); - //DEBUG_REPORT_LOG(true, ("Sending a ChatStatisticsCS msg to game server\n")); + switch(messageType) { + case constcrc("ChatOnGetFriendsList") : + { + Archive::ReadIterator cri(msg.getByteStream()); + ChatOnGetFriendsList c(cri); + gc->send(c, true); + //DEBUG_REPORT_LOG(true, ("Sending a ChatOnGetFriendsList msg to game server\n")); + break; + } + case constcrc("ChatOnChangeIgnoreStatus") : + { + Archive::ReadIterator cri(msg.getByteStream()); + ChatOnChangeIgnoreStatus c(cri); + gc->send(c, true); + //DEBUG_REPORT_LOG(true, ("Sending a ChatOnChangeIgnoreStatus msg to game server\n")); + break; + } + case constcrc("ChatOnChangeFriendStatus") : + { + Archive::ReadIterator cri(msg.getByteStream()); + ChatOnChangeFriendStatus c(cri); + gc->send(c, true); + //DEBUG_REPORT_LOG(true, ("Sending a ChatOnChangeFriendStatus msg to game server\n")); + break; + } + case constcrc("ChatOnGetIgnoreList") : + { + Archive::ReadIterator cri(msg.getByteStream()); + ChatOnGetIgnoreList c(cri); + gc->send(c, true); + //DEBUG_REPORT_LOG(true, ("Sending a ChatOnGetIgnoreList msg to game server\n")); + break; + } + case constcrc("ChatStatisticsCS") : + { + Archive::ReadIterator cri(msg.getByteStream()); + GenericValueTypeMessage, std::pair > > chatStatistics(cri); + gc->send(chatStatistics, true); + //DEBUG_REPORT_LOG(true, ("Sending a ChatStatisticsCS msg to game server\n")); + break; + } } } } diff --git a/engine/server/application/ConnectionServer/src/shared/Client.cpp b/engine/server/application/ConnectionServer/src/shared/Client.cpp index 5809bfde..f7dadc0c 100755 --- a/engine/server/application/ConnectionServer/src/shared/Client.cpp +++ b/engine/server/application/ConnectionServer/src/shared/Client.cpp @@ -20,6 +20,8 @@ #include "sharedNetworkMessages/DisconnectPlayerMessage.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //---------------------------------------------------------------------- Client::Client(ClientConnection * cconn, const NetworkId& oid) : @@ -157,7 +159,9 @@ void Client::leaveRoom(const unsigned int roomId) void Client::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { - if(message.isType("GameConnectionClosed")) + const uint32 messageType = message.getType(); + + if(messageType == constcrc("GameConnectionClosed")) { // Game server has crashed. With luck, we'll get transferred to a new server shortly // So, clear our connection and put us on a queue. If we don't get transferred in a @@ -166,12 +170,12 @@ void Client::receiveMessage(const MessageDispatch::Emitter & source, const Messa m_gameConnection = 0; ConnectionServer::addRecoveringClient(getNetworkId()); } - else if(message.isType("ChatServerConnectionOpened")) + else if(messageType == constcrc("ChatServerConnectionOpened")) { const ChatServerConnection & chatConnection = static_cast(source); setChatConnection(const_cast(&chatConnection)); } - else if(message.isType("CustomerServiceConnectionOpened")) + else if(messageType == constcrc("CustomerServiceConnectionOpened")) { const CustomerServiceConnection & customerServiceConnection = static_cast(source); setCustomerServiceConnection(const_cast(&customerServiceConnection)); diff --git a/engine/server/application/ConnectionServer/src/shared/ClientConnection.cpp b/engine/server/application/ConnectionServer/src/shared/ClientConnection.cpp index f7b3020b..21af7631 100755 --- a/engine/server/application/ConnectionServer/src/shared/ClientConnection.cpp +++ b/engine/server/application/ConnectionServer/src/shared/ClientConnection.cpp @@ -50,6 +50,8 @@ #include "Session/LoginAPI/Client.h" #include "UdpLibrary.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include //----------------------------------------------------------------------- @@ -82,7 +84,7 @@ m_canCreateRegularCharacter(false), m_canCreateJediCharacter(false), m_hasRequestedCharacterCreate(false), m_hasCreatedCharacter(false), -m_pendingCharacterCreate(NULL), +m_pendingCharacterCreate(nullptr), m_canSkipTutorial(false), m_characterId(NetworkId::cms_invalid), m_characterName(), @@ -144,7 +146,7 @@ ClientConnection::~ClientConnection() { hasBeenKicked = m_client->hasBeenKicked(); delete m_client; - m_client = NULL; + m_client = nullptr; } // tell Session to stop recording play time for the character @@ -177,7 +179,7 @@ ClientConnection::~ClientConnection() m_pendingChatQueryRoomRequests.clear(); delete m_pendingCharacterCreate; - m_pendingCharacterCreate = NULL; + m_pendingCharacterCreate = nullptr; } @@ -202,7 +204,7 @@ std::string ClientConnection::getPlayTimeDuration() const int playTimeDuration = 0; if (m_startPlayTime > 0) - playTimeDuration = static_cast(::time(NULL) - m_startPlayTime); + playTimeDuration = static_cast(::time(nullptr) - m_startPlayTime); return CalendarTime::convertSecondsToHMS(static_cast(playTimeDuration)); } @@ -214,7 +216,7 @@ std::string ClientConnection::getActivePlayTimeDuration() const int activePlayTimeDuration = static_cast(m_activePlayTimeDuration); if (m_lastActiveTime > 0) - activePlayTimeDuration += static_cast(::time(NULL) - m_lastActiveTime); + activePlayTimeDuration += static_cast(::time(nullptr) - m_lastActiveTime); return CalendarTime::convertSecondsToHMS(static_cast(activePlayTimeDuration)); } @@ -226,7 +228,7 @@ std::string ClientConnection::getCurrentActivePlayTimeDuration() const int activePlayTimeDuration = 0; if (m_lastActiveTime > 0) - activePlayTimeDuration = static_cast(::time(NULL) - m_lastActiveTime); + activePlayTimeDuration = static_cast(::time(nullptr) - m_lastActiveTime); return CalendarTime::convertSecondsToHMS(static_cast(activePlayTimeDuration)); } @@ -400,7 +402,7 @@ void ClientConnection::handleClientIdMessage(const ClientIdMsg& msg) std::hash h; m_suid = h(m_accountName.c_str()); } - onValidateClient(m_suid, m_accountName, m_isSecure, NULL, ConfigConnectionServer::getDefaultGameFeatures(), ConfigConnectionServer::getDefaultSubscriptionFeatures(), 0, 0, 0, 0, ConfigConnectionServer::getFakeBuddyPoints()); + onValidateClient(m_suid, m_accountName, m_isSecure, nullptr, ConfigConnectionServer::getDefaultGameFeatures(), ConfigConnectionServer::getDefaultSubscriptionFeatures(), 0, 0, 0, 0, ConfigConnectionServer::getFakeBuddyPoints()); } } else @@ -452,7 +454,7 @@ void ClientConnection::onIdValidated(bool canLogin, bool canCreateRegularCharact } delete m_pendingCharacterCreate; - m_pendingCharacterCreate = NULL; + m_pendingCharacterCreate = nullptr; return; } @@ -628,205 +630,47 @@ void ClientConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage m(ri); ri = message.begin(); + + const uint32 messageType = m.getType(); //Clients with a selected character get routed to a game server. //@todo check for filtering out bad messages. if (m_hasSelectedCharacter) { // if it is a chat message, send it directly to the chat server - if( - m.isType("ChatAddFriend") || - m.isType("ChatAddModeratorToRoom") || - m.isType("ChatBanAvatarFromRoom") || - m.isType("ChatCreateRoom") || - m.isType("ChatDeletePersistentMessage") || - m.isType("ChatDeleteAllPersistentMessages") || - m.isType("ChatDestroyRoom") || - m.isType("ChatInstantMessageToCharacter") || - m.isType("ChatInviteAvatarToRoom") || - m.isType("ChatKickAvatarFromRoom") || - m.isType("ChatRemoveAvatarFromRoom") || - m.isType("ChatRemoveFriend") || - m.isType("ChatRemoveModeratorFromRoom") || - m.isType("ChatRequestPersistentMessage") || - m.isType("ChatRequestRoomList") || - m.isType("ChatSendToRoom") || - m.isType("ChatUninviteFromRoom") || - m.isType("ChatUnbanAvatarFromRoom") || - m.isType("VerifyPlayerNameMessage") || - m.isType("VoiceChatRequestPersonalChannel") || - m.isType("VoiceChatInvite") || - m.isType("VoiceChatKick") || - m.isType("VoiceChatRequestChannelInfo") - ) - { - DEBUG_REPORT_LOG(true, ("ConnServ: ClientConnection::onReceive()\n")); - - NOT_NULL(m_client); - if(m_client) + switch(messageType) { + case constcrc("ChatAddFriend") : + case constcrc("ChatAddModeratorToRoom") : + case constcrc("ChatBanAvatarFromRoom") : + case constcrc("ChatCreateRoom") : + case constcrc("ChatDeletePersistentMessage") : + case constcrc("ChatDeleteAllPersistentMessages") : + case constcrc("ChatDestroyRoom") : + case constcrc("ChatInstantMessageToCharacter") : + case constcrc("ChatInviteAvatarToRoom") : + case constcrc("ChatKickAvatarFromRoom") : + case constcrc("ChatRemoveAvatarFromRoom") : + case constcrc("ChatRemoveFriend") : + case constcrc("ChatRemoveModeratorFromRoom") : + case constcrc("ChatRequestPersistentMessage") : + case constcrc("ChatRequestRoomList") : + case constcrc("ChatSendToRoom") : + case constcrc("ChatUninviteFromRoom") : + case constcrc("ChatUnbanAvatarFromRoom") : + case constcrc("VerifyPlayerNameMessage") : { - static std::vector v; - v.clear(); - v.push_back(m_client->getNetworkId()); - GameClientMessage gcm(v, true, ri); - if(m_client->getChatConnection()) - { - m_client->getChatConnection()->send(gcm , true); - } - else - { - // defer chat messages until a server is back online - Archive::ByteStream bs; - m.pack(bs); - m_client->deferChatMessage(bs); - } - } - else - { - ConnectionServer::dropClient(this, "m_client is null while receiving a message!"); - disconnect(); - } - } - // ChatEnterRoom and ChatEnterRoomById needs to go to the game server to determine - // if the character is not allowed to enter the room because of game rule restrictions; - // only if that test pass do we forward the message on to the chat server to request - // to enter the room - else if (m.isType("ChatEnterRoom") || - m.isType("ChatEnterRoomById") - ) - { - NOT_NULL(m_client); + DEBUG_REPORT_LOG(true, ("ConnServ: ClientConnection::onReceive()\n")); - unsigned int sequence; - std::string roomName; - - Archive::ReadIterator cri = message.begin(); - if (m.isType("ChatEnterRoom")) - { - ChatEnterRoom const cer(cri); - sequence = cer.getSequence(); - roomName = cer.getRoomName(); - } - else - { - ChatEnterRoomById const cerbi(cri); - sequence = cerbi.getSequence(); - roomName = cerbi.getRoomName(); - } - - if(m_client && m_client->getGameConnection()) - { - if (m_pendingChatEnterRoomRequests.count(sequence) == 0) - { - GenericValueTypeMessage, unsigned int> > const cervr( - "ChatEnterRoomValidationRequest", - std::make_pair( - std::make_pair(m_client->getNetworkId(), roomName), - sequence)); - - m_client->getGameConnection()->send(cervr, true); - - // queue up request until game server responds - static std::vector v; - v.clear(); - v.push_back(m_client->getNetworkId()); - m_pendingChatEnterRoomRequests[sequence] = new GameClientMessage(v, true, ri); - } - } - else - { - // send back response to client saying game server not available - - // the client only cares about sequence and result when it's a failure - ChatOnEnteredRoom fail(sequence, SWG_CHAT_ERR_NO_GAME_SERVER, 0, ChatAvatarId()); - send(fail, true); - } - } - // ChatQueryRoom needs to go to the game server to determine if the character is - // not allowed to query the room because of game rule restrictions; only if that - // test pass do we forward the message on to the chat server for completion - else if (m.isType("ChatQueryRoom")) - { - NOT_NULL(m_client); - - Archive::ReadIterator cri = message.begin(); - ChatQueryRoom cqr(cri); - - if(m_client && m_client->getGameConnection()) - { - if (m_pendingChatQueryRoomRequests.count(cqr.getSequence()) == 0) - { - GenericValueTypeMessage, unsigned int> > const cqrvr( - "ChatQueryRoomValidationRequest", - std::make_pair( - std::make_pair(m_client->getNetworkId(), cqr.getRoomName()), - cqr.getSequence())); - - m_client->getGameConnection()->send(cqrvr, true); - - // queue up request until game server responds - static std::vector v; - v.clear(); - v.push_back(m_client->getNetworkId()); - m_pendingChatQueryRoomRequests[cqr.getSequence()] = new GameClientMessage(v, true, ri); - } - } - } - // ChatInviteGroupToRoom needs to go to the game server to get group information - else if (m.isType("ChatInviteGroupToRoom")) - { - NOT_NULL(m_client); - if(m_client) - { - if (m_client->getGameConnection()) + NOT_NULL(m_client); + if(m_client) { static std::vector v; v.clear(); v.push_back(m_client->getNetworkId()); GameClientMessage gcm(v, true, ri); - m_client->getGameConnection()->send(gcm, true); - } - else - { - // defer chat messages until a server is back online - Archive::ByteStream bs; - m.pack(bs); - m_client->deferChatMessage(bs); - } - } - else - { - ConnectionServer::dropClient(this, "m_client is null while receiving a message!"); - disconnect(); - } - } - // ChatPersistentMessageToServer may need to be passed off to the game server for guild or citizens messages - else if (m.isType("ChatPersistentMessageToServer")) - { - NOT_NULL(m_client); - if(m_client) - { - static std::vector v; - v.clear(); - v.push_back(m_client->getNetworkId()); - - Archive::ReadIterator cri = message.begin(); - ChatPersistentMessageToServer chat(cri); - std::string const &toName = chat.getToCharacterName().name; - if (!_stricmp(toName.c_str(), "guild") || !_strnicmp(toName.c_str(), "guild ", 6) || !_stricmp(toName.c_str(), "citizens")) - { - if (m_client->getGameConnection()) + if(m_client->getChatConnection()) { - GameClientMessage gcm(v, true, ri); - m_client->getGameConnection()->send(gcm, true); - } - } - else - { - if (m_client->getChatConnection()) - { - GameClientMessage gcm(v, true, ri); - m_client->getChatConnection()->send(gcm, true); + m_client->getChatConnection()->send(gcm , true); } else { @@ -836,350 +680,517 @@ void ClientConnection::onReceive(const Archive::ByteStream & message) m_client->deferChatMessage(bs); } } + else + { + ConnectionServer::dropClient(this, "m_client is nullptr while receiving a message!"); + disconnect(); + } + break; } - else + // ChatEnterRoom and ChatEnterRoomById needs to go to the game server to determine + // if the character is not allowed to enter the room because of game rule restrictions; + // only if that test pass do we forward the message on to the chat server to request + // to enter the room + case constcrc("ChatEnterRoom") : + case constcrc("ChatEnterRoomById") : + { + NOT_NULL(m_client); + + unsigned int sequence; + std::string roomName; + + Archive::ReadIterator cri = message.begin(); + + if (messageType == constcrc("ChatEnterRoom")) + { + ChatEnterRoom const cer(cri); + sequence = cer.getSequence(); + roomName = cer.getRoomName(); + } + else + { + ChatEnterRoomById const cerbi(cri); + sequence = cerbi.getSequence(); + roomName = cerbi.getRoomName(); + } + + if(m_client && m_client->getGameConnection()) + { + if (m_pendingChatEnterRoomRequests.count(sequence) == 0) + { + GenericValueTypeMessage, unsigned int> > const cervr( + "ChatEnterRoomValidationRequest", + std::make_pair( + std::make_pair(m_client->getNetworkId(), roomName), + sequence)); + + m_client->getGameConnection()->send(cervr, true); + + // queue up request until game server responds + static std::vector v; + v.clear(); + v.push_back(m_client->getNetworkId()); + m_pendingChatEnterRoomRequests[sequence] = new GameClientMessage(v, true, ri); + } + } + else + { + // send back response to client saying game server not available + + // the client only cares about sequence and result when it's a failure + ChatOnEnteredRoom fail(sequence, SWG_CHAT_ERR_NO_GAME_SERVER, 0, ChatAvatarId()); + send(fail, true); + } + + break; + } + // ChatQueryRoom needs to go to the game server to determine if the character is + // not allowed to query the room because of game rule restrictions; only if that + // test pass do we forward the message on to the chat server for completion + case constcrc("ChatQueryRoom") : { - ConnectionServer::dropClient(this, "m_client is null while receiving a message!"); - disconnect(); + NOT_NULL(m_client); + + Archive::ReadIterator cri = message.begin(); + ChatQueryRoom cqr(cri); + + if(m_client && m_client->getGameConnection()) + { + if (m_pendingChatQueryRoomRequests.count(cqr.getSequence()) == 0) + { + GenericValueTypeMessage, unsigned int> > const cqrvr( + "ChatQueryRoomValidationRequest", + std::make_pair( + std::make_pair(m_client->getNetworkId(), cqr.getRoomName()), + cqr.getSequence())); + + m_client->getGameConnection()->send(cqrvr, true); + + // queue up request until game server responds + static std::vector v; + v.clear(); + v.push_back(m_client->getNetworkId()); + m_pendingChatQueryRoomRequests[cqr.getSequence()] = new GameClientMessage(v, true, ri); + } + } + break; } - } - // if it is a cs message, send it directly to the cs server - else if ( - m.isType("ConnectPlayerMessage") || - m.isType("DisconnectPlayerMessage") || - m.isType("CreateTicketMessage") || - m.isType("AppendCommentMessage") || - m.isType("CancelTicketMessage") || - m.isType("GetTicketsMessage") || - m.isType("GetCommentsMessage") || - m.isType("SearchKnowledgeBaseMessage") || - m.isType("GetArticleMessage") || - m.isType("RequestCategoriesMessage") || - m.isType("NewTicketActivityMessage") - ) - { - NOT_NULL(m_client); - if(m_client) + // ChatInviteGroupToRoom needs to go to the game server to get group information + case constcrc("ChatInviteGroupToRoom") : { - CustomerServiceConnection *customerServiceConnection = m_client->getCustomerServiceConnection(); - - //DEBUG_REPORT_LOG(true, ("CONSRV::CS - suid: %i\n", getSUID())); - - if (customerServiceConnection != NULL) + NOT_NULL(m_client); + if(m_client) + { + if (m_client->getGameConnection()) + { + static std::vector v; + v.clear(); + v.push_back(m_client->getNetworkId()); + GameClientMessage gcm(v, true, ri); + m_client->getGameConnection()->send(gcm, true); + } + else + { + // defer chat messages until a server is back online + Archive::ByteStream bs; + m.pack(bs); + m_client->deferChatMessage(bs); + } + } + else + { + ConnectionServer::dropClient(this, "m_client is nullptr while receiving a message!"); + disconnect(); + } + break; + } + // ChatPersistentMessageToServer may need to be passed off to the game server for guild or citizens messages + case constcrc("ChatPersistentMessageToServer") : + { + NOT_NULL(m_client); + if(m_client) { static std::vector v; v.clear(); v.push_back(m_client->getNetworkId()); - if (m.isType("ConnectPlayerMessage")) - { - ConnectPlayerMessage message(ri); - message.setStationId(getSUID()); - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); - } - else if (m.isType("CreateTicketMessage")) + Archive::ReadIterator cri = message.begin(); + ChatPersistentMessageToServer chat(cri); + std::string const &toName = chat.getToCharacterName().name; + if (!_stricmp(toName.c_str(), "guild") || !_strnicmp(toName.c_str(), "guild ", 6) || !_stricmp(toName.c_str(), "citizens")) { - CreateTicketMessage message(ri); - message.setStationId(getSUID()); - - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); - } - else if (m.isType("AppendCommentMessage")) - { - AppendCommentMessage message(ri); - message.setStationId(getSUID()); - - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); - } - else if (m.isType("CancelTicketMessage")) - { - CancelTicketMessage message(ri); - message.setStationId(getSUID()); - - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); - } - else if (m.isType("GetTicketsMessage")) - { - GetTicketsMessage message(ri); - message.setStationId(getSUID()); - - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); - } - else if (m.isType("NewTicketActivityMessage")) - { - NewTicketActivityMessage message(ri); - message.setStationId(getSUID()); - - GameClientMessage gcm(v, true, message); - customerServiceConnection->send(gcm , true); + if (m_client->getGameConnection()) + { + GameClientMessage gcm(v, true, ri); + m_client->getGameConnection()->send(gcm, true); + } } else { - GameClientMessage gcm(v, true, ri); - customerServiceConnection->send(gcm , true); - } - //else - //{ - // /*// defer chat messages until a server is back online - // Archive::ByteStream bs; - // m.pack(bs); - // m_client->deferChatMessage(bs); - // */ - //} - } - } - else - { - ConnectionServer::dropClient(this, "m_client is null while receiving a message!"); - disconnect(); - } - } - else if (m.isType("28afefcc187a11dc888b001")) // obfuscation for ClientInactivityMessage message - { - GenericValueTypeMessage msg(ri); - - if (m_hasBeenValidated && m_sessionValidated) - { - // client went inactive - if (msg.getValue()) - { - if (m_lastActiveTime > 0) - { - // record the amount of active time - m_activePlayTimeDuration += static_cast(::time(NULL) - m_lastActiveTime); - - // tell Session to stop recording play time for the character - if (ConnectionServer::getSessionApiClient() && ConfigConnectionServer::getSessionRecordPlayTime()) + if (m_client->getChatConnection()) { - LOG("CustomerService", ("Login:%s calling SessionStopPlay() for %s/%s/%s (%s). Active play time: %s", ClientConnection::describeAccount(this).c_str(), this->getSessionId().c_str(), ConfigConnectionServer::getClusterName(), this->getCharacterName().c_str(), this->getCharacterId().getValueString().c_str(), this->getCurrentActivePlayTimeDuration().c_str())); - ConnectionServer::getSessionApiClient()->stopPlay(*this); + GameClientMessage gcm(v, true, ri); + m_client->getChatConnection()->send(gcm, true); } - - // client is no longer active; this needs to be set after the LOG() statement - // above because getCurrentActivePlayTimeDuration() uses m_lastActiveTime - m_lastActiveTime = 0; - - // update the play time info on the game server - sendPlayTimeInfoToGameServer(); - - // drop inactive character - if (ConfigConnectionServer::getDisconnectOnInactive()) + else { - LOG("ClientDisconnect", ("Disconnecting %u because the player was inactive for too long.",getSUID())); - ConnectionServer::dropClient(this, "Client inactivity"); - disconnect(); - } - else if (ConfigConnectionServer::getDisconnectFreeTrialOnInactive() && ((m_featureBitsSubscription & ClientSubscriptionFeature::Base) == 0)) - { - LOG("ClientDisconnect", ("Disconnecting (free trial) %u because the player was inactive for too long.",getSUID())); - ConnectionServer::dropClient(this, "Client inactivity (free trial)"); - disconnect(); + // defer chat messages until a server is back online + Archive::ByteStream bs; + m.pack(bs); + m_client->deferChatMessage(bs); } } } - // client went active else { - if (m_lastActiveTime == 0) + ConnectionServer::dropClient(this, "m_client is nullptr while receiving a message!"); + disconnect(); + } + break; + } + // if it is a cs message, send it directly to the cs server + case constcrc("ConnectPlayerMessage") : + case constcrc("DisconnectPlayerMessage") : + case constcrc("CreateTicketMessage") : + case constcrc("AppendCommentMessage") : + case constcrc("CancelTicketMessage") : + case constcrc("GetTicketsMessage") : + case constcrc("GetCommentsMessage") : + case constcrc("SearchKnowledgeBaseMessage") : + case constcrc("GetArticleMessage") : + case constcrc("RequestCategoriesMessage") : + case constcrc("NewTicketActivityMessage") : + { + NOT_NULL(m_client); + if(m_client) + { + CustomerServiceConnection *customerServiceConnection = m_client->getCustomerServiceConnection(); + + //DEBUG_REPORT_LOG(true, ("CONSRV::CS - suid: %i\n", getSUID())); + + if (customerServiceConnection != nullptr) { - // record the time client went active - m_lastActiveTime = ::time(NULL); + static std::vector v; + v.clear(); + v.push_back(m_client->getNetworkId()); - // tell Session to start recording play time for the character - if (ConnectionServer::getSessionApiClient() && ConfigConnectionServer::getSessionRecordPlayTime()) - { - LOG("CustomerService", ("Login:%s calling SessionStartPlay() for %s/%s/%s (%s)", ClientConnection::describeAccount(this).c_str(), this->getSessionId().c_str(), ConfigConnectionServer::getClusterName(), this->getCharacterName().c_str(), this->getCharacterId().getValueString().c_str())); - ConnectionServer::getSessionApiClient()->startPlay(*this); + // TODO: this shit could be made into a template + switch (messageType) { + case constcrc("ConnectPlayerMessage") : { + ConnectPlayerMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + case constcrc("CreateTicketMessage") : { + CreateTicketMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + case constcrc("AppendCommentMessage") : { + AppendCommentMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + case constcrc("CancelTicketMessage") : { + CancelTicketMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + case constcrc("GetTicketsMessage") : { + GetTicketsMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + case constcrc("NewTicketActivityMessage") : { + NewTicketActivityMessage message(ri); + message.setStationId(getSUID()); + + GameClientMessage gcm(v, true, message); + customerServiceConnection->send(gcm , true); + break; + } + default : { + GameClientMessage gcm(v, true, ri); + customerServiceConnection->send(gcm , true); + break; + } } - - // update the play time info on the game server - sendPlayTimeInfoToGameServer(); } } - } - } - else - { - //Forward on to Game Server - DEBUG_REPORT_LOG((!m_client || !m_client->getGameConnection()), ("Warn, received game message with no game connection. This may happen for a short time after a GameServer crashes. If it continues to happen, it indicates a bug.\n")); - - if (m_client && m_client->getGameConnection()) - { - static std::vector v; - v.clear(); - v.push_back(m_client->getNetworkId()); - GameClientMessage gcm(v, true, ri); - m_client->getGameConnection()->send(gcm, true); - } - } - } - - else if(m.isType("ClientIdMsg")) - { - DEBUG_REPORT_LOG(true,("Recieved ClientIdMsg\n")); - ClientIdMsg k(ri); - - handleClientIdMessage(k); - } - else if(m.isType("SelectCharacter")) - { - SelectCharacter s(ri); - DEBUG_REPORT_LOG(true,("Recvd SelectCharacter message for %s.\n", s.getId().getValueString().c_str())); - - handleSelectCharacterMessage(s); - } - else if(m.isType("ClientCreateCharacter")) - { - if (m_hasBeenValidated && !m_hasSelectedCharacter) //lint !e774 no this doesn't always eval to true - { - ClientCreateCharacter clientCreate(ri); - DEBUG_REPORT_LOG(true,("Got ClientCreateCharacter message for %lu with name %s\n", m_suid, Unicode::wideToNarrow(clientCreate.getCharacterName()).c_str())); - LOG("TraceCharacterCreation", ("%d sent ClientCreateCharacter(charaterName=%s, templateName=%s, scaleFactor=%f, startingLocation=%s, hairTemplateName=%s, profession=%s, jedi=%d, useNewbieTutorial=%d, skillTemplate=%s, workingSkill=%s)", - getSUID(), - Unicode::wideToNarrow(clientCreate.getCharacterName()).c_str(), - clientCreate.getTemplateName().c_str(), - clientCreate.getScaleFactor(), - clientCreate.getStartingLocation().c_str(), - clientCreate.getHairTemplateName().c_str(), - clientCreate.getProfession().c_str(), - static_cast(clientCreate.getJedi()), - static_cast(clientCreate.getUseNewbieTutorial()), - clientCreate.getSkillTemplate().c_str(), - clientCreate.getWorkingSkill().c_str())); - - if (!clientCreate.getUseNewbieTutorial() && !m_canSkipTutorial) - { - LOG("TraceCharacterCreation", ("%d failed character creation. The client is not allowed to skip the tutorial", getSUID())); - // This is probably a hack attempt, because the Client was already told they couldn't skip the tutorial - LOG("ClientDisconnect", ("Disconnecting %u because they tried to skip the tutorial without permission.\n",getSUID())); - disconnect(); - } - else if (clientCreate.getJedi() && !m_canCreateJediCharacter) - { - LOG("TraceCharacterCreation", ("%d failed character creation. The request character type was Jedi, but this client cannot create a Jedi character", getSUID())); - // This is probably a hack attempt, because the Client was already told they couldn't create a character - LOG("ClientDisconnect", ("Disconnecting %u because they tried to create a Jedi character without permission.\n",getSUID())); - disconnect(); - } - else if (!clientCreate.getJedi() && !m_canCreateRegularCharacter) - { - LOG("TraceCharacterCreation", ("%d failed character creation. The client is not allowed to create any characters", getSUID())); - // This is probably a hack attempt, because the Client was already told they couldn't create a character - LOG("ClientDisconnect", ("Disconnecting %u because they tried to create a regular character without permission.\n",getSUID())); - disconnect(); - } - else if (m_hasRequestedCharacterCreate) - { - LOG("TraceCharacterCreation", ("%d failed character creation. The client has already requested character creation on this connection", getSUID())); - LOG("ClientDisconnect", ("Disconnecting %u because the client has already requested character creation on this connection.\n",getSUID())); - disconnect(); - } - else if (m_hasCreatedCharacter) - { - LOG("TraceCharacterCreation", ("%d failed character creation. A character has been created on this or another galaxy for this account while this connection was up", getSUID())); - LOG("ClientDisconnect", ("Disconnecting %u because a character has been created on this or another galaxy for this account while this connection was up.\n",getSUID())); - disconnect(); - } - else if (clientCreate.getCharacterName().length()==0) - { - LOG("TraceCharacterCreation", ("%d failed character creation. The character's name is empty", getSUID())); - LOG("ClientDisconnect",("Disconnecting %u because they tried to create a character with no name.\n",getSUID())); - disconnect(); - } - else - { - Unicode::String biography(clientCreate.getBiography()); - if (biography.length() > 1024) + else { - IGNORE_RETURN( biography.erase(1024) ); - DEBUG_REPORT_LOG(true,("Biography shortened to 1024 characters.\n")); + ConnectionServer::dropClient(this, "m_client is nullptr while receiving a message!"); + disconnect(); + } + break; + } + case constcrc("28afefcc187a11dc888b001") : // obfuscation for ClientInactivityMessage message + { + GenericValueTypeMessage msg(ri); + + if (m_hasBeenValidated && m_sessionValidated) + { + // client went inactive + if (msg.getValue()) + { + if (m_lastActiveTime > 0) + { + // record the amount of active time + m_activePlayTimeDuration += static_cast(::time(nullptr) - m_lastActiveTime); + + // tell Session to stop recording play time for the character + if (ConnectionServer::getSessionApiClient() && ConfigConnectionServer::getSessionRecordPlayTime()) + { + LOG("CustomerService", ("Login:%s calling SessionStopPlay() for %s/%s/%s (%s). Active play time: %s", ClientConnection::describeAccount(this).c_str(), this->getSessionId().c_str(), ConfigConnectionServer::getClusterName(), this->getCharacterName().c_str(), this->getCharacterId().getValueString().c_str(), this->getCurrentActivePlayTimeDuration().c_str())); + ConnectionServer::getSessionApiClient()->stopPlay(*this); + } + + // client is no longer active; this needs to be set after the LOG() statement + // above because getCurrentActivePlayTimeDuration() uses m_lastActiveTime + m_lastActiveTime = 0; + + // update the play time info on the game server + sendPlayTimeInfoToGameServer(); + + // drop inactive character + if (ConfigConnectionServer::getDisconnectOnInactive()) + { + LOG("ClientDisconnect", ("Disconnecting %u because the player was inactive for too long.",getSUID())); + ConnectionServer::dropClient(this, "Client inactivity"); + disconnect(); + } + else if (ConfigConnectionServer::getDisconnectFreeTrialOnInactive() && ((m_featureBitsSubscription & ClientSubscriptionFeature::Base) == 0)) + { + LOG("ClientDisconnect", ("Disconnecting (free trial) %u because the player was inactive for too long.",getSUID())); + ConnectionServer::dropClient(this, "Client inactivity (free trial)"); + disconnect(); + } + } + } + // client went active + else + { + if (m_lastActiveTime == 0) + { + // record the time client went active + m_lastActiveTime = ::time(nullptr); + + // tell Session to start recording play time for the character + if (ConnectionServer::getSessionApiClient() && ConfigConnectionServer::getSessionRecordPlayTime()) + { + LOG("CustomerService", ("Login:%s calling SessionStartPlay() for %s/%s/%s (%s)", ClientConnection::describeAccount(this).c_str(), this->getSessionId().c_str(), ConfigConnectionServer::getClusterName(), this->getCharacterName().c_str(), this->getCharacterId().getValueString().c_str())); + ConnectionServer::getSessionApiClient()->startPlay(*this); + } + + // update the play time info on the game server + sendPlayTimeInfoToGameServer(); + } + } + } + break; + } + default : + { + //Forward on to Game Server + DEBUG_REPORT_LOG((!m_client || !m_client->getGameConnection()), ("Warn, received game message with no game connection. This may happen for a short time after a GameServer crashes. If it continues to happen, it indicates a bug.\n")); + + if (m_client && m_client->getGameConnection()) + { + static std::vector v; + v.clear(); + v.push_back(m_client->getNetworkId()); + GameClientMessage gcm(v, true, ri); + m_client->getGameConnection()->send(gcm, true); } - if (m_isAdminAccount) - { - ConnectionCreateCharacter connectionCreate( - m_suid, - clientCreate.getCharacterName(), - clientCreate.getTemplateName(), - clientCreate.getScaleFactor(), - clientCreate.getStartingLocation(), - clientCreate.getAppearanceData(), - clientCreate.getHairTemplateName(), - clientCreate.getHairAppearanceData(), - clientCreate.getProfession(), - clientCreate.getJedi(), - biography, - clientCreate.getUseNewbieTutorial(), - clientCreate.getSkillTemplate(), - clientCreate.getWorkingSkill(), - m_isAdminAccount, - false, - m_featureBitsGame); - - ConnectionServer::sendToCentralProcess(connectionCreate); - LOG("TraceCharacterCreation", ("%d character creation request sent to CentralServer", getSUID())); - } - else - { - // for regular players, do one final check with the LoginServer - // to make sure the character can be created (i.e. that character - // limits have not been exceeded) - delete m_pendingCharacterCreate; - m_pendingCharacterCreate = new ConnectionCreateCharacter( - m_suid, - clientCreate.getCharacterName(), - clientCreate.getTemplateName(), - clientCreate.getScaleFactor(), - clientCreate.getStartingLocation(), - clientCreate.getAppearanceData(), - clientCreate.getHairTemplateName(), - clientCreate.getHairAppearanceData(), - clientCreate.getProfession(), - clientCreate.getJedi(), - biography, - clientCreate.getUseNewbieTutorial(), - clientCreate.getSkillTemplate(), - clientCreate.getWorkingSkill(), - m_isAdminAccount, - false, - m_featureBitsGame); - - LOG("TraceCharacterCreation", ("%d character creation request awaiting final verification from LoginServer", getSUID())); - - ValidateAccountMessage vcm(m_suid, 0, m_featureBitsSubscription); - ConnectionServer::sendToCentralProcess(vcm); - } - - m_hasRequestedCharacterCreate = true; + break; } } - } - else if(m.isType("ClientRandomNameRequest")) - { - ClientRandomNameRequest clientRandomName(ri); + } else { + switch (messageType) { + case constcrc("ClientIdMsg") : + { + DEBUG_REPORT_LOG(true,("Recieved ClientIdMsg\n")); + ClientIdMsg k(ri); - RandomNameRequest randomNameRequest(m_suid, clientRandomName.getCreatureTemplate()); - ConnectionServer::sendToCentralProcess(randomNameRequest); - LOG("TraceCharacterCreation", ("%d requested a random name. Request sent to CentralServer", getSUID())); - } - else if(m.isType("ClientVerifyAndLockNameRequest")) - { - ClientVerifyAndLockNameRequest clientVerifyAndLockNameRequest(ri); + handleClientIdMessage(k); + break; + } + case constcrc("SelectCharacter") : + { + SelectCharacter s(ri); + DEBUG_REPORT_LOG(true,("Recvd SelectCharacter message for %s.\n", s.getId().getValueString().c_str())); - VerifyAndLockNameRequest verifyAndLockNameRequest(m_suid, NetworkId::cms_invalid, clientVerifyAndLockNameRequest.getTemplateName(), clientVerifyAndLockNameRequest.getCharacterName(), m_featureBitsGame); - ConnectionServer::sendToCentralProcess(verifyAndLockNameRequest); - LOG("TraceCharacterCreation", ("%d requested a verify and lock of name: %s. Request sent to CentralServer", getSUID(), Unicode::wideToNarrow(verifyAndLockNameRequest.getCharacterName()).c_str())); - } - else if(m.isType("LagRequest")) - { - /* - handleLagRequest(); - */ + handleSelectCharacterMessage(s); + break; + } + case constcrc("ClientCreateCharacter") : + { + if (m_hasBeenValidated && !m_hasSelectedCharacter) //lint !e774 no this doesn't always eval to true + { + ClientCreateCharacter clientCreate(ri); + DEBUG_REPORT_LOG(true,("Got ClientCreateCharacter message for %lu with name %s\n", m_suid, Unicode::wideToNarrow(clientCreate.getCharacterName()).c_str())); + LOG("TraceCharacterCreation", ("%d sent ClientCreateCharacter(charaterName=%s, templateName=%s, scaleFactor=%f, startingLocation=%s, hairTemplateName=%s, profession=%s, jedi=%d, useNewbieTutorial=%d, skillTemplate=%s, workingSkill=%s)", + getSUID(), + Unicode::wideToNarrow(clientCreate.getCharacterName()).c_str(), + clientCreate.getTemplateName().c_str(), + clientCreate.getScaleFactor(), + clientCreate.getStartingLocation().c_str(), + clientCreate.getHairTemplateName().c_str(), + clientCreate.getProfession().c_str(), + static_cast(clientCreate.getJedi()), + static_cast(clientCreate.getUseNewbieTutorial()), + clientCreate.getSkillTemplate().c_str(), + clientCreate.getWorkingSkill().c_str())); + + if (!clientCreate.getUseNewbieTutorial() && !m_canSkipTutorial) + { + LOG("TraceCharacterCreation", ("%d failed character creation. The client is not allowed to skip the tutorial", getSUID())); + // This is probably a hack attempt, because the Client was already told they couldn't skip the tutorial + LOG("ClientDisconnect", ("Disconnecting %u because they tried to skip the tutorial without permission.\n",getSUID())); + disconnect(); + } + else if (clientCreate.getJedi() && !m_canCreateJediCharacter) + { + LOG("TraceCharacterCreation", ("%d failed character creation. The request character type was Jedi, but this client cannot create a Jedi character", getSUID())); + // This is probably a hack attempt, because the Client was already told they couldn't create a character + LOG("ClientDisconnect", ("Disconnecting %u because they tried to create a Jedi character without permission.\n",getSUID())); + disconnect(); + } + else if (!clientCreate.getJedi() && !m_canCreateRegularCharacter) + { + LOG("TraceCharacterCreation", ("%d failed character creation. The client is not allowed to create any characters", getSUID())); + // This is probably a hack attempt, because the Client was already told they couldn't create a character + LOG("ClientDisconnect", ("Disconnecting %u because they tried to create a regular character without permission.\n",getSUID())); + disconnect(); + } + else if (m_hasRequestedCharacterCreate) + { + LOG("TraceCharacterCreation", ("%d failed character creation. The client has already requested character creation on this connection", getSUID())); + LOG("ClientDisconnect", ("Disconnecting %u because the client has already requested character creation on this connection.\n",getSUID())); + disconnect(); + } + else if (m_hasCreatedCharacter) + { + LOG("TraceCharacterCreation", ("%d failed character creation. A character has been created on this or another galaxy for this account while this connection was up", getSUID())); + LOG("ClientDisconnect", ("Disconnecting %u because a character has been created on this or another galaxy for this account while this connection was up.\n",getSUID())); + disconnect(); + } + else if (clientCreate.getCharacterName().length()==0) + { + LOG("TraceCharacterCreation", ("%d failed character creation. The character's name is empty", getSUID())); + LOG("ClientDisconnect",("Disconnecting %u because they tried to create a character with no name.\n",getSUID())); + disconnect(); + } + else + { + Unicode::String biography(clientCreate.getBiography()); + if (biography.length() > 1024) + { + IGNORE_RETURN( biography.erase(1024) ); + DEBUG_REPORT_LOG(true,("Biography shortened to 1024 characters.\n")); + } + + if (m_isAdminAccount) + { + ConnectionCreateCharacter connectionCreate( + m_suid, + clientCreate.getCharacterName(), + clientCreate.getTemplateName(), + clientCreate.getScaleFactor(), + clientCreate.getStartingLocation(), + clientCreate.getAppearanceData(), + clientCreate.getHairTemplateName(), + clientCreate.getHairAppearanceData(), + clientCreate.getProfession(), + clientCreate.getJedi(), + biography, + clientCreate.getUseNewbieTutorial(), + clientCreate.getSkillTemplate(), + clientCreate.getWorkingSkill(), + m_isAdminAccount, + false, + m_featureBitsGame); + + ConnectionServer::sendToCentralProcess(connectionCreate); + LOG("TraceCharacterCreation", ("%d character creation request sent to CentralServer", getSUID())); + } + else + { + // for regular players, do one final check with the LoginServer + // to make sure the character can be created (i.e. that character + // limits have not been exceeded) + delete m_pendingCharacterCreate; + m_pendingCharacterCreate = new ConnectionCreateCharacter( + m_suid, + clientCreate.getCharacterName(), + clientCreate.getTemplateName(), + clientCreate.getScaleFactor(), + clientCreate.getStartingLocation(), + clientCreate.getAppearanceData(), + clientCreate.getHairTemplateName(), + clientCreate.getHairAppearanceData(), + clientCreate.getProfession(), + clientCreate.getJedi(), + biography, + clientCreate.getUseNewbieTutorial(), + clientCreate.getSkillTemplate(), + clientCreate.getWorkingSkill(), + m_isAdminAccount, + false, + m_featureBitsGame); + + LOG("TraceCharacterCreation", ("%d character creation request awaiting final verification from LoginServer", getSUID())); + + ValidateAccountMessage vcm(m_suid, 0, m_featureBitsSubscription); + ConnectionServer::sendToCentralProcess(vcm); + } + + m_hasRequestedCharacterCreate = true; + } + } + break; + } + case constcrc("ClientRandomNameRequest") : + { + ClientRandomNameRequest clientRandomName(ri); + + RandomNameRequest randomNameRequest(m_suid, clientRandomName.getCreatureTemplate()); + ConnectionServer::sendToCentralProcess(randomNameRequest); + LOG("TraceCharacterCreation", ("%d requested a random name. Request sent to CentralServer", getSUID())); + break; + } + case constcrc("ClientVerifyAndLockNameRequest") : + { + ClientVerifyAndLockNameRequest clientVerifyAndLockNameRequest(ri); + + VerifyAndLockNameRequest verifyAndLockNameRequest(m_suid, NetworkId::cms_invalid, clientVerifyAndLockNameRequest.getTemplateName(), clientVerifyAndLockNameRequest.getCharacterName(), m_featureBitsGame); + ConnectionServer::sendToCentralProcess(verifyAndLockNameRequest); + LOG("TraceCharacterCreation", ("%d requested a verify and lock of name: %s. Request sent to CentralServer", getSUID(), Unicode::wideToNarrow(verifyAndLockNameRequest.getCharacterName()).c_str())); + break; + } + case constcrc("LagRequest") : + { + // TODO: why is this commented out? + // handleLagRequest(); + break; + } + } } } catch(const Archive::ReadException & readException) @@ -1413,7 +1424,6 @@ void ClientConnection::onCharacterValidated(bool isValid, const NetworkId &chara if (isValid) { - LOG("TraceCharacterSelection", ("%d received a validation response. The character (%s: %s) at (%s,%f,%f,%f,%s) selected is valid", getSUID(), character.getValueString().c_str(), characterName.c_str(), scene.c_str(), coordinates.x, coordinates.y, coordinates.z, container.getValueString().c_str())); LOG("CustomerService", ("Login:%s received a validation response. The character (%s: %s) at (%s,%f,%f,%f,%s) selected is valid", describeAccount(this).c_str(), character.getValueString().c_str(), characterName.c_str(), scene.c_str(), coordinates.x, coordinates.y, coordinates.z, container.getValueString().c_str())); m_targetScene = scene; @@ -1424,33 +1434,6 @@ void ClientConnection::onCharacterValidated(bool isValid, const NetworkId &chara m_hasSelectedCharacter = true; - - - // If they don't have access to mustafar but are on the planet, move them to a safe spot - uint32 features = getGameFeatures(); - if ( (strncmp(scene.c_str(), "mustafar", strlen("mustafar")) == 0 ) && - ( (features & ClientGameFeature::TrialsOfObiwanRetail) == 0 ) ) - { - // mos eisley starport - m_sendToStarport = true; - m_targetScene = "tatooine"; - m_targetCoordinates.x = 3528; - m_targetCoordinates.y = 4; - m_targetCoordinates.z = -4804; - - // Make sure Central knows the right sceneId for the player - GenericValueTypeMessage > > const msg( - "SetSceneForPlayer", - std::make_pair( - m_characterId, - std::make_pair("tatooine", false))); - ConnectionServer::sendToCentralProcess(msg); - - - LOG("TraceCharacterSelection", ("Character didn't have Mustafar feature bit, moving to Tattoine.")); - } - - // ask CentralServer to suggest a game server for this character // (Central will forward the request to a Planet Server) @@ -1582,10 +1565,6 @@ void ClientConnection::onValidateClient (uint32 suid, const std::string & userna m_featureBitsGame &= ~ClientGameFeature::HousePackupReward; m_featureBitsGame &= ~ClientGameFeature::BuddyProgramReward; } - - //hack to prevent non-jtl users from using jtl assets. In this hack, clients who didn't patch through jtl patcher will send us information requesting we clear their jtl bit since they are supposed to go through the jtl patcher. We can remove this hack once the launch pad takes care of this for us. - m_featureBitsGame &= ~m_gameBitsToClear; - //end hack ValidateAccountMessage vcm(m_suid, 0, m_featureBitsSubscription); ConnectionServer::sendToCentralProcess(vcm); @@ -1616,7 +1595,7 @@ void ClientConnection::onValidateClient (uint32 suid, const std::string & userna } // tell client the server-side game and subscription feature bits and which ConnectionServer we are and the current server Epoch time - GenericValueTypeMessage, std::pair > > const msgFeatureBits("AccountFeatureBits", std::make_pair(std::make_pair(gameFeatures, subscriptionFeatures), std::make_pair(ConfigConnectionServer::getConnectionServerNumber(), static_cast(::time(NULL))))); + GenericValueTypeMessage, std::pair > > const msgFeatureBits("AccountFeatureBits", std::make_pair(std::make_pair(gameFeatures, subscriptionFeatures), std::make_pair(ConfigConnectionServer::getConnectionServerNumber(), static_cast(::time(nullptr))))); send(msgFeatureBits, true); std::string const gameFeaturesDescription = ClientGameFeature::getDescription(gameFeatures); diff --git a/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.cpp b/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.cpp index f98eee21..b06dbe14 100755 --- a/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.cpp +++ b/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.cpp @@ -88,6 +88,7 @@ void ConfigConnectionServer::install(void) KEY_INT (lagReportThreshold, 10000); KEY_INT (defaultGameFeatures, 0xFFFFFFFF); KEY_INT (defaultSubscriptionFeatures, 0xFFFFFFFF); + KEY_INT (maxConnectionsPerIP, 6); KEY_BOOL (validateStationKey, false); KEY_STRING (sessionServers, ""); @@ -113,6 +114,8 @@ void ConfigConnectionServer::install(void) KEY_INT (connectionServerNumber, 0); KEY_INT (fakeBuddyPoints, 0); + KEY_STRING (altPublicBindAddress, ""); + int index = 0; char const * result = 0; do @@ -163,4 +166,11 @@ int ConfigConnectionServer::getFakeBuddyPoints() return data->fakeBuddyPoints; } +// ---------------------------------------------------------------------- + +const char * ConfigConnectionServer::getPublicBindAddress() +{ + return data->altPublicBindAddress; +} + // ====================================================================== diff --git a/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.h b/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.h index 46f67d1e..6f1ce686 100755 --- a/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.h +++ b/engine/server/application/ConnectionServer/src/shared/ConfigConnectionServer.h @@ -42,6 +42,7 @@ public: int clientMaxDataHoldTime; int clientHashTableSize; int lagReportThreshold; + int maxConnectionsPerIP; bool validateStationKey; const char * sessionServers; @@ -68,6 +69,9 @@ public: int connectionServerNumber; int fakeBuddyPoints; + + + const char * altPublicBindAddress; }; @@ -133,6 +137,9 @@ public: static int getConnectionServerNumber(); static int getFakeBuddyPoints(); + static const char * getPublicBindAddress(); + + static int getMaxConnectionsPerIP(); private: static Data * data; }; @@ -462,4 +469,10 @@ inline int ConfigConnectionServer::getConnectionServerNumber() return data->connectionServerNumber; } + +inline int ConfigConnectionServer::getMaxConnectionsPerIP() +{ + return data->maxConnectionsPerIP; +} + #endif // _ConfigConnectionServer_H diff --git a/engine/server/application/ConnectionServer/src/shared/ConnectionServer.cpp b/engine/server/application/ConnectionServer/src/shared/ConnectionServer.cpp index b698ecb6..0ca253d3 100755 --- a/engine/server/application/ConnectionServer/src/shared/ConnectionServer.cpp +++ b/engine/server/application/ConnectionServer/src/shared/ConnectionServer.cpp @@ -1,8 +1,6 @@ - // ConnectionServer.cpp // copyright 2001 Verant Interactive - //----------------------------------------------------------------------- #include "FirstConnectionServer.h" @@ -56,13 +54,15 @@ #include "sharedUtility/DataTableManager.h" #include +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== namespace ConnectionServerNamespace { - ConnectionServer * s_connectionServer = 0; + ConnectionServer * s_connectionServer = 0; NetworkSetupData * s_clientServiceSetup = 0; - const std::string SCENE_NAME_TUTORIAL = "tutorial"; + const std::string SCENE_NAME_TUTORIAL = "tutorial"; const std::string SCENE_NAME_FALCON_PREFIX = "space_npe_falcon"; }; @@ -78,53 +78,53 @@ ConnectionServer & ConnectionServer::instance() //----------------------------------------------------------------------- ConnectionServer::ConnectionServer() : -MessageDispatch::Receiver(), -chatService(0), -customerService(0), -clientServicePrivate(0), -clientServicePublic(0), -gameService(0), -loginServerKeys(0), -done(false), -m_id(0), -m_metricsData(0), -centralConnection(0), -chatServers(), -customerServiceServers(), -clientMap(), -connectedMap(), -gameServerMap(), -freeTrials(), -networkBarrier(0), -pingSocket (new UdpSock), -m_recoverTime(0), -m_sessionApiClient(0), -m_pingTrafficNumBytes(0), -m_recoveringClientList() + MessageDispatch::Receiver(), + chatService(0), + customerService(0), + clientServicePrivate(0), + clientServicePublic(0), + gameService(0), + loginServerKeys(0), + done(false), + m_id(0), + m_metricsData(0), + centralConnection(0), + chatServers(), + customerServiceServers(), + clientMap(), + connectedMap(), + gameServerMap(), + freeTrials(), + networkBarrier(0), + pingSocket(new UdpSock), + m_recoverTime(0), + m_sessionApiClient(0), + m_pingTrafficNumBytes(0), + m_recoveringClientList() { - if(s_clientServiceSetup == 0) + if (s_clientServiceSetup == 0) s_clientServiceSetup = new NetworkSetupData; - + s_clientServiceSetup->maxOutstandingPackets = ConfigConnectionServer::getClientMaxOutstandingPackets(); s_clientServiceSetup->maxRawPacketSize = ConfigConnectionServer::getClientMaxRawPacketSize(); s_clientServiceSetup->maxConnections = ConfigConnectionServer::getClientMaxConnections(); s_clientServiceSetup->fragmentSize = ConfigConnectionServer::getClientFragmentSize(); s_clientServiceSetup->maxDataHoldTime = ConfigConnectionServer::getClientMaxDataHoldTime(); - s_clientServiceSetup->hashTableSize=ConfigConnectionServer::getClientHashTableSize(); + s_clientServiceSetup->hashTableSize = ConfigConnectionServer::getClientHashTableSize(); s_clientServiceSetup->port = ConfigConnectionServer::getClientServicePortPublic(); + s_clientServiceSetup->maxConnectionsPerIP = ConfigConnectionServer::getMaxConnectionsPerIP(); s_clientServiceSetup->compress = ConfigConnectionServer::getCompressClientNetworkTraffic(); s_clientServiceSetup->useTcp = false; loginServerKeys = new KeyServer(20); Address a("", ConfigConnectionServer::getPingPort()); - IGNORE_RETURN(pingSocket->bind (a)); + IGNORE_RETURN(pingSocket->bind(a)); if (ConfigConnectionServer::getValidateStationKey()) { installSessionValidation(); } - } //----------------------------------------------------------------------- @@ -137,7 +137,7 @@ ConnectionServer::~ConnectionServer() delete loginServerKeys; loginServerKeys = 0; - centralConnection=0; + centralConnection = 0; chatServers.clear(); @@ -157,13 +157,13 @@ ConnectionServer::~ConnectionServer() //----------------------------------------------------------------------- -const CustomerServiceConnection * ConnectionServer::getCustomerServiceConnection () +const CustomerServiceConnection * ConnectionServer::getCustomerServiceConnection() { - if(! instance().customerServiceServers.empty()) + if (!instance().customerServiceServers.empty()) { return (*(instance().customerServiceServers.begin())); } - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -180,10 +180,10 @@ void ConnectionServer::addGameConnection(unsigned long gameServerId, GameConnect cs.gameServerMap[gameServerId] = gc;//@todo check for dupe // find characters pending for THIS gameserver SuidMap::iterator i; - for(i = cs.connectedMap.begin(); i != cs.connectedMap.end(); ++i) + for (i = cs.connectedMap.begin(); i != cs.connectedMap.end(); ++i) { ClientConnection * c = (*i).second; - if(!c->getHasBeenSentToGameServer()) + if (!c->getHasBeenSentToGameServer()) IGNORE_RETURN(c->sendToGameServer()); } } @@ -199,16 +199,15 @@ bool ConnectionServer::decryptToken(const KeyShare::Token & token, uint32 & stat unsigned char * keyBuffer = new unsigned char[len]; unsigned char * keyBufferPointer = keyBuffer; memset(keyBuffer, 0, len); - - - bool retval = cs.loginServerKeys->decipherToken(token, keyBuffer, len); - if (! retval) + bool retval = cs.loginServerKeys->decipherToken(token, keyBuffer, len); + + if (!retval) return retval; char *tmpBuffer = new char[MAX_ACCOUNT_NAME_LENGTH + 1]; memset(tmpBuffer, 0, MAX_ACCOUNT_NAME_LENGTH + 1); - + memcpy(&stationUserId, keyBufferPointer, sizeof(uint32)); keyBufferPointer += sizeof(uint32); memcpy(&secure, keyBufferPointer, sizeof(bool)); @@ -216,33 +215,31 @@ bool ConnectionServer::decryptToken(const KeyShare::Token & token, uint32 & stat memcpy(tmpBuffer, keyBufferPointer, MAX_ACCOUNT_NAME_LENGTH); accountName = tmpBuffer; delete[] tmpBuffer; - delete [] keyBuffer; + delete[] keyBuffer; return retval; -} +} bool ConnectionServer::decryptToken(const KeyShare::Token & token, char* sessionKey, StationId & stationId) { static ConnectionServer & cs = instance(); - + uint32 len = apiSessionIdWidth + sizeof(StationId); unsigned char * keyBuffer = new unsigned char[len + 1]; unsigned char * keyBufferPointer = keyBuffer; memset(keyBuffer, 0, sizeof(*keyBuffer)); - - - bool retval = cs.loginServerKeys->decipherToken(token, keyBuffer, len); - if (! retval) + bool retval = cs.loginServerKeys->decipherToken(token, keyBuffer, len); + + if (!retval) return retval; - memcpy(sessionKey, keyBufferPointer, sizeof(*keyBuffer)); + memcpy(sessionKey, keyBufferPointer, len); keyBufferPointer += apiSessionIdWidth; memcpy(&stationId, keyBufferPointer, sizeof(StationId)); - delete [] keyBuffer; + delete[] keyBuffer; return retval; } - //----------------------------------------------------------------------- const Service * ConnectionServer::getChatService() @@ -297,21 +294,21 @@ void ConnectionServer::addNewClient(ClientConnection* cconn, const NetworkId &oi { static ConnectionServer & cs = instance(); ClientMap::iterator i = cs.clientMap.find(oid); - if(i != cs.clientMap.end()) + if (i != cs.clientMap.end()) { - if(cconn->getClient()) - { - WARNING_STRICT_FATAL(true, ("Client already connected, attempting to drop old one\n")); - dropClient(cconn, "Duplicate Login"); - return; - } - else - { - // stale connection in map - cs.removeFromClientMap(oid); - } + if (cconn->getClient()) + { + WARNING_STRICT_FATAL(true, ("Client already connected, attempting to drop old one\n")); + dropClient(cconn, "Duplicate Login"); + return; + } + else + { + // stale connection in map + cs.removeFromClientMap(oid); + } } - + // Create a new entry in the client map cs.addToClientMap(oid, cconn); @@ -322,51 +319,51 @@ void ConnectionServer::addNewClient(ClientConnection* cconn, const NetworkId &oi // select a chat server connection for the client // if non exists, then the client will be notified when // one starts - if(! cs.chatServers.empty()) + if (!cs.chatServers.empty()) { //ChatServerConnection * c = (*chatServers.begin()); // find chat server with least load size_t max = 0xFFFFFFFF; ChatServerConnection * candidate = 0; std::set::const_iterator iter; - for(iter = cs.chatServers.begin(); iter != cs.chatServers.end(); ++iter) + for (iter = cs.chatServers.begin(); iter != cs.chatServers.end(); ++iter) { - if((*iter)->getClients().size() <= max) + if ((*iter)->getClients().size() <= max) { candidate = (*iter); max = (*iter)->getClients().size(); } } - if(candidate) + if (candidate) newClient->setChatConnection(candidate); } // select a cs server connection for the client // if non exists, then the client will be notified when // one starts - if(! cs.customerServiceServers.empty()) + if (!cs.customerServiceServers.empty()) { //ChatServerConnection * c = (*chatServers.begin()); // find chat server with least load size_t max = 0xFFFFFFFF; CustomerServiceConnection * candidate = 0; std::set::const_iterator iter; - for(iter = cs.customerServiceServers.begin(); iter != cs.customerServiceServers.end(); ++iter) + for (iter = cs.customerServiceServers.begin(); iter != cs.customerServiceServers.end(); ++iter) { - if((*iter)->getClients().size() <= max) + if ((*iter)->getClients().size() <= max) { candidate = (*iter); max = (*iter)->getClients().size(); } } - if(candidate) + if (candidate) newClient->setCustomerServiceConnection(candidate); } - + //send the game server a message about this client. static const std::string loginTrace("TRACE_LOGIN"); LOG(loginTrace, ("NewClient(%d, %s, %s)", cconn->getSUID(), oid.getValueString().c_str(), cconn->getAccountName().c_str())); - NewClient m(oid, cconn->getAccountName(), cconn->getRemoteAddress(), cconn->getIsSecure(), false, cconn->getSUID(), NULL, cconn->getGameFeatures(), cconn->getSubscriptionFeatures(), cconn->getEntitlementTotalTime(), cconn->getEntitlementEntitledTime(), cconn->getEntitlementTotalTimeSinceLastLogin(), cconn->getEntitlementEntitledTimeSinceLastLogin(), cconn->getBuddyPoints(), cconn->getConsumedRewardEvents(), cconn->getClaimedRewardItems(), cconn->isUsingAdminLogin(), cconn->getCanSkipTutorial(), sendToStarport ); + NewClient m(oid, cconn->getAccountName(), cconn->getRemoteAddress(), cconn->getIsSecure(), false, cconn->getSUID(), nullptr, cconn->getGameFeatures(), cconn->getSubscriptionFeatures(), cconn->getEntitlementTotalTime(), cconn->getEntitlementEntitledTime(), cconn->getEntitlementTotalTimeSinceLastLogin(), cconn->getEntitlementEntitledTimeSinceLastLogin(), cconn->getBuddyPoints(), cconn->getConsumedRewardEvents(), cconn->getClaimedRewardItems(), cconn->isUsingAdminLogin(), cconn->getCanSkipTutorial(), sendToStarport); gconn->send(m, true); //@todo move this to ClientConnection.cpp } @@ -375,10 +372,10 @@ void ConnectionServer::addNewClient(ClientConnection* cconn, const NetworkId &oi void ConnectionServer::dropClient(ClientConnection * conn, const std::string& description) { - DEBUG_FATAL(!conn, ("Cannot call dropClient with NULL connection")); + DEBUG_FATAL(!conn, ("Cannot call dropClient with nullptr connection")); if (!conn) //lint !e774 // boolean within 'if' always evaluates to False //suppresed because this is only relevant in DEBUG builds return; - + static ConnectionServer & cs = instance(); //Client dropped. Tell game server if they've logged in. LOG("ClientDisconnect", ("Dropping client for SUID %d\n", conn->getSUID())); @@ -415,7 +412,7 @@ void ConnectionServer::dropClient(ClientConnection * conn, const std::string& de // void ConnectionServer::addPendingCharacter(uint32 suid, ClientConnection* conn) // { // if (pendingMap.find(suid) == pendingMap.end()) -// pendingMap[suid] = conn; +// pendingMap[suid] = conn; // else // { // WARNING_STRICT_FATAL(true, ("Attepting to add duplicate pending chatacter")); @@ -438,7 +435,7 @@ ClientConnection* ConnectionServer::getClientConnection(const uint32 suid) static ConnectionServer & cs = instance(); ClientConnection * result = 0; SuidMap::const_iterator i = cs.connectedMap.find(suid); - if(i != cs.connectedMap.end()) + if (i != cs.connectedMap.end()) { result = (*i).second; } @@ -459,14 +456,14 @@ GameConnection* ConnectionServer::getGameConnection(const std::string &sceneName { static ConnectionServer & cs = instance(); GameServerMap::iterator i = cs.gameServerMap.begin(); - for(; i != cs.gameServerMap.end(); ++i) + for (; i != cs.gameServerMap.end(); ++i) { if (sceneName == (*i).second->getSceneName()) { return (*i).second; } } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- @@ -477,20 +474,22 @@ void ConnectionServer::handleConnectionServerIdMessage(const ConnectionServerId const Service * const servicePrivate = getClientServicePrivate(); const Service * const servicePublic = getClientServicePublic(); - FATAL(servicePrivate == NULL && servicePublic == NULL, ("No client service is active!")); + FATAL(servicePrivate == nullptr && servicePublic == nullptr, ("No client service is active!")); const Service * const g = getGameService(); - FATAL(g == NULL, ("No game service is active!")); + FATAL(g == nullptr, ("No game service is active!")); const Service * const c = getChatService(); const Service * const cs = getCustomerService(); - const uint16 pingPort = getPingPort (); + const uint16 pingPort = getPingPort(); - if((servicePrivate != NULL || servicePublic != NULL) && g != NULL) //lint !e774 // always evaluates to false // suppresed because the FATAL macro triggers this lint warning + if ((servicePrivate != nullptr || servicePublic != nullptr) && g != nullptr) //lint !e774 // always evaluates to false // suppresed because the FATAL macro triggers this lint warning { uint16 chatPort = 0; uint16 csPort = 0; - if(c) + if (c) + { chatPort = c->getBindPort(); + } if (cs) { @@ -498,23 +497,34 @@ void ConnectionServer::handleConnectionServerIdMessage(const ConnectionServerId } uint16 publicPort = 0; - if(servicePublic) + if (servicePublic) + { publicPort = servicePublic->getBindPort(); + } + uint16 privatePort = 0; - if(servicePrivate) + if (servicePrivate) + { privatePort = servicePrivate->getBindPort(); + } + + std::string clientServicePublicBindAddress = ConfigConnectionServer::getPublicBindAddress(); + if (clientServicePublicBindAddress.empty()) + { + clientServicePublicBindAddress = NetworkHandler::getHostName(); + } - std::string clientServicePublicBindAddress = NetworkHandler::getHostName(); - NOT_NULL(gameService); NOT_NULL(chatService); NOT_NULL(customerService); - + const NewCentralConnectionServer ncs(gameService->getBindAddress(), clientServicePublicBindAddress, chatService->getBindAddress(), customerService->getBindAddress(), privatePort, publicPort, g->getBindPort(), chatPort, csPort, pingPort, ConfigConnectionServer::getConnectionServerNumber()); sendToCentralProcess(ncs); } else + { FATAL(true, ("Error in connection server startup")); + } } // ---------------------------------------------------------------------- @@ -523,413 +533,445 @@ void ConnectionServer::receiveMessage(const MessageDispatch::Emitter & source, c { // it's reasonably safe to cast, message type verified // determine message type - - if(message.isType("GameConnectionOpened")) - { - DEBUG_REPORT_LOG(true,("Game Connection opened\n")); - } - else if (message.isType("GameConnectionClosed")) - { - //@todo handle case where game server drops and we have users connected to it. - //Drop all connected clients. - const GameConnection & downConnection = static_cast(source); - DEBUG_REPORT_LOG(true, ("Game Server connection went down. Dropping clients.\n")); - //remove Game Conection from list - - PseudoClientConnection::gameConnectionClosed(&downConnection); - - GameServerMap::iterator j = gameServerMap.find(downConnection.getGameServerId()); - if (j != gameServerMap.end()) - { - gameServerMap.erase(j); - } - } - - else if(message.isType("CentralConnectionOpened")) - { - DEBUG_REPORT_LOG(true,("Opened connection with central\n")); - centralConnection = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) - if(s_clientServiceSetup == 0) - s_clientServiceSetup = new NetworkSetupData; - - s_clientServiceSetup->useTcp = false; - if(ConfigConnectionServer::getStartPublicServer()) - clientServicePublic = new Service(ConnectionAllocator(), *s_clientServiceSetup); - s_clientServiceSetup->port = ConfigConnectionServer::getClientServicePortPrivate(); - clientServicePrivate = new Service(ConnectionAllocator(), *s_clientServiceSetup); - s_clientServiceSetup->port = ConfigConnectionServer::getClientServicePortPublic(); - - connectToMessage("ClientConnectionOpened"); - connectToMessage("ClientConnectionClosed"); - - } - else if (message.isType("CentralConnectionClosed")) - { - centralConnection = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) - setDone("CentralConnectionClosed: %s", centralConnection ? centralConnection->getDisconnectReason().c_str() : ""); - centralConnection = 0; - DEBUG_REPORT_LOG(true, ("CentralDied. So we will too\n")); - //@todo Drop all pending clients. - } - else if(message.isType("ClientConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Opened connection with client\n")); - } - else if (message.isType("ClientConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Client is Dropping connection\n")); - ClientConnection * cconn = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) - - //tell CentralServer - if (centralConnection) - { - GenericValueTypeMessage const msg("ClientConnectionClosed", cconn->getSUID()); - centralConnection->send(msg,true); - } - - //Client dropped. Tell game server if they've logged in. - Client *client = cconn->getClient(); - if (client) - { - DropClient msg(client->getNetworkId()); - GameConnection* gconn = client->getGameConnection(); - //Don't worry about sending a message to a non-existant game server - if (gconn) - gconn->send(msg, true); - - // Remove the entry from the client map - removeFromClientMap(client->getNetworkId()); - } - else - { - //If they aren't connected to the game yet, they're probably on the pending list. -// removePendingCharacter(cconn->getSUID()); - } - removeFromConnectedMap(cconn->getSUID()); - } - else if (message.isType("ConnectionServerId")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ConnectionServerId m(ri); - handleConnectionServerIdMessage(m); - } - else if (message.isType("ConnectionKeyPush")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ConnectionKeyPush pk(ri); - loginServerKeys->pushKey(pk.getKey()); - } - - else if (message.isType("LoginKeyPush")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const LoginKeyPush k(ri); - loginServerKeys->pushKey(k.getKey()); - } - else if (message.isType("CharacterListMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const CharacterListMessage msg(ri); - WARNING_STRICT_FATAL(true,("CharacterListMessage is deprecated on the ConnectionServer -- fix whoever is sending it.\n")); - } - else if (message.isType("ConnectionCreateCharacterSuccess")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const ConnectionCreateCharacterSuccess msg(ri); - LOG("TraceCharacterCreation", ("Received ConnectionCreateCharacterSuccess for %d", msg.getStationId())); - ClientConnection* const client = getClientConnection(msg.getStationId()); - if (client) - { - const ClientCreateCharacterSuccess m (msg.getNetworkId ()); - client->send(m, true); - } - else - { - LOG("CustomerService", ("CharacterTransfer: Trying to deliver ConnectionCreateCharacterSuccess to PsuedoClientConnection(%d)", msg.getStationId())); - PseudoClientConnection::tryToDeliverMessageTo(static_cast(msg.getStationId()), static_cast(message).getByteStream()); - } - } - else if (message.isType("ConnectionCreateCharacterFailed")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const ConnectionCreateCharacterFailed msg(ri); - ClientConnection* client = getClientConnection(msg.getStationId()); - if (client) - { - client->setHasRequestedCharacterCreate(false); + const uint32 messageType = message.getType(); - ClientCreateCharacterFailed m(msg.getName(), msg.getErrorMessage()); //lint !e1013 !e1055 !e746 (Symbol 'getErrorMessage' not a member of class 'const ConnectionCreateCharacterFailed') // supressed because it IS a member of that class. //lint !e1055 //lint !e746 - client->send(m, true); - } - else + switch(messageType) { + case constcrc("GameConnectionOpened") : { - PseudoClientConnection::tryToDeliverMessageTo(static_cast(msg.getStationId()), static_cast(message).getByteStream()); + DEBUG_REPORT_LOG(true, ("Game Connection opened\n")); + break; } - } - else if (message.isType("NewCharacterCreated")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const msg(ri); - ClientConnection* client = getClientConnection(msg.getValue()); - if (client) + case constcrc("GameConnectionClosed") : { - // don't allow this client to request another character create; - // this will forced the client to disconnect and reconnect at which time - // a check will be done (taking the newly created character into account) - // to see if the client is allowed to create another character on this account - client->setHasCreatedCharacter(true); - } - } - else if (message.isType("RandomNameResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RandomNameResponse connMsg(ri); + //@todo handle case where game server drops and we have users connected to it. + //Drop all connected clients. + const GameConnection & downConnection = static_cast(source); + DEBUG_REPORT_LOG(true, ("Game Server connection went down. Dropping clients.\n")); + //remove Game Conection from list - ClientConnection* cconn = getClientConnection(connMsg.getStationId()); - ClientRandomNameResponse cnr(connMsg.getCreatureTemplate(), connMsg.getName(), connMsg.getErrorMessage());//lint !e1013 (Symbol 'getErrorMessage' not a member of class 'RandomNameResponse') // supressed because it IS a member of that class. - if (cconn) - cconn->send(cnr, true); - } - else if (message.isType("VerifyAndLockNameResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - VerifyAndLockNameResponse connMsg(ri); + PseudoClientConnection::gameConnectionClosed(&downConnection); - ClientConnection* cconn = getClientConnection(connMsg.getStationId()); - ClientVerifyAndLockNameResponse cvalnr(connMsg.getCharacterName(), connMsg.getErrorMessage()); - if (cconn) - cconn->send(cvalnr, true); - } - else if (message.isType("ChatServerConnectionOpened")) - { - ChatServerConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is - IGNORE_RETURN(chatServers.insert(c)); - } - else if (message.isType("ChatServerConnectionClosed")) - { - ChatServerConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is - std::set::iterator f = chatServers.find(c); - if(f != chatServers.end()) - { - // migrate players that were on this chat server - // to another chat server - - // now remove the server from the set - chatServers.erase(f); - if(!chatServers.empty()) + GameServerMap::iterator j = gameServerMap.find(downConnection.getGameServerId()); + if (j != gameServerMap.end()) { - std::set::iterator ic = chatServers.begin(); + gameServerMap.erase(j); + } + break; + } + case constcrc("CentralConnectionOpened") : + { + DEBUG_REPORT_LOG(true, ("Opened connection with central\n")); + centralConnection = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) - const std::set & clients = c->getClients(); - std::set::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++ i) + if (ConfigConnectionServer::getStartPublicServer()) + { + s_clientServiceSetup->port = ConfigConnectionServer::getClientServicePortPublic(); + s_clientServiceSetup->maxConnectionsPerIP = ConfigConnectionServer::getMaxConnectionsPerIP(); + clientServicePublic = new Service(ConnectionAllocator(), *s_clientServiceSetup); + } + + s_clientServiceSetup->port = ConfigConnectionServer::getClientServicePortPrivate(); + s_clientServiceSetup->maxConnectionsPerIP = 0; + clientServicePrivate = new Service(ConnectionAllocator(), *s_clientServiceSetup); + + connectToMessage("ClientConnectionOpened"); + connectToMessage("ClientConnectionClosed"); + break; + } + case constcrc("CentralConnectionClosed") : + { + centralConnection = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) + setDone("CentralConnectionClosed: %s", centralConnection ? centralConnection->getDisconnectReason().c_str() : ""); + centralConnection = 0; + DEBUG_REPORT_LOG(true, ("CentralDied. So we will too\n")); + //@todo Drop all pending clients. + break; + } + case constcrc("ClientConnectionOpened") : + { + DEBUG_REPORT_LOG(true, ("Opened connection with client\n")); + break; + } + case constcrc("ClientConnectionClosed") : + { + DEBUG_REPORT_LOG(true, ("Client is Dropping connection\n")); + ClientConnection * cconn = const_cast(static_cast(&source));//lint !e826 // info: Suspiscious pointer-to-pointer conversion (area too small) + + //tell CentralServer + if (centralConnection) + { + GenericValueTypeMessage const msg("ClientConnectionClosed", cconn->getSUID()); + centralConnection->send(msg, true); + } + + //Client dropped. Tell game server if they've logged in. + Client *client = cconn->getClient(); + if (client) + { + DropClient msg(client->getNetworkId()); + GameConnection* gconn = client->getGameConnection(); + //Don't worry about sending a message to a non-existant game server + if (gconn) + gconn->send(msg, true); + + // Remove the entry from the client map + removeFromClientMap(client->getNetworkId()); + } + else + { + // TODO: wtf is this? @Darth, fix it! + //If they aren't connected to the game yet, they're probably on the pending list. + //removePendingCharacter(cconn->getSUID()); + } + removeFromConnectedMap(cconn->getSUID()); + break; + } + case constcrc("ConnectionServerId") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ConnectionServerId m(ri); + handleConnectionServerIdMessage(m); + break; + } + case constcrc("ConnectionKeyPush") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ConnectionKeyPush pk(ri); + loginServerKeys->pushKey(pk.getKey()); + break; + } + case constcrc("LoginKeyPush") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const LoginKeyPush k(ri); + loginServerKeys->pushKey(k.getKey()); + break; + } + case constcrc("CharacterListMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const CharacterListMessage msg(ri); + WARNING_STRICT_FATAL(true, ("CharacterListMessage is deprecated on the ConnectionServer -- fix whoever is sending it.\n")); + break; + } + case constcrc("ConnectionCreateCharacterSuccess") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const ConnectionCreateCharacterSuccess msg(ri); + LOG("TraceCharacterCreation", ("Received ConnectionCreateCharacterSuccess for %d", msg.getStationId())); + ClientConnection* const client = getClientConnection(msg.getStationId()); + if (client) + { + const ClientCreateCharacterSuccess m(msg.getNetworkId()); + client->send(m, true); + } + else + { + LOG("CustomerService", ("CharacterTransfer: Trying to deliver ConnectionCreateCharacterSuccess to PsuedoClientConnection(%d)", msg.getStationId())); + PseudoClientConnection::tryToDeliverMessageTo(static_cast(msg.getStationId()), static_cast(message).getByteStream()); + } + break; + } + case constcrc("ConnectionCreateCharacterFailed") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const ConnectionCreateCharacterFailed msg(ri); + ClientConnection* client = getClientConnection(msg.getStationId()); + if (client) + { + client->setHasRequestedCharacterCreate(false); + + ClientCreateCharacterFailed m(msg.getName(), msg.getErrorMessage()); //lint !e1013 !e1055 !e746 (Symbol 'getErrorMessage' not a member of class 'const ConnectionCreateCharacterFailed') // supressed because it IS a member of that class. //lint !e1055 //lint !e746 + client->send(m, true); + } + else + { + PseudoClientConnection::tryToDeliverMessageTo(static_cast(msg.getStationId()), static_cast(message).getByteStream()); + } + break; + } + case constcrc("NewCharacterCreated") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage const msg(ri); + ClientConnection* client = getClientConnection(msg.getValue()); + if (client) + { + // don't allow this client to request another character create; + // this will forced the client to disconnect and reconnect at which time + // a check will be done (taking the newly created character into account) + // to see if the client is allowed to create another character on this account + client->setHasCreatedCharacter(true); + } + break; + } + case constcrc("RandomNameResponse") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RandomNameResponse connMsg(ri); + + ClientConnection* cconn = getClientConnection(connMsg.getStationId()); + ClientRandomNameResponse cnr(connMsg.getCreatureTemplate(), connMsg.getName(), connMsg.getErrorMessage());//lint !e1013 (Symbol 'getErrorMessage' not a member of class 'RandomNameResponse') // supressed because it IS a member of that class. + if (cconn) + cconn->send(cnr, true); + + break; + } + case constcrc("VerifyAndLockNameResponse") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + VerifyAndLockNameResponse connMsg(ri); + + ClientConnection* cconn = getClientConnection(connMsg.getStationId()); + ClientVerifyAndLockNameResponse cvalnr(connMsg.getCharacterName(), connMsg.getErrorMessage()); + if (cconn) + cconn->send(cvalnr, true); + + break; + } + case constcrc("ChatServerConnectionOpened") : + { + ChatServerConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is + IGNORE_RETURN(chatServers.insert(c)); + break; + } + case constcrc("ChatServerConnectionClosed") : + { + ChatServerConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is + std::set::iterator f = chatServers.find(c); + if (f != chatServers.end()) + { + // migrate players that were on this chat server + // to another chat server + + // now remove the server from the set + chatServers.erase(f); + if (!chatServers.empty()) { - ChatServerConnection * newConn = (*ic); - Client * cl = (*i); - cl->setChatConnection(newConn); - ++ic; - if(ic == chatServers.end()) - ic = chatServers.begin(); + std::set::iterator ic = chatServers.begin(); + + const std::set & clients = c->getClients(); + std::set::const_iterator i; + for (i = clients.begin(); i != clients.end(); ++i) + { + ChatServerConnection * newConn = (*ic); + Client * cl = (*i); + cl->setChatConnection(newConn); + ++ic; + if (ic == chatServers.end()) + ic = chatServers.begin(); + } + } + else + { + const std::set & clients = c->getClients(); + std::set::const_iterator i; + for (i = clients.begin(); i != clients.end(); ++i) + { + (*i)->setChatConnection(nullptr); + } + } + } + break; + } + case constcrc("CustomerServiceConnectionOpened") : + { + CustomerServiceConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is + IGNORE_RETURN(customerServiceServers.insert(c)); + break; + } + case constcrc("CustomerServiceConnectionClosed") : + { + CustomerServiceConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is + std::set::iterator f = customerServiceServers.find(c); + if (f != customerServiceServers.end()) + { + // migrate players that were on this chat server + // to another chat server + + // now remove the server from the set + customerServiceServers.erase(f); + if (!customerServiceServers.empty()) + { + std::set::iterator ic = customerServiceServers.begin(); + + const std::set & clients = c->getClients(); + std::set::const_iterator i; + for (i = clients.begin(); i != clients.end(); ++i) + { + CustomerServiceConnection * newConn = (*ic); + Client * cl = (*i); + cl->setCustomerServiceConnection(newConn); + ++ic; + if (ic == customerServiceServers.end()) + ic = customerServiceServers.begin(); + } + } + else + { + const std::set & clients = c->getClients(); + std::set::const_iterator i; + for (i = clients.begin(); i != clients.end(); ++i) + { + (*i)->setCustomerServiceConnection(nullptr); + } + } + } + break; + } + case constcrc("GameServerForLoginMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GameServerForLoginMessage msg(ri); + + ClientConnection* client = getClientConnection(msg.getStationId()); + + // see if the client is for the same character as the login message. + // this is required to prevent admin login via the CS Tool from + // disconnecting other characters logged in from the same account + // (but not the same character) as the character we're administratively + // logging in. + bool clientIsForSameCharacterId = false; + if (client) + { + clientIsForSameCharacterId = client->getCharacterId() == msg.getCharacterId(); + } + + bool handledByPseudoClient = false; + // if the character id in the message doesn't match the character id for + // the existing client, it may be for a pseudoclient. Check, and if so, + // handle there. + if (!clientIsForSameCharacterId) + { + PseudoClientConnection * pcc = PseudoClientConnection::getPseudoClientConnection(msg.getCharacterId()); + // hand off to the PCC only if we do have a pseudoclient, and either we don't have a client, or + // the pseudoclient has a tool id, telling us that it's for cs tool login. + if (pcc && ((!client) || (pcc->getTransferCharacterData().getCSToolId() > 0))) + { + handledByPseudoClient = true; + bool result; + result = PseudoClientConnection::tryToDeliverMessageTo(msg.getStationId(), static_cast(message).getByteStream()); + UNREF(result); + DEBUG_REPORT_LOG(!result, ("Received GameServerForLoginMessage for %lu, who was not connected.\n", msg.getStationId())); + } + } + + if (client && (!handledByPseudoClient)) + { + static const std::string loginTrace("TRACE_LOGIN"); + LOG(loginTrace, ("GameServerForLoginMessage(%d, %s)", client->getSUID(), client->getCharacterId().getValueString().c_str())); + client->handleGameServerForLoginMessage(msg.getServer()); + } + break; + } + case constcrc("ValidateCharacterForLoginReplyMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const ValidateCharacterForLoginReplyMessage msg(ri); + + ClientConnection* cconn = getClientConnection(msg.getSuid()); + if (!cconn) + DEBUG_REPORT_LOG(true, ("Received ValidateCharacterForLoginReplyMessage for account %lu, which is no longer connected.\n", msg.getSuid())); + else + { + cconn->onCharacterValidated(msg.getApproved(), msg.getCharacterId(), Unicode::wideToNarrow(msg.getCharacterName()), msg.getContainerId(), msg.getScene(), msg.getCoordinates()); + } + break; + } + case constcrc("ValidateAccountReplyMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const ValidateAccountReplyMessage msg(ri); + + ClientConnection* cconn = getClientConnection(msg.getStationId()); + if (!cconn) + DEBUG_REPORT_LOG(true, ("Received ValidateAccountReplyMessage for account %lu, which is no longer connected.\n", msg.getStationId())); + else + { + cconn->onIdValidated(msg.getCanLogin(), msg.getCanCreateRegular(), msg.getCanCreateJedi(), msg.getCanSkipTutorial(), msg.getConsumedRewardEvents(), msg.getClaimedRewardItems()); + } + break; + } + case constcrc("SetConnectionServerPublic") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + SetConnectionServerPublic p(ri);//lint !e40 !e522 !e10 // Undeclared identifier 'SetConnectionServerPublic' // suppressed because it IS declared + bool statusChanged = false; + DEBUG_REPORT_LOG(true, ("Conn Server: attempting to chang status\n")); + if (p.getIsPublic())//lint !e40 !e1013 !e10 // Undeclared identifier 'p' // suppressed because it IS declared + { + if (!clientServicePublic) + { + statusChanged = true; } } else { - const std::set & clients = c->getClients(); - std::set::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++ i) - { - (*i)->setChatConnection(NULL); - } - } - } - } - else if (message.isType("CustomerServiceConnectionOpened")) - { - CustomerServiceConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is - IGNORE_RETURN(customerServiceServers.insert(c)); - } - else if (message.isType("CustomerServiceConnectionClosed")) - { - CustomerServiceConnection * c = const_cast(static_cast(&source));//lint !e826 suspiscious pointer-to-pointer conversion // suppressed, you bet it is - std::set::iterator f = customerServiceServers.find(c); - if(f != customerServiceServers.end()) - { - // migrate players that were on this chat server - // to another chat server - - // now remove the server from the set - customerServiceServers.erase(f); - if(!customerServiceServers.empty()) - { - std::set::iterator ic = customerServiceServers.begin(); - - const std::set & clients = c->getClients(); - std::set::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++ i) - { - CustomerServiceConnection * newConn = (*ic); - Client * cl = (*i); - cl->setCustomerServiceConnection(newConn); - ++ic; - if(ic == customerServiceServers.end()) - ic = customerServiceServers.begin(); - } - } - else - { - const std::set & clients = c->getClients(); - std::set::const_iterator i; - for(i = clients.begin(); i != clients.end(); ++ i) - { - (*i)->setCustomerServiceConnection(NULL); - } - } - - } - } - else if (message.isType("GameServerForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GameServerForLoginMessage msg(ri); - - ClientConnection* client = getClientConnection(msg.getStationId()); - - // see if the client is for the same character as the login message. - // this is required to prevent admin login via the CS Tool from - // disconnecting other characters logged in from the same account - // (but not the same character) as the character we're administratively - // logging in. - bool clientIsForSameCharacterId = false; - if(client) - { - clientIsForSameCharacterId = client->getCharacterId() == msg.getCharacterId(); - } - - bool handledByPseudoClient = false; - // if the character id in the message doesn't match the character id for - // the existing client, it may be for a pseudoclient. Check, and if so, - // handle there. - if (!clientIsForSameCharacterId) - { - PseudoClientConnection * pcc = PseudoClientConnection::getPseudoClientConnection(msg.getCharacterId()); - // hand off to the PCC only if we do have a pseudoclient, and either we don't have a client, or - // the pseudoclient has a tool id, telling us that it's for cs tool login. - if(pcc && ((!client) || (pcc->getTransferCharacterData().getCSToolId() > 0))) - { - handledByPseudoClient = true; - bool result; - result = PseudoClientConnection::tryToDeliverMessageTo(msg.getStationId(), static_cast(message).getByteStream()); - UNREF(result); - DEBUG_REPORT_LOG(! result,("Received GameServerForLoginMessage for %lu, who was not connected.\n",msg.getStationId())); - } - } - - if (client && (!handledByPseudoClient)) - { - static const std::string loginTrace("TRACE_LOGIN"); - LOG(loginTrace, ("GameServerForLoginMessage(%d, %s)", client->getSUID(), client->getCharacterId().getValueString().c_str())); - client->handleGameServerForLoginMessage(msg.getServer()); - } - } - else if (message.isType("ValidateCharacterForLoginReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const ValidateCharacterForLoginReplyMessage msg(ri); - - ClientConnection* cconn = getClientConnection(msg.getSuid()); - if (!cconn) - DEBUG_REPORT_LOG(true, ("Received ValidateCharacterForLoginReplyMessage for account %lu, which is no longer connected.\n",msg.getSuid())); - else - { - cconn->onCharacterValidated(msg.getApproved(),msg.getCharacterId(), Unicode::wideToNarrow(msg.getCharacterName()), msg.getContainerId(), msg.getScene(), msg.getCoordinates()); - } - } - else if (message.isType("ValidateAccountReplyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const ValidateAccountReplyMessage msg(ri); - - ClientConnection* cconn = getClientConnection(msg.getStationId()); - if (!cconn) - DEBUG_REPORT_LOG(true, ("Received ValidateAccountReplyMessage for account %lu, which is no longer connected.\n",msg.getStationId())); - else - { - cconn->onIdValidated(msg.getCanLogin(),msg.getCanCreateRegular(),msg.getCanCreateJedi(),msg.getCanSkipTutorial(),msg.getConsumedRewardEvents(),msg.getClaimedRewardItems()); - } - } - else if(message.isType("SetConnectionServerPublic")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - SetConnectionServerPublic p(ri);//lint !e40 !e522 !e10 // Undeclared identifier 'SetConnectionServerPublic' // suppressed because it IS declared - bool statusChanged = false; - DEBUG_REPORT_LOG(true, ("Conn Server: attempting to chang status\n")); - if(p.getIsPublic())//lint !e40 !e1013 !e10 // Undeclared identifier 'p' // suppressed because it IS declared - { - if(! clientServicePublic) - { + delete clientServicePublic; + clientServicePublic = 0; statusChanged = true; } - } - else - { - delete clientServicePublic; - clientServicePublic = 0; - statusChanged = true; - } - if(statusChanged && centralConnection) - { - const Service * publicService = getClientServicePublic(); - const Service * privateService = getClientServicePrivate(); - if(publicService || privateService) + if (statusChanged && centralConnection) { - uint16 publicServicePort = 0; - uint16 privateServicePort = 0; - if(publicService) + const Service * publicService = getClientServicePublic(); + const Service * privateService = getClientServicePrivate(); + if (publicService || privateService) { - publicServicePort = publicService->getBindPort(); + uint16 publicServicePort = 0; + uint16 privateServicePort = 0; + if (publicService) + { + publicServicePort = publicService->getBindPort(); + } + if (privateService) + { + privateServicePort = privateService->getBindPort(); + } + const UpdateConnectionServerStatus ucs(publicServicePort, privateServicePort); + centralConnection->send(ucs, true); } - if(privateService) - { - privateServicePort = privateService->getBindPort(); - } - const UpdateConnectionServerStatus ucs(publicServicePort, privateServicePort); - centralConnection->send(ucs, true); } - } - }//lint !e529 // Symbol 'ri' not subsequently referenced // suppressed because it IS referenced. I think lint is very confused for some reason. - else if(message.isType("ProfilerOperationMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ProfilerOperationMessage msg(ri); - unsigned int processId = msg.getProcessId(); - if (!processId) - Profiler::handleOperation(msg.getOperation().c_str()); - } - else if (message.isType("ExcommunicateGameServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ExcommunicateGameServerMessage msg(ri); - - LOG("GameGameConnect",("Told to drop connection to %lu by Central",msg.getServerId())); - - GameConnection *conn =getGameConnection(msg.getServerId()); - if (conn) - conn->disconnect(); - } - else if (message.isType("CntrlSrvDropDupeConns")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - ClientConnection* client = getClientConnection(msg.getValue().first); - if (client && !client->isUsingAdminLogin() && !client->getIsSecure()) + break; + }//lint !e529 // Symbol 'ri' not subsequently referenced // suppressed because it IS referenced. I think lint is very confused for some reason. + case constcrc("ProfilerOperationMessage") : { - std::string s = "New Connection on galaxy "; - s += msg.getValue().second; + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ProfilerOperationMessage msg(ri); + unsigned int processId = msg.getProcessId(); + if (!processId) + Profiler::handleOperation(msg.getOperation().c_str()); + + break; + } + case constcrc("ExcommunicateGameServerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ExcommunicateGameServerMessage msg(ri); - dropClient(client, s); + LOG("GameGameConnect", ("Told to drop connection to %lu by Central", msg.getServerId())); + + GameConnection *conn = getGameConnection(msg.getServerId()); + if (conn) + conn->disconnect(); + + break; + } + case constcrc("CntrlSrvDropDupeConns") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + ClientConnection* client = getClientConnection(msg.getValue().first); + if (client && !client->isUsingAdminLogin() && !client->getIsSecure()) + { + std::string s = "New Connection on galaxy "; + s += msg.getValue().second; + + dropClient(client, s); + } + break; } } } @@ -940,12 +982,12 @@ void ConnectionServer::install() { s_connectionServer = new ConnectionServer; - char tmp[128] = {"\0"}; - IGNORE_RETURN(snprintf(tmp, sizeof(tmp), "ConnectionServer:%d", Os::getProcessId())); + char tmp[128] = { "\0" }; + IGNORE_RETURN(snprintf(tmp, sizeof(tmp), "ConnectionServer:%d", Os::getProcessId())); SetupSharedLog::install(tmp); s_connectionServer->setupConnections(); s_connectionServer->m_metricsData = new ConnectionServerMetricsData; - MetricsManager::install(s_connectionServer->m_metricsData, true, "ConnectionServer" , "", ConfigConnectionServer::getConnectionServerNumber()); + MetricsManager::install(s_connectionServer->m_metricsData, true, "ConnectionServer", "", ConfigConnectionServer::getConnectionServerNumber()); DataTableManager::install(); AdminAccountManager::install(ConfigConnectionServer::getAdminAccountDataTable()); } @@ -958,30 +1000,29 @@ void ConnectionServer::remove() delete s_connectionServer->m_metricsData; s_connectionServer->m_metricsData = 0; - // explicitly delete all connections that were setup from setupConnections rather than letting + // explicitly delete all connections that were setup from setupConnections rather than letting // Connection::remove do it. There are connections that require a valid s_connectionServer which is deleted - // and set to NULL. + // and set to nullptr. s_connectionServer->unsetupConnections(); - + SetupSharedLog::remove(); - + delete s_connectionServer; s_connectionServer = 0; } //----------------------------------------------------------------------- - void ConnectionServer::run(void) { static const bool shouldSleep = ConfigConnectionServer::getShouldSleep(); static ConnectionServer & cserver = instance(); - DEBUG_FATAL (!cserver.m_metricsData, ("Connection server not installed properly")); + DEBUG_FATAL(!cserver.m_metricsData, ("Connection server not installed properly")); unsigned long startTime = Clock::timeMs(); Clock::setFrameRateLimit(50.0f); - LOG("ServerStartup",("ConnectionServer starting on %s", NetworkHandler::getHostName().c_str())); + LOG("ServerStartup", ("ConnectionServer starting on %s", NetworkHandler::getHostName().c_str())); while (!cserver.done) { PROFILER_AUTO_BLOCK_DEFINE("main loop"); @@ -1004,10 +1045,10 @@ void ConnectionServer::run(void) { GenericValueTypeMessage > const syncStampMessage("SetSyncStamp", std::make_pair(static_cast(UdpMisc::LocalSyncStampShort()), static_cast(UdpMisc::LocalSyncStampLong()))); GameServerMap::iterator end = cserver.gameServerMap.end(); - for(GameServerMap::iterator iter = cserver.gameServerMap.begin(); iter != end; ++iter) + for (GameServerMap::iterator iter = cserver.gameServerMap.begin(); iter != end; ++iter) iter->second->send(syncStampMessage, true); } - + { PROFILER_AUTO_BLOCK_DEFINE("NetworkHandler::dispatch"); NetworkHandler::dispatch(); @@ -1030,23 +1071,21 @@ void ConnectionServer::run(void) startTime = curTime; } - if (shouldSleep) { PROFILER_AUTO_BLOCK_DEFINE("Os::sleep"); Os::sleep(1); } - } while (!cserver.done); NetworkHandler::clearBytesThisFrame(); - + cserver.updateRecoveringClientList(static_cast(Clock::frameTime()*1000.0f)); } } // ---------------------------------------------------------------------- -/** +/** * Invoked every frame to do whatever updates are needed */ void ConnectionServer::update() @@ -1054,7 +1093,7 @@ void ConnectionServer::update() if (centralConnection) { static Timer t(5.0f); - if(t.updateZero(Clock::frameTime())) + if (t.updateZero(Clock::frameTime())) { // Update the population on the central server updatePopulationOnCentralServer(); @@ -1074,16 +1113,16 @@ void ConnectionServer::update() static const int ping_throttle_max = 1024; - static char buffer [4]; + static char buffer[4]; - for (int throttle = 0; pingSocket->canRecv () && throttle < ping_throttle_max; ++throttle) + for (int throttle = 0; pingSocket->canRecv() && throttle < ping_throttle_max; ++throttle) { Address addr; - const uint32 count = pingSocket->recvFrom (addr, buffer, 4); + const uint32 count = pingSocket->recvFrom(addr, buffer, 4); m_pingTrafficNumBytes += static_cast(count); if (m_pingTrafficNumBytes < 0) m_pingTrafficNumBytes = 0; - IGNORE_RETURN(pingSocket->sendTo (addr, buffer, count)); + IGNORE_RETURN(pingSocket->sendTo(addr, buffer, count)); } } @@ -1102,7 +1141,7 @@ void ConnectionServer::updateRecoveringClientList(uint elapsedTime) m_recoverTime += elapsedTime; static std::set listPlayersDropped; - for (RecoveringClientListType::iterator i=m_recoveringClientList.begin(); i!=m_recoveringClientList.end();) + for (RecoveringClientListType::iterator i = m_recoveringClientList.begin(); i != m_recoveringClientList.end();) { if (m_recoverTime > i->first) { @@ -1110,16 +1149,16 @@ void ConnectionServer::updateRecoveringClientList(uint elapsedTime) if (client) { if (client->getGameConnection()) - DEBUG_REPORT_LOG(true,("Player %s recovered from a server crash and will not be dropped.\n",i->second.getValueString().c_str())); + DEBUG_REPORT_LOG(true, ("Player %s recovered from a server crash and will not be dropped.\n", i->second.getValueString().c_str())); else { - LOG("Network", ("Dropping player %s because game server crashed and no other server took authority.\n",i->second.getValueString().c_str())); + LOG("Network", ("Dropping player %s because game server crashed and no other server took authority.\n", i->second.getValueString().c_str())); dropClient(client->getClientConnection(), "Game Server Crash"); IGNORE_RETURN(listPlayersDropped.insert(i->second)); } } - i=m_recoveringClientList.erase(i); + i = m_recoveringClientList.erase(i); } else ++i; @@ -1141,7 +1180,7 @@ void ConnectionServer::updateRecoveringClientList(uint elapsedTime) } if (m_recoveringClientList.empty()) - m_recoverTime = 0; // prevent rollover and other problems I don't want to worry about + m_recoverTime = 0; // prevent rollover and other problems I don't want to worry about } } @@ -1158,15 +1197,15 @@ void ConnectionServer::unsetupConnections() { // remove all ClientConnection objects so when Connection::remove() is called we don't crash since // ConnectionServer no longer exists - while( !instance().connectedMap.empty() ) + while (!instance().connectedMap.empty()) { SuidMap::iterator i = instance().connectedMap.begin(); - if( i != instance().connectedMap.end() ) + if (i != instance().connectedMap.end()) { ClientConnection * c = (*i).second; uint32 suid = (*i).first; IGNORE_RETURN(instance().connectedMap.erase(suid)); - if( c ) + if (c) { ConnectionServer::dropClient(c, "ConnectionServer shutting down."); delete c; @@ -1174,30 +1213,29 @@ void ConnectionServer::unsetupConnections() } } - if( customerService ) + if (customerService) { delete customerService; customerService = 0; } - if( chatService ) + if (chatService) { delete chatService; chatService = 0; } - if( centralConnection ) + if (centralConnection) { delete centralConnection; centralConnection = 0; } - if( gameService ) + if (gameService) { delete gameService; gameService = 0; } - } //----------------------------------------------------------------------- @@ -1239,7 +1277,7 @@ void ConnectionServer::setupConnections() connectToMessage("ConnectionKeyPush"); connectToMessage("LoginKeyPush"); connectToMessage("CharacterListMessage"); - + //Create Characters Messages connectToMessage("ClientCreateCharacter"); connectToMessage("ConnectionCreateCharacterSuccess"); @@ -1250,7 +1288,7 @@ void ConnectionServer::setupConnections() // name query messages connectToMessage("ClientRandomNameRequest"); // from client connectToMessage("RandomNameResponse"); // from game server - + connectToMessage("ClientVerifyAndLockNameRequest"); // from client connectToMessage("VerifyAndLockNameResponse"); // from game server @@ -1283,10 +1321,10 @@ void ConnectionServer::setupConnections() //---------------------------------------------------------------------- -uint16 ConnectionServer::getPingPort () +uint16 ConnectionServer::getPingPort() { static ConnectionServer & cs = instance(); - return cs.pingSocket->getBindAddress ().getHostPort (); + return cs.pingSocket->getBindAddress().getHostPort(); } //----------------------------------------------------------------------- @@ -1315,8 +1353,8 @@ GameConnection* ConnectionServer::getGameConnection(uint32 gameServerId) const GameServerMap::const_iterator i = cs.gameServerMap.find(gameServerId); if (i != cs.gameServerMap.end()) return (*i).second; - - return NULL; + + return nullptr; } //----------------------------------------------------------------------- @@ -1327,7 +1365,7 @@ GameConnection* ConnectionServer::getAnyGameConnection() if (!cs.gameServerMap.empty()) return cs.gameServerMap.begin()->second; - return NULL; + return nullptr; } //----------------------------------------------------------------------- @@ -1448,11 +1486,11 @@ void ConnectionServer::addToConnectedMap(uint32 suid, ClientConnection* cconn) connectedMap[suid] = cconn; } - if ( ((cconn->getSubscriptionFeatures() & ClientSubscriptionFeature::FreeTrial) != 0) - && ((cconn->getSubscriptionFeatures() & ClientSubscriptionFeature::Base) == 0)) + if (((cconn->getSubscriptionFeatures() & ClientSubscriptionFeature::FreeTrial) != 0) + && ((cconn->getSubscriptionFeatures() & ClientSubscriptionFeature::Base) == 0)) { freeTrials.insert(suid); - } + } // Update the population on the CentralServer immediately // since we are trying to avoid people "rushing" the server @@ -1468,7 +1506,7 @@ void ConnectionServer::removeFromConnectedMap(uint32 suid) { connectedMap.erase(i); } - + FreeTrialsSet::iterator j = freeTrials.find(suid); if (j != freeTrials.end()) { @@ -1487,20 +1525,20 @@ void ConnectionServer::updatePopulationOnCentralServer() if (centralConnection) { // Total number of clients and how many of those are free trials - const int numPlayers = getNumberOfClients(); + const int numPlayers = getNumberOfClients(); const int numFreeTrial = getNumberOfFreeTrials(); // We are concerned about too many people piling up at the beginning // of the tutorial, so count how many players could be a problem - int numPlayersEmptyScene = 0; + int numPlayersEmptyScene = 0; int numPlayersTutorialScene = 0; - int numPlayersFalconScene = 0; + int numPlayersFalconScene = 0; // Walk through the clients and evaluate what scene they are in SuidMap::const_iterator i; - for(i = connectedMap.begin(); i != connectedMap.end(); ++i) + for (i = connectedMap.begin(); i != connectedMap.end(); ++i) { - const ClientConnection * const conn = (*i).second; + const ClientConnection * const conn = (*i).second; const Client * const client = conn->getClient(); if (client && client->getGameConnection()) @@ -1527,18 +1565,17 @@ void ConnectionServer::updatePopulationOnCentralServer() } const UpdatePlayerCountMessage msg(false, numPlayers, numFreeTrial, numPlayersEmptyScene, numPlayersTutorialScene, numPlayersFalconScene); - centralConnection->send(msg,true); + centralConnection->send(msg, true); } } - // ---------------------------------------------------------------------- SessionApiClient* ConnectionServer::getSessionApiClient() { // this is causing crashes when ConnectionServer is shutdown and something calls this function // because instance() returns 0. - if( s_connectionServer ) + if (s_connectionServer) { return instance().m_sessionApiClient; } @@ -1558,7 +1595,7 @@ void ConnectionServer::setDone(char const *reasonfmt, ...) va_list ap; va_start(ap, reasonfmt); IGNORE_RETURN(_vsnprintf(reason, sizeof(reason), reasonfmt, ap));//lint !e530 Symbol 'ap' not initialized - reason[sizeof(reason)-1] = '\0'; + reason[sizeof(reason) - 1] = '\0'; LOG( "ServerShutdown", @@ -1580,4 +1617,3 @@ void ConnectionServer::setDone(char const *reasonfmt, ...) } // ====================================================================== - diff --git a/engine/server/application/ConnectionServer/src/shared/GameConnection.cpp b/engine/server/application/ConnectionServer/src/shared/GameConnection.cpp index ddf0fe38..ab5bc281 100755 --- a/engine/server/application/ConnectionServer/src/shared/GameConnection.cpp +++ b/engine/server/application/ConnectionServer/src/shared/GameConnection.cpp @@ -31,6 +31,8 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "unicodeArchive/UnicodeArchive.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- GameConnection::GameConnection(const std::string & a, const unsigned short p) : @@ -81,266 +83,286 @@ void GameConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage m(ri); ri = message.begin(); + + const uint32 messageType = m.getType(); - if (m.isType("GameClientMessage")) - { - //we're receiving a message to forward to the client. - //it is prefixed with NetworkId and reliable. - const GameClientMessage msg(ri); - const std::vector & v = msg.getDistributionList(); - std::vector::const_iterator i; - const bool reliable = msg.getReliable(); - - Service *service = ConnectionServer::getClientServicePrivate(); - LogicalPacket const * p = service->createPacket(msg.getByteStream().getBuffer(), static_cast(msg.getByteStream().getSize())); - for(i = v.begin(); i != v.end(); ++i) + switch (messageType) { + case constcrc("GameClientMessage") : { - Client* client = ConnectionServer::getClient((*i)); - if (client) + //we're receiving a message to forward to the client. + //it is prefixed with NetworkId and reliable. + const GameClientMessage msg(ri); + const std::vector & v = msg.getDistributionList(); + std::vector::const_iterator i; + const bool reliable = msg.getReliable(); + + Service *service = ConnectionServer::getClientServicePrivate(); + LogicalPacket const * p = service->createPacket(msg.getByteStream().getBuffer(), static_cast(msg.getByteStream().getSize())); + for(i = v.begin(); i != v.end(); ++i) { - client->getClientConnection()->sendSharedPacket(p, reliable); + Client* client = ConnectionServer::getClient((*i)); + if (client) + { + client->getClientConnection()->sendSharedPacket(p, reliable); + } } + service->releasePacket(p); + + break; } - service->releasePacket(p); - } - else if (m.isType("CreateTicketMessage")) - { - Archive::ReadIterator cri(m.getByteStream()); - CreateTicketMessage const c(cri); - CustomerServiceConnection * const customerServiceConnection = - const_cast(ConnectionServer::getCustomerServiceConnection()); - if (customerServiceConnection) + case constcrc("CreateTicketMessage") : { - customerServiceConnection->send(c, true); - } - } - else if(m.isType("ControlAssumed")) - { - ControlAssumed ca(ri); - - static const std::string loginTrace("TRACE_LOGIN"); - LOG(loginTrace, ("Received Control Assumed Message from game server %lu for %s skipLoadScreen=%s", getGameServerId(), ca.getNetworkId().getValueString().c_str(), (ca.getSkipLoadScreen() ? "yes" : "no"))); - - Client *client = ConnectionServer::getClient(ca.getNetworkId()); - if (!client) - { - // perhaps it's a transfer client? - PseudoClientConnection * pseudoClient = PseudoClientConnection::getPseudoClientConnection(ca.getNetworkId()); - if(! pseudoClient) + Archive::ReadIterator cri(m.getByteStream()); + CreateTicketMessage const c(cri); + CustomerServiceConnection * const customerServiceConnection = + const_cast(ConnectionServer::getCustomerServiceConnection()); + if (customerServiceConnection) { - DEBUG_REPORT_LOG(true, ("Client %s was already dropped, notifying GameServer.\n", ca.getNetworkId().getValueString().c_str())); - DropClient const drop(ca.getNetworkId()); - send(drop, true); - return; + customerServiceConnection->send(c, true); } - else + break; + } + case constcrc("ControlAssumed") : + { + ControlAssumed ca(ri); + + static const std::string loginTrace("TRACE_LOGIN"); + LOG(loginTrace, ("Received Control Assumed Message from game server %lu for %s skipLoadScreen=%s", getGameServerId(), ca.getNetworkId().getValueString().c_str(), (ca.getSkipLoadScreen() ? "yes" : "no"))); + + Client *client = ConnectionServer::getClient(ca.getNetworkId()); + if (!client) { - pseudoClient->controlAssumed(); - return; - } - } - if (!client->getClientConnection()) - { - WARNING_STRICT_FATAL(true, ("We have a client with no client connection\n")); - return; - } - - if (ca.getSkipLoadScreen()) - client->skipLoadScreen(); - - if (!client->getSkipLoadScreen()) - { - CmdStartScene const startScene( - ca.getNetworkId(), - ca.getSceneName(), - ca.getStartPosition(), - ca.getStartYaw(), - ca.getTemplateName(), - ca.getTimeSeconds(), - static_cast(::time(NULL)), - ConfigConnectionServer::getDisableWorldSnapshot()); - client->getClientConnection()->send(startScene, true); - } - client->handleTransfer(ca.getSceneName(), this); - - // record the time when play started for the character - if (client->getClientConnection()->getStartPlayTime() == 0) - { - client->getClientConnection()->setStartPlayTime(::time(NULL)); - } - - // update the play time info on the game server - // must be called after client->handleTransfer() so the - // client object has been updated to point to the correct - // game server for the client->sendPlayTimeInfoToGameServer() - // call to work properly - client->getClientConnection()->sendPlayTimeInfoToGameServer(); - } - else if (m.isType("ReplyBankCTSLoaded")) - { - LOG("CustomerService", ("CharacterTransfer: Game Connection received ReplyBankCTSLoaded message")); - GenericValueTypeMessage characterId(ri); - - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(characterId.getValue(), message)); - } - else if (m.isType("PackedHousesLoaded")) - { - LOG("CustomerService", ("CharacterTransfer: Game Connection received PackedHousesLoaded message")); - GenericValueTypeMessage characterId(ri); - - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(characterId.getValue(), message)); - } - else if (m.isType("NewGameServer")) - { - DEBUG_REPORT_LOG(true, ("Received NewGameServerMessage.\n")); - // a game server has connected. Add it to the map - const NewGameServer newGameServer(ri); - - setGameServerId(newGameServer.getServerId()); - setSceneName(newGameServer.getSceneName()); - - // set the GameServerId @todo - // add it to the map if a game process - ConnectionServer::addGameConnection(newGameServer.getServerId(), this); - } - - else if (m.isType("KickPlayer")) - { - const KickPlayer kickPlayer(ri); - Client *client = ConnectionServer::getClient(kickPlayer.getNetworkId()); - if (client) - client->kick(kickPlayer.getReason()); - } - - else if (m.isType("TransferControlMessage")) - { - // a game server is giving up authority for an object we control - const TransferControlMessage transferControl(ri); - - DEBUG_REPORT_LOG(true, ("Received TransferControlMessage for %s.\n", transferControl.getNetworkId().getValueString().c_str())); - //question, do we need to check scene here? - Client* client = ConnectionServer::getClient(transferControl.getNetworkId()); - - if(client) - { - if (transferControl.getSkipLoadScreen()) - client->skipLoadScreen(); - if (client->getClientConnection()) - { - ClientConnection* cconn = client->getClientConnection(); - GameConnection* newConnection = ConnectionServer::getGameConnection(transferControl.getGameServerId()); - if(cconn && newConnection) - { - //We have a client, and a game connection, so send the newClient message off to the game server in question. - //It will respond with a control assumed message. - NewClient const newClient(transferControl.getNetworkId(), cconn->getAccountName(), cconn->getRemoteAddress(), cconn->getIsSecure(), transferControl.getSkipLoadScreen(), cconn->getSUID(), &transferControl.getObservedObjects(), cconn->getGameFeatures(), cconn->getSubscriptionFeatures(), cconn->getEntitlementTotalTime(), cconn->getEntitlementEntitledTime(), cconn->getEntitlementTotalTimeSinceLastLogin(), cconn->getEntitlementEntitledTimeSinceLastLogin(), cconn->getBuddyPoints(), cconn->getConsumedRewardEvents(), cconn->getClaimedRewardItems(), cconn->isUsingAdminLogin(), cconn->getCanSkipTutorial()); - newConnection->send(newClient, true); + // perhaps it's a transfer client? + PseudoClientConnection * pseudoClient = PseudoClientConnection::getPseudoClientConnection(ca.getNetworkId()); + if(! pseudoClient) + { + DEBUG_REPORT_LOG(true, ("Client %s was already dropped, notifying GameServer.\n", ca.getNetworkId().getValueString().c_str())); + DropClient const drop(ca.getNetworkId()); + send(drop, true); + return; } else { - WARNING_STRICT_FATAL(true, ("A TransferControl message was received to transfer client %s to GameServer %lu, but that game server is no longer available. The client will be dropped.", transferControl.getNetworkId().getValueString().c_str(), transferControl.getGameServerId())); - DropClient const drop(transferControl.getNetworkId()); - send(drop, true); + pseudoClient->controlAssumed(); + return; } } - } - else - { - DEBUG_WARNING(true, ("Received a TransferControllMessage but the client is no longer available. This might be a lost race between the connection server notifiying a game server that the client has disconnected, and the game server notifying the connection server that the client is transferring.")); - DropClient const drop(transferControl.getNetworkId()); - send(drop, true); - } - } - else if(m.isType("ReplyTransferData") || m.isType("ApplyTransferDataSuccess") || m.isType("ApplyTransferDataFail")) - { - GenericValueTypeMessage reply(ri); + if (!client->getClientConnection()) + { + WARNING_STRICT_FATAL(true, ("We have a client with no client connection\n")); + return; + } - IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(reply.getValue().getCharacterId(), message)); - } - else if (m.isType("ChatEnterRoomValidationResponse")) - { - GenericValueTypeMessage, unsigned int> > const reply(ri); + if (ca.getSkipLoadScreen()) + client->skipLoadScreen(); - Client* client = ConnectionServer::getClient(reply.getValue().first.first); - if (client && client->getClientConnection()) - { - client->getClientConnection()->handleChatEnterRoomValidationResponse(reply.getValue().second, reply.getValue().first.second); + if (!client->getSkipLoadScreen()) + { + CmdStartScene const startScene( + ca.getNetworkId(), + ca.getSceneName(), + ca.getStartPosition(), + ca.getStartYaw(), + ca.getTemplateName(), + ca.getTimeSeconds(), + static_cast(::time(nullptr)), + ConfigConnectionServer::getDisableWorldSnapshot()); + client->getClientConnection()->send(startScene, true); + } + client->handleTransfer(ca.getSceneName(), this); + + // record the time when play started for the character + if (client->getClientConnection()->getStartPlayTime() == 0) + { + client->getClientConnection()->setStartPlayTime(::time(nullptr)); + } + + // update the play time info on the game server + // must be called after client->handleTransfer() so the + // client object has been updated to point to the correct + // game server for the client->sendPlayTimeInfoToGameServer() + // call to work properly + client->getClientConnection()->sendPlayTimeInfoToGameServer(); + break; } - } - else if (m.isType("ChatQueryRoomValidationResponse")) - { - GenericValueTypeMessage, unsigned int> > const reply(ri); - - Client* client = ConnectionServer::getClient(reply.getValue().first.first); - if (client && client->getClientConnection()) + case constcrc("ReplyBankCTSLoaded") : { - client->getClientConnection()->handleChatQueryRoomValidationResponse(reply.getValue().second, reply.getValue().first.second); + LOG("CustomerService", ("CharacterTransfer: Game Connection received ReplyBankCTSLoaded message")); + GenericValueTypeMessage characterId(ri); + + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(characterId.getValue(), message)); + break; } - } - else if (m.isType("AccountFeatureIdRequest")) - { - AccountFeatureIdRequest * const msg = new AccountFeatureIdRequest(ri); - - SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); - if (sessionApiClient) + case constcrc("PackedHousesLoaded") : { - // SessionApiClient will own (and delete) msg - sessionApiClient->getFeatures(msg->getTargetStationId(), msg->getGameCode(), msg); + LOG("CustomerService", ("CharacterTransfer: Game Connection received PackedHousesLoaded message")); + GenericValueTypeMessage characterId(ri); + + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(characterId.getValue(), message)); + break; + } + case constcrc("NewGameServer") : + { + DEBUG_REPORT_LOG(true, ("Received NewGameServerMessage.\n")); + // a game server has connected. Add it to the map + const NewGameServer newGameServer(ri); + + setGameServerId(newGameServer.getServerId()); + setSceneName(newGameServer.getSceneName()); + + // set the GameServerId @todo + // add it to the map if a game process + ConnectionServer::addGameConnection(newGameServer.getServerId(), this); + break; } - else + case constcrc("KickPlayer") : { - // a cluster running without session authentication stores - // account feature id information on the LoginServer, so - // pass request to the LoginServer (via CentralServer) - CentralConnection * const cc = ConnectionServer::getCentralConnection(); - if (cc) - cc->send(*msg, true); - - delete msg; + const KickPlayer kickPlayer(ri); + Client *client = ConnectionServer::getClient(kickPlayer.getNetworkId()); + if (client) + client->kick(kickPlayer.getReason()); + + break; } - } - else if (m.isType("AdjustAccountFeatureIdRequest")) - { - AdjustAccountFeatureIdRequest * const msg = new AdjustAccountFeatureIdRequest(ri); - - SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); - if (sessionApiClient) + case constcrc("TransferControlMessage") : { - // SessionApiClient will own (and delete) msg - sessionApiClient->getFeatures(msg->getTargetStationId(), msg->getGameCode(), msg); + // a game server is giving up authority for an object we control + const TransferControlMessage transferControl(ri); + + DEBUG_REPORT_LOG(true, ("Received TransferControlMessage for %s.\n", transferControl.getNetworkId().getValueString().c_str())); + //question, do we need to check scene here? + Client* client = ConnectionServer::getClient(transferControl.getNetworkId()); + + if(client) + { + if (transferControl.getSkipLoadScreen()) + client->skipLoadScreen(); + if (client->getClientConnection()) + { + ClientConnection* cconn = client->getClientConnection(); + GameConnection* newConnection = ConnectionServer::getGameConnection(transferControl.getGameServerId()); + if(cconn && newConnection) + { + //We have a client, and a game connection, so send the newClient message off to the game server in question. + //It will respond with a control assumed message. + NewClient const newClient(transferControl.getNetworkId(), cconn->getAccountName(), cconn->getRemoteAddress(), cconn->getIsSecure(), transferControl.getSkipLoadScreen(), cconn->getSUID(), &transferControl.getObservedObjects(), cconn->getGameFeatures(), cconn->getSubscriptionFeatures(), cconn->getEntitlementTotalTime(), cconn->getEntitlementEntitledTime(), cconn->getEntitlementTotalTimeSinceLastLogin(), cconn->getEntitlementEntitledTimeSinceLastLogin(), cconn->getBuddyPoints(), cconn->getConsumedRewardEvents(), cconn->getClaimedRewardItems(), cconn->isUsingAdminLogin(), cconn->getCanSkipTutorial()); + newConnection->send(newClient, true); + } + else + { + WARNING_STRICT_FATAL(true, ("A TransferControl message was received to transfer client %s to GameServer %lu, but that game server is no longer available. The client will be dropped.", transferControl.getNetworkId().getValueString().c_str(), transferControl.getGameServerId())); + DropClient const drop(transferControl.getNetworkId()); + send(drop, true); + } + } + } + else + { + DEBUG_WARNING(true, ("Received a TransferControllMessage but the client is no longer available. This might be a lost race between the connection server notifiying a game server that the client has disconnected, and the game server notifying the connection server that the client is transferring.")); + DropClient const drop(transferControl.getNetworkId()); + send(drop, true); + } + break; } - else + case constcrc("ReplyTransferData") : + case constcrc("ApplyTransferDataSuccess") : + case constcrc("ApplyTransferDataFail") : { - // a cluster running without session authentication stores - // account feature id information on the LoginServer, so - // pass request to the LoginServer (via CentralServer) - CentralConnection * const cc = ConnectionServer::getCentralConnection(); - if (cc) - cc->send(*msg, true); + GenericValueTypeMessage reply(ri); - delete msg; + IGNORE_RETURN(PseudoClientConnection::tryToDeliverMessageTo(reply.getValue().getCharacterId(), message)); + break; } - } - else if (m.isType("ClaimRewardsMessage")) - { - ClaimRewardsMessage * const msg = new ClaimRewardsMessage(ri); - - SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); - if ((msg->getAccountFeatureId() > 0) && sessionApiClient) + case constcrc("ChatEnterRoomValidationResponse") : { - // SessionApiClient will own (and delete) msg - sessionApiClient->getFeatures(msg->getStationId(), PlatformGameCode::SWG, msg); + GenericValueTypeMessage, unsigned int> > const reply(ri); + + Client* client = ConnectionServer::getClient(reply.getValue().first.first); + if (client && client->getClientConnection()) + { + client->getClientConnection()->handleChatEnterRoomValidationResponse(reply.getValue().second, reply.getValue().first.second); + } + break; } - else + case constcrc("ChatQueryRoomValidationResponse") : { - // a cluster running without session authentication stores - // account feature id information on the LoginServer, so - // pass request to the LoginServer (via CentralServer) - CentralConnection * const cc = ConnectionServer::getCentralConnection(); - if (cc) - cc->send(*msg, true); + GenericValueTypeMessage, unsigned int> > const reply(ri); - delete msg; + Client* client = ConnectionServer::getClient(reply.getValue().first.first); + if (client && client->getClientConnection()) + { + client->getClientConnection()->handleChatQueryRoomValidationResponse(reply.getValue().second, reply.getValue().first.second); + } + break; + } + case constcrc("AccountFeatureIdRequest") : + { + AccountFeatureIdRequest * const msg = new AccountFeatureIdRequest(ri); + + SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); + if (sessionApiClient) + { + // SessionApiClient will own (and delete) msg + sessionApiClient->getFeatures(msg->getTargetStationId(), msg->getGameCode(), msg); + } + else + { + // a cluster running without session authentication stores + // account feature id information on the LoginServer, so + // pass request to the LoginServer (via CentralServer) + CentralConnection * const cc = ConnectionServer::getCentralConnection(); + if (cc) + cc->send(*msg, true); + + delete msg; + } + break; + } + case constcrc("AdjustAccountFeatureIdRequest") : + { + AdjustAccountFeatureIdRequest * const msg = new AdjustAccountFeatureIdRequest(ri); + + SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); + if (sessionApiClient) + { + // SessionApiClient will own (and delete) msg + sessionApiClient->getFeatures(msg->getTargetStationId(), msg->getGameCode(), msg); + } + else + { + // a cluster running without session authentication stores + // account feature id information on the LoginServer, so + // pass request to the LoginServer (via CentralServer) + CentralConnection * const cc = ConnectionServer::getCentralConnection(); + if (cc) + cc->send(*msg, true); + + delete msg; + } + break; + } + case constcrc("ClaimRewardsMessage") : + { + ClaimRewardsMessage * const msg = new ClaimRewardsMessage(ri); + + SessionApiClient * const sessionApiClient = ConnectionServer::getSessionApiClient(); + if ((msg->getAccountFeatureId() > 0) && sessionApiClient) + { + // SessionApiClient will own (and delete) msg + sessionApiClient->getFeatures(msg->getStationId(), PlatformGameCode::SWG, msg); + } + else + { + // a cluster running without session authentication stores + // account feature id information on the LoginServer, so + // pass request to the LoginServer (via CentralServer) + CentralConnection * const cc = ConnectionServer::getCentralConnection(); + if (cc) + cc->send(*msg, true); + + delete msg; + } + break; } } } diff --git a/engine/server/application/ConnectionServer/src/shared/PseudoClientConnection.cpp b/engine/server/application/ConnectionServer/src/shared/PseudoClientConnection.cpp index 49553a04..21beeb2b 100755 --- a/engine/server/application/ConnectionServer/src/shared/PseudoClientConnection.cpp +++ b/engine/server/application/ConnectionServer/src/shared/PseudoClientConnection.cpp @@ -21,6 +21,8 @@ #include "sharedUtility/StartingLocationData.h" #include "sharedUtility/StartingLocationManager.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace PseudoClientConnectionNamespace @@ -231,171 +233,186 @@ void PseudoClientConnection::receiveMessage(const Archive::ByteStream & message) const GameNetworkMessage msg(ri); ri = message.begin(); - if(msg.isType("GameServerForLoginMessage")) - { - const GameServerForLoginMessage gameServerForLogin(ri); - LOG("CustomerService", ("CharacterTransfer: *** ConnectionServer: Received GameServerForLoginMessage for %d, server=%d\n", gameServerForLogin.getStationId(), gameServerForLogin.getServer())); - m_gameConnection = ConnectionServer::getGameConnection(gameServerForLogin.getServer()); - if(m_gameConnection) + const uint32 messageType = msg.getType(); + + switch(messageType) { + case constcrc("GameServerForLoginMessage") : { - NetworkId characterId = m_transferCharacterData.getCharacterId(); - unsigned int stationId = m_trackStationId; - if(m_transferCharacterData.getScriptDictionaryData().size()) + const GameServerForLoginMessage gameServerForLogin(ri); + LOG("CustomerService", ("CharacterTransfer: *** ConnectionServer: Received GameServerForLoginMessage for %d, server=%d\n", gameServerForLogin.getStationId(), gameServerForLogin.getServer())); + m_gameConnection = ConnectionServer::getGameConnection(gameServerForLogin.getServer()); + if(m_gameConnection) { - LOG("CustomerService", ("CharacterTransfer: Setting up login for destination server")); - characterId = m_transferCharacterData.getDestinationCharacterId(); + NetworkId characterId = m_transferCharacterData.getCharacterId(); + unsigned int stationId = m_trackStationId; + if(m_transferCharacterData.getScriptDictionaryData().size()) + { + LOG("CustomerService", ("CharacterTransfer: Setting up login for destination server")); + characterId = m_transferCharacterData.getDestinationCharacterId(); + } + std::vector > static const emptyStringVector; + NewClient m(characterId, "TransferServer", NetworkHandler::getHostName(), true, false, stationId, nullptr, 0, 0, 0, 0, 0, 0, 0, emptyStringVector, emptyStringVector, m_transferCharacterData.getCSToolId() != 0, true); + m_gameConnection->send(m, true); + LOG("CustomerService", ("CharacterTransfer: Sent NewClient(%s, \"TransferServer\", \"%s\", true, false, %d, nullptr, 0, 0)\n", characterId.getValueString().c_str(), NetworkHandler::getHostName().c_str(), stationId)); } - std::vector > static const emptyStringVector; - NewClient m(characterId, "TransferServer", NetworkHandler::getHostName(), true, false, stationId, NULL, 0, 0, 0, 0, 0, 0, 0, emptyStringVector, emptyStringVector, m_transferCharacterData.getCSToolId() != 0, true); - m_gameConnection->send(m, true); - LOG("CustomerService", ("CharacterTransfer: Sent NewClient(%s, \"TransferServer\", \"%s\", true, false, %d, NULL, 0, 0)\n", characterId.getValueString().c_str(), NetworkHandler::getHostName().c_str(), stationId)); + break; } - } - else if(msg.isType("TransferLoginCharacterToSourceServer")) - { - // this is a message that will create a new pseudoclient connection - LOG("CustomerService", ("CharacterTransfer: requestGameServerForLogin()")); - GenericValueTypeMessage loginRequest(ri); - const NetworkId & requestCharacterId = loginRequest.getValue().getCharacterId(); - if(requestCharacterId == NetworkId::cms_invalid || requestCharacterId != m_transferCharacterData.getCharacterId()) + case constcrc("TransferLoginCharacterToSourceServer") : { - LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Received a request to login to source server for %s, but a transfer for %s is already in progress. Sending failure.", loginRequest.getValue().toString().c_str(), m_transferCharacterData.toString().c_str())); + // this is a message that will create a new pseudoclient connection + LOG("CustomerService", ("CharacterTransfer: requestGameServerForLogin()")); + GenericValueTypeMessage loginRequest(ri); + const NetworkId & requestCharacterId = loginRequest.getValue().getCharacterId(); + if(requestCharacterId == NetworkId::cms_invalid || requestCharacterId != m_transferCharacterData.getCharacterId()) + { + LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Received a request to login to source server for %s, but a transfer for %s is already in progress. Sending failure.", loginRequest.getValue().toString().c_str(), m_transferCharacterData.toString().c_str())); + GenericValueTypeMessage fail("ReplyTransferDataFail", m_transferCharacterData); + ConnectionServer::sendToCentralProcess(fail); + } + else + { + requestGameServerForLogin(); + } + break; + } + case constcrc("TransferLoginCharacterToDestinationServer") : + { + GenericValueTypeMessage loginRequest(ri); + const NetworkId & requestCharacterId = loginRequest.getValue().getCharacterId(); + if(requestCharacterId == NetworkId::cms_invalid || requestCharacterId != m_transferCharacterData.getCharacterId()) + { + LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Received a request to login to destination server for %s, but a transfer for %s is already in progress. Sending failure.", loginRequest.getValue().toString().c_str(), m_transferCharacterData.toString().c_str())); + GenericValueTypeMessage fail("ReplyTransferDataFail", m_transferCharacterData); + ConnectionServer::sendToCentralProcess(fail); + } + else + { + // find a valid starting location + std::vector startingLocations; + StartingLocationData bestLocation; + startingLocations = StartingLocationManager::getLocations(); + if(! startingLocations.empty()) + { + bestLocation = *(startingLocations.begin()); + } + m_transferCharacterData.setScene(bestLocation.planet); + m_transferCharacterData.setStartingCoordinates(Vector(bestLocation.x, bestLocation.y, bestLocation.z)); + + // start character creation process + ConnectionCreateCharacter connectionCreate( + m_transferCharacterData.getDestinationStationId(), + Unicode::narrowToWide(m_transferCharacterData.getDestinationCharacterName()), + m_transferCharacterData.getObjectTemplateName(), + m_transferCharacterData.getScaleFactor(), + bestLocation.name, + m_transferCharacterData.getCustomizationData(), + m_transferCharacterData.getHairTemplateName(), + m_transferCharacterData.getHairAppearanceData(), + m_transferCharacterData.getProfession(), + false, + m_transferCharacterData.getBiography(), + false, + m_transferCharacterData.getSkillTemplate(), + m_transferCharacterData.getWorkingSkill(), + false, + true, + 0xFFFFFFFF); // assume all feature bits set, so that character creation will not be blocked by account features + LOG("CustomerService", ("CharacterTransfer: Sending ConnectionCreateCharacter to CentralServer : %s", m_transferCharacterData.toString().c_str())); + ConnectionServer::sendToCentralProcess(connectionCreate); + } + break; + } + case constcrc("CtsSrcCharWrongPlanet") : + { + LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Source character is not one of the 10 original ground planets. Sending failure for %s.", m_transferCharacterData.toString().c_str())); GenericValueTypeMessage fail("ReplyTransferDataFail", m_transferCharacterData); ConnectionServer::sendToCentralProcess(fail); + break; } - else + case constcrc("ReplyTransferData") : { + // the game server has responded with valid transfer information. + // upload the data to the transfer server (by way of the CentralServer) + // and disconnect the client since there's nothing more needed to be + // done here + GenericValueTypeMessage reply(ri); + m_transferCharacterData = reply.getValue(); + LOG("CustomerService", ("CharacterTransfer: Received ReplyTransferData %s", m_transferCharacterData.toString().c_str())); + + CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); + if(centralServerConnection) + { + const GenericValueTypeMessage transferReply("TransferReceiveDataFromGameServer", m_transferCharacterData); + centralServerConnection->send(transferReply, true); + } + + DropClient dropMsg(m_transferCharacterData.getCharacterId()); + if(m_gameConnection) + { + m_gameConnection->send(dropMsg, true); + } + delete this; + break; + } + case constcrc("ConnectionCreateCharacterSuccess") : + { + const ConnectionCreateCharacterSuccess success(ri); + // woohoo! character has been created on the server! + // Log the character back in, run the transfer scripts to + // apply data in the script dictionary associated with the character + LOG("CustomerService", ("CharacterTransfer: Received ConnectionCreateCharacterSuccess for %s", m_transferCharacterData.toString().c_str())); + m_transferCharacterData.setDestinationCharacterId(success.getNetworkId()); requestGameServerForLogin(); + s_pseudoClientConnectionMapByCharacterId[m_transferCharacterData.getDestinationCharacterId()] = this; + break; } - } - else if(msg.isType("TransferLoginCharacterToDestinationServer")) - { - GenericValueTypeMessage loginRequest(ri); - const NetworkId & requestCharacterId = loginRequest.getValue().getCharacterId(); - if(requestCharacterId == NetworkId::cms_invalid || requestCharacterId != m_transferCharacterData.getCharacterId()) + case constcrc("ConnectionCreateCharacterFailed") : { - LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Received a request to login to destination server for %s, but a transfer for %s is already in progress. Sending failure.", loginRequest.getValue().toString().c_str(), m_transferCharacterData.toString().c_str())); - GenericValueTypeMessage fail("ReplyTransferDataFail", m_transferCharacterData); - ConnectionServer::sendToCentralProcess(fail); - } - else - { - // find a valid starting location - std::vector startingLocations; - StartingLocationData bestLocation; - startingLocations = StartingLocationManager::getLocations(); - if(! startingLocations.empty()) + const ConnectionCreateCharacterFailed failed(ri); + LOG("CustomerService", ("CharacterTransfer: Received ConnectionCreateCharacterFailed [%s, %s] for %s", failed.getErrorMessage().getDebugString().c_str(), failed.getOptionalDetailedErrorMessage().c_str(), m_transferCharacterData.toString().c_str())); + s_pseudoClientConnectionMapByCharacterId[m_transferCharacterData.getDestinationCharacterId()] = this; + GenericValueTypeMessage reply("TransferCreateCharacterFailed", m_transferCharacterData); + CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); + if(centralServerConnection) { - bestLocation = *(startingLocations.begin()); + centralServerConnection->send(reply, true); } - m_transferCharacterData.setScene(bestLocation.planet); - m_transferCharacterData.setStartingCoordinates(Vector(bestLocation.x, bestLocation.y, bestLocation.z)); - - // start character creation process - ConnectionCreateCharacter connectionCreate( - m_transferCharacterData.getDestinationStationId(), - Unicode::narrowToWide(m_transferCharacterData.getDestinationCharacterName()), - m_transferCharacterData.getObjectTemplateName(), - m_transferCharacterData.getScaleFactor(), - bestLocation.name, - m_transferCharacterData.getCustomizationData(), - m_transferCharacterData.getHairTemplateName(), - m_transferCharacterData.getHairAppearanceData(), - m_transferCharacterData.getProfession(), - false, - m_transferCharacterData.getBiography(), - false, - m_transferCharacterData.getSkillTemplate(), - m_transferCharacterData.getWorkingSkill(), - false, - true, - 0xFFFFFFFF); // assume all feature bits set, so that character creation will not be blocked by account features - LOG("CustomerService", ("CharacterTransfer: Sending ConnectionCreateCharacter to CentralServer : %s", m_transferCharacterData.toString().c_str())); - ConnectionServer::sendToCentralProcess(connectionCreate); + break; } - } - else if(msg.isType("CtsSrcCharWrongPlanet")) - { - LOG("CustomerService", ("CharacterTransfer: *** ERROR *** Source character is not one of the 10 original ground planets. Sending failure for %s.", m_transferCharacterData.toString().c_str())); - GenericValueTypeMessage fail("ReplyTransferDataFail", m_transferCharacterData); - ConnectionServer::sendToCentralProcess(fail); - } - else if(msg.isType("ReplyTransferData")) - { - // the game server has responded with valid transfer information. - // upload the data to the transfer server (by way of the CentralServer) - // and disconnect the client since there's nothing more needed to be - // done here - GenericValueTypeMessage reply(ri); - m_transferCharacterData = reply.getValue(); - LOG("CustomerService", ("CharacterTransfer: Received ReplyTransferData %s", m_transferCharacterData.toString().c_str())); - - CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); - if(centralServerConnection) + case constcrc("ApplyTransferDataSuccess") : { - const GenericValueTypeMessage transferReply("TransferReceiveDataFromGameServer", m_transferCharacterData); - centralServerConnection->send(transferReply, true); + GenericValueTypeMessage success(ri); + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from GameServer! %s", success.getValue().toString().c_str())); + CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); + if(centralServerConnection) + { + centralServerConnection->send(success, true); + } + break; } - - DropClient dropMsg(m_transferCharacterData.getCharacterId()); - if(m_gameConnection) + case constcrc("ApplyTransferDataFail") : { - m_gameConnection->send(dropMsg, true); + GenericValueTypeMessage fail(ri); + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from GameServer! %s", fail.getValue().toString().c_str())); + CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); + if(centralServerConnection) + { + centralServerConnection->send(fail, true); + } + break; } - delete this; - } - else if(msg.isType("ConnectionCreateCharacterSuccess")) - { - const ConnectionCreateCharacterSuccess success(ri); - // woohoo! character has been created on the server! - // Log the character back in, run the transfer scripts to - // apply data in the script dictionary associated with the character - LOG("CustomerService", ("CharacterTransfer: Received ConnectionCreateCharacterSuccess for %s", m_transferCharacterData.toString().c_str())); - m_transferCharacterData.setDestinationCharacterId(success.getNetworkId()); - requestGameServerForLogin(); - s_pseudoClientConnectionMapByCharacterId[m_transferCharacterData.getDestinationCharacterId()] = this; - } - else if(msg.isType("ConnectionCreateCharacterFailed")) - { - const ConnectionCreateCharacterFailed failed(ri); - LOG("CustomerService", ("CharacterTransfer: Received ConnectionCreateCharacterFailed [%s, %s] for %s", failed.getErrorMessage().getDebugString().c_str(), failed.getOptionalDetailedErrorMessage().c_str(), m_transferCharacterData.toString().c_str())); - s_pseudoClientConnectionMapByCharacterId[m_transferCharacterData.getDestinationCharacterId()] = this; - GenericValueTypeMessage reply("TransferCreateCharacterFailed", m_transferCharacterData); - CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); - if(centralServerConnection) + case constcrc("ReplyBankCTSLoaded") : { - centralServerConnection->send(reply, true); + LOG("CustomerService", ("CharacterTransfer: Received ReplyBankCTSLoaded from GameServer!")); + onBankLoaded(); + break; } - } - else if(msg.isType("ApplyTransferDataSuccess")) - { - GenericValueTypeMessage success(ri); - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from GameServer! %s", success.getValue().toString().c_str())); - CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); - if(centralServerConnection) + case constcrc("PackedHousesLoaded") : { - centralServerConnection->send(success, true); + onPackedHousesLoaded(); + break; } } - else if(msg.isType("ApplyTransferDataFail")) - { - GenericValueTypeMessage fail(ri); - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from GameServer! %s", fail.getValue().toString().c_str())); - CentralConnection * centralServerConnection = ConnectionServer::getCentralConnection(); - if(centralServerConnection) - { - centralServerConnection->send(fail, true); - } - } - else if(msg.isType("ReplyBankCTSLoaded")) - { - LOG("CustomerService", ("CharacterTransfer: Received ReplyBankCTSLoaded from GameServer!")); - onBankLoaded(); - } - else if(msg.isType("PackedHousesLoaded")) - { - onPackedHousesLoaded(); - } } //----------------------------------------------------------------------- @@ -433,7 +450,9 @@ bool PseudoClientConnection::tryToDeliverMessageTo(unsigned int stationId, const ri = message.begin(); bool result = false; - if(msg.isType("TransferLoginCharacterToSourceServer") || msg.isType("TransferLoginCharacterToDestinationServer")) + const uint32 messageType = msg.getType(); + + if(messageType == constcrc("TransferLoginCharacterToSourceServer") || messageType == constcrc("TransferLoginCharacterToDestinationServer")) { // this is a message that will create a new pseudoclient connection const GenericValueTypeMessage login(ri); diff --git a/engine/server/application/ConnectionServer/src/shared/SessionApiClient.cpp b/engine/server/application/ConnectionServer/src/shared/SessionApiClient.cpp index dba551e9..fd2c41e5 100755 --- a/engine/server/application/ConnectionServer/src/shared/SessionApiClient.cpp +++ b/engine/server/application/ConnectionServer/src/shared/SessionApiClient.cpp @@ -19,6 +19,8 @@ #include "sharedGame/PlatformFeatureBits.h" #include "sharedLog/Log.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include #include #include @@ -303,23 +305,35 @@ void SessionApiClient::OnGetFeatures(const apiTrackingNumber trackingNumber, if (i != ms_getFeaturesTrackingNumberMap.end()) { bool reuseMessage = false; - AccountFeatureIdRequest const * accountFeatureIdRequest = NULL; - AdjustAccountFeatureIdRequest const * adjustAccountFeatureIdRequest = NULL; - AdjustAccountFeatureIdResponse * adjustAccountFeatureIdResponse = NULL; - ClaimRewardsMessage * claimRewardsMessage = NULL; + AccountFeatureIdRequest const * accountFeatureIdRequest = nullptr; + AdjustAccountFeatureIdRequest const * adjustAccountFeatureIdRequest = nullptr; + AdjustAccountFeatureIdResponse * adjustAccountFeatureIdResponse = nullptr; + ClaimRewardsMessage * claimRewardsMessage = nullptr; - if (i->second->isType("AccountFeatureIdRequest")) - accountFeatureIdRequest = dynamic_cast(i->second); - else if (i->second->isType("AdjustAccountFeatureIdRequest")) - adjustAccountFeatureIdRequest = dynamic_cast(i->second); - else if (i->second->isType("AdjustAccountFeatureIdResponse")) - adjustAccountFeatureIdResponse = dynamic_cast(i->second); - else if (i->second->isType("ClaimRewardsMessage")) - claimRewardsMessage = dynamic_cast(i->second); + const uint32 msgType = i->second->getType(); + + switch(msgType) { + case constcrc("AccountFeatureIdRequest") : { + accountFeatureIdRequest = dynamic_cast(i->second); + break; + } + case constcrc("AdjustAccountFeatureIdRequest") : { + adjustAccountFeatureIdRequest = dynamic_cast(i->second); + break; + } + case constcrc("AdjustAccountFeatureIdResponse") : { + adjustAccountFeatureIdResponse = dynamic_cast(i->second); + break; + } + case constcrc("ClaimRewardsMessage") : { + claimRewardsMessage = dynamic_cast(i->second); + break; + } + } if (result == RESULT_SUCCESS) { - ClientConnection * clientConnection = NULL; + ClientConnection * clientConnection = nullptr; if (accountFeatureIdRequest) clientConnection = ConnectionServer::getClientConnection(accountFeatureIdRequest->getTargetStationId()); else if (adjustAccountFeatureIdRequest) @@ -391,7 +405,7 @@ void SessionApiClient::OnGetFeatures(const apiTrackingNumber trackingNumber, else { // if account already has the feature, adjust it, otherwise add the feature - LoginAPI::Feature const * existingFeature = NULL; + LoginAPI::Feature const * existingFeature = nullptr; for (unsigned k = 0; k < featureCount; ++k) { @@ -444,7 +458,7 @@ void SessionApiClient::OnGetFeatures(const apiTrackingNumber trackingNumber, } else { - LoginAPI::Feature const * newlyAddedFeature = NULL; + LoginAPI::Feature const * newlyAddedFeature = nullptr; for (unsigned k = 0; k < featureCount; ++k) { @@ -506,7 +520,7 @@ void SessionApiClient::OnGetFeatures(const apiTrackingNumber trackingNumber, else { // see if account already has the required feature - LoginAPI::Feature const * existingFeature = NULL; + LoginAPI::Feature const * existingFeature = nullptr; for (unsigned k = 0; k < featureCount; ++k) { @@ -904,7 +918,7 @@ void SessionApiClient::validateClient (ClientConnection* client, const std::stri void SessionApiClient::startPlay(const ClientConnection& client) { - IGNORE_RETURN(SessionStartPlay(client.getSessionId().c_str(), ConfigConnectionServer::getClusterName(), client.getCharacterName().c_str(), NULL)); + IGNORE_RETURN(SessionStartPlay(client.getSessionId().c_str(), ConfigConnectionServer::getClusterName(), client.getCharacterName().c_str(), nullptr)); } //------------------------------------------------------------ diff --git a/engine/server/application/ConnectionServer/src/win32/FirstConnectionServer.cpp b/engine/server/application/ConnectionServer/src/win32/FirstConnectionServer.cpp new file mode 100644 index 00000000..137cad41 --- /dev/null +++ b/engine/server/application/ConnectionServer/src/win32/FirstConnectionServer.cpp @@ -0,0 +1 @@ +#include "FirstConnectionServer.h" diff --git a/engine/server/application/ConnectionServer/src/win32/WinMain.cpp b/engine/server/application/ConnectionServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..236a8ebf --- /dev/null +++ b/engine/server/application/ConnectionServer/src/win32/WinMain.cpp @@ -0,0 +1,58 @@ +#include "FirstConnectionServer.h" +#include "ConfigConnectionServer.h" +#include "ConnectionServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/PerThreadData.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" + +#include + +int main(int argc, char ** argv) +{ + // command line hack + std::string cmdLine; + for(int i = 1; i < argc; ++i) + { + cmdLine += argv[i]; + if(i + 1 < argc) + { + cmdLine += " "; + } + } + + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + +//-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + +// setupFoundationData.hInstance = hInstance; + setupFoundationData.commandLine = cmdLine.c_str(); + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install (setupFoundationData); + SetupSharedFile::install(false); + SetupSharedCompression::install(); + + SetupSharedNetworkMessages::install(); + SetupSharedRandom::install(int(time(NULL))); + + //-- setup game server + ConfigConnectionServer::install (); + + ConnectionServer::install(); + //-- run game + SetupSharedFoundation::callbackWithExceptionHandling(ConnectionServer::run); + ConnectionServer::remove(); + ConfigConnectionServer::remove(); + SetupSharedFoundation::remove(); + PerThreadData::threadRemove(); + return 0; +} diff --git a/engine/server/application/CustomerServiceServer/src/linux/main.cpp b/engine/server/application/CustomerServiceServer/src/linux/main.cpp index 7cdc4016..35924a2c 100755 --- a/engine/server/application/CustomerServiceServer/src/linux/main.cpp +++ b/engine/server/application/CustomerServiceServer/src/linux/main.cpp @@ -30,7 +30,7 @@ int main(int argc, char *argv[]) SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(static_cast(time(NULL))); + SetupSharedRandom::install(static_cast(time(nullptr))); Os::setProgramName("CustomerServiceServer"); ConfigCustomerServiceServer::install(); NetworkHandler::install(); diff --git a/engine/server/application/CustomerServiceServer/src/shared/CentralServerConnection.cpp b/engine/server/application/CustomerServiceServer/src/shared/CentralServerConnection.cpp index 68a2ded3..8e74a876 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/CentralServerConnection.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/CentralServerConnection.cpp @@ -49,7 +49,7 @@ void CentralServerConnection::onConnectionOpened() Service *chatServerService = CustomerServiceServer::getInstance().getChatServerService(); - if (chatServerService != NULL) + if (chatServerService != nullptr) { const std::string address(chatServerService->getBindAddress()); const int port = chatServerService->getBindPort(); @@ -62,7 +62,7 @@ void CentralServerConnection::onConnectionOpened() } else { - LOG("CentralServerConnection", ("onConnectionOpened() ERROR: ChatServerService is NULL")); + LOG("CentralServerConnection", ("onConnectionOpened() ERROR: ChatServerService is nullptr")); } } @@ -71,7 +71,7 @@ void CentralServerConnection::onConnectionOpened() Service *gameServerService = CustomerServiceServer::getInstance().getGameServerService(); - if (gameServerService != NULL) + if (gameServerService != nullptr) { const std::string address(gameServerService->getBindAddress()); const int port = gameServerService->getBindPort(); @@ -84,7 +84,7 @@ void CentralServerConnection::onConnectionOpened() } else { - LOG("CentralServerConnection", ("onConnectionOpened() ERROR: GameServerService is NULL")); + LOG("CentralServerConnection", ("onConnectionOpened() ERROR: GameServerService is nullptr")); } } } diff --git a/engine/server/application/CustomerServiceServer/src/shared/ChatServerConnection.cpp b/engine/server/application/CustomerServiceServer/src/shared/ChatServerConnection.cpp index 239a4630..30a167b1 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/ChatServerConnection.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/ChatServerConnection.cpp @@ -64,13 +64,13 @@ void ChatServerConnection::sendTo(GameNetworkMessage const &message) { LOG("ChatServerConnection", ("sendTo() message(%s)", message.getCmdName().c_str())); - if (s_connection != NULL) + if (s_connection != nullptr) { s_connection->send(message, true); } else { - LOG("ChatServerConnection", ("sendTo() Unable to send, NULL ChatServerConnection")); + LOG("ChatServerConnection", ("sendTo() Unable to send, nullptr ChatServerConnection")); } } diff --git a/engine/server/application/CustomerServiceServer/src/shared/ConfigCustomerServiceServer.cpp b/engine/server/application/CustomerServiceServer/src/shared/ConfigCustomerServiceServer.cpp index eff05cf2..d0e93110 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/ConfigCustomerServiceServer.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/ConfigCustomerServiceServer.cpp @@ -12,19 +12,19 @@ namespace ConfigCustomerServiceServerNamespace { - const char * s_clusterName = NULL; - const char * s_centralServerAddress = NULL; + const char * s_clusterName = nullptr; + const char * s_centralServerAddress = nullptr; int s_centralServerPort = 0; - const char * s_gameCode = NULL; - const char * s_csServerAddress = NULL; + const char * s_gameCode = nullptr; + const char * s_csServerAddress = nullptr; int s_csServerPort = 0; int s_maxPacketsPerSecond = 50; int s_requestTimeoutSeconds = 300; int s_maxAllowedNumberOfTickets = 1; int s_gameServicePort = 0; int s_chatServicePort = 0; - const char* s_chatServiceBindInterface = NULL; - const char* s_gameServiceBindInterface = NULL; + const char* s_chatServiceBindInterface = nullptr; + const char* s_gameServiceBindInterface = nullptr; bool s_writeTicketToBugLog = false; }; diff --git a/engine/server/application/CustomerServiceServer/src/shared/ConnectionServerConnection.cpp b/engine/server/application/CustomerServiceServer/src/shared/ConnectionServerConnection.cpp index 3031dd2a..1e70e7a5 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/ConnectionServerConnection.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/ConnectionServerConnection.cpp @@ -24,6 +24,8 @@ #include "sharedNetwork/NetworkSetupData.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- ConnectionServerConnection::ConnectionServerConnection(const std::string & a, const unsigned short p) : @@ -62,11 +64,13 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message) ri = message.begin(); - if (m.isType("GameClientMessage")) + if (m.getType() == constcrc("GameClientMessage")) { GameClientMessage c(ri); Archive::ReadIterator cri = c.getByteStream().begin(); GameNetworkMessage cm(cri); + + const uint32 messageType = cm.getType(); std::vector::const_iterator i; for (i = c.getDistributionList().begin(); i != c.getDistributionList().end(); ++i) @@ -75,68 +79,81 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message) NetworkId const &networkId = (*i); - if (cm.isType("RequestCategoriesMessage")) - { - RequestCategoriesMessage message(cri); - CustomerServiceServer::getInstance().requestCategories(networkId, message.getLanguage()); - } - else if (cm.isType("ConnectPlayerMessage")) - { - ConnectPlayerMessage message(cri); - CustomerServiceServer::getInstance().requestRegisterCharacter(networkId, this, message.getStationId()); - } - else if (cm.isType("DisconnectPlayerMessage")) - { - CustomerServiceServer::getInstance().requestUnRegisterCharacter(networkId); - } - else if (cm.isType("CreateTicketMessage")) - { - CreateTicketMessage message(cri); + switch(messageType) { + case constcrc("RequestCategoriesMessage") : + { + RequestCategoriesMessage message(cri); + CustomerServiceServer::getInstance().requestCategories(networkId, message.getLanguage()); + break; + } + case constcrc("ConnectPlayerMessage") : + { + ConnectPlayerMessage message(cri); + CustomerServiceServer::getInstance().requestRegisterCharacter(networkId, this, message.getStationId()); + break; + } + case constcrc("DisconnectPlayerMessage") : + { + CustomerServiceServer::getInstance().requestUnRegisterCharacter(networkId); + break; + } + case constcrc("CreateTicketMessage") : + { + CreateTicketMessage message(cri); - CustomerServiceServer::getInstance().createTicket(networkId, - message.getStationId(), message.getCharacterName(), - message.getCategory(), message.getSubCategory(), - message.getDetails(), message.getHiddenDetails(), - message.getHarassingPlayerName(), - message.getLanguage(), message.isBug() - ); - } - else if (cm.isType("AppendCommentMessage")) - { - AppendCommentMessage message(cri); - CustomerServiceServer::getInstance().appendComment(networkId, message.getStationId(), message.getCharacterName(), message.getTicketId(), message.getComment()); - } - else if (cm.isType("CancelTicketMessage")) - { - CancelTicketMessage message(cri); - CustomerServiceServer::getInstance().cancelTicket(networkId, message.getStationId(), message.getTicketId(), message.getComment()); - } - else if (cm.isType("GetTicketsMessage")) - { - GetTicketsMessage message(cri); - CustomerServiceServer::getInstance().getTickets(networkId, message.getStationId()); - } - else if (cm.isType("GetCommentsMessage")) - { - GetCommentsMessage message(cri); - CustomerServiceServer::getInstance().getComments(networkId, - message.getTicketId()); - } - else if (cm.isType("SearchKnowledgeBaseMessage")) - { - SearchKnowledgeBaseMessage message(cri); - CustomerServiceServer::getInstance().searchKnowledgeBase(networkId, message.getSearchString(), message.getLanguage()); - } - else if (cm.isType("GetArticleMessage")) - { - GetArticleMessage message(cri); - CustomerServiceServer::getInstance().getArticle(networkId, message.getId(), message.getLanguage()); - } - else if (cm.isType("NewTicketActivityMessage")) - { - NewTicketActivityMessage message(cri); + CustomerServiceServer::getInstance().createTicket(networkId, + message.getStationId(), message.getCharacterName(), + message.getCategory(), message.getSubCategory(), + message.getDetails(), message.getHiddenDetails(), + message.getHarassingPlayerName(), + message.getLanguage(), message.isBug() + ); + break; + } + case constcrc("AppendCommentMessage") : + { + AppendCommentMessage message(cri); + CustomerServiceServer::getInstance().appendComment(networkId, message.getStationId(), message.getCharacterName(), message.getTicketId(), message.getComment()); + break; + } + case constcrc("CancelTicketMessage") : + { + CancelTicketMessage message(cri); + CustomerServiceServer::getInstance().cancelTicket(networkId, message.getStationId(), message.getTicketId(), message.getComment()); + break; + } + case constcrc("GetTicketsMessage") : + { + GetTicketsMessage message(cri); + CustomerServiceServer::getInstance().getTickets(networkId, message.getStationId()); + break; + } + case constcrc("GetCommentsMessage") : + { + GetCommentsMessage message(cri); + CustomerServiceServer::getInstance().getComments(networkId, + message.getTicketId()); + break; + } + case constcrc("SearchKnowledgeBaseMessage") : + { + SearchKnowledgeBaseMessage message(cri); + CustomerServiceServer::getInstance().searchKnowledgeBase(networkId, message.getSearchString(), message.getLanguage()); + break; + } + case constcrc("GetArticleMessage") : + { + GetArticleMessage message(cri); + CustomerServiceServer::getInstance().getArticle(networkId, message.getId(), message.getLanguage()); + break; + } + case constcrc("NewTicketActivityMessage") : + { + NewTicketActivityMessage message(cri); - CustomerServiceServer::getInstance().requestNewTicketActivity(networkId, message.getStationId()); + CustomerServiceServer::getInstance().requestNewTicketActivity(networkId, message.getStationId()); + break; + } } } } diff --git a/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceInterface.cpp b/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceInterface.cpp index e1e93c31..333117be 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceInterface.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceInterface.cpp @@ -38,7 +38,7 @@ using namespace CSAssist; /////////////////////////////////////////////////////////////////////////////// CustomerServiceInterface::ClientInfo::ClientInfo() - : m_connection(NULL) + : m_connection(nullptr) , m_stationUserId(0) , m_ticketCount(-1) , m_pendingTicketCount(0) @@ -71,10 +71,10 @@ CustomerServiceInterface::~CustomerServiceInterface() delete m_japaneseCategoryList; delete m_clientConnectionMap; - m_clientConnectionMap = NULL; + m_clientConnectionMap = nullptr; delete m_suidToNetworkIdMap; - m_suidToNetworkIdMap = NULL; + m_suidToNetworkIdMap = nullptr; } //----------------------------------------------------------------------- @@ -97,8 +97,8 @@ void CustomerServiceInterface::OnConnectCSAssist( } m_connectionToBackEndEstablised = true; - m_englishCategoryTrack = requestGetIssueHierarchy(NULL, Unicode::narrowToWide("Default").data(), Unicode::narrowToWide("en").data());; - m_japaneseCategoryTrack = requestGetIssueHierarchy(NULL, Unicode::narrowToWide("Default").data(), Unicode::narrowToWide("ja").data());; + m_englishCategoryTrack = requestGetIssueHierarchy(nullptr, Unicode::narrowToWide("Default").data(), Unicode::narrowToWide("en").data());; + m_japaneseCategoryTrack = requestGetIssueHierarchy(nullptr, Unicode::narrowToWide("Default").data(), Unicode::narrowToWide("ja").data());; } } @@ -117,7 +117,7 @@ void CustomerServiceInterface::OnConnectRejectedCSAssist(const CSAssistGameAPITr void CustomerServiceInterface::parseIssueChild(CategoryList & categoryList, xmlNodePtr childPtr) { - static CustomerServiceCategory *currentCategory = NULL; + static CustomerServiceCategory *currentCategory = nullptr; xmlNodePtr child = childPtr->children; //start element @@ -142,19 +142,19 @@ void CustomerServiceInterface::parseIssueChild(CategoryList & categoryList, xmlN val = reinterpret_cast(xmlGetProp(childPtr, (const unsigned char *)"isBugType")); - bool const isBugType = (val != NULL) && (strcmp(val, "true") == 0); + bool const isBugType = (val != nullptr) && (strcmp(val, "true") == 0); // Check for service type val = reinterpret_cast(xmlGetProp(childPtr, (const unsigned char *)"isServiceType")); - bool const isServiceType = (val != NULL) && (strcmp(val, "true") == 0); + bool const isServiceType = (val != nullptr) && (strcmp(val, "true") == 0); // Check if valid val = reinterpret_cast(xmlGetProp(childPtr, (const unsigned char *)"invalid")); - bool const invalid = (val != NULL) && (strcmp(val, "true") == 0); + bool const invalid = (val != nullptr) && (strcmp(val, "true") == 0); if (!invalid) { @@ -187,9 +187,9 @@ void CustomerServiceInterface::parseIssueChild(CategoryList & categoryList, xmlN } } - while (child != NULL) + while (child != nullptr) { - if (child->name != NULL) + if (child->name != nullptr) { parseIssueChild(categoryList, child); } @@ -204,7 +204,7 @@ void CustomerServiceInterface::parseIssueChild(CategoryList & categoryList, xmlN if (currentCategory) { delete currentCategory; - currentCategory = NULL; + currentCategory = nullptr; } } @@ -215,13 +215,13 @@ void CustomerServiceInterface::parseIssueChild(CategoryList & categoryList, xmlN void CustomerServiceInterface::parseIssueHierarchy(CategoryList & categoryList, Unicode::String const & xmlData) { - xmlDocPtr xmlInfo = NULL; + xmlDocPtr xmlInfo = nullptr; Unicode::UTF8String xmlDataUtf8(Unicode::wideToUTF8(xmlData)); - if ((xmlInfo = xmlParseMemory(xmlDataUtf8.c_str(), xmlDataUtf8.length())) != NULL) + if ((xmlInfo = xmlParseMemory(xmlDataUtf8.c_str(), xmlDataUtf8.length())) != nullptr) { xmlNodePtr xmlCurrent = xmlDocGetRootElement(xmlInfo); - if (xmlCurrent != NULL) + if (xmlCurrent != nullptr) { parseIssueChild(categoryList, xmlCurrent); } @@ -247,7 +247,7 @@ void CustomerServiceInterface::OnGetIssueHierarchy( return; } - if (hierarchyBody != NULL) + if (hierarchyBody != nullptr) { if (track == m_englishCategoryTrack) { @@ -266,7 +266,7 @@ void CustomerServiceInterface::OnGetIssueHierarchy( } else { - LOG("CSServer", ("ERROR: NULL hierarchy returned from platform...why did this happen?", track, modifyData, result, getErrorString(result))); + LOG("CSServer", ("ERROR: nullptr hierarchy returned from platform...why did this happen?", track, modifyData, result, getErrorString(result))); } } @@ -282,9 +282,9 @@ void CustomerServiceInterface::OnCreateTicket( CreateTicketResponseMessage message(result, ticket); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnCreateTicket() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); + LOG("CSServer", ("OnCreateTicket() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { if (result == CSASSIST_RESULT_SUCCESS) { @@ -296,7 +296,7 @@ void CustomerServiceInterface::OnCreateTicket( sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -312,14 +312,14 @@ void CustomerServiceInterface::OnAppendTicketComment( AppendCommentResponseMessage message(result, ticket); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnAppendTicketComment() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); + LOG("CSServer", ("OnAppendTicketComment() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -335,9 +335,9 @@ void CustomerServiceInterface::OnCancelTicket( CancelTicketResponseMessage message(result, ticket); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnCancelTicket() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); + LOG("CSServer", ("OnCancelTicket() track(%i) result(%i) (%s) networkId(%s) ticketId(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", ticket)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { if (result == CSASSIST_RESULT_SUCCESS) { @@ -347,7 +347,7 @@ void CustomerServiceInterface::OnCancelTicket( sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -378,9 +378,9 @@ void CustomerServiceInterface::OnGetTicketByCharacter( GetTicketsResponseMessage message(result, totalNumber, tickets); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnGetTicketByCharacter() track(%i) result(%i) (%s) networkId(%s) totalNumber(%i) numberReturned(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", totalNumber, numberReturned)); + LOG("CSServer", ("OnGetTicketByCharacter() track(%i) result(%i) (%s) networkId(%s) totalNumber(%i) numberReturned(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", totalNumber, numberReturned)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { // Save the number of tickets this player has @@ -396,7 +396,7 @@ void CustomerServiceInterface::OnGetTicketByCharacter( sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -423,14 +423,14 @@ void CustomerServiceInterface::OnGetTicketComments( const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnGetTicketComments() track(%i) result(%i) (%s) networkId(%s) numberRead(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", numberRead)); + LOG("CSServer", ("OnGetTicketComments() track(%i) result(%i) (%s) networkId(%s) numberRead(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", numberRead)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -455,14 +455,14 @@ void CustomerServiceInterface::OnSearchKB( SearchKnowledgeBaseResponseMessage message(result, searchResultsVector); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnSearchKB() track(%i) result(%i) (%s) networkId(%s) numberRead(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", numberRead)); + LOG("CSServer", ("OnSearchKB() track(%i) result(%i) (%s) networkId(%s) numberRead(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", numberRead)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -482,12 +482,12 @@ void CustomerServiceInterface::OnGetKBArticle( { GetArticleResponseMessage message(result, Unicode::String(articleBody)); const NetworkId *tmpNetworkId = reinterpret_cast(userData); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } } @@ -501,7 +501,7 @@ void CustomerServiceInterface::OnIssueHierarchyChanged( { LOG("CSServer", ("OnIssueHierarchyChanged()")); - requestGetIssueHierarchy(NULL, version, language); + requestGetIssueHierarchy(nullptr, version, language); } //----------------------------------------------------------------------- @@ -512,9 +512,9 @@ void CustomerServiceInterface::OnNewTicketActivity(const CSAssistGameAPITrack tr const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnNewTicketActivity() track(%i) result(%i) (%s) networkId(%s) activity(%s) ticket count(%i)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA", NewActivityFlag ? "yes" : "no", HasTickets)); + LOG("CSServer", ("OnNewTicketActivity() track(%i) result(%i) (%s) networkId(%s) activity(%s) ticket count(%i)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA", NewActivityFlag ? "yes" : "no", HasTickets)); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { // Save the number of tickets this player has @@ -530,7 +530,7 @@ void CustomerServiceInterface::OnNewTicketActivity(const CSAssistGameAPITrack tr sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -540,12 +540,12 @@ void CustomerServiceInterface::OnMarkTicketRead(const CSAssistGameAPITrack track { const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnMarkTicketRead() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA")); + LOG("CSServer", ("OnMarkTicketRead() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA")); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -575,16 +575,16 @@ void CustomerServiceInterface::OnRegisterCharacter(const CSAssistGameAPITrack tr { const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnRegisterCharacter() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA")); + LOG("CSServer", ("OnRegisterCharacter() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA")); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { ConnectPlayerResponseMessage message(result); sendToClient(*tmpNetworkId, message); delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -594,9 +594,9 @@ void CustomerServiceInterface::OnUnRegisterCharacter(const CSAssistGameAPITrack { const NetworkId *tmpNetworkId = reinterpret_cast(userData); - LOG("CSServer", ("OnUnRegisterCharacter() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != NULL) ? tmpNetworkId->getValueString().c_str() : "NA")); + LOG("CSServer", ("OnUnRegisterCharacter() track(%i) result(%i) (%s) networkId(%s)", track, result, getErrorString(result), (tmpNetworkId != nullptr) ? tmpNetworkId->getValueString().c_str() : "NA")); - if (tmpNetworkId != NULL) + if (tmpNetworkId != nullptr) { // If the player was successfully unregistered, remove the local cached reference @@ -606,7 +606,7 @@ void CustomerServiceInterface::OnUnRegisterCharacter(const CSAssistGameAPITrack } delete tmpNetworkId; - tmpNetworkId = NULL; + tmpNetworkId = nullptr; } } @@ -708,7 +708,7 @@ void CustomerServiceInterface::sendToClient(const NetworkId &player, const GameN } else { - LOG("CSServer", ("sendToClient() Connection is NULL: networkId(%s) cmdName(%s)", player.getValueString().c_str(), message.getCmdName().c_str())); + LOG("CSServer", ("sendToClient() Connection is nullptr: networkId(%s) cmdName(%s)", player.getValueString().c_str(), message.getCmdName().c_str())); } } else @@ -779,7 +779,7 @@ void CustomerServiceInterface::requestUnRegisterCharacter(const NetworkId &reque LOG("CSServer", ("requestUnRegisterCharacter() networkId(%s) suid(%i)", requester.getValueString().c_str(), suid)); NetworkId *tmpNetworkId = new NetworkId(requester); - CSAssistGameAPI::requestUnRegisterCharacter(reinterpret_cast(tmpNetworkId), suid, NULL); + CSAssistGameAPI::requestUnRegisterCharacter(reinterpret_cast(tmpNetworkId), suid, nullptr); } else { diff --git a/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceServer.cpp b/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceServer.cpp index 7beaacc5..ba68856b 100755 --- a/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceServer.cpp +++ b/engine/server/application/CustomerServiceServer/src/shared/CustomerServiceServer.cpp @@ -49,7 +49,7 @@ namespace CustomerServiceServerNamespace using namespace CustomerServiceServerNamespace; -CustomerServiceServer *CustomerServiceServer::m_instance = NULL; +CustomerServiceServer *CustomerServiceServer::m_instance = nullptr; /////////////////////////////////////////////////////////////////////////////// // @@ -83,12 +83,12 @@ CustomerServiceServer::PendingTicket::PendingTicket() CustomerServiceServer::CustomerServiceServer() : m_callback(new MessageDispatch::Callback), -m_centralServerConnection(NULL), +m_centralServerConnection(nullptr), m_connectionServerSet(new ConnectionServerSet), m_done(false), m_csInterface(ConfigCustomerServiceServer::getCustomerServiceServerAddress(), ConfigCustomerServiceServer::getCustomerServiceServerPort(), ConfigCustomerServiceServer::getRequestTimeoutSeconds()), -m_gameServerService(NULL), -m_chatServerService(NULL), +m_gameServerService(nullptr), +m_chatServerService(nullptr), m_nextSequenceId(0), m_pendingTicketList(new PendingTicketList) { @@ -103,7 +103,7 @@ m_pendingTicketList(new PendingTicketList) m_callback->connect(*this, &CustomerServiceServer::onEnumerateServers); char text[512]; - snprintf(text, sizeof(text), "CustomerServiceServer() - ServerName(%s) ServerPort(%i) GameCode(%s)", ConfigCustomerServiceServer::getCustomerServiceServerAddress(), ConfigCustomerServiceServer::getCustomerServiceServerPort(), ConfigCustomerServiceServer::getGameCode()); + snprintf(text, 512, "CustomerServiceServer() - ServerName(%s) ServerPort(%i) GameCode(%s)", ConfigCustomerServiceServer::getCustomerServiceServerAddress(), ConfigCustomerServiceServer::getCustomerServiceServerPort(), ConfigCustomerServiceServer::getGameCode()); REPORT_LOG(true, ("%s\n", text)); LOG("CSServer", ("%s", text)); @@ -113,7 +113,7 @@ m_pendingTicketList(new PendingTicketList) m_csInterface.setMaxPacketsPerSecond(ConfigCustomerServiceServer::getMaxPacketsPerSecond()); - m_csInterface.connectCSAssist(NULL, + m_csInterface.connectCSAssist(nullptr, Unicode::narrowToWide(ConfigCustomerServiceServer::getGameCode()).data(), Unicode::narrowToWide(ConfigCustomerServiceServer::getClusterName()).data()); @@ -148,19 +148,19 @@ CustomerServiceServer::~CustomerServiceServer() m_centralServerConnection->disconnect(); delete m_callback; - m_callback = NULL; + m_callback = nullptr; delete m_connectionServerSet; - m_connectionServerSet = NULL; + m_connectionServerSet = nullptr; delete m_gameServerService; - m_gameServerService = NULL; + m_gameServerService = nullptr; delete m_chatServerService; - m_chatServerService = NULL; + m_chatServerService = nullptr; delete m_pendingTicketList; - m_pendingTicketList = NULL; + m_pendingTicketList = nullptr; MetricsManager::remove(); delete s_customerServiceServerMetricsData; @@ -233,7 +233,7 @@ void CustomerServiceServer::update() CustomerServiceServer &CustomerServiceServer::getInstance() { - if (m_instance == NULL) + if (m_instance == nullptr) { m_instance = new CustomerServiceServer; } @@ -405,7 +405,7 @@ void CustomerServiceServer::getTickets( NetworkId *tmpNetworkId = new NetworkId(requester); m_csInterface.requestGetTicketByCharacter( - reinterpret_cast(tmpNetworkId), suid, NULL, + reinterpret_cast(tmpNetworkId), suid, nullptr, start, count, markAsRead); } @@ -475,7 +475,7 @@ void CustomerServiceServer::requestNewTicketActivity(const NetworkId &requester, NetworkId *tmpNetworkId = new NetworkId(requester); - m_csInterface.requestNewTicketActivity(reinterpret_cast(tmpNetworkId), suid, NULL); + m_csInterface.requestNewTicketActivity(reinterpret_cast(tmpNetworkId), suid, nullptr); } //----------------------------------------------------------------------- @@ -497,7 +497,7 @@ void CustomerServiceServer::requestRegisterCharacter(const NetworkId &requester, LOG("CSServer", ("CustomerServiceInterface::requestRegisterCharacter() - networkId(%s) suid(%i)", requester.getValueString().c_str(), suid)); NetworkId *tmpNetworkId = new NetworkId(requester); - m_csInterface.requestRegisterCharacter(reinterpret_cast(tmpNetworkId), suid, NULL, 0); + m_csInterface.requestRegisterCharacter(reinterpret_cast(tmpNetworkId), suid, nullptr, 0); } } diff --git a/engine/server/application/LogServer/src/CMakeLists.txt b/engine/server/application/LogServer/src/CMakeLists.txt index d1fe60d8..80ac0f32 100644 --- a/engine/server/application/LogServer/src/CMakeLists.txt +++ b/engine/server/application/LogServer/src/CMakeLists.txt @@ -78,3 +78,7 @@ target_link_libraries(LogServer unicodeArchive ${CMAKE_DL_LIBS} ) + +if(${BUILD_MULODI_LIB}) + target_link_libraries(LogServer mulodi) +endif() diff --git a/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp b/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp index 89591848..c2429a76 100755 --- a/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp +++ b/engine/server/application/LogServer/src/shared/LoggingServerApi.cpp @@ -9,8 +9,6 @@ #include "LoggingServerApi.h" - - LoggingServerApi::LoggingServerApi(LoggingServerHandler *handler, int queueSize) { mHandler = handler; @@ -18,21 +16,22 @@ LoggingServerApi::LoggingServerApi(LoggingServerHandler *handler, int queueSize) mQueue = new QueueEntry[mQueueSize]; mQueuePosition = 0; mQueueCount = 0; + mLoginSent = 0; mAuthenticated = false; mLoginName[0] = 0; mPassword[0] = 0; mDefaultDirectory[0] = 0; - mConnection = NULL; - mUdpManager = NULL; - mTransaction = NULL; - mSessionId = int(time(NULL)); + mConnection = nullptr; + mUdpManager = nullptr; + mTransaction = nullptr; + mSessionId = int(time(nullptr)); mSessionSequence = 1; } LoggingServerApi::~LoggingServerApi() { - if (mTransaction != NULL) + if (mTransaction != nullptr) StopTransaction(); for (int i = 0; i < mQueueCount; i++) @@ -77,7 +76,7 @@ void LoggingServerApi::Connect(const char *address, int port, const char *loginN mUdpManager = new UdpManager(¶ms); mConnection = mUdpManager->EstablishConnection(address, port, 30000); - if (mConnection != NULL) + if (mConnection != nullptr) mConnection->SetHandler(this); mLoginSent = false; } @@ -89,17 +88,17 @@ void LoggingServerApi::Disconnect() mPassword[0] = 0; mDefaultDirectory[0] = 0; - if (mConnection != NULL) + if (mConnection != nullptr) { mConnection->Disconnect(); mConnection->Release(); - mConnection = NULL; + mConnection = nullptr; } - if (mUdpManager != NULL) + if (mUdpManager != nullptr) { mUdpManager->Release(); - mUdpManager = NULL; + mUdpManager = nullptr; } } @@ -117,22 +116,22 @@ void LoggingServerApi::Flush(int timeout) UdpMisc::Sleep(20); } -LoggingServerApi::Status LoggingServerApi::GetStatus() const +LoggingServerApi::Status LoggingServerApi::GetStatus() const { - if (mConnection != NULL) + if (mConnection != nullptr) { switch (mConnection->GetStatus()) { - case UdpConnection::cStatusConnected: - if (mAuthenticated) - return(cStatusConnected); - else - return(cStatusAuthenticating); - break; - case UdpConnection::cStatusNegotiating: - return(cStatusNegotiating); - default: - break; + case UdpConnection::cStatusConnected: + if (mAuthenticated) + return(cStatusConnected); + else + return(cStatusAuthenticating); + break; + case UdpConnection::cStatusNegotiating: + return(cStatusNegotiating); + default: + break; } } return(cStatusDisconnected); @@ -140,69 +139,69 @@ LoggingServerApi::Status LoggingServerApi::GetStatus() const void LoggingServerApi::OnRoutePacket(UdpConnection *, const uchar *data, int) { - switch(data[0]) + switch (data[0]) { - case cS2CPacketLoginConfirm: + case cS2CPacketLoginConfirm: + { + mAuthenticated = data[1] ? true : false; + if (mAuthenticated) { - mAuthenticated = data[1] ? true : false; - if (mAuthenticated) - { - // flush the queue on authentication. This sends not only any data that was queued before connecting - // but also any data that was sent in the last 3 minutes, just to ensure that it didn't get lost on the - // server side of things - FlushQueue(); - } + // flush the queue on authentication. This sends not only any data that was queued before connecting + // but also any data that was sent in the last 3 minutes, just to ensure that it didn't get lost on the + // server side of things + FlushQueue(); + } - if (mHandler != NULL) - mHandler->LshOnLoginConfirm(mAuthenticated); - break; - } - case cS2CPacketMonitor: - { - char *ptr = (char *)(data + 1); - int sessionId = UdpMisc::GetValue32(ptr); - ptr += 4; - int sequenceNumber = UdpMisc::GetValue32(ptr); - ptr += 4; - int typeCode = UdpMisc::GetValue32(ptr); - ptr += 4; - char *name = ptr; - ptr += strlen(ptr) + 1; - char *filename = ptr; - ptr += strlen(ptr) + 1; - char *message = ptr; - if (mHandler != NULL) - mHandler->LshOnMonitor(sessionId, sequenceNumber, name, filename, typeCode, message); - break; - } - case cS2CPacketFileList: - { - if (mHandler != NULL) - mHandler->LshOnFileList((char *)(data + 1)); - break; - } - default: - break; + if (mHandler != nullptr) + mHandler->LshOnLoginConfirm(mAuthenticated); + break; + } + case cS2CPacketMonitor: + { + char *ptr = (char *)(data + 1); + int sessionId = UdpMisc::GetValue32(ptr); + ptr += 4; + int sequenceNumber = UdpMisc::GetValue32(ptr); + ptr += 4; + int typeCode = UdpMisc::GetValue32(ptr); + ptr += 4; + char *name = ptr; + ptr += strlen(ptr) + 1; + char *filename = ptr; + ptr += strlen(ptr) + 1; + char *message = ptr; + if (mHandler != nullptr) + mHandler->LshOnMonitor(sessionId, sequenceNumber, name, filename, typeCode, message); + break; + } + case cS2CPacketFileList: + { + if (mHandler != nullptr) + mHandler->LshOnFileList((char *)(data + 1)); + break; + } + default: + break; } } void LoggingServerApi::OnTerminated(UdpConnection *con) { - if(mHandler != NULL) + if (mHandler != nullptr) { - mHandler->LshOnTerminated( con->GetDisconnectReason() ); + mHandler->LshOnTerminated(con->GetDisconnectReason()); } } void LoggingServerApi::GiveTime() { - if (mConnection != NULL && mConnection->GetStatus() == UdpConnection::cStatusConnected) + if (mConnection != nullptr && mConnection->GetStatus() == UdpConnection::cStatusConnected) { if (!mLoginSent) { mLoginSent = true; - // send login packet + // send login packet char buf[1024]; char *ptr = buf; *ptr++ = cC2SPacketLogin; @@ -221,11 +220,11 @@ void LoggingServerApi::GiveTime() { int spot = mQueuePosition % mQueueSize; - // if entry was actually sent and it has been sitting in the queue long enough to be deleted - if (mQueue[spot].sentTime != 0 && UdpMisc::ClockElapsed(mQueue[spot].sentTime) > cSafetyQueueTime) + // if entry was actually sent and it has been sitting in the queue long enough to be deleted + if (mQueue[spot].sentTime != 0 && UdpMisc::ClockElapsed(mQueue[spot].sentTime) > cSafetyQueueTime) { mQueue[spot].packet->Release(); - mQueue[spot].packet = NULL; + mQueue[spot].packet = nullptr; mQueuePosition++; mQueueCount--; } @@ -235,7 +234,7 @@ void LoggingServerApi::GiveTime() } } - if (mUdpManager != NULL) + if (mUdpManager != nullptr) { mUdpManager->GiveTime(); } @@ -243,40 +242,40 @@ void LoggingServerApi::GiveTime() void LoggingServerApi::StartTransaction() { - if (mTransaction == NULL) + if (mTransaction == nullptr) mTransaction = new GroupLogicalPacket(); } void LoggingServerApi::StopTransaction() { - if (mTransaction != NULL) + if (mTransaction != nullptr) { PacketSend(mTransaction); mTransaction->Release(); - mTransaction = NULL; + mTransaction = nullptr; } } void LoggingServerApi::PacketSend(LogicalPacket *lp) { - // make room in queue + // make room in queue if (mQueueCount == mQueueSize) { int spot = mQueuePosition % mQueueSize; mQueue[spot].packet->Release(); - mQueue[spot].packet = NULL; + mQueue[spot].packet = nullptr; mQueuePosition++; mQueueCount--; } - // queue it + // queue it int spot = (mQueuePosition + mQueueCount) % mQueueSize; lp->AddRef(); mQueue[spot].packet = lp; mQueue[spot].sentTime = 0; mQueueCount++; - // if possible, send it + // if possible, send it if (GetStatus() == cStatusConnected) { mQueue[spot].sentTime = UdpMisc::Clock(); @@ -284,7 +283,6 @@ void LoggingServerApi::PacketSend(LogicalPacket *lp) } } - void LoggingServerApi::Log16(const char *filename, int typeCode, const unsigned short *ucs2String) { char buffer[32768]; @@ -374,9 +372,9 @@ void LoggingServerApi::Log(const char *filename, int typeCode, const char *messa void LoggingServerApi::LogPacket(char *data, int len) { - if (mTransaction != NULL) + if (mTransaction != nullptr) { - // add it to the transaction + // add it to the transaction mTransaction->AddPacket(data, len); } else @@ -389,7 +387,7 @@ void LoggingServerApi::LogPacket(char *data, int len) LogicalPacket *LoggingServerApi::CreatePacket(char *data, int dataLen) { - if (mUdpManager != NULL) + if (mUdpManager != nullptr) { return(mUdpManager->CreatePacket(data, dataLen)); } @@ -437,12 +435,12 @@ void LoggingServerApi::RequestFileList() void LoggingServerApi::GetStatistics(LoggingServerApiStatistics *stats) { - memset( stats, 0, sizeof( *stats) ); + memset(stats, 0, sizeof(*stats)); UdpConnectionStatistics udpConnectionStats; - memset( &udpConnectionStats, 0, sizeof( udpConnectionStats ) ); - if( mConnection != NULL ) + memset(&udpConnectionStats, 0, sizeof(udpConnectionStats)); + if (mConnection != nullptr) { - mConnection->GetStats( &udpConnectionStats ); + mConnection->GetStats(&udpConnectionStats); stats->applicationPacketsReceived = udpConnectionStats.applicationPacketsReceived; stats->applicationPacketsSent = udpConnectionStats.applicationPacketsSent; stats->totalBytesReceived = udpConnectionStats.totalBytesReceived; @@ -454,25 +452,25 @@ void LoggingServerApi::GetStatistics(LoggingServerApiStatistics *stats) } UdpManagerStatistics managerStats; - if( mUdpManager != NULL ) + if (mUdpManager != nullptr) { - mUdpManager->GetStats( &managerStats ); + mUdpManager->GetStats(&managerStats); udp_int64 iterations = managerStats.iterations; int elapseTime = managerStats.elapsedTime; - if( elapseTime != 0 ) + if (elapseTime != 0) { - stats->iterationsPerSecond = (double)((iterations * 1000 )/(double)elapseTime); + stats->iterationsPerSecond = (double)((iterations * 1000) / (double)elapseTime); } mUdpManager->ResetStats(); } } -void LoggingServerHandler::LshOnLoginConfirm(bool ) +void LoggingServerHandler::LshOnLoginConfirm(bool) { } -void LoggingServerHandler::LshOnMonitor(int , int , const char * const, const char * const, int , const char * const) +void LoggingServerHandler::LshOnMonitor(int, int, const char * const, const char * const, int, const char * const) { } @@ -482,4 +480,4 @@ void LoggingServerHandler::LshOnFileList(const char * const) void LoggingServerHandler::LshOnTerminated(UdpConnection::DisconnectReason) { -} +} \ No newline at end of file diff --git a/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp b/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp index 209b2b0d..199f65da 100755 --- a/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp +++ b/engine/server/application/LogServer/src/shared/LoggingServerApiObserver.cpp @@ -1,5 +1,5 @@ // LoggingServerApiObserver.cpp -// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. // Author: Justin Randall //----------------------------------------------------------------------- @@ -15,7 +15,7 @@ //----------------------------------------------------------------------- LoggingServerApiObserver::LoggingServerApiObserver() : -m_loggingServerApi(new LoggingServerApi(0, ConfigLogServer::getLoggingServerApiQueueSize())) + m_loggingServerApi(new LoggingServerApi(0, ConfigLogServer::getLoggingServerApiQueueSize())) { m_loggingServerApi->Connect(ConfigLogServer::getLoggingServerApiAddress(), LoggingServerApi::cDefaultPort, ConfigLogServer::getLoggingServerApiLoginName(), ConfigLogServer::getLoggingServerApiPassword(), ConfigLogServer::getLoggingServerApiDefaultDirectory()); } @@ -47,30 +47,30 @@ LogObserver * LoggingServerApiObserver::create(const std::string &) void LoggingServerApiObserver::log(const LogMessage & msg) { std::string fileName = "misc.txt"; - + std::string msgText; - if(! msg.getText().empty()) + if (!msg.getText().empty()) { time_t now; tm t; - IGNORE_RETURN( time(&now) ); - IGNORE_RETURN( gmtime_r(&now, &t) ); - char dirBuf[128] = {"\0"}; - snprintf(dirBuf, sizeof(dirBuf), "%d/%d/%d/", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday); + IGNORE_RETURN(time(&now)); + IGNORE_RETURN(gmtime_r(&now, &t)); + char dirBuf[128] = { "\0" }; + snprintf(dirBuf, 128, "%d/%d/%d/", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday); fileName = ConfigLogServer::getClusterName(); fileName += "/"; fileName += dirBuf; - + std::string splittext = msg.getText(); - if(splittext.find(":") != splittext.npos) + if (splittext.find(":") != splittext.npos) { fileName += splittext.substr(0, splittext.find(":")) + ".txt"; } msgText = splittext.substr(splittext.find(":") + 1); - + // If there is ANY Unicode, send the whole log as Unicode. If there is ONLY non-Unicode, then send the log non-Unicode. if (!msg.getUnicodeAttach().empty()) @@ -106,7 +106,7 @@ void LoggingServerApiObserver::flush() void LoggingServerApiObserver::update() { - if(m_loggingServerApi->GetStatus() == LoggingServerApi::cStatusDisconnected) + if (m_loggingServerApi->GetStatus() == LoggingServerApi::cStatusDisconnected) { m_loggingServerApi->Connect(ConfigLogServer::getLoggingServerApiAddress(), LoggingServerApi::cDefaultPort, ConfigLogServer::getLoggingServerApiLoginName(), ConfigLogServer::getLoggingServerApiPassword(), ConfigLogServer::getLoggingServerApiDefaultDirectory()); } @@ -114,5 +114,4 @@ void LoggingServerApiObserver::update() m_loggingServerApi->GiveTime(); } -//----------------------------------------------------------------------- - +//----------------------------------------------------------------------- \ No newline at end of file diff --git a/engine/server/application/LogServer/src/win32/LoggingServerApiWrapper.cpp b/engine/server/application/LogServer/src/win32/LoggingServerApiWrapper.cpp new file mode 100644 index 00000000..78b377f5 --- /dev/null +++ b/engine/server/application/LogServer/src/win32/LoggingServerApiWrapper.cpp @@ -0,0 +1,16 @@ +// LoggingServerApiWrapper.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +// This is a wrapper cpp to workaround PCH and RSP's. While a DSP +// may exclude a single file from using precompiled headers, the +// dsp builder has no way (I know of) to honor this behavior. +//----------------------------------------------------------------------- + +#include "FirstLogServer.h" +//#include "LoggingServerApi.cpp" + +//----------------------------------------------------------------------- + +//----------------------------------------------------------------------- + diff --git a/engine/server/application/LogServer/src/win32/WinMain.cpp b/engine/server/application/LogServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..21d829c4 --- /dev/null +++ b/engine/server/application/LogServer/src/win32/WinMain.cpp @@ -0,0 +1,55 @@ +// ====================================================================== +// +// WinMain.cpp +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "FirstLogServer.h" +#include "sharedFoundation/FirstSharedFoundation.h" +#include "LogServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedThread/SetupSharedThread.h" + +// ====================================================================== + +int main(int argc, char **argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install(setupFoundationData); + + SetupSharedCompression::install(); + + SetupSharedFile::install(false); + SetupSharedNetworkMessages::install(); + + //-- setup server + LogServer::install(); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(LogServer::run); + + LogServer::remove(); + SetupSharedFoundation::remove(); + SetupSharedThread::remove(); + + return 0; +} + +// ====================================================================== diff --git a/engine/server/application/LoginServer/src/CMakeLists.txt b/engine/server/application/LoginServer/src/CMakeLists.txt index 94910cb3..80a0989a 100644 --- a/engine/server/application/LoginServer/src/CMakeLists.txt +++ b/engine/server/application/LoginServer/src/CMakeLists.txt @@ -79,18 +79,18 @@ else() endif() include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/shared + ${CMAKE_CURRENT_SOURCE_DIR}/shared ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedCommandParser/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedCompression/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDatabaseInterface/include/public - ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFile/include/public - ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public - ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedGame/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedLog/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMath/include/public - ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMessageDispatch/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedNetwork/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedNetworkMessages/include/public @@ -101,7 +101,7 @@ include_directories( ${SWG_ENGINE_SOURCE_DIR}/server/library/serverKeyShare/include/public ${SWG_ENGINE_SOURCE_DIR}/server/library/serverNetworkMessages/include/public ${SWG_ENGINE_SOURCE_DIR}/server/library/serverUtility/include/public - ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/archive/include + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/archive/include ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localization/include ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localizationArchive/include/public ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/singleton/include @@ -110,6 +110,7 @@ include_directories( ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/platform/projects ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/platform/utils ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/udplibrary + ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/webAPI ) add_executable(LoginServer @@ -150,5 +151,7 @@ target_link_libraries(LoginServer CommonAPI LoginAPI MonAPI2 + webAPI + ${CURL_LIBRARIES} ${CMAKE_DL_LIBS} ) diff --git a/engine/server/application/LoginServer/src/linux/main.cpp b/engine/server/application/LoginServer/src/linux/main.cpp index 7b4d7c1b..e08cb606 100755 --- a/engine/server/application/LoginServer/src/linux/main.cpp +++ b/engine/server/application/LoginServer/src/linux/main.cpp @@ -35,7 +35,7 @@ int main(int argc, char ** argv) SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + SetupSharedRandom::install(static_cast(time(nullptr))); //lint !e1924 !e64 // nullptr is a C-Style cast? Os::setProgramName("LoginServer"); //setup the server diff --git a/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp b/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp index 3da0b98b..9163a15a 100755 --- a/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp +++ b/engine/server/application/LoginServer/src/shared/CSToolConnection.cpp @@ -14,9 +14,9 @@ #include "sharedLog/Log.h" #if defined(WIN32) - #include +#include #else // for non-windows platforms (linux) - #include +#include #endif namespace CSToolConnectionNamespace @@ -28,9 +28,9 @@ uint32 CSToolConnection::m_curToolID = 0; // statics -CSToolConnection * CSToolConnection::getCSToolConnectionByToolId( uint32 id ) +CSToolConnection * CSToolConnection::getCSToolConnectionByToolId(uint32 id) { - std::map< uint32, CSToolConnection * >::iterator it = CSToolConnectionNamespace::toolsByID.find( id ); + std::map< uint32, CSToolConnection * >::iterator it = CSToolConnectionNamespace::toolsByID.find(id); return it == CSToolConnectionNamespace::toolsByID.end() ? 0 : it->second; } @@ -40,9 +40,9 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api CSToolConnection * p_connection = getCSToolConnectionByToolId(toolId); if (!p_connection) return; // no connection, they must have bailed. - + // check the result - if(result == RESULT_SUCCESS) + if (result == RESULT_SUCCESS) { // if we're valid, set to logged in p_connection->m_bLoggedIn = true; @@ -50,38 +50,37 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api { p_connection->m_bSecure = true; } - - // if we have a null session type, then we aren't connected to the + + // if we have a nullptr session type, then we aren't connected to the // Session Server and are in debug mode. // // if we *do* have a good session, then check the admin table for access level. int accessLevel = 100; - + bool sessionNull = (session.GetType() == SESSION_TYPE_NULL); bool isAdmin = AdminAccountManager::isAdminAccount(p_connection->m_sUserName, accessLevel); bool needSecure = ConfigLoginServer::getRequireSecureLoginForCsTool(); bool isInternal = AdminAccountManager::isInternalIp(p_connection->getRemoteAddress()); - DEBUG_REPORT_LOG( true, ("CS Tool login for %s, admin=%s, access=%d, internal=%s\n", - p_connection->m_sUserName.c_str(), - isAdmin ? "true" : "false", - accessLevel, - isInternal ? "true" : "false")); + DEBUG_REPORT_LOG(true, ("CS Tool login for %s, admin=%s, access=%d, internal=%s\n", + p_connection->m_sUserName.c_str(), + isAdmin ? "true" : "false", + accessLevel, + isInternal ? "true" : "false")); - bool canLogin = isInternal; // we always have to be internal. if (sessionNull) { - // null session means we can skip everything else. + // nullptr session means we can skip everything else. canLogin = canLogin && true; accessLevel = 100; } else { // if we don't have a session, we need to be on the admin table - if(isAdmin) + if (isAdmin) { // allow login if we either don't need to be secure, or if we are. - if((!needSecure) || p_connection->m_bSecure) + if ((!needSecure) || p_connection->m_bSecure) { canLogin = canLogin && true; } @@ -94,58 +93,57 @@ void CSToolConnection::validateCSTool(uint32 toolId, apiResult result, const api { canLogin = false; } - } - - if(canLogin) + } + + if (canLogin) { // and inform std::string response = "Logged in successfully."; response += "\r\n"; p_connection->sendToTool(response); - + p_connection->m_ui32PrivilegeLevel = (uint32)accessLevel; } else { p_connection->sendToTool("Invalid name/password.\r\n"); } - } - // otherwise, give the appropriate response - else if( result == RESULT_INVALID_NAME_OR_PASSWORD ) + // otherwise, give the appropriate response + else if (result == RESULT_INVALID_NAME_OR_PASSWORD) { p_connection->sendToTool("Invalid name/password.\r\n"); } else { - DEBUG_REPORT_LOG(true,("Could not log in CS Tool for user %s, reason %d\n", p_connection->m_sUserName.c_str(), result)); + DEBUG_REPORT_LOG(true, ("Could not log in CS Tool for user %s, reason %d\n", p_connection->m_sUserName.c_str(), result)); p_connection->sendToTool("Invalid name/password.\r\n"); } - } // members -CSToolConnection::CSToolConnection( UdpConnectionMT * pUdpConn, TcpClient * pTcpConn ) : - Connection( pUdpConn, pTcpConn ), - m_ui32StationID( 0 ), - m_bSecure( false ), - m_bLoggedIn( false ), - m_ui32PrivilegeLevel( 0 ) +CSToolConnection::CSToolConnection(UdpConnectionMT * pUdpConn, TcpClient * pTcpConn) : + Connection(pUdpConn, pTcpConn), + m_ui32StationID(0), + m_bSecure(false), + m_bLoggedIn(false), + m_ui32PrivilegeLevel(0), + m_toolID(0) { - if( pTcpConn ) // it'd better be! - setRawTCP( true ); + if (pTcpConn) // it'd better be! + setRawTCP(true); } CSToolConnection::~CSToolConnection() { } -void CSToolConnection::onReceive( const Archive::ByteStream & message ) +void CSToolConnection::onReceive(const Archive::ByteStream & message) { // for testing purposes, just echo back to the user. - + // add to buffer std::string input; const unsigned char * uc = message.getBuffer(); @@ -156,242 +154,234 @@ void CSToolConnection::onReceive( const Archive::ByteStream & message ) ++uc; } m_sInputBuffer += input; - - + // while we've got an EOL signifier std::string::size_type pos; - while( ( pos = m_sInputBuffer.find( '\r' ) ) != std::string::npos ) + while ((pos = m_sInputBuffer.find('\r')) != std::string::npos) { // rebuild message buffer properly. - std::string command = m_sInputBuffer.substr( 0, pos ); + std::string command = m_sInputBuffer.substr(0, pos); // should dispatch here, for now we're echoing back for debug. - + //command = command + "\r\n"; //sendToTool( command ); - this->parse( command ); + this->parse(command); // then we have additional data. Otherwise, we don't. - if( m_sInputBuffer.size() >= pos + 2 ) + if (m_sInputBuffer.size() >= pos + 2) { - m_sInputBuffer = m_sInputBuffer.substr( pos + 2, m_sInputBuffer.length() - ( pos + 2 ) ); + m_sInputBuffer = m_sInputBuffer.substr(pos + 2, m_sInputBuffer.length() - (pos + 2)); } else { m_sInputBuffer.clear(); } - } } -void CSToolConnection::parse( const std::string command ) +void CSToolConnection::parse(const std::string command) { // grab the first word of the command. std::string first; std::string args; std::string::size_type pos; - if( ( pos = command.find( ' ' ) ) == std::string::npos ) + if ((pos = command.find(' ')) == std::string::npos) { first = command; } else { - first = command.substr( 0, pos ); - args = command.substr( pos + 1, command.size() - ( pos + 1 ) ); + first = command.substr(0, pos); + args = command.substr(pos + 1, command.size() - (pos + 1)); } // test for empty commands. - if( first.length() == 0 || first[ 0 ] == ' ' ) + if (first.length() == 0 || first[0] == ' ') { return; } - + std::string response = "ls:"; - - - if( first == "clusters" ) + + if (first == "clusters") { response += "Active clusters:\r\n"; - std::map< std::string, uint32 > data; - LoginServer::getInstance().getAllClusterNamesAndIDs( data ); - for( std::map< std::string, uint32 >::iterator it = data.begin(); - it != data.end(); - ++it ) + std::map< std::string, uint32 > data; + LoginServer::getInstance().getAllClusterNamesAndIDs(data); + for (std::map< std::string, uint32 >::iterator it = data.begin(); + it != data.end(); + ++it) { response += it->first + "\r\n"; } - sendToTool( response ); + sendToTool(response); } - else if ( first == "select" ) + else if (first == "select") { // see if we're adding, removing, or exclusive-adding. - if( args[ 0 ] == '+' ) + if (args[0] == '+') { - if( args.size() > 1 ) + if (args.size() > 1) { - if( args[ 1 ] == '+' ) + if (args[1] == '+') { m_selectedClusters.clear(); - sendToTool( "ls:deselected all servers\r\n" ); + sendToTool("ls:deselected all servers\r\n"); } - pos = args.find_first_not_of( "+" ); - if( pos == std::string::npos ) + pos = args.find_first_not_of("+"); + if (pos == std::string::npos) { } else { - std::string cluster = args.substr( pos, args.size() - pos ); - response += selectCluster( cluster ); - sendToTool( response ); + std::string cluster = args.substr(pos, args.size() - pos); + response += selectCluster(cluster); + sendToTool(response); } } } - else if( args[ 0 ] == '-' ) + else if (args[0] == '-') { - if( args.size() > 1 ) + if (args.size() > 1) { - std::string cluster = args.substr( 1, args.size() - 1 ); - if( m_selectedClusters.find( cluster ) != m_selectedClusters.end() ) + std::string cluster = args.substr(1, args.size() - 1); + if (m_selectedClusters.find(cluster) != m_selectedClusters.end()) { - response += deselectCluster( cluster ); - sendToTool( response ); + response += deselectCluster(cluster); + sendToTool(response); } } } else { - sendToTool( "Error! Bad select format!\r\n" ); + sendToTool("Error! Bad select format!\r\n"); } } - else if ( first == "showselected" ) + else if (first == "showselected") { response += "Currently selected clusters:\r\n"; - for( std::set< std::string >::iterator it = m_selectedClusters.begin(); - it != m_selectedClusters.end(); - ++it ) + for (std::set< std::string >::iterator it = m_selectedClusters.begin(); + it != m_selectedClusters.end(); + ++it) { response += *it + "\r\n"; } - sendToTool( response ); - + sendToTool(response); } - else if( first == "login" ) + else if (first == "login") { // assume name/pw do not have spaces. std::string name; std::string pw; - + // split apart - unsigned pos = args.find( " " ); - if( pos != std::string::npos ) + unsigned pos = args.find(" "); + if (pos != std::string::npos) { - name = args.substr( 0, pos ); - pw = args.substr( pos + 1, args.length() - pos - 1 ); + name = args.substr(0, pos); + pw = args.substr(pos + 1, args.length() - pos - 1); m_sUserName = name; - if( !LoginServer::getInstance().getSessionApiClient() ) + if (!LoginServer::getInstance().getSessionApiClient()) { apiSession session; - validateCSTool( m_toolID, RESULT_SUCCESS, session ); + validateCSTool(m_toolID, RESULT_SUCCESS, session); return; } LoginServer::getInstance().getSessionApiClient()-> - SessionLogin(name.c_str(), - pw.c_str(), + SessionLogin(name.c_str(), + pw.c_str(), SESSION_TYPE_STARWARS, - inet_addr( getRemoteAddress().c_str() ), + inet_addr(getRemoteAddress().c_str()), 0, - _defaultNamespace, - ( void * )m_toolID ); + _defaultNamespace, + (void *)m_toolID); } - + // pass to session. } // default command handler. else { - if( m_bLoggedIn ) + if (m_bLoggedIn) { - sendToClusters( first, command ); + sendToClusters(first, command); } else { - sendToTool( "Not logged in.\r\n" ); + sendToTool("Not logged in.\r\n"); } } - } -void CSToolConnection::sendToClusters( const std::string & sCommand, const std::string & sCommandLine ) +void CSToolConnection::sendToClusters(const std::string & sCommand, const std::string & sCommandLine) { // build the message - CSToolRequest msg( m_ui32StationID, m_ui32PrivilegeLevel, sCommandLine, sCommand, m_toolID, m_sUserName ); - + CSToolRequest msg(m_ui32StationID, m_ui32PrivilegeLevel, sCommandLine, sCommand, m_toolID, m_sUserName); + // send to all currently selected clusters. - for( std::set< std::string >::iterator it = m_selectedClusters.begin(); - it != m_selectedClusters.end(); - ++it ) + for (std::set< std::string >::iterator it = m_selectedClusters.begin(); + it != m_selectedClusters.end(); + ++it) { - LoginServer::getInstance().sendToCluster( LoginServer::getInstance().getClusterIDByName( *it ), msg ); + LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(*it), msg); } } -std::string CSToolConnection::selectCluster( const std::string & cluster ) +std::string CSToolConnection::selectCluster(const std::string & cluster) { std::string response; // see if we have a valid cluster. - uint32 cluster_id = LoginServer::getInstance().getClusterIDByName( cluster ); - if( cluster_id == 0 ) + uint32 cluster_id = LoginServer::getInstance().getClusterIDByName(cluster); + if (cluster_id == 0) { response += "Cluster " + cluster + " does not exist.\r\n"; } else { - m_selectedClusters.insert( cluster ); + m_selectedClusters.insert(cluster); response += "Cluster " + cluster + " added to active list\r\n"; } return response; } -std::string CSToolConnection::deselectCluster( const std::string & cluster ) +std::string CSToolConnection::deselectCluster(const std::string & cluster) { std::string response; - + // see if we are currently talking to that cluster. - std::set< std::string >::iterator it = m_selectedClusters.find( cluster ); - if( it == m_selectedClusters.end() ) + std::set< std::string >::iterator it = m_selectedClusters.find(cluster); + if (it == m_selectedClusters.end()) { response += "Cluster " + cluster + " is not currently selected.\r\n"; } else { - m_selectedClusters.erase( it ); + m_selectedClusters.erase(it); response += "Cluster " + cluster + " removed from active list.\r\n"; } return response; - } -void CSToolConnection::sendToTool( const std::string & message ) +void CSToolConnection::sendToTool(const std::string & message) { // convert to ByteStream std::string temp = message; temp += "\r\n*\r\n"; Archive::ByteStream bs; - bs.put( temp.c_str(), temp.size() ); + bs.put(temp.c_str(), temp.size()); // send. - this->send( bs, true ); -} + this->send(bs, true); +} void CSToolConnection::onConnectionOpened() { - LOG( "CSTool", ("Connection opened") ); + LOG("CSTool", ("Connection opened")); // assign an ID, and stick it in our map. m_curToolID++; m_toolID = m_curToolID; - CSToolConnectionNamespace::toolsByID[ m_toolID ] = this; - + CSToolConnectionNamespace::toolsByID[m_toolID] = this; } void CSToolConnection::onConnectionClosed() { - LOG( "CSTool", ("Connection closed") ); - CSToolConnectionNamespace::toolsByID.erase( m_toolID ); - -} + LOG("CSTool", ("Connection closed")); + CSToolConnectionNamespace::toolsByID.erase(m_toolID); +} \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/CentralServerConnection.cpp b/engine/server/application/LoginServer/src/shared/CentralServerConnection.cpp index 6b803038..443e187e 100755 --- a/engine/server/application/LoginServer/src/shared/CentralServerConnection.cpp +++ b/engine/server/application/LoginServer/src/shared/CentralServerConnection.cpp @@ -30,6 +30,8 @@ #include "Unicode.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace CentralServerConnectionNamespace @@ -101,194 +103,216 @@ void CentralServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); GameNetworkMessage m(ri); ri = message.begin(); - // handle messages the connection object itself may be interested in - if(m.isType("LoginClusterName")) - { - const LoginClusterName c(ri); - ri = message.begin(); - setClusterName(c.getClusterName()); - LOG("CentralServerConnection", ("Galaxy [%s] connected", c.getClusterName().c_str())); - } - else if ( m.isType( "LoginClusterName2" ) ) - { - const LoginClusterName2 c( ri ); - ri = message.begin(); - - const std::string &clusterName = c.getClusterName(); - const std::string &branch = c.getBranch(); - const int changelist = c.getChangelist(); - const std::string &networkVersion = c.getNetworkVersion(); - - DEBUG_REPORT_LOG( true, ( "!!!!!!!!!!!!!!!! name=%s branch=%s changelist=%d net=%s\n", clusterName.c_str(), branch.c_str(), changelist, networkVersion.c_str() ) ); - - setClusterName( clusterName ); - setNetworkVersion( c.getNetworkVersion() ); - LOG("CentralServerConnection", ("Galaxy [%s] connected", getClusterName().c_str())); - - LoginServer::getInstance().setClusterInfoByName( clusterName, branch, changelist, networkVersion ); - - } - else if(m.isType("ToggleAvatarLoginStatus")) - { - const ToggleAvatarLoginStatus t(ri); - if(t.getEnabled()) - { - LOG("CustomerService", ("CharacterTransfer: ToggleAvatarLoginStatus(%s, %d, %s, true)", t.getClusterName().c_str(), t.getStationId(), t.getCharacterId().getValueString().c_str())); - } - else - { - // send message to the cluster to drop connected clients for the - // station id in case the avatar being disabled is currently logged in - GenericValueTypeMessage const closeRequest("TransferCloseClientConnection", t.getStationId()); - LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(t.getClusterName()), closeRequest); - - LOG("CustomerService", ("CharacterTransfer: ToggleAvatarLoginStatus(%s, %d, %s, false)\n", t.getClusterName().c_str(), t.getStationId(), t.getCharacterId().getValueString().c_str())); - } - DatabaseConnection::getInstance().toggleDisableCharacter(LoginServer::getInstance().getClusterIDByName(t.getClusterName()), t.getCharacterId(), t.getStationId(), t.getEnabled()); - } - else if(m.isType("CtsCompletedForcharacter")) - { - const GenericValueTypeMessage > msg(ri); - LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(msg.getValue().first), msg); - } - else if(m.isType("TransferRequestCharacterList")) - { - const GenericValueTypeMessage request(ri); - const TransferCharacterData & d = request.getValue(); - DatabaseConnection::getInstance().requestAvatarListForAccount(d.getSourceStationId(), &d); - } - else if(m.isType("TransferReplyLoginLocationData")) - { - const GenericValueTypeMessage reply(ri); - const TransferCharacterData & d = reply.getValue(); - LOG("CustomerService", ("CharacterTransfer: Received login location data. %s", d.toString().c_str())); - } - else if(m.isType("TransferGetCharacterDataFromLoginServer")) - { - // the TransferServer sent a request to the central server - // to retrieve a character ID from the login database given - // a source station ID and a source character name. Retrieve - // this data from the login database. - const GenericValueTypeMessage request(ri); - TransferCharacterData d = request.getValue(); - DatabaseConnection::getInstance().requestAvatarListForAccount(d.getSourceStationId(), &d); - LOG("CustomerService", ("CharacterTransfer: Received TransferGetCharactetrDataFromLoginServer from CentralServer. %s", d.toString().c_str())); - } - else if(m.isType("TransferRenameCharacterInLoginDatabase")) - { - const GenericValueTypeMessage request(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterInLoginDatabase : %s", request.getValue().toString().c_str())); - const TransferCharacterData & requestData = request.getValue(); - DatabaseConnection::getInstance().renameCharacter(getClusterId(), requestData.getCharacterId(), Unicode::narrowToWide(requestData.getDestinationCharacterName()), &requestData); - } - else if(m.isType("TransferKickConnectedClients")) - { - const GenericValueTypeMessage kick(ri); - ClientConnection * clientConnection = LoginServer::getInstance().getValidatedClient(kick.getValue()); - if(! clientConnection) - { - clientConnection = LoginServer::getInstance().getUnvalidatedClient(kick.getValue()); - } - - if(clientConnection) - { - clientConnection->disconnect(); - } - } - else if(m.isType("TransferAccountRequestLoginServer")) - { - const GenericValueTypeMessage request(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestLoginServer from station ID %d to from station ID %d", request.getValue().getSourceStationId(), request.getValue().getDestinationStationId())); - const TransferAccountData requestData = request.getValue(); - DatabaseConnection::getInstance().requestAvatarListAccountTransfer(&requestData); - } - else if(m.isType("EnableCharacterMessage")) - { - const GenericValueTypeMessage, std::string> > msg(ri); - - LOG("LoginServer", ("EnableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - - DatabaseConnection::getInstance().enableCharacter(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, true, m_clusterId); - } - else if(m.isType("DisableCharacterMessage")) - { - const GenericValueTypeMessage, std::string> > msg(ri); - - LOG("LoginServer", ("DisableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - - DatabaseConnection::getInstance().enableCharacter(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, false, m_clusterId); - } - else if(m.isType("DeleteFailedTransfer")) - { - GenericValueTypeMessage deleteCharacter(ri); - LOG("CustomerService", ("CharacterTransfer: LoginServer received request to delete a character for a failed transfer. %s", deleteCharacter.getValue().toString().c_str())); - LoginServer::getInstance().deleteCharacter(m_clusterId, deleteCharacter.getValue().getDestinationCharacterId(), deleteCharacter.getValue().getDestinationStationId()); - } - else if(m.isType("RequestTransferClosePseudoClientConnection")) - { - GenericValueTypeMessage > const request(ri); - GenericValueTypeMessage const closeRequest("TransferClosePseudoClientConnection", request.getValue().second); - LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(request.getValue().first), closeRequest); - } - else if(m.isType("CSToolResponse" ) ) - { - CSToolResponse response(ri); - // find the connection, if it still exists - CSToolConnection * con = CSToolConnection::getCSToolConnectionByToolId( response.getToolId() ); - - // send the response - if( con ) - { - std::string message; - message = m_clusterName + ":" + response.getResult(); - - if( message[ message.length() -1 ] == '\n' && message[ message.length() - 2 ] != '\r' ) - { - message[ message.length() - 1 ] = '\r'; - message += '\n'; - } - - con->sendToTool( message ); - } - } - else if(m.isType("ConGenericMessage")) - { - ConGenericMessage con(ri); - parseCommand(con.getMsg(), con.getMsgId()); - } - else if(m.isType("LoginToggleCompletedTutorial")) - { - GenericValueTypeMessage< std::pair > const request(ri); - std::pair values = request.getValue(); - DatabaseConnection::getInstance().toggleCompletedTutorial(values.first, values.second); - } - else if(m.isType("AllCluserGlobalChannel")) - { - typedef std::pair, bool> PayloadType; - GenericValueTypeMessage msg(ri); + const uint32 messageType = m.getType(); + + // handle messages the connection object itself may be interested in + switch (messageType) { + case constcrc("LoginClusterName") : + { + const LoginClusterName c(ri); + ri = message.begin(); + setClusterName(c.getClusterName()); + LOG("CentralServerConnection", ("Galaxy [%s] connected", c.getClusterName().c_str())); + break; + } + case constcrc( "LoginClusterName2" ) : + { + const LoginClusterName2 c( ri ); + ri = message.begin(); + + const std::string &clusterName = c.getClusterName(); + const std::string &branch = c.getBranch(); + const int changelist = c.getChangelist(); + const std::string &networkVersion = c.getNetworkVersion(); + + DEBUG_REPORT_LOG( true, ( "!!!!!!!!!!!!!!!! name=%s branch=%s changelist=%d net=%s\n", clusterName.c_str(), branch.c_str(), changelist, networkVersion.c_str() ) ); + + setClusterName( clusterName ); + setNetworkVersion( c.getNetworkVersion() ); + LOG("CentralServerConnection", ("Galaxy [%s] connected", getClusterName().c_str())); + + LoginServer::getInstance().setClusterInfoByName( clusterName, branch, changelist, networkVersion ); + + break; + } + case constcrc("ToggleAvatarLoginStatus") : + { + const ToggleAvatarLoginStatus t(ri); + if(t.getEnabled()) + { + LOG("CustomerService", ("CharacterTransfer: ToggleAvatarLoginStatus(%s, %d, %s, true)", t.getClusterName().c_str(), t.getStationId(), t.getCharacterId().getValueString().c_str())); + } + else + { + // send message to the cluster to drop connected clients for the + // station id in case the avatar being disabled is currently logged in + GenericValueTypeMessage const closeRequest("TransferCloseClientConnection", t.getStationId()); + LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(t.getClusterName()), closeRequest); - PayloadType const & payload = msg.getValue(); - std::string const & channelName = payload.first.first; - std::string const & messageText = payload.first.second; - bool const & isRemove = payload.second; + LOG("CustomerService", ("CharacterTransfer: ToggleAvatarLoginStatus(%s, %d, %s, false)\n", t.getClusterName().c_str(), t.getStationId(), t.getCharacterId().getValueString().c_str())); + } + DatabaseConnection::getInstance().toggleDisableCharacter(LoginServer::getInstance().getClusterIDByName(t.getClusterName()), t.getCharacterId(), t.getStationId(), t.getEnabled()); + break; + } + case constcrc("CtsCompletedForcharacter") : + { + const GenericValueTypeMessage > msg(ri); + LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(msg.getValue().first), msg); + break; + } + case constcrc("TransferRequestCharacterList") : + { + const GenericValueTypeMessage request(ri); + const TransferCharacterData & d = request.getValue(); + DatabaseConnection::getInstance().requestAvatarListForAccount(d.getSourceStationId(), &d); + break; + } + case constcrc("TransferReplyLoginLocationData") : + { + const GenericValueTypeMessage reply(ri); + const TransferCharacterData & d = reply.getValue(); + LOG("CustomerService", ("CharacterTransfer: Received login location data. %s", d.toString().c_str())); + break; + } + case constcrc("TransferGetCharacterDataFromLoginServer") : + { + // the TransferServer sent a request to the central server + // to retrieve a character ID from the login database given + // a source station ID and a source character name. Retrieve + // this data from the login database. + const GenericValueTypeMessage request(ri); + TransferCharacterData d = request.getValue(); + DatabaseConnection::getInstance().requestAvatarListForAccount(d.getSourceStationId(), &d); + LOG("CustomerService", ("CharacterTransfer: Received TransferGetCharactetrDataFromLoginServer from CentralServer. %s", d.toString().c_str())); + break; + } + case constcrc("TransferRenameCharacterInLoginDatabase") : + { + const GenericValueTypeMessage request(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterInLoginDatabase : %s", request.getValue().toString().c_str())); + const TransferCharacterData & requestData = request.getValue(); + DatabaseConnection::getInstance().renameCharacter(getClusterId(), requestData.getCharacterId(), Unicode::narrowToWide(requestData.getDestinationCharacterName()), &requestData); + break; + } + case constcrc("TransferKickConnectedClients") : + { + const GenericValueTypeMessage kick(ri); + ClientConnection * clientConnection = LoginServer::getInstance().getValidatedClient(kick.getValue()); + if(! clientConnection) + { + clientConnection = LoginServer::getInstance().getUnvalidatedClient(kick.getValue()); + } - LOG("CustomerService", ("BroadcastVoiceChannel: LoginServer sending AllCluserGlobalChannel to all clusters chan(%s) text(%s) remove(%d)", - channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); + if(clientConnection) + { + clientConnection->disconnect(); + } + break; + } + case constcrc("TransferAccountRequestLoginServer") : + { + const GenericValueTypeMessage request(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestLoginServer from station ID %d to from station ID %d", request.getValue().getSourceStationId(), request.getValue().getDestinationStationId())); + const TransferAccountData requestData = request.getValue(); + DatabaseConnection::getInstance().requestAvatarListAccountTransfer(&requestData); + break; + } + case constcrc("EnableCharacterMessage") : + { + const GenericValueTypeMessage, std::string> > msg(ri); - LoginServer::getInstance().sendToAllClusters(msg); - } + LOG("LoginServer", ("EnableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - else if(m.isType("GcwScoreStatRaw")) - { - GenericValueTypeMessage >, std::map > > > > const msg(ri); - LoginServer::getInstance().sendToAllClusters(msg, NULL, 0, msg.getValue().first.c_str()); - } + DatabaseConnection::getInstance().enableCharacter(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, true, m_clusterId); + break; + } + case constcrc("DisableCharacterMessage") : + { + const GenericValueTypeMessage, std::string> > msg(ri); - else if(m.isType("GcwScoreStatPct")) - { - GenericValueTypeMessage, std::map > > > const msg(ri); - LoginServer::getInstance().sendToAllClusters(msg, NULL, 0, msg.getValue().first.c_str()); + LOG("LoginServer", ("DisableCharacter %d, %s request from %s\n", msg.getValue().first.first, msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); + + DatabaseConnection::getInstance().enableCharacter(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, false, m_clusterId); + break; + } + case constcrc("DeleteFailedTransfer") : + { + GenericValueTypeMessage deleteCharacter(ri); + LOG("CustomerService", ("CharacterTransfer: LoginServer received request to delete a character for a failed transfer. %s", deleteCharacter.getValue().toString().c_str())); + LoginServer::getInstance().deleteCharacter(m_clusterId, deleteCharacter.getValue().getDestinationCharacterId(), deleteCharacter.getValue().getDestinationStationId()); + break; + } + case constcrc("RequestTransferClosePseudoClientConnection") : + { + GenericValueTypeMessage > const request(ri); + GenericValueTypeMessage const closeRequest("TransferClosePseudoClientConnection", request.getValue().second); + LoginServer::getInstance().sendToCluster(LoginServer::getInstance().getClusterIDByName(request.getValue().first), closeRequest); + break; + } + case constcrc("CSToolResponse") : + { + CSToolResponse response(ri); + // find the connection, if it still exists + CSToolConnection * con = CSToolConnection::getCSToolConnectionByToolId( response.getToolId() ); + + // send the response + if( con ) + { + std::string message; + message = m_clusterName + ":" + response.getResult(); + + if( message[ message.length() -1 ] == '\n' && message[ message.length() - 2 ] != '\r' ) + { + message[ message.length() - 1 ] = '\r'; + message += '\n'; + } + + con->sendToTool( message ); + } + break; + } + case constcrc("ConGenericMessage") : + { + ConGenericMessage con(ri); + parseCommand(con.getMsg(), con.getMsgId()); + break; + } + case constcrc("LoginToggleCompletedTutorial") : + { + GenericValueTypeMessage< std::pair > const request(ri); + std::pair values = request.getValue(); + DatabaseConnection::getInstance().toggleCompletedTutorial(values.first, values.second); + break; + } + case constcrc("AllCluserGlobalChannel") : + { + typedef std::pair, bool> PayloadType; + GenericValueTypeMessage msg(ri); + + PayloadType const & payload = msg.getValue(); + std::string const & channelName = payload.first.first; + std::string const & messageText = payload.first.second; + bool const & isRemove = payload.second; + + LOG("CustomerService", ("BroadcastVoiceChannel: LoginServer sending AllCluserGlobalChannel to all clusters chan(%s) text(%s) remove(%d)", + channelName.c_str(), messageText.c_str(), (isRemove?1:0) )); + + LoginServer::getInstance().sendToAllClusters(msg); + break; + } + case constcrc("GcwScoreStatRaw") : + { + GenericValueTypeMessage >, std::map > > > > const msg(ri); + LoginServer::getInstance().sendToAllClusters(msg, nullptr, 0, msg.getValue().first.c_str()); + break; + } + case constcrc("GcwScoreStatPct") : + { + GenericValueTypeMessage, std::map > > > const msg(ri); + LoginServer::getInstance().sendToAllClusters(msg, nullptr, 0, msg.getValue().first.c_str()); + break; + } } } @@ -354,6 +378,7 @@ void CentralServerConnection::setClusterId(uint32 clusterId) void CentralServerConnection::parseCommand(const std::string & cmd, int track) { + //TODO: wtf is this crap? // int i = s_track; // s_resultsMap[i] = this; // ++s_track; diff --git a/engine/server/application/LoginServer/src/shared/ClientConnection.cpp b/engine/server/application/LoginServer/src/shared/ClientConnection.cpp index 087796db..4af007c3 100755 --- a/engine/server/application/LoginServer/src/shared/ClientConnection.cpp +++ b/engine/server/application/LoginServer/src/shared/ClientConnection.cpp @@ -23,8 +23,14 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "sharedNetworkMessages/LoginEnumCluster.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include +#include "webAPI.h" + +using namespace StellaBellum; + //----------------------------------------------------------------------- ClientConnection::ClientConnection(UdpConnectionMT * u, TcpClient * t) : @@ -53,13 +59,20 @@ ClientConnection::~ClientConnection() void ClientConnection::onConnectionClosed() { // client has disconnected - DEBUG_REPORT_LOG(true, ("Client %lu disconnected\n", getStationId())); - LOG("LoginClientConnection", ("onConnectionClosed() for stationId (%lu) at IP (%s)", m_stationId, getRemoteAddress().c_str())); - LoginServer::getInstance().removeClient(m_clientId); - - if (!m_isValidated) + if (m_clientId) { - SessionApiClient * session = LoginServer::getInstance().getSessionApiClient(); + if (m_stationId) + { + DEBUG_REPORT_LOG(true, ("Client %lu disconnected\n", m_stationId)); + LOG("LoginClientConnection", + ("onConnectionClosed() for stationId (%lu) at IP (%s)", m_stationId, getRemoteAddress().c_str())); + } + + LoginServer::getInstance().removeClient(m_clientId); + } + + if (!m_isValidated) { + SessionApiClient *session = LoginServer::getInstance().getSessionApiClient(); if (session) session->dropClient(this); } @@ -86,77 +99,79 @@ void ClientConnection::onReceive(const Archive::ByteStream & message) GameNetworkMessage m(ri); ri = message.begin(); + const uint32 messageType = m.getType(); + //Validation check - if (!getIsValidated() && !m.isType("LoginClientId")) - { - //Receiving message from unvalidated client. Pitch it. - DEBUG_WARNING(true, ("Received %s message from unknown, unvalidated client", m.getCmdName().c_str())); + if (!getIsValidated() && messageType != constcrc("LoginClientId")) { + //Receiving message from unvalidated client. Pitch it. + DEBUG_WARNING(true, ("Received %s message from unknown, unvalidated client", m.getCmdName().c_str())); return; } - - if(m.isType("LoginClientId")) - { - // send the client the server "now" Epoch time so that the - // client has an idea of how much difference there is between - // the client's Epoch time and the server Epoch time - GenericValueTypeMessage const serverNowEpochTime( - "ServerNowEpochTime", static_cast(::time(NULL))); - send(serverNowEpochTime, true); - LoginClientId id(ri); - - // verify version -#if PRODUCTION == 1 + switch (messageType) { + case constcrc("LoginClientId") : + { + // send the client the server "now" Epoch time so that the + // client has an idea of how much difference there is between + // the client's Epoch time and the server Epoch time + GenericValueTypeMessage const serverNowEpochTime( + "ServerNowEpochTime", static_cast(::time(nullptr))); + send(serverNowEpochTime, true); - if(!ConfigLoginServer::getValidateClientVersion() || id.getVersion() == GameNetworkMessage::NetworkVersionId) - { - validateClient(id.getId(), id.getKey()); - } - else - { - LOG("CustomerService", ("Login:LoginServer dropping client (stationId=[%lu], ip=[%s], id=[%s], key=[%s], version=[%s]) because of network version mismatch (required version=[%s])", m_stationId, getRemoteAddress().c_str(), id.getId().c_str(), id.getKey().c_str(), id.getVersion().c_str(), GameNetworkMessage::NetworkVersionId.c_str())); - // disconnect is handled on the client side, as soon as it recieves this message - #if _DEBUG - LoginIncorrectClientId incorrectId(GameNetworkMessage::NetworkVersionId, ApplicationVersion::getInternalVersion()); - #else - LoginIncorrectClientId incorrectId("", ""); - #endif // _DEBUG - send(incorrectId, true); - } - -#else - - validateClient( id.getId(), id.getKey() ); - -#endif // PRODUCTION == 1 - - } - else if ( m.isType( "RequestExtendedClusterInfo" ) ) - { - LoginServer::getInstance().sendExtendedClusterInfo( *this ); - } - else if (m.isType("DeleteCharacterMessage")) - { - DeleteCharacterMessage msg(ri); - std::vector::const_iterator f = std::find(m_charactersPendingDeletion.begin(), m_charactersPendingDeletion.end(), msg.getCharacterId()); - if ((m_waitingForCharacterLoginDeletion || m_waitingForCharacterClusterDeletion) && f != m_charactersPendingDeletion.end()) - { - DeleteCharacterReplyMessage reply(DeleteCharacterReplyMessage::rc_ALREADY_IN_PROGRESS); - send(reply,true); - } - else - { - if (LoginServer::getInstance().deleteCharacter(msg.getClusterId(), msg.getCharacterId(), getStationId())) + LoginClientId id(ri); + + // verify version + #if PRODUCTION == 1 + if(!ConfigLoginServer::getValidateClientVersion() || id.getVersion() == GameNetworkMessage::NetworkVersionId) { - m_waitingForCharacterLoginDeletion=true; - m_waitingForCharacterClusterDeletion=true; - m_charactersPendingDeletion.push_back(msg.getCharacterId()); + validateClient(id.getId(), id.getKey()); } else { - DeleteCharacterReplyMessage reply(DeleteCharacterReplyMessage::rc_CLUSTER_DOWN); + LOG("CustomerService", ("Login:LoginServer dropping client (stationId=[%lu], ip=[%s], id=[%s], key=[%s], version=[%s]) because of network version mismatch (required version=[%s])", m_stationId, getRemoteAddress().c_str(), id.getId().c_str(), id.getKey().c_str(), id.getVersion().c_str(), GameNetworkMessage::NetworkVersionId.c_str())); + // disconnect is handled on the client side, as soon as it recieves this message + #if _DEBUG + LoginIncorrectClientId incorrectId(GameNetworkMessage::NetworkVersionId, ApplicationVersion::getInternalVersion()); + #else + LoginIncorrectClientId incorrectId("", ""); + #endif // _DEBUG + send(incorrectId, true); + } + #else + validateClient( id.getId(), id.getKey() ); + #endif // PRODUCTION == 1 + + break; + } + case constcrc("RequestExtendedClusterInfo" ) : + { + LoginServer::getInstance().sendExtendedClusterInfo( *this ); + break; + } + case constcrc("DeleteCharacterMessage") : + { + DeleteCharacterMessage msg(ri); + std::vector::const_iterator f = std::find(m_charactersPendingDeletion.begin(), m_charactersPendingDeletion.end(), msg.getCharacterId()); + if ((m_waitingForCharacterLoginDeletion || m_waitingForCharacterClusterDeletion) && f != m_charactersPendingDeletion.end()) + { + DeleteCharacterReplyMessage reply(DeleteCharacterReplyMessage::rc_ALREADY_IN_PROGRESS); send(reply,true); } + else + { + if (LoginServer::getInstance().deleteCharacter(msg.getClusterId(), msg.getCharacterId(), getStationId())) + { + m_waitingForCharacterLoginDeletion=true; + m_waitingForCharacterClusterDeletion=true; + m_charactersPendingDeletion.push_back(msg.getCharacterId()); + } + else + { + DeleteCharacterReplyMessage reply(DeleteCharacterReplyMessage::rc_CLUSTER_DOWN); + send(reply,true); + } + } + break; } } } @@ -168,41 +183,73 @@ void ClientConnection::onReceive(const Archive::ByteStream & message) } //----------------------------------------------------------------------- -//----------------------------------------------------------------------- -// Stub routine for station API account validation. -// Grab a challenge key from the list and send it back to the client. +// originally was used to validate station API credentials, now uses our custom api void ClientConnection::validateClient(const std::string & id, const std::string & key) { - - if (ConfigLoginServer::getValidateStationKey()) - { - m_requestedAdminSuid = atoi(id.c_str()); // for normal logins, this will be set to 0 + bool authOK = false; + StationId suid = atoi(id.c_str()); + static const std::string authURL(ConfigLoginServer::getExternalAuthUrl()); + std::string uname; - SessionApiClient * sessionApiClient = LoginServer::getInstance().getSessionApiClient(); - DEBUG_FATAL(!sessionApiClient, ("Config file says to validate with session, but no session api is installed")); - if(sessionApiClient) //lint !e774 //(Boolean within 'if' always evaluates to True) the previous DEBUG_FATAL probably causes this warning - sessionApiClient->validateClient(this, key); - } - else if (ConfigLoginServer::getDoSessionLogin()) + if (!authURL.empty()) { - SessionApiClient * sessionApiClient = LoginServer::getInstance().getSessionApiClient(); - DEBUG_FATAL(!sessionApiClient, ("Config file says to do session login, but no session api is installed")); - if(sessionApiClient) //lint !e774 //(Boolean within 'if' always evaluates to True) the previous DEBUG_FATAL probably causes this warning - sessionApiClient->loginClient(this, id, key); + // create the object + webAPI api(authURL); + + // add our data + api.addJsonData("user_name", id); + api.addJsonData("user_password", key); + api.addJsonData("ip", getRemoteAddress()); + + if (api.submit()) + { + bool status = api.getNullableValue("status"); + uname = api.getString("username"); + + if (status && !uname.empty()) + { + authOK = true; + } + else + { + std::string msg = api.getString("message"); + if (msg.empty()) + { + msg = "Invalid username or password."; + } + + ErrorMessage err("Login Failed", msg); + this->send(err, true); + } + } + else + { + ErrorMessage err("Login Failed", "Could not connect to remote."); + this->send(err, true); + } } else { - StationId suid = atoi(id.c_str()); + // test mode + authOK = true; + uname = id; + } - if (suid==0) + if (authOK) + { + if (suid == 0) { - std::hash h; - suid = h(id); //lint !e603 // Symbol 'h' not initialized (it's a functor) - } - - LOG("LoginClientConnection", ("validateClient() for stationId (%lu) at IP (%s), id (%s) key (%s), skipping validating session", m_stationId, getRemoteAddress().c_str(), id.c_str(), key.c_str())); + if (uname.length() > MAX_ACCOUNT_NAME_LENGTH) { + uname.resize(MAX_ACCOUNT_NAME_LENGTH); + } - LoginServer::getInstance().onValidateClient(suid, id, this, true, NULL, 0xFFFFFFFF, 0xFFFFFFFF); + std::hash h; + suid = h(uname.c_str()); + } + + LOG("LoginClientConnection", ("validateClient() for stationId (%lu) at IP (%s), id (%s)", m_stationId, getRemoteAddress().c_str(), uname.c_str())); + + LoginServer::getInstance().onValidateClient(suid, uname, this, true, NULL, 0xFFFFFFFF, 0xFFFFFFFF); } } diff --git a/engine/server/application/LoginServer/src/shared/ClientConnection.h b/engine/server/application/LoginServer/src/shared/ClientConnection.h index 432e875f..8f92f68f 100755 --- a/engine/server/application/LoginServer/src/shared/ClientConnection.h +++ b/engine/server/application/LoginServer/src/shared/ClientConnection.h @@ -10,6 +10,10 @@ #include "serverUtility/ServerConnection.h" #include "sharedFoundation/StationId.h" +#include +#include +#include + class ClientCommandChannel; class NetworkId; @@ -68,6 +72,20 @@ private: }; //lint !e1712 // default constructor not defined +//----------------------------------------------------------------------- + +// stolen from http://www.codeproject.com/Articles/10880/A-trim-implementation-for-std-string +// i'm rusty and haven't gotten to lambdas yet +inline const std::string trim(std::string str) +{ + + str.erase(str.begin(), std::find_if(str.begin(), str.end(), + [](char& ch)->bool { return !isspace(ch); })); + str.erase(std::find_if(str.rbegin(), str.rend(), + [](char& ch)->bool { return !isspace(ch); }).base(), str.end()); + return str; +} + //----------------------------------------------------------------------- inline const StationId ClientConnection::getStationId() const diff --git a/engine/server/application/LoginServer/src/shared/ConfigLoginServer.cpp b/engine/server/application/LoginServer/src/shared/ConfigLoginServer.cpp index 2de2a2fa..9b1d6c07 100755 --- a/engine/server/application/LoginServer/src/shared/ConfigLoginServer.cpp +++ b/engine/server/application/LoginServer/src/shared/ConfigLoginServer.cpp @@ -112,8 +112,11 @@ void ConfigLoginServer::install(void) KEY_INT (populationHeavyThresholdPercent, 32); KEY_INT (populationMediumThresholdPercent, 16); KEY_INT (populationLightThresholdPercent, 8); - KEY_INT (csToolPort, 10666); + KEY_INT (csToolPort, 0); // use 10666 if you want to turn the tool on KEY_BOOL(requireSecureLoginForCsTool, true); + KEY_BOOL(useExternalAuth, false); + KEY_STRING(externalAuthURL, ""); + KEY_INT(maxConnectionsPerIP, 4); // assuming 2 people playing in the same household int index = 0; char const * result = 0; diff --git a/engine/server/application/LoginServer/src/shared/ConfigLoginServer.h b/engine/server/application/LoginServer/src/shared/ConfigLoginServer.h index 7bd94880..330eb9f3 100755 --- a/engine/server/application/LoginServer/src/shared/ConfigLoginServer.h +++ b/engine/server/application/LoginServer/src/shared/ConfigLoginServer.h @@ -17,14 +17,14 @@ class ConfigLoginServer int maxClients; int taskServicePort; int pingServicePort; - int httpServicePort; + int httpServicePort; bool validateClientVersion; bool validateStationKey; bool doSessionLogin; - bool doConsumption; + bool doConsumption; const char * sessionServers; int sessionType; - + const char * DSN; const char * databaseUID; const char * schemaOwner; @@ -54,7 +54,7 @@ class ConfigLoginServer const char * purgeAccountSourceTable; const char * adminAccountDataTable; bool allowSkipTutorialToAll; - + bool internalBypassOnlineLimit; int populationExtremelyHeavyThresholdPercent; @@ -63,8 +63,13 @@ class ConfigLoginServer int populationMediumThresholdPercent; int populationLightThresholdPercent; int csToolPort; - - bool requireSecureLoginForCsTool; + + bool requireSecureLoginForCsTool; + bool useExternalAuth; + + const char * externalAuthURL; + + int maxConnectionsPerIP; }; static const uint16 getCentralServicePort(); @@ -79,7 +84,7 @@ class ConfigLoginServer static const bool getDoConsumption(); static const char * getSessionServers(); static const int getSessionType(); - + static const int getMaxClients (); static const char * getPrivateIpMask(); static const char * getDSN(); @@ -102,7 +107,7 @@ class ConfigLoginServer static void install (); static void remove (); - static int getNumberOfSessionServers(); + static int getNumberOfSessionServers(); static char const * getSessionServer(int index); static const int getDisconnectSleepTime (void); static const int getClusterGroup(); @@ -115,11 +120,11 @@ class ConfigLoginServer static int getPurgePhaseAdvanceDays(int purgePhase); static const char * getAdminAccountDataTable(); static bool getAllowSkipTutorialToAll(); - + static bool getInternalBypassOnlineLimit(); static const int getCSToolPort(); - static bool getRequireSecureLoginForCsTool(); + static bool getRequireSecureLoginForCsTool(); static int getPopulationExtremelyHeavyThresholdPercent(); static int getPopulationVeryHeavyThresholdPercent(); @@ -127,9 +132,14 @@ class ConfigLoginServer static int getPopulationMediumThresholdPercent(); static int getPopulationLightThresholdPercent(); + static bool getUseExternalAuth(); + static const char * getExternalAuthUrl(); + // has character creation for this cluster been disabled through config option static bool isCharacterCreationDisabled(std::string const & cluster); - static stdset::fwd const & getCharacterCreationDisabledClusterList(); + static stdset::fwd const & getCharacterCreationDisabledClusterList(); + + static const int getMaxConnectionsPerIP(); private: static Data * data; @@ -467,6 +477,21 @@ inline const int ConfigLoginServer::getCSToolPort() { return data->csToolPort; } + +inline bool ConfigLoginServer::getUseExternalAuth() +{ + return data->useExternalAuth; +} + +inline const char * ConfigLoginServer::getExternalAuthUrl() +{ + return data->externalAuthURL; +} + +inline const int ConfigLoginServer::getMaxConnectionsPerIP() +{ + return data->maxConnectionsPerIP; +} // ====================================================================== #endif // _ConfigLoginServer_H diff --git a/engine/server/application/LoginServer/src/shared/ConsoleCommandParserLoginServer.cpp b/engine/server/application/LoginServer/src/shared/ConsoleCommandParserLoginServer.cpp index b1a2dfad..5d0d579e 100755 --- a/engine/server/application/LoginServer/src/shared/ConsoleCommandParserLoginServer.cpp +++ b/engine/server/application/LoginServer/src/shared/ConsoleCommandParserLoginServer.cpp @@ -22,12 +22,6 @@ namespace CommandNames #undef MAKE_COMMAND } -const CommandParser::CmdInfo cmds[] = -{ - {"runState", 0, "", "Return the running state of the CentralServer. It should always return 'running'"}, - {"", 0, "", ""} // this must be last -}; - //----------------------------------------------------------------------- ConsoleCommandParserLoginServer::ConsoleCommandParserLoginServer() : diff --git a/engine/server/application/LoginServer/src/shared/ConsoleManager.cpp b/engine/server/application/LoginServer/src/shared/ConsoleManager.cpp index ecaaa8fa..8721d5c6 100755 --- a/engine/server/application/LoginServer/src/shared/ConsoleManager.cpp +++ b/engine/server/application/LoginServer/src/shared/ConsoleManager.cpp @@ -14,7 +14,7 @@ namespace ConsoleManagerNamespace { - ConsoleCommandParser * s_consoleCommandParserRoot = NULL; + ConsoleCommandParser * s_consoleCommandParserRoot = nullptr; } using namespace ConsoleManagerNamespace; diff --git a/engine/server/application/LoginServer/src/shared/LoginServer.cpp b/engine/server/application/LoginServer/src/shared/LoginServer.cpp index a38d3725..6e41ffc5 100755 --- a/engine/server/application/LoginServer/src/shared/LoginServer.cpp +++ b/engine/server/application/LoginServer/src/shared/LoginServer.cpp @@ -2,7 +2,6 @@ // copyright 2000 Verant Interactive // Author: Justin Randall - //----------------------------------------------------------------------- #include "FirstLoginServer.h" @@ -69,6 +68,8 @@ #include "sharedNetworkMessages/LoginEnumCluster.h" #include "sharedUtility/DataTableManager.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include //----------------------------------------------------------------------- @@ -123,27 +124,28 @@ bool ConnectionServerEntryLessThan::operator()(const LoginServer::ConnectionServ return x.numClients < y.numClients; } - //----------------------------------------------------------------------- LoginServer::LoginServer() : -Singleton(), -MessageDispatch::Receiver(), -done(false), -m_centralService(NULL), -clientService(0), -pingService(0), -keyServer(0), -m_clientMap(), -m_clusterList(), -m_sessionApiClient(0), -m_validatedClientMap(), -m_clusterStatusChanged(false), -m_soeMonitor(0) + Singleton(), + MessageDispatch::Receiver(), + done(false), + m_centralService(nullptr), + clientService(0), + pingService(0), + keyServer(0), + m_clientMap(), + m_clusterList(), + m_sessionApiClient(0), + m_validatedClientMap(), + m_clusterStatusChanged(false), + m_soeMonitor(0) { NetworkSetupData setup; setup.port = ConfigLoginServer::getClientServicePort(); setup.maxConnections = ConfigLoginServer::getMaxClients(); + setup.maxConnectionsPerIP = ConfigLoginServer::getMaxConnectionsPerIP(); + setup.oldestUnacknowledgedTimeout = 30000; setup.keepAliveDelay = 45000; setup.compress = ConfigLoginServer::getCompressClientNetworkTraffic(); setup.useTcp = false; @@ -158,12 +160,16 @@ m_soeMonitor(0) if (ConfigLoginServer::getDevelopmentMode()) { setup.port = ConfigLoginServer::getCentralServicePort(); - setup.maxConnections = 1000; + //setup.maxConnections = 1000; m_centralService = new Service(ConnectionAllocator(), setup); } - + + // only start the customer tool connection listener if the port is set (defaults to 0) setup.port = ConfigLoginServer::getCSToolPort(); - m_CSService = new Service(ConnectionAllocator(), setup ); + if (setup.port) + { + m_CSService = new Service(ConnectionAllocator(), setup); + } // set up message connections connectToMessage("ClaimRewardsMessage"); @@ -209,7 +215,7 @@ LoginServer::~LoginServer() //----------------------------------------------------------------------- -int LoginServer::addClient (ClientConnection & client) +int LoginServer::addClient(ClientConnection & client) { DEBUG_FATAL(client.getIsValidated(), ("Tried to add an already validated client?!")); //Perhaps add a debug only check to make sure a client connection isn't in twice...I'm not sure how that could happen. @@ -221,18 +227,17 @@ int LoginServer::addClient (ClientConnection & client) //----------------------------------------------------------------------- -ClientConnection* LoginServer::getValidatedClient (const StationId& clientId) +ClientConnection* LoginServer::getValidatedClient(const StationId& clientId) { std::map::iterator i = m_validatedClientMap.find(clientId); if (i == m_validatedClientMap.end()) return 0; return i->second; - } //----------------------------------------------------------------------- -ClientConnection* LoginServer::getUnvalidatedClient (int clientId) +ClientConnection* LoginServer::getUnvalidatedClient(int clientId) { WARNING_STRICT_FATAL(clientId == 0, ("Tried to get an unvalidated client with client id == 0")); std::map::iterator i = m_clientMap.find(clientId); @@ -243,18 +248,24 @@ ClientConnection* LoginServer::getUnvalidatedClient (int clientId) } //----------------------------------------------------------------------- -void LoginServer::removeClient (int clientId) +void LoginServer::removeClient(int clientId) { - WARNING_STRICT_FATAL(clientId == 0, ("Tried to remove a client with client id == 0")); - std::map::iterator i = m_clientMap.find(clientId); - if (i != m_clientMap.end()) - { - if (i->second->getIsValidated()) - { - IGNORE_RETURN(m_validatedClientMap.erase(i->second->getStationId())); - } - IGNORE_RETURN(m_clientMap.erase(clientId)); - } + if (clientId) // yeah why bother if it's 0 or null? i realize 0 is a valid int but since previously the warning below fired if it was 0....yeah, no + { + std::map::iterator i = m_clientMap.find(clientId); + if (i != m_clientMap.end()) + { + if (i->second->getIsValidated()) + { + IGNORE_RETURN(m_validatedClientMap.erase(i->second->getStationId())); + } + IGNORE_RETURN(m_clientMap.erase(clientId)); + } + } + else + { + WARNING_STRICT_FATAL(true, ("Tried to remove a client with client id == 0")); + } } //----------------------------------------------------------------------- @@ -268,7 +279,7 @@ void LoginServer::installSessionValidation() for (i = 0; i < numberOfSessionServers; ++i) { char const * const p = ConfigLoginServer::getSessionServer(i); - if(p) + if (p) { REPORT_LOG(true, ("Using session server %s\n", p)); sessionServers.push_back(p); @@ -291,7 +302,7 @@ bool LoginServer::deleteCharacter(uint32 clusterId, NetworkId const & characterI if (cle->m_centralServerConnection) { ServerDeleteCharacterMessage smsg(suid, characterId, 0); - cle->m_centralServerConnection->send(smsg,true); + cle->m_centralServerConnection->send(smsg, true); ClientConnection* target = getValidatedClient(suid); if (target) @@ -304,18 +315,17 @@ bool LoginServer::deleteCharacter(uint32 clusterId, NetworkId const & characterI } else { - DEBUG_REPORT_LOG(true,("User %lu requested deleting character %s on cluster %lu, but the cluster is not currently connected.\n",suid , characterId.getValueString().c_str(), clusterId)); + DEBUG_REPORT_LOG(true, ("User %lu requested deleting character %s on cluster %lu, but the cluster is not currently connected.\n", suid, characterId.getValueString().c_str(), clusterId)); return false; } } else { - DEBUG_REPORT_LOG(true,("User %lu requested deleting character %s on cluster %lu, but we have no cluster with that number.\n", suid, characterId.getValueString().c_str(), clusterId)); + DEBUG_REPORT_LOG(true, ("User %lu requested deleting character %s on cluster %lu, but we have no cluster with that number.\n", suid, characterId.getValueString().c_str(), clusterId)); return false; } } - //----------------------------------------------------------------------- const KeyShare::Key & LoginServer::getCurrentKey(void) const @@ -330,7 +340,6 @@ SessionApiClient * LoginServer::getSessionApiClient() return m_sessionApiClient; } - //----------------------------------------------------------------------- KeyShare::Token LoginServer::makeToken(const unsigned char * const data, const uint32 dataLen) const @@ -342,7 +351,7 @@ KeyShare::Token LoginServer::makeToken(const unsigned char * const data, const u void LoginServer::pushAllKeys(CentralServerConnection * targetGameServer) const { - for(int i = static_cast(keyServer->getKeyCount()) - 1; i >=0 ; i --) + for (int i = static_cast(keyServer->getKeyCount()) - 1; i >= 0; i--) { LoginKeyPush pk(keyServer->getKey(static_cast(i))); targetGameServer->send(pk, true); @@ -353,24 +362,24 @@ void LoginServer::pushAllKeys(CentralServerConnection * targetGameServer) const void LoginServer::pushKeyToAllServers(void) { - KeyShare::Key k = keyServer->getKey(0); - CentralServerConnection * c; + KeyShare::Key k = keyServer->getKey(0); + CentralServerConnection * c; - LoginKeyPush msg(k); + LoginKeyPush msg(k); - unsigned char s[128]; - memcpy(s, k.value, 16); //lint !e64 !e119 !e534 // not sure where lint is finding a memcpy(void *, int) prototype - DEBUG_REPORT_LOG(true, ("Key Exchange ->: ")); - for(int x = 0; x < 16; x++) - { - DEBUG_REPORT_LOG(true, ("[%3i]", s[x])); - } - DEBUG_REPORT_LOG(true, ("\n")); + unsigned char s[128]; + memcpy(s, k.value, 16); //lint !e64 !e119 !e534 // not sure where lint is finding a memcpy(void *, int) prototype + DEBUG_REPORT_LOG(true, ("Key Exchange ->: ")); + for (int x = 0; x < 16; x++) + { + DEBUG_REPORT_LOG(true, ("[%3i]", s[x])); + } + DEBUG_REPORT_LOG(true, ("\n")); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { c = (*i)->m_centralServerConnection; - if(c) + if (c) { c->send(msg, true); } @@ -382,612 +391,655 @@ void LoginServer::pushKeyToAllServers(void) void LoginServer::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { // determine message type - - if(message.isType("LoginClusterName") || message.isType( "LoginClusterName2" ) ) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const LoginClusterName msg(ri); - if(msg.getClusterName().length() > 0) - { - CentralServerConnection * connection = const_cast(safe_cast(&source)); - DEBUG_REPORT_LOG(true, ("Cluster connection %s opened\n", msg.getClusterName().c_str())); - ClusterListEntry *cle=NULL; - if (ConfigLoginServer::getDevelopmentMode()) + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("LoginClusterName") : + case constcrc("LoginClusterName2") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const LoginClusterName msg(ri); + if (msg.getClusterName().length() > 0) { - // in this mode, we trust the name sent by the cluster and we dynamically add clusters we don't know about - cle = findClusterByName(msg.getClusterName()); - if (!cle) - cle = addCluster(msg.getClusterName()); - } - else - { - // in this mode, the cluster name has to match what we were expecting - cle = findClusterByConnection(connection); - if (!cle) - DEBUG_FATAL(true,("PROGRAMMER BUG: Got a connection from %s:%hu, which we weren't expecting. Cluster name is \"%s\".\n",connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); - else - if (msg.getClusterName() != cle->m_clusterName) + CentralServerConnection * connection = const_cast(safe_cast(&source)); + DEBUG_REPORT_LOG(true, ("Cluster connection %s opened\n", msg.getClusterName().c_str())); + ClusterListEntry *cle = nullptr; + if (ConfigLoginServer::getDevelopmentMode()) { + // in this mode, we trust the name sent by the cluster + cle = findClusterByName(msg.getClusterName()); +#ifdef _DEBUG + // if in debug mode, we dynamically add clusters we don't know about + // DO NOT USE ON PRODUCTION! This is where other servers are getting hijacked. + if (!cle) { - WARNING(true,("Server %i is named \"%s\" in the database. The server at the specified address (%s:%hu) reports its name as \"%s\". It will not be allowed in the service. Either the name in the database or the name in Central's config file should be corrected.\n",cle->m_clusterId, cle->m_clusterName.c_str(), connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); - disconnectCluster(*cle,true,false); - cle=NULL; + cle = addCluster(msg.getClusterName()); } - } - - if (cle) - { - cle->m_timeZone = msg.getTimeZone(); - cle->m_centralServerConnection = connection; - cle->m_connected = true; - pushAllKeys(connection); - - if (cle->m_clusterId == 0) - { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: cle->m_clusterId was 0 in non-development mode. The code before this line should have prevented this.\n")); - DEBUG_REPORT_LOG(true,("Cluster was not on the list. Adding it to the database.\n")); - DatabaseConnection::getInstance().registerNewCluster(msg.getClusterName(), connection->getRemoteAddress()); - } - else - cle->m_centralServerConnection->setClusterId(cle->m_clusterId); - - m_clusterStatusChanged = true; - - // tell the cluster its cluster id - if (cle->m_clusterId > 0) - { - GenericValueTypeMessage const msgClusterId("ClusterId", cle->m_clusterId); - cle->m_centralServerConnection->send(msgClusterId, true); - } - - // tell the cluster about its locked and secret state - GenericValueTypeMessage > const msgState("UpdateClusterLockedAndSecretState", std::make_pair(cle->m_locked, cle->m_secret)); - cle->m_centralServerConnection->send(msgState,true); - } - } - } - else if (message.isType("LoginConnectionServerAddress")) - { - const CentralServerConnection * cs = safe_cast(&source); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - - LoginConnectionServerAddress m(ri); //lint !e1774 !e826onServerEntry entry; - ConnectionServerEntry entry; - entry.clientServiceAddress = Address(Address(m.getClientServiceAddress(), 0).getSockAddr4()).getHostAddress(); - entry.clientServicePortPrivate = m.getClientServicePortPrivate(); - entry.clientServicePortPublic = m.getClientServicePortPublic(); - entry.id = m.getId(); - entry.numClients = m.getNumClients(); - entry.pingPort = m.getPingPort (); - - DEBUG_REPORT_LOG(true, ("ConnectionServer Reconnect - address from connection server (%s), address after conversion (%s)\n", m.getClientServiceAddress().c_str(), entry.clientServiceAddress.c_str())); - - ClusterListEntry *cle = findClusterByConnection(cs); - if (cle) - { - WARNING_STRICT_FATAL(!cle->m_centralServerConnection, ("Got reconnect for connection server with no central! Cluster %s\n",cs->getClusterName().c_str())); - std::vector::iterator i = std::find(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), entry); - if (i == cle->m_connectionServers.end()) - { - cle->m_connectionServers.push_back(entry); - m_clusterStatusChanged = true; - } - else - { - *i = entry; - } - - std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); - } - else - WARNING_STRICT_FATAL(true,("Programmer bug: Got LoginConnectionServerAddress from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); - } - else if (message.isType("PreloadFinishedMessage")) - { - const CentralServerConnection * cs = safe_cast(&source); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PreloadFinishedMessage msg(ri); - - ClusterListEntry *cle = findClusterByConnection(cs); - if (cle) - { - if (msg.getFinished()) - { - DEBUG_REPORT_LOG(true, ("Cluster %s is ready for players.\n",cle->m_clusterName.c_str())); - if (!cle->m_readyForPlayers) - { - cle->m_readyForPlayers = true; - m_clusterStatusChanged = true; - } - } - else - { - DEBUG_REPORT_LOG(true, ("Cluster %s is not ready for players.\n",cle->m_clusterName.c_str())); - if (cle->m_readyForPlayers) - { - cle->m_readyForPlayers = false; - m_clusterStatusChanged = true; - PurgeManager::onClusterNoLongerReady(cle->m_clusterId); - } - } - } - else - WARNING_STRICT_FATAL(true,("Programmer bug: Got PreloadFinishedMessage from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); - } - else if(message.isType("ConnectionServerDown")) - { - - const CentralServerConnection * centralConnection = safe_cast(&source); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ConnectionServerDown c(ri); //lint !e1774 !e826 - ClusterListEntry *cle = findClusterByConnection(centralConnection); - if (cle) - { - DEBUG_REPORT_LOG(true, ("Lost a connection server %d for %s.\n", c.getId(), cle->m_clusterName.c_str())); - - std::vector::iterator iter = cle->m_connectionServers.begin(); - bool found = false; - for (; iter != cle->m_connectionServers.end(); ++iter) - { - if (iter->id == c.getId()) - { - IGNORE_RETURN(cle->m_connectionServers.erase(iter)); - std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); - found = true; - break; - } - } - DEBUG_REPORT_LOG(!found, ("Tried to remove a connection server that wasn't in our list.\n")); - m_clusterStatusChanged = true; - } - else - WARNING_STRICT_FATAL(true,("Programmer bug: Got ConnectionServerDown from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); - } - else if(message.isType("ConnectionClosed")) - { - const CentralServerConnection *c = dynamic_cast(&source); - if (c) - { - ClusterListEntry *cle = findClusterByConnection(c); - if (cle) - { - DEBUG_REPORT_LOG(true, ("Cluster connection %s closed.\n", c->getClusterName().c_str())); - disconnectCluster(*cle,false,true); - } - else - WARNING_STRICT_FATAL(true,("Programmer bug: Cluster disconnected but it wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); - } - } - else if (message.isType("ValidateAccountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateAccountMessage msg(ri); - - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().getAccountValidationData(msg.getStationId(), conn->getClusterId(), msg.getTrack(), msg.getSubscriptionBits()); - else - WARNING_STRICT_FATAL(true,("Expect ValidateAccountMessage's to only come from CentralServers.\n")); - } - else if (message.isType("CntrlSrvDropDupeConns")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - sendToAllClusters(msg, dynamic_cast(&source)); - } - else if (message.isType("AdjustAccountFeatureIdRequest")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AdjustAccountFeatureIdRequest const msg(ri); - - if (m_sessionApiClient) - { - // on a session authenticated cluster, this request should have been serviced by the ConnectionServer - } - else - { - // for testing purpose when not using session authentication, store - // the account feature Ids locally in memory, which will get cleared - // (obviously) when the LoginServer is restarted - std::map > * nonSessionTestingAccountFeatureIds = NULL; - if (msg.getGameCode() == PlatformGameCode::SWG) - nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgFeatureIds; - else if (msg.getGameCode() == PlatformGameCode::SWGTCG) - nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgTcgFeatureIds; - - int currentFeatureIdCount = 0; - int updatedFeatureIdCount = 0; - if (nonSessionTestingAccountFeatureIds) - { - std::map & accountFeatureIds = (*nonSessionTestingAccountFeatureIds)[msg.getTargetStationId()]; - std::map::const_iterator accountFeatureId = accountFeatureIds.find(msg.getFeatureId()); - if (accountFeatureId != accountFeatureIds.end()) - currentFeatureIdCount = accountFeatureId->second; - - updatedFeatureIdCount = std::max(0, currentFeatureIdCount + msg.getAdjustment()); - if (updatedFeatureIdCount > 0) - { - accountFeatureIds[msg.getFeatureId()] = updatedFeatureIdCount; +#endif } else { - IGNORE_RETURN(accountFeatureIds.erase(msg.getFeatureId())); - if (accountFeatureIds.empty()) - IGNORE_RETURN(nonSessionTestingAccountFeatureIds->erase(msg.getTargetStationId())); - } - } + // in this mode, the cluster name has to match what we were expecting + cle = findClusterByConnection(connection); + if (!cle) + DEBUG_FATAL(true, ("PROGRAMMER BUG: Got a connection from %s:%hu, which we weren't expecting. Cluster name is \"%s\".\n", connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); + else + if (msg.getClusterName() != cle->m_clusterName) + { + WARNING(true, ("Server %i is named \"%s\" in the database. The server at the specified address (%s:%hu) reports its name as \"%s\". It will not be allowed in the service. Either the name in the database or the name in Central's config file should be corrected.\n", cle->m_clusterId, cle->m_clusterName.c_str(), connection->getRemoteAddress().c_str(), connection->getRemotePort(), msg.getClusterName().c_str())); + disconnectCluster(*cle, true, false); + cle = nullptr; + } + } - // CS log SWG TCG account feature grant or SWG account feature grant for reward item trade in - if (nonSessionTestingAccountFeatureIds && !msg.getTargetPlayerDescription().empty() && msg.getTargetItem().isValid() && !msg.getTargetItemDescription().empty()) - { - if (msg.getGameCode() == PlatformGameCode::SWGTCG) - LOG("CustomerService",("TcgRedemption: %s redeemed %s for SWGTCG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); - else if (msg.getGameCode() == PlatformGameCode::SWG) - LOG("CustomerService",("VeteranRewards: %s traded in %s for SWG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); - } - - const CentralServerConnection * conn = dynamic_cast(&source); - if (conn) - { - AdjustAccountFeatureIdResponse const rsp(msg.getRequestingPlayer(), msg.getGameServer(), msg.getTargetPlayer(), msg.getTargetPlayerDescription(), msg.getTargetStationId(), msg.getTargetItem(), msg.getTargetItemDescription(), msg.getGameCode(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount, (nonSessionTestingAccountFeatureIds ? RESULT_SUCCESS : RESULT_CANCELLED), false); - sendToCluster(conn->getClusterId(), rsp); - } - } - } - else if (message.isType("AccountFeatureIdRequest")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AccountFeatureIdRequest const msg(ri); - - if (m_sessionApiClient) - { - // on a session authenticated cluster, this request should have been serviced by the ConnectionServer - } - else - { - // for testing purpose when not using session authentication, store - // the account feature Ids locally in memory, which will get cleared - // (obviously) when the LoginServer is restarted - std::map > * nonSessionTestingAccountFeatureIds = NULL; - if (msg.getGameCode() == PlatformGameCode::SWG) - nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgFeatureIds; - else if (msg.getGameCode() == PlatformGameCode::SWGTCG) - nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgTcgFeatureIds; - - static std::map const empty; - std::map const * accountFeatureIds = ∅ - - if (nonSessionTestingAccountFeatureIds) - { - std::map >::const_iterator iterFind = nonSessionTestingAccountFeatureIds->find(msg.getTargetStationId()); - if (iterFind != nonSessionTestingAccountFeatureIds->end()) - accountFeatureIds = &(iterFind->second); - } - - const CentralServerConnection * conn = dynamic_cast(&source); - if (conn) - { - static std::map const empty; - AccountFeatureIdResponse const rsp(msg.getRequester(), msg.getGameServer(), msg.getTarget(), msg.getTargetStationId(), msg.getGameCode(), msg.getRequestReason(), RESULT_SUCCESS, false, *accountFeatureIds, empty); - sendToCluster(conn->getClusterId(), rsp); - } - } - } - else if (message.isType("FeatureIdTransactionRequest")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FeatureIdTransactionRequest const fitr(ri); - - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().featureIdTransactionRequest(conn->getClusterId(), fitr.getStationId(), fitr.getPlayer(), fitr.getGameServer()); - } - else if (message.isType("FeatureIdTransactionSyncUpdate")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FeatureIdTransactionSyncUpdate const fitsu(ri); - - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().featureIdTransactionSyncUpdate(conn->getClusterId(), fitsu.getStationId(), fitsu.getPlayer(), fitsu.getItemId(), fitsu.getAdjustment()); - } - else if (message.isType("TransferRequestMoveValidation")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const TransferRequestMoveValidation request(ri); - - TransferReplyMoveValidation::TransferReplyMoveValidationResult result = TransferReplyMoveValidation::TRMVR_can_create_regular_character; - - ClusterListEntry * cle = findClusterByName(request.getDestinationGalaxy()); - if (!cle) - { - result = TransferReplyMoveValidation::TRMVR_destination_galaxy_invalid; - } - else if (!cle->m_centralServerConnection) - { - result = TransferReplyMoveValidation::TRMVR_destination_galaxy_not_connected; - } - else if (!cle->m_readyForPlayers) - { - result = TransferReplyMoveValidation::TRMVR_destination_galaxy_in_loading; - } - - if (result == TransferReplyMoveValidation::TRMVR_can_create_regular_character) - { - // check with DB to see if account is allowed to create character on the destination galaxy - LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation : %s (character template id %lu) on %s to %s on %s. Forwarding request to Login Database.", request.getSourceCharacter().c_str(), request.getSourceCharacterTemplateId(), request.getSourceGalaxy().c_str(), request.getDestinationCharacter().c_str(), request.getDestinationGalaxy().c_str())); - DatabaseConnection::getInstance().getAccountValidationData(request, cle->m_centralServerConnection->getClusterId()); - } - else - { - // send failure back to originating server - TransferReplyMoveValidation reply(request.getTransferRequestSource(), request.getTrack(), request.getSourceStationId(), request.getDestinationStationId(), request.getSourceGalaxy(), request.getDestinationGalaxy(), request.getSourceCharacter(), request.getSourceCharacterId(), request.getSourceCharacterTemplateId(), request.getDestinationCharacter(), request.getCustomerLocalizedLanguage(), result); - const CentralServerConnection * conn = dynamic_cast(&source); - if(conn) - { - ClusterListEntry * sourceEntry = findClusterById(conn->getClusterId()); - if(sourceEntry && sourceEntry->m_centralServerConnection) + if (cle) { - sourceEntry->m_centralServerConnection->send(reply, true); - } - } - } - } - else if (message.isType("TransferReplyNameValidation")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const replyNameValidation(ri); + cle->m_timeZone = msg.getTimeZone(); + cle->m_centralServerConnection = connection; + cle->m_connected = true; + pushAllKeys(connection); - const CentralServerConnection * conn = dynamic_cast(&source); - if (conn) - { - ClusterListEntry * cle = findClusterByName(replyNameValidation.getValue().second.getSourceGalaxy()); - if (cle && cle->m_centralServerConnection) - { - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from destination galaxy CentralServer, forwarding to source galaxy CentralServer : %s", replyNameValidation.getValue().second.toString().c_str())); - cle->m_centralServerConnection->send(replyNameValidation, true); - } - } - } - else if (message.isType("TransferLoginCharacterToDestinationServer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const login(ri); - - const CentralServerConnection * conn = dynamic_cast(&source); - if (conn) - { - ClusterListEntry * cle = findClusterByName(login.getValue().getDestinationGalaxy()); - if (cle && cle->m_centralServerConnection) - { - LOG("CustomerService", ("CharacterTransfer: Received TransferLoginCharacterToDestinationServer from source galaxy CentralServer, forwarding to destination galaxy CentralServer : %s", login.getValue().toString().c_str())); - cle->m_centralServerConnection->send(login, true); - } - } - } - else if (message.isType("UpdateLoginConnectionServerStatus")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UpdateLoginConnectionServerStatus msg(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - { - ClusterListEntry *cle = findClusterByConnection(conn); - if (cle) - { - std::vector::iterator i = cle->m_connectionServers.begin(); - for (; i!= cle->m_connectionServers.end(); ++i) - { - if (i->id == msg.getId()) + if (cle->m_clusterId == 0) { - i->clientServicePortPublic = msg.getPublicPort(); - i->clientServicePortPrivate = msg.getPrivatePort(); - i->numClients = msg.getPlayerCount(); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: cle->m_clusterId was 0 in non-development mode. The code before this line should have prevented this.\n")); + DEBUG_REPORT_LOG(true, ("Cluster was not on the list. Adding it to the database.\n")); + DatabaseConnection::getInstance().registerNewCluster(msg.getClusterName(), connection->getRemoteAddress()); + } + else + cle->m_centralServerConnection->setClusterId(cle->m_clusterId); + + m_clusterStatusChanged = true; + + // tell the cluster its cluster id + if (cle->m_clusterId > 0) + { + GenericValueTypeMessage const msgClusterId("ClusterId", cle->m_clusterId); + cle->m_centralServerConnection->send(msgClusterId, true); + } + + // tell the cluster about its locked and secret state + GenericValueTypeMessage > const msgState("UpdateClusterLockedAndSecretState", std::make_pair(cle->m_locked, cle->m_secret)); + cle->m_centralServerConnection->send(msgState, true); + } + } + break; + } + case constcrc("LoginConnectionServerAddress") : + { + const CentralServerConnection * cs = safe_cast(&source); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + + LoginConnectionServerAddress m(ri); //lint !e1774 !e826onServerEntry entry; + ConnectionServerEntry entry; + entry.clientServiceAddress = Address(Address(m.getClientServiceAddress(), 0).getSockAddr4()).getHostAddress(); + entry.clientServicePortPrivate = m.getClientServicePortPrivate(); + entry.clientServicePortPublic = m.getClientServicePortPublic(); + entry.id = m.getId(); + entry.numClients = m.getNumClients(); + entry.pingPort = m.getPingPort(); + + DEBUG_REPORT_LOG(true, ("ConnectionServer Reconnect - address from connection server (%s), address after conversion (%s)\n", m.getClientServiceAddress().c_str(), entry.clientServiceAddress.c_str())); + + ClusterListEntry *cle = findClusterByConnection(cs); + if (cle) + { + WARNING_STRICT_FATAL(!cle->m_centralServerConnection, ("Got reconnect for connection server with no central! Cluster %s\n", cs->getClusterName().c_str())); + std::vector::iterator i = std::find(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), entry); + if (i == cle->m_connectionServers.end()) + { + cle->m_connectionServers.push_back(entry); + m_clusterStatusChanged = true; + } + else + { + *i = entry; + } + + std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); + } + else + WARNING_STRICT_FATAL(true, ("Programmer bug: Got LoginConnectionServerAddress from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + break; + } + case constcrc("PreloadFinishedMessage") : + { + const CentralServerConnection * cs = safe_cast(&source); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PreloadFinishedMessage msg(ri); + + ClusterListEntry *cle = findClusterByConnection(cs); + if (cle) + { + if (msg.getFinished()) + { + REPORT_LOG(true, ("Cluster %s is ready for players.\n", cle->m_clusterName.c_str())); + if (!cle->m_readyForPlayers) + { + cle->m_readyForPlayers = true; + m_clusterStatusChanged = true; + } + } + else + { + REPORT_LOG(true, ("Cluster %s is not ready for players.\n", cle->m_clusterName.c_str())); + if (cle->m_readyForPlayers) + { + cle->m_readyForPlayers = false; + m_clusterStatusChanged = true; + PurgeManager::onClusterNoLongerReady(cle->m_clusterId); + } + } + } + else + WARNING_STRICT_FATAL(true, ("Programmer bug: Got PreloadFinishedMessage from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + + break; + } + case constcrc("ConnectionServerDown") : + { + const CentralServerConnection * centralConnection = safe_cast(&source); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ConnectionServerDown c(ri); //lint !e1774 !e826 + ClusterListEntry *cle = findClusterByConnection(centralConnection); + if (cle) + { + DEBUG_REPORT_LOG(true, ("Lost a connection server %d for %s.\n", c.getId(), cle->m_clusterName.c_str())); + + std::vector::iterator iter = cle->m_connectionServers.begin(); + bool found = false; + for (; iter != cle->m_connectionServers.end(); ++iter) + { + if (iter->id == c.getId()) + { + IGNORE_RETURN(cle->m_connectionServers.erase(iter)); + std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); + found = true; break; } } - std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); + DEBUG_REPORT_LOG(!found, ("Tried to remove a connection server that wasn't in our list.\n")); + m_clusterStatusChanged = true; } + else + WARNING_STRICT_FATAL(true, ("Programmer bug: Got ConnectionServerDown from a cluster that wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); + + break; } - - } - else if (message.isType("UpdatePlayerCountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UpdatePlayerCountMessage msg(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) + case constcrc("ConnectionClosed") : { - ClusterListEntry *cle = findClusterByConnection(conn); - if (cle) + const CentralServerConnection *c = dynamic_cast(&source); + if (c) { - const int tutorialPlayerCount = (msg.getEmptySceneCount() + msg.getTutorialSceneCount() + msg.getFalconSceneCount()); - - // We only want to update the clients if some "threshold" has been crossed - if ((cle->m_notRecommendedCentral != msg.getLoadedRecently()) - || hasCrossedThreshold(cle->m_onlineTutorialLimit, cle->m_numTutorialPlayers, tutorialPlayerCount) - || hasCrossedThreshold(cle->m_onlineFreeTrialLimit, cle->m_numFreeTrialPlayers, msg.getFreeTrialCount()) - || hasCrossedThreshold(cle->m_onlinePlayerLimit, cle->m_numPlayers, msg.getCount())) + ClusterListEntry *cle = findClusterByConnection(c); + if (cle) { - m_clusterStatusChanged = true; + DEBUG_REPORT_LOG(true, ("Cluster connection %s closed.\n", c->getClusterName().c_str())); + disconnectCluster(*cle, false, true); } - - cle->m_numPlayers = msg.getCount(); - cle->m_numFreeTrialPlayers = msg.getFreeTrialCount(); - cle->m_notRecommendedCentral = msg.getLoadedRecently(); - cle->m_numTutorialPlayers = tutorialPlayerCount; + else + WARNING_STRICT_FATAL(true, ("Programmer bug: Cluster disconnected but it wasn't on the list. Probably indicates we aren't tracking connections properly.\n")); } + break; } - } - else if (message.isType("RenameCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RenameCharacterMessage msg(ri); - - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().renameCharacter(conn->getClusterId(), msg.getCharacterId(), msg.getNewName(), NULL); - else - WARNING_STRICT_FATAL(true,("Got RenameCharacterMessage from something other than CentralServerConnection.\n")); - } - else if (message.isType("LoginCreateCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginCreateCharacterMessage msg(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().createCharacter(conn->getClusterId(),msg.getStationId(),msg.getCharacterName(),msg.getCharacterObjectId(),msg.getTemplateId(), msg.getJedi()); - } - else if (message.isType("LoginRestoreCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginRestoreCharacterMessage msg(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().restoreCharacter(conn->getClusterId(),msg.getWhoRequested(),msg.getAccount(),msg.getCharacterName(),msg.getCharacterId(),msg.getTemplateId(), msg.getJedi()); - } - else if (message.isType("LoginUpgradeAccountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoginUpgradeAccountMessage *msg = new LoginUpgradeAccountMessage(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().upgradeAccount(msg,conn->getClusterId()); - } - else if (message.isType("ClaimRewardsMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ClaimRewardsMessage const * msg = new ClaimRewardsMessage(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) + case constcrc("ValidateAccountMessage") : { - // current restriction is that once per account event or item cannot require a "consuming" account feature id - uint32 const requiredAccountFeatureId = msg->getAccountFeatureId(); - bool const consumeAccountFeatureId = msg->getConsumeAccountFeatureId(); - if ((msg->getConsumeEvent() || msg->getConsumeItem()) && (requiredAccountFeatureId > 0) && consumeAccountFeatureId) + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateAccountMessage msg(ri); + + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().getAccountValidationData(msg.getStationId(), conn->getClusterId(), msg.getTrack(), msg.getSubscriptionBits()); + else + WARNING_STRICT_FATAL(true, ("Expect ValidateAccountMessage's to only come from CentralServers.\n")); + break; + } + case constcrc("CntrlSrvDropDupeConns") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + sendToAllClusters(msg, dynamic_cast(&source)); + break; + } + case constcrc("AdjustAccountFeatureIdRequest") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AdjustAccountFeatureIdRequest const msg(ri); + + if (m_sessionApiClient) { - ClaimRewardsReplyMessage const rsp(msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getRewardItem(), requiredAccountFeatureId, consumeAccountFeatureId, 0, 0, false); - sendToCluster(conn->getClusterId(), rsp); - delete msg; + // on a session authenticated cluster, this request should have been serviced by the ConnectionServer } - else if (requiredAccountFeatureId > 0) + else { - if (m_sessionApiClient) + // for testing purpose when not using session authentication, store + // the account feature Ids locally in memory, which will get cleared + // (obviously) when the LoginServer is restarted + std::map > * nonSessionTestingAccountFeatureIds = nullptr; + if (msg.getGameCode() == PlatformGameCode::SWG) + nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgFeatureIds; + else if (msg.getGameCode() == PlatformGameCode::SWGTCG) + nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgTcgFeatureIds; + + int currentFeatureIdCount = 0; + int updatedFeatureIdCount = 0; + if (nonSessionTestingAccountFeatureIds) { - if (consumeAccountFeatureId) + std::map & accountFeatureIds = (*nonSessionTestingAccountFeatureIds)[msg.getTargetStationId()]; + std::map::const_iterator accountFeatureId = accountFeatureIds.find(msg.getFeatureId()); + if (accountFeatureId != accountFeatureIds.end()) + currentFeatureIdCount = accountFeatureId->second; + + updatedFeatureIdCount = std::max(0, currentFeatureIdCount + msg.getAdjustment()); + if (updatedFeatureIdCount > 0) { - // request session/Platform to update the account feature id - // SessionApiClient will own (and delete) msg - m_sessionApiClient->handleClaimRewardsMessage(conn->getClusterId(), msg); + accountFeatureIds[msg.getFeatureId()] = updatedFeatureIdCount; } else { - LoginAPI::Feature oldFeature; - oldFeature.SetID(requiredAccountFeatureId); - oldFeature.SetData(msg->getAccountFeatureIdOldValue()); + IGNORE_RETURN(accountFeatureIds.erase(msg.getFeatureId())); + if (accountFeatureIds.empty()) + IGNORE_RETURN(nonSessionTestingAccountFeatureIds->erase(msg.getTargetStationId())); + } + } - LoginAPI::Feature newFeature; - newFeature.SetID(requiredAccountFeatureId); - newFeature.SetData(msg->getAccountFeatureIdNewValue()); + // CS log SWG TCG account feature grant or SWG account feature grant for reward item trade in + if (nonSessionTestingAccountFeatureIds && !msg.getTargetPlayerDescription().empty() && msg.getTargetItem().isValid() && !msg.getTargetItemDescription().empty()) + { + if (msg.getGameCode() == PlatformGameCode::SWGTCG) + LOG("CustomerService", ("TcgRedemption: %s redeemed %s for SWGTCG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); + else if (msg.getGameCode() == PlatformGameCode::SWG) + LOG("CustomerService", ("VeteranRewards: %s traded in %s for SWG account feature Id %lu (%d -> %d)", msg.getTargetPlayerDescription().c_str(), msg.getTargetItemDescription().c_str(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount)); + } + + const CentralServerConnection * conn = dynamic_cast(&source); + if (conn) + { + AdjustAccountFeatureIdResponse const rsp(msg.getRequestingPlayer(), msg.getGameServer(), msg.getTargetPlayer(), msg.getTargetPlayerDescription(), msg.getTargetStationId(), msg.getTargetItem(), msg.getTargetItemDescription(), msg.getGameCode(), msg.getFeatureId(), currentFeatureIdCount, updatedFeatureIdCount, (nonSessionTestingAccountFeatureIds ? RESULT_SUCCESS : RESULT_CANCELLED), false); + sendToCluster(conn->getClusterId(), rsp); + } + } + break; + } + case constcrc("AccountFeatureIdRequest") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AccountFeatureIdRequest const msg(ri); + + if (m_sessionApiClient) + { + // on a session authenticated cluster, this request should have been serviced by the ConnectionServer + } + else + { + // for testing purpose when not using session authentication, store + // the account feature Ids locally in memory, which will get cleared + // (obviously) when the LoginServer is restarted + std::map > * nonSessionTestingAccountFeatureIds = nullptr; + if (msg.getGameCode() == PlatformGameCode::SWG) + nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgFeatureIds; + else if (msg.getGameCode() == PlatformGameCode::SWGTCG) + nonSessionTestingAccountFeatureIds = &s_nonSessionTestingAccountSwgTcgFeatureIds; + + static std::map const empty; + std::map const * accountFeatureIds = ∅ + + if (nonSessionTestingAccountFeatureIds) + { + std::map >::const_iterator iterFind = nonSessionTestingAccountFeatureIds->find(msg.getTargetStationId()); + if (iterFind != nonSessionTestingAccountFeatureIds->end()) + accountFeatureIds = &(iterFind->second); + } + + const CentralServerConnection * conn = dynamic_cast(&source); + if (conn) + { + static std::map const empty; + AccountFeatureIdResponse const rsp(msg.getRequester(), msg.getGameServer(), msg.getTarget(), msg.getTargetStationId(), msg.getGameCode(), msg.getRequestReason(), RESULT_SUCCESS, false, *accountFeatureIds, empty); + sendToCluster(conn->getClusterId(), rsp); + } + } + break; + } + case constcrc("FeatureIdTransactionRequest") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FeatureIdTransactionRequest const fitr(ri); + + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().featureIdTransactionRequest(conn->getClusterId(), fitr.getStationId(), fitr.getPlayer(), fitr.getGameServer()); + break; + } + case constcrc("FeatureIdTransactionSyncUpdate") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FeatureIdTransactionSyncUpdate const fitsu(ri); + + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().featureIdTransactionSyncUpdate(conn->getClusterId(), fitsu.getStationId(), fitsu.getPlayer(), fitsu.getItemId(), fitsu.getAdjustment()); + break; + } + case constcrc("TransferRequestMoveValidation") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const TransferRequestMoveValidation request(ri); + + TransferReplyMoveValidation::TransferReplyMoveValidationResult result = TransferReplyMoveValidation::TRMVR_can_create_regular_character; + + ClusterListEntry * cle = findClusterByName(request.getDestinationGalaxy()); + if (!cle) + { + result = TransferReplyMoveValidation::TRMVR_destination_galaxy_invalid; + } + else if (!cle->m_centralServerConnection) + { + result = TransferReplyMoveValidation::TRMVR_destination_galaxy_not_connected; + } + else if (!cle->m_readyForPlayers) + { + result = TransferReplyMoveValidation::TRMVR_destination_galaxy_in_loading; + } + + if (result == TransferReplyMoveValidation::TRMVR_can_create_regular_character) + { + // check with DB to see if account is allowed to create character on the destination galaxy + LOG("CustomerService", ("CharacterTransfer: Received TransferRequestMoveValidation : %s (character template id %lu) on %s to %s on %s. Forwarding request to Login Database.", request.getSourceCharacter().c_str(), request.getSourceCharacterTemplateId(), request.getSourceGalaxy().c_str(), request.getDestinationCharacter().c_str(), request.getDestinationGalaxy().c_str())); + DatabaseConnection::getInstance().getAccountValidationData(request, cle->m_centralServerConnection->getClusterId()); + } + else + { + // send failure back to originating server + TransferReplyMoveValidation reply(request.getTransferRequestSource(), request.getTrack(), request.getSourceStationId(), request.getDestinationStationId(), request.getSourceGalaxy(), request.getDestinationGalaxy(), request.getSourceCharacter(), request.getSourceCharacterId(), request.getSourceCharacterTemplateId(), request.getDestinationCharacter(), request.getCustomerLocalizedLanguage(), result); + const CentralServerConnection * conn = dynamic_cast(&source); + if (conn) + { + ClusterListEntry * sourceEntry = findClusterById(conn->getClusterId()); + if (sourceEntry && sourceEntry->m_centralServerConnection) + { + sourceEntry->m_centralServerConnection->send(reply, true); + } + } + } + break; + } + case constcrc("TransferReplyNameValidation") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const replyNameValidation(ri); + + const CentralServerConnection * conn = dynamic_cast(&source); + if (conn) + { + ClusterListEntry * cle = findClusterByName(replyNameValidation.getValue().second.getSourceGalaxy()); + if (cle && cle->m_centralServerConnection) + { + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyNameValidation from destination galaxy CentralServer, forwarding to source galaxy CentralServer : %s", replyNameValidation.getValue().second.toString().c_str())); + cle->m_centralServerConnection->send(replyNameValidation, true); + } + } + break; + } + case constcrc("TransferLoginCharacterToDestinationServer") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage const login(ri); + + const CentralServerConnection * conn = dynamic_cast(&source); + if (conn) + { + ClusterListEntry * cle = findClusterByName(login.getValue().getDestinationGalaxy()); + if (cle && cle->m_centralServerConnection) + { + LOG("CustomerService", ("CharacterTransfer: Received TransferLoginCharacterToDestinationServer from source galaxy CentralServer, forwarding to destination galaxy CentralServer : %s", login.getValue().toString().c_str())); + cle->m_centralServerConnection->send(login, true); + } + } + break; + } + case constcrc("UpdateLoginConnectionServerStatus") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UpdateLoginConnectionServerStatus msg(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + { + ClusterListEntry *cle = findClusterByConnection(conn); + if (cle) + { + std::vector::iterator i = cle->m_connectionServers.begin(); + for (; i != cle->m_connectionServers.end(); ++i) + { + if (i->id == msg.getId()) + { + i->clientServicePortPublic = msg.getPublicPort(); + i->clientServicePortPrivate = msg.getPrivatePort(); + i->numClients = msg.getPlayerCount(); + break; + } + } + std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); + } + } + break; + } + case constcrc("UpdatePlayerCountMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UpdatePlayerCountMessage msg(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + { + ClusterListEntry *cle = findClusterByConnection(conn); + if (cle) + { + const int tutorialPlayerCount = (msg.getEmptySceneCount() + msg.getTutorialSceneCount() + msg.getFalconSceneCount()); + + // We only want to update the clients if some "threshold" has been crossed + if ((cle->m_notRecommendedCentral != msg.getLoadedRecently()) + || hasCrossedThreshold(cle->m_onlineTutorialLimit, cle->m_numTutorialPlayers, tutorialPlayerCount) + || hasCrossedThreshold(cle->m_onlineFreeTrialLimit, cle->m_numFreeTrialPlayers, msg.getFreeTrialCount()) + || hasCrossedThreshold(cle->m_onlinePlayerLimit, cle->m_numPlayers, msg.getCount())) + { + m_clusterStatusChanged = true; + } + + cle->m_numPlayers = msg.getCount(); + cle->m_numFreeTrialPlayers = msg.getFreeTrialCount(); + cle->m_notRecommendedCentral = msg.getLoadedRecently(); + cle->m_numTutorialPlayers = tutorialPlayerCount; + } + } + break; + } + case constcrc("RenameCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RenameCharacterMessage msg(ri); + + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().renameCharacter(conn->getClusterId(), msg.getCharacterId(), msg.getNewName(), nullptr); + else + WARNING_STRICT_FATAL(true, ("Got RenameCharacterMessage from something other than CentralServerConnection.\n")); + + break; + } + case constcrc("LoginCreateCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginCreateCharacterMessage msg(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().createCharacter(conn->getClusterId(), msg.getStationId(), msg.getCharacterName(), msg.getCharacterObjectId(), msg.getTemplateId(), msg.getJedi()); + + break; + } + case constcrc("LoginRestoreCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginRestoreCharacterMessage msg(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().restoreCharacter(conn->getClusterId(), msg.getWhoRequested(), msg.getAccount(), msg.getCharacterName(), msg.getCharacterId(), msg.getTemplateId(), msg.getJedi()); + + break; + } + case constcrc("LoginUpgradeAccountMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoginUpgradeAccountMessage *msg = new LoginUpgradeAccountMessage(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().upgradeAccount(msg, conn->getClusterId()); + + break; + } + case constcrc("ClaimRewardsMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ClaimRewardsMessage const * msg = new ClaimRewardsMessage(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + { + // current restriction is that once per account event or item cannot require a "consuming" account feature id + uint32 const requiredAccountFeatureId = msg->getAccountFeatureId(); + bool const consumeAccountFeatureId = msg->getConsumeAccountFeatureId(); + if ((msg->getConsumeEvent() || msg->getConsumeItem()) && (requiredAccountFeatureId > 0) && consumeAccountFeatureId) + { + ClaimRewardsReplyMessage const rsp(msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getRewardItem(), requiredAccountFeatureId, consumeAccountFeatureId, 0, 0, false); + sendToCluster(conn->getClusterId(), rsp); + delete msg; + } + else if (requiredAccountFeatureId > 0) + { + if (m_sessionApiClient) + { + if (consumeAccountFeatureId) + { + // request session/Platform to update the account feature id + // SessionApiClient will own (and delete) msg + m_sessionApiClient->handleClaimRewardsMessage(conn->getClusterId(), msg); + } + else + { + LoginAPI::Feature oldFeature; + oldFeature.SetID(requiredAccountFeatureId); + oldFeature.SetData(msg->getAccountFeatureIdOldValue()); + + LoginAPI::Feature newFeature; + newFeature.SetID(requiredAccountFeatureId); + newFeature.SetData(msg->getAccountFeatureIdNewValue()); + + DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), requiredAccountFeatureId, false, oldFeature.GetConsumeCount(), newFeature.GetConsumeCount()); + delete msg; + } + } + else + { + // for testing purpose when not using session authentication, store + // the account feature Ids locally in memory, which will get cleared + // (obviously) when the LoginServer is restarted + std::map & accountFeatureIds = s_nonSessionTestingAccountSwgFeatureIds[msg->getStationId()]; + std::map::const_iterator accountFeatureId = accountFeatureIds.find(requiredAccountFeatureId); + int currentFeatureIdCount = 0; + if (accountFeatureId != accountFeatureIds.end()) + currentFeatureIdCount = accountFeatureId->second; + + if (currentFeatureIdCount <= 0) + { + // fail because account doesn't have required feature id + IGNORE_RETURN(accountFeatureIds.erase(requiredAccountFeatureId)); + if (accountFeatureIds.empty()) + IGNORE_RETURN(s_nonSessionTestingAccountSwgFeatureIds.erase(msg->getStationId())); + + ClaimRewardsReplyMessage rsp(msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getRewardItem(), requiredAccountFeatureId, consumeAccountFeatureId, 0, 0, false); + sendToCluster(conn->getClusterId(), rsp); + } + else + { + // account has required feature id so claim is success, so update feature id for claim + int const updatedFeatureIdCount = (consumeAccountFeatureId ? std::max(0, currentFeatureIdCount - 1) : currentFeatureIdCount); + + if (consumeAccountFeatureId) + { + if (updatedFeatureIdCount > 0) + { + accountFeatureIds[requiredAccountFeatureId] = updatedFeatureIdCount; + } + else + { + IGNORE_RETURN(accountFeatureIds.erase(requiredAccountFeatureId)); + if (accountFeatureIds.empty()) + IGNORE_RETURN(s_nonSessionTestingAccountSwgFeatureIds.erase(msg->getStationId())); + } + } + + // if feature id updated successfully, record transaction + DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), requiredAccountFeatureId, consumeAccountFeatureId, currentFeatureIdCount, updatedFeatureIdCount); + } - DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), requiredAccountFeatureId, false, oldFeature.GetConsumeCount(), newFeature.GetConsumeCount()); delete msg; } } else { - // for testing purpose when not using session authentication, store - // the account feature Ids locally in memory, which will get cleared - // (obviously) when the LoginServer is restarted - std::map & accountFeatureIds = s_nonSessionTestingAccountSwgFeatureIds[msg->getStationId()]; - std::map::const_iterator accountFeatureId = accountFeatureIds.find(requiredAccountFeatureId); - int currentFeatureIdCount = 0; - if (accountFeatureId != accountFeatureIds.end()) - currentFeatureIdCount = accountFeatureId->second; - - if (currentFeatureIdCount <= 0) - { - // fail because account doesn't have required feature id - IGNORE_RETURN(accountFeatureIds.erase(requiredAccountFeatureId)); - if (accountFeatureIds.empty()) - IGNORE_RETURN(s_nonSessionTestingAccountSwgFeatureIds.erase(msg->getStationId())); - - ClaimRewardsReplyMessage rsp(msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getRewardItem(), requiredAccountFeatureId, consumeAccountFeatureId, 0, 0, false); - sendToCluster(conn->getClusterId(), rsp); - } - else - { - // account has required feature id so claim is success, so update feature id for claim - int const updatedFeatureIdCount = (consumeAccountFeatureId ? std::max(0, currentFeatureIdCount - 1) : currentFeatureIdCount); - - if (consumeAccountFeatureId) - { - if (updatedFeatureIdCount > 0) - { - accountFeatureIds[requiredAccountFeatureId] = updatedFeatureIdCount; - } - else - { - IGNORE_RETURN(accountFeatureIds.erase(requiredAccountFeatureId)); - if (accountFeatureIds.empty()) - IGNORE_RETURN(s_nonSessionTestingAccountSwgFeatureIds.erase(msg->getStationId())); - } - } - - // if feature id updated successfully, record transaction - DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), requiredAccountFeatureId, consumeAccountFeatureId, currentFeatureIdCount, updatedFeatureIdCount); - } - + DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), 0, false, 0, 0); delete msg; } } else { - DatabaseConnection::getInstance().claimRewards(conn->getClusterId(), msg->getGameServer(), msg->getStationId(), msg->getPlayer(), msg->getRewardEvent(), msg->getConsumeEvent(), msg->getRewardItem(), msg->getConsumeItem(), 0, false, 0, 0); delete msg; } + + break; } - else + case constcrc("PurgeCompleteMessage") : { - delete msg; + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + PurgeManager::handlePurgeCompleteOnCluster(msg.getValue(), conn->getClusterId()); + else + WARNING_STRICT_FATAL(true, ("Programmer bug: got PurgeCompleteMessage from something that couldn't be cast to a CentralServerConnection")); + + break; } - } - else if (message.isType("PurgeCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - PurgeManager::handlePurgeCompleteOnCluster(msg.getValue(), conn->getClusterId()); - else - WARNING_STRICT_FATAL(true,("Programmer bug: got PurgeCompleteMessage from something that couldn't be cast to a CentralServerConnection")); - } - else if (message.isType("OccupyUnlockedSlotReq")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq(ri); + case constcrc("OccupyUnlockedSlotReq") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().occupyUnlockedSlot(conn->getClusterId(), static_cast(occupyUnlockedSlotReq.getValue().first.first), occupyUnlockedSlotReq.getValue().first.second, occupyUnlockedSlotReq.getValue().second); - } - else if (message.isType("VacateUnlockedSlotReq")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().occupyUnlockedSlot(conn->getClusterId(), static_cast(occupyUnlockedSlotReq.getValue().first.first), occupyUnlockedSlotReq.getValue().first.second, occupyUnlockedSlotReq.getValue().second); + + break; + } + case constcrc("VacateUnlockedSlotReq") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().vacateUnlockedSlot(conn->getClusterId(), static_cast(vacateUnlockedSlotReq.getValue().first.first), vacateUnlockedSlotReq.getValue().first.second, vacateUnlockedSlotReq.getValue().second); - } - else if (message.isType("SwapUnlockedSlotReq")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq(ri); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().vacateUnlockedSlot(conn->getClusterId(), static_cast(vacateUnlockedSlotReq.getValue().first.first), vacateUnlockedSlotReq.getValue().first.second, vacateUnlockedSlotReq.getValue().second); + + break; + } + case constcrc("SwapUnlockedSlotReq") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq(ri); - const CentralServerConnection *conn = dynamic_cast(&source); - if (conn) - DatabaseConnection::getInstance().swapUnlockedSlot(conn->getClusterId(), static_cast(swapUnlockedSlotReq.getValue().first.first), swapUnlockedSlotReq.getValue().first.second, swapUnlockedSlotReq.getValue().second.second, swapUnlockedSlotReq.getValue().second.first); + const CentralServerConnection *conn = dynamic_cast(&source); + if (conn) + DatabaseConnection::getInstance().swapUnlockedSlot(conn->getClusterId(), static_cast(swapUnlockedSlotReq.getValue().first.first), swapUnlockedSlotReq.getValue().first.second, swapUnlockedSlotReq.getValue().second.second, swapUnlockedSlotReq.getValue().second.first); + + break; + } } } @@ -1010,11 +1062,11 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, // allow logins unless the cluster is full bool clientIsInternal = false; ClientConnection *conn = getValidatedClient(stationId); - if (conn) + if (conn) { clientIsInternal = AdminAccountManager::isInternalIp(conn->getRemoteAddress()); } - + if (clientIsInternal && ConfigLoginServer::getInternalBypassOnlineLimit()) { canLogin = true; @@ -1022,17 +1074,17 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, else if (cle->m_numPlayers <= cle->m_onlinePlayerLimit) { canLogin = true; - + // Check cluster npe user limit if (cle->m_numTutorialPlayers > cle->m_onlineTutorialLimit) { - canCreateRegular=false; - canCreateJedi=false; + canCreateRegular = false; + canCreateJedi = false; } - + // limit login/character creation based on subscription feature bits - if ( ((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) - && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)) + if (((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) + && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)) { // Check cluster free trial user limit if (cle->m_numFreeTrialPlayers > cle->m_onlineFreeTrialLimit) @@ -1042,25 +1094,25 @@ void LoginServer::validateAccount(const StationId& stationId, uint32 clusterId, // Check cluster free trial character creation if (!cle->m_freeTrialCanCreateChar) { - canCreateRegular=false; - canCreateJedi=false; + canCreateRegular = false; + canCreateJedi = false; } } } if (!canLogin) { - canCreateRegular=false; - canCreateJedi=false; - canSkipTutorial=false; + canCreateRegular = false; + canCreateJedi = false; + canSkipTutorial = false; } // check if we want to allow skip tutorial to all if (ConfigLoginServer::getAllowSkipTutorialToAll()) - canSkipTutorial=true; + canSkipTutorial = true; ValidateAccountReplyMessage msg(stationId, canLogin, canCreateRegular, canCreateJedi, canSkipTutorial, track, consumedRewardEvents, claimedRewardItems); - cle->m_centralServerConnection->send(msg,true); + cle->m_centralServerConnection->send(msg, true); } } @@ -1095,7 +1147,7 @@ void LoginServer::validateAccountForTransfer(const TransferRequestMoveValidation } ClusterListEntry * cle = findClusterById(clusterId); - if(cle && cle->m_centralServerConnection) + if (cle && cle->m_centralServerConnection) { TransferReplyMoveValidation response(request.getTransferRequestSource(), request.getTrack(), request.getSourceStationId(), request.getDestinationStationId(), request.getSourceGalaxy(), request.getDestinationGalaxy(), request.getSourceCharacter(), request.getSourceCharacterId(), sourceCharacterTemplateId, request.getDestinationCharacter(), request.getCustomerLocalizedLanguage(), (canCreateRegular ? TransferReplyMoveValidation::TRMVR_can_create_regular_character : TransferReplyMoveValidation::TRMVR_cannot_create_regular_character)); cle->m_centralServerConnection->send(response, true); @@ -1126,7 +1178,7 @@ void LoginServer::run(void) mon->add(masterChannel, WORLD_COUNT_CHANNEL); std::string host = NetworkHandler::getHostName().c_str(); size_t dotPos = host.find("."); - if(dotPos != host.npos) + if (dotPos != host.npos) { host = host.substr(0, dotPos - 1); } @@ -1136,11 +1188,11 @@ void LoginServer::run(void) mon->add("Galaxies", CLUSTER_COUNT_CHANNEL); - while(!getInstance().done) + while (!getInstance().done) { startTime = Clock::timeMs(); IGNORE_RETURN(Os::update()); - if(getInstance().keyServer->update()) + if (getInstance().keyServer->update()) { getInstance().pushKeyToAllServers(); } @@ -1149,10 +1201,10 @@ void LoginServer::run(void) { Os::sleep(1); NetworkHandler::update(); - } while(Clock::timeMs() - startTime < limit); + } while (Clock::timeMs() - startTime < limit); DatabaseConnection::getInstance().update(); - PurgeManager::update(static_cast(limit)/ 1000.0f); + PurgeManager::update(static_cast(limit) / 1000.0f); if (getInstance().m_clusterStatusChanged) { getInstance().sendClusterStatusToAll(); @@ -1175,9 +1227,9 @@ void LoginServer::run(void) mon->set(WORLD_COUNT_CHANNEL, static_cast(getInstance().m_clientMap.size())); int count = 0; ClusterListType::const_iterator i; - for(i = getInstance().m_clusterList.begin(); i != getInstance().m_clusterList.end(); ++i) + for (i = getInstance().m_clusterList.begin(); i != getInstance().m_clusterList.end(); ++i) { - if((*i)->m_connected) + if ((*i)->m_connected) ++count; } mon->set(CLUSTER_COUNT_CHANNEL, count); @@ -1194,7 +1246,6 @@ void LoginServer::run(void) NetworkHandler::remove(); } - //----------------------------------------------------------------------- void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumberJediSlot, const AvatarList &avatars, TransferCharacterData * const transferData) @@ -1203,7 +1254,7 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber chardata.reserve(avatars.size()); EnumerateCharacterId::Chardata temp; - for (AvatarList::const_iterator i=avatars.begin(); i!=avatars.end(); ++i) + for (AvatarList::const_iterator i = avatars.begin(); i != avatars.end(); ++i) { temp.m_name = (*i).m_name; temp.m_objectTemplateId = (*i).m_objectTemplateId; @@ -1216,15 +1267,15 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber EnumerateCharacterId msg(chardata); - if(transferData) + if (transferData) { // send this to the appropriate CentralServer - if(transferData->getSourceCharacterName().empty()) + if (transferData->getSourceCharacterName().empty()) { // CTS API character list request bool result = CentralServerConnection::sendCharacterListResponse(transferData->getSourceStationId(), avatars, *transferData); UNREF(result); - DEBUG_REPORT_LOG(! result,("Could not send avatar list to StationId %lu because connection has been closed.\n",stationId)); + DEBUG_REPORT_LOG(!result, ("Could not send avatar list to StationId %lu because connection has been closed.\n", stationId)); } else { @@ -1234,11 +1285,11 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber if (cle) { // find associated character ID - for (AvatarList::const_iterator i=avatars.begin(); i!=avatars.end(); ++i) + for (AvatarList::const_iterator i = avatars.begin(); i != avatars.end(); ++i) { REPORT_LOG(true, ("checking %s == %s\n", Unicode::wideToNarrow(i->m_name).c_str(), transferData->getSourceCharacterName().c_str())); - if(Unicode::wideToNarrow(i->m_name) == transferData->getSourceCharacterName() - && i->m_clusterId == cle->m_clusterId) + if (Unicode::wideToNarrow(i->m_name) == transferData->getSourceCharacterName() + && i->m_clusterId == cle->m_clusterId) { characterTemplateId = static_cast(i->m_objectTemplateId); characterId = i->m_networkId; @@ -1267,13 +1318,13 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber // this message ***MUST*** be sent first, as the client expects to // receive this information before receiving the avatar list information GenericValueTypeMessage const msgStationIdHasJediSlot("StationIdHasJediSlot", stationIdNumberJediSlot); - conn->send(msgStationIdHasJediSlot,true); + conn->send(msgStationIdHasJediSlot, true); - conn->send(msg,true); + conn->send(msg, true); } else { - DEBUG_REPORT_LOG(true,("Could not send avatar list to StationId %lu.\n",stationId)); + DEBUG_REPORT_LOG(true, ("Could not send avatar list to StationId %lu.\n", stationId)); LOG("LoginClientConnection", ("sendAvatarList() for stationId (%lu), cannot find connection to client for sending avatar list", stationId)); } } @@ -1281,7 +1332,7 @@ void LoginServer::sendAvatarList(const StationId& stationId, int stationIdNumber // ---------------------------------------------------------------------- -void LoginServer::performAccountTransfer (const AvatarList &avatars, TransferAccountData * transferAccountData) +void LoginServer::performAccountTransfer(const AvatarList &avatars, TransferAccountData * transferAccountData) { // grab the station ids StationId sourceStationId = transferAccountData->getSourceStationId(); @@ -1297,14 +1348,14 @@ void LoginServer::performAccountTransfer (const AvatarList &avatars, TransferAcc if (cluster) { - std::string clusterName = cluster->m_clusterName; + std::string clusterName = cluster->m_clusterName; std::string avatarName = Unicode::wideToNarrow(i->m_name); avatarData.push_back(AvatarData(clusterName, avatarName)); - + LOG("CustomerService", ("CharacterTransfer: Sending request to update game db (via cluster: %s) for account transfer from %lu to %lu (avatar: %s)", clusterName.c_str(), sourceStationId, destinationStationId, avatarName.c_str())); const GenericValueTypeMessage message("TransferAccountRequestCentralDatabase", *transferAccountData); - sendToCluster (i->m_clusterId, message); + sendToCluster(i->m_clusterId, message); } else { @@ -1331,38 +1382,38 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, NOT_NULL(conn); WARNING_STRICT_FATAL(getValidatedClient(suid), ("Validating an already valid client in onValidateClient(). StationId: %d UserName: %s", suid, username.c_str())); - int adminLevel=0; + int adminLevel = 0; const bool isAdminAccount = AdminAccountManager::isAdminAccount(Unicode::toLower(username), adminLevel); if (conn->getRequestedAdminSuid() != 0) { //verify internal, secure, is on the god list - bool loginOK=false; - if(!isSecure) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but was not using a SecureID token", username.c_str(),suid, conn->getRequestedAdminSuid())); + bool loginOK = false; + if (!isSecure) + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but was not using a SecureID token", username.c_str(), suid, conn->getRequestedAdminSuid())); else { if (!AdminAccountManager::isInternalIp(conn->getRemoteAddress())) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but was not logging in from an internal IP", username.c_str(),suid, conn->getRequestedAdminSuid())); + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but was not logging in from an internal IP", username.c_str(), suid, conn->getRequestedAdminSuid())); else { if (!isAdminAccount || adminLevel < 10) - LOG("CustomerService",("AdminLogin: User %s (account %li) attempted to log into account %li, but did not have sufficient permissions", username.c_str(),suid, conn->getRequestedAdminSuid())); + LOG("CustomerService", ("AdminLogin: User %s (account %li) attempted to log into account %li, but did not have sufficient permissions", username.c_str(), suid, conn->getRequestedAdminSuid())); else { suid = conn->getRequestedAdminSuid(); - loginOK=true; + loginOK = true; } } } - + if (!loginOK) { conn->disconnect(); return; } } - + // encrypt the clients credentials with the key, return // the cipher text to the client for use as a connection // token with the central server @@ -1408,39 +1459,39 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, const LoginClientToken k(a.getBuffer(), static_cast(a.getSize()), static_cast(suid), username); conn->send(k, true); - delete [] keyBuffer; + delete[] keyBuffer; // send cluster enum bool clientInternal = AdminAccountManager::isInternalIp(conn->getRemoteAddress()); - + std::vector data; - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; - if (cle && cle->m_clusterId!=0 && cle->m_clusterName.size()!=0 && (clientInternal || !cle->m_secret)) + if (cle && cle->m_clusterId != 0 && cle->m_clusterName.size() != 0 && (clientInternal || !cle->m_secret)) { LoginEnumCluster::ClusterData item; - item.m_clusterId = cle->m_clusterId; + item.m_clusterId = cle->m_clusterId; item.m_clusterName = cle->m_clusterName; - item.m_timeZone = cle->m_timeZone; + item.m_timeZone = cle->m_timeZone; data.push_back(item); } } - - LoginEnumCluster e( data, ConfigLoginServer::getMaxCharactersPerAccount() ); - - conn->send(e,true); + + LoginEnumCluster e(data, ConfigLoginServer::getMaxCharactersPerAccount()); + + conn->send(e, true); //Send off list of cluster that has character //creation disabled, even if the list is empty //***MUST*** be done after sending LoginEnumCluster GenericValueTypeMessage > const msgCharacterCreationDisabledClusterList("CharacterCreationDisabled", ConfigLoginServer::getCharacterCreationDisabledClusterList()); - conn->send(msgCharacterCreationDisabledClusterList,true); + conn->send(msgCharacterCreationDisabledClusterList, true); //Send off request for the avatar list from the database. DatabaseConnection::getInstance().requestAvatarListForAccount(suid, 0); - DEBUG_REPORT_LOG(true, ("Client connected. Station Id: %lu, Username: %s\n", suid, username.c_str())); + REPORT_LOG(true, ("Client connected. Station Id: %lu, Username: %s\n", suid, username.c_str())); LOG("LoginClientConnection", ("onValidateClient() for stationId (%lu) at IP (%s), id (%s), requesting avatar list for account", suid, conn->getRemoteAddress().c_str(), username.c_str())); //Set up the connection as being validated with this suid. @@ -1459,26 +1510,26 @@ void LoginServer::onValidateClient(StationId suid, const std::string & username, LoginServer::ClusterListEntry *LoginServer::findClusterByName(const std::string &clusterName) { ClusterListType::iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - NOT_NULL(*i); // not legal to push null pointers on the vector + NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_clusterName == clusterName) return *i; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- -uint32 LoginServer::getClusterIDByName( const std::string &sName ) +uint32 LoginServer::getClusterIDByName(const std::string &sName) { - ClusterListEntry const * const p_cluster = findClusterByName( sName ); + ClusterListEntry const * const p_cluster = findClusterByName(sName); return p_cluster ? p_cluster->m_clusterId : 0; } // ---------------------------------------------------------------------- -const std::string & LoginServer::getClusterNameById( uint32 clusterId ) +const std::string & LoginServer::getClusterNameById(uint32 clusterId) { static std::string const empty; @@ -1493,7 +1544,7 @@ const std::string & LoginServer::getClusterNameById( uint32 clusterId ) LoginServer::ClusterListEntry *LoginServer::addCluster(const std::string &clusterName) { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: addCluster(std::string&) can only be used in development mode.\n")); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: addCluster(std::string&) can only be used in development mode.\n")); ClusterListEntry *e = new ClusterListEntry; e->m_clusterName = clusterName; @@ -1503,27 +1554,26 @@ LoginServer::ClusterListEntry *LoginServer::addCluster(const std::string &cluste // ---------------------------------------------------------------------- -void LoginServer::sendExtendedClusterInfo( ClientConnection &client ) const +void LoginServer::sendExtendedClusterInfo(ClientConnection &client) const { std::vector data; - - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; - if ( cle ) + if (cle) { LoginClusterStatusEx::ClusterData item; - item.m_clusterId = cle->m_clusterId; - item.m_branch = cle->m_branch; - item.m_version = cle->m_changelist; + item.m_clusterId = cle->m_clusterId; + item.m_branch = cle->m_branch; + item.m_version = cle->m_changelist; item.m_networkVersion = cle->m_networkVersion; - data.push_back( item ); + data.push_back(item); } - } - - client.send( LoginClusterStatusEx( data ), true ); + + client.send(LoginClusterStatusEx(data), true); } // ---------------------------------------------------------------------- @@ -1536,15 +1586,15 @@ void LoginServer::sendExtendedClusterInfo( ClientConnection &client ) const */ void LoginServer::sendClusterStatus(ClientConnection &conn) const { - const bool clientIsPrivate = AdminAccountManager::isInternalIp(conn.getRemoteAddress()); - const unsigned int subscriptionBits = conn.getSubscriptionBits(); - const bool isFreeTrialAccount = ( ((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) - && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)); + const bool clientIsPrivate = AdminAccountManager::isInternalIp(conn.getRemoteAddress()); + const unsigned int subscriptionBits = conn.getSubscriptionBits(); + const bool isFreeTrialAccount = (((subscriptionBits & ClientSubscriptionFeature::FreeTrial) != 0) + && ((subscriptionBits & ClientSubscriptionFeature::Base) == 0)); std::vector data; std::vector dataEx; - - for(ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) + + for (ClusterListType::const_iterator j = m_clusterList.begin(); j != m_clusterList.end(); ++j) { ClusterListEntry *cle = *j; // Cluster is OK for login if @@ -1553,26 +1603,26 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const // 3) We have at least one Connection Server // 4) Client is internal or the cluster is not secret // 5) Cluster has told us its ready for players - if (cle && cle->m_clusterId!=0 && cle->m_connected && !cle->m_connectionServers.empty() && (clientIsPrivate || !cle->m_secret)) + if (cle && cle->m_clusterId != 0 && cle->m_connected && !cle->m_connectionServers.empty() && (clientIsPrivate || !cle->m_secret)) { - DEBUG_FATAL(!cle->m_centralServerConnection,("Programmer bug: m_connected was true but m_centralServerConnection was NULL\n")); + DEBUG_FATAL(!cle->m_centralServerConnection, ("Programmer bug: m_connected was true but m_centralServerConnection was nullptr\n")); LoginClusterStatus::ClusterData item; item.m_clusterId = cle->m_clusterId; item.m_timeZone = cle->m_timeZone; -// size_t connectionServerChoice = Random::random(cle->m_connectionServers.size() - 1); //lint !e713 !e732 // loss of precision (arg no 1) + // size_t connectionServerChoice = Random::random(cle->m_connectionServers.size() - 1); //lint !e713 !e732 // loss of precision (arg no 1) ConnectionServerEntry &connServer = cle->m_connectionServers[0]; - item.m_connectionServerAddress = connServer.clientServiceAddress; - if(clientIsPrivate) + item.m_connectionServerAddress = connServer.clientServiceAddress; + if (clientIsPrivate) { - item.m_connectionServerPort = connServer.clientServicePortPrivate; + item.m_connectionServerPort = connServer.clientServicePortPrivate; } else { - item.m_connectionServerPort = connServer.clientServicePortPublic; + item.m_connectionServerPort = connServer.clientServicePortPublic; } - if(item.m_connectionServerPort) + if (item.m_connectionServerPort) { item.m_connectionServerPingPort = connServer.pingPort; @@ -1580,27 +1630,27 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const // population count to secured internal connections with // admin privilege >= 10 if (clientIsPrivate && conn.getIsSecure() && (conn.getAdminLevel() >= 10)) - item.m_populationOnline = cle->m_numPlayers; + item.m_populationOnline = cle->m_numPlayers; else - item.m_populationOnline = -1; + item.m_populationOnline = -1; const int percentFull = cle->m_numPlayers * 100 / cle->m_onlinePlayerLimit; if (percentFull >= 100) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_full; else if (percentFull >= ConfigLoginServer::getPopulationExtremelyHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_extremely_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationVeryHeavyThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationVeryHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_very_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationHeavyThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationHeavyThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_heavy; - else if (percentFull >= ConfigLoginServer::getPopulationMediumThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationMediumThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_medium; - else if (percentFull >= ConfigLoginServer::getPopulationLightThresholdPercent()) + else if (percentFull >= ConfigLoginServer::getPopulationLightThresholdPercent()) item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_light; - else + else item.m_populationOnlineStatus = LoginClusterStatus::ClusterData::PS_very_light; - item.m_maxCharactersPerAccount = cle->m_maxCharactersPerAccount; + item.m_maxCharactersPerAccount = cle->m_maxCharactersPerAccount; if (cle->m_readyForPlayers) { item.m_status = LoginClusterStatus::ClusterData::S_up; @@ -1611,7 +1661,7 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const item.m_status = LoginClusterStatus::ClusterData::S_restricted; } if ((cle->m_numPlayers >= cle->m_onlinePlayerLimit) - || (isFreeTrialAccount && (cle->m_numFreeTrialPlayers >= cle->m_onlineFreeTrialLimit))) + || (isFreeTrialAccount && (cle->m_numFreeTrialPlayers >= cle->m_onlineFreeTrialLimit))) { item.m_status = LoginClusterStatus::ClusterData::S_full; } @@ -1620,31 +1670,30 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const item.m_status = LoginClusterStatus::ClusterData::S_loading; if (cle->m_locked && !clientIsPrivate) item.m_status = LoginClusterStatus::ClusterData::S_locked; // locked takes precedence over up or loading - + item.m_dontRecommend = (cle->m_notRecommendedDatabase || cle->m_notRecommendedCentral); - item.m_onlinePlayerLimit = cle->m_onlinePlayerLimit; - item.m_onlineFreeTrialLimit = cle->m_onlineFreeTrialLimit; - + item.m_onlinePlayerLimit = cle->m_onlinePlayerLimit; + item.m_onlineFreeTrialLimit = cle->m_onlineFreeTrialLimit; + data.push_back(item); } ++connServer.numClients; std::sort(cle->m_connectionServers.begin(), cle->m_connectionServers.end(), ConnectionServerEntryLessThan()); - } - - if ( cle ) + + if (cle) { LoginClusterStatusEx::ClusterData itemEx; itemEx.m_clusterId = cle->m_clusterId; - itemEx.m_branch = cle->m_branch; - itemEx.m_version = cle->m_changelist; - dataEx.push_back( itemEx ); + itemEx.m_branch = cle->m_branch; + itemEx.m_version = cle->m_changelist; + dataEx.push_back(itemEx); } } LoginClusterStatus msg(data); - conn.send(msg,true); + conn.send(msg, true); } // ---------------------------------------------------------------------- @@ -1654,7 +1703,7 @@ void LoginServer::sendClusterStatus(ClientConnection &conn) const */ void LoginServer::sendClusterStatusToAll() const { - for (std::map::const_iterator i=m_validatedClientMap.begin(); i!=m_validatedClientMap.end(); ++i) + for (std::map::const_iterator i = m_validatedClientMap.begin(); i != m_validatedClientMap.end(); ++i) { if (i->second) sendClusterStatus(*(i->second)); @@ -1664,29 +1713,30 @@ void LoginServer::sendClusterStatusToAll() const // ---------------------------------------------------------------------- LoginServer::ClusterListEntry::ClusterListEntry() : - m_clusterId(0), - m_clusterName(), - m_centralServerConnection(0), - m_connectionServers(), - m_numPlayers(0), - m_numFreeTrialPlayers(0), - m_numTutorialPlayers(0), - m_maxCharacters(ConfigLoginServer::getMaxCharactersPerCluster()), - m_maxCharactersPerAccount(0), - m_onlinePlayerLimit(0), - m_onlineFreeTrialLimit(0), - m_onlineTutorialLimit(0), - m_freeTrialCanCreateChar(false), - m_timeZone(0), - m_connected(false), - m_address(""), - m_port(0), - m_allowReconnect(true), - m_secret(false), - m_readyForPlayers(false), - m_locked(false), - m_notRecommendedDatabase(false), - m_notRecommendedCentral(false) + m_clusterId(0), + m_clusterName(), + m_centralServerConnection(0), + m_connectionServers(), + m_numPlayers(0), + m_numFreeTrialPlayers(0), + m_numTutorialPlayers(0), + m_maxCharacters(ConfigLoginServer::getMaxCharactersPerCluster()), + m_maxCharactersPerAccount(0), + m_onlinePlayerLimit(0), + m_onlineFreeTrialLimit(0), + m_onlineTutorialLimit(0), + m_freeTrialCanCreateChar(false), + m_timeZone(0), + m_connected(false), + m_address(""), + m_port(0), + m_allowReconnect(true), + m_secret(false), + m_readyForPlayers(false), + m_locked(false), + m_notRecommendedDatabase(false), + m_notRecommendedCentral(false), + m_changelist(0) { } @@ -1713,26 +1763,26 @@ void LoginServer::updateClusterData(uint32 clusterId, const std::string &cluster // refreshing data on a cluster we already know about if ((cle->m_clusterName != clusterName) || (cle->m_address != address) || (cle->m_port != port)) { - DEBUG_REPORT_LOG(true,("Disconnecting from cluster %lu because its data has changed in the database.\n",clusterId)); - disconnectCluster(*cle,true,true); + DEBUG_REPORT_LOG(true, ("Disconnecting from cluster %lu because its data has changed in the database.\n", clusterId)); + disconnectCluster(*cle, true, true); } } } if (!cle) { - DEBUG_REPORT_LOG(true,("Cluster %lu: %s\n", clusterId, clusterName.c_str())); + DEBUG_REPORT_LOG(true, ("Cluster %lu: %s\n", clusterId, clusterName.c_str())); cle = new ClusterListEntry; m_clusterList.push_back(cle); } if ((cle->m_secret != secret) - || (cle->m_locked != locked) - || (cle->m_onlinePlayerLimit != onlinePlayerLimit) - || (cle->m_onlineFreeTrialLimit != onlineFreeTrialLimit) - || (cle->m_freeTrialCanCreateChar != freeTrialCanCreateChar) - || (cle->m_onlineTutorialLimit != onlineTutorialLimit)) + || (cle->m_locked != locked) + || (cle->m_onlinePlayerLimit != onlinePlayerLimit) + || (cle->m_onlineFreeTrialLimit != onlineFreeTrialLimit) + || (cle->m_freeTrialCanCreateChar != freeTrialCanCreateChar) + || (cle->m_onlineTutorialLimit != onlineTutorialLimit)) { // The cluster may now be locked/unlocked to some players, so let them know m_clusterStatusChanged = true; @@ -1742,7 +1792,7 @@ void LoginServer::updateClusterData(uint32 clusterId, const std::string &cluster if (((cle->m_locked != locked) || (cle->m_secret != secret)) && cle->m_connected && cle->m_centralServerConnection) { GenericValueTypeMessage > const msgState("UpdateClusterLockedAndSecretState", std::make_pair(locked, secret)); - cle->m_centralServerConnection->send(msgState,true); + cle->m_centralServerConnection->send(msgState, true); } bool const clusterIdSet = ((cle->m_clusterId == 0) && (clusterId > 0)); @@ -1806,7 +1856,7 @@ void LoginServer::disconnectCluster(ClusterListEntry &cle, bool const forceDisco // started, and the LoginServer will connect to it if (!ConfigLoginServer::getDevelopmentMode() && reconnect) { - for (ClusterListType::iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); if (!(*i)->m_centralServerConnection && !(*i)->m_allowReconnect && ((*i)->m_address == cle.m_address)) @@ -1824,7 +1874,7 @@ void LoginServer::disconnectCluster(ClusterListEntry &cle, bool const forceDisco */ void LoginServer::onClusterRegistered(uint32 clusterId, const std::string &clusterName) { - DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(),("Programmer bug: should not be registering new clusters automatically unless running in development mode.\n")); + DEBUG_FATAL(!ConfigLoginServer::getDevelopmentMode(), ("Programmer bug: should not be registering new clusters automatically unless running in development mode.\n")); static std::string noAddress(""); updateClusterData(clusterId, clusterName, noAddress, 0, false, false, false, 8, 100, 100, true, 350); } @@ -1838,14 +1888,14 @@ void LoginServer::onClusterRegistered(uint32 clusterId, const std::string &clust LoginServer::ClusterListEntry * LoginServer::findClusterById(uint32 clusterId) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - NOT_NULL(*i); // not legal to push null pointers on the vector + NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_clusterId == clusterId) return *i; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- @@ -1857,14 +1907,14 @@ LoginServer::ClusterListEntry * LoginServer::findClusterById(uint32 clusterId) LoginServer::ClusterListEntry * LoginServer::findClusterByConnection(const CentralServerConnection *connection) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - NOT_NULL(*i); // not legal to push null pointers on the vector + NOT_NULL(*i); // not legal to push nullptr pointers on the vector if ((*i)->m_centralServerConnection == connection) return *i; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- @@ -1874,7 +1924,7 @@ void LoginServer::refreshConnections() if (ConfigLoginServer::getDevelopmentMode()) return; // in development mode, we don't establish any connections ClusterListType::iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { NOT_NULL(*i); if (!(*i)->m_centralServerConnection && (*i)->m_allowReconnect) @@ -1890,13 +1940,13 @@ void LoginServer::refreshConnections() // ---------------------------------------------------------------------- -void LoginServer::sendToCluster (uint32 clusterId, const GameNetworkMessage &message) +void LoginServer::sendToCluster(uint32 clusterId, const GameNetworkMessage &message) { ClusterListEntry *cle = findClusterById(clusterId); if (cle && cle->m_connected && cle->m_centralServerConnection) - cle->m_centralServerConnection->send(message,true); + cle->m_centralServerConnection->send(message, true); else - DEBUG_REPORT_LOG(true,("Could not send message to cluster %lu because it was not connected.\n",clusterId)); + DEBUG_REPORT_LOG(true, ("Could not send message to cluster %lu because it was not connected.\n", clusterId)); } //----------------------------------------------------------------------- @@ -1908,13 +1958,13 @@ void LoginServer::setDone(const bool isDone) // ---------------------------------------------------------------------- -void LoginServer::sendToAllClusters(GameNetworkMessage const & message, Connection const * excludeCentralConnection /*= NULL*/, uint32 excludeClusterId /*= 0*/, char const * excludeClusterName /*= NULL*/) +void LoginServer::sendToAllClusters(GameNetworkMessage const & message, Connection const * excludeCentralConnection /*= nullptr*/, uint32 excludeClusterId /*= 0*/, char const * excludeClusterName /*= nullptr*/) { ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - if (NON_NULL(*i)->m_connected && (*i)->m_centralServerConnection && ((*i)->m_centralServerConnection != excludeCentralConnection) && ((*i)->m_clusterId != excludeClusterId) && ((excludeClusterName == NULL) || _stricmp(excludeClusterName, (*i)->m_centralServerConnection->getClusterName().c_str()))) - (*i)->m_centralServerConnection->send(message,true); + if (NON_NULL(*i)->m_connected && (*i)->m_centralServerConnection && ((*i)->m_centralServerConnection != excludeCentralConnection) && ((*i)->m_clusterId != excludeClusterId) && ((excludeClusterName == nullptr) || _stricmp(excludeClusterName, (*i)->m_centralServerConnection->getClusterName().c_str()))) + (*i)->m_centralServerConnection->send(message, true); } } @@ -1924,9 +1974,9 @@ bool LoginServer::areAllClustersUp() const { if (m_clusterList.empty()) return false; - + ClusterListType::const_iterator i; - for (i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { if (!(NON_NULL(*i)->m_readyForPlayers)) return false; @@ -1936,16 +1986,15 @@ bool LoginServer::areAllClustersUp() const // ---------------------------------------------------------------------- -void LoginServer::getAllClusterNamesAndIDs( std::map< std::string, uint32 > &results ) const +void LoginServer::getAllClusterNamesAndIDs(std::map< std::string, uint32 > &results) const { results.clear(); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) { - if( !*i ) + if (!*i) continue; - results[ (*i)->m_clusterName ] = (*i)->m_clusterId; + results[(*i)->m_clusterName] = (*i)->m_clusterId; } - } // ---------------------------------------------------------------------- @@ -1953,20 +2002,20 @@ void LoginServer::getAllClusterNamesAndIDs( std::map< std::string, uint32 > &res void LoginServer::getClusterIds(std::vector result) { result.reserve(m_clusterList.size()); - for (ClusterListType::const_iterator i=m_clusterList.begin(); i!=m_clusterList.end(); ++i) + for (ClusterListType::const_iterator i = m_clusterList.begin(); i != m_clusterList.end(); ++i) result.push_back(NON_NULL(*i)->m_clusterId); } // ---------------------------------------------------------------------- -void LoginServer::setClusterInfoByName( const std::string &name, const std::string &branch, int changelist, const std::string &networkVersion ) +void LoginServer::setClusterInfoByName(const std::string &name, const std::string &branch, int changelist, const std::string &networkVersion) { - ClusterListEntry *entry = findClusterByName( name ); - - if ( entry ) + ClusterListEntry *entry = findClusterByName(name); + + if (entry) { - entry->m_branch = branch; - entry->m_changelist = changelist; + entry->m_branch = branch; + entry->m_changelist = changelist; entry->m_networkVersion = networkVersion; } } diff --git a/engine/server/application/LoginServer/src/shared/LoginServer.h b/engine/server/application/LoginServer/src/shared/LoginServer.h index a284068e..f1d4de5b 100755 --- a/engine/server/application/LoginServer/src/shared/LoginServer.h +++ b/engine/server/application/LoginServer/src/shared/LoginServer.h @@ -64,7 +64,7 @@ public: void validateAccount (const StationId& stationId, uint32 clusterId, uint32 subscriptionBits, bool canCreateRegular, bool canCreateJedi, bool canSkipTutorial, unsigned int track, std::vector > const & consumedRewardEvents, std::vector > const & claimedRewardItems); void validateAccountForTransfer(const TransferRequestMoveValidation & request, uint32 clusterId, uint32 sourceCharacterTemplateId, bool canCreateRegular, bool canCreateJedi); void sendToCluster (uint32 clusterId, const GameNetworkMessage &message); - void sendToAllClusters (GameNetworkMessage const & message, Connection const * excludeCentralConnection = NULL, uint32 excludeClusterId = 0, char const * excludeClusterName = NULL); + void sendToAllClusters (GameNetworkMessage const & message, Connection const * excludeCentralConnection = nullptr, uint32 excludeClusterId = 0, char const * excludeClusterName = nullptr); bool areAllClustersUp () const; void getClusterIds (stdvector::fwd result); void performAccountTransfer (const AvatarList &avatars, TransferAccountData * transferAccountData); diff --git a/engine/server/application/LoginServer/src/shared/SessionApiClient.cpp b/engine/server/application/LoginServer/src/shared/SessionApiClient.cpp index f130d691..73ff91ae 100755 --- a/engine/server/application/LoginServer/src/shared/SessionApiClient.cpp +++ b/engine/server/application/LoginServer/src/shared/SessionApiClient.cpp @@ -435,7 +435,7 @@ void SessionApiClient::NotifySessionKick(const char ** sessionList, void SessionApiClient::checkStatusForPurge(StationId account) { - GetAccountSubscription(account, PlatformGameCode::SWG, NULL); + GetAccountSubscription(account, PlatformGameCode::SWG, nullptr); } //------------------------------------------------------------------------------------------ diff --git a/engine/server/application/LoginServer/src/shared/TaskCreateCharacter.cpp b/engine/server/application/LoginServer/src/shared/TaskCreateCharacter.cpp index 6e8ed6d4..243f3c71 100755 --- a/engine/server/application/LoginServer/src/shared/TaskCreateCharacter.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskCreateCharacter.cpp @@ -58,7 +58,7 @@ void TaskCreateCharacter::onComplete() // let all other galaxies know that a new character has been created for the station account GenericValueTypeMessage const ncc("NewCharacterCreated", m_stationId); - LoginServer::getInstance().sendToAllClusters(ncc, NULL, m_clusterId); + LoginServer::getInstance().sendToAllClusters(ncc, nullptr, m_clusterId); } // ====================================================================== diff --git a/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp b/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp index b72adbe3..209d613d 100755 --- a/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskEnableCharacter.cpp @@ -18,12 +18,13 @@ // ====================================================================== TaskEnableCharacter::TaskEnableCharacter(StationId &stationId, const NetworkId &characterId, const std::string &whoRequested, bool enabled, uint32 clusterId) : - TaskRequest(), - m_stationId(stationId), - m_characterId(characterId), - m_whoRequested(whoRequested), - m_enabled(enabled), - m_clusterId(clusterId) + TaskRequest(), + m_stationId(stationId), + m_characterId(characterId), + m_whoRequested(whoRequested), + m_enabled(enabled), + m_clusterId(clusterId), + m_result(0) { } @@ -32,16 +33,15 @@ TaskEnableCharacter::TaskEnableCharacter(StationId &stationId, const NetworkId & bool TaskEnableCharacter::process(DB::Session *session) { EnableCharacterQuery qry; - qry.station_id=static_cast(m_stationId); - qry.character_id=m_characterId; + qry.station_id = static_cast(m_stationId); + qry.character_id = m_characterId; qry.enabled.setValue(m_enabled); bool rval = session->exec(&qry); - + qry.done(); m_result = qry.result.getValue(); return rval; - } // ---------------------------------------------------------------------- @@ -51,34 +51,34 @@ void TaskEnableCharacter::onComplete() std::string message; switch (m_result) { - case 1: - if (m_enabled) - message = "Character enabled."; - else - message = "Character disabled."; - break; + case 1: + if (m_enabled) + message = "Character enabled."; + else + message = "Character disabled."; + break; - case 2: - message = "Could not find Character"; - break; + case 2: + message = "Could not find Character"; + break; - default: - message = "The database returned an unknown error code"; - break; + default: + message = "The database returned an unknown error code"; + break; } - + GenericValueTypeMessage > reply("EnableCharacterReplyMessage", - std::make_pair(m_whoRequested, message)); + std::make_pair(m_whoRequested, message)); LoginServer::getInstance().sendToCluster(m_clusterId, reply); } // ---------------------------------------------------------------------- TaskEnableCharacter::EnableCharacterQuery::EnableCharacterQuery() : - Query(), - station_id(), - character_id(), - enabled() + Query(), + station_id(), + character_id(), + enabled() { } @@ -87,7 +87,6 @@ TaskEnableCharacter::EnableCharacterQuery::EnableCharacterQuery() : void TaskEnableCharacter::EnableCharacterQuery::getSQL(std::string &sql) { sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.enable_disable_character(:station_id, :character_id, :enabled); end;"; - } // ---------------------------------------------------------------------- @@ -116,4 +115,4 @@ DB::Query::QueryMode TaskEnableCharacter::EnableCharacterQuery::getExecutionMode return MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp b/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp index bc755e82..061b1c4d 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetAccountForPurge.cpp @@ -30,7 +30,7 @@ namespace TaskGetAccountForPurgeNamespace virtual QueryMode getExecutionMode() const; StationId getAccount() const; - + private: DB::BindableLong m_account; DB::BindableLong m_min_age; @@ -46,8 +46,9 @@ using namespace TaskGetAccountForPurgeNamespace; // ====================================================================== TaskGetAccountForPurge::TaskGetAccountForPurge(int purgePhase) : - DB::TaskRequest(), - m_purgePhase(purgePhase) + DB::TaskRequest(), + m_purgePhase(purgePhase), + m_account(0) { } @@ -71,12 +72,11 @@ void TaskGetAccountForPurge::onComplete() // ====================================================================== - GetAccountForPurgeQuery::GetAccountForPurgeQuery(int purgePhase, int minAge) : - Query(), - m_account(), - m_min_age(minAge), - m_purge_phase(purgePhase) + Query(), + m_account(), + m_min_age(minAge), + m_purge_phase(purgePhase) { } @@ -84,7 +84,7 @@ GetAccountForPurgeQuery::GetAccountForPurgeQuery(int purgePhase, int minAge) : void GetAccountForPurgeQuery::getSQL(std::string &sql) { - sql=std::string("begin :account := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"purge_process.get_account_for_purge(:purge_phase, :min_age); end;"; + sql = std::string("begin :account := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "purge_process.get_account_for_purge(:purge_phase, :min_age); end;"; } // ---------------------------------------------------------------------- @@ -121,4 +121,4 @@ StationId GetAccountForPurgeQuery::getAccount() const return 0; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskGetCharactersForDelete.cpp b/engine/server/application/LoginServer/src/shared/TaskGetCharactersForDelete.cpp index 5259daf4..3cc49cef 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetCharactersForDelete.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetCharactersForDelete.cpp @@ -14,7 +14,7 @@ // ====================================================================== TaskGetCharactersForDelete::TaskGetCharactersForDelete (StationId stationId, int clusterGroupId) : - TaskGetAvatarList(stationId, clusterGroupId, NULL) + TaskGetAvatarList(stationId, clusterGroupId, nullptr) { } diff --git a/engine/server/application/LoginServer/src/shared/TaskGetClusterList.cpp b/engine/server/application/LoginServer/src/shared/TaskGetClusterList.cpp index 23919142..96bf1c19 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetClusterList.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetClusterList.cpp @@ -54,6 +54,8 @@ bool TaskGetClusterList::process(DB::Session *session) qry.free_trial_can_create_char.getValue(temp.m_freeTrialCanCreateChar); qry.online_tutorial_limit.getValue(temp.m_onlineTutorialLimit); + DEBUG_WARNING(true, ("Customer facing cluster address for %s is %s", temp.m_clusterName.c_str(), temp.m_address.c_str())); + m_clusterData.push_back(temp); } return (rowsFetched >= 0); diff --git a/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp b/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp index d646b57c..735e9e7a 100755 --- a/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp +++ b/engine/server/application/LoginServer/src/shared/TaskGetValidationData.cpp @@ -46,8 +46,8 @@ namespace TaskGetValidationDataNamespace public: GetCompletedTutorialQuery(StationId stationId); - DB::BindableLong station_id; - DB::BindableBool completed_tutorial; + DB::BindableLong station_id; + DB::BindableBool completed_tutorial; virtual void getSQL(std::string &sql); virtual bool bindParameters(); @@ -72,13 +72,13 @@ namespace TaskGetValidationDataNamespace std::string getEventId() const; uint32 getClusterId() const; NetworkId const getCharacterId() const; - + private: DB::BindableLong station_id; DB::BindableString<100> event_id; DB::BindableLong cluster_id; DB::BindableNetworkId character_id; - + private: //disable GetConsumedRewardEventsQuery(); GetConsumedRewardEventsQuery(const GetConsumedRewardEventsQuery&); @@ -119,13 +119,13 @@ namespace TaskGetValidationDataNamespace DB::BindableLong cluster_id; //lint !e1925 // public data member DB::BindableLong result; //lint !e1925 // public data member - virtual void getSQL (std::string &sql); - virtual bool bindParameters (); - virtual bool bindColumns (); - virtual QueryMode getExecutionMode () const; + virtual void getSQL(std::string &sql); + virtual bool bindParameters(); + virtual bool bindColumns(); + virtual QueryMode getExecutionMode() const; private: //disable - IsClusterAtLimitQuery (const IsClusterAtLimitQuery&); + IsClusterAtLimitQuery(const IsClusterAtLimitQuery&); IsClusterAtLimitQuery &operator= (const IsClusterAtLimitQuery&); }; } @@ -134,36 +134,37 @@ using namespace TaskGetValidationDataNamespace; // ====================================================================== -TaskGetValidationData::TaskGetValidationData (StationId stationId, int clusterGroupId, uint32 clusterId, unsigned int track, uint32 subscriptionBits) : - TaskRequest(), - m_stationId(stationId), - m_clusterGroupId(clusterGroupId), - m_clusterId(clusterId), - m_openCharacterSlots(4,0), - m_canSkipTutorial(false), - m_track(track), - m_subscriptionBits(subscriptionBits), - m_transferRequest(0), - m_transferRequestSourceCharacterTemplateId(0), - m_consumedRewardEvents(), - m_claimedRewardItems() +TaskGetValidationData::TaskGetValidationData(StationId stationId, int clusterGroupId, uint32 clusterId, unsigned int track, uint32 subscriptionBits) : + TaskRequest(), + m_stationId(stationId), + m_clusterGroupId(clusterGroupId), + m_clusterId(clusterId), + m_openCharacterSlots(4, 0), + m_canSkipTutorial(false), + m_track(track), + m_subscriptionBits(subscriptionBits), + m_transferRequest(0), + m_transferRequestSourceCharacterTemplateId(0), + m_consumedRewardEvents(), + m_claimedRewardItems() { } // ---------------------------------------------------------------------- TaskGetValidationData::TaskGetValidationData(const TransferRequestMoveValidation & request, int clusterGroupId, uint32 clusterId) : - TaskRequest(), - m_stationId(request.getDestinationStationId()), - m_clusterGroupId(clusterGroupId), - m_clusterId(clusterId), - m_openCharacterSlots(4,0), - m_canSkipTutorial(true), - m_track(request.getTrack()), - m_transferRequest(0), - m_transferRequestSourceCharacterTemplateId(request.getSourceCharacterTemplateId()), - m_consumedRewardEvents(), - m_claimedRewardItems() + TaskRequest(), + m_stationId(request.getDestinationStationId()), + m_clusterGroupId(clusterGroupId), + m_clusterId(clusterId), + m_openCharacterSlots(4, 0), + m_canSkipTutorial(true), + m_track(request.getTrack()), + m_transferRequest(0), + m_transferRequestSourceCharacterTemplateId(request.getSourceCharacterTemplateId()), + m_consumedRewardEvents(), + m_claimedRewardItems(), + m_subscriptionBits(0) { Archive::ByteStream bs; request.pack(bs); @@ -205,10 +206,10 @@ bool TaskGetValidationData::process(DB::Session *session) qry.cluster_id = static_cast(m_clusterId); int rowsFetched; - if (! (session->exec(&qry))) + if (!(session->exec(&qry))) return false; while ((rowsFetched = qry.fetch()) > 0) - m_openCharacterSlots[static_cast(qry.character_type_id.getValue())]=qry.num_open_slots.getValue(); + m_openCharacterSlots[static_cast(qry.character_type_id.getValue())] = qry.num_open_slots.getValue(); qry.done(); if (rowsFetched < 0) return false; @@ -219,12 +220,12 @@ bool TaskGetValidationData::process(DB::Session *session) GetValidationDataQuery qry; qry.station_id = static_cast(m_stationId); qry.cluster_id = static_cast(m_clusterId); - + int rowsFetched; - if (! (session->exec(&qry))) + if (!(session->exec(&qry))) return false; while ((rowsFetched = qry.fetch()) > 0) - m_openCharacterSlots[static_cast(qry.character_type_id.getValue())]=qry.num_open_slots.getValue(); + m_openCharacterSlots[static_cast(qry.character_type_id.getValue())] = qry.num_open_slots.getValue(); qry.done(); if (rowsFetched < 0) return false; @@ -254,7 +255,7 @@ bool TaskGetValidationData::process(DB::Session *session) qryGetCharacters.character_name.getValue(characterName); if (characterName == m_transferRequest->getSourceCharacter()) { - qryGetCharacters.object_template_id.getValue(m_transferRequestSourceCharacterTemplateId); + qryGetCharacters.object_template_id.getValue(m_transferRequestSourceCharacterTemplateId); break; } } @@ -267,13 +268,13 @@ bool TaskGetValidationData::process(DB::Session *session) { GetConsumedRewardEventsQuery eventQuery(m_stationId); int rowsFetched; - if (! (session->exec(&eventQuery))) + if (!(session->exec(&eventQuery))) return false; while ((rowsFetched = eventQuery.fetch()) > 0) { // If the event was claimed on this cluster, tell the cluster the network ID of the character that claimed it. - // If claimed on another cluster, hide the network ID because it's not meaningful - NetworkId const characterId = eventQuery.getClusterId()==m_clusterId ? eventQuery.getCharacterId() : NetworkId::cms_invalid; + // If claimed on another cluster, hide the network ID because it's not meaningful + NetworkId const characterId = eventQuery.getClusterId() == m_clusterId ? eventQuery.getCharacterId() : NetworkId::cms_invalid; m_consumedRewardEvents.push_back(std::make_pair(characterId, eventQuery.getEventId())); } eventQuery.done(); @@ -281,11 +282,11 @@ bool TaskGetValidationData::process(DB::Session *session) return false; GetClaimedRewardItemsQuery itemQuery(m_stationId); - if (! (session->exec(&itemQuery))) + if (!(session->exec(&itemQuery))) return false; while ((rowsFetched = itemQuery.fetch()) > 0) { - NetworkId const characterId = itemQuery.getClusterId()==m_clusterId ? itemQuery.getCharacterId() : NetworkId::cms_invalid; + NetworkId const characterId = itemQuery.getClusterId() == m_clusterId ? itemQuery.getCharacterId() : NetworkId::cms_invalid; m_claimedRewardItems.push_back(std::make_pair(characterId, itemQuery.getItemId())); } itemQuery.done(); @@ -294,12 +295,12 @@ bool TaskGetValidationData::process(DB::Session *session) // check to see if the account can skip the tutorial or not GetCompletedTutorialQuery tutorialQuery(m_stationId); - if (! (session->exec(&tutorialQuery))) + if (!(session->exec(&tutorialQuery))) return false; while ((rowsFetched = tutorialQuery.fetch()) > 0) { tutorialQuery.completed_tutorial.getValue(m_canSkipTutorial); - } + } tutorialQuery.done(); if (rowsFetched < 0) return false; @@ -311,21 +312,21 @@ bool TaskGetValidationData::process(DB::Session *session) void TaskGetValidationData::onComplete() { - bool canCreateNormal=false; - bool canCreateJedi=false; + bool canCreateNormal = false; + bool canCreateJedi = false; if (m_openCharacterSlots[1] > 0) - canCreateNormal=true; + canCreateNormal = true; if (m_openCharacterSlots[2] > 0 && m_openCharacterSlots[3] > 0) - canCreateJedi=true; + canCreateJedi = true; // check to see if character creation has been disabled for the cluster if (ConfigLoginServer::isCharacterCreationDisabled(LoginServer::getInstance().getClusterNameById(m_clusterId))) { - canCreateNormal=false; - canCreateJedi=false; + canCreateNormal = false; + canCreateJedi = false; } - if(m_transferRequest) + if (m_transferRequest) { LoginServer::getInstance().validateAccountForTransfer(*m_transferRequest, m_clusterId, m_transferRequestSourceCharacterTemplateId, canCreateNormal, false); } @@ -339,7 +340,7 @@ void TaskGetValidationData::onComplete() void GetValidationDataQuery::getSQL(std::string &sql) { - sql = std::string("begin :rc := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_open_character_slots(:station_id,:cluster_id); end;"; + sql = std::string("begin :rc := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_open_character_slots(:station_id,:cluster_id); end;"; } // ---------------------------------------------------------------------- @@ -347,9 +348,9 @@ void GetValidationDataQuery::getSQL(std::string &sql) bool GetValidationDataQuery::bindParameters() { if (!bindParameter(station_id)) return false; - if (!bindParameter(cluster_id)) return false; + if (!bindParameter(cluster_id)) return false; - return true; + return true; } // ---------------------------------------------------------------------- @@ -372,11 +373,11 @@ DB::Query::QueryMode GetValidationDataQuery::getExecutionMode() const // ---------------------------------------------------------------------- GetValidationDataQuery::GetValidationDataQuery() : - Query(), - station_id(), - cluster_id(), - character_type_id(), - num_open_slots() + Query(), + station_id(), + cluster_id(), + character_type_id(), + num_open_slots() { } @@ -384,7 +385,7 @@ GetValidationDataQuery::GetValidationDataQuery() : void GetCompletedTutorialQuery::getSQL(std::string &sql) { - sql = std::string("begin :rc := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_completed_tutorial(:station_id); end;"; + sql = std::string("begin :rc := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_completed_tutorial(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -393,7 +394,7 @@ bool GetCompletedTutorialQuery::bindParameters() { if (!bindParameter(station_id)) return false; - return true; + return true; } // ---------------------------------------------------------------------- @@ -415,20 +416,20 @@ DB::Query::QueryMode GetCompletedTutorialQuery::getExecutionMode() const // ---------------------------------------------------------------------- GetCompletedTutorialQuery::GetCompletedTutorialQuery(StationId stationId) : - DB::Query(), - station_id(stationId), - completed_tutorial(false) + DB::Query(), + station_id(stationId), + completed_tutorial(false) { } // ====================================================================== GetConsumedRewardEventsQuery::GetConsumedRewardEventsQuery(StationId stationId) : - DB::Query(), - station_id(static_cast(stationId)), - event_id(), - cluster_id(), - character_id() + DB::Query(), + station_id(static_cast(stationId)), + event_id(), + cluster_id(), + character_id() { } @@ -436,7 +437,7 @@ GetConsumedRewardEventsQuery::GetConsumedRewardEventsQuery(StationId stationId) void GetConsumedRewardEventsQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_consumed_reward_events(:station_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_consumed_reward_events(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -488,11 +489,11 @@ NetworkId const GetConsumedRewardEventsQuery::getCharacterId() const // ====================================================================== GetClaimedRewardItemsQuery::GetClaimedRewardItemsQuery(StationId stationId) : - DB::Query(), - station_id(static_cast(stationId)), - item_id(), - cluster_id(), - character_id() + DB::Query(), + station_id(static_cast(stationId)), + item_id(), + cluster_id(), + character_id() { } @@ -500,7 +501,7 @@ GetClaimedRewardItemsQuery::GetClaimedRewardItemsQuery(StationId stationId) : void GetClaimedRewardItemsQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.get_claimed_reward_items(:station_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.get_claimed_reward_items(:station_id); end;"; } // ---------------------------------------------------------------------- @@ -552,9 +553,9 @@ NetworkId const GetClaimedRewardItemsQuery::getCharacterId() const // ====================================================================== IsClusterAtLimitQuery::IsClusterAtLimitQuery() : -Query(), -cluster_id(), -result() + Query(), + cluster_id(), + result() { } @@ -562,7 +563,7 @@ result() void IsClusterAtLimitQuery::getSQL(std::string &sql) { - sql = std::string("begin :result := ")+DatabaseConnection::getInstance().getSchemaQualifier()+"login.is_cluster_at_limit(:cluster_id); end;"; + sql = std::string("begin :result := ") + DatabaseConnection::getInstance().getSchemaQualifier() + "login.is_cluster_at_limit(:cluster_id); end;"; } // ---------------------------------------------------------------------- @@ -588,4 +589,4 @@ DB::Query::QueryMode IsClusterAtLimitQuery::getExecutionMode() const return MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/LoginServer/src/shared/TaskUpdatePurgeAccountList.h b/engine/server/application/LoginServer/src/shared/TaskUpdatePurgeAccountList.h index 3888e9a5..645d30c4 100755 --- a/engine/server/application/LoginServer/src/shared/TaskUpdatePurgeAccountList.h +++ b/engine/server/application/LoginServer/src/shared/TaskUpdatePurgeAccountList.h @@ -18,10 +18,6 @@ class TaskUpdatePurgeAccountList : public DB::TaskRequest TaskUpdatePurgeAccountList(); virtual bool process (DB::Session *session); virtual void onComplete (); - - private: - StationId m_account; - int m_purgePhase; }; // ====================================================================== diff --git a/engine/server/application/LoginServer/src/win32/FirstLoginServer.cpp b/engine/server/application/LoginServer/src/win32/FirstLoginServer.cpp new file mode 100644 index 00000000..199562bb --- /dev/null +++ b/engine/server/application/LoginServer/src/win32/FirstLoginServer.cpp @@ -0,0 +1 @@ +#include "FirstLoginServer.h" diff --git a/engine/server/application/LoginServer/src/win32/WinMain.cpp b/engine/server/application/LoginServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..f5c7056c --- /dev/null +++ b/engine/server/application/LoginServer/src/win32/WinMain.cpp @@ -0,0 +1,46 @@ +#include "FirstLoginServer.h" +#include "ConfigLoginServer.h" +#include "LoginServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" + +#include + +int main(int argc, char **argv) +{ + + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + + SetupSharedFoundation::install (setupFoundationData); + SetupSharedNetworkMessages::install(); + + SetupSharedCompression::install(); + + SetupSharedFile::install(false); + + SetupSharedRandom::install(time(NULL)); + + //-- setup game server + ConfigLoginServer::install (); + + //-- run game + SetupSharedFoundation::callbackWithExceptionHandling(LoginServer::run); + + SetupSharedFoundation::remove(); + + return 0; +} diff --git a/engine/server/application/MetricsServer/src/linux/main.cpp b/engine/server/application/MetricsServer/src/linux/main.cpp index 2287e9de..d4a429d8 100755 --- a/engine/server/application/MetricsServer/src/linux/main.cpp +++ b/engine/server/application/MetricsServer/src/linux/main.cpp @@ -40,7 +40,7 @@ int main(int argc, char ** argv) SetupSharedNetwork::getDefaultServerSetupData(networkSetupData); SetupSharedNetwork::install(networkSetupData); - SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + SetupSharedRandom::install(static_cast(time(nullptr))); //lint !e1924 !e64 // nullptr is a C-Style cast? Os::setProgramName("MetricsServer"); //setup the server diff --git a/engine/server/application/MetricsServer/src/shared/MetricsGatheringConnection.cpp b/engine/server/application/MetricsServer/src/shared/MetricsGatheringConnection.cpp index 4cab5ae6..0f0c735d 100755 --- a/engine/server/application/MetricsServer/src/shared/MetricsGatheringConnection.cpp +++ b/engine/server/application/MetricsServer/src/shared/MetricsGatheringConnection.cpp @@ -10,6 +10,8 @@ #include "MonAPI2/MonitorAPI.h" #include "serverNetworkMessages/MetricsInitiationMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include //----------------------------------------------------------------------- @@ -79,34 +81,42 @@ void MetricsGatheringConnection::onReceive(const Archive::ByteStream & message) GameNetworkMessage m(ri); ri = message.begin(); - if(m.isType("ConnectionServerMetricsMessage")) - { - DEBUG_FATAL(true, ("This message has been depricated")); - } - else if (m.isType("MetricsInitiationMessage")) - { - WARNING_STRICT_FATAL(m_initialized, ("Received initialize metrics on initialized connection")); - //Get process name and secondary field (i.e. planet) - MetricsInitiationMessage mx(ri); - bool dynamic = mx.getIsDynamic(); - std::string process = mx.getPrimaryName(); - std::string planet = mx.getSecondaryName(); - int index = mx.getIndex(); - initialize(process, planet, dynamic, index); - } - else if (m.isType("MetricsDataMessage")) - { - if (!m_initialized) + const uint32 messageType = m.getType(); + + switch(messageType) { + case constcrc("ConnectionServerMetricsMessage") : { - //Received data on uninitialized connection. - return; + DEBUG_FATAL(true, ("This message has been depricated")); + break; + } + case constcrc("MetricsInitiationMessage") : + { + WARNING_STRICT_FATAL(m_initialized, ("Received initialize metrics on initialized connection")); + //Get process name and secondary field (i.e. planet) + MetricsInitiationMessage mx(ri); + bool dynamic = mx.getIsDynamic(); + std::string process = mx.getPrimaryName(); + std::string planet = mx.getSecondaryName(); + int index = mx.getIndex(); + initialize(process, planet, dynamic, index); + break; + } + case constcrc("MetricsDataMessage") : + { + if (!m_initialized) + { + //Received data on uninitialized connection. + return; + } + MetricsDataMessage metricsData(ri); + update(metricsData.getData()); + break; + } + default : + { + ServerConnection::onReceive(message); + break; } - MetricsDataMessage metricsData(ri); - update(metricsData.getData()); - } - else - { - ServerConnection::onReceive(message); } } @@ -169,19 +179,19 @@ void MetricsGatheringConnection::update(const std::vector & data) //note: we know that the "isSecret", and "isLocked" nodes will come after the "population" node in the list // we are iterating over, so they will override the population setting - if (strstr((*dataIter).m_label.c_str(), "population") != NULL) + if (strstr((*dataIter).m_label.c_str(), "population") != nullptr) { // there are nodes under the population node, so don't interpret them as the population - if (strstr((*dataIter).m_label.c_str(), "population.") == NULL) + if (strstr((*dataIter).m_label.c_str(), "population.") == nullptr) mon->set(MetricsServer::getWorldCountChannel(), std::max((*dataIter).m_value, 0)); } - else if (strstr((*dataIter).m_label.c_str(), "isSecret") != NULL - || strstr((*dataIter).m_label.c_str(), "isLocked") != NULL) + else if (strstr((*dataIter).m_label.c_str(), "isSecret") != nullptr + || strstr((*dataIter).m_label.c_str(), "isLocked") != nullptr) { if ((*dataIter).m_value == 1) mon->set(MetricsServer::getWorldCountChannel(), STATUS_LOCKED); } - else if (strstr((*dataIter).m_label.c_str(), "isLoading") != NULL) + else if (strstr((*dataIter).m_label.c_str(), "isLoading") != nullptr) { // include in the root node description how // long the cluster has been loading @@ -226,19 +236,19 @@ void MetricsGatheringConnection::update(const std::vector & data) //note: we know that the "isSecret", and "isLocked" nodes will come after the "population" node in the list // we are iterating over, so they will override the population setting - if (strstr((*dataIter).m_label.c_str(), "population") != NULL) + if (strstr((*dataIter).m_label.c_str(), "population") != nullptr) { // there are nodes under the population node, so don't interpret them as the population - if (strstr((*dataIter).m_label.c_str(), "population.") == NULL) + if (strstr((*dataIter).m_label.c_str(), "population.") == nullptr) mon->set(MetricsServer::getWorldCountChannel(), std::max((*dataIter).m_value, 0)); } - else if (strstr((*dataIter).m_label.c_str(), "isSecret") != NULL - || strstr((*dataIter).m_label.c_str(), "isLocked") != NULL) + else if (strstr((*dataIter).m_label.c_str(), "isSecret") != nullptr + || strstr((*dataIter).m_label.c_str(), "isLocked") != nullptr) { if ((*dataIter).m_value == 1) mon->set(MetricsServer::getWorldCountChannel(), STATUS_LOCKED); } - else if (strstr((*dataIter).m_label.c_str(), "isLoading") != NULL) + else if (strstr((*dataIter).m_label.c_str(), "isLoading") != nullptr) { // include in the root node description how // long the cluster has been loading diff --git a/engine/server/application/MetricsServer/src/shared/MetricsServer.cpp b/engine/server/application/MetricsServer/src/shared/MetricsServer.cpp index 9754caca..aab52220 100755 --- a/engine/server/application/MetricsServer/src/shared/MetricsServer.cpp +++ b/engine/server/application/MetricsServer/src/shared/MetricsServer.cpp @@ -29,8 +29,8 @@ std::string MetricsServer::m_worldCountChannelDescription; bool MetricsServer::m_done = false; Service* MetricsServer::m_metricsService; CMonitorAPI * MetricsServer::m_soeMonitor; -Service * MetricsServer::ms_service = NULL; -TaskConnection * MetricsServer::ms_taskConnection = NULL; +Service * MetricsServer::ms_service = nullptr; +TaskConnection * MetricsServer::ms_taskConnection = nullptr; //---------------------------------------------------------------- diff --git a/engine/server/application/MetricsServer/src/shared/TaskConnection.cpp b/engine/server/application/MetricsServer/src/shared/TaskConnection.cpp index c3a6d841..3ec3e534 100755 --- a/engine/server/application/MetricsServer/src/shared/TaskConnection.cpp +++ b/engine/server/application/MetricsServer/src/shared/TaskConnection.cpp @@ -72,10 +72,6 @@ void TaskConnection::onConnectionOpened() void TaskConnection::onReceive(const Archive::ByteStream & message) { UNREF(message); -#if 0 - Archive::ReadIterator r(message); - GameNetworkMessage m(r); -#endif } //----------------------------------------------------------------------- diff --git a/engine/server/application/MetricsServer/src/win32/WinMain.cpp b/engine/server/application/MetricsServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..5955efba --- /dev/null +++ b/engine/server/application/MetricsServer/src/win32/WinMain.cpp @@ -0,0 +1,91 @@ +#include "sharedFoundation/FirstSharedFoundation.h" + +#include "ConfigMetricsServer.h" +#include "MetricsServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetwork/NetworkHandler.h" +#include "sharedNetwork/SetupSharedNetwork.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" + +#include + +// ====================================================================== + +int main(int argc, char ** argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + // command line hack + std::string cmdLine; + for(int i = 1; i < argc; ++i) + { + cmdLine += argv[i]; + if(i + 1 < argc) + { + cmdLine += " "; + } + } + + setupFoundationData.commandLine = cmdLine.c_str(); + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install (setupFoundationData); + + { + //SetupSharedObject::Data data; + //SetupSharedObject::setupDefaultGameData(data); + //SetupSharedObject::install(data); + } + SetupSharedCompression::install(); + SetupSharedFile::install(true, 32); + + SetupSharedNetwork::SetupData networkSetupData; + SetupSharedNetwork::getDefaultServerSetupData(networkSetupData); + SetupSharedNetwork::install(networkSetupData); + + SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + + //Os::setProgramName("MetricsServer"); + //setup the server + ConfigMetricsServer::install(); + + //set command line + cmdLine = setupFoundationData.commandLine; + size_t firstArg = cmdLine.find(" ", 0); + size_t lastSlash = 0; + size_t nextSlash = 0; + while(nextSlash < firstArg) + { + nextSlash = cmdLine.find("/", lastSlash); + if(nextSlash == cmdLine.npos || nextSlash >= firstArg) //lint !e1705 static class members may be accessed by the scoping operator (huh?) + break; + lastSlash = nextSlash + 1; + } + cmdLine = cmdLine.substr(lastSlash); + MetricsServer::setCommandLine(cmdLine); + + + //-- run game + NetworkHandler::install(); + MetricsServer::install(); + MetricsServer::run(); + MetricsServer::remove(); + NetworkHandler::remove(); + SetupSharedFoundation::remove(); + + return 0; +} + + diff --git a/engine/server/application/PlanetServer/src/linux/main.cpp b/engine/server/application/PlanetServer/src/linux/main.cpp index d77747cf..7d8b5908 100755 --- a/engine/server/application/PlanetServer/src/linux/main.cpp +++ b/engine/server/application/PlanetServer/src/linux/main.cpp @@ -46,7 +46,7 @@ int main(int argc, char ** argv) SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(time(NULL)); //lint !e732 loss of sign (of 0!) + SetupSharedRandom::install(time(nullptr)); //lint !e732 loss of sign (of 0!) SetupSharedUtility::Data sharedUtilityData; SetupSharedUtility::setupGameData (sharedUtilityData); diff --git a/engine/server/application/PlanetServer/src/shared/ConsoleCommandParser.cpp b/engine/server/application/PlanetServer/src/shared/ConsoleCommandParser.cpp index b5839b87..4a3fec7d 100755 --- a/engine/server/application/PlanetServer/src/shared/ConsoleCommandParser.cpp +++ b/engine/server/application/PlanetServer/src/shared/ConsoleCommandParser.cpp @@ -31,7 +31,7 @@ const CommandParser::CmdInfo cmds[] = //----------------------------------------------------------------------- ConsoleCommandParser::ConsoleCommandParser() : -CommandParser ("", 0, "...", "console commands", NULL) +CommandParser ("", 0, "...", "console commands", nullptr) { createDelegateCommands(cmds); } diff --git a/engine/server/application/PlanetServer/src/shared/ConsoleManager.cpp b/engine/server/application/PlanetServer/src/shared/ConsoleManager.cpp index 2326cbf2..4a94be0c 100755 --- a/engine/server/application/PlanetServer/src/shared/ConsoleManager.cpp +++ b/engine/server/application/PlanetServer/src/shared/ConsoleManager.cpp @@ -14,7 +14,7 @@ namespace ConsoleManagerNamespace { - ConsoleCommandParser * s_consoleCommandParserRoot = NULL; + ConsoleCommandParser * s_consoleCommandParserRoot = nullptr; } using namespace ConsoleManagerNamespace; diff --git a/engine/server/application/PlanetServer/src/shared/GameServerConnection.cpp b/engine/server/application/PlanetServer/src/shared/GameServerConnection.cpp index 82eb4d35..f2a60fbb 100755 --- a/engine/server/application/PlanetServer/src/shared/GameServerConnection.cpp +++ b/engine/server/application/PlanetServer/src/shared/GameServerConnection.cpp @@ -15,6 +15,8 @@ #include "sharedLog/Log.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== GameServerConnection::GameServerConnection(UdpConnectionMT *u, TcpClient *t) : @@ -62,39 +64,46 @@ void GameServerConnection::onReceive(Archive::ByteStream const &message) GameNetworkMessage msg(ri); ri = message.begin(); + const uint32 messageType = msg.getType(); + if (!m_forwardDestinationServers.empty()) { - if (isMessageForwardable(msg.getType())) + if (isMessageForwardable(messageType)) { m_forwardMessages.push_back(std::make_pair(message, m_forwardDestinationServers.back())); return; } - else if (msg.isType("EndForward")) + else { - if (--m_forwardCounts.back() == 0) - { - m_forwardCounts.pop_back(); - m_forwardDestinationServers.pop_back(); - if (m_forwardDestinationServers.empty()) - pushAndClearObjectForwarding(); + switch (messageType) { + case constcrc("EndForward") : + { + if (--m_forwardCounts.back() == 0) + { + m_forwardCounts.pop_back(); + m_forwardDestinationServers.pop_back(); + if (m_forwardDestinationServers.empty()) + pushAndClearObjectForwarding(); + } + return; + } + case constcrc("BeginForward") : + { + GenericValueTypeMessage > const beginForwardMessage(ri); + if (beginForwardMessage.getValue() == m_forwardDestinationServers.back()) + ++m_forwardCounts.back(); + else + { + m_forwardCounts.push_back(1); + m_forwardDestinationServers.push_back(beginForwardMessage.getValue()); + } + return; + } } - return; - } - else if (msg.isType("BeginForward")) - { - GenericValueTypeMessage > const beginForwardMessage(ri); - if (beginForwardMessage.getValue() == m_forwardDestinationServers.back()) - ++m_forwardCounts.back(); - else - { - m_forwardCounts.push_back(1); - m_forwardDestinationServers.push_back(beginForwardMessage.getValue()); - } - return; } } - if (msg.isType("BeginForward")) + if (messageType == constcrc("BeginForward")) { GenericValueTypeMessage > const beginForwardMessage(ri); diff --git a/engine/server/application/PlanetServer/src/shared/GameServerData.cpp b/engine/server/application/PlanetServer/src/shared/GameServerData.cpp index 58a57f31..e7e91d59 100755 --- a/engine/server/application/PlanetServer/src/shared/GameServerData.cpp +++ b/engine/server/application/PlanetServer/src/shared/GameServerData.cpp @@ -27,7 +27,7 @@ GameServerData::GameServerData(GameServerConnection *connection) : // ---------------------------------------------------------------------- GameServerData::GameServerData(const GameServerData &rhs) : - m_connection(NULL), // connection pointer is not copied when we copy GameServerDatas + m_connection(nullptr), // connection pointer is not copied when we copy GameServerDatas m_objectCount(rhs.m_objectCount), m_interestObjectCount(rhs.m_interestObjectCount), m_interestCreatureObjectCount(rhs.m_interestCreatureObjectCount), @@ -38,7 +38,7 @@ GameServerData::GameServerData(const GameServerData &rhs) : // ---------------------------------------------------------------------- GameServerData::GameServerData() : - m_connection(NULL), + m_connection(nullptr), m_objectCount(0), m_interestObjectCount(0), m_interestCreatureObjectCount(0), @@ -53,7 +53,7 @@ GameServerData &GameServerData::operator=(const GameServerData &rhs) if (&rhs == this) return *this; - m_connection=NULL; // connection pointer is not copied when we copy GameServerDatas + m_connection=nullptr; // connection pointer is not copied when we copy GameServerDatas m_objectCount=rhs.m_objectCount; m_interestObjectCount=rhs.m_interestObjectCount; m_interestCreatureObjectCount=rhs.m_interestCreatureObjectCount; diff --git a/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp b/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp index 0fff2eb7..5e6a0338 100755 --- a/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp +++ b/engine/server/application/PlanetServer/src/shared/PlanetProxyObject.cpp @@ -32,42 +32,43 @@ MemoryBlockManager* PlanetProxyObject::memoryBlockManager; // ====================================================================== -PlanetProxyObject::PlanetProxyObject (const NetworkId &objectId) : - m_objectId(objectId), - m_containedBy(NetworkId::cms_invalid), - m_x(0), - m_y(0), - m_z(0), - m_authoritativeServer(0), - m_lastReportedServer(0), - m_interestRadius(0), - m_quadtreeNode(NULL), - m_authTransferTimeMs(Clock::timeMs()), - m_contents(NULL), - m_level(0), - m_hibernating(false), - m_templateCrc(0), - m_aiActivity(-1), - m_creationType(-1) +PlanetProxyObject::PlanetProxyObject(const NetworkId &objectId) : + m_objectId(objectId), + m_containedBy(NetworkId::cms_invalid), + m_x(0), + m_y(0), + m_z(0), + m_authoritativeServer(0), + m_lastReportedServer(0), + m_interestRadius(0), + m_quadtreeNode(nullptr), + m_authTransferTimeMs(Clock::timeMs()), + m_contents(nullptr), + m_level(0), + m_hibernating(false), + m_templateCrc(0), + m_aiActivity(-1), + m_creationType(-1), + m_objectTypeTag(0) { } // ---------------------------------------------------------------------- -PlanetProxyObject::~PlanetProxyObject () +PlanetProxyObject::~PlanetProxyObject() { if (PlanetServer::getInstance().isWatcherPresent()) { outputStatusToAll(true); } - m_quadtreeNode=0; + m_quadtreeNode = 0; if (m_contents) { - for (std::vector::const_iterator i=m_contents->begin(); i!=m_contents->end(); ++i) - WARNING(true,("Object %s was deleted without removing contained object %s first",m_objectId.getValueString().c_str(), i->getValueString().c_str())); + for (std::vector::const_iterator i = m_contents->begin(); i != m_contents->end(); ++i) + WARNING(true, ("Object %s was deleted without removing contained object %s first", m_objectId.getValueString().c_str(), i->getValueString().c_str())); delete m_contents; - m_contents=0; + m_contents = 0; } } @@ -79,7 +80,7 @@ PlanetProxyObject::~PlanetProxyObject () */ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint32 authoritativeServer, int interestRadius, int objectTypeTag, int const level, bool const hibernating, uint32 const templateCrc, int const aiActivity, int const creationType) { - WARNING_DEBUG_FATAL(m_objectId==NetworkId::cms_invalid,("Object ID was 0.")); + WARNING_DEBUG_FATAL(m_objectId == NetworkId::cms_invalid, ("Object ID was 0.")); bool watcherUpdateNeeded = false; m_level = level; @@ -88,64 +89,64 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 m_aiActivity = aiActivity; m_creationType = creationType; - if ((m_authoritativeServer != 0 ) && (authoritativeServer != m_authoritativeServer) && (containedBy == NetworkId::cms_invalid)) + if ((m_authoritativeServer != 0) && (authoritativeServer != m_authoritativeServer) && (containedBy == NetworkId::cms_invalid)) { static unsigned long authTransferSanityCheckTimeMs = ConfigPlanetServer::getAuthTransferSanityCheckTimeMs(); - if (Clock::timeMs()-m_authTransferTimeMs > authTransferSanityCheckTimeMs) + if (Clock::timeMs() - m_authTransferTimeMs > authTransferSanityCheckTimeMs) { - WARNING(true, ("Resending auth transfer for %s to %lu due to receiving a stale position update.", m_objectId.getValueString().c_str(), authoritativeServer)); + DEBUG_WARNING(true, ("Resending auth transfer for %s to %lu due to receiving a stale position update.", m_objectId.getValueString().c_str(), authoritativeServer)); sendAuthorityChange(authoritativeServer, m_authoritativeServer, false); return; } if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Ignoring update for %s from %lu because server was not authoritative.",m_objectId.getValueString().c_str(),authoritativeServer)); + LOG("ObjectLoading", ("Ignoring update for %s from %lu because server was not authoritative.", m_objectId.getValueString().c_str(), authoritativeServer)); return; } - - if (interestRadius>ConfigPlanetServer::getMaxInterestRadius()) + + if (interestRadius > ConfigPlanetServer::getMaxInterestRadius()) interestRadius = ConfigPlanetServer::getMaxInterestRadius(); - - if (interestRadius>0 && PlanetServer::getInstance().isInTutorialMode()) + + if (interestRadius > 0 && PlanetServer::getInstance().isInTutorialMode()) interestRadius = 1; - if (containedBy!=NetworkId::cms_invalid) + if (containedBy != NetworkId::cms_invalid) { // get coordinates from container PlanetProxyObject *container = Scene::getInstance().findObjectByID(containedBy); if (container) { - x=container->getX(); - y=container->getY(); - z=container->getZ(); + x = container->getX(); + y = container->getY(); + z = container->getZ(); } else { - LOG("PlanetUpdate",("Game server said object %s was contained by object %s, but we could not find the container.",m_objectId.getValueString().c_str(),containedBy.getValueString().c_str())); + LOG("PlanetUpdate", ("Game server said object %s was contained by object %s, but we could not find the container.", m_objectId.getValueString().c_str(), containedBy.getValueString().c_str())); containedBy = NetworkId::cms_invalid; // so that we'll try again when the object moves again, in case we just got objects out-of-order from the game server } } - + std::vector oldProxyList; - Node *newNode=Scene::getInstance().findNodeByPosition(x,z); + Node *newNode = Scene::getInstance().findNodeByPosition(x, z); NOT_NULL(newNode); - if (newNode!=m_quadtreeNode || m_interestRadius != interestRadius || m_authoritativeServer != authoritativeServer || m_containedBy != containedBy) + if (newNode != m_quadtreeNode || m_interestRadius != interestRadius || m_authoritativeServer != authoritativeServer || m_containedBy != containedBy) { watcherUpdateNeeded = true; // For debugging, update the contents of the containers - if (ConfigPlanetServer::getEnableContentsChecking() && (m_containedBy!=containedBy)) + if (ConfigPlanetServer::getEnableContentsChecking() && (m_containedBy != containedBy)) updateContentsTracking(containedBy); - - bool const firstUpdate = (m_quadtreeNode == NULL); - if (m_quadtreeNode!=NULL) // if this is the first update for this object, m_quadtreeNode will be NULL because it hasn't been placed anywhere yet + bool const firstUpdate = (m_quadtreeNode == nullptr); + + if (m_quadtreeNode != nullptr) // if this is the first update for this object, m_quadtreeNode will be nullptr because it hasn't been placed anywhere yet { removeServerStatistics(); // remember old list of proxies getServers(oldProxyList); - + // remove from the old location m_quadtreeNode->removeObject(this); @@ -153,34 +154,34 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 LOG("ObjectLoading", ("unsubscribing nodes for object id=[%s]", m_objectId.getValueString().c_str())); unsubscribeSurroundingNodes(false); } - + // update data - m_quadtreeNode=newNode; - m_x=x; - m_y=y; - m_z=z; - m_interestRadius=interestRadius; + m_quadtreeNode = newNode; + m_x = x; + m_y = y; + m_z = z; + m_interestRadius = interestRadius; m_objectTypeTag = objectTypeTag; - m_authoritativeServer=authoritativeServer; - m_containedBy=containedBy; + m_authoritativeServer = authoritativeServer; + m_containedBy = containedBy; // make sure the destination is loaded if (!newNode->isLoaded()) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Loading node %s because object %s entered it.",newNode->getDebugNodeString().c_str(), m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Loading node %s because object %s entered it.", newNode->getDebugNodeString().c_str(), m_objectId.getValueString().c_str())); newNode->load(); } - + // check if we're on the right server if (!isAuthorityOk()) { uint32 preferredServer = m_quadtreeNode->getPreferredServer(); - if (m_containedBy==NetworkId::cms_invalid) + if (m_containedBy == NetworkId::cms_invalid) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Changing authority for object %s from %lu to %lu because node %s is authoritative on that server.", - m_objectId.getValueString().c_str(),m_authoritativeServer,preferredServer,m_quadtreeNode->getDebugNodeString().c_str())); + LOG("ObjectLoading", ("Changing authority for object %s from %lu to %lu because node %s is authoritative on that server.", + m_objectId.getValueString().c_str(), m_authoritativeServer, preferredServer, m_quadtreeNode->getDebugNodeString().c_str())); changeAuthority(preferredServer, false, false); // changes m_authoritativeServer and sends message // we received the object for the first time, and we had to @@ -192,8 +193,8 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 } else { - WARNING(true,("Programmer bug: Object %s is in container %s, which is node %s. The object should be authoritative on server %i but it is authoritative on server %i.", - m_objectId.getValueString().c_str(),m_containedBy.getValueString().c_str(),m_quadtreeNode->getDebugNodeString().c_str(), m_authoritativeServer, preferredServer)); + WARNING(true, ("Programmer bug: Object %s is in container %s, which is node %s. The object should be authoritative on server %i but it is authoritative on server %i.", + m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str(), m_quadtreeNode->getDebugNodeString().c_str(), m_authoritativeServer, preferredServer)); } } @@ -204,30 +205,30 @@ void PlanetProxyObject::update(int x, int y, int z, NetworkId containedBy, uint3 { if (ConfigPlanetServer::getLogObjectLoading()) LOG("ObjectLoading", ("subscribing nodes for object id=[%s]", m_objectId.getValueString().c_str())); - subscribeSurroundingNodes(); + subscribeSurroundingNodes(); } - + // check against new interested servers, and send proxy/unproxy as needed - if (m_containedBy==NetworkId::cms_invalid) // we don't manage proxies for containers + if (m_containedBy == NetworkId::cms_invalid) // we don't manage proxies for containers { std::vector newProxyList; getServers(newProxyList); - changeProxies(oldProxyList,newProxyList); + changeProxies(oldProxyList, newProxyList); } - + addServerStatistics(); - } + } else { if (m_interestRadius > 0 || (abs(m_x - x) > 25) || (abs(m_z - z) > 25)) watcherUpdateNeeded = true; } - + if (PlanetServer::getInstance().isWatcherPresent() && watcherUpdateNeeded) { - m_x=x; - m_y=y; - m_z=z; + m_x = x; + m_y = y; + m_z = z; m_objectTypeTag = objectTypeTag; outputStatusToAll(false); @@ -240,11 +241,11 @@ void PlanetProxyObject::unsubscribeSurroundingNodes(bool clearZeroSubscriptions) { if (m_interestRadius <= 0) return; - + Scene::NodeListType nodelist; - Scene::getInstance().findIntersection(nodelist,m_x,m_z,m_interestRadius); - - for (Scene::NodeListType::iterator i=nodelist.begin(); i!=nodelist.end(); ++i) + Scene::getInstance().findIntersection(nodelist, m_x, m_z, m_interestRadius); + + for (Scene::NodeListType::iterator i = nodelist.begin(); i != nodelist.end(); ++i) { (*i)->unsubscribeServer(m_authoritativeServer, 1, clearZeroSubscriptions); } @@ -253,20 +254,20 @@ void PlanetProxyObject::unsubscribeSurroundingNodes(bool clearZeroSubscriptions) // ---------------------------------------------------------------------- void PlanetProxyObject::subscribeSurroundingNodes() -{ +{ if (m_interestRadius <= 0) return; NOT_NULL(m_quadtreeNode); Scene::NodeListType nodelist; - Scene::getInstance().findIntersection(nodelist,m_x,m_z,m_interestRadius); - - for (Scene::NodeListType::iterator i=nodelist.begin(); i!=nodelist.end(); ++i) + Scene::getInstance().findIntersection(nodelist, m_x, m_z, m_interestRadius); + + for (Scene::NodeListType::iterator i = nodelist.begin(); i != nodelist.end(); ++i) { (*i)->subscribeServer(m_authoritativeServer, 1); uint32 serverId = (*i)->getPreferredServer(); if (serverId != m_authoritativeServer) - m_quadtreeNode->subscribeServer(serverId,0); // make sure if we can see them, they can see us + m_quadtreeNode->subscribeServer(serverId, 0); // make sure if we can see them, they can see us } } @@ -332,22 +333,22 @@ void PlanetProxyObject::unload(bool tellGameServer) if (m_quadtreeNode) m_quadtreeNode->removeObject(this); - Scene::getInstance().removeObjectFromMap(m_objectId,tellGameServer); + Scene::getInstance().removeObjectFromMap(m_objectId, tellGameServer); if (tellGameServer) { - PlanetServer::getInstance().unloadObject(m_objectId,m_authoritativeServer); + PlanetServer::getInstance().unloadObject(m_objectId, m_authoritativeServer); } removeServerStatistics(); - if (ConfigPlanetServer::getEnableContentsChecking() && m_containedBy!=NetworkId::cms_invalid) + if (ConfigPlanetServer::getEnableContentsChecking() && m_containedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); if (container) container->removeContainedObject(m_objectId); else - WARNING(true,("Unloading object %s in container %s, but the container could not be found.",m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); + WARNING(true, ("Unloading object %s in container %s, but the container could not be found.", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); } } @@ -368,7 +369,7 @@ void PlanetProxyObject::outputStatus(WatcherConnection &conn, bool deleteObject) void PlanetProxyObject::outputStatusToAll(bool deleteObject) const { const PlanetServer::WatcherList &connections = PlanetServer::getInstance().getWatchers(); - for (PlanetServer::WatcherList::const_iterator i= connections.begin(); i!=connections.end(); ++i) + for (PlanetServer::WatcherList::const_iterator i = connections.begin(); i != connections.end(); ++i) { outputStatus(**i, deleteObject); } @@ -376,21 +377,21 @@ void PlanetProxyObject::outputStatusToAll(bool deleteObject) const // ---------------------------------------------------------------------- -/** +/** * Update the GameServerData with statistics about this object. */ void PlanetProxyObject::addServerStatistics() const { - GameServerData *data=PlanetServer::getInstance().getGameServerData(m_authoritativeServer); + GameServerData *data = PlanetServer::getInstance().getGameServerData(m_authoritativeServer); if (data) { data->adjustObjectCount(1); - if (m_interestRadius!=0) + if (m_interestRadius != 0) { data->adjustInterestObjectCount(1); if (isCreature()) data->adjustInterestCreatureObjectCount(1); - } + } } } @@ -402,15 +403,15 @@ void PlanetProxyObject::addServerStatistics() const */ void PlanetProxyObject::removeServerStatistics() const { - GameServerData *data=PlanetServer::getInstance().getGameServerData(m_authoritativeServer); + GameServerData *data = PlanetServer::getInstance().getGameServerData(m_authoritativeServer); if (data) { data->adjustObjectCount(-1); - if (m_interestRadius!=0) + if (m_interestRadius != 0) { data->adjustInterestObjectCount(-1); if (isCreature()) - data->adjustInterestCreatureObjectCount(-1); + data->adjustInterestCreatureObjectCount(-1); } } } @@ -423,7 +424,7 @@ void PlanetProxyObject::removeServerStatistics() const void PlanetProxyObject::install() { memoryBlockManager = new MemoryBlockManager("PlanetProxyObject::memoryBlockManager", true, sizeof(PlanetProxyObject), 0, 0, 0); - ExitChain::add(&remove, "PlanetProxyObject::remove"); + ExitChain::add(&remove, "PlanetProxyObject::remove"); } // ---------------------------------------------------------------------- @@ -461,7 +462,7 @@ void PlanetProxyObject::operator delete(void* pointer) void PlanetProxyObject::sendAuthorityChange(uint32 currentAuthServer, uint32 newAuthServer, bool handlingCrash) { - DEBUG_WARNING(!isAuthorityClean(), ("Object %s attempted to change authority before previous authority change was complete.",getObjectId().getValueString().c_str())); + DEBUG_WARNING(!isAuthorityClean(), ("Object %s attempted to change authority before previous authority change was complete.", getObjectId().getValueString().c_str())); SetAuthoritativeMessage const auth(getObjectId(), newAuthServer, false, handlingCrash, NetworkId::cms_invalid, Transform::identity, false); PlanetServer::getInstance().sendToGameServer(currentAuthServer, auth); @@ -473,7 +474,7 @@ void PlanetProxyObject::sendAuthorityChange(uint32 currentAuthServer, uint32 new void PlanetProxyObject::sendAddProxy(uint32 proxyServer) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Gameserver %lu needs a proxy of object %s",proxyServer,m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Gameserver %lu needs a proxy of object %s", proxyServer, m_objectId.getValueString().c_str())); if (isAuthorityClean()) { LoadObjectMessage const loadMsg(getObjectId(), proxyServer); @@ -491,15 +492,15 @@ void PlanetProxyObject::sendAddProxy(uint32 proxyServer) void PlanetProxyObject::sendRemoveProxy(uint32 proxyServer) { if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading",("Gameserver %lu no longer needs a proxy of object %s",proxyServer,m_objectId.getValueString().c_str())); + LOG("ObjectLoading", ("Gameserver %lu no longer needs a proxy of object %s", proxyServer, m_objectId.getValueString().c_str())); if (isAuthorityClean()) { - UnloadProxyMessage msg(getObjectId(),proxyServer); + UnloadProxyMessage msg(getObjectId(), proxyServer); PlanetServer::getInstance().sendToGameServer(m_authoritativeServer, msg); } else { - UnloadProxyMessage *msg = new UnloadProxyMessage(getObjectId(),proxyServer); + UnloadProxyMessage *msg = new UnloadProxyMessage(getObjectId(), proxyServer); PlanetServer::getInstance().queueMessageForObject(getObjectId(), msg); } } @@ -516,7 +517,7 @@ void PlanetProxyObject::onReceivedMessageFromServer(uint32 server) if (m_lastReportedServer != m_authoritativeServer && server == m_authoritativeServer) // we've received a message from the new authoritative server. Send queued messages: PlanetServer::getInstance().sendQueuedMessagesForObject(*this); - + m_lastReportedServer = server; } @@ -534,8 +535,8 @@ void PlanetProxyObject::getServers(std::vector &serverList) const } else { - PlanetProxyObject *container=Scene::getInstance().findObjectByID(m_containedBy); - WARNING_STRICT_FATAL(!container,("Object %s is in container %s, which couldn't be found",m_objectId.getValueString().c_str(),m_containedBy.getValueString().c_str())); + PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); + WARNING_STRICT_FATAL(!container, ("Object %s is in container %s, which couldn't be found", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); if (container) effectiveNode = container->getNode(); else @@ -557,12 +558,12 @@ void PlanetProxyObject::getServers(std::vector &serverList) const void PlanetProxyObject::changeProxies(const std::vector &oldServers, const std::vector &newServers) { { - for (std::vector::const_iterator i=oldServers.begin(); i!=oldServers.end(); ++i) + for (std::vector::const_iterator i = oldServers.begin(); i != oldServers.end(); ++i) { if (*i != m_authoritativeServer) { bool removeNeeded = true; - for (std::vector::const_iterator j=newServers.begin(); j!=newServers.end(); ++j) + for (std::vector::const_iterator j = newServers.begin(); j != newServers.end(); ++j) { if (*i == *j) { @@ -576,12 +577,12 @@ void PlanetProxyObject::changeProxies(const std::vector &oldServers, con } } { - for (std::vector::const_iterator i=newServers.begin(); i!=newServers.end(); ++i) + for (std::vector::const_iterator i = newServers.begin(); i != newServers.end(); ++i) { if (*i != m_authoritativeServer) { bool addNeeded = true; - for (std::vector::const_iterator j=oldServers.begin(); j!=oldServers.end(); ++j) + for (std::vector::const_iterator j = oldServers.begin(); j != oldServers.end(); ++j) { if (*i == *j) { @@ -638,10 +639,10 @@ void PlanetProxyObject::addContainedObject(const NetworkId &theObject) { m_contents = new std::vector; } - for (std::vector::const_iterator i=m_contents->begin(); i!=m_contents->end(); ++i) + for (std::vector::const_iterator i = m_contents->begin(); i != m_contents->end(); ++i) { - if (*i==theObject) - WARNING(true,("Object %s was placed in container %s twice.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + if (*i == theObject) + WARNING(true, ("Object %s was placed in container %s twice.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); } m_contents->push_back(theObject); } @@ -652,13 +653,13 @@ void PlanetProxyObject::removeContainedObject(const NetworkId &theObject) { if (!m_contents) { - WARNING(true,("Attempted to remove object %s from object %s, but that object has no contents.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + WARNING(true, ("Attempted to remove object %s from object %s, but that object has no contents.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); return; } - std::vector::iterator newEnd=std::remove(m_contents->begin(), m_contents->end(), theObject); - if (newEnd==m_contents->end()) + std::vector::iterator newEnd = std::remove(m_contents->begin(), m_contents->end(), theObject); + if (newEnd == m_contents->end()) { - WARNING(true,("Attempted to remove object %s from object %s, but it was not in the container.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); + WARNING(true, ("Attempted to remove object %s from object %s, but it was not in the container.", theObject.getValueString().c_str(), m_objectId.getValueString().c_str())); return; } m_contents->erase(newEnd, m_contents->end()); @@ -672,22 +673,22 @@ void PlanetProxyObject::removeContainedObject(const NetworkId &theObject) */ void PlanetProxyObject::updateContentsTracking(const NetworkId &newContainedBy) { - if (m_containedBy!=NetworkId::cms_invalid) + if (m_containedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(m_containedBy); if (container) container->removeContainedObject(m_objectId); else - WARNING(true,("Removing object %s from container %s, but the container could not be found.",m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); + WARNING(true, ("Removing object %s from container %s, but the container could not be found.", m_objectId.getValueString().c_str(), m_containedBy.getValueString().c_str())); } - if (newContainedBy!=NetworkId::cms_invalid) + if (newContainedBy != NetworkId::cms_invalid) { PlanetProxyObject *container = Scene::getInstance().findObjectByID(newContainedBy); if (container) container->addContainedObject(m_objectId); else - WARNING(true,("Adding object %s to container %s, but the container could not be found.",m_objectId.getValueString().c_str(), newContainedBy.getValueString().c_str())); + WARNING(true, ("Adding object %s to container %s, but the container could not be found.", m_objectId.getValueString().c_str(), newContainedBy.getValueString().c_str())); } } @@ -695,7 +696,7 @@ void PlanetProxyObject::updateContentsTracking(const NetworkId &newContainedBy) bool PlanetProxyObject::isCreature() const { - return m_objectTypeTag==TAG(C,R,E,O); + return m_objectTypeTag == TAG(C, R, E, O); } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/application/PlanetServer/src/shared/PlanetServer.cpp b/engine/server/application/PlanetServer/src/shared/PlanetServer.cpp index d69a029c..a472d8e1 100755 --- a/engine/server/application/PlanetServer/src/shared/PlanetServer.cpp +++ b/engine/server/application/PlanetServer/src/shared/PlanetServer.cpp @@ -70,6 +70,8 @@ #include "sharedUtility/LocationManager.h" #include "unicodeArchive/UnicodeArchive.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include #include #include @@ -102,12 +104,12 @@ using namespace PlanetServerNamespace; PlanetServer::PlanetServer() : Singleton(), MessageDispatch::Receiver(), - m_pendingCentralServerConnection(NULL), - m_centralServerConnection(NULL), - m_gameService(NULL), - m_watcherService(NULL), + m_pendingCentralServerConnection(nullptr), + m_centralServerConnection(nullptr), + m_gameService(nullptr), + m_watcherService(nullptr), m_gameServers(), - m_taskConnection(NULL), + m_taskConnection(nullptr), m_done(false), m_roundRobinGameServer(0), m_pendingServerStarts(new std::map()), @@ -117,7 +119,7 @@ PlanetServer::PlanetServer() : m_spaceMode(false), m_messagesWaitingForGameServer(), m_metricsData(0), - m_taskManagerConnection(NULL), + m_taskManagerConnection(nullptr), m_sceneTransferChunkLoads(new std::list), m_pendingCharacterSaves(new std::map), m_watchers(), @@ -408,544 +410,583 @@ void PlanetServer::mainLoop(void) void PlanetServer::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { - if(message.isType("CentralConnectionOpened")) - { - DEBUG_REPORT_LOG(true,("Connected to Central.\n")); - - //handle preloading cities -- the preload list will determine how many servers we spawn - PreloadManager::getInstance().handlePreloadList(); - } - else if (message.isType("ShutdownMessage")) - { - REPORT_LOG(true, ("Instructed to shutdown the server\n")); - setDone("Received ShutdownMessage"); - } - else if(message.isType("CentralConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Central server closed connection. Exiting.\n")); - ServerConnection const *serverConnection = dynamic_cast(&source); - setDone("CentralConnectionClosed : %s", serverConnection ? serverConnection->getDisconnectReason().c_str() : ""); - m_centralServerConnection = 0; //lint !e423 // object is deleted elsewhere - m_pendingCentralServerConnection = 0; //lint !e423 // object is deleted elsewhere - } - else if (message.isType("GameConnectionClosed")) - { - GameServerConnection *gameServer=const_cast(dynamic_cast(&source)); - std::set::iterator f = m_pendingGameServerDisconnects.find(gameServer); - - WARNING_DEBUG_FATAL(gameServer==0,("Source was NULL or source was not a GameServerConnection.")); - DEBUG_REPORT_LOG(true, ("removing crashed gameserver\n")); - uint32 id = gameServer->getProcessId(); - GameServerMapType::iterator i=m_gameServers.find(id); - if (i!=m_gameServers.end()) + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("CentralConnectionOpened") : { - delete i->second; - m_gameServers.erase(i); + DEBUG_REPORT_LOG(true,("Connected to Central.\n")); + + //handle preloading cities -- the preload list will determine how many servers we spawn + PreloadManager::getInstance().handlePreloadList(); + + break; } - - // must call this before removeGameServer() to get the preload number - // for the dead game server; we'll need that in order to start a replacement - PreloadServerId preloadServerId = PreloadManager::getInstance().getPreloadServerId(id); - - // if the game server hadn't gotten far enough to be assigned a preload - // number, use the preload number that was assigned to it when it was started - if (preloadServerId == 0) - preloadServerId = gameServer->getPreloadNumber(); - - PreloadManager::getInstance().removeGameServer(id); - if(f == m_pendingGameServerDisconnects.end()) + case constcrc("ShutdownMessage") : { - std::set startGameServerList; - IGNORE_RETURN(startGameServerList.insert(preloadServerId)); - - startGameServer(startGameServerList, ConfigPlanetServer::getGameServerRestartDelayTimeSeconds()); + REPORT_LOG(true, ("Instructed to shutdown the server\n")); + setDone("Received ShutdownMessage"); + break; } - else + case constcrc("CentralConnectionClosed") : { - m_pendingGameServerDisconnects.erase(f); + DEBUG_REPORT_LOG(true, ("Central server closed connection. Exiting.\n")); + ServerConnection const *serverConnection = dynamic_cast(&source); + setDone("CentralConnectionClosed : %s", serverConnection ? serverConnection->getDisconnectReason().c_str() : ""); + m_centralServerConnection = 0; //lint !e423 // object is deleted elsewhere + m_pendingCentralServerConnection = 0; //lint !e423 // object is deleted elsewhere + break; } - // advise watchers that the game server has closed its connection - ServerInfo info; - info.ipAddress = gameServer->getRemoteAddress(); - info.serverId = id; - info.systemPid = gameServer->getOsProcessId(); - GameServerStatus statusMsg(false, info); - std::vector::iterator w; - std::vector::iterator begin = m_watchers.begin(); - std::vector::iterator end = m_watchers.end(); - - for(w = begin; w != end; ++w) + case constcrc("GameConnectionClosed") : { - (*w)->send(statusMsg, true); - } + GameServerConnection *gameServer=const_cast(dynamic_cast(&source)); + std::set::iterator f = m_pendingGameServerDisconnects.find(gameServer); - if (m_firstGameServer == id) - { - if (m_gameServers.size() == 0) - m_firstGameServer = 0; + WARNING_DEBUG_FATAL(gameServer==0,("Source was nullptr or source was not a GameServerConnection.")); + DEBUG_REPORT_LOG(true, ("removing crashed gameserver\n")); + uint32 id = gameServer->getProcessId(); + GameServerMapType::iterator i=m_gameServers.find(id); + if (i!=m_gameServers.end()) + { + delete i->second; + m_gameServers.erase(i); + } + + // must call this before removeGameServer() to get the preload number + // for the dead game server; we'll need that in order to start a replacement + PreloadServerId preloadServerId = PreloadManager::getInstance().getPreloadServerId(id); + + // if the game server hadn't gotten far enough to be assigned a preload + // number, use the preload number that was assigned to it when it was started + if (preloadServerId == 0) + preloadServerId = gameServer->getPreloadNumber(); + + PreloadManager::getInstance().removeGameServer(id); + if(f == m_pendingGameServerDisconnects.end()) + { + std::set startGameServerList; + IGNORE_RETURN(startGameServerList.insert(preloadServerId)); + + startGameServer(startGameServerList, ConfigPlanetServer::getGameServerRestartDelayTimeSeconds()); + } else { - GameServerMapType::const_iterator j=m_gameServers.begin(); - m_firstGameServer = j->first; - FirstPlanetGameServerIdMessage const msg(m_firstGameServer); - for (; j!=m_gameServers.end(); ++j) - j->second->getConnection()->send(msg, true); + m_pendingGameServerDisconnects.erase(f); } - } - PreloadFinishedMessage const preloadFinishedMessage(PreloadManager::getInstance().isPreloadComplete()); - sendToCentral(preloadFinishedMessage, true); - } + // advise watchers that the game server has closed its connection + ServerInfo info; + info.ipAddress = gameServer->getRemoteAddress(); + info.serverId = id; + info.systemPid = gameServer->getOsProcessId(); + GameServerStatus statusMsg(false, info); + std::vector::iterator w; + std::vector::iterator begin = m_watchers.begin(); + std::vector::iterator end = m_watchers.end(); - else if(message.isType("GameGameServerConnect")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameGameServerConnect msg(ri); - GameServerConnection * conn = const_cast(safe_cast(&source)); - - std::map >::iterator f = m_startingGameServers->find(msg.getSpawnCookie()); - if(f != m_startingGameServers->end()) - m_startingGameServers->erase(f); - - uint32 id = msg.getProcessId(); - m_gameServers[id]=new GameServerData(conn); - conn->setProcessId(id); - conn->setPreloadNumber(msg.getPreloadNumber()); - LOG("PlanetServerConnections",("Game Server %lu (preload %d) connected on scene %s. m_startingGameServers is now %i", id, msg.getPreloadNumber(), ConfigPlanetServer::getSceneID(),m_startingGameServers->size())); - - DEBUG_REPORT_LOG(true,("Game Server %lu (preload %d) connected on scene %s.\n", id, msg.getPreloadNumber(), ConfigPlanetServer::getSceneID())); - - ServerInfo info; - info.ipAddress = conn->getRemoteAddress(); - info.serverId = id; - info.systemPid = conn->getOsProcessId(); - GameServerStatus statusMsg(true, info); - std::vector::iterator i; - std::vector::iterator begin = m_watchers.begin(); - std::vector::iterator end = m_watchers.end(); - - for(i = begin; i != end; ++i) - { - (*i)->send(statusMsg, true); - } - - if (m_firstGameServer == 0) - { - WARNING_STRICT_FATAL(m_gameServers.size() > 1, ("m_firstGameServer was not set but there were Game Server connections in the list.")); - m_firstGameServer = id; - } - - FirstPlanetGameServerIdMessage const fpgsim(m_firstGameServer); - conn->send(fpgsim, true); - } - else if(message.isType("GameServerReadyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GameServerReadyMessage msg(ri); - - GameServerConnection * conn = const_cast(dynamic_cast(&source)); - if (conn) - { - uint32 id = conn->getProcessId(); - GameServerMapType::iterator mapIter = m_gameServers.find(id); - if (mapIter==m_gameServers.end()) + for(w = begin; w != end; ++w) { - WARNING_STRICT_FATAL(true,("GameServer %lu wasn't in the map, but we got GameServerReadyMessage from it.",id)); - return; - } - Scene::getInstance().setMapSize(msg.getMapWidth()); - mapIter->second->ready(); - } - } - else if(message.isType("GameServerUniverseLoadedMessage")) - { - GameServerConnection * conn = const_cast(dynamic_cast(&source)); - if (conn) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const GameServerUniverseLoadedMessage msg(ri); - - uint32 id = conn->getProcessId(); - LOG("PlanetServerConnections", ("Game Server %lu (preload %d) has loaded the universe objects.", conn->getProcessId(), conn->getPreloadNumber())); - - GameServerMapType::iterator mapIter = m_gameServers.find(id); - WARNING_STRICT_FATAL(mapIter==m_gameServers.end(),("GameServer %s wasn't in the map, but we got UniverseLoadedMessage from it.",id)); - if (mapIter==m_gameServers.end()) - return; - mapIter->second->universeLoaded(); - if(! PreloadManager::getInstance().onGameServerReady(id, static_cast(conn->getPreloadNumber()))) - { - m_pendingGameServerDisconnects.insert(conn); - conn->disconnect(); - } - } - flushWaitingMessages(); - } - else if (message.isType("PreloadRequestCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const PreloadRequestCompleteMessage msg(ri); - - PreloadManager::getInstance().preloadCompleteOnServer(msg.getGameServerId()); - GameServerData *data = getGameServerData(msg.getGameServerId()); - if (data) - data->preloadComplete(); - } - else if (message.isType("RequestGameServerForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - const RequestGameServerForLoginMessage *msg = new RequestGameServerForLoginMessage(ri); - - handleRequestGameServerForLoginMessage(msg); //this function handles memory management for msg. msg is INVALID after this call. - msg = 0; - } - else if (message.isType("RequestSceneTransfer")) - { - //This message comes from Central in response to a GameServer sending central a request scene transfer message. - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestSceneTransfer const *msg = new RequestSceneTransfer(ri); - - handleRequestSceneTransfer(msg); //this function handles memory management for msg. msg is INVALID after this call. - msg = 0; - } - else if (message.isType("ChunkCompleteMessage")) - { - GameServerConnection * conn = const_cast(dynamic_cast(&source)); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ChunkCompleteMessage msg(ri); - handleChunkComplete(msg, conn); - } - else if (message.isType("WatcherConnectionOpened")) - { - WatcherConnection *newConn = const_cast(dynamic_cast(&source)); - if (newConn) - { - // advertise status of all game servers to new watcher - GameServerMapType::iterator i; - GameServerMapType::iterator begin = m_gameServers.begin(); - GameServerMapType::iterator end = m_gameServers.end(); - for(i = begin; i != end; ++i) - { - ServerInfo info; - info.ipAddress = (*i).second->getConnection()->getRemoteAddress(); - info.serverId = (*i).second->getConnection()->getProcessId(); - info.systemPid = (*i).second->getConnection()->getOsProcessId(); - info.sceneId = ConfigPlanetServer::getSceneID(); - GameServerStatus const status(true, info); - newConn->send(status, true); + (*w)->send(statusMsg, true); } - if (static_cast(m_watchers.size() + 1) > ConfigPlanetServer::getMaxWatcherConnections()) + if (m_firstGameServer == id) { - DEBUG_REPORT_LOG(true,("Dropping previous watcher connection.\n")); - WARNING_DEBUG_FATAL(m_watchers.size()==0,("MaxWatcherConnections must be at least 1.")); - m_watchers[0]->disconnect(); - } - m_watchers.push_back(newConn); - m_watcherIsPresent=true; - Scene::getInstance().outputStatus(*newConn); - } - else - WARNING_STRICT_FATAL(true,("Got WatcherConnectionOpened from something that wasn't a WatcherConnection.")); - } - else if (message.isType("WatcherConnectionClosed")) - { - for (WatcherList::iterator i=m_watchers.begin(); i!= m_watchers.end(); ) - { - if ((*i)==&source) - i=m_watchers.erase(i); - else - ++i; - } - if (m_watchers.empty()) - { - m_watcherIsPresent=false; - DEBUG_REPORT_LOG(true,("No more watchers connected.\n")); - } - } - else if (message.isType("TaskConnectionOpened")) - { - std::set startGameServerList; - startGameServer(startGameServerList, 0); // flush any pending game server start requests - } - else if(message.isType("ProfilerOperationMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ProfilerOperationMessage msg(ri); - unsigned int processId = msg.getProcessId(); - if (!processId) - Profiler::handleOperation(msg.getOperation().c_str()); - } - else if(message.isType("FrameEndMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FrameEndMessage const msg(ri); - for (WatcherList::const_iterator i = m_watchers.begin(); i != m_watchers.end(); ++i) - (*i)->send(msg, true); - } - else if (message.isType("UnloadedPlayerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UnloadedPlayerMessage msg(ri); - - GameServerConnection *gameServer=const_cast(dynamic_cast(&source)); - WARNING_DEBUG_FATAL(gameServer==0,("Source was NULL or source was not a GameServerConnection.")); - uint32 gameServerId = gameServer->getProcessId(); - - (*m_pendingCharacterSaves)[msg.getPlayerId()]=gameServerId; - } - else if (message.isType("PersistedPlayerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PersistedPlayerMessage msg(ri); - - m_pendingCharacterSaves->erase(msg.getPlayerId()); - } - else if (message.isType("ExcommunicateGameServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ExcommunicateGameServerMessage msg(ri); - - LOG("GameGameConnect",("Planet Server %s was told to drop connection to %lu by Central",Scene::getInstance().getSceneId().c_str(),msg.getServerId())); - - GameServerConnection *conn =getGameServerConnection(msg.getServerId()); - if (conn) - conn->disconnect(); - } - else if (message.isType("FactionalSystemMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FactionalSystemMessage msg(ri); - - // forward message to all game servers on this planet for processing - for (GameServerMapType::iterator i = m_gameServers.begin(); i != m_gameServers.end(); ++i) - (*i).second->getConnection()->send(msg, true); - } - else if (message.isType("MessageToPlayersOnPlanet")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage >, std::pair >, std::pair > > const msg(ri); - - // forward message to all game servers on this planet for processing - for (GameServerMapType::iterator i = m_gameServers.begin(); i != m_gameServers.end(); ++i) - (*i).second->getConnection()->send(msg, true); - } - else if (message.isType("RequestSameServer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - bool result=Scene::getInstance().requestSameServer(msg.getValue().first, msg.getValue().second); - - GameServerConnection * const gameServer = const_cast(dynamic_cast(&source)); - - if (gameServer) - { - GenericValueTypeMessage const rssReply("RequestSameServerReply", result); - gameServer->send(rssReply, true); - } - } - else if (message.isType("RequestAuthTransfer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - bool result=Scene::getInstance().requestAuthTransfer(msg.getValue().first, msg.getValue().second); - - GameServerConnection * const gameServer = const_cast(dynamic_cast(&source)); - - if (gameServer) - { - GenericValueTypeMessage const ratReply("RequestAuthTransferReply", result); - gameServer->send(ratReply, true); - } - } - else if (message.isType("GameServerForceChangeAuthorityMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GameServerForceChangeAuthorityMessage msg(ri); - GameServerData * fromServer = PlanetServer::getGameServerData(msg.getFromProcess()); - GameServerData * toServer = PlanetServer::getGameServerData(msg.getToProcess()); - PlanetProxyObject * object = Scene::getInstance().findObjectByID(msg.getId()); - if (fromServer == NULL || toServer == NULL || object == NULL) - { - if (fromServer == NULL) - { - WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " - "from server %lu", msg.getFromProcess())); - } - if (toServer == NULL) - { - WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " - "to server %lu", msg.getToProcess())); - } - if (object == NULL) - { - WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " - "object for id %s", msg.getId().getValueString().c_str())); - } - } - else if (Scene::getInstance().getGameServerForObject(msg.getId()) != msg.getFromProcess()) - { - WARNING(true, ("Message GameServerForceChangeAuthorityMessage: object " - "%s was supposed to be on process %lu, but we think it is on %lu", - msg.getId().getValueString().c_str(), msg.getFromProcess(), - Scene::getInstance().getGameServerForObject(msg.getId()))); - } - else - { - object->changeAuthority(msg.getToProcess(), false, true); - } - } - else if (message.isType("FindAuthObjectResponse")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, bool> > msg(ri); - GameServerConnection const *gameServer = dynamic_cast(&source); - NOT_NULL(gameServer); - handleFindAuthObjectResponse(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, gameServer->getProcessId()); - } - else if (message.isType("TaskProcessDiedMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - TaskProcessDiedMessage died(ri); - // verify it was a game server - const std::string & proc = died.getProcessName(); - if(proc.find("SwgGameServer") != proc.npos) - { - // pull cookie and preload server id from the command line of the process that died - size_t start = proc.find("spawnCookie"); - size_t preloadServerIdIndex = proc.find("preloadNumber"); - if ((start != proc.npos) && (preloadServerIdIndex != proc.npos)) - { - start += std::string("spawnCookie=").length(); - size_t end = proc.find(' ', start); - std::string cookieName = proc.substr(start, end); - int i = atoi(cookieName.c_str()); - std::map >::iterator f = m_startingGameServers->find(i); - if(f != m_startingGameServers->end()) - { - m_startingGameServers->erase(f); - - preloadServerIdIndex += std::string("preloadNumber=").length(); - end = proc.find(' ', preloadServerIdIndex); - std::string preloadServerIdStr = proc.substr(preloadServerIdIndex, end); - PreloadServerId preloadServerId = static_cast(atoi(preloadServerIdStr.c_str())); - - std::set startGameServerList; - IGNORE_RETURN(startGameServerList.insert(preloadServerId)); - - startGameServer(startGameServerList, ConfigPlanetServer::getGameServerRestartDelayTimeSeconds()); - - LOG("TaskProcessDied", ("TaskManager advises the PlanetServer that a GameServer %u for scene %s started with cookie %i is no longer running", preloadServerId, ConfigPlanetServer::getSceneID(), i)); - } - } - } - } - else if (message.isType ("LocationRequest")) - { - Archive::ReadIterator readIterator = static_cast (message).getByteStream ().begin (); - - //-- received a location request message - LocationRequest const locationRequest (readIterator); - - //-- ask the location manager if the location is valid - float x = locationRequest.getSearchX (); - float z = locationRequest.getSearchZ (); - bool const valid = LocationManager::requestLocation (x, z, locationRequest.getSearchRadius (), locationRequest.getLocationReservationRadius (), locationRequest.getCheckWater (), locationRequest.getCheckSlope (), x, z); - - //-- sent result back to gameserver that requested it - LocationResponse const locationResponse (locationRequest.getNetworkId (), valid, locationRequest.getLocationId (), x, z, locationRequest.getLocationReservationRadius ()); - PlanetServer::getInstance ().sendToGameServer (locationRequest.getProcessId (), locationResponse); - } - else if (message.isType ("DatabaseSaveComplete")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - handleDatabaseSaveComplete(msg.getValue()); - } - else if (message.isType("LocateStructureMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LocateStructureMessage msg(ri); - LoadStructureMessage lsm(msg.getStructureId(), msg.getWhoRequested()); - - uint32 gameServerId = Scene::getInstance().findNodeByPosition(msg.getX(), msg.getZ())->getPreferredServer(); - PlanetServer::getInstance().sendToGameServer(gameServerId, lsm); - } - else if (message.isType("DenySetAuthoritativeMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > const msg(ri); - - // restore the authority of the object - PlanetProxyObject *object = Scene::getInstance().findObjectByID(msg.getValue().first); - if (object) - { - if (ConfigPlanetServer::getLogObjectLoading()) - LOG("ObjectLoading", - ("Set authoritative denied by game server: restoring authority for object %s to server %lu", - msg.getValue().first.getValueString().c_str(),msg.getValue().second)); - - object->restoreAuthority(msg.getValue().second); - } - } - else if (message.isType("RestartServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RestartServerMessage const msg(ri); - - Node const * const node = Scene::getInstance().findNodeByPositionConst(msg.getX(), msg.getZ()); - uint32 const serverId = NON_NULL(node)->getPreferredServer(); - - if (serverId != 0) - { - ExcommunicateGameServerMessage exmsg(serverId, 0, ""); - sendToCentral(exmsg, true); - } - } - else if (message.isType("SAMGS")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage const startAnyMissingGameServer(ri); - UNREF(startAnyMissingGameServer); - - LOG("PlanetServer", ("startanymissinggameserver:Planet %s checking for any game servers that are not started, and starting them.", Scene::getInstance().getSceneId().c_str())); - if (m_centralServerConnection) - { - // if it's been "awhile" since we requested to restart the GameServer, - // then assume that something has gone wrong, and try the restart again - time_t const timeNow = ::time(NULL); - - for (std::map >::iterator iter = m_startingGameServers->begin(); iter != m_startingGameServers->end(); ++iter) - { - if ((iter->second.second + static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())) < timeNow) - { - LOG("CentralServer", ("startanymissinggameserver:Starting missing game server (%s) because it has been %s since we requested it to be started, which has exceeded the %s limit.", iter->second.first.c_str(), CalendarTime::convertSecondsToMS(static_cast(timeNow - iter->second.second)).c_str(), CalendarTime::convertSecondsToMS(static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())).c_str())); - iter->second.second = timeNow; - TaskSpawnProcess spawn("any", "SwgGameServer", iter->second.first); - m_centralServerConnection->send(spawn,true); - } + if (m_gameServers.size() == 0) + m_firstGameServer = 0; else { - LOG("PlanetServer", ("startanymissinggameserver:It's only been %s since we requested for game server (%s) to be started, and we must wait %s before we can start it again.", CalendarTime::convertSecondsToMS(static_cast(timeNow - iter->second.second)).c_str(), iter->second.first.c_str(), CalendarTime::convertSecondsToMS(static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())).c_str())); + GameServerMapType::const_iterator j=m_gameServers.begin(); + m_firstGameServer = j->first; + FirstPlanetGameServerIdMessage const msg(m_firstGameServer); + for (; j!=m_gameServers.end(); ++j) + j->second->getConnection()->send(msg, true); } } + PreloadFinishedMessage const preloadFinishedMessage(PreloadManager::getInstance().isPreloadComplete()); + sendToCentral(preloadFinishedMessage, true); + break; } - else + case constcrc("GameGameServerConnect") : { - LOG("PlanetServer", ("startanymissinggameserver:Planet %s ignoring request because there is no central server connection.", Scene::getInstance().getSceneId().c_str())); - } - } - else if (message.isType("RestartServerByRoleMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameGameServerConnect msg(ri); + GameServerConnection * conn = const_cast(safe_cast(&source)); - uint32 serverId = PreloadManager::getInstance().getRealServerId(msg.getValue().second); - if (serverId != 0) + std::map >::iterator f = m_startingGameServers->find(msg.getSpawnCookie()); + if(f != m_startingGameServers->end()) + m_startingGameServers->erase(f); + + uint32 id = msg.getProcessId(); + m_gameServers[id]=new GameServerData(conn); + conn->setProcessId(id); + conn->setPreloadNumber(msg.getPreloadNumber()); + LOG("PlanetServerConnections",("Game Server %lu (preload %d) connected on scene %s. m_startingGameServers is now %i", id, msg.getPreloadNumber(), ConfigPlanetServer::getSceneID(),m_startingGameServers->size())); + + DEBUG_REPORT_LOG(true,("Game Server %lu (preload %d) connected on scene %s.\n", id, msg.getPreloadNumber(), ConfigPlanetServer::getSceneID())); + + ServerInfo info; + info.ipAddress = conn->getRemoteAddress(); + info.serverId = id; + info.systemPid = conn->getOsProcessId(); + GameServerStatus statusMsg(true, info); + std::vector::iterator i; + std::vector::iterator begin = m_watchers.begin(); + std::vector::iterator end = m_watchers.end(); + + for(i = begin; i != end; ++i) + { + (*i)->send(statusMsg, true); + } + + if (m_firstGameServer == 0) + { + WARNING_STRICT_FATAL(m_gameServers.size() > 1, ("m_firstGameServer was not set but there were Game Server connections in the list.")); + m_firstGameServer = id; + } + + FirstPlanetGameServerIdMessage const fpgsim(m_firstGameServer); + conn->send(fpgsim, true); + break; + } + case constcrc("GameServerReadyMessage") : { - ExcommunicateGameServerMessage exmsg(serverId, 0, ""); - sendToCentral(exmsg, true); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GameServerReadyMessage msg(ri); + + GameServerConnection * conn = const_cast(dynamic_cast(&source)); + if (conn) + { + uint32 id = conn->getProcessId(); + GameServerMapType::iterator mapIter = m_gameServers.find(id); + if (mapIter==m_gameServers.end()) + { + WARNING_STRICT_FATAL(true,("GameServer %lu wasn't in the map, but we got GameServerReadyMessage from it.",id)); + return; + } + Scene::getInstance().setMapSize(msg.getMapWidth()); + mapIter->second->ready(); + } + break; + } + case constcrc("GameServerUniverseLoadedMessage") : + { + GameServerConnection * conn = const_cast(dynamic_cast(&source)); + if (conn) + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const GameServerUniverseLoadedMessage msg(ri); + + uint32 id = conn->getProcessId(); + LOG("PlanetServerConnections", ("Game Server %lu (preload %d) has loaded the universe objects.", conn->getProcessId(), conn->getPreloadNumber())); + + GameServerMapType::iterator mapIter = m_gameServers.find(id); + WARNING_STRICT_FATAL(mapIter==m_gameServers.end(),("GameServer %s wasn't in the map, but we got UniverseLoadedMessage from it.",id)); + if (mapIter==m_gameServers.end()) + return; + mapIter->second->universeLoaded(); + if(! PreloadManager::getInstance().onGameServerReady(id, static_cast(conn->getPreloadNumber()))) + { + m_pendingGameServerDisconnects.insert(conn); + conn->disconnect(); + } + } + flushWaitingMessages(); + break; + } + case constcrc("PreloadRequestCompleteMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const PreloadRequestCompleteMessage msg(ri); + + PreloadManager::getInstance().preloadCompleteOnServer(msg.getGameServerId()); + GameServerData *data = getGameServerData(msg.getGameServerId()); + if (data) + data->preloadComplete(); + break; + } + case constcrc("RequestGameServerForLoginMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + const RequestGameServerForLoginMessage *msg = new RequestGameServerForLoginMessage(ri); + + handleRequestGameServerForLoginMessage(msg); //this function handles memory management for msg. msg is INVALID after this call. + msg = 0; + break; + } + case constcrc("RequestSceneTransfer") : + { + //This message comes from Central in response to a GameServer sending central a request scene transfer message. + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestSceneTransfer const *msg = new RequestSceneTransfer(ri); + + handleRequestSceneTransfer(msg); //this function handles memory management for msg. msg is INVALID after this call. + msg = 0; + break; + } + case constcrc("ChunkCompleteMessage") : + { + GameServerConnection * conn = const_cast(dynamic_cast(&source)); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ChunkCompleteMessage msg(ri); + handleChunkComplete(msg, conn); + break; + } + case constcrc("WatcherConnectionOpened") : + { + WatcherConnection *newConn = const_cast(dynamic_cast(&source)); + if (newConn) + { + // advertise status of all game servers to new watcher + GameServerMapType::iterator i; + GameServerMapType::iterator begin = m_gameServers.begin(); + GameServerMapType::iterator end = m_gameServers.end(); + for(i = begin; i != end; ++i) + { + ServerInfo info; + info.ipAddress = (*i).second->getConnection()->getRemoteAddress(); + info.serverId = (*i).second->getConnection()->getProcessId(); + info.systemPid = (*i).second->getConnection()->getOsProcessId(); + info.sceneId = ConfigPlanetServer::getSceneID(); + GameServerStatus const status(true, info); + newConn->send(status, true); + } + + if (static_cast(m_watchers.size() + 1) > ConfigPlanetServer::getMaxWatcherConnections()) + { + DEBUG_REPORT_LOG(true,("Dropping previous watcher connection.\n")); + WARNING_DEBUG_FATAL(m_watchers.size()==0,("MaxWatcherConnections must be at least 1.")); + m_watchers[0]->disconnect(); + } + m_watchers.push_back(newConn); + m_watcherIsPresent=true; + Scene::getInstance().outputStatus(*newConn); + } + else + WARNING_STRICT_FATAL(true,("Got WatcherConnectionOpened from something that wasn't a WatcherConnection.")); + + break; + } + case constcrc("WatcherConnectionClosed") : + { + for (WatcherList::iterator i=m_watchers.begin(); i!= m_watchers.end(); ) + { + if ((*i)==&source) + i=m_watchers.erase(i); + else + ++i; + } + if (m_watchers.empty()) + { + m_watcherIsPresent=false; + DEBUG_REPORT_LOG(true,("No more watchers connected.\n")); + } + break; + } + case constcrc("TaskConnectionOpened") : + { + std::set startGameServerList; + startGameServer(startGameServerList, 0); // flush any pending game server start requests + break; + } + case constcrc("ProfilerOperationMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ProfilerOperationMessage msg(ri); + unsigned int processId = msg.getProcessId(); + if (!processId) + Profiler::handleOperation(msg.getOperation().c_str()); + + break; + } + case constcrc("FrameEndMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FrameEndMessage const msg(ri); + for (WatcherList::const_iterator i = m_watchers.begin(); i != m_watchers.end(); ++i) + (*i)->send(msg, true); + break; + } + case constcrc("UnloadedPlayerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UnloadedPlayerMessage msg(ri); + + GameServerConnection *gameServer=const_cast(dynamic_cast(&source)); + WARNING_DEBUG_FATAL(gameServer==0,("Source was nullptr or source was not a GameServerConnection.")); + uint32 gameServerId = gameServer->getProcessId(); + + (*m_pendingCharacterSaves)[msg.getPlayerId()]=gameServerId; + break; + } + case constcrc("PersistedPlayerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PersistedPlayerMessage msg(ri); + + m_pendingCharacterSaves->erase(msg.getPlayerId()); + break; + } + case constcrc("ExcommunicateGameServerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ExcommunicateGameServerMessage msg(ri); + + LOG("GameGameConnect",("Planet Server %s was told to drop connection to %lu by Central",Scene::getInstance().getSceneId().c_str(),msg.getServerId())); + + GameServerConnection *conn =getGameServerConnection(msg.getServerId()); + if (conn) + conn->disconnect(); + break; + } + case constcrc("FactionalSystemMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FactionalSystemMessage msg(ri); + + // forward message to all game servers on this planet for processing + for (GameServerMapType::iterator i = m_gameServers.begin(); i != m_gameServers.end(); ++i) + (*i).second->getConnection()->send(msg, true); + break; + } + case constcrc("MessageToPlayersOnPlanet") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage >, std::pair >, std::pair > > const msg(ri); + + // forward message to all game servers on this planet for processing + for (GameServerMapType::iterator i = m_gameServers.begin(); i != m_gameServers.end(); ++i) + (*i).second->getConnection()->send(msg, true); + break; + } + case constcrc("RequestSameServer") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + bool result=Scene::getInstance().requestSameServer(msg.getValue().first, msg.getValue().second); + + GameServerConnection * const gameServer = const_cast(dynamic_cast(&source)); + + if (gameServer) + { + GenericValueTypeMessage const rssReply("RequestSameServerReply", result); + gameServer->send(rssReply, true); + } + break; + } + case constcrc("RequestAuthTransfer") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + bool result=Scene::getInstance().requestAuthTransfer(msg.getValue().first, msg.getValue().second); + + GameServerConnection * const gameServer = const_cast(dynamic_cast(&source)); + + if (gameServer) + { + GenericValueTypeMessage const ratReply("RequestAuthTransferReply", result); + gameServer->send(ratReply, true); + } + break; + } + case constcrc("GameServerForceChangeAuthorityMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GameServerForceChangeAuthorityMessage msg(ri); + GameServerData * fromServer = PlanetServer::getGameServerData(msg.getFromProcess()); + GameServerData * toServer = PlanetServer::getGameServerData(msg.getToProcess()); + PlanetProxyObject * object = Scene::getInstance().findObjectByID(msg.getId()); + if (fromServer == nullptr || toServer == nullptr || object == nullptr) + { + if (fromServer == nullptr) + { + WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " + "from server %lu", msg.getFromProcess())); + } + if (toServer == nullptr) + { + WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " + "to server %lu", msg.getToProcess())); + } + if (object == nullptr) + { + WARNING(true, ("Message GameServerForceChangeAuthorityMessage: no " + "object for id %s", msg.getId().getValueString().c_str())); + } + } + else if (Scene::getInstance().getGameServerForObject(msg.getId()) != msg.getFromProcess()) + { + WARNING(true, ("Message GameServerForceChangeAuthorityMessage: object " + "%s was supposed to be on process %lu, but we think it is on %lu", + msg.getId().getValueString().c_str(), msg.getFromProcess(), + Scene::getInstance().getGameServerForObject(msg.getId()))); + } + else + { + object->changeAuthority(msg.getToProcess(), false, true); + } + break; + } + case constcrc("FindAuthObjectResponse") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, bool> > msg(ri); + GameServerConnection const *gameServer = dynamic_cast(&source); + NOT_NULL(gameServer); + handleFindAuthObjectResponse(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, gameServer->getProcessId()); + break; + } + case constcrc("TaskProcessDiedMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + TaskProcessDiedMessage died(ri); + // verify it was a game server + const std::string & proc = died.getProcessName(); + if(proc.find("SwgGameServer") != proc.npos) + { + // pull cookie and preload server id from the command line of the process that died + size_t start = proc.find("spawnCookie"); + size_t preloadServerIdIndex = proc.find("preloadNumber"); + if ((start != proc.npos) && (preloadServerIdIndex != proc.npos)) + { + start += std::string("spawnCookie=").length(); + size_t end = proc.find(' ', start); + std::string cookieName = proc.substr(start, end); + int i = atoi(cookieName.c_str()); + std::map >::iterator f = m_startingGameServers->find(i); + if(f != m_startingGameServers->end()) + { + m_startingGameServers->erase(f); + + preloadServerIdIndex += std::string("preloadNumber=").length(); + end = proc.find(' ', preloadServerIdIndex); + std::string preloadServerIdStr = proc.substr(preloadServerIdIndex, end); + PreloadServerId preloadServerId = static_cast(atoi(preloadServerIdStr.c_str())); + + std::set startGameServerList; + IGNORE_RETURN(startGameServerList.insert(preloadServerId)); + + startGameServer(startGameServerList, ConfigPlanetServer::getGameServerRestartDelayTimeSeconds()); + + LOG("TaskProcessDied", ("TaskManager advises the PlanetServer that a GameServer %u for scene %s started with cookie %i is no longer running", preloadServerId, ConfigPlanetServer::getSceneID(), i)); + } + } + } + break; + } + case constcrc("LocationRequest") : + { + Archive::ReadIterator readIterator = static_cast (message).getByteStream ().begin (); + + //-- received a location request message + LocationRequest const locationRequest (readIterator); + + //-- ask the location manager if the location is valid + float x = locationRequest.getSearchX (); + float z = locationRequest.getSearchZ (); + bool const valid = LocationManager::requestLocation (x, z, locationRequest.getSearchRadius (), locationRequest.getLocationReservationRadius (), locationRequest.getCheckWater (), locationRequest.getCheckSlope (), x, z); + + //-- sent result back to gameserver that requested it + LocationResponse const locationResponse (locationRequest.getNetworkId (), valid, locationRequest.getLocationId (), x, z, locationRequest.getLocationReservationRadius ()); + PlanetServer::getInstance ().sendToGameServer (locationRequest.getProcessId (), locationResponse); + break; + } + case constcrc("DatabaseSaveComplete") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + handleDatabaseSaveComplete(msg.getValue()); + break; + } + case constcrc("LocateStructureMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LocateStructureMessage msg(ri); + LoadStructureMessage lsm(msg.getStructureId(), msg.getWhoRequested()); + + uint32 gameServerId = Scene::getInstance().findNodeByPosition(msg.getX(), msg.getZ())->getPreferredServer(); + PlanetServer::getInstance().sendToGameServer(gameServerId, lsm); + break; + } + case constcrc("DenySetAuthoritativeMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > const msg(ri); + + // restore the authority of the object + PlanetProxyObject *object = Scene::getInstance().findObjectByID(msg.getValue().first); + if (object) + { + if (ConfigPlanetServer::getLogObjectLoading()) + LOG("ObjectLoading", + ("Set authoritative denied by game server: restoring authority for object %s to server %lu", + msg.getValue().first.getValueString().c_str(),msg.getValue().second)); + + object->restoreAuthority(msg.getValue().second); + } + break; + } + case constcrc("RestartServerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RestartServerMessage const msg(ri); + + Node const * const node = Scene::getInstance().findNodeByPositionConst(msg.getX(), msg.getZ()); + uint32 const serverId = NON_NULL(node)->getPreferredServer(); + + if (serverId != 0) + { + ExcommunicateGameServerMessage exmsg(serverId, 0, ""); + sendToCentral(exmsg, true); + } + break; + } + case constcrc("SAMGS") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage const startAnyMissingGameServer(ri); + UNREF(startAnyMissingGameServer); + + LOG("PlanetServer", ("startanymissinggameserver:Planet %s checking for any game servers that are not started, and starting them.", Scene::getInstance().getSceneId().c_str())); + if (m_centralServerConnection) + { + // if it's been "awhile" since we requested to restart the GameServer, + // then assume that something has gone wrong, and try the restart again + time_t const timeNow = ::time(nullptr); + + for (std::map >::iterator iter = m_startingGameServers->begin(); iter != m_startingGameServers->end(); ++iter) + { + if ((iter->second.second + static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())) < timeNow) + { + LOG("CentralServer", ("startanymissinggameserver:Starting missing game server (%s) because it has been %s since we requested it to be started, which has exceeded the %s limit.", iter->second.first.c_str(), CalendarTime::convertSecondsToMS(static_cast(timeNow - iter->second.second)).c_str(), CalendarTime::convertSecondsToMS(static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())).c_str())); + iter->second.second = timeNow; + TaskSpawnProcess spawn("any", "SwgGameServer", iter->second.first); + m_centralServerConnection->send(spawn,true); + } + else + { + LOG("PlanetServer", ("startanymissinggameserver:It's only been %s since we requested for game server (%s) to be started, and we must wait %s before we can start it again.", CalendarTime::convertSecondsToMS(static_cast(timeNow - iter->second.second)).c_str(), iter->second.first.c_str(), CalendarTime::convertSecondsToMS(static_cast(ConfigPlanetServer::getMaxTimeToWaitForGameServerStartSeconds())).c_str())); + } + } + } + else + { + LOG("PlanetServer", ("startanymissinggameserver:Planet %s ignoring request because there is no central server connection.", Scene::getInstance().getSceneId().c_str())); + } + break; + } + case constcrc("RestartServerByRoleMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + uint32 serverId = PreloadManager::getInstance().getRealServerId(msg.getValue().second); + if (serverId != 0) + { + ExcommunicateGameServerMessage exmsg(serverId, 0, ""); + sendToCentral(exmsg, true); + } + break; } } } @@ -1005,7 +1046,7 @@ GameServerConnection *PlanetServer::getGameServerConnection(uint32 serverId) if (i!=m_gameServers.end()) return (*i).second->getConnection(); else - return NULL; + return nullptr; } // ---------------------------------------------------------------------- @@ -1290,7 +1331,7 @@ void PlanetServer::startGameServer(const std::set & preloadServ TaskSpawnProcess spawn("any", "SwgGameServer", options, i->second); if (m_centralServerConnection) { - (*m_startingGameServers)[cookie] = std::make_pair(options, ::time(NULL)); + (*m_startingGameServers)[cookie] = std::make_pair(options, ::time(nullptr)); ++cookie; m_centralServerConnection->send(spawn,true); DEBUG_REPORT_LOG(true, ("Sent start gameserver request for scene %s\n", ConfigPlanetServer::getSceneID())); @@ -1321,7 +1362,7 @@ GameServerData *PlanetServer::getGameServerData(uint32 serverId) const if (i!=m_gameServers.end()) return i->second; else - return NULL; + return nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/application/PlanetServer/src/shared/PlanetServer.h b/engine/server/application/PlanetServer/src/shared/PlanetServer.h index cf457544..7a75e4fc 100755 --- a/engine/server/application/PlanetServer/src/shared/PlanetServer.h +++ b/engine/server/application/PlanetServer/src/shared/PlanetServer.h @@ -146,7 +146,7 @@ inline int PlanetServer::getNumberOfGameServers() const inline void PlanetServer::onCentralConnected(CentralServerConnection *connection) { - m_pendingCentralServerConnection=NULL; + m_pendingCentralServerConnection=nullptr; m_centralServerConnection=connection; } diff --git a/engine/server/application/PlanetServer/src/shared/PreloadManager.cpp b/engine/server/application/PlanetServer/src/shared/PreloadManager.cpp index 37371536..15811eeb 100755 --- a/engine/server/application/PlanetServer/src/shared/PreloadManager.cpp +++ b/engine/server/application/PlanetServer/src/shared/PreloadManager.cpp @@ -119,7 +119,7 @@ void PreloadManager::handlePreloadList() if (PlanetServer::getInstance().getEnablePreload()) { DataTable * data = DataTableManager::getTable(ConfigPlanetServer::getPreloadDataTableName(),true); - FATAL(data==NULL,("Could not find data table %s, needed for preload",ConfigPlanetServer::getPreloadDataTableName())); + FATAL(data==nullptr,("Could not find data table %s, needed for preload",ConfigPlanetServer::getPreloadDataTableName())); int numRows = data->getNumRows(); for (int row=0; row(&source); - WARNING_DEBUG_FATAL(gameServer==0,("Source was NULL or source was not a GameServerConnection.")); + WARNING_DEBUG_FATAL(gameServer==0,("Source was nullptr or source was not a GameServerConnection.")); - if (message.isType("GameConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Handling a game server crash for server %lu\n", gameServer->getProcessId())); - handleCrash(gameServer->getProcessId()); - } - - else if (message.isType("UpdateObjectOnPlanetMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UpdateObjectOnPlanetMessage msg(ri); - - int interestRadius = msg.getInterestRadius(); - - if(msg.getWatched() && interestRadius == 0) - interestRadius = 1; - - if (m_deletedObjects.find(msg.getObjectId())!=m_deletedObjects.end()) + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("GameConnectionClosed") : { - DEBUG_REPORT_LOG(true,("Ignoring update for object %s which has been removed.\n",msg.getObjectId().getValueString().c_str())); + DEBUG_REPORT_LOG(true, ("Handling a game server crash for server %lu\n", gameServer->getProcessId())); + handleCrash(gameServer->getProcessId()); + break; } - else + case constcrc("UpdateObjectOnPlanetMessage") : { - NetworkId container(msg.getTopmostContainer()); - if (container==msg.getObjectId()) // game server sends container == objectId if the object is not contained - container=NetworkId::cms_invalid; + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UpdateObjectOnPlanetMessage msg(ri); - bool processUpdate = true; - if (container != NetworkId::cms_invalid) + int interestRadius = msg.getInterestRadius(); + + if(msg.getWatched() && interestRadius == 0) + interestRadius = 1; + + if (m_deletedObjects.find(msg.getObjectId())!=m_deletedObjects.end()) { - PlanetProxyObject const *const containerObject = findObjectByID(container); - if (containerObject) + DEBUG_REPORT_LOG(true,("Ignoring update for object %s which has been removed.\n",msg.getObjectId().getValueString().c_str())); + } + else + { + NetworkId container(msg.getTopmostContainer()); + if (container==msg.getObjectId()) // game server sends container == objectId if the object is not contained + container=NetworkId::cms_invalid; + + bool processUpdate = true; + if (container != NetworkId::cms_invalid) { - if (containerObject->getAuthoritativeServer() != gameServer->getProcessId()) + PlanetProxyObject const *const containerObject = findObjectByID(container); + if (containerObject) { - // This update message came from a server that is not - // authoritative for the container of this object. This - // can happen when the planet server is in control of - // switching the container's authority but is not in - // charge of changing the container content's authority. - // This happens to the rider of a mount when the mount - // switches authority. - processUpdate = false; + if (containerObject->getAuthoritativeServer() != gameServer->getProcessId()) + { + // This update message came from a server that is not + // authoritative for the container of this object. This + // can happen when the planet server is in control of + // switching the container's authority but is not in + // charge of changing the container content's authority. + // This happens to the rider of a mount when the mount + // switches authority. + processUpdate = false; + } } } - } - if (processUpdate) - { - PlanetProxyObject *theObject=findObjectByID(msg.getObjectId()); - if (!theObject) + if (processUpdate) { - // this is a new object - theObject=new PlanetProxyObject(msg.getObjectId()); - addObject(theObject); + PlanetProxyObject *theObject=findObjectByID(msg.getObjectId()); + if (!theObject) + { + // this is a new object + theObject=new PlanetProxyObject(msg.getObjectId()); + addObject(theObject); + } + + theObject->onReceivedMessageFromServer(gameServer->getProcessId()); + theObject->update(msg.getX(), msg.getY(), msg.getZ(), container, gameServer->getProcessId(), interestRadius, msg.getObjectTypeTag(), msg.getLevel(), msg.getHibernating(), msg.getTemplateCrc(), msg.getAiActivity(), msg.getCreationType()); + + //-- handle updating LocationManager + if (msg.getLocationReservationRadius () > 0.f) + LocationManager::updateObject (msg.getObjectId (), msg.getX (), msg.getZ (), msg.getLocationReservationRadius ()); } - - theObject->onReceivedMessageFromServer(gameServer->getProcessId()); - theObject->update(msg.getX(), msg.getY(), msg.getZ(), container, gameServer->getProcessId(), interestRadius, msg.getObjectTypeTag(), msg.getLevel(), msg.getHibernating(), msg.getTemplateCrc(), msg.getAiActivity(), msg.getCreationType()); - - //-- handle updating LocationManager - if (msg.getLocationReservationRadius () > 0.f) - LocationManager::updateObject (msg.getObjectId (), msg.getX (), msg.getZ (), msg.getLocationReservationRadius ()); } + break; } - } - else if (message.isType("PlanetRemoveObject")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PlanetRemoveObject msg(ri); - handleRemoveObject(msg.getObjectId()); + case constcrc("PlanetRemoveObject") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PlanetRemoveObject msg(ri); + handleRemoveObject(msg.getObjectId()); - //-- handle updating LocationManager - LocationManager::removeObject (msg.getObjectId ()); - } - else if (message.isType("ForceLoadArea")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::pair > > > const msg(ri); + //-- handle updating LocationManager + LocationManager::removeObject (msg.getObjectId ()); + break; + } + case constcrc("ForceLoadArea") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, std::pair > > > const msg(ri); - handleForceLoadArea( - msg.getValue().first, - static_cast(msg.getValue().second.first.first), - static_cast(msg.getValue().second.first.second), - static_cast(msg.getValue().second.second.first), - static_cast(msg.getValue().second.second.second)); - } - else - { - DEBUG_REPORT_LOG(true,("Scene.cpp received an unidentified message.\n")); + handleForceLoadArea( + msg.getValue().first, + static_cast(msg.getValue().second.first.first), + static_cast(msg.getValue().second.first.second), + static_cast(msg.getValue().second.second.first), + static_cast(msg.getValue().second.second.second) + ); + + break; + } + default : + { + DEBUG_REPORT_LOG(true,("Scene.cpp received an unidentified message.\n")); + break; + } } } @@ -216,7 +228,7 @@ Node *Scene::findNodeByPosition(int x, int z) /** * Given coordinates, return a const pointer to the node that encloses - * those coordinates. Will not create new nodes, so it may return NULL. + * those coordinates. Will not create new nodes, so it may return nullptr. */ const Node *Scene::findNodeByPositionConst(int x, int z) const { @@ -245,7 +257,7 @@ Node *Scene::findNodeByRoundedPosition(int x, int z) /** * Given coordinates that are known to be a node boundary, return a const pointer - * to the node. Does not create new nodes, so may return NULL. + * to the node. Does not create new nodes, so may return nullptr. */ const Node *Scene::findNodeByRoundedPositionConst(int x, int z) const { @@ -254,7 +266,7 @@ const Node *Scene::findNodeByRoundedPositionConst(int x, int z) const if (i!=m_nodeMap.end()) return (*i).second; else - return NULL; + return nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/application/PlanetServer/src/win32/FirstPlanetServer.cpp b/engine/server/application/PlanetServer/src/win32/FirstPlanetServer.cpp new file mode 100644 index 00000000..97e05471 --- /dev/null +++ b/engine/server/application/PlanetServer/src/win32/FirstPlanetServer.cpp @@ -0,0 +1,8 @@ +// ====================================================================== +// +// FirstPlanetServer.cpp +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#include "FirstPlanetServer.h" diff --git a/engine/server/application/PlanetServer/src/win32/WinMain.cpp b/engine/server/application/PlanetServer/src/win32/WinMain.cpp new file mode 100644 index 00000000..f153fee1 --- /dev/null +++ b/engine/server/application/PlanetServer/src/win32/WinMain.cpp @@ -0,0 +1,67 @@ +#include "FirstPlanetServer.h" +#include "ConfigPlanetServer.h" +#include "PlanetServer.h" + +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedLog/SetupSharedLog.h" +#include "sharedNetwork/SetupSharedNetwork.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" +#include "sharedUtility/SetupSharedUtility.h" + +#include + +//_____________________________________________________________________ +int main(int argc, char ** argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + SetupSharedFile::install(false); + + SetupSharedNetwork::SetupData networkSetupData; + SetupSharedNetwork::getDefaultServerSetupData(networkSetupData); + SetupSharedNetwork::install(networkSetupData); + + SetupSharedNetworkMessages::install(); + + SetupSharedRandom::install(int(time(NULL))); + + SetupSharedUtility::Data sharedUtilityData; + SetupSharedUtility::setupGameData (sharedUtilityData); + SetupSharedUtility::install (sharedUtilityData); + + //-- setup server + ConfigPlanetServer::install (); + + char tmp[92]; + sprintf(tmp, "PlanetServer:%d", Os::getProcessId()); + SetupSharedLog::install(tmp); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(PlanetServer::run); + + SetupSharedLog::remove(); + SetupSharedFoundation::remove(); + SetupSharedThread::remove(); + + return 0; +} + +//_____________________________________________________________________ diff --git a/engine/server/application/ServerConsole/src/shared/ServerConsoleConnection.cpp b/engine/server/application/ServerConsole/src/shared/ServerConsoleConnection.cpp index 1816a580..68d7686b 100755 --- a/engine/server/application/ServerConsole/src/shared/ServerConsoleConnection.cpp +++ b/engine/server/application/ServerConsole/src/shared/ServerConsoleConnection.cpp @@ -10,6 +10,8 @@ #include "sharedNetwork/NetworkSetupData.h" #include "sharedNetworkMessages/ConsoleChannelMessages.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- ServerConsoleConnection::ServerConsoleConnection(const std::string & address, const unsigned short port) : @@ -44,15 +46,21 @@ void ServerConsoleConnection::onReceive(const Archive::ByteStream & bs) Archive::ReadIterator ri = bs.begin(); GameNetworkMessage m(ri); ri = bs.begin(); + + const uint32 messageType = m.getType(); - if(m.isType("ConGenericMessage")) - { - ConGenericMessage msg(ri); - fprintf(stdout, "%s", msg.getMsg().c_str()); - } - else if(m.isType("RequestDisconnect")) - { - disconnect(); + switch(messageType) { + case constcrc("ConGenericMessage") : + { + ConGenericMessage msg(ri); + fprintf(stdout, "%s", msg.getMsg().c_str()); + break; + } + case constcrc("RequestDisconnect") : + { + disconnect(); + break; + } } } diff --git a/engine/server/application/ServerConsole/src/win32/main.cpp b/engine/server/application/ServerConsole/src/win32/main.cpp new file mode 100644 index 00000000..3de57087 --- /dev/null +++ b/engine/server/application/ServerConsole/src/win32/main.cpp @@ -0,0 +1,59 @@ +// main.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "FirstServerConsole.h" + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetwork/SetupSharedNetwork.h" +#include "sharedNetwork/NetworkHandler.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedThread/SetupSharedThread.h" +#include "ServerConsole.h" +#include "ConfigServerConsole.h" + +//----------------------------------------------------------------------- + +int main(int argc, char ** argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.clockUsesSleep = true; + setupFoundationData.createWindow = false; + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + SetupSharedNetworkMessages::install(); + + SetupSharedNetwork::SetupData networkSetupData; + SetupSharedNetwork::getDefaultClientSetupData(networkSetupData); + SetupSharedNetwork::install(networkSetupData); + NetworkHandler::install(); + + ConfigServerConsole::install(); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(ServerConsole::run); + + NetworkHandler::remove(); + SetupSharedFoundation::remove(); + SetupSharedThread::remove(); + + return 0; +} + +//----------------------------------------------------------------------- + diff --git a/engine/server/application/StationPlayersCollector/src/linux/main.cpp b/engine/server/application/StationPlayersCollector/src/linux/main.cpp index 7112ccde..d2abdabf 100755 --- a/engine/server/application/StationPlayersCollector/src/linux/main.cpp +++ b/engine/server/application/StationPlayersCollector/src/linux/main.cpp @@ -35,7 +35,7 @@ int main(int argc, char ** argv) SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + SetupSharedRandom::install(static_cast(time(nullptr))); //lint !e1924 !e64 // nullptr is a C-Style cast? Os::setProgramName("StationPlayersCollector"); diff --git a/engine/server/application/StationPlayersCollector/src/shared/CentralServerConnection.cpp b/engine/server/application/StationPlayersCollector/src/shared/CentralServerConnection.cpp index ca07f218..372241a3 100755 --- a/engine/server/application/StationPlayersCollector/src/shared/CentralServerConnection.cpp +++ b/engine/server/application/StationPlayersCollector/src/shared/CentralServerConnection.cpp @@ -17,6 +17,8 @@ #include "sharedNetwork/NetworkSetupData.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== namespace CentralServerConnectionNamespace @@ -84,19 +86,16 @@ void CentralServerConnection::onReceive(const Archive::ByteStream & message) GameNetworkMessage msg(ri); ri = message.begin(); - if (msg.isType("SPCharacterProfileMessage")) + if (msg.getType() == constcrc("SPCharacterProfileMessage")) { - DEBUG_REPORT_LOG(true,(" Got SPCharacterProfileMessage:")); - StationPlayersCollector::handleSPCharacterProfileData(msg); - } - else if ( msg.isType("SomeOtherMessage") ) - { - + DEBUG_REPORT_LOG(true,(" Got SPCharacterProfileMessage:")); + StationPlayersCollector::handleSPCharacterProfileData(msg); } + // else if ( msg.isType("SomeOtherMessage") ) {} leaving this here just so i can ask, what the fuck sony? else { - DEBUG_REPORT_LOG(true, ("Got (%s) handing off to ServerConnection::onReceive\n", msg.getCmdName().c_str())); - ServerConnection::onReceive(message); + DEBUG_REPORT_LOG(true, ("Got (%s) handing off to ServerConnection::onReceive\n", msg.getCmdName().c_str())); + ServerConnection::onReceive(message); } } diff --git a/engine/server/application/TaskManager/src/linux/ConsoleInput.cpp b/engine/server/application/TaskManager/src/linux/ConsoleInput.cpp index a0d4580c..756bd237 100755 --- a/engine/server/application/TaskManager/src/linux/ConsoleInput.cpp +++ b/engine/server/application/TaskManager/src/linux/ConsoleInput.cpp @@ -22,7 +22,7 @@ struct SetBufferMode SetBufferMode::SetBufferMode() { - setvbuf(stdin, NULL, _IONBF, 0); + setvbuf(stdin, nullptr, _IONBF, 0); } //----------------------------------------------------------------------- diff --git a/engine/server/application/TaskManager/src/linux/ProcessSpawner.cpp b/engine/server/application/TaskManager/src/linux/ProcessSpawner.cpp index 3996480b..e63ffd6b 100755 --- a/engine/server/application/TaskManager/src/linux/ProcessSpawner.cpp +++ b/engine/server/application/TaskManager/src/linux/ProcessSpawner.cpp @@ -92,7 +92,7 @@ void makeParameters(const std::vector & parameters, std::vector(TaskManager::getNumGameConnections()); return ret; - -#endif } //----------------------------------------------------------------------- diff --git a/engine/server/application/TaskManager/src/linux/main.cpp b/engine/server/application/TaskManager/src/linux/main.cpp index 9eb1a06f..0557283d 100755 --- a/engine/server/application/TaskManager/src/linux/main.cpp +++ b/engine/server/application/TaskManager/src/linux/main.cpp @@ -29,7 +29,7 @@ int main(int argc, char ** argv) SetupSharedCompression::install(); SetupSharedFile::install(false); SetupSharedNetworkMessages::install(); - SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + SetupSharedRandom::install(static_cast(time(nullptr))); //lint !e1924 !e64 // nullptr is a C-Style cast? Os::setProgramName("TaskManager"); //setup the server diff --git a/engine/server/application/TaskManager/src/shared/CentralConnection.cpp b/engine/server/application/TaskManager/src/shared/CentralConnection.cpp index 416b0af0..b8ca9f88 100755 --- a/engine/server/application/TaskManager/src/shared/CentralConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/CentralConnection.cpp @@ -14,6 +14,8 @@ #include "sharedFoundation/Clock.h" #include "sharedMessageDispatch/Transceiver.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- CentralConnection::CentralConnection(TaskConnection * c, const std::string & n) : @@ -84,30 +86,37 @@ void CentralConnection::receive(const Archive::ByteStream & message) { Archive::ReadIterator r(message); GameNetworkMessage m(r); - r = message.begin(); - if(m.isType("TaskSpawnProcess")) - { - TaskSpawnProcess s(r); - IGNORE_RETURN(TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay())); - } - else if(m.isType("PreloadFinishedMessage")) - { - PreloadFinishedMessage m(r); - if (m.getFinished()) - TaskManager::onPreloadFinished(); - } - else if(m.isType("ConGenericMessage")) - { - ConGenericMessage taskConsoleCommand(r); + + const uint32 messageType = m.getType(); - static std::string command = taskConsoleCommand.getMsg(); - while(command.rfind(' ') != command.npos || command.rfind('\n') != command.npos || command.rfind('\r') != command.npos) + switch (messageType) { + case constcrc("TaskSpawnProcess") : { - command = command.substr(0, command.length() - 1); + TaskSpawnProcess s(r); + IGNORE_RETURN(TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay())); + break; } + case constcrc("PreloadFinishedMessage") : + { + PreloadFinishedMessage m(r); + if (m.getFinished()) + TaskManager::onPreloadFinished(); + break; + } + case constcrc("ConGenericMessage") : + { + ConGenericMessage taskConsoleCommand(r); - TaskManager::executeCommand(command); + static std::string command = taskConsoleCommand.getMsg(); + while(command.rfind(' ') != command.npos || command.rfind('\n') != command.npos || command.rfind('\r') != command.npos) + { + command = command.substr(0, command.length() - 1); + } + + TaskManager::executeCommand(command); + break; + } } } diff --git a/engine/server/application/TaskManager/src/shared/DatabaseConnection.cpp b/engine/server/application/TaskManager/src/shared/DatabaseConnection.cpp index 4eee169c..9e2451c4 100755 --- a/engine/server/application/TaskManager/src/shared/DatabaseConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/DatabaseConnection.cpp @@ -10,6 +10,8 @@ #include "serverNetworkMessages/GameTaskManagerMessages.h" #include "serverNetworkMessages/TaskSpawnProcess.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- DatabaseConnection::DatabaseConnection() : @@ -42,17 +44,23 @@ void DatabaseConnection::receive(const Archive::ByteStream & message) { Archive::ReadIterator r(message); GameNetworkMessage m(r); - r = message.begin(); - if(m.isType("TaskSpawnProcess")) - { - TaskSpawnProcess s(r); - IGNORE_RETURN(TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay())); - } - else if(m.isType("ServerIdleMessage")) - { - ServerIdleMessage msg(r); - TaskManager::onDatabaseIdle(msg.getIsIdle()); + + const uint32 messageType = m.getType(); + + switch(messageType) { + case constcrc("TaskSpawnProcess") : + { + TaskSpawnProcess s(r); + IGNORE_RETURN(TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay())); + break; + } + case constcrc("ServerIdleMessage") : + { + ServerIdleMessage msg(r); + TaskManager::onDatabaseIdle(msg.getIsIdle()); + break; + } } } diff --git a/engine/server/application/TaskManager/src/shared/GameConnection.cpp b/engine/server/application/TaskManager/src/shared/GameConnection.cpp index d297a6dd..baa6adfb 100755 --- a/engine/server/application/TaskManager/src/shared/GameConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/GameConnection.cpp @@ -89,7 +89,7 @@ void GameConnection::receive(const Archive::ByteStream & message) char filename[30]; snprintf(filename, sizeof(filename)-1, "/proc/%lu/cmdline", m_pid); - // format of the cmdline file is a NULL separates every + // format of the cmdline file is a nullptr separates every // parameter, so we'll have to replace the NULLs with spaces FILE *inFile = fopen(filename,"rb"); if (inFile) diff --git a/engine/server/application/TaskManager/src/shared/Locator.cpp b/engine/server/application/TaskManager/src/shared/Locator.cpp index 994d2184..2dac97f8 100755 --- a/engine/server/application/TaskManager/src/shared/Locator.cpp +++ b/engine/server/application/TaskManager/src/shared/Locator.cpp @@ -25,11 +25,11 @@ namespace LocatorNamespace float getConfigSetting(const char *section, const char *key, const float defaultValue) { const ConfigFile::Section * sec = ConfigFile::getSection(section); - if (sec == NULL) + if (sec == nullptr) return defaultValue; const ConfigFile::Key * ky = sec->findKey(key); - if (ky == NULL) + if (ky == nullptr) return defaultValue; return ky->getAsFloat(ky->getCount()-1, defaultValue); @@ -364,7 +364,7 @@ void Locator::opened(std::string const &label, ManagerConnection *newConnection) TaskManager::runSpawnRequestQueue(); } else - WARNING_STRICT_FATAL(true, ("Passed null connection to Locator::opened")); + WARNING_STRICT_FATAL(true, ("Passed nullptr connection to Locator::opened")); } // ---------------------------------------------------------------------- diff --git a/engine/server/application/TaskManager/src/shared/ManagerConnection.cpp b/engine/server/application/TaskManager/src/shared/ManagerConnection.cpp index 3720de92..3aa53136 100755 --- a/engine/server/application/TaskManager/src/shared/ManagerConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/ManagerConnection.cpp @@ -24,6 +24,8 @@ #include "TaskConnection.h" #include "TaskManager.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace ManagerConnectionNamespace @@ -94,115 +96,126 @@ void ManagerConnection::onReceive(const Archive::ByteStream & message) { Archive::ReadIterator r(message); GameNetworkMessage m(r); - r = message.begin(); - if (m.isType("SystemTimeCheck")) - { - long const currentTime = static_cast(::time(NULL)); - GenericValueTypeMessage > msg(r); - - if (TaskManager::getNodeLabel() == "node0") + + const uint32 messageType = m.getType(); + + switch(messageType) { + case constcrc("SystemTimeCheck") : { - if ((std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)) > ConfigTaskManager::getMaximumClockDriftToleranceSeconds()) + long const currentTime = static_cast(::time(nullptr)); + GenericValueTypeMessage > msg(r); + + if (TaskManager::getNodeLabel() == "node0") { - LOG("CustomerService", ("system_clock_mismatch:System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld)", (std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, msg.getValue().first.c_str(), getRemoteAddress().c_str(), msg.getValue().second)); - - // tell CentralServer about the system clock mismatch so it can report an alert to SOEMon - GenericValueTypeMessage systemTimeMismatchMessage("SystemTimeMismatchNotification", - FormattedString<1024>().sprintf("%s: %s (%s) is off by %ld seconds", CalendarTime::convertEpochToTimeStringLocal(static_cast(currentTime)).c_str(), msg.getValue().first.c_str(), getRemoteAddress().c_str(), (std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)))); - TaskManager::sendToCentralServer(systemTimeMismatchMessage); - } - } - } - else if (m.isType("TaskConnectionIdMessage")) - { - static long const clockDriftFatalTimePeriod = static_cast(TaskManager::getStartTime()) + ConfigTaskManager::getClockDriftFatalIntervalSeconds(); - long const currentTime = static_cast(::time(NULL)); - TaskConnectionIdMessage t(r); - WARNING_STRICT_FATAL(t.getServerType() != TaskConnectionIdMessage::TaskManager, - ("ManagerConnection received wrong type identifier")); - WARNING_STRICT_FATAL(m_nodeLabel, ("Received new taskconnectionIdMessage with an already named connection")); - - FATAL((ConfigTaskManager::getVerifyClusterName() && (TaskManager::getNodeLabel() == "node0") && (t.getServerType() == TaskConnectionIdMessage::TaskManager) && (t.getClusterName() != std::string(ConfigTaskManager::getClusterName()))), ("Remote TaskManager %s (%s) reported cluster name (%s) that is different from my cluster name (%s)", t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getClusterName().c_str(), ConfigTaskManager::getClusterName())); - - // don't allow cluster to start if the system clock across the boxes are out of sync - bool remoteSystemClockInSync = true; - if (TaskManager::getNodeLabel() == "node0") - { - if ((std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())) > ConfigTaskManager::getMaximumClockDriftToleranceSeconds()) - { - remoteSystemClockInSync = false; - - // don't bring down the cluster if we lost a box and when the box is - // restarted, its system clock is out of sync; just ignore that - // TaskManager, and send it a message to terminate itself - if (currentTime <= clockDriftFatalTimePeriod) + if ((std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)) > ConfigTaskManager::getMaximumClockDriftToleranceSeconds()) { - FATAL(true, ("System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld)", (std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getCurrentEpochTime())); - } - else - { - LOG("CustomerService", ("system_clock_mismatch:System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld). Telling remote TaskManager to terminate.", (std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getCurrentEpochTime())); + LOG("CustomerService", ("system_clock_mismatch:System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld)", (std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, msg.getValue().first.c_str(), getRemoteAddress().c_str(), msg.getValue().second)); - GenericValueTypeMessage > > systemTimeMismatchMessage("SystemTimeMismatchMessage", std::make_pair(TaskManager::getNodeLabel(), std::make_pair(static_cast(currentTime), t.getCurrentEpochTime()))); - send(systemTimeMismatchMessage); - } - } - } - - if (remoteSystemClockInSync) - { - m_nodeLabel = new std::string(t.getCommandLine()); - Locator::opened(*m_nodeLabel, this); - TaskManager::resendUnacknowledgedSpawnRequests(this, *m_nodeLabel); - } - } - else if (m.isType("SystemTimeMismatchMessage")) - { - GenericValueTypeMessage > > msg(r); - FATAL((msg.getValue().first == "node0"), ("System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), self epoch (%ld)", (std::max(msg.getValue().second.first, msg.getValue().second.second) - std::min(msg.getValue().second.first, msg.getValue().second.second)), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), msg.getValue().second.first, msg.getValue().second.second)); - } - else if(m.isType("TaskSpawnProcess")) - { - TaskSpawnProcess s(r); - if (TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay()) == 0) - { - DEBUG_REPORT_LOG(true, ("Failed to spawn %s on this node\n", s.getProcessName().c_str())); - //send fail message back - } - else - { - TaskSpawnProcessAck ack(s.getTransactionId()); - send(ack); - } - } - else if(m.isType("TaskUtilization")) - { - TaskUtilization util(r); - switch(util.getUtilType()) - { - case TaskUtilization::SYSTEM_AVG: - { - if (m_nodeLabel) - { - m_remoteUtilAvg = util.getUtilAmount(); - Locator::updateServerLoad(*m_nodeLabel, m_remoteUtilAvg); + // tell CentralServer about the system clock mismatch so it can report an alert to SOEMon + GenericValueTypeMessage systemTimeMismatchMessage("SystemTimeMismatchNotification", + FormattedString<1024>().sprintf("%s: %s (%s) is off by %ld seconds", CalendarTime::convertEpochToTimeStringLocal(static_cast(currentTime)).c_str(), msg.getValue().first.c_str(), getRemoteAddress().c_str(), (std::max(currentTime, msg.getValue().second) - std::min(currentTime, msg.getValue().second)))); + TaskManager::sendToCentralServer(systemTimeMismatchMessage); } } break; - default: + } + case constcrc("TaskConnectionIdMessage") : + { + static long const clockDriftFatalTimePeriod = static_cast(TaskManager::getStartTime()) + ConfigTaskManager::getClockDriftFatalIntervalSeconds(); + long const currentTime = static_cast(::time(nullptr)); + TaskConnectionIdMessage t(r); + WARNING_STRICT_FATAL(t.getServerType() != TaskConnectionIdMessage::TaskManager, + ("ManagerConnection received wrong type identifier")); + WARNING_STRICT_FATAL(m_nodeLabel, ("Received new taskconnectionIdMessage with an already named connection")); + + FATAL((ConfigTaskManager::getVerifyClusterName() && (TaskManager::getNodeLabel() == "node0") && (t.getServerType() == TaskConnectionIdMessage::TaskManager) && (t.getClusterName() != std::string(ConfigTaskManager::getClusterName()))), ("Remote TaskManager %s (%s) reported cluster name (%s) that is different from my cluster name (%s)", t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getClusterName().c_str(), ConfigTaskManager::getClusterName())); + + // don't allow cluster to start if the system clock across the boxes are out of sync + bool remoteSystemClockInSync = true; + if (TaskManager::getNodeLabel() == "node0") + { + if ((std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())) > ConfigTaskManager::getMaximumClockDriftToleranceSeconds()) + { + remoteSystemClockInSync = false; + + // don't bring down the cluster if we lost a box and when the box is + // restarted, its system clock is out of sync; just ignore that + // TaskManager, and send it a message to terminate itself + if (currentTime <= clockDriftFatalTimePeriod) + { + FATAL(true, ("System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld)", (std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getCurrentEpochTime())); + } + else + { + LOG("CustomerService", ("system_clock_mismatch:System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), remote TaskManager %s (%s) epoch (%ld). Telling remote TaskManager to terminate.", (std::max(currentTime, t.getCurrentEpochTime()) - std::min(currentTime, t.getCurrentEpochTime())), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), currentTime, t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getCurrentEpochTime())); + + GenericValueTypeMessage > > systemTimeMismatchMessage("SystemTimeMismatchMessage", std::make_pair(TaskManager::getNodeLabel(), std::make_pair(static_cast(currentTime), t.getCurrentEpochTime()))); + send(systemTimeMismatchMessage); + } + } + } + + if (remoteSystemClockInSync) + { + m_nodeLabel = new std::string(t.getCommandLine()); + Locator::opened(*m_nodeLabel, this); + TaskManager::resendUnacknowledgedSpawnRequests(this, *m_nodeLabel); + } + break; + } + case constcrc("SystemTimeMismatchMessage") : + { + GenericValueTypeMessage > > msg(r); + FATAL((msg.getValue().first == "node0"), ("System clock mismatch (%d seconds) by more than %d seconds: master TaskManager epoch (%ld), self epoch (%ld)", (std::max(msg.getValue().second.first, msg.getValue().second.second) - std::min(msg.getValue().second.first, msg.getValue().second.second)), ConfigTaskManager::getMaximumClockDriftToleranceSeconds(), msg.getValue().second.first, msg.getValue().second.second)); + break; + } + case constcrc("TaskSpawnProcess") : + { + TaskSpawnProcess s(r); + if (TaskManager::startServer(s.getProcessName(), s.getOptions(), s.getTargetHostAddress(), s.getSpawnDelay()) == 0) + { + DEBUG_REPORT_LOG(true, ("Failed to spawn %s on this node\n", s.getProcessName().c_str())); + //send fail message back + } + else + { + TaskSpawnProcessAck ack(s.getTransactionId()); + send(ack); + } + break; + } + case constcrc("TaskUtilization") : + { + TaskUtilization util(r); + switch(util.getUtilType()) + { + case TaskUtilization::SYSTEM_AVG: + { + if (m_nodeLabel) + { + m_remoteUtilAvg = util.getUtilAmount(); + Locator::updateServerLoad(*m_nodeLabel, m_remoteUtilAvg); + } + } + break; + default: + break; + } + break; + } + case constcrc("TaskProcessDiedMessage") : + { + TaskProcessDiedMessage died(r); + TaskManager::sendToCentralServer(died); + break; + } + case constcrc("TaskSpawnProcessAck") : + { + TaskSpawnProcessAck ack(r); + TaskManager::removePendingSpawnProcessAck(ack.getTransactionId()); break; } - } - else if(m.isType("TaskProcessDiedMessage")) - { - TaskProcessDiedMessage died(r); - TaskManager::sendToCentralServer(died); - } - else if(m.isType("TaskSpawnProcessAck")) - { - TaskSpawnProcessAck ack(r); - TaskManager::removePendingSpawnProcessAck(ack.getTransactionId()); } } diff --git a/engine/server/application/TaskManager/src/shared/MetricsServerConnection.cpp b/engine/server/application/TaskManager/src/shared/MetricsServerConnection.cpp index eeef0926..f5287c2a 100755 --- a/engine/server/application/TaskManager/src/shared/MetricsServerConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/MetricsServerConnection.cpp @@ -77,10 +77,6 @@ void MetricsServerConnection::onProcessKilled(const ProcessKilled & k) void MetricsServerConnection::receive(const Archive::ByteStream & ) { -#if 0 - Archive::ReadIterator r(message); - GameNetworkMessage m(r); -#endif } //----------------------------------------------------------------------- diff --git a/engine/server/application/TaskManager/src/shared/TaskConnection.cpp b/engine/server/application/TaskManager/src/shared/TaskConnection.cpp index 522578f5..b1751e29 100755 --- a/engine/server/application/TaskManager/src/shared/TaskConnection.cpp +++ b/engine/server/application/TaskManager/src/shared/TaskConnection.cpp @@ -20,6 +20,8 @@ #include "serverNetworkMessages/TaskKillProcess.h" #include "sharedNetwork/NetworkSetupData.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- TaskConnection::TaskConnection(const std::string & a, const unsigned short p) : @@ -94,70 +96,79 @@ void TaskConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator r(message); GameNetworkMessage m(r); - if(m.isType("TaskConnectionIdMessage")) - { - r = message.begin(); - TaskConnectionIdMessage t(r); - - FATAL((ConfigTaskManager::getVerifyClusterName() && (TaskManager::getNodeLabel() == "node0") && (t.getServerType() == TaskConnectionIdMessage::TaskManager) && (t.getClusterName() != std::string(ConfigTaskManager::getClusterName()))), ("Remote TaskManager %s (%s) reported cluster name (%s) that is different from my cluster name (%s)", t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getClusterName().c_str(), ConfigTaskManager::getClusterName())); - - Identified i = {this, t.getServerType() }; - identified.emitMessage(i); - - switch(i.id) + + const uint32 messageType = m.getType(); + + switch(messageType) { + case constcrc("TaskConnectionIdMessage") : { - case TaskConnectionIdMessage::Central: - { - REPORT_LOG(true, ("New Central Server connection active\n")); - handler = new CentralConnection(this, t.getCommandLine()); - TaskManager::setCentralConnection(this); - } - break; - case TaskConnectionIdMessage::Game: - { - REPORT_LOG(true, ("New Game Server connection active\n")); - handler = new GameConnection(this); - } - break; - case TaskConnectionIdMessage::Database: - { - REPORT_LOG(true, ("New Database Server connection active\n")); - handler = new DatabaseConnection(); - } - break; - case TaskConnectionIdMessage::Metrics: - { - REPORT_LOG(true, ("New Metrics Server connection active\n")); - handler = new MetricsServerConnection(this, t.getCommandLine()); - } - break; - case TaskConnectionIdMessage::Planet: - { - REPORT_LOG(true, ("New Planet Server connection active\n")); - handler = new PlanetConnection(this); - } - break; + r = message.begin(); + TaskConnectionIdMessage t(r); - default: - WARNING_STRICT_FATAL(true, ("Unknown id (%d) received on task connection", i.id)); + FATAL((ConfigTaskManager::getVerifyClusterName() && (TaskManager::getNodeLabel() == "node0") && (t.getServerType() == TaskConnectionIdMessage::TaskManager) && (t.getClusterName() != std::string(ConfigTaskManager::getClusterName()))), ("Remote TaskManager %s (%s) reported cluster name (%s) that is different from my cluster name (%s)", t.getCommandLine().c_str(), getRemoteAddress().c_str(), t.getClusterName().c_str(), ConfigTaskManager::getClusterName())); + + Identified i = {this, t.getServerType() }; + identified.emitMessage(i); + + switch(i.id) + { + case TaskConnectionIdMessage::Central: + { + REPORT_LOG(true, ("New Central Server connection active\n")); + handler = new CentralConnection(this, t.getCommandLine()); + TaskManager::setCentralConnection(this); + } + break; + case TaskConnectionIdMessage::Game: + { + REPORT_LOG(true, ("New Game Server connection active\n")); + handler = new GameConnection(this); + } + break; + case TaskConnectionIdMessage::Database: + { + REPORT_LOG(true, ("New Database Server connection active\n")); + handler = new DatabaseConnection(); + } + break; + case TaskConnectionIdMessage::Metrics: + { + REPORT_LOG(true, ("New Metrics Server connection active\n")); + handler = new MetricsServerConnection(this, t.getCommandLine()); + } + break; + case TaskConnectionIdMessage::Planet: + { + REPORT_LOG(true, ("New Planet Server connection active\n")); + handler = new PlanetConnection(this); + } + break; + + default: + WARNING_STRICT_FATAL(true, ("Unknown id (%d) received on task connection", i.id)); + break; + } + break; + } + case constcrc("ExcommunicateGameServerMessage") : + { + r = message.begin(); + ExcommunicateGameServerMessage ex(r); + TaskKillProcess k(ex.getHostName(), ex.getProcessId(), true); + TaskManager::killProcess(k); + + // broadcast to other task managers + Locator::sendToAllTaskManagers(k); + + break; + } + case constcrc("TaskKillProcess") : + { + r = message.begin(); + TaskKillProcess k(r); + TaskManager::killProcess(k); break; } - } - else if(m.isType("ExcommunicateGameServerMessage")) - { - r = message.begin(); - ExcommunicateGameServerMessage ex(r); - TaskKillProcess k(ex.getHostName(), ex.getProcessId(), true); - TaskManager::killProcess(k); - - // broadcast to other task managers - Locator::sendToAllTaskManagers(k); - } - else if(m.isType("TaskKillProcess")) - { - r = message.begin(); - TaskKillProcess k(r); - TaskManager::killProcess(k); } msg.message = &message; diff --git a/engine/server/application/TaskManager/src/shared/TaskManager.cpp b/engine/server/application/TaskManager/src/shared/TaskManager.cpp index 192ab1a3..24243de7 100755 --- a/engine/server/application/TaskManager/src/shared/TaskManager.cpp +++ b/engine/server/application/TaskManager/src/shared/TaskManager.cpp @@ -161,7 +161,7 @@ m_processEntries(), m_localServers(), m_remoteServers(), m_nodeLabel(), -m_startTime(::time(NULL)), +m_startTime(::time(nullptr)), m_nodeList(), m_nodeNumber(-1), m_nodeToConnectToList(), @@ -362,7 +362,7 @@ void TaskManager::processRcFile() void TaskManager::setupNodeList() { char buffer[64]; - const char* result = NULL; + const char* result = nullptr; int nodeIndex = 0; bool found = true; @@ -375,7 +375,7 @@ void TaskManager::setupNodeList() { found = false; sprintf(buffer, "node%d", nodeIndex); - result = ConfigFile::getKeyString("TaskManager", buffer, NULL); + result = ConfigFile::getKeyString("TaskManager", buffer, nullptr); if (result) { NodeEntry n(result, buffer, nodeIndex); @@ -831,15 +831,6 @@ void TaskManager::update() lastTime = currentTime; } -#if 0 - instance().m_sysInfoSource->update(); - if (ms_doUpdate) - { - Locator::updateAllLoads(); - ms_doUpdate = false; - } -#endif//0 - // get process status std::set >::iterator i; for(i = instance().m_localServers.begin(); i != instance().m_localServers.end();) @@ -967,8 +958,8 @@ void TaskManager::update() // of slave TaskManager that has disconnected but has not reconnected, // so that an alert can be made in SOEMon so ops can see it and restart // the disconnected TaskManager - static time_t timeSystemTimeCheck = ::time(NULL) + ConfigTaskManager::getSystemTimeCheckIntervalSeconds(); - time_t const timeNow = ::time(NULL); + static time_t timeSystemTimeCheck = ::time(nullptr) + ConfigTaskManager::getSystemTimeCheckIntervalSeconds(); + time_t const timeNow = ::time(nullptr); if (timeSystemTimeCheck <= timeNow) { if (getNodeLabel() != "node0") diff --git a/engine/server/application/TaskManager/src/win32/ConsoleInput.cpp b/engine/server/application/TaskManager/src/win32/ConsoleInput.cpp new file mode 100644 index 00000000..dfd6c431 --- /dev/null +++ b/engine/server/application/TaskManager/src/win32/ConsoleInput.cpp @@ -0,0 +1,22 @@ +// ConsoleInput.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "FirstTaskManager.h" +#include "Console.h" +#include + +//----------------------------------------------------------------------- + +const char Console::getNextChar() +{ + char result = 0; + if(_kbhit()) + result = static_cast(_getche()); + return result; +} + +//----------------------------------------------------------------------- + diff --git a/engine/server/application/TaskManager/src/win32/EnvironmentVariable.cpp b/engine/server/application/TaskManager/src/win32/EnvironmentVariable.cpp new file mode 100644 index 00000000..017b221e --- /dev/null +++ b/engine/server/application/TaskManager/src/win32/EnvironmentVariable.cpp @@ -0,0 +1,33 @@ +#include "FirstTaskManager.h" + +namespace EnvironmentVariable +{ + bool addToEnvironmentVariable(const char* key, const char* value) + { + bool retval = false; + char oldValue[256]; + DWORD tmp = GetEnvironmentVariable(key, oldValue, sizeof(oldValue)); + if (tmp != 0) + { + std::string s(oldValue); + s += ";"; + s += value; + + //Bad things happen if the first character happens to be ; (ie from an empty environment string) + const char* newValue = s.c_str(); + if (newValue[0] == ';') + ++newValue; + + retval = (SetEnvironmentVariable(key, newValue) != 0); + } + else + { + retval = (SetEnvironmentVariable(key, value) != 0); + } + return retval; + } + bool setEnvironmentVariable(const char* key, const char* value) + { + return (SetEnvironmentVariable(key, value) != 0); + } +}; diff --git a/engine/server/application/TaskManager/src/win32/ProcessSpawner.cpp b/engine/server/application/TaskManager/src/win32/ProcessSpawner.cpp new file mode 100644 index 00000000..b544a301 --- /dev/null +++ b/engine/server/application/TaskManager/src/win32/ProcessSpawner.cpp @@ -0,0 +1,153 @@ +#include "FirstTaskManager.h" +#include "sharedFoundation/FirstSharedFoundation.h" +#include "ProcessSpawner.h" +#include +#include +#include "TaskManager.h" + +#include + +uint32 ProcessSpawner::prefix; +std::map procById; + +//----------------------------------------------------------------------- + +bool tokenize (const std::string & str, std::vector & result) +{ + size_t end_pos = 0; + size_t start_pos = 0; + + result.clear (); + + for (;;) + { + if (end_pos >= str.size ()) + break; + + start_pos = str.find_first_not_of (' ', end_pos); + + if (start_pos == str.npos) + break; + + //---------------------------------------------------------------------- + + if (str [start_pos] == '\"') + { + if (++start_pos >= str.size ()) + break; + end_pos = str.find_first_of ('\"', start_pos); + } + else + end_pos = str.find_first_of (' ', start_pos); + + //---------------------------------------------------------------------- + + if (start_pos == end_pos) + break; + + if (end_pos == str.npos) + { + result.push_back (str.substr (start_pos)); + break; + } + else + result.push_back (str.substr (start_pos, end_pos - start_pos)); + + ++start_pos; + } + + return true; +} + +uint32 ProcessSpawner::execute(const std::string & processName, const std::vector & parameters) +{ + STARTUPINFO si; + PROCESS_INFORMATION pi; + char cmd[1024] = {"\0"}; + std::string cmdLine; + + cmdLine = processName.c_str(); + cmdLine += " "; + std::vector::const_iterator i; + for(i = parameters.begin(); i != parameters.end(); ++i) + { + cmdLine += (*i).c_str(); + cmdLine += " "; + } + + _snprintf(cmd, 1024, "%s.exe", processName.c_str()); +// _snprintf(cmd, 1024, "%s", processName.c_str()); + memset(&si, 0, sizeof(si)); + memset(&pi, 0, sizeof(pi)); + + si.cb = sizeof(si); + + const int result = CreateProcess(cmd, const_cast(cmdLine.c_str()), NULL, NULL, false, 0, 0, 0, &si, &pi); + UNREF (result); + +#ifdef _DEBUG + if (!result) + { + DWORD iErr = GetLastError(); + char * errStr = strerror(iErr); + DEBUG_REPORT_LOG(true, ("ProcessSpawner: %s - %s\n", cmd, errStr)); + } +#endif + + procById.insert(std::pair(pi.dwProcessId, pi.hProcess)); + return pi.dwProcessId; +} + +//----------------------------------------------------------------------- + +uint32 ProcessSpawner::execute(const std::string & cmd) +{ + std::vector args; + size_t firstArg = cmd.find_first_of(" "); + std::string processName; + if(firstArg < cmd.size()) + { + std::string a = cmd.substr(firstArg + 1); + tokenize(a, args); + processName = cmd.substr(0, firstArg); + } + else + { + processName = cmd; + } + return execute(processName, args); +} + +//----------------------------------------------------------------------- + +bool ProcessSpawner::isProcessActive(uint32 pid) +{ + bool result = false; + std::map::const_iterator f = procById.find(pid); + if(f != procById.end()) + { + DWORD exitCode; + GetExitCodeProcess((*f).second, &exitCode); + result = (exitCode == STILL_ACTIVE); + } + return result; +} + +//----------------------------------------------------------------------- + +void ProcessSpawner::kill(uint32 pid) +{ + HANDLE p = OpenProcess(PROCESS_TERMINATE, false, (DWORD)pid); + if(p) + TerminateProcess(p, 0); +} + +//----------------------------------------------------------------------- + +void ProcessSpawner::forceCore(const unsigned long pid) +{ + ProcessSpawner::kill(pid); +} + +//----------------------------------------------------------------------- + diff --git a/engine/server/application/TaskManager/src/win32/TaskManagerSysInfo.cpp b/engine/server/application/TaskManager/src/win32/TaskManagerSysInfo.cpp new file mode 100644 index 00000000..feadf4f6 --- /dev/null +++ b/engine/server/application/TaskManager/src/win32/TaskManagerSysInfo.cpp @@ -0,0 +1,147 @@ +// TaskManagerSysInfo.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "FirstTaskManager.h" +#include "TaskManagerSysInfo.h" +#pragma warning ( disable : 4201) +#include +#include +//----------------------------------------------------------------------- + +TaskManagerSysInfo::TaskManagerSysInfo() : +averageScore() +{ + update(); +} + +//----------------------------------------------------------------------- + +TaskManagerSysInfo::TaskManagerSysInfo(const TaskManagerSysInfo &) +{ + +} + +//----------------------------------------------------------------------- + +TaskManagerSysInfo::~TaskManagerSysInfo() +{ +} + +//----------------------------------------------------------------------- + +TaskManagerSysInfo & TaskManagerSysInfo::operator = (const TaskManagerSysInfo & rhs) +{ + if(this != &rhs) + { + // make assignments if right hand side is not this instance + } + return *this; +} + +//----------------------------------------------------------------------- + +const float TaskManagerSysInfo::getScore() const +{ + std::list::const_iterator i; + float avg = 0.0f; + for(i = averageScore.begin(); i != averageScore.end(); ++i) + { + avg += (*i); + } + avg = avg / averageScore.size(); + return avg; +} + +//----------------------------------------------------------------------- + +void TaskManagerSysInfo::update() +{ + static int64 activeTime[2] = {0}; + static int64 currentTime[2] = {0}; + + float currentScore = 0.0f; + activeTime[0] = activeTime[1]; + currentTime[0] = currentTime[1]; + activeTime[1] = 0; + + HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0); + double procAvg = 0.0f; + + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + + currentScore = static_cast(static_cast(memStat.dwMemoryLoad) * 0.005f); + if(hProcessSnap != INVALID_HANDLE_VALUE) + { + PROCESSENTRY32 pe32 = {0}; + pe32.dwSize = sizeof(PROCESSENTRY32); + if (Process32First(hProcessSnap, &pe32)) + { + do + { + HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION, false, pe32.th32ProcessID); + // some stuf with the enumerated processes + FILETIME createTime = {0}; + FILETIME exitTime = {0}; + FILETIME kernelTime = {0}; + FILETIME userTime = {0}; + GetProcessTimes(proc, &createTime, &exitTime, &kernelTime, &userTime); + int64 totals; + + // SDK docs say: + // It is not recommended that you add and subtract values + // from the FILETIME structure to obtain relative times. Instead, you should + // Copy the resulting FILETIME structure to a ULARGE_INTEGER structure. + // Use normal 64-bit arithmetic on the ULARGE_INTEGER value. + int64 c; + int64 e; + int64 k; + int64 u; + memcpy(&c, &createTime, sizeof(int64)); + memcpy(&e, &exitTime, sizeof(int64)); + memcpy(&k, &kernelTime, sizeof(int64)); + memcpy(&u, &userTime, sizeof(int64)); + + totals = k + u; + + FILETIME fst; + SYSTEMTIME st; + GetSystemTime(&st); + SystemTimeToFileTime(&st, &fst); + + int64 runTime; + memcpy(&runTime, &fst, sizeof(int64)); + runTime = runTime - c; + + if(c || e || k || u) + { + activeTime[1] += k + e; + } + + } + while (Process32Next(hProcessSnap, &pe32)); + } + } + + FILETIME fst; + SYSTEMTIME st; + GetSystemTime(&st); + SystemTimeToFileTime(&st, &fst); + memcpy(¤tTime[1], &fst, sizeof(int64)); + int64 timeSlice = currentTime[1] - currentTime[0]; + int64 activeSlice = activeTime[1] - activeTime[0]; + procAvg = static_cast(static_cast(activeSlice) / timeSlice); + //REPORT_LOG(true, ("%f\n", procAvg)); + currentScore = currentScore + static_cast(procAvg * 0.5); + + averageScore.insert(averageScore.end(), currentScore); + + if(averageScore.size() > 100) + averageScore.erase(averageScore.begin()); +} + +//----------------------------------------------------------------------- + diff --git a/engine/server/application/TaskManager/src/win32/WinMain.cpp b/engine/server/application/TaskManager/src/win32/WinMain.cpp new file mode 100644 index 00000000..14a6ab39 --- /dev/null +++ b/engine/server/application/TaskManager/src/win32/WinMain.cpp @@ -0,0 +1,50 @@ +#include "FirstTaskManager.h" + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedRandom/SetupSharedRandom.h" +#include "sharedThread/SetupSharedThread.h" +#include "TaskManager.h" +#include "ConfigTaskManager.h" + +//===================================================================== + +int main(int argc, char **argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = false; + setupFoundationData.clockUsesSleep = true; + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + SetupSharedFile::install(false); + SetupSharedNetworkMessages::install(); + SetupSharedRandom::install(static_cast(time(NULL))); //lint !e1924 !e64 // NULL is a C-Style cast? + + ConfigTaskManager::install(); + + TaskManager::install(); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(TaskManager::run); + + TaskManager::remove(); + SetupSharedFoundation::remove(); + SetupSharedThread::remove(); + + return 0; +} + +//===================================================================== diff --git a/engine/server/application/TransferServer/src/shared/CTSAPIClient.cpp b/engine/server/application/TransferServer/src/shared/CTSAPIClient.cpp index 6d456516..ca5d0845 100755 --- a/engine/server/application/TransferServer/src/shared/CTSAPIClient.cpp +++ b/engine/server/application/TransferServer/src/shared/CTSAPIClient.cpp @@ -147,7 +147,7 @@ void CTSAPIClient::onRequestMove(const unsigned server_track, const char *langua { LOG("CTSAPI", ("Received a transfer request for station ID %d, but a transfer for that id is already in progress", uid)); const unsigned int result = static_cast(CTService::CT_GAMERESULT_SOFTERROR); - IGNORE_RETURN(replyMove(server_track, result, NULL, NULL)); + IGNORE_RETURN(replyMove(server_track, result, nullptr, nullptr)); } } @@ -165,7 +165,7 @@ void CTSAPIClient::onRequestTransferAccount(const unsigned server_track, const u { LOG("CTSAPI", ("Received a transfer request for station ID %d, but a transfer for that id is already in progress", uid)); const unsigned int result = static_cast(CTService::CT_GAMERESULT_SOFTERROR); - IGNORE_RETURN(replyTransferAccount(server_track, result, NULL, NULL)); + IGNORE_RETURN(replyTransferAccount(server_track, result, nullptr, nullptr)); } } @@ -197,12 +197,12 @@ void CTSAPIClient::onRequestServerList(const unsigned server_track, const char * if(! servers.empty()) { const unsigned int result = static_cast(CTService::CT_RESULT_SUCCESS); - IGNORE_RETURN(replyServerList(server_track, result, servers.size(), &servers[0], NULL)); + IGNORE_RETURN(replyServerList(server_track, result, servers.size(), &servers[0], nullptr)); } else { const unsigned int result = static_cast(CTService::CT_RESULT_FAILURE); - IGNORE_RETURN(replyServerList(server_track, result, servers.size(), NULL, NULL)); + IGNORE_RETURN(replyServerList(server_track, result, servers.size(), nullptr, nullptr)); } } @@ -226,12 +226,12 @@ void CTSAPIClient::onRequestDestinationServerList(const unsigned server_track, c if(! servers.empty()) { const unsigned int result = static_cast(CTService::CT_RESULT_SUCCESS); - IGNORE_RETURN(replyDestinationServerList(server_track, result, servers.size(), &servers[0], NULL)); + IGNORE_RETURN(replyDestinationServerList(server_track, result, servers.size(), &servers[0], nullptr)); } else { const unsigned int result = static_cast(CTService::CT_RESULT_FAILURE); - IGNORE_RETURN(replyDestinationServerList(server_track, result, servers.size(), NULL, NULL)); + IGNORE_RETURN(replyDestinationServerList(server_track, result, servers.size(), nullptr, nullptr)); } } @@ -260,7 +260,7 @@ void CTSAPIClient::moveStart(unsigned int stationId, unsigned int track, const C std::map::iterator f = s_completedTransfers.find(track); if(f != s_completedTransfers.end()) { - IGNORE_RETURN(replyMove(track, f->second, NULL, NULL)); + IGNORE_RETURN(replyMove(track, f->second, nullptr, nullptr)); } else { @@ -284,7 +284,7 @@ void CTSAPIClient::lostCentralServerConnection(const CentralServerConnection * c { if(i->second.m_sourceCentralServerConnection == centralServerConnection || i->second.m_destinationCentralServerConnection == centralServerConnection) { - IGNORE_RETURN(replyMove(i->second.m_track, result, NULL, NULL)); + IGNORE_RETURN(replyMove(i->second.m_track, result, nullptr, nullptr)); s_activeTransfers.erase(i++); } else diff --git a/engine/server/application/TransferServer/src/shared/CentralServerConnection.cpp b/engine/server/application/TransferServer/src/shared/CentralServerConnection.cpp index 5fb34c0b..ece4ff3d 100755 --- a/engine/server/application/TransferServer/src/shared/CentralServerConnection.cpp +++ b/engine/server/application/TransferServer/src/shared/CentralServerConnection.cpp @@ -25,6 +25,8 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- namespace CentralServerConnectionNamespace @@ -95,306 +97,329 @@ void CentralServerConnection::onReceive(const Archive::ByteStream & message) Archive::ReadIterator ri = message.begin(); const GameNetworkMessage msg(ri); ri = message.begin(); - if(msg.isType("CentralGalaxyName")) - { - - const GenericValueTypeMessage cgn(ri); - setGalaxyName(cgn.getValue()); - LOG("CustomerService", ("CharacterTransfer: Received CentralGalaxyName for %s", cgn.getValue().c_str())); - } - else if(msg.isType("UploadCharacterMessage")) - { - // receiving character data - const UploadCharacterMessage ucm(ri); - CharacterTransferData data; - data.stationId = ucm.getStationId(); - data.fromGalaxy = m_galaxyName; - data.packedData = ucm.getPackedCharacterData(); - bool result = TransferServer::uploadCharacterTransferData(data, ucm.getIsAdmin()); - if(result) + + const uint32 messageType = msg.getType(); + + switch(messageType) { + case constcrc("CentralGalaxyName") : { - CharacterTransferStatusMessage uploadResult(ucm.getFromGameServerId(), ucm.getFromCharacterId(), "@base_player:upload_success"); - send(uploadResult, true); + const GenericValueTypeMessage cgn(ri); + setGalaxyName(cgn.getValue()); + LOG("CustomerService", ("CharacterTransfer: Received CentralGalaxyName for %s", cgn.getValue().c_str())); + break; } - else + case constcrc("UploadCharacterMessage") : { - CharacterTransferStatusMessage uploadResult(ucm.getFromGameServerId(), ucm.getFromCharacterId(), "@base_player:upload_fail"); - send(uploadResult, true); - } - } - else if(msg.isType("DownloadCharacterMessage")) - { - // retreive packed data from transfer server and - // send it to the requesting central server - const DownloadCharacterMessage dcm(ri); - const CharacterTransferData * data = TransferServer::getCharacterTransferData(dcm.getStationId(), m_galaxyName, dcm.getIsAdmin()); - if(data) - { - const UploadCharacterMessage ucm(data->stationId, data->packedData, dcm.getGameServerId(), dcm.getToCharacterId(), true); - send(ucm, true); - LOG("CustomerService", ("CharacterTransfer: Character data for SUID %d downloaded\n", data->stationId)); - } - else - { - CharacterTransferStatusMessage downloadResult(dcm.getGameServerId(), dcm.getToCharacterId(), "@base_player:download_fail"); - send(downloadResult, true); - } - - } - else if(msg.isType("AuthorizeDownload")) - { - const GenericValueTypeMessage auth(ri); - TransferServer::authorizeDownload(auth.getValue()); - } - else if(msg.isType("UnauthorizeDownload")) - { - const GenericValueTypeMessage auth(ri); - TransferServer::unauthorizeDownload(auth.getValue()); - } - else if(msg.isType("TransferReplyCharacterList")) - { - const TransferReplyCharacterList reply(ri); - - // TESTING! - LOG("CustomerService", ("CharacterTransfer: Received character list for station id %d\n", reply.getStationId())); - const std::vector & avatarList = reply.getAvatarList(); - std::vector::const_iterator i; - LOG("CustomerService", ("CharacterTransfer: Enumerating %d characters", avatarList.size())); - for(i = avatarList.begin() ; i != avatarList.end(); ++i) - { - LOG("CustomerService", ("CharacterTransfer: m_name = \"%s\" m_networkId = %s\n", Unicode::wideToNarrow(i->m_name).c_str(), i->m_networkId.getValueString().c_str())); - } - - // TESTING END - TransferServer::replyCharacterList(reply); - } - else if(msg.isType("TransferReplyMoveValidation")) - { - const TransferReplyMoveValidation reply(ri); - if(reply.getResult() == TransferReplyMoveValidation::TRMVR_can_create_regular_character) - { - // save off the source character's template crc so it can be used in - // subsequent TransferRequestMoveValidation queries, so the LoginServer - // doesn't have to continually query the DB to fetch the same information - // over and over again, because the character's template crc - // (i.e. the character's species) should never, ever change - TransferServer::cacheSourceCharacterTemplateCrc(reply.getSourceStationId(), reply.getSourceGalaxy(), reply.getSourceCharacter(), reply.getSourceCharacterTemplateId()); - - TransferCharacterData requestData(reply.getTransferRequestSource()); - requestData.setTrack(reply.getTrack()); - requestData.setCustomerLocalizedLanguage(reply.getCustomerLocalizedLanguage()); - requestData.setSourceGalaxy(reply.getSourceGalaxy()); - requestData.setDestinationGalaxy(reply.getDestinationGalaxy()); - requestData.setSourceCharacterName(reply.getSourceCharacter()); - requestData.setObjectTemplateCrc(reply.getSourceCharacterTemplateId()); - requestData.setDestinationCharacterName(reply.getDestinationCharacter()); - requestData.setSourceStationId(reply.getSourceStationId()); - requestData.setDestinationStationId(reply.getDestinationStationId()); - const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", requestData); - CentralServerConnection * destinationConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getDestinationGalaxy()); - - LOG("CustomerService", ("CharacterTransfer: Received TransferReplyMoveValidation for %s on %s to %s on %s from CentralServer. Sending TransferRequestNameValidation to destination CentralServer.", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); - - const GenericValueTypeMessage > kick("TransferRequestKickConnectedClients", std::make_pair(requestData.getSourceStationId(), requestData.getDestinationStationId())); - if(destinationConnection) + // receiving character data + const UploadCharacterMessage ucm(ri); + CharacterTransferData data; + data.stationId = ucm.getStationId(); + data.fromGalaxy = m_galaxyName; + data.packedData = ucm.getPackedCharacterData(); + bool result = TransferServer::uploadCharacterTransferData(data, ucm.getIsAdmin()); + if(result) { - destinationConnection->send(requestNameValidation, true); - destinationConnection->send(kick, true); + CharacterTransferStatusMessage uploadResult(ucm.getFromGameServerId(), ucm.getFromCharacterId(), "@base_player:upload_success"); + send(uploadResult, true); } - - CentralServerConnection * sourceConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getSourceGalaxy()); - if(sourceConnection) + else { - sourceConnection->send(kick, true); + CharacterTransferStatusMessage uploadResult(ucm.getFromGameServerId(), ucm.getFromCharacterId(), "@base_player:upload_fail"); + send(uploadResult, true); } + break; } - else + case constcrc("DownloadCharacterMessage") : { - LOG("CustomerService", ("CharacterTransfer: TransferReplyMoveValidation failed for %s on %s to %s on %s from CentralServer because the account cannot create a new character on the destination server", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); - TransferServer::failedToValidateTransfer(reply); - } - } - else if(msg.isType("TransferReplyNameValidation")) - { - const GenericValueTypeMessage > replyNameValidation(ri); - if(!replyNameValidation.getValue().second.getIsMoveRequest()) - { - LOG("CustomerService", ("CharacterTransfer: Received replyNameValidation for move validation request. (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); - TransferServer::replyValidateMove(replyNameValidation.getValue().second); - } - else - { - if(TransferServer::isRename(replyNameValidation.getValue().second)) + // retreive packed data from transfer server and + // send it to the requesting central server + const DownloadCharacterMessage dcm(ri); + const CharacterTransferData * data = TransferServer::getCharacterTransferData(dcm.getStationId(), m_galaxyName, dcm.getIsAdmin()); + if(data) { - LOG("CustomerService", ("CharacterTransfer: Received replyNameValidation for rename request, starting character rename protocol. (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); - const GenericValueTypeMessage renameCharacter("TransferRenameCharacter", replyNameValidation.getValue().second); - CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(replyNameValidation.getValue().second.getSourceGalaxy()); - if(centralServerConnection) + const UploadCharacterMessage ucm(data->stationId, data->packedData, dcm.getGameServerId(), dcm.getToCharacterId(), true); + send(ucm, true); + LOG("CustomerService", ("CharacterTransfer: Character data for SUID %d downloaded\n", data->stationId)); + } + else + { + CharacterTransferStatusMessage downloadResult(dcm.getGameServerId(), dcm.getToCharacterId(), "@base_player:download_fail"); + send(downloadResult, true); + } + break; + + } + case constcrc("AuthorizeDownload") : + { + const GenericValueTypeMessage auth(ri); + TransferServer::authorizeDownload(auth.getValue()); + break; + } + case constcrc("UnauthorizeDownload") : + { + const GenericValueTypeMessage auth(ri); + TransferServer::unauthorizeDownload(auth.getValue()); + break; + } + case constcrc("TransferReplyCharacterList") : + { + const TransferReplyCharacterList reply(ri); + + // TESTING! + LOG("CustomerService", ("CharacterTransfer: Received character list for station id %d\n", reply.getStationId())); + const std::vector & avatarList = reply.getAvatarList(); + std::vector::const_iterator i; + LOG("CustomerService", ("CharacterTransfer: Enumerating %d characters", avatarList.size())); + for(i = avatarList.begin() ; i != avatarList.end(); ++i) + { + LOG("CustomerService", ("CharacterTransfer: m_name = \"%s\" m_networkId = %s\n", Unicode::wideToNarrow(i->m_name).c_str(), i->m_networkId.getValueString().c_str())); + } + + // TESTING END + TransferServer::replyCharacterList(reply); + break; + } + case constcrc("TransferReplyMoveValidation") : + { + const TransferReplyMoveValidation reply(ri); + if(reply.getResult() == TransferReplyMoveValidation::TRMVR_can_create_regular_character) + { + // save off the source character's template crc so it can be used in + // subsequent TransferRequestMoveValidation queries, so the LoginServer + // doesn't have to continually query the DB to fetch the same information + // over and over again, because the character's template crc + // (i.e. the character's species) should never, ever change + TransferServer::cacheSourceCharacterTemplateCrc(reply.getSourceStationId(), reply.getSourceGalaxy(), reply.getSourceCharacter(), reply.getSourceCharacterTemplateId()); + + TransferCharacterData requestData(reply.getTransferRequestSource()); + requestData.setTrack(reply.getTrack()); + requestData.setCustomerLocalizedLanguage(reply.getCustomerLocalizedLanguage()); + requestData.setSourceGalaxy(reply.getSourceGalaxy()); + requestData.setDestinationGalaxy(reply.getDestinationGalaxy()); + requestData.setSourceCharacterName(reply.getSourceCharacter()); + requestData.setObjectTemplateCrc(reply.getSourceCharacterTemplateId()); + requestData.setDestinationCharacterName(reply.getDestinationCharacter()); + requestData.setSourceStationId(reply.getSourceStationId()); + requestData.setDestinationStationId(reply.getDestinationStationId()); + const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", requestData); + CentralServerConnection * destinationConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getDestinationGalaxy()); + + LOG("CustomerService", ("CharacterTransfer: Received TransferReplyMoveValidation for %s on %s to %s on %s from CentralServer. Sending TransferRequestNameValidation to destination CentralServer.", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); + + const GenericValueTypeMessage > kick("TransferRequestKickConnectedClients", std::make_pair(requestData.getSourceStationId(), requestData.getDestinationStationId())); + if(destinationConnection) { - centralServerConnection->send(renameCharacter, true); + destinationConnection->send(requestNameValidation, true); + destinationConnection->send(kick, true); } - else + + CentralServerConnection * sourceConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getSourceGalaxy()); + if(sourceConnection) { - TransferServer::transferCreateCharacterFailed(replyNameValidation.getValue().second); + sourceConnection->send(kick, true); } } else { - DEBUG_FATAL(true, ("Received TransferReplyNameValidation for a move request that is not a rename!")); + LOG("CustomerService", ("CharacterTransfer: TransferReplyMoveValidation failed for %s on %s to %s on %s from CentralServer because the account cannot create a new character on the destination server", reply.getSourceCharacter().c_str(), reply.getSourceGalaxy().c_str(), reply.getDestinationCharacter().c_str(), reply.getDestinationGalaxy().c_str())); + TransferServer::failedToValidateTransfer(reply); } + break; } - } - else if(msg.isType("TransferReplyCharacterDataFromLoginServer")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Got TransferReplyCharacterDataFromLoginServer, characterId=%s\n", reply.getValue().getCharacterId().getValueString().c_str())); - - // is this a transfer or a rename? - if(TransferServer::isRename(reply.getValue())) + case constcrc("TransferReplyNameValidation") : { - LOG("CustomerService", ("CharacterTransfer: Sending TransferRequestNameValidation for character rename request: %s", reply.getValue().toString().c_str())); - // send a name validation request - const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", reply.getValue()); - CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getValue().getSourceGalaxy()); + const GenericValueTypeMessage > replyNameValidation(ri); + if(!replyNameValidation.getValue().second.getIsMoveRequest()) + { + LOG("CustomerService", ("CharacterTransfer: Received replyNameValidation for move validation request. (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); + TransferServer::replyValidateMove(replyNameValidation.getValue().second); + } + else + { + if(TransferServer::isRename(replyNameValidation.getValue().second)) + { + LOG("CustomerService", ("CharacterTransfer: Received replyNameValidation for rename request, starting character rename protocol. (%s) %s", replyNameValidation.getValue().first.c_str(), replyNameValidation.getValue().second.toString().c_str())); + const GenericValueTypeMessage renameCharacter("TransferRenameCharacter", replyNameValidation.getValue().second); + CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(replyNameValidation.getValue().second.getSourceGalaxy()); + if(centralServerConnection) + { + centralServerConnection->send(renameCharacter, true); + } + else + { + TransferServer::transferCreateCharacterFailed(replyNameValidation.getValue().second); + } + } + else + { + DEBUG_FATAL(true, ("Received TransferReplyNameValidation for a move request that is not a rename!")); + } + } + break; + } + case constcrc("TransferReplyCharacterDataFromLoginServer") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Got TransferReplyCharacterDataFromLoginServer, characterId=%s\n", reply.getValue().getCharacterId().getValueString().c_str())); + + // is this a transfer or a rename? + if(TransferServer::isRename(reply.getValue())) + { + LOG("CustomerService", ("CharacterTransfer: Sending TransferRequestNameValidation for character rename request: %s", reply.getValue().toString().c_str())); + // send a name validation request + const GenericValueTypeMessage requestNameValidation("TransferRequestNameValidation", reply.getValue()); + CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(reply.getValue().getSourceGalaxy()); + if(centralServerConnection) + { + centralServerConnection->send(requestNameValidation, true); + } + } + else + { + // this is a transfer + TransferServer::getLoginLocationData(reply.getValue()); + } + break; + } + case constcrc("TransferReplyLoginLocationData") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Got TransferReplyLoginLocationData from CentralServer. TransferCharacterData=%s\n", reply.getValue().toString().c_str())); + + // send character to ConnectionServer for login to a game server + const GenericValueTypeMessage login("TransferLoginCharacterToSourceServer", reply.getValue()); + LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToSourceServer to CentralServer : %s", login.getValue().toString().c_str())); + send(login, true); + break; + } + case constcrc("TransferReceiveDataFromGameServer") : + { + const GenericValueTypeMessage transferReply(ri); + LOG("CustomerService", ("CharacterTransfer: Got TransferReceiveDataFromGameServer: %s", transferReply.getValue().toString().c_str())); + REPORT_LOG(true, ("Got TransferReceiveDataFromGameServer: %s\n", transferReply.getValue().toString().c_str())); + + // find a central server connection for the target cluster + CentralServerConnection * destinationCentralConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(transferReply.getValue().getDestinationGalaxy()); + if(destinationCentralConnection) + { + // send character to ConnectionServer for creation on the destination server + GenericValueTypeMessage login("TransferLoginCharacterToDestinationServer", transferReply.getValue()); + destinationCentralConnection->send(login, true); + LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToDestinationServer to CentralServer (%s) for (%s)", transferReply.getValue().getDestinationGalaxy().c_str(), login.getValue().toString().c_str())); + } + else + { + //@todo: report error to CTS API + LOG("CustomerService", ("CharacterTransfer: Failed to get a CentralServer connection for %s", transferReply.getValue().getDestinationGalaxy().c_str())); + TransferServer::transferCreateCharacterFailed(transferReply.getValue()); + } + break; + } + case constcrc("ApplyTransferDataSuccess") : + { + const GenericValueTypeMessage success(ri); + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from target galaxy. %s", success.getValue().toString().c_str())); + + CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(success.getValue().getSourceGalaxy()); if(centralServerConnection) { - centralServerConnection->send(requestNameValidation, true); + LOG("CustomerService", ("CharacterTransfer: Sending ToggleAvatarLoginStatus request to source central server")); + const ToggleAvatarLoginStatus toggleLoginStatus(success.getValue().getSourceGalaxy(), success.getValue().getSourceStationId(), success.getValue().getCharacterId(), false); + centralServerConnection->send(toggleLoginStatus, true); + TransferServer::replyMoveSuccess(success.getValue()); + LOG("CustomerService", ("CharacterTransfer: TRANSFER SUCCESSFUL for transactionId=%u", success.getValue().getTransactionId())); } + else + { + LOG("CustomerService", ("CharacterTransfer: Transfer failed on target galaxy : %s", success.getValue().toString().c_str())); + TransferServer::transferCreateCharacterFailed(success.getValue()); + } + break; } - else + case constcrc("ApplyTransferDataFail") : { - // this is a transfer - TransferServer::getLoginLocationData(reply.getValue()); - } - } - else if(msg.isType("TransferReplyLoginLocationData")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Got TransferReplyLoginLocationData from CentralServer. TransferCharacterData=%s\n", reply.getValue().toString().c_str())); - - // send character to ConnectionServer for login to a game server - const GenericValueTypeMessage login("TransferLoginCharacterToSourceServer", reply.getValue()); - LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToSourceServer to CentralServer : %s", login.getValue().toString().c_str())); - send(login, true); - } - else if(msg.isType("TransferReceiveDataFromGameServer")) - { - const GenericValueTypeMessage transferReply(ri); - LOG("CustomerService", ("CharacterTransfer: Got TransferReceiveDataFromGameServer: %s", transferReply.getValue().toString().c_str())); - REPORT_LOG(true, ("Got TransferReceiveDataFromGameServer: %s\n", transferReply.getValue().toString().c_str())); - - // find a central server connection for the target cluster - CentralServerConnection * destinationCentralConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(transferReply.getValue().getDestinationGalaxy()); - if(destinationCentralConnection) - { - // send character to ConnectionServer for creation on the destination server - GenericValueTypeMessage login("TransferLoginCharacterToDestinationServer", transferReply.getValue()); - destinationCentralConnection->send(login, true); - LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToDestinationServer to CentralServer (%s) for (%s)", transferReply.getValue().getDestinationGalaxy().c_str(), login.getValue().toString().c_str())); - } - else - { - //@todo: report error to CTS API - LOG("CustomerService", ("CharacterTransfer: Failed to get a CentralServer connection for %s", transferReply.getValue().getDestinationGalaxy().c_str())); - TransferServer::transferCreateCharacterFailed(transferReply.getValue()); - } - - } - else if(msg.isType("ApplyTransferDataSuccess")) - { - const GenericValueTypeMessage success(ri); - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataSuccess from target galaxy. %s", success.getValue().toString().c_str())); - - CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(success.getValue().getSourceGalaxy()); - if(centralServerConnection) - { - LOG("CustomerService", ("CharacterTransfer: Sending ToggleAvatarLoginStatus request to source central server")); - const ToggleAvatarLoginStatus toggleLoginStatus(success.getValue().getSourceGalaxy(), success.getValue().getSourceStationId(), success.getValue().getCharacterId(), false); - centralServerConnection->send(toggleLoginStatus, true); - TransferServer::replyMoveSuccess(success.getValue()); - LOG("CustomerService", ("CharacterTransfer: TRANSFER SUCCESSFUL for transactionId=%u", success.getValue().getTransactionId())); - } - else - { - LOG("CustomerService", ("CharacterTransfer: Transfer failed on target galaxy : %s", success.getValue().toString().c_str())); - TransferServer::transferCreateCharacterFailed(success.getValue()); - } - - } - else if(msg.isType("ApplyTransferDataFail")) - { - const GenericValueTypeMessage fail(ri); - LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from target galaxy. %s", fail.getValue().toString().c_str())); - - CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(fail.getValue().getDestinationGalaxy()); - if(centralServerConnection) - { - LOG("CustomerService", ("CharacterTransfer: failed to apply transfer data. Deleting character on destination server. %s", fail.getValue().toString().c_str())); - const GenericValueTypeMessage deleteCharacter("DeleteFailedTransfer", fail.getValue()); - centralServerConnection->send(deleteCharacter, true); - TransferServer::failedToApplyTransferData(fail.getValue()); - } - } - else if(msg.isType("TransferCreateCharacterFailed")) - { - const GenericValueTypeMessage fail(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferCreateCharacterFailed, sending response to CTS API. %s", fail.getValue().toString().c_str())); - TransferServer::transferCreateCharacterFailed(fail.getValue()); - } - else if(msg.isType("TransferRenameCharacterReply")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReply from Central Server : %s", reply.getValue().toString().c_str())); - if(reply.getValue().getIsValidName()) - { - TransferServer::replyMoveSuccess(reply.getValue()); - } - else - { - TransferServer::transferCreateCharacterFailed(reply.getValue()); - } - } - else if(msg.isType("TransferAccountReplySuccessTransferServer")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountReplySuccessTransferServer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); - TransferServer::replyTransferAccountSuccess(reply.getValue()); - } - else if(msg.isType("TransferAccountFailedToUpdateGameDatabase")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedToUpdateGameDatabase for transfer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); - TransferServer::failedToTransferAccountNoCentralConnection(reply.getValue()); - } - else if(msg.isType("TransferAccountFailedDestinationNotEmpty")) - { - const GenericValueTypeMessage reply(ri); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedDestinationNotEmpty for transfer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); - TransferServer::failedToTransferAccountDestinationNotEmpty(reply.getValue()); - } - else if(msg.isType("ReplyTransferDataFail")) - { - const GenericValueTypeMessage reply(ri); - TransferServer::failedToRetrieveTransferData(reply.getValue()); - } - else if(msg.isType("TransferFailGameServerClosedConnectionWithConnectionServer")) - { - const GenericValueTypeMessage fail(ri); - TransferServer::failedToTransferCharacterGameConnectionClosed(fail.getValue()); - } - else if(msg.isType("TransferFailConnectionServerClosedConnectionWithCentralServer")) - { - const GenericValueTypeMessage fail(ri); - TransferServer::failedToTransferCharacterConnectionServerConnectionClosed(fail.getValue()); - } - else if(msg.isType("ConGenericMessage")) - { - const ConGenericMessage cm(ri); - std::string result; - ConsoleManager::processString(cm.getMsg(), static_cast(cm.getMsgId()), result); - const ConGenericMessage response(result, cm.getMsgId()); - send(response, true); + const GenericValueTypeMessage fail(ri); + LOG("CustomerService", ("CharacterTransfer: Received ApplyTransferDataFail from target galaxy. %s", fail.getValue().toString().c_str())); + CentralServerConnection * centralServerConnection = CentralServerConnection::getCentralServerConnectionForGalaxy(fail.getValue().getDestinationGalaxy()); + if(centralServerConnection) + { + LOG("CustomerService", ("CharacterTransfer: failed to apply transfer data. Deleting character on destination server. %s", fail.getValue().toString().c_str())); + const GenericValueTypeMessage deleteCharacter("DeleteFailedTransfer", fail.getValue()); + centralServerConnection->send(deleteCharacter, true); + TransferServer::failedToApplyTransferData(fail.getValue()); + } + break; + } + case constcrc("TransferCreateCharacterFailed") : + { + const GenericValueTypeMessage fail(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferCreateCharacterFailed, sending response to CTS API. %s", fail.getValue().toString().c_str())); + TransferServer::transferCreateCharacterFailed(fail.getValue()); + break; + } + case constcrc("TransferRenameCharacterReply") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacterReply from Central Server : %s", reply.getValue().toString().c_str())); + if(reply.getValue().getIsValidName()) + { + TransferServer::replyMoveSuccess(reply.getValue()); + } + else + { + TransferServer::transferCreateCharacterFailed(reply.getValue()); + } + break; + } + case constcrc("TransferAccountReplySuccessTransferServer") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountReplySuccessTransferServer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); + TransferServer::replyTransferAccountSuccess(reply.getValue()); + break; + } + case constcrc("TransferAccountFailedToUpdateGameDatabase") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedToUpdateGameDatabase for transfer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); + TransferServer::failedToTransferAccountNoCentralConnection(reply.getValue()); + break; + } + case constcrc("TransferAccountFailedDestinationNotEmpty") : + { + const GenericValueTypeMessage reply(ri); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountFailedDestinationNotEmpty for transfer from station Id %d to station Id %d", reply.getValue().getSourceStationId(), reply.getValue().getDestinationStationId())); + TransferServer::failedToTransferAccountDestinationNotEmpty(reply.getValue()); + break; + } + case constcrc("ReplyTransferDataFail") : + { + const GenericValueTypeMessage reply(ri); + TransferServer::failedToRetrieveTransferData(reply.getValue()); + break; + } + case constcrc("TransferFailGameServerClosedConnectionWithConnectionServer") : + { + const GenericValueTypeMessage fail(ri); + TransferServer::failedToTransferCharacterGameConnectionClosed(fail.getValue()); + break; + } + case constcrc("TransferFailConnectionServerClosedConnectionWithCentralServer") : + { + const GenericValueTypeMessage fail(ri); + TransferServer::failedToTransferCharacterConnectionServerConnectionClosed(fail.getValue()); + break; + } + case constcrc("ConGenericMessage") : + { + const ConGenericMessage cm(ri); + std::string result; + ConsoleManager::processString(cm.getMsg(), static_cast(cm.getMsgId()), result); + const ConGenericMessage response(result, cm.getMsgId()); + send(response, true); + break; + } } } diff --git a/engine/server/application/TransferServer/src/shared/ConsoleManager.cpp b/engine/server/application/TransferServer/src/shared/ConsoleManager.cpp index c0208e0d..1a04dc38 100755 --- a/engine/server/application/TransferServer/src/shared/ConsoleManager.cpp +++ b/engine/server/application/TransferServer/src/shared/ConsoleManager.cpp @@ -14,7 +14,7 @@ namespace ConsoleManagerNamespace { - ConsoleCommandParser * s_consoleCommandParserRoot = NULL; + ConsoleCommandParser * s_consoleCommandParserRoot = nullptr; } using namespace ConsoleManagerNamespace; diff --git a/engine/server/application/TransferServer/src/shared/TransferServer.cpp b/engine/server/application/TransferServer/src/shared/TransferServer.cpp index 07334ab4..6533fd3e 100755 --- a/engine/server/application/TransferServer/src/shared/TransferServer.cpp +++ b/engine/server/application/TransferServer/src/shared/TransferServer.cpp @@ -150,10 +150,10 @@ namespace TransferServerNamespace if(s_apiClient) { const std::string resultString = resultToString(resultCode); - LOG("CustomerService", ("CharacterTransfer: transactionId=%u replyMove(%u, %s, NULL, NULL)", reply.getTransactionId(), reply.getTrack(), resultString.c_str())); + LOG("CustomerService", ("CharacterTransfer: transactionId=%u replyMove(%u, %s, nullptr, nullptr)", reply.getTransactionId(), reply.getTrack(), resultString.c_str())); const unsigned int result = static_cast(resultCode); s_apiClient->moveComplete(reply.getSourceStationId(), reply.getTrack(), result); - IGNORE_RETURN(s_apiClient->replyMove(reply.getTrack(), result, Unicode::narrowToWide(resultString).c_str(), NULL)); + IGNORE_RETURN(s_apiClient->replyMove(reply.getTrack(), result, Unicode::narrowToWide(resultString).c_str(), nullptr)); } } @@ -282,7 +282,7 @@ void TransferServer::requestCharacterList(unsigned int track, unsigned int stati { const unsigned int result = static_cast(CTService::CT_RESULT_FAILURE); - IGNORE_RETURN(s_apiClient->replyCharacterList(track, result, 0, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyCharacterList(track, result, 0, nullptr, nullptr)); s_apiClient->moveComplete(stationId, track, result); } } @@ -410,7 +410,7 @@ void TransferServer::requestTransferAccount(unsigned int track, unsigned int sou if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); - IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, NULL, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, nullptr, nullptr, nullptr)); s_apiClient->moveComplete(sourceStationId, track, result); } @@ -430,7 +430,7 @@ void TransferServer::requestTransferAccount(unsigned int track, unsigned int sou if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_SERVER_IS_DOWN); - IGNORE_RETURN(s_apiClient->replyTransferAccount(track, result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(track, result, nullptr, nullptr)); s_apiClient->moveComplete(sourceStationId, track, result); } @@ -442,12 +442,12 @@ void TransferServer::requestTransferAccount(unsigned int track, unsigned int sou if(destinationStationId == 0 || sourceStationId == 0) { - LOG("CustomerService", ("CharacterTransfer: Account move request made with a null destination station id: or source station id: %lu\n", sourceStationId)); + LOG("CustomerService", ("CharacterTransfer: Account move request made with a nullptr destination station id: or source station id: %lu\n", sourceStationId)); if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); - IGNORE_RETURN(s_apiClient->replyTransferAccount(track, result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(track, result, nullptr, nullptr)); s_apiClient->moveComplete(sourceStationId, track, result); } @@ -488,7 +488,7 @@ void TransferServer::requestMoveValidation(unsigned int track, unsigned int sour if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); - IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, NULL, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, nullptr, nullptr, nullptr)); s_apiClient->moveComplete(sourceStationId, track, result); } } @@ -516,7 +516,7 @@ void TransferServer::requestMoveValidation(unsigned int track, unsigned int sour if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_SERVER_IS_DOWN); - IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, NULL, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyValidateMove(track, result, nullptr, nullptr, nullptr)); s_apiClient->moveComplete(sourceStationId, track, result); } } @@ -651,8 +651,8 @@ void TransferServer::replyCharacterList(const TransferReplyCharacterList & reply result = static_cast(CTService::CT_RESULT_FAILURE); s_apiClient->moveComplete(reply.getStationId(), reply.getTrack(), result); } - LOG("CTSAPI", ("invoking CTServiceAPI::replyCharacterList(%d, %d, %d, characters, NULL)", reply.getTrack(), result, chars.size())); - IGNORE_RETURN(s_apiClient->replyCharacterList(reply.getTrack(), result, reply.getAvatarList().size(), characters, NULL)); + LOG("CTSAPI", ("invoking CTServiceAPI::replyCharacterList(%d, %d, %d, characters, nullptr)", reply.getTrack(), result, chars.size())); + IGNORE_RETURN(s_apiClient->replyCharacterList(reply.getTrack(), result, reply.getAvatarList().size(), characters, nullptr)); } // else use another interface if available } @@ -675,7 +675,7 @@ void TransferServer::replyValidateMove(const TransferCharacterData & reply) { LOG("CustomerService", ("CharacterTransfer: replyValidateMove passed name validation for %s", reply.toString().c_str())); } - IGNORE_RETURN(s_apiClient->replyValidateMove(reply.getTrack(), result, NULL, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyValidateMove(reply.getTrack(), result, nullptr, nullptr, nullptr)); s_apiClient->moveComplete(reply.getSourceStationId(), reply.getTrack(), result); } } @@ -736,7 +736,7 @@ void TransferServer::replyTransferAccountSuccess(const TransferAccountData & rep LOG("CustomerService", ("CharacterTransfer: Could not transfer chat avatars for character %s on cluster %s from %lu to %lu: central connection does not exist in transferserver", i->second.c_str(), i->first.c_str(), reply.getSourceStationId(), reply.getDestinationStationId())); const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); s_apiClient->moveComplete(reply.getSourceStationId(), reply.getTrack(), result); - IGNORE_RETURN(s_apiClient->replyTransferAccount(reply.getTrack(), result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(reply.getTrack(), result, nullptr, nullptr)); } } } @@ -748,7 +748,7 @@ void TransferServer::replyTransferAccountSuccess(const TransferAccountData & rep if(s_apiClient) { const unsigned int result = static_cast(CTService::CT_GAMERESULT_SUCCESS); - IGNORE_RETURN(s_apiClient->replyTransferAccount(reply.getTrack(), result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(reply.getTrack(), result, nullptr, nullptr)); s_apiClient->moveComplete(reply.getSourceStationId(), reply.getTrack(), result); } } @@ -808,7 +808,7 @@ void TransferServer::failedToTransferAccountNoCentralConnection(const TransferAc LOG("CustomerService", ("CharacterTransfer: Transfer failed: Could not connect to central server to update game database. Sending HARD ERROR to CTS API. %s", failed.toString().c_str())); const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); s_apiClient->moveComplete(failed.getSourceStationId(), failed.getTrack(), result); - IGNORE_RETURN(s_apiClient->replyTransferAccount(failed.getTrack(), result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(failed.getTrack(), result, nullptr, nullptr)); } } @@ -821,7 +821,7 @@ void TransferServer::failedToTransferAccountDestinationNotEmpty (const TransferA LOG("CustomerService", ("CharacterTransfer: Transfer failed: Destination stationId has avatars. Sending HARD ERROR to CTS API. %s", failed.toString().c_str())); const unsigned int result = static_cast(CTService::CT_GAMERESULT_HARDERROR); s_apiClient->moveComplete(failed.getSourceStationId(), failed.getTrack(), result); - IGNORE_RETURN(s_apiClient->replyTransferAccount(failed.getTrack(), result, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyTransferAccount(failed.getTrack(), result, nullptr, nullptr)); } } @@ -860,7 +860,7 @@ void TransferServer::failedToValidateTransfer(const TransferReplyMoveValidation { const unsigned int result = ((reply.getResult() == TransferReplyMoveValidation::TRMVR_cannot_create_regular_character) ? static_cast(CTService::CT_GAMERESULT_MAX_CHAR_ON_DEST_SERVER) : static_cast(CTService::CT_GAMERESULT_SERVER_IS_DOWN)); - IGNORE_RETURN(s_apiClient->replyValidateMove(reply.getTrack(), result, NULL, NULL, NULL)); + IGNORE_RETURN(s_apiClient->replyValidateMove(reply.getTrack(), result, nullptr, nullptr, nullptr)); s_apiClient->moveComplete(reply.getSourceStationId(), reply.getTrack(), result); // close pseudoclientconnections diff --git a/engine/server/application/TransferServer/src/win32/WinMain.cpp b/engine/server/application/TransferServer/src/win32/WinMain.cpp new file mode 100755 index 00000000..b1533f7c --- /dev/null +++ b/engine/server/application/TransferServer/src/win32/WinMain.cpp @@ -0,0 +1,60 @@ +// main.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "FirstTransferServer.h" + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "sharedCompression/SetupSharedCompression.h" +#include "sharedDebug/SetupSharedDebug.h" +#include "sharedFile/SetupSharedFile.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/SetupSharedFoundation.h" +#include "sharedNetwork/SetupSharedNetwork.h" +#include "sharedNetwork/NetworkHandler.h" +#include "sharedNetworkMessages/SetupSharedNetworkMessages.h" +#include "sharedThread/SetupSharedThread.h" +#include "TransferServer.h" +#include "ConfigTransferServer.h" + +//----------------------------------------------------------------------- + +int main(int argc, char ** argv) +{ + SetupSharedThread::install(); + SetupSharedDebug::install(1024); + + //-- setup foundation + SetupSharedFoundation::Data setupFoundationData(SetupSharedFoundation::Data::D_game); + + setupFoundationData.argc = argc; + setupFoundationData.argv = argv; + setupFoundationData.createWindow = true; + SetupSharedFoundation::install (setupFoundationData); + + SetupSharedCompression::install(); + SetupSharedFile::install(false); + SetupSharedNetworkMessages::install(); + + SetupSharedNetwork::SetupData networkSetupData; + SetupSharedNetwork::getDefaultServerSetupData(networkSetupData); + SetupSharedNetwork::install(networkSetupData); + NetworkHandler::install(); + + //Os::setProgramName("TransferServer"); + ConfigTransferServer::install(); + + //-- run server + SetupSharedFoundation::callbackWithExceptionHandling(TransferServer::run); + + NetworkHandler::remove(); + SetupSharedFoundation::remove(); + SetupSharedThread::remove(); + + return 0; +} + +//----------------------------------------------------------------------- + diff --git a/engine/server/library/CMakeLists.txt b/engine/server/library/CMakeLists.txt index 84cb7c94..75f23aba 100644 --- a/engine/server/library/CMakeLists.txt +++ b/engine/server/library/CMakeLists.txt @@ -1,4 +1,3 @@ - add_subdirectory(serverBase) add_subdirectory(serverDatabase) add_subdirectory(serverGame) diff --git a/engine/server/library/serverDatabase/src/shared/CentralServerConnection.cpp b/engine/server/library/serverDatabase/src/shared/CentralServerConnection.cpp index ff845939..9873c649 100755 --- a/engine/server/library/serverDatabase/src/shared/CentralServerConnection.cpp +++ b/engine/server/library/serverDatabase/src/shared/CentralServerConnection.cpp @@ -25,6 +25,8 @@ #include "Unicode.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== CentralServerConnection::CentralServerConnection(const std::string & a, const unsigned short p) : @@ -65,31 +67,39 @@ void CentralServerConnection::onReceive(const Archive::ByteStream & message) const GameNetworkMessage msg(ri); ri = message.begin(); - if(msg.isType("TransferRenameCharacter")) - { - const GenericValueTypeMessage request(ri); - const TransferCharacterData & requestData = request.getValue(); - LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacter, starting game database name change. %s", requestData.toString().c_str())); - Persister::getInstance().renameCharacter(0, static_cast(RenameCharacterMessageEx::RCMS_cts_rename), request.getValue().getSourceStationId(), request.getValue().getCharacterId(), Unicode::narrowToWide(request.getValue().getDestinationCharacterName()), Unicode::narrowToWide(request.getValue().getSourceCharacterName()), false, NetworkId::cms_invalid, &requestData); - } - else if(msg.isType("ConGenericMessage")) - { - const ConGenericMessage cm(ri); - std::string result; - ConsoleManager::processString(cm.getMsg(), cm.getMsgId(), result); - const ConGenericMessage response(result, cm.getMsgId()); - send(response, true); - } - else if(msg.isType("TransferAccountRequestCentralDatabase")) - { - const GenericValueTypeMessage request(ri); - const TransferAccountData & requestData = request.getValue(); - LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestCentralDatabase, starting game database change from station ID %d to station ID %d", request.getValue().getSourceStationId(), request.getValue().getDestinationStationId())); - Persister::getInstance().changeStationId(&requestData); - } - else - { - ServerConnection::onReceive(message); + const uint32 messageType = msg.getType(); + + switch(messageType) { + case constcrc("TransferRenameCharacter") : + { + const GenericValueTypeMessage request(ri); + const TransferCharacterData & requestData = request.getValue(); + LOG("CustomerService", ("CharacterTransfer: Received TransferRenameCharacter, starting game database name change. %s", requestData.toString().c_str())); + Persister::getInstance().renameCharacter(0, static_cast(RenameCharacterMessageEx::RCMS_cts_rename), request.getValue().getSourceStationId(), request.getValue().getCharacterId(), Unicode::narrowToWide(request.getValue().getDestinationCharacterName()), Unicode::narrowToWide(request.getValue().getSourceCharacterName()), false, NetworkId::cms_invalid, &requestData); + break; + } + case constcrc("ConGenericMessage") : + { + const ConGenericMessage cm(ri); + std::string result; + ConsoleManager::processString(cm.getMsg(), cm.getMsgId(), result); + const ConGenericMessage response(result, cm.getMsgId()); + send(response, true); + break; + } + case constcrc("TransferAccountRequestCentralDatabase") : + { + const GenericValueTypeMessage request(ri); + const TransferAccountData & requestData = request.getValue(); + LOG("CustomerService", ("CharacterTransfer: Received TransferAccountRequestCentralDatabase, starting game database change from station ID %d to station ID %d", request.getValue().getSourceStationId(), request.getValue().getDestinationStationId())); + Persister::getInstance().changeStationId(&requestData); + break; + } + default : + { + ServerConnection::onReceive(message); + break; + } } } diff --git a/engine/server/library/serverDatabase/src/shared/CentralServerConnection.h b/engine/server/library/serverDatabase/src/shared/CentralServerConnection.h index c273c793..3c8bfd56 100755 --- a/engine/server/library/serverDatabase/src/shared/CentralServerConnection.h +++ b/engine/server/library/serverDatabase/src/shared/CentralServerConnection.h @@ -26,7 +26,7 @@ public: void onReceive (const Archive::ByteStream & message); void receiveMessage (const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message); private: - CentralServerConnection(CentralServerConnection&); + CentralServerConnection(const CentralServerConnection&); CentralServerConnection& operator=(CentralServerConnection&); }; diff --git a/engine/server/library/serverDatabase/src/shared/ConfigServerDatabase.cpp b/engine/server/library/serverDatabase/src/shared/ConfigServerDatabase.cpp index 2760bb31..a6bb553f 100755 --- a/engine/server/library/serverDatabase/src/shared/ConfigServerDatabase.cpp +++ b/engine/server/library/serverDatabase/src/shared/ConfigServerDatabase.cpp @@ -74,7 +74,7 @@ void ConfigServerDatabase::install(void) KEY_BOOL (enableLoadLocks, true); KEY_INT (databaseReconnectTime, 0); KEY_BOOL (logChunkLoading,false); - KEY_BOOL (useMemoryManagerForOCI,true); + KEY_BOOL (useMemoryManagerForOCI,false); KEY_INT (maxCharactersPerLoadRequest,10); KEY_INT (maxChunksPerLoadRequest,200); KEY_FLOAT (maxLoadStartDelay,300.0f); diff --git a/engine/server/library/serverDatabase/src/shared/ConsoleManager.cpp b/engine/server/library/serverDatabase/src/shared/ConsoleManager.cpp index 4e24a67e..70f8342d 100755 --- a/engine/server/library/serverDatabase/src/shared/ConsoleManager.cpp +++ b/engine/server/library/serverDatabase/src/shared/ConsoleManager.cpp @@ -14,7 +14,7 @@ namespace ConsoleManagerNamespace { - ConsoleCommandParser * s_consoleCommandParserRoot = NULL; + ConsoleCommandParser * s_consoleCommandParserRoot = nullptr; } using namespace ConsoleManagerNamespace; diff --git a/engine/server/library/serverDatabase/src/shared/DataLookup.cpp b/engine/server/library/serverDatabase/src/shared/DataLookup.cpp index dd42952a..e03392dc 100755 --- a/engine/server/library/serverDatabase/src/shared/DataLookup.cpp +++ b/engine/server/library/serverDatabase/src/shared/DataLookup.cpp @@ -28,9 +28,11 @@ #include "sharedNetworkMessages/NameErrors.h" #include "unicodeArchive/UnicodeArchive.h" +#include "sharedFoundation/CrcConstexpr.hpp" + //----------------------------------------------------------------------- -DataLookup *DataLookup::ms_theInstance = NULL; +DataLookup *DataLookup::ms_theInstance = nullptr; //----------------------------------------------------------------------- @@ -93,59 +95,71 @@ void DataLookup::receiveMessage(const MessageDispatch::Emitter &source, const Me { UNREF(source); - if (message.isType("VerifyNameRequest")) - { - const GameServerConnection * g = safe_cast(&source); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - VerifyNameRequest * vnr = new VerifyNameRequest(ri); - - LOG("TraceCharacterCreation", ("%d received VerifyNameRequest", vnr->getStationId())); - verifyName(g->getProcessId(), vnr); - } - else if (message.isType("ReleaseNameMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ReleaseNameMessage rnm(ri); + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("VerifyNameRequest") : + { + const GameServerConnection * g = safe_cast(&source); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + VerifyNameRequest * vnr = new VerifyNameRequest(ri); + + LOG("TraceCharacterCreation", ("%d received VerifyNameRequest", vnr->getStationId())); + verifyName(g->getProcessId(), vnr); + break; + } + case constcrc("ReleaseNameMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ReleaseNameMessage rnm(ri); - LOG("TraceCharacterCreation", ("%d received ReleaseNameMessage", rnm.getStationId())); + LOG("TraceCharacterCreation", ("%d received ReleaseNameMessage", rnm.getStationId())); - releaseName(rnm.getStationId(), rnm.getCharacterId()); - } - else if (message.isType("RequestBiographyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestBiographyMessage msg(ri); + releaseName(rnm.getStationId(), rnm.getCharacterId()); + break; + } + case constcrc("RequestBiographyMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestBiographyMessage msg(ri); - const GameServerConnection *conn = dynamic_cast(&source); - if (conn) - getBiography(msg.getOwner(),conn->getProcessId()); - else - DEBUG_WARNING(true,("Got RequestBiographyMessage from something that wasn't a GameServerConnection.\n")); - } - else if (message.isType("BiographyMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - BiographyMessage msg(ri); + const GameServerConnection *conn = dynamic_cast(&source); + if (conn) + getBiography(msg.getOwner(),conn->getProcessId()); + else + DEBUG_WARNING(true,("Got RequestBiographyMessage from something that wasn't a GameServerConnection.\n")); + + break; + } + case constcrc("BiographyMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + BiographyMessage msg(ri); - setBiography(msg.getOwner(),msg.getBio()); - } - else if (message.isType("PurgeStructuresForAccountMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); + setBiography(msg.getOwner(),msg.getBio()); + break; + } + case constcrc("PurgeStructuresForAccountMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); - getStructuresForPurge(msg.getValue(), false); - } - else if (message.isType("WarnStructuresAboutPurgeMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); + getStructuresForPurge(msg.getValue(), false); + break; + } + case constcrc("WarnStructuresAboutPurgeMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); - getStructuresForPurge(msg.getValue(), true); - } - else - { - DEBUG_REPORT_LOG(true,("Unrecognized message recieved by DataLookup.\n")); + getStructuresForPurge(msg.getValue(), true); + break; + } + default : + { + DEBUG_REPORT_LOG(true,("Unrecognized message recieved by DataLookup.\n")); + break; + } } } @@ -455,33 +469,7 @@ const Unicode::String DataLookup::normalizeName(const Unicode::String &name) con } //-------------------------------------------------------------------- -/* -const std::string DataLookup::getNameByStationId(uint32 stationId) const -{ - std::map::const_iterator i=m_reservations.find(stationId); - if (i == m_reservations.end()) - { - WARNING_STRICT_FATAL(true, ("asked for name that wasn't in the reservation list")); - return std::string(); - } - return Unicode::wideToNarrow(i->second.originalName); -} -//-------------------------------------------------------------------- - -const std::string DataLookup::getNormalizedNameByStationId(uint32 stationId) const -{ - std::map::const_iterator i=m_reservations.find(stationId); - if (i == m_reservations.end()) - { - WARNING_STRICT_FATAL(true, ("asked for name that wasn't in the reservation list")); - return std::string(); - } - return Unicode::wideToNarrow(i->second.name); -} - -//-------------------------------------------------------------------- -*/ DataLookup::reservationList * DataLookup::getReservationList(uint32 stationId) { std::map::iterator i = m_reservations.find(stationId); @@ -524,7 +512,7 @@ void DataLookup::deleteReservationList(uint32 stationId) reservationList * rl = rlIter->second; if (!rl) { - WARNING_STRICT_FATAL(true, ("Reservation list for stationID %lu is NULL", stationId)); + WARNING_STRICT_FATAL(true, ("Reservation list for stationID %lu is nullptr", stationId)); return; } reservationList::iterator i; diff --git a/engine/server/library/serverDatabase/src/shared/DatabaseProcess.cpp b/engine/server/library/serverDatabase/src/shared/DatabaseProcess.cpp index 1c0eca40..4df57236 100755 --- a/engine/server/library/serverDatabase/src/shared/DatabaseProcess.cpp +++ b/engine/server/library/serverDatabase/src/shared/DatabaseProcess.cpp @@ -44,9 +44,11 @@ #include "sharedNetworkMessages/FrameEndMessage.h" #include "UnicodeUtils.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ---------------------------------------------------------------------- -DatabaseProcess *DatabaseProcess::ms_theInstance = NULL; +DatabaseProcess *DatabaseProcess::ms_theInstance = nullptr; // ---------------------------------------------------------------------- @@ -418,160 +420,162 @@ void DatabaseProcess::gameServerGoByeBye(uint32 processId) void DatabaseProcess::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { UNREF(source); + + const uint32 messageType = message.getType(); //--- // Connection info messages // - if(message.isType("CentralConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Connection with Central server opened\n")); - DEBUG_FATAL(centralServerConnection != &source,("Got CentralConnectionOpened from something other than our CentralServer connection.\n")); - - //TODO: Make a DatabaseProcessConnect version of this message, perhaps ? - CentralGameServerConnect c("database", "127.0.0.1", 0, gameService->getBindAddress(), gameService->getBindPort()); - centralServerConnection->send(c, true); - - } - else if(message.isType("GameConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Connection with Game server opened\n")); - } - else if(message.isType("TaskConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Connection with Task manager opened\n")); - - // get cluster name - std::string clusterName; - ConfigFile::Section const * const sec = ConfigFile::getSection("TaskManager"); - if (sec) + switch(messageType) { + case constcrc("CentralConnectionOpened") : { - ConfigFile::Key const * const ky = sec->findKey("clusterName"); - if (ky) + DEBUG_REPORT_LOG(true, ("Connection with Central server opened\n")); + DEBUG_FATAL(centralServerConnection != &source,("Got CentralConnectionOpened from something other than our CentralServer connection.\n")); + + //TODO: Make a DatabaseProcessConnect version of this message, perhaps ? + CentralGameServerConnect c("database", "127.0.0.1", 0, gameService->getBindAddress(), gameService->getBindPort()); + centralServerConnection->send(c, true); + break; + } + case constcrc("GameConnectionOpened") : + { + DEBUG_REPORT_LOG(true, ("Connection with Game server opened\n")); + break; + } + case constcrc("TaskConnectionOpened") : + { + DEBUG_REPORT_LOG(true, ("Connection with Task manager opened\n")); + + // get cluster name + std::string clusterName; + ConfigFile::Section const * const sec = ConfigFile::getSection("TaskManager"); + if (sec) { - clusterName = ky->getAsString(ky->getCount()-1, ""); + ConfigFile::Key const * const ky = sec->findKey("clusterName"); + if (ky) + { + clusterName = ky->getAsString(ky->getCount()-1, ""); + } } + + TaskConnectionIdMessage tid(TaskConnectionIdMessage::Database, "", clusterName); + taskService->send(tid, true); + + break; } - - TaskConnectionIdMessage tid(TaskConnectionIdMessage::Database, "", clusterName); - taskService->send(tid, true); - } - else if(message.isType("CommoditiesConnectionOpened")) - { - DEBUG_REPORT_LOG(true, ("Connection with Commodities Server opened\n")); - CommoditiesServerConnection * con = const_cast(static_cast(&source)); - if (commoditiesConnection) - LOG("CommoditiesConnectionOpened",("Connection Opened while another connection already exists.")); - commoditiesConnection = con; - } - else if(message.isType("CentralConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Central server closed its connection, we must die a tragicly heroic death.\n")); - setDone("CentralConnectionClosed : %s", centralServerConnection->getDisconnectReason().c_str()); - centralServerConnection = 0; - WARNING(true,("Database lost connection to central.")); - } - else if(message.isType("GameConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("a Game server closed its connection\n")); - } - else if(message.isType("TaskConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Task manager closed its connection\n")); - taskService=0; - } - else if(message.isType("CommoditiesConnectionClosed")) - { - DEBUG_REPORT_LOG(true, ("Commodities Server closed its connection\n")); - commoditiesService = 0; - commoditiesConnection = 0; - } - // end connection info messages - //--- - - else if(message.isType("CentralGameServerSetProcessId")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CentralGameServerSetProcessId id(ri); - setProcessId(id.getProcessId()); - clusterName = id.getClusterName(); - - Loader::getInstance().checkVersionNumber(ConfigServerDatabase::getExpectedDBVersion(), ConfigServerDatabase::isCorrectDBVersionRequired()); - Loader::getInstance().loadClock(); - } - else if(message.isType("LoadObjectMessage")) - { -#if 0 - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadObjectMessage lom(ri); - connectToGameServer(lom.getAddress().c_str(),lom.getPort(),lom.getProcess()); -#endif - } - else if (message.isType("LoadUniverseMessage")) - { -#if 0 - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadUniverseMessage lom(ri); - connectToGameServer(lom.getAddress().c_str(),lom.getPort(),lom.getProcess()); -#endif - } - - else if(message.isType("GameSetProcessId") || message.isType("GameGameServerConnect")) - { - GameServerConnection * g = const_cast(static_cast(&source)); - gameServerConnections[g->getProcessId()] = g; - - GameServerConnectAck reply; - g->send(reply,true); - } - else if(message.isType("ProfilerOperationMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ProfilerOperationMessage m(ri); - uint32 processId = m.getProcessId(); - if (processId == 0 || processId == getProcessId()) - Profiler::handleOperation(m.getOperation().c_str()); - } - else if(message.isType("ChatServerOnline")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ChatServerOnline cso(ri); - - // establish a connection with the chat server if one doesn't already exist - if (!chatServerConnection) + case constcrc("CommoditiesConnectionOpened") : { - REPORT_LOG(true, ("New chat server connection active\n")); - chatServerConnection = new ChatServerConnection(cso.getAddress(), cso.getPort()); + DEBUG_REPORT_LOG(true, ("Connection with Commodities Server opened\n")); + CommoditiesServerConnection * con = const_cast(static_cast(&source)); + if (commoditiesConnection) + LOG("CommoditiesConnectionOpened",("Connection Opened while another connection already exists.")); + commoditiesConnection = con; + break; } - } - else if(message.isType("ChatServerConnectionClosed")) - { - REPORT_LOG(true, ("DatabaseProcess: Chat Server connection closed\n")); - chatServerConnection = 0; - } - else if(message.isType("FrameEndMessage")) - { - // TODO: handle this game server's frame ending - } - else if (message.isType("CentralPingMessage")) - { - CentralPingMessage reply; - sendToCentralServer(reply,true); - } - else if (message.isType("ExcommunicateGameServerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ExcommunicateGameServerMessage msg(ri); - - LOG("GameGameConnect",("Database Process was told to drop connection to %lu by Central",msg.getServerId())); - - FATAL (msg.getServerId() == getProcessId(),("Crashing because Central told us to (probably indicates we weren't responding to pings)")); - GameServerConnection *conn =getConnectionByProcess(msg.getServerId()); - if (conn) + case constcrc("CentralConnectionClosed") : { - conn->setDisconnectReason("Told to excommunicate by central"); - conn->disconnect(); + DEBUG_REPORT_LOG(true, ("Central server closed its connection, we must die a tragicly heroic death.\n")); + setDone("CentralConnectionClosed : %s", centralServerConnection->getDisconnectReason().c_str()); + centralServerConnection = 0; + WARNING(true,("Database lost connection to central.")); + break; } - } + case constcrc("GameConnectionClosed") : + { + DEBUG_REPORT_LOG(true, ("a Game server closed its connection\n")); + break; + } + case constcrc("TaskConnectionClosed") : + { + DEBUG_REPORT_LOG(true, ("Task manager closed its connection\n")); + taskService = 0; + break; + } + case constcrc("CommoditiesConnectionClosed") : + { + DEBUG_REPORT_LOG(true, ("Commodities Server closed its connection\n")); + commoditiesService = 0; + commoditiesConnection = 0; + break; + } + // end connection info messages + case constcrc("CentralGameServerSetProcessId") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CentralGameServerSetProcessId id(ri); + setProcessId(id.getProcessId()); + clusterName = id.getClusterName(); + + Loader::getInstance().checkVersionNumber(ConfigServerDatabase::getExpectedDBVersion(), ConfigServerDatabase::isCorrectDBVersionRequired()); + Loader::getInstance().loadClock(); + break; + } + case constcrc("GameSetProcessId") : + case constcrc("GameGameServerConnect") : + { + GameServerConnection * g = const_cast(static_cast(&source)); + gameServerConnections[g->getProcessId()] = g; + + GameServerConnectAck reply; + g->send(reply,true); + break; + } + case constcrc("ProfilerOperationMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ProfilerOperationMessage m(ri); + uint32 processId = m.getProcessId(); + if (processId == 0 || processId == getProcessId()) + Profiler::handleOperation(m.getOperation().c_str()); + break; + } + case constcrc("ChatServerOnline") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ChatServerOnline cso(ri); + + // establish a connection with the chat server if one doesn't already exist + if (!chatServerConnection) + { + REPORT_LOG(true, ("New chat server connection active\n")); + chatServerConnection = new ChatServerConnection(cso.getAddress(), cso.getPort()); + } + break; + } + case constcrc("ChatServerConnectionClosed") : + { + REPORT_LOG(true, ("DatabaseProcess: Chat Server connection closed\n")); + chatServerConnection = 0; + break; + } + case constcrc("FrameEndMessage") : + { + // TODO: handle this game server's frame ending + break; + } + case constcrc("CentralPingMessage") : + { + CentralPingMessage reply; + sendToCentralServer(reply,true); + break; + } + case constcrc("ExcommunicateGameServerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ExcommunicateGameServerMessage msg(ri); + + LOG("GameGameConnect",("Database Process was told to drop connection to %lu by Central",msg.getServerId())); + + FATAL (msg.getServerId() == getProcessId(),("Crashing because Central told us to (probably indicates we weren't responding to pings)")); + GameServerConnection *conn =getConnectionByProcess(msg.getServerId()); + if (conn) + { + conn->setDisconnectReason("Told to excommunicate by central"); + conn->disconnect(); + } + break; + } + } } // ---------------------------------------------------------------------- @@ -627,7 +631,7 @@ void DatabaseProcess::sendToCommoditiesServer(GameNetworkMessage const &message, commoditiesConnection->send(message,reliable); } else - DEBUG_REPORT_LOG(true, ("commoditiesConnection is NULL\n")); + DEBUG_REPORT_LOG(true, ("commoditiesConnection is nullptr\n")); } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp b/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp index 67ec7bd2..3463861b 100755 --- a/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp +++ b/engine/server/library/serverDatabase/src/shared/DeleteCharacterCustomPersistStep.cpp @@ -16,8 +16,9 @@ // ====================================================================== DeleteCharacterCustomPersistStep::DeleteCharacterCustomPersistStep(uint32 stationId, const NetworkId &characterId) : - m_characterId(characterId), - m_stationId(stationId) + m_characterId(characterId), + m_stationId(stationId), + m_resultCode(0) { } @@ -33,12 +34,12 @@ bool DeleteCharacterCustomPersistStep::beforePersist(DB::Session *) bool DeleteCharacterCustomPersistStep::afterPersist(DB::Session *session) { DeleteCharacterQuery qry(m_stationId, m_characterId); - - if (! (session->exec(&qry))) + + if (!(session->exec(&qry))) return false; qry.done(); - m_resultCode=qry.result.getValue(); + m_resultCode = qry.result.getValue(); return true; } @@ -48,18 +49,18 @@ void DeleteCharacterCustomPersistStep::onComplete() { if (m_resultCode == 2) { - GenericValueTypeMessage msg("ReleaseCharacterNameByIdMessage",m_characterId); - DatabaseProcess::getInstance().sendToAllGameServers(msg,true); + GenericValueTypeMessage msg("ReleaseCharacterNameByIdMessage", m_characterId); + DatabaseProcess::getInstance().sendToAllGameServers(msg, true); } } // ====================================================================== DeleteCharacterCustomPersistStep::DeleteCharacterQuery::DeleteCharacterQuery(uint32 stationId, const NetworkId &characterId) : - station_id(stationId), - character_id(characterId), - delete_minutes(ConfigServerDatabase::getCharacterImmediateDeleteMinutes()), - result() + station_id(stationId), + character_id(characterId), + delete_minutes(ConfigServerDatabase::getCharacterImmediateDeleteMinutes()), + result() { } @@ -67,7 +68,7 @@ DeleteCharacterCustomPersistStep::DeleteCharacterQuery::DeleteCharacterQuery(uin void DeleteCharacterCustomPersistStep::DeleteCharacterQuery::getSQL(std::string &sql) { - sql="begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "persister.delete_character (:station_id, :character_id, :delete_minutes); end;"; + sql = "begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "persister.delete_character (:station_id, :character_id, :delete_minutes); end;"; } // ---------------------------------------------------------------------- @@ -95,4 +96,4 @@ DB::Query::QueryMode DeleteCharacterCustomPersistStep::DeleteCharacterQuery::get return DB::Query::MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverDatabase/src/shared/GameServerConnection.h b/engine/server/library/serverDatabase/src/shared/GameServerConnection.h index 3cb47a73..3c183f01 100755 --- a/engine/server/library/serverDatabase/src/shared/GameServerConnection.h +++ b/engine/server/library/serverDatabase/src/shared/GameServerConnection.h @@ -31,7 +31,7 @@ private: ChunkCompleteQueueType * const m_chunkCompleteQueue; private: - GameServerConnection(GameServerConnection&); + GameServerConnection(const GameServerConnection&); GameServerConnection& operator=(GameServerConnection&); }; diff --git a/engine/server/library/serverDatabase/src/shared/ImmediateDeleteCustomPersistStep.cpp b/engine/server/library/serverDatabase/src/shared/ImmediateDeleteCustomPersistStep.cpp index e1c3d149..c205c79d 100755 --- a/engine/server/library/serverDatabase/src/shared/ImmediateDeleteCustomPersistStep.cpp +++ b/engine/server/library/serverDatabase/src/shared/ImmediateDeleteCustomPersistStep.cpp @@ -23,7 +23,7 @@ ImmediateDeleteCustomPersistStep::ImmediateDeleteCustomPersistStep() : ImmediateDeleteCustomPersistStep::~ImmediateDeleteCustomPersistStep() { delete m_objects; - m_objects = NULL; + m_objects = nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverDatabase/src/shared/LazyDeleter.cpp b/engine/server/library/serverDatabase/src/shared/LazyDeleter.cpp index 16baa713..ecdc4260 100755 --- a/engine/server/library/serverDatabase/src/shared/LazyDeleter.cpp +++ b/engine/server/library/serverDatabase/src/shared/LazyDeleter.cpp @@ -27,7 +27,7 @@ // ====================================================================== -LazyDeleter * LazyDeleter::ms_instance=NULL; +LazyDeleter * LazyDeleter::ms_instance=nullptr; // ====================================================================== @@ -80,13 +80,13 @@ void LazyDeleter::remove() { NOT_NULL(ms_instance); delete ms_instance; - ms_instance = NULL; + ms_instance = nullptr; } // ---------------------------------------------------------------------- LazyDeleter::LazyDeleter() : - m_workerThread(NULL), // Avoid starting the worker thread until the other member variables are initialized + m_workerThread(nullptr), // Avoid starting the worker thread until the other member variables are initialized m_incomingObjects(new std::vector), m_objectsToDelete(new std::deque), m_objectListLock(new Mutex), @@ -113,11 +113,11 @@ LazyDeleter::~LazyDeleter() delete m_objectsToDelete; delete m_objectListLock; - m_workerThread = NULL; - m_incomingObjects = NULL; - m_objectsToDelete = NULL; - m_objectListLock = NULL; - m_session = NULL; + m_workerThread = nullptr; + m_incomingObjects = nullptr; + m_objectsToDelete = nullptr; + m_objectListLock = nullptr; + m_session = nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverDatabase/src/shared/LazyDeleter.h b/engine/server/library/serverDatabase/src/shared/LazyDeleter.h index e93816ec..7e35e05f 100755 --- a/engine/server/library/serverDatabase/src/shared/LazyDeleter.h +++ b/engine/server/library/serverDatabase/src/shared/LazyDeleter.h @@ -47,7 +47,7 @@ class LazyDeleter ~LazyDeleter(); private: - LazyDeleter(LazyDeleter&); //disable + LazyDeleter(const LazyDeleter&); //disable LazyDeleter &operator=(const LazyDeleter&); //disable private: diff --git a/engine/server/library/serverDatabase/src/shared/Loader.cpp b/engine/server/library/serverDatabase/src/shared/Loader.cpp index fb4b5a6c..ba3d66ac 100755 --- a/engine/server/library/serverDatabase/src/shared/Loader.cpp +++ b/engine/server/library/serverDatabase/src/shared/Loader.cpp @@ -51,11 +51,13 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "unicodeArchive/UnicodeArchive.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include // ====================================================================== -Loader *Loader::ms_instance = NULL; +Loader *Loader::ms_instance = nullptr; // ====================================================================== @@ -72,7 +74,7 @@ void Loader::remove() { NOT_NULL(ms_instance); delete ms_instance; - ms_instance = NULL; + ms_instance = nullptr; } // ---------------------------------------------------------------------- @@ -411,147 +413,175 @@ void Loader::queueOutgoingSnapshot(LoaderSnapshotGroup *outgoingSnapshot) void Loader::receiveMessage(const MessageDispatch::Emitter & source, const MessageDispatch::MessageBase & message) { UNREF(source); - if(message.isType("LoadObjectMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadObjectMessage lom(ri); - DEBUG_FATAL(true,("LoadObjectMessage is deprecated on the database process.\n")); -// requestObject(lom.getId(),lom.getProcess()); - } - else if(message.isType("RequestChunkMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestChunkMessage m(ri); - - std::vector const & chunks = m.getChunks(); - for (std::vector::const_iterator i=chunks.begin(); i!=chunks.end(); ++i) - requestChunk(i->m_process, i->m_nodeX, i->m_nodeZ, m.getSceneId()); - } - else if(message.isType("RequestOIDsMessage")) - { -// DEBUG_REPORT_LOG(true,("Got RequestOIDsMessage.\n")); - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RequestOIDsMessage m(ri); + + const uint32 messageType = message.getType(); + switch (messageType) { + case constcrc("LoadObjectMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoadObjectMessage lom(ri); + DEBUG_FATAL(true,("LoadObjectMessage is deprecated on the database process.\n")); + // requestObject(lom.getId(),lom.getProcess()); + break; + } + case constcrc("RequestChunkMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestChunkMessage m(ri); + + std::vector const & chunks = m.getChunks(); + for (std::vector::const_iterator i=chunks.begin(); i!=chunks.end(); ++i) + requestChunk(i->m_process, i->m_nodeX, i->m_nodeZ, m.getSceneId()); + + break; + } + case constcrc("RequestOIDsMessage") : + { + // DEBUG_REPORT_LOG(true,("Got RequestOIDsMessage.\n")); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RequestOIDsMessage m(ri); - if (m.getLogRequest()) - LOG("ObjectIdManager", ("Received RequestOIDsMessage for %lu more object ids for pid %lu", m.getHowMany(), m.getServerId())); + if (m.getLogRequest()) + LOG("ObjectIdManager", ("Received RequestOIDsMessage for %lu more object ids for pid %lu", m.getHowMany(), m.getServerId())); - getObjectIds(static_cast(m.getServerId()),static_cast(m.getHowMany()), m.getLogRequest()); - } - else if(message.isType("ValidateCharacterForLoginMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ValidateCharacterForLoginMessage msg(ri); - verifyCharacter(msg.getSuid(), msg.getCharacterId(), NULL); - } - else if(message.isType("TransferGetLoginLocationData")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage request(ri); - TransferCharacterData * transferData = new TransferCharacterData(request.getValue()); - verifyCharacter(transferData->getSourceStationId(), transferData->getCharacterId(), transferData); - }//lint !e429 not freed : suppressed because verifyCharacter will own this copy of the data - else if(message.isType("LoadUniverseMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadUniverseMessage m(ri); - DEBUG_REPORT_LOG(true,("Got LoadUniverseMessage\n")); - loadUniverse(m.getProcess()); - } - else if(message.isType("PlanetLoadCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PlanetLoadCharacterMessage m(ri); - DEBUG_REPORT_LOG(true,("Got PlanetLoadCharacterMessage\n")); - requestCharacter(m.getCharacterId(), m.getGameServerId()); - } - else if(message.isType("LoadContainedObjectMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadContainedObjectMessage msg(ri); + getObjectIds(static_cast(m.getServerId()),static_cast(m.getHowMany()), m.getLogRequest()); + break; + } + case constcrc("ValidateCharacterForLoginMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ValidateCharacterForLoginMessage msg(ri); + verifyCharacter(msg.getSuid(), msg.getCharacterId(), nullptr); + break; + } + case constcrc("TransferGetLoginLocationData") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage request(ri); + TransferCharacterData * transferData = new TransferCharacterData(request.getValue()); + verifyCharacter(transferData->getSourceStationId(), transferData->getCharacterId(), transferData); + break; + }//lint !e429 not freed : suppressed because verifyCharacter will own this copy of the data + case constcrc("LoadUniverseMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoadUniverseMessage m(ri); + DEBUG_REPORT_LOG(true,("Got LoadUniverseMessage\n")); + loadUniverse(m.getProcess()); + break; + } + case constcrc("PlanetLoadCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PlanetLoadCharacterMessage m(ri); + DEBUG_REPORT_LOG(true,("Got PlanetLoadCharacterMessage\n")); + requestCharacter(m.getCharacterId(), m.getGameServerId()); + break; + } + case constcrc("LoadContainedObjectMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoadContainedObjectMessage msg(ri); - const GameServerConnection * g = dynamic_cast(&source); - if (g) - loadContainedObject(msg.getContainerId(), msg.getObjectId(), g->getProcessId()); - else - WARNING_STRICT_FATAL(true,("Got LoadContainedObjectMessage for %s, but sender was not a GameServerConnection.\n",msg.getObjectId().getValueString().c_str())); - } - else if(message.isType("LoadContentsMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LoadContentsMessage msg(ri); + const GameServerConnection * g = dynamic_cast(&source); + if (g) + loadContainedObject(msg.getContainerId(), msg.getObjectId(), g->getProcessId()); + else + WARNING_STRICT_FATAL(true,("Got LoadContainedObjectMessage for %s, but sender was not a GameServerConnection.\n",msg.getObjectId().getValueString().c_str())); + + break; + } + case constcrc("LoadContentsMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LoadContentsMessage msg(ri); - const GameServerConnection * g = dynamic_cast(&source); - if (g) - loadContents(msg.getContainerId(), g->getProcessId()); - else - WARNING_STRICT_FATAL(true,("Got LoadContentsMessage for container %s, but sender was not a GameServerConnection.\n",msg.getContainerId().getValueString().c_str())); - } - else if(message.isType("LocateStructureMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - LocateStructureMessage msg(ri); + const GameServerConnection * g = dynamic_cast(&source); + if (g) + loadContents(msg.getContainerId(), g->getProcessId()); + else + WARNING_STRICT_FATAL(true,("Got LoadContentsMessage for container %s, but sender was not a GameServerConnection.\n",msg.getContainerId().getValueString().c_str())); + + break; + } + case constcrc("LocateStructureMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + LocateStructureMessage msg(ri); - const GameServerConnection * g = dynamic_cast(&source); - if (g) - locateStructure(msg.getStructureId(), msg.getWhoRequested()); - else - WARNING_STRICT_FATAL(true,("Got LocateStructureMessage for %s, but sender was not a GameServerConnection.\n",msg.getStructureId().getValueString().c_str())); - } - else if(message.isType("PreloadRequestCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - PreloadRequestCompleteMessage msg(ri); + const GameServerConnection * g = dynamic_cast(&source); + if (g) + locateStructure(msg.getStructureId(), msg.getWhoRequested()); + else + WARNING_STRICT_FATAL(true,("Got LocateStructureMessage for %s, but sender was not a GameServerConnection.\n",msg.getStructureId().getValueString().c_str())); + + break; + } + case constcrc("PreloadRequestCompleteMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + PreloadRequestCompleteMessage msg(ri); - preloadRequestComplete(msg.getGameServerId(), msg.getPreloadAreaId()); - } - else if(message.isType("LoadAckMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - const GameServerConnection * g = dynamic_cast(&source); - if (g) - handleLoadAck(g->getProcessId(), msg.getValue()); - else - WARNING_STRICT_FATAL(true,("Got LoadAckMessage, but sender was not a GameServerConnection.")); - } - else if( message.isType("CSGetCharactersRequestMessage") ) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CSGetCharactersRequestMessage const msg( ri ); - handleCSGetCharacters( msg ); - } - else if( message.isType("CSGetDeletedItemsRequestMessage") ) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CSGetDeletedItemsRequestMessage const msg( ri ); - handleCSGetDeletedItems( msg ); - - } - else if( message.isType("DBCSRequestMessage" ) ) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - DBCSRequestMessage const msg( ri ); - handleCSRequest( msg ); + preloadRequestComplete(msg.getGameServerId(), msg.getPreloadAreaId()); + + break; + } + case constcrc("LoadAckMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + const GameServerConnection * g = dynamic_cast(&source); + if (g) + handleLoadAck(g->getProcessId(), msg.getValue()); + else + WARNING_STRICT_FATAL(true,("Got LoadAckMessage, but sender was not a GameServerConnection.")); + + break; + } + case constcrc("CSGetCharactersRequestMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CSGetCharactersRequestMessage const msg( ri ); + handleCSGetCharacters( msg ); + break; + } + case constcrc("CSGetDeletedItemsRequestMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CSGetDeletedItemsRequestMessage const msg( ri ); + handleCSGetDeletedItems( msg ); + break; + } + case constcrc("DBCSRequestMessage" ) : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + DBCSRequestMessage const msg( ri ); + handleCSRequest( msg ); + break; + } } } void Loader::handleCSRequest( const DBCSRequestMessage & msg ) { DEBUG_REPORT_LOG( true, ( "Message:%s\n", msg.getCommand().c_str() ) ); - if( msg.getCommand() == "get_characters" ) + + std::string cmd = msg.getCommand(); + + // TODO : maybe constexpr this one sometime + if(cmd == "get_characters" ) { handleCSGetCharacters( msg ); } - else if( msg.getCommand() == "get_deleted_items" ) + else if(cmd == "get_deleted_items" ) { handleCSGetDeletedItems( msg ); } - else if( msg.getCommand() == "list_structures" ) + else if(cmd == "list_structures" ) { handleCSGetStructures( msg ); } - else if( msg.getCommand() == "get_player_id" ) + else if(cmd == "get_player_id" ) { handleCSGetPlayerId( msg ); } @@ -647,7 +677,7 @@ void Loader::checkVersionNumber(int expectedVersion, bool fatalOnMismatch) void Loader::requestChunk(uint32 processId,int nodeX, int nodeZ, const std::string &sceneId) { ObjectLocator * const regularLocator=new ChunkLocator(nodeX, nodeZ, sceneId, processId, true); - ObjectLocator * goldLocator=NULL; + ObjectLocator * goldLocator=nullptr; if (ConfigServerDatabase::getEnableGoldDatabase()) goldLocator = new ChunkLocator(nodeX, nodeZ, sceneId, processId, false); addLocatorsForServer(processId, regularLocator, goldLocator); @@ -671,7 +701,7 @@ void Loader::requestCharacter(const NetworkId &characterId, uint32 gameServerId) i=m_multipleLoginLock.find(characterId); if (i==m_multipleLoginLock.end()) { - addLocatorsForServer(gameServerId, new CharacterLocator(characterId), NULL); + addLocatorsForServer(gameServerId, new CharacterLocator(characterId), nullptr); DEBUG_REPORT_LOG(true,("Adding multipleLoginLock for %s\n",characterId.getValueString().c_str())); m_multipleLoginLock[characterId] = gameServerId; @@ -684,7 +714,7 @@ void Loader::requestCharacter(const NetworkId &characterId, uint32 gameServerId) } } else - addLocatorsForServer(gameServerId, new CharacterLocator(characterId), NULL); + addLocatorsForServer(gameServerId, new CharacterLocator(characterId), nullptr); } // ---------------------------------------------------------------------- @@ -692,7 +722,7 @@ void Loader::requestCharacter(const NetworkId &characterId, uint32 gameServerId) void Loader::loadContainedObject(const NetworkId &containerId, const NetworkId &objectId, uint32 gameServerId) { LOG("AuctionRetrieval", ("Loader::received loadContainedObject for loading object %s for retrieval", objectId.getValueString().c_str())); - addLocatorsForServer(gameServerId, new ContainedObjectLocator(containerId,objectId), NULL); + addLocatorsForServer(gameServerId, new ContainedObjectLocator(containerId,objectId), nullptr); } @@ -700,7 +730,7 @@ void Loader::loadContainedObject(const NetworkId &containerId, const NetworkId & void Loader::loadContents(const NetworkId &containerId, uint32 gameServerId) { - addLocatorsForServer(gameServerId, new ContentsLocator(containerId), NULL); + addLocatorsForServer(gameServerId, new ContentsLocator(containerId), nullptr); } // ---------------------------------------------------------------------- @@ -820,7 +850,7 @@ void Loader::removeLoadLock(const NetworkId &characterId) if (i->second!=0) { DEBUG_REPORT_LOG(true,("Now handling delayed login request for character %s\n",characterId.getValueString().c_str())); - addLocatorsForServer(i->second, new CharacterLocator(characterId), NULL); + addLocatorsForServer(i->second, new CharacterLocator(characterId), nullptr); } m_loadLock.erase(i); diff --git a/engine/server/library/serverDatabase/src/shared/MessageToManager.cpp b/engine/server/library/serverDatabase/src/shared/MessageToManager.cpp index 6773ccca..d47dc773 100755 --- a/engine/server/library/serverDatabase/src/shared/MessageToManager.cpp +++ b/engine/server/library/serverDatabase/src/shared/MessageToManager.cpp @@ -16,7 +16,7 @@ // ====================================================================== -MessageToManager *MessageToManager::ms_instance=NULL; +MessageToManager *MessageToManager::ms_instance=nullptr; // ====================================================================== @@ -34,7 +34,7 @@ void MessageToManager::remove() { NOT_NULL(ms_instance); delete ms_instance; - ms_instance = NULL; + ms_instance = nullptr; } // ---------------------------------------------------------------------- @@ -51,7 +51,7 @@ MessageToManager::~MessageToManager() for (MessagesByObjectType::iterator i=m_messagesByObject.begin(); i!=m_messagesByObject.end(); ++i) { delete i->second; - i->second=NULL; + i->second=nullptr; } } @@ -71,7 +71,7 @@ void MessageToManager::handleMessageTo(const MessageToPayload &data) { DEBUG_WARNING(true,("Received message %s twice.",data.getMessageId().getValueString().c_str())); delete i->second; - i->second = NULL; + i->second = nullptr; } m_messagesByObject[theKey]=new MessageToPayload(data); @@ -127,7 +127,7 @@ void MessageToManager::removeMessage(const MessageToId &messageId) if (j!=m_messagesByObject.end()) { delete j->second; - j->second=NULL; + j->second=nullptr; m_messagesByObject.erase(j); } m_messageToObjectMap.erase(i); diff --git a/engine/server/library/serverDatabase/src/shared/Persister.cpp b/engine/server/library/serverDatabase/src/shared/Persister.cpp index 89c299ff..19270519 100755 --- a/engine/server/library/serverDatabase/src/shared/Persister.cpp +++ b/engine/server/library/serverDatabase/src/shared/Persister.cpp @@ -65,12 +65,14 @@ #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "sharedNetworkMessages/ObjectChannelMessages.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include #include // ====================================================================== -Persister *Persister::ms_instance=NULL; +Persister *Persister::ms_instance=nullptr; // ====================================================================== @@ -88,7 +90,7 @@ void Persister::remove() { NOT_NULL(ms_instance); delete ms_instance; - ms_instance = NULL; + ms_instance = nullptr; } //----------------------------------------------------------------------- @@ -108,9 +110,9 @@ Persister::Persister() : m_charactersToDeleteThisSaveCycle(new CharactersToDeleteType), m_charactersToDeleteNextSaveCycle(new CharactersToDeleteType), m_timeSinceLastSave(0), - m_messageSnapshot(NULL), - m_commoditiesSnapshot(NULL), - m_arbitraryGameDataSnapshot(NULL), + m_messageSnapshot(nullptr), + m_commoditiesSnapshot(nullptr), + m_arbitraryGameDataSnapshot(nullptr), m_saveStartTime(0), m_totalSaveTime(0), m_maxSaveTime(0), @@ -181,15 +183,15 @@ Persister::~Persister() m_currentSnapshots.clear(); m_newObjectSnapshots.clear(); m_objectSnapshotMap.clear(); - m_messageSnapshot = NULL; - m_commoditiesSnapshot = NULL; - m_arbitraryGameDataSnapshot = NULL; + m_messageSnapshot = nullptr; + m_commoditiesSnapshot = nullptr; + m_arbitraryGameDataSnapshot = nullptr; delete m_charactersToDeleteThisSaveCycle; - m_charactersToDeleteThisSaveCycle = NULL; + m_charactersToDeleteThisSaveCycle = nullptr; delete m_charactersToDeleteNextSaveCycle; - m_charactersToDeleteNextSaveCycle = NULL; + m_charactersToDeleteNextSaveCycle = nullptr; } // ---------------------------------------------------------------------- @@ -283,7 +285,7 @@ void Persister::onFrameBarrierReached() /** * Moves the current & new object snapshots onto the queue to be saved. * - * Does nothing if these snapshots are null. + * Does nothing if these snapshots are nullptr. */ void Persister::startSave(void) @@ -351,9 +353,9 @@ void Persister::startSave(void) m_currentSnapshots.clear(); m_newObjectSnapshots.clear(); m_objectSnapshotMap.clear(); - m_messageSnapshot = NULL; - m_commoditiesSnapshot = NULL; - m_arbitraryGameDataSnapshot = NULL; + m_messageSnapshot = nullptr; + m_commoditiesSnapshot = nullptr; + m_arbitraryGameDataSnapshot = nullptr; // prepare the list of characters to delete during the next save cycle if (m_charactersToDeleteNextSaveCycle && m_charactersToDeleteThisSaveCycle) @@ -515,7 +517,7 @@ void Persister::newObject(uint32 serverId, const NetworkId &objectId, int templa return; } - Snapshot *snap=NULL; + Snapshot *snap=nullptr; PendingCharactersType::iterator chardata=m_pendingCharacters.find(objectId); if (chardata!=m_pendingCharacters.end()) @@ -543,7 +545,7 @@ void Persister::newObject(uint32 serverId, const NetworkId &objectId, int templa else { // Add the object to the appropriate snapshot - snap=NULL; + snap=nullptr; { ObjectSnapshotMap::const_iterator j=m_objectSnapshotMap.find(container); if (j!=m_objectSnapshotMap.end() && j->second->getMode() == DB::ModeQuery::mode_INSERT) @@ -650,243 +652,282 @@ void Persister::receiveMessage(const MessageDispatch::Emitter & source, const Me if (gameConnection) sourceGameServer = gameConnection->getProcessId(); - if(message.isType("FlagObjectForDeleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - FlagObjectForDeleteMessage m(ri); - handleDeleteMessage(sourceGameServer, m.getId(),m.getReason(),m.getImmediate(),m.getDemandLoadedContainer(),m.getCascadeReason()); - } - else if(message.isType("CreateObjectByCrcMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - CreateObjectByCrcMessage t(ri); -// DEBUG_REPORT_LOG(true,("Got CreateObjectByCrcMessage for %s\n", t.getId().getValueString().c_str())); - newObject(sourceGameServer, t.getId(), t.getCrc(), t.getObjectType(), t.getContainer()); - } - else if(message.isType("EndBaselinesMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - EndBaselinesMessage t(ri); - endBaselines(t.getId(),sourceGameServer); - } - else if(message.isType("DeltasMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - DeltasMessage msg(ri); - - handleDeltasMessage(sourceGameServer,msg); - } - else if(message.isType("BaselinesMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - BaselinesMessage msg(ri); - - handleBaselinesMessage(sourceGameServer,msg); - } - else if(message.isType("UpdateObjectPositionMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UpdateObjectPositionMessage msg(ri); - - getSnapshotForObject(msg.getNetworkId(), sourceGameServer).handleUpdateObjectPosition(msg); - } - else if(message.isType("AddCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AddCharacterMessage ocm(ri); - DEBUG_REPORT_LOG(true, ("Got AddCharacterMessage for object %s.\n",ocm.getObjectId().getValueString().c_str())); - - addCharacter(ocm.getAccountNumber(), ocm.getObjectId(), ocm.getProcess(), ocm.getName(), ocm.getSpecial()); - } - else if (message.isType("UnloadObjectMessage")) - { - // TODO: keep track of when it's done saving so we know when we can reload it - } - else if (message.isType("MessageToMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - MessageToMessage m(ri); - - handleMessageTo (sourceGameServer, m.getData()); - } - else if (message.isType("MessageToAckMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - MessageToAckMessage m(ri); - - handleMessageToAck (sourceGameServer, m.getMessageId()); - } - else if (message.isType("ServerDeleteCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - ServerDeleteCharacterMessage m(ri); - - deleteCharacter(m.getStationId(), m.getCharacterId()); - } - else if (message.isType("RenameCharacterMessageEx")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - RenameCharacterMessageEx msg(ri); - - renameCharacter(sourceGameServer, static_cast(msg.getRenameCharacterMessageSource()), msg.getStationId(), msg.getCharacterId(), msg.getNewName(), msg.getOldName(), msg.getLastNameChangeOnly(), msg.getRequestedBy(), NULL); - } - else if (message.isType("UnloadedPlayerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - UnloadedPlayerMessage msg(ri); - - unloadCharacter(msg.getPlayerId(),sourceGameServer); - } - else if (message.isType("MoveToPlayer")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - moveToPlayer(sourceGameServer, msg.getValue().first, msg.getValue().second, -1, false, false); - } - else if (message.isType("MoveToPlayerBankMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - moveToPlayer(sourceGameServer, msg.getValue().first, msg.getValue().second, -1, true, false); - } - else if (message.isType("MoveToPlayerDatapadMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, int> > msg(ri); - - moveToPlayer(sourceGameServer, msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, false, true); - } - else if (message.isType("FixLoadWith")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, int> > msg(ri); - - fixLoadWith(sourceGameServer, msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second); - } - else if (message.isType("ClusterShutdownMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - - m_clusterShuttingDown = msg.getValue(); - } - else if (message.isType("StartSaveMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - - userRequestedSave(sourceGameServer, msg.getValue()); - } - else if (message.isType("RestoreHouseMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - restoreHouse(msg.getValue().first, msg.getValue().second); - } - else if (message.isType("RestoreCharacterMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - restoreCharacter(msg.getValue().first, msg.getValue().second); - } - else if (message.isType("UndeleteItemMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage > msg(ri); - - LOG("CustomerService", ("undeleteItem %s request from %s", msg.getValue().first.getValueString().c_str(), msg.getValue().second.c_str())); - undeleteItem(msg.getValue().first, msg.getValue().second); - } - else if (message.isType("MoveToPlayerMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::string> > msg(ri); - - LOG("CustomerService", ("moveToPlayer %s, %s request from %s", msg.getValue().first.first.getValueString().c_str(), msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); - moveToPlayer(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second); - } - else if (message.isType("CentralRequestSave")) - { - centralRequestedSave(); - } - else if (message.isType("PlanetRequestSave")) - { - planetRequestedSave(); - } - else if (message.isType("AddResourceTypeMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - AddResourceTypeMessage msg(ri); - handleAddResourceTypeMessage(sourceGameServer, msg); - } - else if (message.isType("BountyHunterTargetMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - BountyHunterTargetMessage msg(ri); - getSnapshotForServer(sourceGameServer).handleBountyHunterTargetMessage(msg); - } - else if ( (message.isType("CMCreateAuctionMessage")) || - (message.isType("CMCreateAuctionBidMessage")) || - (message.isType("CMCreateLocationMessage")) || - (message.isType("CMUpdateAuctionMessage")) || - (message.isType("CMUpdateLocationMessage")) || - (message.isType("CMDeleteAuctionMessage")) || - (message.isType("CMDeleteLocationMessage")) ) - { - const CommoditiesServerConnection * commConnection = dynamic_cast(&source); - uint32 commServerId = 0; - if (commConnection) - commServerId = commConnection->getProcessId(); - - getCommoditiesSnapshot(commServerId).handleCommoditiesDataMessage(message); - } - else if (message.isType("LoadCommodities")) - { - if (m_commoditiesSnapshot) + const uint32 messageType = message.getType(); + + switch(messageType) { + case constcrc("FlagObjectForDeleteMessage") : { - m_commoditiesSnapshot->startLoadAfterSaveComplete(); - if (!isSaveInProgress()) - m_startSaveWhenPossible = true; + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + FlagObjectForDeleteMessage m(ri); + handleDeleteMessage(sourceGameServer, m.getId(),m.getReason(),m.getImmediate(),m.getDemandLoadedContainer(),m.getCascadeReason()); + break; } - else + case constcrc("CreateObjectByCrcMessage") : { - startLoadCommodities(); + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + CreateObjectByCrcMessage t(ri); + // DEBUG_REPORT_LOG(true,("Got CreateObjectByCrcMessage for %s\n", t.getId().getValueString().c_str())); + newObject(sourceGameServer, t.getId(), t.getCrc(), t.getObjectType(), t.getContainer()); + break; + } + case constcrc("EndBaselinesMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + EndBaselinesMessage t(ri); + endBaselines(t.getId(),sourceGameServer); + break; + } + case constcrc("DeltasMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + DeltasMessage msg(ri); + + handleDeltasMessage(sourceGameServer,msg); + break; + } + case constcrc("BaselinesMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + BaselinesMessage msg(ri); + + handleBaselinesMessage(sourceGameServer,msg); + break; + } + case constcrc("UpdateObjectPositionMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UpdateObjectPositionMessage msg(ri); + + getSnapshotForObject(msg.getNetworkId(), sourceGameServer).handleUpdateObjectPosition(msg); + break; + } + case constcrc("AddCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AddCharacterMessage ocm(ri); + DEBUG_REPORT_LOG(true, ("Got AddCharacterMessage for object %s.\n",ocm.getObjectId().getValueString().c_str())); + + addCharacter(ocm.getAccountNumber(), ocm.getObjectId(), ocm.getProcess(), ocm.getName(), ocm.getSpecial()); + break; + } + case constcrc("UnloadObjectMessage") : + { + // TODO: keep track of when it's done saving so we know when we can reload it + break; + } + case constcrc("MessageToMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + MessageToMessage m(ri); + + handleMessageTo (sourceGameServer, m.getData()); + break; + } + case constcrc("MessageToAckMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + MessageToAckMessage m(ri); + + handleMessageToAck (sourceGameServer, m.getMessageId()); + break; + } + case constcrc("ServerDeleteCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + ServerDeleteCharacterMessage m(ri); + + deleteCharacter(m.getStationId(), m.getCharacterId()); + break; + } + case constcrc("RenameCharacterMessageEx") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + RenameCharacterMessageEx msg(ri); + + renameCharacter(sourceGameServer, static_cast(msg.getRenameCharacterMessageSource()), msg.getStationId(), msg.getCharacterId(), msg.getNewName(), msg.getOldName(), msg.getLastNameChangeOnly(), msg.getRequestedBy(), nullptr); + break; + } + case constcrc("UnloadedPlayerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + UnloadedPlayerMessage msg(ri); + + unloadCharacter(msg.getPlayerId(),sourceGameServer); + break; + } + case constcrc("MoveToPlayer") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + moveToPlayer(sourceGameServer, msg.getValue().first, msg.getValue().second, -1, false, false); + break; + } + case constcrc("MoveToPlayerBankMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + moveToPlayer(sourceGameServer, msg.getValue().first, msg.getValue().second, -1, true, false); + break; + } + case constcrc("MoveToPlayerDatapadMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, int> > msg(ri); + + moveToPlayer(sourceGameServer, msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second, false, true); + break; + } + case constcrc("FixLoadWith") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, int> > msg(ri); + + fixLoadWith(sourceGameServer, msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second); + break; + } + case constcrc("ClusterShutdownMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + + m_clusterShuttingDown = msg.getValue(); + break; + } + case constcrc("StartSaveMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + + userRequestedSave(sourceGameServer, msg.getValue()); + break; + } + case constcrc("RestoreHouseMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + restoreHouse(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("RestoreCharacterMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + restoreCharacter(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("UndeleteItemMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage > msg(ri); + + LOG("CustomerService", ("undeleteItem %s request from %s", msg.getValue().first.getValueString().c_str(), msg.getValue().second.c_str())); + undeleteItem(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("MoveToPlayerMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, std::string> > msg(ri); + + LOG("CustomerService", ("moveToPlayer %s, %s request from %s", msg.getValue().first.first.getValueString().c_str(), msg.getValue().first.second.getValueString().c_str(), msg.getValue().second.c_str())); + moveToPlayer(msg.getValue().first.first, msg.getValue().first.second, msg.getValue().second); + break; + } + case constcrc("CentralRequestSave") : + { + centralRequestedSave(); + break; + } + case constcrc("PlanetRequestSave") : + { + planetRequestedSave(); + break; + } + case constcrc("AddResourceTypeMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + AddResourceTypeMessage msg(ri); + handleAddResourceTypeMessage(sourceGameServer, msg); + break; + } + case constcrc("BountyHunterTargetMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + BountyHunterTargetMessage msg(ri); + getSnapshotForServer(sourceGameServer).handleBountyHunterTargetMessage(msg); + break; + } + case constcrc("CMCreateAuctionMessage") : + case constcrc("CMCreateAuctionBidMessage") : + case constcrc("CMCreateLocationMessage") : + case constcrc("CMUpdateAuctionMessage") : + case constcrc("CMUpdateLocationMessage") : + case constcrc("CMDeleteAuctionMessage") : + case constcrc("CMDeleteLocationMessage") : + { + const CommoditiesServerConnection * commConnection = dynamic_cast(&source); + uint32 commServerId = 0; + if (commConnection) + commServerId = commConnection->getProcessId(); + + getCommoditiesSnapshot(commServerId).handleCommoditiesDataMessage(message); + break; + } + case constcrc("LoadCommodities") : + { + if (m_commoditiesSnapshot) + { + m_commoditiesSnapshot->startLoadAfterSaveComplete(); + if (!isSaveInProgress()) + m_startSaveWhenPossible = true; + } + else + { + startLoadCommodities(); + } + break; + } + case constcrc("GetMoneyFromOfflineObjectMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GetMoneyFromOfflineObjectMessage msg(ri); + getMoneyFromOfflineObject(sourceGameServer, msg.getSourceObject(), msg.getAmount(), msg.getReplyTo(), msg.getSuccessCallback(), msg.getFailCallback(), msg.getPackedDictionary()); + break; + } + case constcrc("PurgeCompleteMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage msg(ri); + handlePurgeCompleteMessage(sourceGameServer, msg.getValue()); + break; + } + case constcrc("DBCSRequestMessage" ) : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + DBCSRequestMessage const msg( ri ); + handleCSRequest( msg ); + break; + } + case constcrc("UndeleteItemForCsMessage") : + { + Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); + GenericValueTypeMessage, std::string>, bool> > undeleteRequest(ri); + handleCsUndelete(undeleteRequest.getValue().first.first.first, + undeleteRequest.getValue().first.first.second, + undeleteRequest.getValue().first.second, + undeleteRequest.getValue().second); + + break; + } + default : + { + DEBUG_REPORT_LOG(true,("Unrecognized message recieved by Persister.\n")); + break; } - } - else if (message.isType("GetMoneyFromOfflineObjectMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GetMoneyFromOfflineObjectMessage msg(ri); - getMoneyFromOfflineObject(sourceGameServer, msg.getSourceObject(), msg.getAmount(), msg.getReplyTo(), msg.getSuccessCallback(), msg.getFailCallback(), msg.getPackedDictionary()); - } - else if (message.isType("PurgeCompleteMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage msg(ri); - handlePurgeCompleteMessage(sourceGameServer, msg.getValue()); - } - else if( message.isType("DBCSRequestMessage" ) ) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - DBCSRequestMessage const msg( ri ); - handleCSRequest( msg ); - } - else if (message.isType("UndeleteItemForCsMessage")) - { - Archive::ReadIterator ri = static_cast(message).getByteStream().begin(); - GenericValueTypeMessage, std::string>, bool> > undeleteRequest(ri); - handleCsUndelete(undeleteRequest.getValue().first.first.first, - undeleteRequest.getValue().first.first.second, - undeleteRequest.getValue().first.second, - undeleteRequest.getValue().second); - } - else - { - DEBUG_REPORT_LOG(true,("Unrecognized message recieved by Persister.\n")); } } diff --git a/engine/server/library/serverDatabase/src/shared/Persister.h b/engine/server/library/serverDatabase/src/shared/Persister.h index 3c432fbc..9cc76ac8 100755 --- a/engine/server/library/serverDatabase/src/shared/Persister.h +++ b/engine/server/library/serverDatabase/src/shared/Persister.h @@ -191,7 +191,7 @@ class Persister : public MessageDispatch::Receiver static void installDerived(Persister *derivedInstance); private: - Persister(Persister&); //disable + Persister(const Persister&); //disable Persister &operator=(const Persister&); //disable private: diff --git a/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp b/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp index fbb863ff..a7e3f5fb 100755 --- a/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp +++ b/engine/server/library/serverDatabase/src/shared/TaskCheckCharacterName.cpp @@ -16,8 +16,9 @@ // ====================================================================== TaskCheckCharacterName::TaskCheckCharacterName(uint32 stationId, const Unicode::String &name) : - m_name(name), - m_stationId(stationId) + m_name(name), + m_stationId(stationId), + m_resultCode(0) { } @@ -26,11 +27,11 @@ TaskCheckCharacterName::TaskCheckCharacterName(uint32 stationId, const Unicode:: bool TaskCheckCharacterName::process(DB::Session *session) { CheckCharacterNameQuery qry(Unicode::wideToNarrow(m_name)); - + bool rval = session->exec(&qry); qry.done(); - m_resultCode=qry.result.getValue(); + m_resultCode = qry.result.getValue(); return rval; } @@ -38,14 +39,14 @@ bool TaskCheckCharacterName::process(DB::Session *session) void TaskCheckCharacterName::onComplete() { - DataLookup::getInstance().onCharacterNameChecked(m_stationId, m_name,m_resultCode); + DataLookup::getInstance().onCharacterNameChecked(m_stationId, m_name, m_resultCode); LOG("TraceCharacterCreation", ("%d TaskCheckCharacterName(%s) complete with result code %d", m_stationId, Unicode::wideToNarrow(m_name).c_str(), m_resultCode)); } // ====================================================================== TaskCheckCharacterName::CheckCharacterNameQuery::CheckCharacterNameQuery(const std::string &name) : - character_name(name) + character_name(name) { } @@ -53,7 +54,7 @@ TaskCheckCharacterName::CheckCharacterNameQuery::CheckCharacterNameQuery(const s void TaskCheckCharacterName::CheckCharacterNameQuery::getSQL(std::string &sql) { - sql="begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "datalookup.check_character_name (:name); end;"; + sql = "begin :result := " + DatabaseProcess::getInstance().getSchemaQualifier() + "datalookup.check_character_name (:name); end;"; } // ---------------------------------------------------------------------- @@ -79,4 +80,4 @@ DB::Query::QueryMode TaskCheckCharacterName::CheckCharacterNameQuery::getExecuti return DB::Query::MODE_PROCEXEC; } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverDatabase/src/shared/TaskGetBiography.cpp b/engine/server/library/serverDatabase/src/shared/TaskGetBiography.cpp index 9c6cb243..96b976fb 100755 --- a/engine/server/library/serverDatabase/src/shared/TaskGetBiography.cpp +++ b/engine/server/library/serverDatabase/src/shared/TaskGetBiography.cpp @@ -19,7 +19,7 @@ TaskGetBiography::TaskGetBiography(const NetworkId &owner, uint32 requestingProcess) : m_owner(owner), m_requestingProcess(requestingProcess), - m_bio(NULL) + m_bio(nullptr) { } @@ -28,7 +28,7 @@ TaskGetBiography::TaskGetBiography(const NetworkId &owner, uint32 requestingProc TaskGetBiography::~TaskGetBiography() { delete m_bio; - m_bio=NULL; + m_bio=nullptr; } // ---------------------------------------------------------------------- @@ -53,7 +53,7 @@ bool TaskGetBiography::process(DB::Session *session) void TaskGetBiography::onComplete() { - WARNING_STRICT_FATAL(!m_bio,("In TaskGetBiography::onComplete, but m_bio is NULL\n")); + WARNING_STRICT_FATAL(!m_bio,("In TaskGetBiography::onComplete, but m_bio is nullptr\n")); if (m_bio) { BiographyMessage msg(m_owner, *m_bio); diff --git a/engine/server/library/serverDatabase/src/shared/TaskManagerConnection.h b/engine/server/library/serverDatabase/src/shared/TaskManagerConnection.h index 94d33a42..4a5cd576 100755 --- a/engine/server/library/serverDatabase/src/shared/TaskManagerConnection.h +++ b/engine/server/library/serverDatabase/src/shared/TaskManagerConnection.h @@ -20,7 +20,7 @@ public: void onConnectionOpened (); private: - TaskManagerConnection(TaskManagerConnection&); + TaskManagerConnection(const TaskManagerConnection&); TaskManagerConnection& operator=(TaskManagerConnection&); }; diff --git a/engine/server/library/serverDatabase/src/shared/TaskSetBiography.cpp b/engine/server/library/serverDatabase/src/shared/TaskSetBiography.cpp index d8a98958..501cfe48 100755 --- a/engine/server/library/serverDatabase/src/shared/TaskSetBiography.cpp +++ b/engine/server/library/serverDatabase/src/shared/TaskSetBiography.cpp @@ -24,7 +24,7 @@ TaskSetBiography::TaskSetBiography(const NetworkId &owner, const Unicode::String TaskSetBiography::~TaskSetBiography() { delete m_bio; - m_bio=NULL; + m_bio=nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverDatabase/src/win32/FirstServerDatabase.cpp b/engine/server/library/serverDatabase/src/win32/FirstServerDatabase.cpp new file mode 100755 index 00000000..944e604d --- /dev/null +++ b/engine/server/library/serverDatabase/src/win32/FirstServerDatabase.cpp @@ -0,0 +1,9 @@ +// ====================================================================== +// +// FirstServerDatabase.cpp +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#include "serverDatabase/FirstServerDatabase.h" + diff --git a/engine/server/library/serverGame/src/CMakeLists.txt b/engine/server/library/serverGame/src/CMakeLists.txt index c4a092e5..98fb2c19 100644 --- a/engine/server/library/serverGame/src/CMakeLists.txt +++ b/engine/server/library/serverGame/src/CMakeLists.txt @@ -543,16 +543,22 @@ set(SHARED_SOURCES shared/objectTemplate/ServerManufactureInstallationObjectTemplate.h shared/objectTemplate/ServerManufactureSchematicObjectTemplate.cpp shared/objectTemplate/ServerManufactureSchematicObjectTemplate.h + shared/objectTemplate/ServerMissionBoardObjectTemplate.cpp + shared/objectTemplate/ServerMissionBoardObjectTemplate.h + shared/objectTemplate/ServerMissionDataObjectTemplate.cpp + shared/objectTemplate/ServerMissionDataObjectTemplate.h + shared/objectTemplate/ServerMissionListEntryObjectTemplate.cpp + shared/objectTemplate/ServerMissionListEntryObjectTemplate.h shared/objectTemplate/ServerMissionObjectTemplate.cpp shared/objectTemplate/ServerMissionObjectTemplate.h shared/objectTemplate/ServerObjectTemplate.cpp shared/objectTemplate/ServerObjectTemplate.h shared/objectTemplate/ServerPlanetObjectTemplate.cpp shared/objectTemplate/ServerPlanetObjectTemplate.h - shared/objectTemplate/ServerPlayerQuestObjectTemplate.h - shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp shared/objectTemplate/ServerPlayerObjectTemplate.cpp shared/objectTemplate/ServerPlayerObjectTemplate.h + shared/objectTemplate/ServerPlayerQuestObjectTemplate.cpp + shared/objectTemplate/ServerPlayerQuestObjectTemplate.h shared/objectTemplate/ServerResourceContainerObjectTemplate.cpp shared/objectTemplate/ServerResourceContainerObjectTemplate.h shared/objectTemplate/ServerSharedObjectTemplateInterface.cpp @@ -563,6 +569,8 @@ set(SHARED_SOURCES shared/objectTemplate/ServerStaticObjectTemplate.h shared/objectTemplate/ServerTangibleObjectTemplate.cpp shared/objectTemplate/ServerTangibleObjectTemplate.h + shared/objectTemplate/ServerTokenObjectTemplate.cpp + shared/objectTemplate/ServerTokenObjectTemplate.h shared/objectTemplate/ServerUniverseObjectTemplate.cpp shared/objectTemplate/ServerUniverseObjectTemplate.h shared/objectTemplate/ServerVehicleObjectTemplate.cpp @@ -570,7 +578,7 @@ set(SHARED_SOURCES shared/objectTemplate/ServerWeaponObjectTemplate.cpp shared/objectTemplate/ServerWeaponObjectTemplate.h shared/objectTemplate/ServerXpManagerObjectTemplate.cpp - shared/objectTemplate/ServerXpManagerObjectTemplate.h + shared/objectTemplate/ServerXpManagerObjectTemplate.h shared/pvp/Pvp.cpp shared/pvp/PvpFactions.cpp @@ -752,7 +760,6 @@ include_directories( ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/unicode/include ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/unicodeArchive/include/public ${SWG_EXTERNALS_SOURCE_DIR}/3rd/library/platform/projects - ${Boost_INCLUDE_DIR} ${JNI_INCLUDE_DIRS} ${PCRE_INCLUDE_DIR} ) @@ -779,9 +786,17 @@ add_library(serverGame STATIC ${CMAKE_CURRENT_BINARY_DIR}/shared/generated/Packager.cpp ) +if(NOT WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8) + target_link_libraries(mulodi) +endif() + target_link_libraries(serverGame sharedCommandParser sharedPathfinding sharedSkillSystem sharedTerrain ) + +if(${BUILD_MULODI_LIB}) + target_link_libraries(serverGame mulodi) +endif() diff --git a/engine/server/library/serverGame/src/shared/ai/AggroListProperty.cpp b/engine/server/library/serverGame/src/shared/ai/AggroListProperty.cpp index 0b0a552d..e06b0d40 100755 --- a/engine/server/library/serverGame/src/shared/ai/AggroListProperty.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AggroListProperty.cpp @@ -106,7 +106,7 @@ bool AggroListPropertyNamespace::isIncapacitated(TangibleObject const & target) { CreatureObject const * const targetCreatureObject = target.asCreatureObject(); - return (targetCreatureObject != NULL) ? targetCreatureObject->isIncapacitated() : false; + return (targetCreatureObject != nullptr) ? targetCreatureObject->isIncapacitated() : false; } // ---------------------------------------------------------------------- @@ -114,7 +114,7 @@ bool AggroListPropertyNamespace::isDead(TangibleObject const & target) { CreatureObject const * const targetCreatureObject = target.asCreatureObject(); - return (targetCreatureObject != NULL) ? targetCreatureObject->isDead() : false; + return (targetCreatureObject != nullptr) ? targetCreatureObject->isDead() : false; } // ---------------------------------------------------------------------- @@ -122,7 +122,7 @@ bool AggroListPropertyNamespace::isInvulnerable(TangibleObject const & target) { CreatureObject const * const targetCreatureObject = target.asCreatureObject(); - return (targetCreatureObject != NULL) ? targetCreatureObject->isInvulnerable() : false; + return (targetCreatureObject != nullptr) ? targetCreatureObject->isInvulnerable() : false; } // ---------------------------------------------------------------------- @@ -138,7 +138,7 @@ bool AggroListPropertyNamespace::isFeigningDeath(TangibleObject const & target) { CreatureObject const * const targetCreatureObject = target.asCreatureObject(); - return (targetCreatureObject != NULL) ? targetCreatureObject->getState(States::FeignDeath) : false; + return (targetCreatureObject != nullptr) ? targetCreatureObject->getState(States::FeignDeath) : false; } // ---------------------------------------------------------------------- @@ -146,7 +146,7 @@ bool AggroListPropertyNamespace::isInPlayerBuilding(TangibleObject const & targe { ServerObject const * const topMostServerObject = ServerObject::asServerObject(ContainerInterface::getTopmostContainer(target)); - return (topMostServerObject != NULL) ? (topMostServerObject->getGameObjectType() == SharedObjectTemplate::GOT_building_player) : false; + return (topMostServerObject != nullptr) ? (topMostServerObject->getGameObjectType() == SharedObjectTemplate::GOT_building_player) : false; } // ---------------------------------------------------------------------- @@ -154,7 +154,7 @@ bool AggroListPropertyNamespace::isAggroImmune(TangibleObject const & target) { PlayerObject const * const playerObject = PlayerCreatureController::getPlayerObject(target.asCreatureObject()); - return (playerObject != NULL) ? playerObject->isAggroImmune() : false; + return (playerObject != nullptr) ? playerObject->isAggroImmune() : false; } // ====================================================================== @@ -212,7 +212,7 @@ void AggroListProperty::alter() // First, list things that invalidate this target in the aggro list // Second, list the things that promote the target to the hate list - if (target.getObject() == NULL) + if (target.getObject() == nullptr) { purgeList.push_back(iterTargetList); } @@ -315,7 +315,7 @@ TangibleObject & AggroListProperty::getTangibleOwner() AggroListProperty * AggroListProperty::getAggroListProperty(Object & object) { Property * const property = object.getProperty(getClassPropertyId()); - AggroListProperty * const aggroProperty = (property != NULL) ? static_cast(property) : NULL; + AggroListProperty * const aggroProperty = (property != nullptr) ? static_cast(property) : nullptr; return aggroProperty; } diff --git a/engine/server/library/serverGame/src/shared/ai/AiCombatPulseQueue.cpp b/engine/server/library/serverGame/src/shared/ai/AiCombatPulseQueue.cpp index c3e95004..328d9540 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiCombatPulseQueue.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiCombatPulseQueue.cpp @@ -45,7 +45,7 @@ void AiCombatPulseQueue::remove() void AiCombatPulseQueue::schedule(TangibleObject * const object, int waitTimeMs, unsigned long currentFrameTimeMs) { - if (object == NULL) + if (object == nullptr) return; unsigned long desiredTime = Clock::getFrameStartTimeMs() + currentFrameTimeMs + waitTimeMs; @@ -97,7 +97,7 @@ void AiCombatPulseQueue::alter(real time) TangibleObject * const object = (j->second)->first; - if (object != NULL && object->isInCombat()) + if (object != nullptr && object->isInCombat()) { NetworkId const & id = object->getNetworkId(); @@ -107,7 +107,7 @@ void AiCombatPulseQueue::alter(real time) GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(object); - if (gameScriptObject != NULL) + if (gameScriptObject != nullptr) { ScriptParams scriptParams; IGNORE_RETURN(gameScriptObject->trigAllScripts(Scripting::TRIG_AI_COMBAT_FRAME, scriptParams)); diff --git a/engine/server/library/serverGame/src/shared/ai/AiCreatureCombatProfile.cpp b/engine/server/library/serverGame/src/shared/ai/AiCreatureCombatProfile.cpp index cf2cb505..c27828d6 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiCreatureCombatProfile.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiCreatureCombatProfile.cpp @@ -136,9 +136,9 @@ void AiCreatureCombatProfileNamespace::loadCombatProfileTable(DataTable const & for (int i = 0; i < serverObjectCount; ++i) { ServerObject * const serverObject = ServerWorld::getObject(i); - CreatureObject * const creatureObject = (serverObject != NULL) ? serverObject->asCreatureObject() : NULL; + CreatureObject * const creatureObject = (serverObject != nullptr) ? serverObject->asCreatureObject() : nullptr; - if ( (creatureObject != NULL) + if ( (creatureObject != nullptr) && !creatureObject->isPlayerControlled()) { creatureObject->makeDead(NetworkId::cms_invalid, NetworkId::cms_invalid); @@ -228,7 +228,7 @@ void AiCreatureCombatProfileNamespace::grantActions(CreatureObject & owner, AiCr // ---------------------------------------------------------------------- AiCreatureCombatProfile::AiCreatureCombatProfile() - : m_profileId(NULL) + : m_profileId(nullptr) , m_singleUseActionList() , m_delayRepeatActionList() , m_instantRepeatActionList() @@ -247,7 +247,7 @@ void AiCreatureCombatProfile::install() bool const openIfNotFound = true; DataTable * const dataTable = DataTableManager::getTable(s_combatProfileTable, openIfNotFound); - if (dataTable != NULL) + if (dataTable != nullptr) { #ifdef _DEBUG DataTableManager::addReloadCallback(s_combatProfileTable, &loadCombatProfileTable); @@ -267,7 +267,7 @@ void AiCreatureCombatProfile::install() // ---------------------------------------------------------------------- AiCreatureCombatProfile const * AiCreatureCombatProfile::getCombatProfile(CrcString const & profileName) { - AiCreatureCombatProfile const * result = NULL; + AiCreatureCombatProfile const * result = nullptr; CombatProfileMap::const_iterator iterCombatProfileMap = s_combatProfileMap.find(PersistentCrcString(profileName)); if (iterCombatProfileMap != s_combatProfileMap.end()) diff --git a/engine/server/library/serverGame/src/shared/ai/AiCreatureData.cpp b/engine/server/library/serverGame/src/shared/ai/AiCreatureData.cpp index 034f9980..3d90a5f7 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiCreatureData.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiCreatureData.cpp @@ -46,7 +46,7 @@ namespace AiCreatureDataNamespace CreatureDataMap s_creatureDataMap; WeaponDataMap s_weaponDataMap; - AiCreatureData const * s_defaultCreatureData = NULL; + AiCreatureData const * s_defaultCreatureData = nullptr; int s_creatureErrorCount = 0; int s_weaponErrorCount = 0; @@ -154,7 +154,7 @@ void AiCreatureDataNamespace::verifySecondaryWeapon(CrcString const & creatureNa void AiCreatureDataNamespace::verifyPrimarySpecials(CrcString const & creatureName, CrcString & primarySpecials) { if ( !primarySpecials.isEmpty() - && (AiCreatureCombatProfile::getCombatProfile(primarySpecials) == NULL)) + && (AiCreatureCombatProfile::getCombatProfile(primarySpecials) == nullptr)) { ++s_creatureErrorCount; WARNING(true, ("AiCreatureData::verifyPrimarySpecials() Creature(%s) has invalid primary_weapon_specials(%s)", creatureName.getString(), primarySpecials.getString())); @@ -165,7 +165,7 @@ void AiCreatureDataNamespace::verifyPrimarySpecials(CrcString const & creatureNa void AiCreatureDataNamespace::verifySecondarySpecials(CrcString const & creatureName, CrcString & secondarySpecials) { if ( !secondarySpecials.isEmpty() - && (AiCreatureCombatProfile::getCombatProfile(secondarySpecials) == NULL)) + && (AiCreatureCombatProfile::getCombatProfile(secondarySpecials) == nullptr)) { ++s_creatureErrorCount; WARNING(true, ("AiCreatureData::verifySecondarySpecials() Creature(%s) has invalid secondary_weapon_specials(%s)", creatureName.getString(), secondarySpecials.getString())); @@ -320,7 +320,7 @@ void AiCreatureDataNamespace::loadWeaponColumn(WeaponList & weaponList, std::str // ---------------------------------------------------------------------- AiCreatureData::AiCreatureData() - : m_name(NULL) + : m_name(nullptr) , m_movementSpeedPercent(1.0f) , m_primaryWeapon() , m_secondaryWeapon() @@ -348,7 +348,7 @@ void AiCreatureData::install() bool const openIfNotFound = true; DataTable * const dataTable = DataTableManager::getTable(s_weaponDataTable, openIfNotFound); - if (dataTable != NULL) + if (dataTable != nullptr) { DataTableManager::addReloadCallback(s_weaponDataTable, &loadWeaponData); loadWeaponData(*dataTable); @@ -366,7 +366,7 @@ void AiCreatureData::install() bool const openIfNotFound = true; DataTable * const dataTable = DataTableManager::getTable(s_creaureDataTable, openIfNotFound); - if (dataTable != NULL) + if (dataTable != nullptr) { DataTableManager::addReloadCallback(s_creaureDataTable, &loadCreatureData); loadCreatureData(*dataTable); diff --git a/engine/server/library/serverGame/src/shared/ai/AiCreatureWeaponActions.cpp b/engine/server/library/serverGame/src/shared/ai/AiCreatureWeaponActions.cpp index 781bc2f1..4d5498f8 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiCreatureWeaponActions.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiCreatureWeaponActions.cpp @@ -58,7 +58,7 @@ AiCreatureWeaponActions::AiCreatureWeaponActions() : m_singleUseActionList() , m_delayRepeatActionList() , m_instantRepeatActionList() - , m_combatProfile(NULL) + , m_combatProfile(nullptr) { } @@ -81,7 +81,7 @@ void AiCreatureWeaponActions::setCombatProfile(CreatureObject & owner, AiCreatur // ---------------------------------------------------------------------- void AiCreatureWeaponActions::reset() { - if (m_combatProfile != NULL) + if (m_combatProfile != nullptr) { resetActionTimers(m_singleUseActionList, m_combatProfile->m_singleUseActionList); resetActionTimers(m_delayRepeatActionList, m_combatProfile->m_delayRepeatActionList); @@ -92,9 +92,9 @@ void AiCreatureWeaponActions::reset() // ---------------------------------------------------------------------- PersistentCrcString const & AiCreatureWeaponActions::getCombatAction() { - // If the combat profile is NULL, then the AI has no special actions assigned + // If the combat profile is nullptr, then the AI has no special actions assigned - if (m_combatProfile != NULL) + if (m_combatProfile != nullptr) { time_t const osTime = Os::getRealSystemTime(); diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementArchive.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementArchive.cpp index 723b8c7e..e1508bf4 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementArchive.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementArchive.cpp @@ -34,12 +34,12 @@ namespace Archive get(source, target.m_objectId); get(source, movementType); - AICreatureController * controller = NULL; + AICreatureController * controller = nullptr; Object * object = NetworkIdManager::getObjectById(target.getObjectId()); - if (object != NULL) + if (object != nullptr) controller = dynamic_cast(object->getController()); - if (controller == NULL) + if (controller == nullptr) { WARNING(true, ("AiMovementMessage Archive::get, got message to object %s that doesn't have an AICreatureController", target.getObjectId().getValueString().c_str())); target.m_movement = AiMovementBaseNullPtr; diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementBase.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementBase.cpp index dde28a05..79f1e119 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementBase.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementBase.cpp @@ -30,9 +30,9 @@ AiMovementBase::AiMovementBase( AICreatureController * controller ) : m_controller( controller ), - m_stateFunction( NULL ), + m_stateFunction( nullptr ), m_stateName(), - m_pendingFunction( NULL ), + m_pendingFunction( nullptr ), m_pendingName() { } @@ -41,9 +41,9 @@ AiMovementBase::AiMovementBase( AICreatureController * controller ) AiMovementBase::AiMovementBase( AICreatureController * controller, Archive::ReadIterator & source ) : m_controller( controller ), - m_stateFunction( NULL ), + m_stateFunction( nullptr ), m_stateName(), - m_pendingFunction( NULL ), + m_pendingFunction( nullptr ), m_pendingName() { // !!! @@ -177,7 +177,7 @@ void AiMovementBase::applyStateChange ( void ) m_stateFunction = m_pendingFunction; m_stateName = m_pendingName; - m_pendingFunction = NULL; + m_pendingFunction = nullptr; m_pendingName.clear(); } } @@ -249,49 +249,49 @@ char const * AiMovementBase::getMovementString(AiMovementType const aiMovementTy // ---------------------------------------------------------------------- AiMovementSwarm * AiMovementBase::asAiMovementSwarm() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementFace * AiMovementBase::asAiMovementFace() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementFlee * AiMovementBase::asAiMovementFlee() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementFollow * AiMovementBase::asAiMovementFollow() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementLoiter * AiMovementBase::asAiMovementLoiter() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementMove * AiMovementBase::asAiMovementMove() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementPatrol * AiMovementBase::asAiMovementPatrol() { - return NULL; + return nullptr; } // ---------------------------------------------------------------------- AiMovementWander * AiMovementBase::asAiMovementWander() { - return NULL; + return nullptr; } // ====================================================================== diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementBase.h b/engine/server/library/serverGame/src/shared/ai/AiMovementBase.h index 5881b536..393ba778 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementBase.h +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementBase.h @@ -9,7 +9,7 @@ #ifndef INCLUDED_AiMovementBase_H #define INCLUDED_AiMovementBase_H -#include "boost/smart_ptr.hpp" +#include class AICreatureController; class AiDebugString; @@ -136,7 +136,7 @@ protected: //----------------------------------------------------------------------- // define shared pointer template for AiMovementBase -typedef boost::shared_ptr AiMovementBasePtr; +typedef std::shared_ptr AiMovementBasePtr; #define AiMovementBaseNullPtr AiMovementBasePtr() diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementLoiter.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementLoiter.cpp index 8e4e5a2d..e8e0f5c4 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementLoiter.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementLoiter.cpp @@ -67,9 +67,9 @@ Vector AiMovementLoiterNamespace::getRandomLoiterPosition_p(Vector const anchorP bool AiMovementLoiterNamespace::isPositionOnFloor(Floor const * const floor, Vector const & position_p, float const radius, Vector & floorPosition_p) { bool result = false; - FloorMesh const * const floorMesh = (floor != NULL) ? floor->getFloorMesh() : NULL; + FloorMesh const * const floorMesh = (floor != nullptr) ? floor->getFloorMesh() : nullptr; - if (floorMesh != NULL) + if (floorMesh != nullptr) { // See if the circle fits entirely on the floor { @@ -199,7 +199,7 @@ AiMovementLoiter::AiMovementLoiter( AICreatureController * controller, Archive:: AiMovementLoiter::~AiMovementLoiter() { delete m_cachedAiLocations; - m_cachedAiLocations = NULL; + m_cachedAiLocations = nullptr; } // ---------------------------------------------------------------------- @@ -420,7 +420,7 @@ bool AiMovementLoiter::generateWaypoint() Floor const * const ownerFloor = CollisionWorld::getFloorStandingOn(*creatureOwner); - if (ownerFloor != NULL) + if (ownerFloor != nullptr) { // The owner is standing on a floor @@ -476,7 +476,7 @@ bool AiMovementLoiter::generateWaypoint() TerrainObject const * const terrainObject = TerrainObject::getConstInstance(); - if ( (terrainObject != NULL) + if ( (terrainObject != nullptr) && terrainObject->isPassable(randomPosition_p)) { // Snap the random position to the terrain @@ -518,7 +518,7 @@ bool AiMovementLoiter::generateWaypoint() { BaseExtent const * const extent = collisionProperty->getExtent_l(); - if (extent != NULL) + if (extent != nullptr) { Vector const begin_o(object.rotateTranslate_w2o(m_anchor.getPosition_p())); Vector const end_o(object.rotateTranslate_w2o(randomPosition_p)); @@ -580,7 +580,7 @@ void AiMovementLoiter::addDebug(AiDebugString & aiDebugString) AiMovementWaypoint::addDebug(aiDebugString); FormattedString<512> fs; - aiDebugString.addText(fs.sprintf("LOITER %s\n%s\ndist[%.0f...%.0f]\ndelay[%.1f...%.1f]\n", (m_anchor.getObject() != NULL) ? "TARGET" : "POSITION", m_stateName.c_str(), m_minDistance, m_maxDistance, m_minDelay, m_maxDelay), PackedRgb::solidCyan); + aiDebugString.addText(fs.sprintf("LOITER %s\n%s\ndist[%.0f...%.0f]\ndelay[%.1f...%.1f]\n", (m_anchor.getObject() != nullptr) ? "TARGET" : "POSITION", m_stateName.c_str(), m_minDistance, m_maxDistance, m_minDelay, m_maxDelay), PackedRgb::solidCyan); //if (m_bubbleCheckResult == BCR_invalid) //{ @@ -599,7 +599,7 @@ void AiMovementLoiter::addDebug(AiDebugString & aiDebugString) { Object const * const anchorObject = m_anchor.getObject(); - if (anchorObject != NULL) + if (anchorObject != nullptr) { // We are anchored to a moving target @@ -659,7 +659,7 @@ bool AiMovementLoiter::isAnchorValid() const { TangibleObject const * const tangibleObject = TangibleObject::asTangibleObject(m_anchor.getObject()); - if (tangibleObject != NULL) + if (tangibleObject != nullptr) { if (tangibleObject->isInCombat()) { diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementMove.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementMove.cpp index 9641e7e3..71b6b193 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementMove.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementMove.cpp @@ -85,7 +85,7 @@ AiMovementMove::AiMovementMove( AICreatureController * controller, Archive::Read AiMovementMove::~AiMovementMove() { delete m_pathBuilder; - m_pathBuilder = NULL; + m_pathBuilder = nullptr; } // ---------------------------------------------------------------------- @@ -151,7 +151,7 @@ void AiMovementMove::refresh( void ) m_target = target; m_targetName = targetName; - if (m_controller != NULL) + if (m_controller != nullptr) m_start = AiLocation(m_controller->getCreatureCell(), m_controller->getCreaturePosition_p()); CHANGE_STATE( AiMovementMove::stateWaiting ); } diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementPathFollow.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementPathFollow.cpp index 2105c898..34ab1e1f 100644 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementPathFollow.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementPathFollow.cpp @@ -73,7 +73,7 @@ AiMovementPathFollow::AiMovementPathFollow( AICreatureController * controller, A : AiMovementWaypoint( controller, source ), m_path( new AiPath() ) { - if (m_path != NULL) + if (m_path != nullptr) Archive::get(source, *m_path); } @@ -84,7 +84,7 @@ AiMovementPathFollow::~AiMovementPathFollow() clearPath(); delete m_path; - m_path = NULL; + m_path = nullptr; } // ---------------------------------------------------------------------- @@ -92,7 +92,7 @@ AiMovementPathFollow::~AiMovementPathFollow() void AiMovementPathFollow::pack( Archive::ByteStream & target ) const { AiMovementWaypoint::pack(target); - if (m_path != NULL) + if (m_path != nullptr) Archive::put(target, *m_path); else Archive::put(target, static_cast(0)); @@ -288,7 +288,7 @@ AiPath const * AiMovementPathFollow::getPath ( void ) const void AiMovementPathFollow::swapPath ( AiPath * newPath ) { - if(newPath == NULL) return; + if(newPath == nullptr) return; AiPath::iterator it; diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementPatrol.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementPatrol.cpp index 4ea6a593..c4c73b88 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementPatrol.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementPatrol.cpp @@ -60,7 +60,7 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect m_patrolPointIndex(startPoint) { ServerObject * owner = safe_cast(controller->getOwner()); - if (owner != NULL) + if (owner != nullptr) { DEBUG_REPORT_LOG(ConfigServerGame::isAiLoggingEnabled(), ("AiMovementPatrol creating named path for %s\n", owner->getNetworkId().getValueString().c_str())); @@ -98,7 +98,7 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect { const Unicode::String & pointName = *i; const CityPathNode * node = CityPathGraphManager::getNamedNodeFor(*owner, pointName); - if (node != NULL) + if (node != nullptr) { m_patrolPath.push_back(AiLocation(node->getSourceId())); } @@ -118,16 +118,16 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect // try an find a node on the path that is a previous root node, or isn't // being used in any other path std::vector::iterator i; - const ServerObject * node = NULL; - const ServerObject * root = NULL; + const ServerObject * node = nullptr; + const ServerObject * root = nullptr; for (i = m_patrolPath.begin(); i != m_patrolPath.end(); ++i) { node = safe_cast(i->getObject()); - if (node != NULL) + if (node != nullptr) { if (node->isPatrolPathRoot()) { - if (root == NULL || !root->isPatrolPathRoot()) + if (root == nullptr || !root->isPatrolPathRoot()) { // if we already have a set up root node, use that root = node; @@ -135,18 +135,18 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect else { // we've got two previous root nodes, we can't connect them - root = NULL; + root = nullptr; break; } } - else if (!node->isPatrolPathNode() && root == NULL) + else if (!node->isPatrolPathNode() && root == nullptr) { // found a free node root = node; } } } - if (root != NULL) + if (root != nullptr) { // set up the root node if (!root->isPatrolPathRoot()) @@ -156,7 +156,7 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect for (i = m_patrolPath.begin(); i != m_patrolPath.end(); ++i) { node = safe_cast(i->getObject()); - if (node != NULL && node != root) + if (node != nullptr && node != root) const_cast(node)->setPatrolPathRoot(*root); } const_cast(root)->addPatrolPathingObject(*owner); @@ -167,7 +167,7 @@ AiMovementPatrol::AiMovementPatrol( AICreatureController * controller, std::vect for (i = m_patrolPath.begin(); i != m_patrolPath.end(); ++i) { node = safe_cast(i->getObject()); - if (node != NULL) + if (node != nullptr) nodes += node->getNetworkId().getValueString() + " "; } WARNING(true, ("AiMovementPatrol unable to find root node for path: %s", nodes.c_str())); @@ -266,15 +266,15 @@ void AiMovementPatrol::getDebugInfo ( std::string & outString ) const void AiMovementPatrol::endBehavior() { - if (!m_patrolPath.empty() && m_controller != NULL) + if (!m_patrolPath.empty() && m_controller != nullptr) { const ServerObject * owner = safe_cast(m_controller->getOwner()); - if (owner != NULL) + if (owner != nullptr) { for (std::vector::iterator i = m_patrolPath.begin(); i != m_patrolPath.end(); ++i) { const ServerObject * node = safe_cast(i->getObject()); - if (node != NULL && node->isPatrolPathRoot()) + if (node != nullptr && node->isPatrolPathRoot()) { const_cast(node)->removePatrolPathingObject(*owner); break; @@ -304,7 +304,7 @@ bool AiMovementPatrol::getHibernateOk() const if (!m_patrolPath.empty()) { const ServerObject * node = safe_cast(m_patrolPath.front().getObject()); - if (node != NULL) + if (node != nullptr) { return node->getPatrolPathObservers() == 0; } diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementSwarm.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementSwarm.cpp index 52a3e701..f9593a06 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementSwarm.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementSwarm.cpp @@ -104,10 +104,10 @@ void AiMovementSwarm::alter ( float time ) } // update the offset from our target we want to go to - if (m_target.getObject() != NULL) + if (m_target.getObject() != nullptr) { const CreatureObject * owner = m_controller->getCreature(); - if (owner != NULL) + if (owner != nullptr) { offsetMap::const_iterator found = s_offsetMap.find(CachedNetworkId(*owner)); if (found != s_offsetMap.end()) @@ -179,7 +179,7 @@ AiStateResult AiMovementSwarm::triggerWaiting() { // note: don't use the m_target position function, because it includes the offset position const Object * target = m_target.getObject(); - if (target != NULL) + if (target != nullptr) m_controller->turnToward(target->getParentCell(), target->getPosition_p()); return AiMovementFollow::triggerWaiting(); } @@ -196,7 +196,7 @@ void AiMovementSwarm::init() const CreatureObject * creatureOwner = m_controller->getCreature(); const CreatureObject * creatureTarget = CreatureObject::asCreatureObject(m_target.getObject()); - if (creatureOwner != NULL && creatureTarget != NULL) + if (creatureOwner != nullptr && creatureTarget != nullptr) { CreatureWatcher watchedCreature(creatureOwner); targetMap::iterator found = s_swarmMap.find(CachedNetworkId(*creatureTarget)); @@ -226,7 +226,7 @@ void AiMovementSwarm::cleanup() // note: using static_cast instead of safe_cast because the owner may be in the process of being destructed const CreatureObject * owner = static_cast(m_controller->getOwner()); const CreatureObject * target = static_cast(m_target.getObject()); - if (owner != NULL && target != NULL) + if (owner != nullptr && target != nullptr) { targetMap::iterator found = s_swarmMap.find(CachedNetworkId(*target)); if (found != s_swarmMap.end()) @@ -258,7 +258,7 @@ void AiMovementSwarm::computeGoals() for (targetMap::iterator i = s_swarmMap.begin(); i != s_swarmMap.end();) { const CreatureObject * target = CreatureObject::asCreatureObject((*i).first.getObject()); - if (target != NULL && !target->isDead()) + if (target != nullptr && !target->isDead()) { computeGoals(*target, (*i).second); if ((*i).second.empty()) @@ -294,16 +294,16 @@ void AiMovementSwarm::computeGoals(const CreatureObject & target, std::vectorgetController()); - if (controller != NULL) + if (controller != nullptr) swarmMovement = dynamic_cast(controller->getCurrentMovement()); } - if (mover == NULL || mover->isDead()) + if (mover == nullptr || mover->isDead()) { // dump the mover from our list --count; @@ -314,7 +314,7 @@ void AiMovementSwarm::computeGoals(const CreatureObject & target, std::vectorisDead()) + if (blocker == nullptr || blocker->isDead()) { continue; } @@ -361,7 +361,7 @@ void AiMovementSwarm::computeGoals(const CreatureObject & target, std::vectorasServerObject() != NULL) + if (o != nullptr && o->asServerObject() != nullptr) { // if the target is a player, don't hibernate if (o->asServerObject()->isPlayerControlled()) hibernate = false; // hibernate if who we're following is hibernating - else if (o->asServerObject()->asCreatureObject() != NULL) + else if (o->asServerObject()->asCreatureObject() != nullptr) hibernate = (safe_cast(o->getController()))->getHibernate(); } else @@ -114,7 +114,7 @@ static const AiMovementTarget * preventRecurse = NULL; // clean up recusion checkers if (preventRecurse == this) - preventRecurse = NULL; + preventRecurse = nullptr; --recursionCount; return hibernate; } diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementWanderInterior.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementWanderInterior.cpp index 24a4c66a..a5fe327d 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementWanderInterior.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementWanderInterior.cpp @@ -82,23 +82,23 @@ bool AiMovementWanderInterior::updateWaypoint ( void ) { CreatureObject const * creature = m_controller->getCreature(); - if(creature == NULL) return false; + if(creature == nullptr) return false; CellProperty const * cell = creature->getParentCell(); - if(cell == NULL) return false; + if(cell == nullptr) return false; Floor const * floor = cell->getFloor(); - if(floor == NULL) return false; + if(floor == nullptr) return false; FloorMesh const * floorMesh = floor->getFloorMesh(); - if(floorMesh == NULL) return false; + if(floorMesh == nullptr) return false; PathGraph const * graph = safe_cast(floorMesh->getPathGraph()); - if(graph == NULL) return false; + if(graph == nullptr) return false; // ---------- @@ -107,11 +107,11 @@ bool AiMovementWanderInterior::updateWaypoint ( void ) if(closestIndex == -2) { const CellObject *cellObject = dynamic_cast(&cell->getOwner()); - const BuildingObject *building = (cellObject ? cellObject->getOwnerBuilding() : NULL); + const BuildingObject *building = (cellObject ? cellObject->getOwnerBuilding() : nullptr); Vector creaturePosition = creature->getPosition_w(); LOG("building-data-error",("Building id=%s has no path data but creature id=%s at (x=%.2f,y=%.2f,z=%.2f) requires it for wandering, stopping behavior.", - (building ? building->getNetworkId().getValueString().c_str() : ""), + (building ? building->getNetworkId().getValueString().c_str() : ""), creature->getNetworkId().getValueString().c_str(), creaturePosition.x, creaturePosition.y, @@ -132,7 +132,7 @@ bool AiMovementWanderInterior::updateWaypoint ( void ) { PathNode const * closestNode = graph->getNode(closestIndex); - if(closestNode != NULL) + if(closestNode != nullptr) { m_target = AiLocation(m_controller->getCreatureCell(),closestNode->getPosition_p()); diff --git a/engine/server/library/serverGame/src/shared/ai/AiMovementWaypoint.cpp b/engine/server/library/serverGame/src/shared/ai/AiMovementWaypoint.cpp index 3b2b123e..c92d3100 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiMovementWaypoint.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiMovementWaypoint.cpp @@ -34,7 +34,7 @@ float computeMovementModifier (CreatureObject * const object) { if (!object) { - DEBUG_FATAL(true, ("object is NULL.")); + DEBUG_FATAL(true, ("object is nullptr.")); return 0.0f; } @@ -81,7 +81,7 @@ float computeMovementModifier (CreatureObject * const object) // if the creature has a slope effect property, see if it has a greater // (more negative) effect on the creature than the terrain const Property * property = object->getProperty(SlopeEffectProperty::getClassPropertyId()); - if (property != NULL) + if (property != nullptr) { // note we use the creature's base speed modifier, not the one modified by skills // (although for ai they're probably the same) diff --git a/engine/server/library/serverGame/src/shared/ai/AiTargetingSystem.cpp b/engine/server/library/serverGame/src/shared/ai/AiTargetingSystem.cpp index 2afac7bc..050263d3 100755 --- a/engine/server/library/serverGame/src/shared/ai/AiTargetingSystem.cpp +++ b/engine/server/library/serverGame/src/shared/ai/AiTargetingSystem.cpp @@ -94,7 +94,7 @@ bool AiTargetingSystem::canAttackTarget(TangibleObject const * target) { bool result = false; - if (target != NULL) + if (target != nullptr) { if ( (m_owner.getDistanceBetweenCollisionSpheres_w(*target) <= ConfigServerGame::getMaxCombatRange()) && m_owner.checkLOSTo(*target)) diff --git a/engine/server/library/serverGame/src/shared/ai/Formation.cpp b/engine/server/library/serverGame/src/shared/ai/Formation.cpp index 713d9b00..415989a2 100755 --- a/engine/server/library/serverGame/src/shared/ai/Formation.cpp +++ b/engine/server/library/serverGame/src/shared/ai/Formation.cpp @@ -128,8 +128,8 @@ void Formation::build(Squad & squad) DEBUG_FATAL(squad.isEmpty(), ("Building a formation on an empty squad.")); Object const * const leaderObject = squad.getLeader().getObject(); - CollisionProperty const * const leaderCollisionProperty = (leaderObject != NULL) ? leaderObject->getCollisionProperty() : NULL; - float const leaderRadius = (leaderCollisionProperty != NULL) ? (leaderCollisionProperty->getBoundingSphere_l().getRadius() * 2.0f) : 1.0f; + CollisionProperty const * const leaderCollisionProperty = (leaderObject != nullptr) ? leaderObject->getCollisionProperty() : nullptr; + float const leaderRadius = (leaderCollisionProperty != nullptr) ? (leaderCollisionProperty->getBoundingSphere_l().getRadius() * 2.0f) : 1.0f; int slotIndex = 0; Squad::UnitMap const & unitSet = squad.getUnitMap(); diff --git a/engine/server/library/serverGame/src/shared/ai/HateList.cpp b/engine/server/library/serverGame/src/shared/ai/HateList.cpp index d57fc5cb..496fb2b9 100755 --- a/engine/server/library/serverGame/src/shared/ai/HateList.cpp +++ b/engine/server/library/serverGame/src/shared/ai/HateList.cpp @@ -41,8 +41,8 @@ // ---------------------------------------------------------------------- HateList::HateList() - : m_owner(NULL) - , m_playerObject(NULL) + : m_owner(nullptr) + , m_playerObject(nullptr) , m_hateList() , m_target(CachedNetworkId::cms_cachedInvalid) , m_maxHate(0.0f) @@ -56,8 +56,8 @@ HateList::HateList() HateList::~HateList() { clear(); - m_owner = NULL; - m_playerObject = NULL; + m_owner = nullptr; + m_playerObject = nullptr; } // ---------------------------------------------------------------------- @@ -119,7 +119,7 @@ bool HateList::addHate(NetworkId const & target, float const hate) // If a target AI has a master, the target and the master needs to be added to the hate list (ie. pets should cause their master to gain hate) { CreatureObject const * const targetCreatureObject = CreatureObject::asCreatureObject(targetObject); - NetworkId const & masterId = (targetCreatureObject != NULL) ? targetCreatureObject->getMasterId() : NetworkId::cms_invalid; + NetworkId const & masterId = (targetCreatureObject != nullptr) ? targetCreatureObject->getMasterId() : NetworkId::cms_invalid; if (masterId != NetworkId::cms_invalid) { @@ -274,7 +274,7 @@ bool HateList::removeTarget(NetworkId const & target) { AggroListProperty * const aggroList = AggroListProperty::getAggroListProperty(*m_owner); - if (aggroList != NULL) + if (aggroList != nullptr) { aggroList->addTarget(target); } @@ -301,7 +301,7 @@ bool HateList::isValidTarget(Object * const target) bool valid = true; TangibleObject * const targetTangibleObject = TangibleObject::asTangibleObject(target); - if (targetTangibleObject == NULL) + if (targetTangibleObject == nullptr) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::isValidTarget() owner(%s:%s) TARGET IS NOT A TANGIBLEOBJECT", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str())); valid = false; @@ -334,7 +334,7 @@ bool HateList::isValidTarget(Object * const target) { CreatureObject const * const targetCreatureObject = targetTangibleObject->asCreatureObject(); - if (targetCreatureObject != NULL) + if (targetCreatureObject != nullptr) { if (targetTangibleObject->isDisabled()) { @@ -355,7 +355,7 @@ bool HateList::isValidTarget(Object * const target) { AICreatureController const * const targetAiCreatureController = AICreatureController::asAiCreatureController(targetCreatureObject->getController()); - if ( (targetAiCreatureController != NULL) + if ( (targetAiCreatureController != nullptr) && targetAiCreatureController->isRetreating()) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::isValidTarget() owner(%s:%s) TARGET IS RETREATING", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str())); @@ -370,7 +370,7 @@ bool HateList::isValidTarget(Object * const target) // themselves towards the player so that they and the player // enter combat correctly. { - if ( (m_owner->asCreatureObject() != NULL) + if ( (m_owner->asCreatureObject() != nullptr) && !Pvp::canAttack(*m_owner, *targetTangibleObject)) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::isValidTarget() owner(%s:%s) PVP CAN'T ATTACK", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str())); @@ -393,7 +393,7 @@ CachedNetworkId const & HateList::getTarget() const if ( (m_target.get() == CachedNetworkId::cms_cachedInvalid) && !isEmpty()) { - WARNING(true, ("HateList::getTarget() owner(%s) m_hateList.size(%u) m_target is NULL but the HateList is not empty.", m_owner->getDebugInformation().c_str(), m_hateList.size())); + WARNING(true, ("HateList::getTarget() owner(%s) m_hateList.size(%u) m_target is nullptr but the HateList is not empty.", m_owner->getDebugInformation().c_str(), m_hateList.size())); } #endif // _DEBUG @@ -458,7 +458,7 @@ void HateList::findNewTarget() for (; iterHateList != m_hateList.end(); ++iterHateList) { - if (iterHateList->first.getObject() == NULL) + if (iterHateList->first.getObject() == nullptr) { // This target will be removed in the next alter call continue; @@ -510,11 +510,11 @@ void HateList::setTarget(CachedNetworkId const & target, float const hate) #ifdef _DEBUG // We should only have tangible objects in our target list - if (m_target.get().getObject() != NULL) + if (m_target.get().getObject() != nullptr) { TangibleObject const * const targetTangibleObject = TangibleObject::asTangibleObject(m_target.get().getObject()->asServerObject()); - if (targetTangibleObject == NULL) + if (targetTangibleObject == nullptr) { WARNING(true, ("HateList::setTarget() owner(%s) How did we get a target(%s) that is not a TangibleObject", m_owner->getDebugInformation().c_str(), m_target.get().getObject()->getDebugInformation().c_str())); } @@ -559,7 +559,7 @@ void HateList::triggerTargetChanged(NetworkId const & target) { GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_owner); - if (gameScriptObject != NULL) + if (gameScriptObject != nullptr) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::triggerTargetChanged() owner(%s:%s) target(%s)", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str(), target.getValueString().c_str())); @@ -578,7 +578,7 @@ void HateList::triggerTargetAdded(NetworkId const & target) { GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_owner); - if (gameScriptObject != NULL) + if (gameScriptObject != nullptr) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::triggerTargetAdded() owner(%s:%s) target(%s)", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str(), target.getValueString().c_str())); @@ -597,7 +597,7 @@ void HateList::triggerTargetRemoved(NetworkId const & target) { GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_owner); - if (gameScriptObject != NULL) + if (gameScriptObject != nullptr) { LOGC(AiLogManager::isLogging(m_owner->getNetworkId()), "debug_ai", ("HateList::triggerTargetRemoved() owner(%s:%s) target(%s)", m_owner->getNetworkId().getValueString().c_str(), FileNameUtils::get(m_owner->getDebugName(), FileNameUtils::fileName).c_str(), target.getValueString().c_str())); @@ -628,7 +628,7 @@ int HateList::getAutoExpireTargetDuration() const bool HateList::isOwnerValid() const { CreatureObject const * const ownerCreature = CreatureObject::asCreatureObject(m_owner); - bool const ownerIncapacitated = (ownerCreature != NULL) ? ownerCreature->isIncapacitated() : false; + bool const ownerIncapacitated = (ownerCreature != nullptr) ? ownerCreature->isIncapacitated() : false; if (ownerIncapacitated) { @@ -636,7 +636,7 @@ bool HateList::isOwnerValid() const return false; } - bool const ownerDead = (ownerCreature != NULL) ? ownerCreature->isDead() : false; + bool const ownerDead = (ownerCreature != nullptr) ? ownerCreature->isDead() : false; if (ownerDead) { @@ -644,7 +644,7 @@ bool HateList::isOwnerValid() const return false; } - bool const ownerDisabled = (ownerCreature != NULL) ? ownerCreature->isDisabled() : false; + bool const ownerDisabled = (ownerCreature != nullptr) ? ownerCreature->isDisabled() : false; if (ownerDisabled) { @@ -653,7 +653,7 @@ bool HateList::isOwnerValid() const } AICreatureController const * const ownerAiCreatureController = AICreatureController::asAiCreatureController(m_owner->getController()); - const bool ownerRetreating = (ownerAiCreatureController != NULL) ? ownerAiCreatureController->isRetreating() : false; + const bool ownerRetreating = (ownerAiCreatureController != nullptr) ? ownerAiCreatureController->isRetreating() : false; if (ownerRetreating) { @@ -752,11 +752,11 @@ void HateList::forceHateTarget(const NetworkId &target) #ifdef _DEBUG // We should only have tangible objects in our target list - if (m_target.get().getObject() != NULL) + if (m_target.get().getObject() != nullptr) { TangibleObject const * const targetTangibleObject = TangibleObject::asTangibleObject(m_target.get().getObject()->asServerObject()); - if (targetTangibleObject == NULL) + if (targetTangibleObject == nullptr) { WARNING(true, ("HateList::setTarget() owner(%s) How did we get a target(%s) that is not a TangibleObject", m_owner->getDebugInformation().c_str(), m_target.get().getObject()->getDebugInformation().c_str())); } diff --git a/engine/server/library/serverGame/src/shared/ai/HateList.h b/engine/server/library/serverGame/src/shared/ai/HateList.h index c4f1b761..38a3a685 100755 --- a/engine/server/library/serverGame/src/shared/ai/HateList.h +++ b/engine/server/library/serverGame/src/shared/ai/HateList.h @@ -99,7 +99,7 @@ private: inline bool HateList::isOwnerPlayer() const { - return (m_playerObject != NULL); + return (m_playerObject != nullptr); } // ====================================================================== diff --git a/engine/server/library/serverGame/src/shared/ai/Squad.cpp b/engine/server/library/serverGame/src/shared/ai/Squad.cpp index caced74f..b4a23b20 100755 --- a/engine/server/library/serverGame/src/shared/ai/Squad.cpp +++ b/engine/server/library/serverGame/src/shared/ai/Squad.cpp @@ -380,7 +380,7 @@ void Squad::buildFormation() { NetworkId const & unit = iterUnitMap->first; PersistentCrcString const * unitName = iterUnitMap->second; - DEBUG_FATAL((unitName == NULL), ("The unit should have a non-null name.")); + DEBUG_FATAL((unitName == nullptr), ("The unit should have a non-nullptr name.")); if (unit == m_leader) { @@ -401,7 +401,7 @@ void Squad::buildFormation() #ifdef DEBUG Object * const unitObject = NetworkIdManager::getObjectById(unit); DEBUG_WARNING(true, ("className(%s) Unable to find the ship(%s) [%s] in the formation priority list.", - getClassName(), unitName->getString(), unitObject ? unitObject->getDebugInformation().c_str() : "NULL")); + getClassName(), unitName->getString(), unitObject ? unitObject->getDebugInformation().c_str() : "nullptr")); #endif } @@ -463,7 +463,7 @@ void Squad::calculateSquadPosition_w() Object * const object = NetworkIdManager::getObjectById(unit); - if (object != NULL) + if (object != nullptr) { m_squadPosition_w += object->getPosition_w(); } diff --git a/engine/server/library/serverGame/src/shared/behavior/AiCreatureStateArchive.cpp b/engine/server/library/serverGame/src/shared/behavior/AiCreatureStateArchive.cpp index 08bba97e..b6c5690b 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiCreatureStateArchive.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiCreatureStateArchive.cpp @@ -28,15 +28,15 @@ namespace Archive #ifdef _DEBUG Object * const object = NetworkIdManager::getObjectById(target.m_networkId); - if (object == NULL) + if (object == nullptr) { WARNING(true, ("AiCreatureStateArchive::get() Unable to resolve networkId(%s) to an Object", target.m_networkId.getValueString().c_str())); return; } - AICreatureController * const controller = (object != NULL) ? AICreatureController::asAiCreatureController(object->getController()) : NULL; + AICreatureController * const controller = (object != nullptr) ? AICreatureController::asAiCreatureController(object->getController()) : nullptr; - if (controller == NULL) + if (controller == nullptr) { WARNING(true, ("AiCreatureStateArchive::get() Message to object(%s) that does not have an AICreatureController", object->getDebugInformation().c_str())); return; diff --git a/engine/server/library/serverGame/src/shared/behavior/AiLocation.cpp b/engine/server/library/serverGame/src/shared/behavior/AiLocation.cpp index 885657b9..d73f1f43 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiLocation.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiLocation.cpp @@ -43,9 +43,9 @@ namespace AiLocationArchive AiLocation::AiLocation ( void ) : m_valid(false), m_attached(false), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(Vector::zero), m_position_w(Vector::zero), m_radius(0.0f), @@ -60,9 +60,9 @@ AiLocation::AiLocation ( void ) AiLocation::AiLocation ( CellProperty const * cell, Vector const & position, float radius ) : m_valid(true), m_attached(false), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(cell ? &cell->getOwner() : NULL), + m_cellObject(cell ? &cell->getOwner() : nullptr), m_position_p(position), m_position_w(CollisionUtils::transformToWorld(cell,position)), m_radius(radius), @@ -78,9 +78,9 @@ AiLocation::AiLocation ( CellProperty const * cell, Vector const & position, flo AiLocation::AiLocation ( NetworkId const & cellId, Vector const & position, float radius ) : m_valid(true), m_attached(false), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(position), m_position_w(position), m_radius(radius), @@ -110,9 +110,9 @@ AiLocation::AiLocation ( NetworkId const & cellId, Vector const & position, floa AiLocation::AiLocation ( Object const * object ) : m_valid(true), m_attached(true), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(Vector::zero), m_position_w(Vector::zero), m_radius(0.0f), @@ -129,9 +129,9 @@ AiLocation::AiLocation ( Object const * object ) AiLocation::AiLocation ( NetworkId const & objectId ) : m_valid(true), m_attached(true), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(Vector::zero), m_position_w(Vector::zero), m_radius(0.0f), @@ -148,9 +148,9 @@ AiLocation::AiLocation ( NetworkId const & objectId ) AiLocation::AiLocation ( Object const * object, Vector const & offset, bool relativeOffset ) : m_valid(true), m_attached(true), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(Vector::zero), m_position_w(Vector::zero), m_radius(0.0f), @@ -167,9 +167,9 @@ AiLocation::AiLocation ( Object const * object, Vector const & offset, bool rela AiLocation::AiLocation ( NetworkId const & objectId, Vector const & offset, bool relativeOffset ) : m_valid(true), m_attached(true), - m_object(NULL), + m_object(nullptr), m_objectId(), - m_cellObject(NULL), + m_cellObject(nullptr), m_position_p(Vector::zero), m_position_w(Vector::zero), m_radius(0.0f), @@ -365,7 +365,7 @@ void AiLocation::setObject ( Object const * object ) { if(m_attached) { - if (object == NULL) + if (object == nullptr) { clear(); return; @@ -385,7 +385,7 @@ void AiLocation::setObject ( Object const * object ) void AiLocation::detach ( void ) { - m_object = NULL; + m_object = nullptr; m_objectId = NetworkId::cms_invalid; m_attached = false; } @@ -394,7 +394,7 @@ void AiLocation::detach ( void ) CellProperty const * AiLocation::getCell ( void ) const { - return m_cellObject ? m_cellObject->getCellProperty() : NULL; + return m_cellObject ? m_cellObject->getCellProperty() : nullptr; } // ---------- @@ -424,7 +424,7 @@ bool AiLocation::hasChanged ( void ) const Vector AiLocation::getPosition_p ( void ) const { - if(m_cellObject.getPointer() == NULL) + if(m_cellObject.getPointer() == nullptr) { WARNING(ConfigServerGame::getReportAiWarnings(),("AiLocation::getPosition_p - Locations's parent cell has disappeared\n")); @@ -572,8 +572,8 @@ void AiLocation::clear ( void ) m_valid = false; m_attached = false; - m_object = NULL; - m_cellObject = NULL; + m_object = nullptr; + m_cellObject = nullptr; m_position_p = Vector::zero; m_radius = 0.0f; m_offset_p = Vector::zero; @@ -585,7 +585,7 @@ void AiLocation::clear ( void ) bool AiLocation::isInWorldCell ( void ) const { - return isValid() && ( (getCell() == NULL) || (getCell() == CellProperty::getWorldCellProperty()) ); + return isValid() && ( (getCell() == nullptr) || (getCell() == CellProperty::getWorldCellProperty()) ); } @@ -599,7 +599,7 @@ bool AiLocation::validate ( void ) const TerrainObject * terrain = TerrainObject::getInstance(); - if(terrain == NULL) return true; + if(terrain == nullptr) return true; float w = terrain->getMapWidthInMeters() / 2.0f; diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipAttackTargetList.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipAttackTargetList.cpp index 08958488..9af5e0c8 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipAttackTargetList.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipAttackTargetList.cpp @@ -159,7 +159,7 @@ void AiShipAttackTargetList::add(ShipObject & unit, float const damage) AiShipController * const ownerAiShipController = AiShipController::asAiShipController(m_owner->getController()); - if (ownerAiShipController != NULL) + if (ownerAiShipController != nullptr) { if (!ownerAiShipController->isValidTarget(unit)) { @@ -204,7 +204,7 @@ void AiShipAttackTargetList::add(ShipObject & unit, float const damage) ShipController * const attackingUnitShipController = unit.getController()->asShipController(); - if (attackingUnitShipController != NULL) + if (attackingUnitShipController != nullptr) { attackingUnitShipController->addAiTargetingMe(m_owner->getNetworkId()); } @@ -217,7 +217,7 @@ void AiShipAttackTargetList::add(ShipObject & unit, float const damage) // ---------------------------------------------------------------------- bool AiShipAttackTargetList::remove(NetworkId const & unit, bool const inDestructorHack) { - DEBUG_FATAL((unit == NetworkId::cms_invalid), ("Removing a NULL unit")); + DEBUG_FATAL((unit == NetworkId::cms_invalid), ("Removing a nullptr unit")); bool result = false; @@ -238,11 +238,11 @@ bool AiShipAttackTargetList::remove(NetworkId const & unit, bool const inDestruc // Tell this unit that we are no longer targeting it - if (object != NULL) + if (object != nullptr) { ShipController * const shipController = object->getController()->asShipController(); - if (shipController != NULL) + if (shipController != nullptr) { shipController->removeAiTargetingMe(m_owner->getNetworkId()); } @@ -398,12 +398,12 @@ void AiShipAttackTargetList::findNewPrimaryTarget() // We should only have ship objects in our target list - if (m_primaryTarget.getObject() != NULL) + if (m_primaryTarget.getObject() != nullptr) { ServerObject * const targetServerObject = m_primaryTarget.getObject()->asServerObject(); - ShipObject * const targetShipObject = (targetServerObject != NULL) ? targetServerObject->asShipObject() : NULL; + ShipObject * const targetShipObject = (targetServerObject != nullptr) ? targetServerObject->asShipObject() : nullptr; - if (targetShipObject == NULL) + if (targetShipObject == nullptr) { DEBUG_WARNING(true, ("debug_ai: AiShipAttackTargetList::findNewPrimaryTarget() ERROR: How did we get a target that is not a ShipObject (%s)", m_primaryTarget.getObject()->getDebugInformation().c_str())); } @@ -444,7 +444,7 @@ void AiShipAttackTargetList::verify() AiShipController * const ownerAiShipController = AiShipController::asAiShipController(m_owner->getController()); - if (ownerAiShipController != NULL) + if (ownerAiShipController != nullptr) { if (ownerAiShipController->hasExclusiveAggros()) { @@ -457,9 +457,9 @@ void AiShipAttackTargetList::verify() for (; iterTargetList != m_targetList->end(); ++iterTargetList) { ShipObject * const unitShipObject = ShipObject::asShipObject(iterTargetList->first.getObject()); - CreatureObject const * const unitPilot = (unitShipObject != NULL) ? unitShipObject->getPilot() : NULL; + CreatureObject const * const unitPilot = (unitShipObject != nullptr) ? unitShipObject->getPilot() : nullptr; - if ( (unitPilot == NULL) + if ( (unitPilot == nullptr) || !ownerAiShipController->isExclusiveAggro(*unitPilot)) { s_purgeList.push_back(unitShipObject->getNetworkId()); diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackBomber.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackBomber.cpp index 239342d3..58e90c58 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackBomber.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackBomber.cpp @@ -56,7 +56,7 @@ AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber(AiShipController & aiShip m_evadeChangeDirectionTimer(0.5f), m_missilesFired(0) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber() unit(%s)", (aiShipController.getOwner() != NULL) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber() unit(%s)", (aiShipController.getOwner() != nullptr) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); } // ---------------------------------------------------------------------- @@ -73,7 +73,7 @@ AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber(AiShipBehaviorAttack cons m_evadeChangeDirectionTimer(0.5f), m_missilesFired(0) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber(AiShipBehaviorAttack &) unit(%s)", (m_aiShipController.getOwner() != NULL) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackBomber::AiShipBehaviorAttackBomber(AiShipBehaviorAttack &) unit(%s)", (m_aiShipController.getOwner() != nullptr) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); } // ---------------------------------------------------------------------- @@ -293,7 +293,7 @@ ShipObject const * AiShipBehaviorAttackBomber::getTargetCapitalShip() const return targetShipObject; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackCapitalShip.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackCapitalShip.cpp index d771b837..a1fe30da 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackCapitalShip.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackCapitalShip.cpp @@ -19,7 +19,7 @@ AiShipBehaviorAttackCapitalShip::AiShipBehaviorAttackCapitalShip(AiShipController & aiShipController) : AiShipBehaviorAttack(aiShipController) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackCapitalShip::AiShipBehaviorAttackCapitalShip() unit(%s)", (m_aiShipController.getOwner() != NULL) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackCapitalShip::AiShipBehaviorAttackCapitalShip() unit(%s)", (m_aiShipController.getOwner() != nullptr) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter.cpp index 166eda11..d43510a4 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter.cpp @@ -145,7 +145,7 @@ Vector const AiShipBehaviorAttackFighter::calculateEvadePositionWithinLeashDista AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter(AiShipController & aiShipController) : AiShipBehaviorAttack(aiShipController) - , m_currentManeuver(NULL) + , m_currentManeuver(nullptr) , m_timeDelta(0.0f) , m_projectileTimer() , m_missileLockOnTimer() @@ -165,7 +165,7 @@ AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter(AiShipController & aiSh , m_shotErrorPosition_l() , m_nextShotPosition_w() { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter() unit(%s)", (aiShipController.getOwner() != NULL) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter() unit(%s)", (aiShipController.getOwner() != nullptr) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); initializeTimers(); calculateEvadeHealthPercent(); calculateNextProjectileShotPerfect(); @@ -178,7 +178,7 @@ AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter(AiShipController & aiSh AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter(AiShipBehaviorAttack const & sourceBehavior) : AiShipBehaviorAttack(sourceBehavior) - , m_currentManeuver(NULL) + , m_currentManeuver(nullptr) , m_timeDelta(0.0f) , m_projectileTimer() , m_missileLockOnTimer() @@ -198,7 +198,7 @@ AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter(AiShipBehaviorAttack co , m_shotErrorPosition_l() , m_nextShotPosition_w() { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter() unit(%s)", (getAiShipController().getOwner() != NULL) ? getAiShipController().getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::AiShipBehaviorAttackFighter() unit(%s)", (getAiShipController().getOwner() != nullptr) ? getAiShipController().getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); initializeTimers(); calculateEvadeHealthPercent(); calculateNextProjectileShotPerfect(); @@ -214,7 +214,7 @@ AiShipBehaviorAttackFighter::~AiShipBehaviorAttackFighter() delete m_targetInfo; delete m_currentManeuver; - m_currentManeuver = NULL; + m_currentManeuver = nullptr; } // ---------------------------------------------------------------------- @@ -265,7 +265,7 @@ void AiShipBehaviorAttackFighter::alterManeuver() } else { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::alterManeuver() owner(%s) Why does this ship in the attack state with a NULL attack target?", getAiShipController().getOwner()->getNetworkId().getValueString().c_str())); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorAttackFighter::alterManeuver() owner(%s) Why does this ship in the attack state with a nullptr attack target?", getAiShipController().getOwner()->getNetworkId().getValueString().c_str())); } if (overallHealthPercent > m_lastEvadeHealthPercent) @@ -347,7 +347,7 @@ void AiShipBehaviorAttackFighter::alterWeapons() if (!targetShipObject) { - DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: Why is the primary attack target NULL?", getAiShipController().getShipOwner()->getDebugInformation().c_str())); + DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: Why is the primary attack target nullptr?", getAiShipController().getShipOwner()->getDebugInformation().c_str())); return; } @@ -584,7 +584,7 @@ void AiShipBehaviorAttackFighter::alterTargetInformation() ShipObject & ownerShipObject = *NON_NULL(getAiShipController().getShipOwner()); ShipObject const * const targetShipObject = getAiShipController().getPrimaryAttackTargetShipObject(); - if (targetShipObject != NULL) + if (targetShipObject != nullptr) { //-- Set pilot data here. AiShipPilotData const * pilotData = NON_NULL(getAiShipController().getPilotData()); @@ -600,7 +600,7 @@ void AiShipBehaviorAttackFighter::alterTargetInformation() CreatureObject const * const targetPilot = targetShipObject->getPilot(); - m_targetInfo->m_playerControlled = (targetPilot != NULL) ? targetPilot->isPlayerControlled() : false; + m_targetInfo->m_playerControlled = (targetPilot != nullptr) ? targetPilot->isPlayerControlled() : false; // Cached target info. bool const includeMissiles = true; @@ -707,7 +707,7 @@ void AiShipBehaviorAttackFighter::alterTargetInformation() } else { - DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: The primary attack target is NULL.", ownerShipObject.getDebugInformation().c_str())); + DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: The primary attack target is nullptr.", ownerShipObject.getDebugInformation().c_str())); } } @@ -956,7 +956,7 @@ void AiShipBehaviorAttackFighter::calculateNextShotPosition_w() if (!targetShipObject) { - DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: Why is the primary attack target NULL?", getAiShipController().getShipOwner()->getDebugInformation().c_str())); + DEBUG_WARNING(true, ("debug_ai: unit(%s) ERROR: Why is the primary attack target nullptr?", getAiShipController().getShipOwner()->getDebugInformation().c_str())); return; } @@ -1014,7 +1014,7 @@ void AiShipBehaviorAttackFighter::addDebug(AiDebugString & aiDebugString) AiShipBehaviorAttackFighter::Maneuver::Path const * path = m_currentManeuver->getCurrentPath(); char pathSizeText[256]; - if (path != NULL) + if (path != nullptr) { snprintf(pathSizeText, sizeof(pathSizeText) - 1, "PATH(%d)", path->getLength()); } @@ -1027,7 +1027,7 @@ void AiShipBehaviorAttackFighter::addDebug(AiDebugString & aiDebugString) // Show the current maneuver { - char const * const text = FormattedString<512>().sprintf("attack[%s%s%s] %d %s\n", AiDebugString::getColorCode(PackedRgb::solidWhite).c_str(), (m_currentManeuver != NULL) ? m_currentManeuver->getFighterManeuverString() : "NULL", AiDebugString::getResetColorCode(), (m_currentManeuver != NULL) ? m_currentManeuver->getSequenceId() : -1, pathSizeText); + char const * const text = FormattedString<512>().sprintf("attack[%s%s%s] %d %s\n", AiDebugString::getColorCode(PackedRgb::solidWhite).c_str(), (m_currentManeuver != nullptr) ? m_currentManeuver->getFighterManeuverString() : "nullptr", AiDebugString::getResetColorCode(), (m_currentManeuver != nullptr) ? m_currentManeuver->getSequenceId() : -1, pathSizeText); aiDebugString.addText(text, PackedRgb::solidCyan); } @@ -1060,7 +1060,7 @@ void AiShipBehaviorAttackFighter::addDebug(AiDebugString & aiDebugString) // Show the maneuver path - if ( (path != NULL) + if ( (path != nullptr) && !path->isEmpty()) { AiDebugString::TransformList transformList; diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter_Maneuver.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter_Maneuver.cpp index 17fa39ea..c3b9d975 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter_Maneuver.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorAttackFighter_Maneuver.cpp @@ -72,7 +72,7 @@ AiShipBehaviorAttackFighter::Maneuver::~Maneuver() delete m_pathList; - //m_currentPath = NULL; + //m_currentPath = nullptr; } // ---------------------------------------------------------------------- @@ -128,7 +128,7 @@ void AiShipBehaviorAttackFighter::Maneuver::addPath(Path * const path) AiShipBehaviorAttackFighter::Maneuver::Path * AiShipBehaviorAttackFighter::Maneuver::getCurrentPath() { - Path * currentPath = NULL; + Path * currentPath = nullptr; if (!m_pathList->empty() && m_currentPath != m_pathList->end()) { @@ -230,7 +230,7 @@ void AiShipBehaviorAttackFighter::Maneuver::alterThrottle(float const /*timeDelt AiShipBehaviorAttackFighter::Maneuver * AiShipBehaviorAttackFighter::Maneuver::createManeuver(FighterManeuver const manueverType, AiShipBehaviorAttackFighter & aiShipBehaviorAttack, AiAttackTargetInformation const & targetInfo) { - Maneuver * aiManeuver = NULL; + Maneuver * aiManeuver = nullptr; switch(manueverType) { @@ -298,7 +298,7 @@ public: ShipObject const * const primaryTargetShipObject = getAiShipController().getPrimaryAttackTargetShipObject(); - if (primaryTargetShipObject != NULL) + if (primaryTargetShipObject != nullptr) { float const ownerShipRadius = getAiShipController().getShipOwner()->getRadius(); float const ownerTurnRadius = getAiShipController().getLargestTurnRadius(); @@ -337,7 +337,7 @@ protected: ShipObject const * const primaryTargetShipObject = getAiShipController().getPrimaryAttackTargetShipObject(); - if (primaryTargetShipObject != NULL) + if (primaryTargetShipObject != nullptr) { bool const facingTarget = m_aiShipBehaviorAttack.isFacingTarget(); @@ -450,7 +450,7 @@ private: { ShipObject const * const primaryTargetShipObject = getAiShipController().getPrimaryAttackTargetShipObject(); - if (primaryTargetShipObject != NULL) + if (primaryTargetShipObject != nullptr) { AiShipPilotData const & pilotData = *NON_NULL(getAiShipController().getPilotData()); float const currentSpeed = getAiShipController().getShipOwner()->getCurrentSpeed(); @@ -665,11 +665,11 @@ private: { ShipObject const * const primaryTargetShipObject = getAiShipController().getPrimaryAttackTargetShipObject(); - if (primaryTargetShipObject!= NULL) + if (primaryTargetShipObject!= nullptr) { ShipController const * const targetShipController = primaryTargetShipObject->getController()->asShipController(); - if (targetShipController != NULL) + if (targetShipController != nullptr) { Transform transform; Vector velocity; diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorDock.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorDock.cpp index e8c1aede..f023331c 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorDock.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorDock.cpp @@ -66,7 +66,7 @@ AiShipBehaviorDock::AiShipBehaviorDock(ShipController & shipController, ShipObje , m_goalPosition_w() , m_wingsOpenedBeforeDock(m_shipController.getShipOwner()->hasWings() && m_shipController.getShipOwner()->wingsOpened()) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipBehaviorDock: [1/6] unit(%s) dockTarget(%s) secondsAtDock(%.2f) landingHardPoint(%s)", (shipController.getOwner() != NULL) ? shipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner", dockTarget.getNetworkId().getValueString().c_str(), secondsAtDock, m_hasLandingHardPoint ? "yes" : "no")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipBehaviorDock: [1/6] unit(%s) dockTarget(%s) secondsAtDock(%.2f) landingHardPoint(%s)", (shipController.getOwner() != nullptr) ? shipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner", dockTarget.getNetworkId().getValueString().c_str(), secondsAtDock, m_hasLandingHardPoint ? "yes" : "no")); if (m_shipController.isBeingDocked()) { @@ -119,7 +119,7 @@ AiShipBehaviorDock::AiShipBehaviorDock(ShipController & shipController, ShipObje ShipController * const dockTargetShipController = dockTarget.getController()->asShipController(); - if (dockTargetShipController != NULL) + if (dockTargetShipController != nullptr) { dockTargetShipController->addDockedBy(*shipController.getOwner()); } @@ -146,7 +146,7 @@ AiShipBehaviorDock::AiShipBehaviorDock(ShipController & shipController, ShipObje m_initialApproachHardPointCount = static_cast(m_approachHardPointList->size()); - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipBehaviorDock() unit(%s) dockTarget(%s) approachHardPointCount(%u) exitHardPointCount(%u)", (shipController.getOwner() != NULL) ? shipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner", dockTarget.getNetworkId().getValueString().c_str(), m_approachHardPointList->size(), m_exitHardPointList->size())); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipBehaviorDock() unit(%s) dockTarget(%s) approachHardPointCount(%u) exitHardPointCount(%u)", (shipController.getOwner() != nullptr) ? shipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner", dockTarget.getNetworkId().getValueString().c_str(), m_approachHardPointList->size(), m_exitHardPointList->size())); } // ---------------------------------------------------------------------- @@ -156,7 +156,7 @@ AiShipBehaviorDock::~AiShipBehaviorDock() // Open the wings - if ( (ownerShipObject != NULL) + if ( (ownerShipObject != nullptr) && m_wingsOpenedBeforeDock) { m_shipController.getShipOwner()->openWings(); @@ -168,7 +168,7 @@ AiShipBehaviorDock::~AiShipBehaviorDock() { CollisionCallbackManager::removeIgnoreIntersect(m_shipController.getOwner()->getNetworkId(), m_dockTarget); - if ( (ownerShipObject != NULL) + if ( (ownerShipObject != nullptr) && ownerShipObject->isPlayerShip()) { m_shipController.appendMessage(CM_removeIgnoreIntersect, 0.0f, new MessageQueueGenericValueType(m_dockTarget), GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); @@ -179,11 +179,11 @@ AiShipBehaviorDock::~AiShipBehaviorDock() Object * const dockTarget = m_dockTarget.getObject(); - if (dockTarget != NULL) + if (dockTarget != nullptr) { ShipController * const dockTargetShipController = dockTarget->getController()->asShipController(); - if (dockTargetShipController != NULL) + if (dockTargetShipController != nullptr) { dockTargetShipController->removeDockedBy(*m_shipController.getOwner()); } @@ -200,7 +200,7 @@ void AiShipBehaviorDock::alter(float deltaSeconds) bool abortDocking = false; - if (m_dockTarget.getObject() == NULL) + if (m_dockTarget.getObject() == nullptr) { // If we lose the dock target, fail the docking procedure. @@ -213,7 +213,7 @@ void AiShipBehaviorDock::alter(float deltaSeconds) AiShipController * const dockTargetAiShipController = AiShipController::asAiShipController(m_dockTarget.getObject()->getController()); - if ( (dockTargetAiShipController != NULL) + if ( (dockTargetAiShipController != nullptr) && dockTargetAiShipController->isAttacking()) { LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "debug_ai", ("AiShipBehaviorDock::alter() unit(%s) dockTarget(%s) DOCK TARGET IS ATTACKING...UNDOCKING", m_shipController.getOwner()->getDebugInformation().c_str(), m_dockTarget.getValueString().c_str())); @@ -478,7 +478,7 @@ void AiShipBehaviorDock::triggerDocked() GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_shipController.getOwner()); - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; scriptParams.addParam(m_dockTarget); @@ -499,7 +499,7 @@ void AiShipBehaviorDock::triggerStartUnDock() GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_shipController.getOwner()); - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; scriptParams.addParam(m_dockTarget); @@ -520,7 +520,7 @@ void AiShipBehaviorDock::triggerUnDockWithSuccess() GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_shipController.getOwner()); - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; scriptParams.addParam(m_dockTarget); @@ -542,7 +542,7 @@ void AiShipBehaviorDock::triggerUnDockWithFailure() GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_shipController.getOwner()); - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; scriptParams.addParam(m_dockTarget); @@ -622,7 +622,7 @@ float AiShipBehaviorDock::getMaxTractorBeamSpeed() const float const shipActualSpeedMaximum = m_shipController.getShipOwner()->getShipActualSpeedMaximum(); AiShipController * const aiShipController = m_shipController.asAiShipController(); - return (aiShipController != NULL) ? (shipActualSpeedMaximum * aiShipController->getPilotData()->m_nonCombatMaxSpeedPercent) : shipActualSpeedMaximum; + return (aiShipController != nullptr) ? (shipActualSpeedMaximum * aiShipController->getPilotData()->m_nonCombatMaxSpeedPercent) : shipActualSpeedMaximum; } // ---------------------------------------------------------------------- @@ -676,7 +676,7 @@ void AiShipBehaviorDock::addDebug(AiDebugString & aiDebugString) aiDebugString.addLineToPosition(m_goalPosition_w, PackedRgb::solidCyan); - if (m_dockTarget.getObject() != NULL) + if (m_dockTarget.getObject() != nullptr) { Transform transform; transform.multiply(m_dockTarget.getObject()->getTransform_o2w(), m_dockHardPoint); diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorFollow.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorFollow.cpp index dedc3fda..e8ca1bd5 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorFollow.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorFollow.cpp @@ -45,9 +45,9 @@ AiShipBehaviorFollow::AiShipBehaviorFollow(AiShipController & aiShipController, , m_followedUnit(followedUnit) , m_followedUnitLost(false) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorFollow::AiShipBehaviorFollow() unit(%s) followedUnit(%s)", (m_aiShipController.getOwner() != NULL) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner", followedUnit.getValueString().c_str())); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorFollow::AiShipBehaviorFollow() unit(%s) followedUnit(%s)", (m_aiShipController.getOwner() != nullptr) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner", followedUnit.getValueString().c_str())); - DEBUG_WARNING((m_followedUnit.getObject() == NULL), ("Trying to follow a NULL object.")); + DEBUG_WARNING((m_followedUnit.getObject() == nullptr), ("Trying to follow a nullptr object.")); } // ---------------------------------------------------------------------- @@ -60,7 +60,7 @@ void AiShipBehaviorFollow::alter(float const deltaSeconds) Object * const followedUnitObject = m_followedUnit.getObject(); Vector goalPosition_w; - if (followedUnitObject != NULL) + if (followedUnitObject != nullptr) { goalPosition_w = Formation::getPosition_w(followedUnitObject->getTransform_o2w(), m_aiShipController.getFormationPosition_l()); @@ -69,9 +69,9 @@ void AiShipBehaviorFollow::alter(float const deltaSeconds) if (m_aiShipController.getOwner()->getPosition_w().magnitudeBetweenSquared(goalPosition_w) > sqr(m_aiShipController.getLargestTurnRadius() * slowDownRequestRadiusGain)) { ShipController * const shipController = followedUnitObject->getController()->asShipController(); - AiShipController * const aiShipController = (shipController != NULL) ? shipController->asAiShipController() : NULL; + AiShipController * const aiShipController = (shipController != nullptr) ? shipController->asAiShipController() : nullptr; - if (aiShipController != NULL) + if (aiShipController != nullptr) { aiShipController->requestSlowDown(); } @@ -90,7 +90,7 @@ void AiShipBehaviorFollow::alter(float const deltaSeconds) Object const * const object = m_aiShipController.getOwner(); - if (object != NULL) + if (object != nullptr) { goalPosition_w = object->getPosition_w(); } @@ -109,10 +109,10 @@ void AiShipBehaviorFollow::alter(float const deltaSeconds) void AiShipBehaviorFollow::triggerFollowedUnitLost() { Object * object = m_aiShipController.getOwner(); - ServerObject *serverObject = (object != NULL) ? object->asServerObject() : NULL; - GameScriptObject * gameScriptObject = (serverObject != NULL) ? serverObject->getScriptObject() : NULL; + ServerObject *serverObject = (object != nullptr) ? object->asServerObject() : nullptr; + GameScriptObject * gameScriptObject = (serverObject != nullptr) ? serverObject->getScriptObject() : nullptr; - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; scriptParams.addParam(m_followedUnit); diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorIdle.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorIdle.cpp index 14d8253c..1654e5c8 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorIdle.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorIdle.cpp @@ -25,7 +25,7 @@ AiShipBehaviorIdle::AiShipBehaviorIdle(AiShipController & aiShipController) : AiShipBehaviorBase(aiShipController) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorIdle() unit(%s)", (m_aiShipController.getOwner() != NULL) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorIdle() unit(%s)", (m_aiShipController.getOwner() != nullptr) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner")); } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorTrack.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorTrack.cpp index 68a47863..c1aa8506 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorTrack.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorTrack.cpp @@ -27,7 +27,7 @@ AiShipBehaviorTrack::AiShipBehaviorTrack(AiShipController & aiShipController, Ob : AiShipBehaviorBase(aiShipController) , m_target(&target) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorTrack() unit(%s) target(%s)", (m_aiShipController.getOwner() != NULL) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner", target.getNetworkId().getValueString().c_str())); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorTrack() unit(%s) target(%s)", (m_aiShipController.getOwner() != nullptr) ? m_aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner", target.getNetworkId().getValueString().c_str())); } // ---------------------------------------------------------------------- @@ -36,7 +36,7 @@ void AiShipBehaviorTrack::alter(float deltaSeconds) { PROFILER_AUTO_BLOCK_DEFINE("AiShipBehaviorTrack::alter"); - if (m_target != NULL) + if (m_target != nullptr) { IGNORE_RETURN(m_aiShipController.face(m_target->getPosition_w(), deltaSeconds)); } diff --git a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorWaypoint.cpp b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorWaypoint.cpp index f68335b9..6302a8f9 100755 --- a/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorWaypoint.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/AiShipBehaviorWaypoint.cpp @@ -35,7 +35,7 @@ AiShipBehaviorWaypoint::AiShipBehaviorWaypoint(AiShipController & aiShipControll , m_cyclic(cyclic) , m_moveToCompleteTriggerSent(false) { - LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorWaypoint::AiShipBehaviorWaypoint() unit(%s) cyclic(%s)", (aiShipController.getOwner() != NULL) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "NULL owner", cyclic ? "yes" : "no")); + LOGC(ConfigServerGame::isSpaceAiLoggingEnabled(), "space_debug_ai", ("AiShipBehaviorWaypoint::AiShipBehaviorWaypoint() unit(%s) cyclic(%s)", (aiShipController.getOwner() != nullptr) ? aiShipController.getOwner()->getNetworkId().getValueString().c_str() : "nullptr owner", cyclic ? "yes" : "no")); } // ---------------------------------------------------------------------- @@ -61,7 +61,7 @@ void AiShipBehaviorWaypoint::alter(float deltaSeconds) { SpacePath const * const path = m_aiShipController.getPath(); - if ( (path != NULL) + if ( (path != nullptr) && !m_cyclic && (m_aiShipController.getCurrentPathIndex() == (path->getTransformList().size() - 1))) { @@ -76,7 +76,7 @@ void AiShipBehaviorWaypoint::alter(float deltaSeconds) GameScriptObject * const gameScriptObject = GameScriptObject::asGameScriptObject(m_aiShipController.getOwner()); - if(gameScriptObject != NULL) + if(gameScriptObject != nullptr) { ScriptParams scriptParams; IGNORE_RETURN(gameScriptObject->trigAllScripts(Scripting::TRIG_SPACE_UNIT_MOVE_TO_COMPLETE, scriptParams)); @@ -104,13 +104,13 @@ bool AiShipBehaviorWaypoint::getNextPosition_w(Vector & position_w) SpacePath * const path = m_aiShipController.getPath(); - if ( (path != NULL) + if ( (path != nullptr) && !path->isEmpty() && (m_aiShipController.getCurrentPathIndex() < path->getTransformList().size())) { ShipObject const * const shipObject = m_aiShipController.getShipOwner(); - if (shipObject != NULL) + if (shipObject != nullptr) { SpacePath::TransformList const & transformList = path->getTransformList(); Vector const & nextPosition = getGoalPosition_w(); @@ -166,7 +166,7 @@ Vector AiShipBehaviorWaypoint::getGoalPosition_w() const SpacePath * const path = m_aiShipController.getPath(); - if ( (path != NULL) + if ( (path != nullptr) && !path->isEmpty()) { SpacePath::TransformList const & transformList = path->getTransformList(); @@ -245,7 +245,7 @@ void AiShipBehaviorWaypoint::addDebug(AiDebugString & aiDebugString) { SpacePath const * const path = m_aiShipController.getPath(); - if (path != NULL) + if (path != nullptr) { aiDebugString.addLineToPosition(m_aiShipController.getMoveToGoalPosition_w(), PackedRgb::solidGreen); aiDebugString.addCircle(m_aiShipController.getMoveToGoalPosition_w(), m_aiShipController.getLargestTurnRadius(), PackedRgb::solidGreen); diff --git a/engine/server/library/serverGame/src/shared/behavior/ShipTurretTargetingSystem.cpp b/engine/server/library/serverGame/src/shared/behavior/ShipTurretTargetingSystem.cpp index 23cbc81f..cf1af6f8 100755 --- a/engine/server/library/serverGame/src/shared/behavior/ShipTurretTargetingSystem.cpp +++ b/engine/server/library/serverGame/src/shared/behavior/ShipTurretTargetingSystem.cpp @@ -124,7 +124,7 @@ void ShipTurretTargetingSystem::onTargetLost(NetworkId const & target) ShipObject * const shipObject = NON_NULL(NON_NULL(NON_NULL(m_shipController.getOwner())->asServerObject())->asShipObject()); if (!shipObject) // for release builds { - WARNING(true,("Programmer bug: got a NULL ShipObject in ShipTurretTargetingSystem::onTargetLost(). May indicate that the ShipObject has already been partially deconstructed.")); + WARNING(true,("Programmer bug: got a nullptr ShipObject in ShipTurretTargetingSystem::onTargetLost(). May indicate that the ShipObject has already been partially deconstructed.")); return; } @@ -168,7 +168,7 @@ bool ShipTurretTargetingSystem::buildTargetList() bool result = false; m_targetList->clear(); - if (ownerShipController != NULL) + if (ownerShipController != nullptr) { if (!ownerShipController->getAttackTargetList().isEmpty()) { diff --git a/engine/server/library/serverGame/src/shared/collision/CollisionCallbacks.cpp b/engine/server/library/serverGame/src/shared/collision/CollisionCallbacks.cpp index 99c4f3cb..9bce1404 100755 --- a/engine/server/library/serverGame/src/shared/collision/CollisionCallbacks.cpp +++ b/engine/server/library/serverGame/src/shared/collision/CollisionCallbacks.cpp @@ -86,7 +86,7 @@ void CollisionCallbacksNamespace::remove() int CollisionCallbacksNamespace::convertObjectToIndex(Object * const object) { - FATAL(!object, ("CollisionCallbacksNamespace::convertObjectToIndex: object == NULL.")); + FATAL(!object, ("CollisionCallbacksNamespace::convertObjectToIndex: object == nullptr.")); ServerObject const * serverObject = object->asServerObject(); if (serverObject) @@ -99,11 +99,11 @@ int CollisionCallbacksNamespace::convertObjectToIndex(Object * const object) bool CollisionCallbacksNamespace::onHitDoCollisionWith(Object * const object, Object * const wasHitByThisObject) { - DEBUG_WARNING(!object, ("CollisionCallbacksNamespace::onHitDoCollisionWith: Object == NULL")); - DEBUG_WARNING(!wasHitByThisObject, ("CollisionCallbacksNamespace::onHitDoCollisionWith: wasHitByThisObject == NULL")); + DEBUG_WARNING(!object, ("CollisionCallbacksNamespace::onHitDoCollisionWith: Object == nullptr")); + DEBUG_WARNING(!wasHitByThisObject, ("CollisionCallbacksNamespace::onHitDoCollisionWith: wasHitByThisObject == nullptr")); ShipObject * shipObject = safe_cast(object); - DEBUG_WARNING(!shipObject, ("CollisionCallbacksNamespace::onHitDoCollisionWith: shipObject == NULL")); + DEBUG_WARNING(!shipObject, ("CollisionCallbacksNamespace::onHitDoCollisionWith: shipObject == nullptr")); CollisionCallbackManager::Result result; if (CollisionCallbackManager::intersectAndReflect(object, wasHitByThisObject, result)) @@ -123,10 +123,10 @@ bool CollisionCallbacksNamespace::onHitDoCollisionWith(Object * const object, Ob bool CollisionCallbacksNamespace::onDoCollisionWithTerrain(Object * const object) { - DEBUG_FATAL (!object, ("CollisionCallbacksNamespace::onDoCollisionWithTerrain: Object == NULL")); + DEBUG_FATAL (!object, ("CollisionCallbacksNamespace::onDoCollisionWithTerrain: Object == nullptr")); ShipObject * shipObject = safe_cast(object); - DEBUG_FATAL (!shipObject, ("CollisionCallbacksNamespace::onDoCollisionWithTerrain: shipObject == NULL")); + DEBUG_FATAL (!shipObject, ("CollisionCallbacksNamespace::onDoCollisionWithTerrain: shipObject == nullptr")); CollisionCallbackManager::Result result; if (CollisionCallbackManager::intersectAndReflectWithTerrain(object, result)) diff --git a/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp b/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp index ff3f058c..54e165fb 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp +++ b/engine/server/library/serverGame/src/shared/command/CommandCppFuncs.cpp @@ -145,21 +145,21 @@ namespace CommandCppFuncsNamespace void internalSetBoosterOnOff(NetworkId const & actor, bool onOff) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - - if (actorCreature == NULL) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + + if (actorCreature == nullptr) return; - + ShipObject * const shipObject = actorCreature->getPilotedShip(); - if (shipObject == NULL) + if (shipObject == nullptr) return; - + if (!shipObject->isSlotInstalled(ShipChassisSlotType::SCST_booster)) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::no_booster, Unicode::emptyString); return; } - + if (!shipObject->isComponentFunctional(ShipChassisSlotType::SCST_booster)) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::booster_disabled, Unicode::emptyString); @@ -167,7 +167,7 @@ namespace CommandCppFuncsNamespace } if (onOff && shipObject->getBoosterEnergyCurrent() < shipObject->getBoosterEnergyRechargeRate()) - { + { Chat::sendSystemMessage(*actorCreature, SharedStringIds::booster_low_energy, Unicode::emptyString); return; } @@ -196,38 +196,37 @@ namespace CommandCppFuncsNamespace return o; } - ShipObject *getAttachedShip(CreatureObject *creature) { // The "attached" ship is the ship which must move along with the creature. // This means if the creature is piloting, the ship is is piloting, // or the containing ship if the creature is the ship's owner. ShipObject * const ship = ShipObject::getContainingShipObject(creature); - if ( ship - && ( ship->getOwnerId() == creature->getNetworkId() - || creature->getPilotedShip() == ship)) + if (ship + && (ship->getOwnerId() == creature->getNetworkId() + || creature->getPilotedShip() == ship)) return ship; return 0; } CreatureObject * findAndResolveCreatureByNetworkId(NetworkId const & targetId) { - CreatureObject * targetCreatureObject = NULL; + CreatureObject * targetCreatureObject = nullptr; { // find the target. the target could be either a creature or ship ServerObject * const serverObject = ServerWorld::findObjectByNetworkId(targetId); - targetCreatureObject = (serverObject != NULL) ? serverObject->asCreatureObject() : NULL; + targetCreatureObject = (serverObject != nullptr) ? serverObject->asCreatureObject() : nullptr; - if (targetCreatureObject == NULL) + if (targetCreatureObject == nullptr) { - ShipObject * const shipObject = (serverObject != NULL) ? serverObject->asShipObject() : NULL; + ShipObject * const shipObject = (serverObject != nullptr) ? serverObject->asShipObject() : nullptr; - if (shipObject != NULL) + if (shipObject != nullptr) { targetCreatureObject = shipObject->getPilot(); - if (targetCreatureObject == NULL) + if (targetCreatureObject == nullptr) { // this means that it is a POB ship that doesn't have a pilot // in this case we find the owner @@ -237,7 +236,7 @@ namespace CommandCppFuncsNamespace std::vector::const_iterator ii = passengers.begin(); std::vector::const_iterator iiEnd = passengers.end(); - for (; ii != iiEnd && targetCreatureObject == NULL; ++ii) + for (; ii != iiEnd && targetCreatureObject == nullptr; ++ii) { if ((*ii)->getNetworkId() == shipObject->getOwnerId()) { @@ -263,9 +262,9 @@ namespace CommandCppFuncsNamespace for (ContainerConstIterator i = container->begin(); i != container->end(); ++i) { ServerObject const * const content = safe_cast((*i).getObject()); - if ( content - && content->getGameObjectType() == SharedObjectTemplate::GOT_data_ship_control_device - && !content->isBeingDestroyed()) + if (content + && content->getGameObjectType() == SharedObjectTemplate::GOT_data_ship_control_device + && !content->isBeingDestroyed()) { Container const * const scdContainer = ContainerInterface::getContainer(*content); if (scdContainer) @@ -290,7 +289,7 @@ namespace CommandCppFuncsNamespace Container::ContainerErrorCode errorCode = Container::CEC_Success; for (std::vector >::const_iterator i = oldItems.begin(); i != oldItems.end(); ++i) { - IGNORE_RETURN(ContainerInterface::transferItemToSlottedContainer(destination, *((*i).first), (*i).second, NULL, errorCode)); + IGNORE_RETURN(ContainerInterface::transferItemToSlottedContainer(destination, *((*i).first), (*i).second, nullptr, errorCode)); } } @@ -310,20 +309,20 @@ namespace CommandCppFuncsNamespace { bool creatureIsContainedInPOBShip(CreatureObject const * creatureObject); void removeFromGroupAndCreatePOBGroup(GroupObject * groupToRemoveFrom, - GroupMemberParam const & leader, - GroupObject::GroupMemberParamVector & membersInsidePOB); + GroupMemberParam const & leader, + GroupObject::GroupMemberParamVector & membersInsidePOB); // The owner of the POB ship is not included in the inside POB member lists void separateGroupBasedOffofPOBShip(GroupObject * groupObj, - NetworkId const & ownerOfThePOBShipId, - NetworkId const & POBShipId, - GroupObject::GroupMemberParamVector & membersInsidePOB, - GroupObject::GroupMemberParamVector & membersOutsidePOB); + NetworkId const & ownerOfThePOBShipId, + NetworkId const & POBShipId, + GroupObject::GroupMemberParamVector & membersInsidePOB, + GroupObject::GroupMemberParamVector & membersOutsidePOB); TravelPoint const * getNearestTravelPoint(std::string const & planetName, Vector const & location, std::vector const & cityBanList, uint32 faction, bool starPortAndShuttleportOnly); } void triggerSpaceEjectPlayerFromShip(CreatureObject * creatureObject); - + int const cs_spaceSpeechMultiple = 10; } @@ -340,8 +339,8 @@ bool CommandCppFuncsNamespace::GroupHelpers::creatureIsContainedInPOBShip(Creatu // ---------------------------------------------------------------------- void CommandCppFuncsNamespace::GroupHelpers::removeFromGroupAndCreatePOBGroup(GroupObject * const groupToRemoveFrom, - GroupMemberParam const & leader, - GroupObject::GroupMemberParamVector & membersInsidePOB) + GroupMemberParam const & leader, + GroupObject::GroupMemberParamVector & membersInsidePOB) { if (groupToRemoveFrom != 0) { @@ -372,10 +371,10 @@ void CommandCppFuncsNamespace::GroupHelpers::removeFromGroupAndCreatePOBGroup(Gr // The owner of the POB ship is not included in the inside POB member lists void CommandCppFuncsNamespace::GroupHelpers::separateGroupBasedOffofPOBShip(GroupObject * const groupObj, - NetworkId const & ownerOfThePOBShipId, - NetworkId const & POBShipId, - GroupObject::GroupMemberParamVector & membersInsidePOB, - GroupObject::GroupMemberParamVector & membersOutsidePOB) + NetworkId const & ownerOfThePOBShipId, + NetworkId const & POBShipId, + GroupObject::GroupMemberParamVector & membersInsidePOB, + GroupObject::GroupMemberParamVector & membersOutsidePOB) { NOT_NULL(groupObj); @@ -411,20 +410,20 @@ void CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip(CreatureObject * { if (creatureObject == 0) { - WARNING(true, ("CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip: NULL CreatureObject.")); + WARNING(true, ("CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip: nullptr CreatureObject.")); return; } GameScriptObject * gameScriptObject = creatureObject->getScriptObject(); - if(gameScriptObject != 0) + if (gameScriptObject != 0) { ScriptParams scriptParams; IGNORE_RETURN(gameScriptObject->trigAllScripts(Scripting::TRIG_SPACE_EJECT_PLAYER_FROM_SHIP, scriptParams)); } else { - WARNING(true, ("CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip: NULL ScriptObject.")); + WARNING(true, ("CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip: nullptr ScriptObject.")); } } @@ -432,7 +431,7 @@ void CommandCppFuncsNamespace::triggerSpaceEjectPlayerFromShip(CreatureObject * TravelPoint const * CommandCppFuncsNamespace::GroupHelpers::getNearestTravelPoint(std::string const & planetName, Vector const & location, std::vector const & cityBanList, uint32 faction, bool starPortAndShuttleportOnly) { - TravelPoint const * nearestTravelPoint = NULL; + TravelPoint const * nearestTravelPoint = nullptr; PlanetObject const * const planetObject = ServerUniverse::getInstance().getPlanetByName(planetName); if (planetObject) { @@ -484,7 +483,7 @@ static const std::string OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER("players_can_access static void sendProseMessage(const CreatureObject &actor, const ServerObject * const target, StringId const &stringId) { - Chat::sendSystemMessageSimple (actor, stringId, target); + Chat::sendSystemMessageSimple(actor, stringId, target); } // ====================================================================== @@ -504,7 +503,7 @@ static std::string nextStringParm(Unicode::String const &str, size_t &curpos) size_t endpos = 0; Unicode::String token; if (!Unicode::getFirstToken(str, curpos, endpos, token)) - return std::string (); + return std::string(); curpos = endpos; return Unicode::wideToNarrow(token); } @@ -537,10 +536,9 @@ static NetworkId nextOidParm(Unicode::String const &str, size_t &curpos) static float nextFloatParm(Unicode::String const &str, size_t &curpos) { - return static_cast(strtod(nextStringParm(str, curpos).c_str(), NULL)); + return static_cast(strtod(nextStringParm(str, curpos).c_str(), nullptr)); } - // ---------------------------------------------------------------------- static bool nextBoolParm(Unicode::String const &str, size_t &curpos) @@ -552,11 +550,11 @@ static bool nextBoolParm(Unicode::String const &str, size_t &curpos) static Vector nextVectorParm(Unicode::String const &str, size_t &curpos) { - float x=nextFloatParm(str,curpos); - float y=nextFloatParm(str,curpos); - float z=nextFloatParm(str,curpos); + float x = nextFloatParm(str, curpos); + float y = nextFloatParm(str, curpos); + float z = nextFloatParm(str, curpos); - return Vector(x,y,z); + return Vector(x, y, z); } // ====================================================================== @@ -574,7 +572,7 @@ static void commandFuncConsoleAll(Command const &command, NetworkId const &actor Client *client = obj->getClient(); if (client && client->isGod()) { - LOG("CustomerService",("Avatar:%s executing command: %s", PlayerObject::getAccountDescription(client->getCharacterObjectId()).c_str(), Unicode::wideToNarrow(params).c_str())); + LOG("CustomerService", ("Avatar:%s executing command: %s", PlayerObject::getAccountDescription(client->getCharacterObjectId()).c_str(), Unicode::wideToNarrow(params).c_str())); ConsoleMgr::processString(Unicode::wideToNarrow(params), client, 0); } } @@ -736,7 +734,7 @@ static void commandFuncAdminSetGodMode(Command const &, NetworkId const &actor, // ---------------------------------------------------------------------- static void commandFuncResetCooldowns(Command const &, NetworkId const &actor, - NetworkId const &, Unicode::String const ¶ms) + NetworkId const &, Unicode::String const ¶ms) { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (actorObj) @@ -748,7 +746,7 @@ static void commandFuncResetCooldowns(Command const &, NetworkId const &actor, // ---------------------------------------------------------------------- static void commandFuncSpewCommandQueue(Command const &, NetworkId const &actor, - NetworkId const &, Unicode::String const ¶ms) + NetworkId const &, Unicode::String const ¶ms) { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (actorObj) @@ -780,14 +778,14 @@ static void commandFuncAdminKick(Command const &, NetworkId const &actor, // If the target is a ship, kick all the people in the ship std::vector passengers; shipObject->findAllPassengers(passengers, true); - for (std::vector::const_iterator i=passengers.begin(); i!=passengers.end(); ++i) + for (std::vector::const_iterator i = passengers.begin(); i != passengers.end(); ++i) { KickPlayer const kickMessage((*i)->getNetworkId(), "Admin Kick"); GameServer::getInstance().sendToConnectionServers(kickMessage); } } else - { + { KickPlayer const kickMessage(who, "Admin Kick"); GameServer::getInstance().sendToConnectionServers(kickMessage); } @@ -821,7 +819,7 @@ static void commandFuncLocateStructure(Command const &, NetworkId const &actor, ownerId = actor; } - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!isGod && actorObj->getObjVars().hasItem("timeNextLocateStructureCommandAllowed") && (actorObj->getObjVars().getType("timeNextLocateStructureCommandAllowed") == DynamicVariable::INT)) { int timeNextLocateStructureCommandAllowed = 0; @@ -889,7 +887,7 @@ static void commandFuncLocateVendor(Command const &, NetworkId const &actor, Net ownerId = actor; } - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!isGod && actorObj->getObjVars().hasItem("timeNextLocateVendorCommandAllowed") && (actorObj->getObjVars().getType("timeNextLocateVendorCommandAllowed") == DynamicVariable::INT)) { int timeNextLocateVendorCommandAllowed = 0; @@ -956,7 +954,7 @@ static void commandFuncShowCtsHistory(Command const &, NetworkId const &actor, N if (target != actor) { targetObj = dynamic_cast(ServerWorld::findObjectByNetworkId(target)); - targetPlayerObj = (targetObj ? PlayerCreatureController::getPlayerObject(targetObj) : NULL); + targetPlayerObj = (targetObj ? PlayerCreatureController::getPlayerObject(targetObj) : nullptr); if (!targetPlayerObj) { ConsoleMgr::broadcastString(FormattedString<1024>().sprintf("%s is not a valid or nearby player character.", target.getValueString().c_str()), clientObj); @@ -980,7 +978,7 @@ static void commandFuncShowCtsHistory(Command const &, NetworkId const &actor, N if (i.getValue(ctsTransactionDetail)) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(ctsTransactionDetail, tokens, NULL, NULL) && (tokens.size() >= 4)) + if (Unicode::tokenize(ctsTransactionDetail, tokens, nullptr, nullptr) && (tokens.size() >= 4)) { Unicode::String characterName; for (size_t i = 3, j = tokens.size(); i < j; ++i) @@ -998,7 +996,7 @@ static void commandFuncShowCtsHistory(Command const &, NetworkId const &actor, N if (orderedCtsHistory.empty()) { - ConsoleMgr::broadcastString("No CTS history found.", clientObj); + ConsoleMgr::broadcastString("No CTS history found.", clientObj); } else { @@ -1086,10 +1084,10 @@ static void commandFuncAdminTeleport(Command const &, NetworkId const &actor, Ne if (actorClient) { char buffer[512]; - snprintf(buffer, sizeof(buffer)-1, "specified coordinate (%.2f,%.2f,%.2f) (%.2f,%.2f,%.2f) is out of range", + snprintf(buffer, sizeof(buffer) - 1, "specified coordinate (%.2f,%.2f,%.2f) (%.2f,%.2f,%.2f) is out of range", position_w.x, position_w.y, position_w.z, position_p.x, position_p.y, position_p.z); - buffer[sizeof(buffer)-1] = '\0'; + buffer[sizeof(buffer) - 1] = '\0'; ConsoleMgr::broadcastString(buffer, actorClient); } @@ -1192,16 +1190,16 @@ static void commandFuncAdminListGuilds(Command const &, NetworkId const &actor, static void commandFuncAdminEditBank(Command const &cmd, NetworkId const &actor, NetworkId const &target, Unicode::String const ¶ms) { - CreatureObject * actorCreature = safe_cast(ServerWorld::findObjectByNetworkId(actor)); + CreatureObject * actorCreature = safe_cast(ServerWorld::findObjectByNetworkId(actor)); CreatureObject * targetCreature = safe_cast(ServerWorld::findObjectByNetworkId(target)); if (!targetCreature || !actorCreature) { - DEBUG_REPORT_LOG(true, ("Received open command for null player or target.\n")); + DEBUG_REPORT_LOG(true, ("Received open command for nullptr player or target.\n")); return; } ServerObject * targetBank = targetCreature->getBankContainer(); - if(!targetBank) + if (!targetBank) { DEBUG_REPORT_LOG(true, ("Couldn't get bank for player %s.\n", target.getValueString().c_str())); return; @@ -1238,17 +1236,17 @@ static void commandFuncAdminEditBank(Command const &cmd, NetworkId const &actor, static void commandFuncAdminEditStats(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const &) { - CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (!creatureActor) { - WARNING (true, ("commandFuncAdminEditStats: null actor")); + WARNING(true, ("commandFuncAdminEditStats: nullptr actor")); return; } - CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { - WARNING (true, ("commandFuncAdminEditStats: null target")); + WARNING(true, ("commandFuncAdminEditStats: nullptr target")); return; } @@ -1262,17 +1260,17 @@ static void commandFuncAdminEditStats(Command const &, NetworkId const &actor, N static void commandFuncAdminEditAppearance(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const &) { - CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById (actor)); + CreatureObject* const creatureActor = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (!creatureActor) { - WARNING (true, ("commandFuncAdminEditAppearance: null actor")); + WARNING(true, ("commandFuncAdminEditAppearance: nullptr actor")); return; } - CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + CreatureObject* const creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { - WARNING (true, ("commandFuncAdminEditAppearance: null target")); + WARNING(true, ("commandFuncAdminEditAppearance: nullptr target")); return; } @@ -1296,7 +1294,7 @@ static void commandFuncAdminCredits(Command const &, NetworkId const &, NetworkI // ---------------------------------------------------------------------- -static void commandFuncAdminGetStationName(Command const &, NetworkId const & actor, NetworkId const & target , Unicode::String const & params) +static void commandFuncAdminGetStationName(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { const Object * const actorObj = NetworkIdManager::getObjectById(actor); if (actorObj && actorObj->asServerObject()) @@ -1304,25 +1302,25 @@ static void commandFuncAdminGetStationName(Command const &, NetworkId const & ac Client * const actorClient = actorObj->asServerObject()->getClient(); if (actorClient) { - const CreatureObject* creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (target)); + const CreatureObject* creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!creatureTarget) { size_t pos = 0; NetworkId targetId(nextOidParm(params, pos)); - creatureTarget = dynamic_cast(NetworkIdManager::getObjectById (targetId)); + creatureTarget = dynamic_cast(NetworkIdManager::getObjectById(targetId)); } - if(!creatureTarget) + if (!creatureTarget) { ConsoleMgr::broadcastString("Could not resolve target passed to getStationName", actorClient); return; } const Client * const clientTarget = creatureTarget->getClient(); - if(clientTarget) + if (clientTarget) { const std::string & stationName = clientTarget->getAccountName(); - char buf [512]; + char buf[512]; snprintf(buf, 511, "Station name is: %s.", stationName.c_str()); ConsoleMgr::broadcastString(buf, actorClient); } @@ -1340,7 +1338,6 @@ static void commandFuncAdminGetStationName(Command const &, NetworkId const & ac static void commandFuncAuctionCreate(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { - /*printf("!!!!AUCTION: process = %i\n", (int)GameServer::getInstance().getProcessId()); printf("!!!!PID = %i\n", (int)getpid()); @@ -1385,8 +1382,6 @@ static void commandFuncAuctionCreateImmediate(Command const &, NetworkId const & CreatureObject *actorCreature = dynamic_cast(NetworkIdManager::getObjectById(actor)); - - TangibleObject *itemTangible = dynamic_cast(NetworkIdManager::getObjectById(itemId)); ServerObject *auctionContainer = dynamic_cast(NetworkIdManager::getObjectById(auctionContainerId)); @@ -1413,10 +1408,10 @@ static void commandFuncAuctionBid(Command const &, NetworkId const &actor, Netwo int maxProxyBid = nextIntParm(params, pos); CreatureObject *actorCreature = dynamic_cast(NetworkIdManager::getObjectById(actor)); - CommoditiesMarket::getAuctionDetails(*actorCreature, auctionId); - if (actorCreature) { + CommoditiesMarket::getAuctionDetails(*actorCreature, auctionId); + CommoditiesMarket::auctionBid( *actorCreature, auctionId.getValue(), @@ -1463,26 +1458,6 @@ static void commandFuncAuctionAccept(Command const &, NetworkId const &actor, Ne static void commandFuncAuctionQuery(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { -#if 0 - size_t pos = 0; - NetworkId auctionContainerId(nextOidParm(params, pos)); - int requestId = nextIntParm(params, pos); - int type = nextIntParm(params, pos); - int category = nextIntParm(params, pos); - - CreatureObject *actorCreature = dynamic_cast(NetworkIdManager::getObjectById(actor)); - ServerObject *auctionContainer = dynamic_cast(NetworkIdManager::getObjectById(auctionContainerId)); - - if (actorCreature && auctionContainer) - { - CommoditiesMarket::auctionQuery( - *actorCreature, - requestId, - type, - category, - *auctionContainer); - } -#endif } // ---------------------------------------------------------------------- @@ -1518,29 +1493,29 @@ static void commandFuncSocial(Command const &command, NetworkId const &actor, Ne if (obj) { Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); + Unicode::tokenize(params, sv); - if (sv.empty ()) + if (sv.empty()) { - WARNING (true, ("commandFuncSocial no params")); + WARNING(true, ("commandFuncSocial no params")); return; } - const std::string & socialName = Unicode::wideToNarrow (sv [0]); - const uint32 socialType = SocialsManager::getSocialTypeByName (socialName); + const std::string & socialName = Unicode::wideToNarrow(sv[0]); + const uint32 socialType = SocialsManager::getSocialTypeByName(socialName); if (!socialType) - WARNING (true, ("commandFuncSocial Bad social type specified: [%s]", socialName.c_str ())); + WARNING(true, ("commandFuncSocial Bad social type specified: [%s]", socialName.c_str())); else { bool animationOk = true; - bool textOk = true; - if (sv.size () > 1) - animationOk = !sv [1].empty () && sv [1][0] == '1'; - if (sv.size () > 2) - textOk = !sv [2].empty () && sv [2][0] == '1'; + bool textOk = true; + if (sv.size() > 1) + animationOk = !sv[1].empty() && sv[1][0] == '1'; + if (sv.size() > 2) + textOk = !sv[2].empty() && sv[2][0] == '1'; - obj->performSocial (target, socialType, animationOk, textOk); + obj->performSocial(target, socialType, animationOk, textOk); } } } @@ -1548,7 +1523,7 @@ static void commandFuncSocial(Command const &command, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncSocialInternal (Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) +static void commandFuncSocialInternal(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); if (actor != NetworkId::cms_invalid) @@ -1557,29 +1532,29 @@ static void commandFuncSocialInternal (Command const &command, NetworkId const & if (obj) { Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); + Unicode::tokenize(params, sv); - if (sv.size () < 2) + if (sv.size() < 2) { - WARNING (true, ("commandFuncSocial not enough params")); + WARNING(true, ("commandFuncSocial not enough params")); return; } - const NetworkId targetId (Unicode::wideToNarrow (sv [0])); - const uint32 socialType = atoi (Unicode::wideToNarrow (sv [1]).c_str()); + const NetworkId targetId(Unicode::wideToNarrow(sv[0])); + const uint32 socialType = atoi(Unicode::wideToNarrow(sv[1]).c_str()); if (!socialType) - WARNING (true, ("commandFuncSocialInternal Bad social type specified: '%d'", socialType)); + WARNING(true, ("commandFuncSocialInternal Bad social type specified: '%d'", socialType)); else { bool animationOk = true; - bool textOk = true; - if (sv.size () > 3) + bool textOk = true; + if (sv.size() > 3) { - animationOk = !sv [2].empty () && sv [2][0] == '1'; - textOk = !sv [3].empty () && sv [3][0] == '1'; + animationOk = !sv[2].empty() && sv[2][0] == '1'; + textOk = !sv[3].empty() && sv[3][0] == '1'; } - obj->performSocial (targetId, socialType, animationOk, textOk); + obj->performSocial(targetId, socialType, animationOk, textOk); } } } @@ -1587,7 +1562,7 @@ static void commandFuncSocialInternal (Command const &command, NetworkId const & //---------------------------------------------------------------------- -static void commandFuncSetMood (Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const & params) +static void commandFuncSetMood(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const & params) { UNREF(command); if (actor != NetworkId::cms_invalid) @@ -1595,17 +1570,17 @@ static void commandFuncSetMood (Command const &command, NetworkId const &actor, CreatureObject * const obj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - const std::string moodName = Unicode::wideToNarrow (params); + const std::string moodName = Unicode::wideToNarrow(params); if (moodName == "none") { - obj->setMood (0); + obj->setMood(0); } else { - const uint32 moodType = MoodManager::getMoodByCanonicalName (moodName); + const uint32 moodType = MoodManager::getMoodByCanonicalName(moodName); if (moodType) - obj->setMood (moodType); + obj->setMood(moodType); } } } @@ -1613,7 +1588,7 @@ static void commandFuncSetMood (Command const &command, NetworkId const &actor, // ---------------------------------------------------------------------- -static void commandFuncSetMoodInternal (Command const &command, NetworkId const &actor, +static void commandFuncSetMoodInternal(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); @@ -1623,14 +1598,14 @@ static void commandFuncSetMoodInternal (Command const &command, NetworkId const if (obj) { const uint32 moodType = atoi(Unicode::wideToNarrow(params).c_str()); - obj->setMood (moodType); + obj->setMood(moodType); } } } //---------------------------------------------------------------------- -static void commandFuncRequestWaypointAtPosition (Command const &command, NetworkId const &actor, +static void commandFuncRequestWaypointAtPosition(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(command); @@ -1639,15 +1614,15 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ CreatureObject * const obj = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - if(obj->isPlayerControlled()) + if (obj->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(obj); - if(playerObject) + if (playerObject) { size_t curpos = 0; uint8 color = static_cast(Waypoint::Blue); - std::string planet = nextStringParm (params, curpos); + std::string planet = nextStringParm(params, curpos); // the first parameter may be the name of the planet or an unsigned // int specifying the color of the waypoint, in which case the @@ -1656,8 +1631,8 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ // obfuscation to prevent player from manually entering the // requestWaypointAtPosition command and specifying the waypoint color char buffer[256]; - snprintf(buffer, sizeof(buffer)-1, "(^-,=+_)color_%s(,+-=_^)=", actor.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "(^-,=+_)color_%s(,+-=_^)=", actor.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; if (planet.find(buffer) == 0) { @@ -1674,18 +1649,18 @@ static void commandFuncRequestWaypointAtPosition (Command const &command, Networ planet = nextStringParm(params, curpos); } - const float x = nextFloatParm (params, curpos); - const float y = nextFloatParm (params, curpos); - const float z = nextFloatParm (params, curpos); - curpos = Unicode::skipWhitespace (params, curpos); + const float x = nextFloatParm(params, curpos); + const float y = nextFloatParm(params, curpos); + const float z = nextFloatParm(params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); const std::string& sceneId = ServerWorld::getSceneId(); StringId s("planet_n", sceneId); - const Unicode::String & name = ((curpos != Unicode::String::npos) ? (params.substr (curpos)) : (Unicode::narrowToWide("@" + s.getCanonicalRepresentation()))); + const Unicode::String & name = ((curpos != Unicode::String::npos) ? (params.substr(curpos)) : (Unicode::narrowToWide("@" + s.getCanonicalRepresentation()))); // get player object - Waypoint waypoint(playerObject->createWaypoint(Location(Vector(x, y, z), NetworkId::cms_invalid, Location::getCrcBySceneName(planet)),false)); + Waypoint waypoint(playerObject->createWaypoint(Location(Vector(x, y, z), NetworkId::cms_invalid, Location::getCrcBySceneName(planet)), false)); if (waypoint.isValid()) { waypoint.setName(name); // Waypoints are a bit like smart pointers, so this is changing the data on the PlayerObject, not just on a local variable @@ -1715,14 +1690,13 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act ServerObject * const obj = safe_cast(NetworkIdManager::getObjectById(actor)); if (obj) { - size_t curpos = 0; - const NetworkId targetId (nextStringParm (params, curpos)); - const int chatType = nextIntParm (params, curpos); - const int mood = nextIntParm (params, curpos); - int flags = nextIntParm (params, curpos); - int language = nextIntParm (params, curpos); + const NetworkId targetId(nextStringParm(params, curpos)); + const int chatType = nextIntParm(params, curpos); + const int mood = nextIntParm(params, curpos); + int flags = nextIntParm(params, curpos); + int language = nextIntParm(params, curpos); // Verify the language parameter @@ -1731,29 +1705,29 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act language = GameLanguageManager::getBasicLanguageId(); } - curpos = Unicode::skipWhitespace (params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); if (curpos == Unicode::String::npos) { - DEBUG_WARNING (true, ("empty string in spatial chat")); + DEBUG_WARNING(true, ("empty string in spatial chat")); return; } - const size_t nullpos = params.find (static_cast(0), curpos); + const size_t nullpos = params.find(static_cast(0), curpos); Unicode::String text; Unicode::String oob; if (nullpos != Unicode::String::npos) { - text = params.substr (curpos, nullpos - curpos); - oob = params.substr (nullpos + 1); + text = params.substr(curpos, nullpos - curpos); + oob = params.substr(nullpos + 1); } else { // Strip any color codes the user may have entered - text = TextIterator(params.substr (curpos)).getPrintableText(); + text = TextIterator(params.substr(curpos)).getPrintableText(); } if (text.empty()) @@ -1761,19 +1735,19 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act return; } - const bool isPrivate = SpatialChatManager::isPrivate (chatType); + const bool isPrivate = SpatialChatManager::isPrivate(chatType); if (isPrivate) flags |= MessageQueueSpatialChat::F_isPrivate; if (chatType != -1 && mood != -1 && flags != -1 && curpos != Unicode::String::npos) { - uint16 volume = SpatialChatManager::getVolume (chatType); + uint16 volume = SpatialChatManager::getVolume(chatType); CreatureObject * const creatureActor = obj->asCreatureObject(); //speak cs_spaceSpeechMultiple times when piloting a ship - if(creatureActor && creatureActor->getPilotedShip()) + if (creatureActor && creatureActor->getPilotedShip()) volume *= cs_spaceSpeechMultiple; // track amount of spatial chat for the character @@ -1806,20 +1780,20 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act // character allowed to talk obj->speakText( MessageQueueSpatialChat( - CachedNetworkId(actor), - CachedNetworkId(targetId), - text, - volume, - static_cast(chatType), - static_cast(mood), - flags, - language, - oob)); + CachedNetworkId(actor), + CachedNetworkId(targetId), + text, + volume, + static_cast(chatType), + static_cast(mood), + flags, + language, + oob)); } else if (!squelched && (ConfigServerGame::getChatSpamNotifyPlayerWhenLimitedIntervalSeconds() > 0) && obj->getClient()) { // send message telling character he can no longer talk - const int timeNow = static_cast(::time(NULL)); + const int timeNow = static_cast(::time(nullptr)); const int chatSpamTimeEndInterval = playerObject->getChatSpamTimeEndInterval(); if ((chatSpamTimeEndInterval > timeNow) && (timeNow >= playerObject->getChatSpamNextTimeToNotifyPlayerWhenLimited())) { @@ -1837,7 +1811,7 @@ static void commandFuncSpatialChatInternal(Command const &, NetworkId const &act // ---------------------------------------------------------------------- /** -* Parameters: [null terminator + oob] +* Parameters: [nullptr terminator + oob] * All parameters are strings */ @@ -1854,65 +1828,64 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw Unicode::String moodTypeName; Unicode::String flagsString; - if (!Unicode::getFirstToken (params, curpos, curpos, chatTypeName) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, curpos, curpos, chatTypeName) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no chat type)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no chat type)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, moodTypeName) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, moodTypeName) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no mood type)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no mood type)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, flagsString) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, flagsString) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSpatialChat (no flags)")); + WARNING(true, ("Not enough arguments to commandFuncSpatialChat (no flags)")); return; } curpos = Unicode::skipWhitespace(params, ++curpos); - const std::string & narrow_chatTypeName = Unicode::wideToNarrow (chatTypeName); - const std::string & narrow_moodTypeName = Unicode::wideToNarrow (moodTypeName); + const std::string & narrow_chatTypeName = Unicode::wideToNarrow(chatTypeName); + const std::string & narrow_moodTypeName = Unicode::wideToNarrow(moodTypeName); - const uint32 chatType = SpatialChatManager::getChatTypeByName (narrow_chatTypeName); + const uint32 chatType = SpatialChatManager::getChatTypeByName(narrow_chatTypeName); - curpos = Unicode::skipWhitespace (params, curpos); + curpos = Unicode::skipWhitespace(params, curpos); if (curpos == Unicode::String::npos) { - DEBUG_WARNING (true, ("empty string in spatial chat")); + DEBUG_WARNING(true, ("empty string in spatial chat")); return; } - size_t nullpos = params.find (static_cast(0), curpos); + size_t nullpos = params.find(static_cast(0), curpos); Unicode::String text; Unicode::String oob; if (nullpos != Unicode::String::npos) { - text = params.substr (curpos, nullpos - curpos); - oob = params.substr (nullpos + 1); + text = params.substr(curpos, nullpos - curpos); + oob = params.substr(nullpos + 1); } else { - text = params.substr (curpos); - + text = params.substr(curpos); } if (curpos != Unicode::String::npos) { - const uint32 moodType = MoodManager::getMoodByCanonicalName (narrow_moodTypeName); - const bool isPrivate = SpatialChatManager::isPrivate (chatType); + const uint32 moodType = MoodManager::getMoodByCanonicalName(narrow_moodTypeName); + const bool isPrivate = SpatialChatManager::isPrivate(chatType); - uint32 flags = atoi (Unicode::wideToNarrow (flagsString).c_str ()); + uint32 flags = atoi(Unicode::wideToNarrow(flagsString).c_str()); if (isPrivate) flags |= MessageQueueSpatialChat::F_isPrivate; - const uint16 volume = SpatialChatManager::getVolume (chatType); + const uint16 volume = SpatialChatManager::getVolume(chatType); // track amount of spatial chat for the character bool allowToSpeak = true; @@ -1944,20 +1917,20 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw // character allowed to talk obj->speakText( MessageQueueSpatialChat( - CachedNetworkId(actor), - CachedNetworkId(targetId), - text, - volume, - static_cast(chatType), - static_cast(moodType), - flags, - 0, - oob)); + CachedNetworkId(actor), + CachedNetworkId(targetId), + text, + volume, + static_cast(chatType), + static_cast(moodType), + flags, + 0, + oob)); } else if (!squelched && (ConfigServerGame::getChatSpamNotifyPlayerWhenLimitedIntervalSeconds() > 0) && obj->getClient()) { // send message telling character he can no longer talk - const int timeNow = static_cast(::time(NULL)); + const int timeNow = static_cast(::time(nullptr)); const int chatSpamTimeEndInterval = playerObject->getChatSpamTimeEndInterval(); if ((chatSpamTimeEndInterval > timeNow) && (timeNow >= playerObject->getChatSpamNextTimeToNotifyPlayerWhenLimited())) { @@ -1969,7 +1942,7 @@ static void commandFuncSpatialChat(Command const &, NetworkId const &actor, Netw } } else - WARNING (true, ("Invalid empty output string in commandFuncSpatialChat")); + WARNING(true, ("Invalid empty output string in commandFuncSpatialChat")); } } } @@ -1992,7 +1965,7 @@ static void commandFuncCombatSpam (Command const &, NetworkId const &actor, Netw ServerObject * const obj = safe_cast(actorId.getObject ()); if (!obj) { - WARNING (true, ("null actor in commandFuncCombatSpam")); + WARNING (true, ("nullptr actor in commandFuncCombatSpam")); return; } @@ -2091,31 +2064,31 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network Unicode::String targetTypeStr; Unicode::String targetIdStr; - if (!Unicode::getFirstToken (params, curpos, curpos, targetTypeStr) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, curpos, curpos, targetTypeStr) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); return; } - if (!Unicode::getFirstToken (params, ++curpos, curpos, targetIdStr) || curpos == Unicode::String::npos) + if (!Unicode::getFirstToken(params, ++curpos, curpos, targetIdStr) || curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing bitflags)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing bitflags)")); return; } if (curpos == Unicode::String::npos) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); return; } curpos = Unicode::skipWhitespace(params, ++curpos); - Unicode::String output = params.substr (curpos); + Unicode::String output = params.substr(curpos); - if (output.empty ()) + if (output.empty()) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing msg)")); return; } @@ -2123,11 +2096,11 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network std::string targetId = Unicode::wideToNarrow(targetIdStr); static const Unicode::String oob; - if(targetType == "Player") + if (targetType == "Player") { Chat::sendInstantMessage("SYSTEM", targetId, output, oob); } - else if(targetType == "ChatChannel") + else if (targetType == "ChatChannel") { Chat::sendToRoom("SYSTEM", targetId, output, oob); } @@ -2138,32 +2111,32 @@ static void commandFuncSystemMessage(Command const &, NetworkId const &, Network static void commandFuncSetWaypointActiveStatus(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { CachedNetworkId actorId(actor); - WARNING(! actorId.getObject(), ("commandSetWaypointActiveStatus: Could not get an object for actor id %s\n", actor.getValueString().c_str())); - if(actorId.getObject()) + WARNING(!actorId.getObject(), ("commandSetWaypointActiveStatus: Could not get an object for actor id %s\n", actor.getValueString().c_str())); + if (actorId.getObject()) { CreatureObject * creature = dynamic_cast(actorId.getObject()); - if(creature) + if (creature) { - if(creature->isPlayerControlled()) + if (creature->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creature); - if(playerObject) + if (playerObject) { Waypoint w = playerObject->getWaypoint(target); if (w.isValid()) { Unicode::String status; size_t curpos = 0; - if (!Unicode::getFirstToken (params, curpos, curpos, status)) + if (!Unicode::getFirstToken(params, curpos, curpos, status)) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing int value)")); return; } - if(status == Unicode::narrowToWide("on")) + if (status == Unicode::narrowToWide("on")) { w.setActive(true); } - else if(status == Unicode::narrowToWide("off")) + else if (status == Unicode::narrowToWide("off")) { w.setActive(false); } @@ -2179,25 +2152,25 @@ static void commandFuncSetWaypointActiveStatus(Command const &, NetworkId const static void commandFuncSetWaypointName(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { CachedNetworkId actorId(actor); - WARNING(! actorId.getObject(), ("commandFuncSetWaypointName: Could not get an object for actor id %s\n", actor.getValueString().c_str())); - if(actorId.getObject()) + WARNING(!actorId.getObject(), ("commandFuncSetWaypointName: Could not get an object for actor id %s\n", actor.getValueString().c_str())); + if (actorId.getObject()) { CreatureObject * creature = dynamic_cast(actorId.getObject()); - if(creature) + if (creature) { - if(creature->isPlayerControlled()) + if (creature->isPlayerControlled()) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creature); - if(playerObject) + if (playerObject) { Waypoint w = playerObject->getWaypoint(target); if (w.isValid()) { Unicode::String name; size_t curpos = 0; - if (!Unicode::getFirstToken (params, curpos, curpos, name)) + if (!Unicode::getFirstToken(params, curpos, curpos, name)) { - WARNING (true, ("Not enough arguments to commandFuncSystemMessage (missing text value)")); + WARNING(true, ("Not enough arguments to commandFuncSystemMessage (missing text value)")); return; } w.setName(params); @@ -2213,13 +2186,13 @@ static void commandFuncSetWaypointName(Command const &, NetworkId const & actor, static void commandSetPosture(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const &) { CachedNetworkId actorId(actor); - if (actorId.getObject() != NULL) + if (actorId.getObject() != nullptr) { CreatureController * const controller = dynamic_cast(actorId.getObject()->getController()); - if (controller != NULL) + if (controller != nullptr) { - CreatureObject * const creature = safe_cast(actorId.getObject()); - NOT_NULL (creature); + CreatureObject * const creature = safe_cast(actorId.getObject()); + NOT_NULL(creature); Postures::Enumerator const posture = creature->getPosture(); // send the creature's posture to it @@ -2231,7 +2204,7 @@ static void commandSetPosture(Command const &command, NetworkId const &actor, Ne GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_ALL_CLIENT - ); + ); // Ensure the chair sitting state is off if the player is not sitting. if (posture != Postures::Sitting) @@ -2247,19 +2220,19 @@ static void commandSetPosture(Command const &command, NetworkId const &actor, Ne static void commandFuncJumpServer(Command const &command, NetworkId const &actor, NetworkId const &, Unicode::String const &) { CachedNetworkId actorId(actor); - if (actorId.getObject() != NULL) + if (actorId.getObject() != nullptr) { CreatureController * const controller = dynamic_cast(actorId.getObject()->getController()); - if (controller != NULL) + if (controller != nullptr) { controller->appendMessage( CM_jump, 0.0f, - NULL, + nullptr, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_ALL_CLIENT - ); + ); } } } @@ -2434,9 +2407,9 @@ static void resolveDuelParticipants(CreatureObject &actor, TangibleObject &targe // Dueling a ship // actorFlagObj is the containing ship of the actor if he owns it ShipObject * const actorShip = ShipObject::getContainingShipObject(&actor); - if ( actorShip - && actorShip->isPlayerShip() - && actor.getNetworkId() == actorShip->getOwnerId()) + if (actorShip + && actorShip->isPlayerShip() + && actor.getNetworkId() == actorShip->getOwnerId()) actorFlagObj = actorShip; // targetMessageObj is the owner of the target ship if (targetShip->isPlayerShip()) @@ -2501,7 +2474,7 @@ static void commandFuncDuel(Command const &, NetworkId const &actor, NetworkId c return; } - if(targetObj->getObjVars().hasItem("hologram_performer")) + if (targetObj->getObjVars().hasItem("hologram_performer")) { sendProseMessage(*actorObj, targetMessageObj, CommandStringId::SID_DUEL_NOT_HOLOGRAM); } @@ -2525,58 +2498,56 @@ static void commandFuncDuel(Command const &, NetworkId const &actor, NetworkId c // Call their Script Triggers ServerObject* serverActor = actorObj->asServerObject(); - if(serverActor) + if (serverActor) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverActor->getScriptObject()) + if (serverActor->getScriptObject()) { IGNORE_RETURN(serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); - } } ServerObject* serverTarget = targetObj->asServerObject(); - if(serverTarget) + if (serverTarget) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverTarget->getScriptObject()) + if (serverTarget->getScriptObject()) { - IGNORE_RETURN( serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); + IGNORE_RETURN(serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_START, params)); } } /// End script triggers. - } else { // Duel Request // Call their Script Triggers ServerObject* serverActor = actorObj->asServerObject(); - if(serverActor) + if (serverActor) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverActor->getScriptObject()) + if (serverActor->getScriptObject()) { - if( serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE ) + if (serverActor->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE) return; } } ServerObject* serverTarget = targetObj->asServerObject(); - if(serverTarget) + if (serverTarget) { ScriptParams params; params.addParam(actor); params.addParam(target); - if(serverTarget->getScriptObject()) + if (serverTarget->getScriptObject()) { - if( serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE ) + if (serverTarget->getScriptObject()->trigAllScripts(Scripting::TRIG_ON_DUEL_REQUEST, params) == SCRIPT_OVERRIDE) return; } } @@ -2617,16 +2588,16 @@ static void commandFuncEndDuel(Command const &, NetworkId const &actor, NetworkI // notify script that the duel has ended because of the EndDuel command { - ScriptParams params; - params.addParam(targetObj->getNetworkId(), "target"); - ScriptDictionaryPtr dictionary; - GameScriptObject::makeScriptDictionary(params, dictionary); - if (dictionary.get() != NULL) - { - dictionary->serialize(); - MessageToQueue::getInstance().sendMessageToJava(actorFlagObj->getNetworkId(), - "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); - } + ScriptParams params; + params.addParam(targetObj->getNetworkId(), "target"); + ScriptDictionaryPtr dictionary; + GameScriptObject::makeScriptDictionary(params, dictionary); + if (dictionary.get() != nullptr) + { + dictionary->serialize(); + MessageToQueue::getInstance().sendMessageToJava(actorFlagObj->getNetworkId(), + "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); + } } { @@ -2634,10 +2605,10 @@ static void commandFuncEndDuel(Command const &, NetworkId const &actor, NetworkI params.addParam(actorFlagObj->getNetworkId(), "target"); ScriptDictionaryPtr dictionary; GameScriptObject::makeScriptDictionary(params, dictionary); - if (dictionary.get() != NULL) + if (dictionary.get() != nullptr) { dictionary->serialize(); - MessageToQueue::getInstance().sendMessageToJava(targetObj->getNetworkId(), + MessageToQueue::getInstance().sendMessageToJava(targetObj->getNetworkId(), "endDuelCommandNotification", dictionary->getSerializedData(), 0, false); } } @@ -2670,7 +2641,7 @@ static void commandFuncHarvesterActivate(Command const &, NetworkId const &actor CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->activate(actor); + targetObj->activate(actor); } // ---------------------------------------------------------------------- @@ -2680,8 +2651,7 @@ static void commandFuncHarvesterDeactivate(Command const &, NetworkId const &act CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj &&targetObj->isOnAdminList(*actorObj)) - targetObj->deactivate(); - + targetObj->deactivate(); } // ---------------------------------------------------------------------- @@ -2691,7 +2661,7 @@ static void commandFuncHarvesterHarvest(Command const &, NetworkId const &actor, CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->harvest(); + targetObj->harvest(); } // ---------------------------------------------------------------------- @@ -2721,14 +2691,14 @@ static void commandFuncHarvesterMakeCrate(Command const &, NetworkId const &acto { CreatureObject *actorObj = dynamic_cast(NetworkIdManager::getObjectById(actor)); HarvesterInstallationObject *targetObj = dynamic_cast(NetworkIdManager::getObjectById(target)); - size_t pos=0; - const NetworkId resourceId = nextOidParm(params,pos); - const int amount = nextIntParm(params,pos); - const bool discard = nextBoolParm(params,pos); - const uint8 sequenceId = static_cast(nextIntParm(params,pos)); + size_t pos = 0; + const NetworkId resourceId = nextOidParm(params, pos); + const int amount = nextIntParm(params, pos); + const bool discard = nextBoolParm(params, pos); + const uint8 sequenceId = static_cast(nextIntParm(params, pos)); if (targetObj && actorObj && targetObj->isOnAdminList(*actorObj)) - targetObj->emptyHopper(actor,resourceId,amount,discard,sequenceId); + targetObj->emptyHopper(actor, resourceId, amount, discard, sequenceId); } // ---------------------------------------------------------------------- @@ -2747,14 +2717,13 @@ static void commandFuncResourceContainerTransfer(Command const &, NetworkId cons CreatureObject * const player = safe_cast(ServerWorld::findObjectByNetworkId(actor)); if (!player) return; - + ResourceContainerObject *sourceObj = dynamic_cast(NetworkIdManager::getObjectById(target)); size_t pos = 0; - NetworkId destId = nextOidParm(params,pos); + NetworkId destId = nextOidParm(params, pos); ResourceContainerObject *destObj = dynamic_cast(NetworkIdManager::getObjectById(destId)); - int amount = nextIntParm(params,pos); + int amount = nextIntParm(params, pos); - if (!sourceObj || !destObj || amount <= 0) return; @@ -2769,7 +2738,7 @@ static void commandFuncResourceContainerTransfer(Command const &, NetworkId cons ContainerInterface::sendContainerMessageToClient(*player, error, destObj); return; } - + sourceObj->transferTo(*destObj, amount); } @@ -2788,7 +2757,7 @@ static void commandFuncRequestSurvey(Command const &, NetworkId const &actor, Ne if (actorObj && actorObj->getClient()) { size_t curpos = 0; - Unicode::String resourceName = Unicode::narrowToWide(nextStringParm (params, curpos)); + Unicode::String resourceName = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2809,7 +2778,7 @@ static void commandFuncRequestCoreSample(Command const &, NetworkId const &actor if (actorObj && actorObj->getClient()) { size_t curpos = 0; - Unicode::String resourceName = Unicode::narrowToWide(nextStringParm (params, curpos)); + Unicode::String resourceName = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2835,19 +2804,19 @@ static void commandFuncResourceContainerSplit(Command const &, NetworkId const & return; size_t pos = 0; - const int amount = nextIntParm(params,pos); - const CachedNetworkId destContainer (nextOidParm(params,pos)); - const int arrangementId = nextIntParm(params,pos); - const Vector & newLocation = nextVectorParm(params,pos); + const int amount = nextIntParm(params, pos); + const CachedNetworkId destContainer(nextOidParm(params, pos)); + const int arrangementId = nextIntParm(params, pos); + const Vector & newLocation = nextVectorParm(params, pos); Container::ContainerErrorCode error = Container::CEC_Success; if (!player->canManipulateObject(*sourceObj, true, true, true, 10.0f, error)) { ContainerInterface::sendContainerMessageToClient(*player, error, sourceObj); } - else if (!sourceObj->splitContainer(amount,destContainer,arrangementId,newLocation, safe_cast(NetworkIdManager::getObjectById(actor)))) + else if (!sourceObj->splitContainer(amount, destContainer, arrangementId, newLocation, safe_cast(NetworkIdManager::getObjectById(actor)))) { - ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_Full, safe_cast(destContainer.getObject ())); + ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_Full, safe_cast(destContainer.getObject())); } } @@ -2864,10 +2833,10 @@ static void commandFuncFactoryCrateSplit(Command const &, NetworkId const &actor return; size_t pos = 0; - const int amount = nextIntParm(params,pos); - const CachedNetworkId destContainerId (nextOidParm(params,pos)); + const int amount = nextIntParm(params, pos); + const CachedNetworkId destContainerId(nextOidParm(params, pos)); ServerObject * destContainer = safe_cast(destContainerId.getObject()); - if (destContainer == NULL || ContainerInterface::getVolumeContainer(*destContainer) == NULL) + if (destContainer == nullptr || ContainerInterface::getVolumeContainer(*destContainer) == nullptr) { ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_NotFound); return; @@ -2878,7 +2847,7 @@ static void commandFuncFactoryCrateSplit(Command const &, NetworkId const &actor { ContainerInterface::sendContainerMessageToClient(*player, error, sourceObj); } - else if (sourceObj->makeCopy(*destContainer, amount) == NULL) + else if (sourceObj->makeCopy(*destContainer, amount) == nullptr) { ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_Full, destContainer); @@ -2893,9 +2862,9 @@ static void commandFuncPermissionListModify(Command const &, NetworkId const &ac if (actorObj && actorObj->getClient()) { size_t curpos = 0; - const Unicode::String & playerName = Unicode::narrowToWide(nextStringParm (params, curpos)); - const Unicode::String & listName = Unicode::narrowToWide(nextStringParm (params, curpos)); - const Unicode::String & action = Unicode::narrowToWide(nextStringParm (params, curpos)); + const Unicode::String & playerName = Unicode::narrowToWide(nextStringParm(params, curpos)); + const Unicode::String & listName = Unicode::narrowToWide(nextStringParm(params, curpos)); + const Unicode::String & action = Unicode::narrowToWide(nextStringParm(params, curpos)); ScriptParams params; params.addParam(actor); @@ -2947,12 +2916,12 @@ static void commandFuncHarvesterGetResourceData(Command const &, NetworkId const //------------------------------------------------------------------------------------------ static void commandFuncTransferItem(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const & params) { - ServerObject * const item = ServerWorld::findObjectByNetworkId(target); - ServerObject * const playerSo = ServerWorld::findObjectByNetworkId(actor); + ServerObject * const item = ServerWorld::findObjectByNetworkId(target); + ServerObject * const playerSo = ServerWorld::findObjectByNetworkId(actor); if (!playerSo || !item) { - DEBUG_REPORT_LOG(true, ("Received transfer item command for null player or target.\n")); + DEBUG_REPORT_LOG(true, ("Received transfer item command for nullptr player or target.\n")); return; } @@ -2965,7 +2934,7 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); const Vector & pos = nextVectorParm(params, curpos); Transform t; t.setPosition_p(pos); @@ -3019,10 +2988,10 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net if (!canManipulateTarget) { - if(errorCode == Container::CEC_NoPermission) + if (errorCode == Container::CEC_NoPermission) { Object * parentObject = ContainerInterface::getContainedByObject(*item); - if(parentObject && parentObject->asServerObject() && parentObject->asServerObject()->asTangibleObject() + if (parentObject && parentObject->asServerObject() && parentObject->asServerObject()->asTangibleObject() && parentObject->asServerObject()->asTangibleObject()->isLocked()) { ContainerInterface::sendContainerMessageToClient(*player, errorCode, parentObject->asServerObject()); @@ -3035,50 +3004,48 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net //-- don't transfer from/to factory crates { - if (destination && destination->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (destination && destination->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; - const ServerObject * const containedBy = safe_cast(ContainerInterface::getContainedByObject (*item)); + const ServerObject * const containedBy = safe_cast(ContainerInterface::getContainedByObject(*item)); - if (containedBy && containedBy->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (containedBy && containedBy->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; } // If our destination is a locked container, make sure we can access it. bool lockedDestContainer = false; { - if(destination && destination->asTangibleObject() && destination->asTangibleObject()->isLocked()) + if (destination && destination->asTangibleObject() && destination->asTangibleObject()->isLocked()) { lockedDestContainer = true; TangibleObject * destTangible = destination->asTangibleObject(); - if(!destTangible->isUserOnAccessList(player->getNetworkId()) && !destTangible->isGuildOnAccessList(player->getGuildId()) + if (!destTangible->isUserOnAccessList(player->getNetworkId()) && !destTangible->isGuildOnAccessList(player->getGuildId()) && player->getClient() && !player->getClient()->isGod()) { ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_NoPermission, destination); return; } } - } { // No Drag and Drop while using Loot rules (especially random). const ServerObject * source = getFirstCreatureContainer(item); - if(source && source->asCreatureObject() && source->asCreatureObject()->isDead() && destination) + if (source && source->asCreatureObject() && source->asCreatureObject()->isDead() && destination) { const ServerObject* dest = getFirstCreatureContainer(destination); - if(dest && dest->asCreatureObject() && dest->asCreatureObject()->getGroup()) + if (dest && dest->asCreatureObject() && dest->asCreatureObject()->getGroup()) { int lootRule = dest->asCreatureObject()->getGroup()->getLootRule(); // Random/Lotto Loot Rule, no drag and drop allowed! - if(lootRule == 3 || lootRule == 2) + if (lootRule == 3 || lootRule == 2) { return; } } } - } if (!item->isAuthoritative()) @@ -3127,8 +3094,8 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net } //Don't allow people to put things in unowned containers. Locked containers are allowed since they enforce their own list. - if (!destination->getObjVars().hasItem(OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER) && !lockedDestContainer && - player->getClient() && !player->getClient()->isGod() && + if (!destination->getObjVars().hasItem(OBJVAR_PLAYERS_CAN_ACCESS_CONTAINER) && !lockedDestContainer && + player->getClient() && !player->getClient()->isGod() && destination->getOwnerId() == NetworkId::cms_invalid) { errorCode = Container::CEC_NoPermission; @@ -3163,32 +3130,31 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net { int oldCap = volContainer->debugDoNotUseSetCapacity(allowedOverload); retval = ContainerInterface::transferItemToVolumeContainer(*destination, *item, player, errorCode, true); - IGNORE_RETURN( volContainer->debugDoNotUseSetCapacity(oldCap) ); + IGNORE_RETURN(volContainer->debugDoNotUseSetCapacity(oldCap)); } } } else { const Object * destParent = ContainerInterface::getContainedByObject(*destination); - if(destParent && destParent == player->getAppearanceInventory()) + if (destParent && destParent == player->getAppearanceInventory()) { // Trying to transfer to a container currently in our Appearance inventory. Not allowed. StringId const code("container_error_message", "container34_prose"); ProsePackage pp; pp.stringId = code; - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); retval = false; - } - else if (destination == player->getAppearanceInventory() && ContainerInterface::getContainer(*item) != NULL) + else if (destination == player->getAppearanceInventory() && ContainerInterface::getContainer(*item) != nullptr) { const Container * itemContainer = ContainerInterface::getContainer(*item); - if(itemContainer && itemContainer->getNumberOfItems() == 0) + if (itemContainer && itemContainer->getNumberOfItems() == 0) { retval = ContainerInterface::transferItemToUnknownContainer(*destination, *item, arrangement, t, player, errorCode); } @@ -3198,16 +3164,16 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net ProsePackage pp; pp.stringId = code; - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } } else { retval = ContainerInterface::transferItemToUnknownContainer(*destination, *item, arrangement, t, player, errorCode); - + // if we are equipping an object to a filled slot, move the equipped item(s) to our inventory if (!retval && errorCode == Container::CEC_SlotOccupied && destination->getNetworkId() == player->getNetworkId()) { @@ -3215,7 +3181,7 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net const SlottedContainer * equipment = ContainerInterface::getSlottedContainer(*player); const SlottedContainmentProperty * itemContainmentProperty = ContainerInterface::getSlottedContainmentProperty(*item); - if (inventory != NULL && equipment != NULL && itemContainmentProperty != NULL) + if (inventory != nullptr && equipment != nullptr && itemContainmentProperty != nullptr) { std::vector > oldItems; retval = true; @@ -3225,7 +3191,7 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net SlotId slot = itemContainmentProperty->getSlotId(arrangement, i); const Container::ContainedItem & currentWeaponId = equipment->getObjectInSlot(slot, errorCode); ServerObject * oldItem = safe_cast(currentWeaponId.getObject()); - if (oldItem != NULL) + if (oldItem != nullptr) { if (ContainerInterface::transferItemToVolumeContainer(*inventory, *oldItem, player, errorCode, true)) { @@ -3243,7 +3209,6 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net reequipItems(*destination, oldItems); retval = false; } - } else { @@ -3259,14 +3224,14 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net if (!retval && player) { - if(errorCode == Container::CEC_SlotOccupied && destination == player->getAppearanceInventory()) + if (errorCode == Container::CEC_SlotOccupied && destination == player->getAppearanceInventory()) { // Failed to place an object in our appearance inventory. Let's flush out some more information. ServerObject * appearanceInv = player->getAppearanceInventory(); const SlottedContainer * equipment = ContainerInterface::getSlottedContainer(*appearanceInv); const SlottedContainmentProperty * itemContainmentProperty = ContainerInterface::getSlottedContainmentProperty(*item); - if(!itemContainmentProperty || !equipment || arrangement < 0) + if (!itemContainmentProperty || !equipment || arrangement < 0) { // This should never happen, but if it does - just send our normal bland error message. ContainerInterface::sendContainerMessageToClient(*player, errorCode); @@ -3280,18 +3245,18 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net SlotId slot = itemContainmentProperty->getSlotId(arrangement, i); const Container::ContainedItem & currentWeaponId = equipment->getObjectInSlot(slot, errorCode); ServerObject * oldItem = safe_cast(currentWeaponId.getObject()); - if (oldItem != NULL) + if (oldItem != nullptr) { - if( std::find(objectsToSend.begin(), objectsToSend.end(), oldItem) == objectsToSend.end() ) + if (std::find(objectsToSend.begin(), objectsToSend.end(), oldItem) == objectsToSend.end()) objectsToSend.push_back(oldItem); } } - + std::vector::iterator iter = objectsToSend.begin(); - for(; iter != objectsToSend.end(); ++iter) + for (; iter != objectsToSend.end(); ++iter) { // No idea how this could happen, but just incase. - if((*iter) == NULL) + if ((*iter) == nullptr) continue; StringId const code("container_error_message", "container32_prose"); @@ -3300,22 +3265,22 @@ static void commandFuncTransferItem(Command const &, NetworkId const &actor, Net ProsePackage pp; pp.stringId = code; - pp.target.id = (*iter)->getNetworkId (); - pp.target.str = (*iter)->getAssignedObjectName (); - if (pp.target.str.empty ()) - pp.target.stringId = (*iter)->getObjectNameStringId (); + pp.target.id = (*iter)->getNetworkId(); + pp.target.str = (*iter)->getAssignedObjectName(); + if (pp.target.str.empty()) + pp.target.stringId = (*iter)->getObjectNameStringId(); - pp.other.id = item->getNetworkId(); - pp.other.str = item->getAssignedObjectName(); + pp.other.id = item->getNetworkId(); + pp.other.str = item->getAssignedObjectName(); if (pp.other.str.empty()) pp.other.stringId = item->getObjectNameStringId(); - pp.actor.id = player->getNetworkId (); + pp.actor.id = player->getNetworkId(); // Send to the player. - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } - + return; } @@ -3360,14 +3325,13 @@ static void commandFuncTransferWeapon(Command const & c, NetworkId const &actor, size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); UNREF(destId); - + if (item && actorObject && isGoingInWeaponSlot(*item, arrangement)) { commandFuncTransferItem(c, actor, target, params); } - } //------------------------------------------------------------------------------------------ @@ -3387,14 +3351,14 @@ void CommandCppFuncs::commandFuncTransferMisc(Command const & c, NetworkId const { ServerObject * item = ServerWorld::findObjectByNetworkId(target); CreatureObject * actorObject = safe_cast(ServerWorld::findObjectByNetworkId(actor)); - + size_t curpos = 0; const NetworkId & destId = nextOidParm(params, curpos); - const int arrangement = nextIntParm(params, curpos); + const int arrangement = nextIntParm(params, curpos); //This command can only be used to transfer non-weapon objects not contained directly by the player unless it is not armor if (item && actorObject && !isGoingInWeaponSlot(*item, arrangement) && - ( destId != actor || !GameObjectTypes::isTypeOf(item->getGameObjectType(), SharedObjectTemplate::GOT_armor)) ) + (destId != actor || !GameObjectTypes::isTypeOf(item->getGameObjectType(), SharedObjectTemplate::GOT_armor))) { commandFuncTransferItem(c, actor, target, params); } @@ -3411,7 +3375,7 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor CreatureObject * player = safe_cast(ServerWorld::findObjectByNetworkId(actor)); if (!container || !player) { - DEBUG_REPORT_LOG(true, ("Received open command for null player or target.\n")); + DEBUG_REPORT_LOG(true, ("Received open command for nullptr player or target.\n")); return; } //@todo check permissions @@ -3422,23 +3386,23 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor } //-- don't open factory crates - if (container->getGameObjectType () == SharedObjectTemplate::GOT_misc_factory_crate) + if (container->getGameObjectType() == SharedObjectTemplate::GOT_misc_factory_crate) return; //-- if they are opening a crafting station, what they really want is the hopper //-- but only if the object is not a volume container - if (container->getGameObjectType () == SharedObjectTemplate::GOT_misc_crafting_station - && (NULL == ContainerInterface::getVolumeContainer (*container))) - { + if (container->getGameObjectType() == SharedObjectTemplate::GOT_misc_crafting_station + && (nullptr == ContainerInterface::getVolumeContainer(*container))) + { static const SlotId inputHopperId(SlotIdManager::findSlotId(CrcLowerString("ingredient_hopper"))); ServerObject const * const station = container; - ServerObject * hopper = NULL; - const SlottedContainer * stationContainer = ContainerInterface::getSlottedContainer (*station); - if (stationContainer != NULL) + ServerObject * hopper = nullptr; + const SlottedContainer * stationContainer = ContainerInterface::getSlottedContainer(*station); + if (stationContainer != nullptr) { Container::ContainerErrorCode tmp = Container::CEC_Success; - Object* tmpHopperObj = (stationContainer->getObjectInSlot (inputHopperId, tmp)).getObject(); + Object* tmpHopperObj = (stationContainer->getObjectInSlot(inputHopperId, tmp)).getObject(); if (tmp == Container::CEC_Success && tmpHopperObj) { hopper = tmpHopperObj->asServerObject(); @@ -3459,18 +3423,18 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor size_t curpos = 0; std::string slotName; - int sequence = nextIntParm (params, curpos); + int sequence = nextIntParm(params, curpos); if (curpos != std::string::npos) { ++curpos; - slotName = nextStringParm (params, curpos); + slotName = nextStringParm(params, curpos); } if (container->isAuthoritative()) { Container::ContainerErrorCode code = Container::CEC_Success; - bool const isPublicContainer = container->getGameObjectType () == SharedObjectTemplate::GOT_misc_container_public; + bool const isPublicContainer = container->getGameObjectType() == SharedObjectTemplate::GOT_misc_container_public; if (isPublicContainer && player->getClient()) ObserveTracker::onClientAboutToOpenPublicContainer(*player->getClient(), *container); @@ -3481,10 +3445,10 @@ static void commandFuncOpenContainer(Command const & cmd, NetworkId const &actor if (player->canManipulateObject(*container, false, doPermissionCheckOnItem, doPermissionCheckOnParents, 6.0f, code)) { // Additional check for Locked containers. - if(container->asTangibleObject() && container->asTangibleObject()->isLocked()) + if (container->asTangibleObject() && container->asTangibleObject()->isLocked()) { TangibleObject * tangibleTarget = container->asTangibleObject(); - if(!tangibleTarget->isUserOnAccessList(player->getNetworkId()) && !tangibleTarget->isGuildOnAccessList(player->getGuildId())) + if (!tangibleTarget->isUserOnAccessList(player->getNetworkId()) && !tangibleTarget->isGuildOnAccessList(player->getGuildId())) { // Player is NOT on the admin list or guild list, they cannot open the container. ContainerInterface::sendContainerMessageToClient(*player, Container::CEC_NoPermission, container); @@ -3526,7 +3490,7 @@ static void commandFuncCloseContainer(Command const &, NetworkId const &actor, N ServerObject * const player = ServerWorld::findObjectByNetworkId(actor); if (!container || !player) { - DEBUG_REPORT_LOG(true, ("Received close command for null player or target.\n")); + DEBUG_REPORT_LOG(true, ("Received close command for nullptr player or target.\n")); return; } @@ -3552,7 +3516,6 @@ static void commandFuncCloseContainer(Command const &, NetworkId const &actor, N //@todo the player is trying to access a container not on this server. Somehow get it here //Then do the check } - } //------------------------------------------------------------------------------------------ @@ -3611,11 +3574,11 @@ static void commandFuncCloseLotteryContainer(Command const & cmd, NetworkId cons */ static void commandFuncGiveItem(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const & params) { - ServerObject * const item = ServerWorld::findObjectByNetworkId(target); + ServerObject * const item = ServerWorld::findObjectByNetworkId(target); ServerObject * const player = ServerWorld::findObjectByNetworkId(actor); if (!player || !item) { - DEBUG_REPORT_LOG(true, ("Received give item command for null player or target.\n")); + DEBUG_REPORT_LOG(true, ("Received give item command for nullptr player or target.\n")); return; } size_t curpos = 0; @@ -3669,19 +3632,19 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network // check and see if this is a gem->socket operation, which is handled by our code TangibleObject * const socket = dynamic_cast(destination); - if (socket != NULL) + if (socket != nullptr) { TangibleObject * const gem = dynamic_cast(item); - if (gem != NULL) + if (gem != nullptr) { - const int destGot = socket->getGameObjectType(); + const int destGot = socket->getGameObjectType(); const SharedTangibleObjectTemplate * const gemTemplate = safe_cast(gem->getSharedTemplate()); - const int count = gemTemplate->getSocketDestinationsCount(); + const int count = gemTemplate->getSocketDestinationsCount(); for (int i = 0; i < count; ++i) { const int gemSocketGot = gemTemplate->getSocketDestinations(i); - if (destGot == gemSocketGot || GameObjectTypes::isTypeOf (destGot, gemSocketGot)) + if (destGot == gemSocketGot || GameObjectTypes::isTypeOf(destGot, gemSocketGot)) { // make sure the gem and socket are both in the player's inventory if (!socket->isContainedBy(*player, true) || @@ -3692,13 +3655,13 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network } // if the socketed item is equipped, unequip it temporarily - CreatureObject * owner = NULL; + CreatureObject * owner = nullptr; Object * container = ContainerInterface::getContainedByObject(*socket); - if (container != NULL && container->asServerObject()->asCreatureObject() != NULL) + if (container != nullptr && container->asServerObject()->asCreatureObject() != nullptr) { owner = container->asServerObject()->asCreatureObject(); // fake unequipping the item - owner->onContainerLostItem(NULL, *socket, NULL); + owner->onContainerLostItem(nullptr, *socket, nullptr); } std::vector > skillModBonuses; @@ -3713,10 +3676,10 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network // tell the player they can't use the gem Chat::sendSystemMessage(*player, SharedStringIds::gem_not_inserted, Unicode::emptyString); } - if (owner != NULL) + if (owner != nullptr) { // "re-equip" the item - owner->onContainerGainItem(*socket, NULL, NULL); + owner->onContainerGainItem(*socket, nullptr, nullptr); } return; } @@ -3726,14 +3689,13 @@ static void commandFuncGiveItem(Command const &, NetworkId const &actor, Network // nope, pass it on to scripts ScriptParams scriptParameters; - scriptParameters.addParam (target); - scriptParameters.addParam (actor); + scriptParameters.addParam(target); + scriptParameters.addParam(actor); if (destination->getScriptObject()->trigAllScripts(Scripting::TRIG_GIVE_ITEM, scriptParameters) == SCRIPT_OVERRIDE) { item->permanentlyDestroy(DeleteReasons::BadContainerTransfer); } - } // ---------------------------------------------------------------------- @@ -3796,8 +3758,8 @@ static void commandFuncGroupInvite(Command const & command, NetworkId const &act // send a messageTo to the target to invite to group char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%s|%s|%s", actor.getValueString().c_str(), (actorShipObject ? actorShipObject->getNetworkId().getValueString().c_str() : "0"), (groupObj ? groupObj->getNetworkId().getValueString().c_str() : "0"), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%s|%s|%s", actor.getValueString().c_str(), (actorShipObject ? actorShipObject->getNetworkId().getValueString().c_str() : "0"), (groupObj ? groupObj->getNetworkId().getValueString().c_str() : "0"), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++InviteToGroupReq", @@ -3843,8 +3805,8 @@ static void commandFuncGroupUninvite(Command const &, NetworkId const &actor, Ne // send a messageTo to the target to uninvite char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%s", actor.getValueString().c_str(), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%s", actor.getValueString().c_str(), Unicode::wideToNarrow(actorObj->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++UninviteFromGroupReq", @@ -3964,10 +3926,10 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net GroupObject::GroupMemberParamVector membersOutsidePOB; GroupHelpers::separateGroupBasedOffofPOBShip(groupObj, - actor, - POBShipId, - membersInsidePOB, - membersOutsidePOB); + actor, + POBShipId, + membersInsidePOB, + membersOutsidePOB); // if there are no members outside, then the group only consisted of // the people in the POB. If that's the case, then don't destroy the @@ -4045,10 +4007,10 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net NetworkId const & POBShipId = (*ii).m_memberShipId; GroupHelpers::separateGroupBasedOffofPOBShip(groupObj, - memberId, - POBShipId, - membersInsidePOB[memberId], - membersOutsidePOB[memberId]); + memberId, + POBShipId, + membersInsidePOB[memberId], + membersOutsidePOB[memberId]); } } @@ -4138,7 +4100,7 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net { GroupMemberParam const & leader = *ii; - // create the new POB groups. notice NULL is passed in for the + // create the new POB groups. notice nullptr is passed in for the // groupToRemoveFrom because the original group has already had // all of the members removed @@ -4170,7 +4132,7 @@ static void commandFuncGroupDisband(Command const &, NetworkId const &actor, Net static void commandFuncKickFromShip(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const ¶ms) { - CreatureObject const * const actorObject = dynamic_cast(ServerWorld::findObjectByNetworkId(actor)); + CreatureObject const * const actorObject = dynamic_cast(ServerWorld::findObjectByNetworkId(actor)); if (actorObject != 0) { CreatureObject * const targetObject = dynamic_cast(ServerWorld::findObjectByNetworkId(target)); @@ -4229,7 +4191,6 @@ static void commandFuncAuctionChat(Command const &, NetworkId const &actor, Netw const std::string channelName = "SWG." + GameServer::getInstance().getClusterName() + "." + ServerWorld::getSceneId() + ".named.Auction"; Chat::sendToRoom(firstName, channelName, params, Unicode::String()); - } } @@ -4377,8 +4338,8 @@ static void commandFuncCreateGroupPickup(Command const &, NetworkId const &actor if ((iterGroupMember->first != actor) && groupObj->isMemberPC(iterGroupMember->first)) { char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%d|%d|%d|%s", currentScene.c_str(), static_cast(currentWorldLocation.x), static_cast(currentWorldLocation.y), static_cast(currentWorldLocation.z), actorName.c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%d|%d|%d|%s", currentScene.c_str(), static_cast(currentWorldLocation.x), static_cast(currentWorldLocation.y), static_cast(currentWorldLocation.z), actorName.c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(iterGroupMember->first, "C++GroupPickupPointCreated", @@ -4389,7 +4350,7 @@ static void commandFuncCreateGroupPickup(Command const &, NetworkId const &actor } // create the group pickup point - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); groupObj->setGroupPickupTimer(timeNow, timeNow + static_cast(ConfigServerGame::getGroupPickupPointTimeLimitSeconds())); groupObj->setGroupPickupLocation(currentScene, currentWorldLocation); @@ -4578,7 +4539,7 @@ static void commandFuncUseGroupPickup(Command const &, NetworkId const &actor, N return; } - // if nearest travel point and current planet is the same, and the nearest travel point to the + // if nearest travel point and current planet is the same, and the nearest travel point to the // group pickup point is farther away than the current location to the group pickup point, then // fail, as there is no need to travel as the player is currently closer to the group pickup point if ((sceneIdOfNearestTravelPoint == currentScene) && (sceneIdOfNearestTravelPoint == groupPickupLocation.first) && (groupPickupLocation.second.magnitudeBetweenSquared(nearestTravelPoint->getPosition_w()) > groupPickupLocation.second.magnitudeBetweenSquared(currentWorldLocation))) @@ -4633,8 +4594,8 @@ static void commandFuncUseGroupPickup(Command const &, NetworkId const &actor, N if (cityHallAtNearestTravelPoint.isValid() && (cityShareOfCost > 0)) { char buffer[64]; - snprintf(buffer, sizeof(buffer)-1, "%d", cityShareOfCost); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%d", cityShareOfCost); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(cityHallAtNearestTravelPoint, "C++CityShareGroupPickupPointTravelCost", @@ -4682,7 +4643,7 @@ static void commandFuncGroupPickRandomGroupMember(Command const &, NetworkId con if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextGroupPickRandomGroupMemberCommandAllowed") && (targetObj->getObjVars().getType("timeNextGroupPickRandomGroupMemberCommandAllowed") == DynamicVariable::INT)) { int timeNextGroupPickRandomGroupMemberCommandAllowed = 0; @@ -4703,7 +4664,7 @@ static void commandFuncGroupPickRandomGroupMember(Command const &, NetworkId con if (!params.empty()) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(Unicode::toLower(params), tokens, NULL, NULL) && !tokens.empty()) + if (Unicode::tokenize(Unicode::toLower(params), tokens, nullptr, nullptr) && !tokens.empty()) { static Unicode::String const paramsPoint1 = Unicode::narrowToWide("-point"); static Unicode::String const paramsPoint2 = Unicode::narrowToWide("point"); @@ -4805,7 +4766,7 @@ static void commandFuncGroupTextChatRoomRejoin(Command const &, NetworkId const if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextGroupTextChatRoomRejoinCommandAllowed") && (targetObj->getObjVars().getType("timeNextGroupTextChatRoomRejoinCommandAllowed") == DynamicVariable::INT)) { int timeNextGroupTextChatRoomRejoinCommandAllowed = 0; @@ -4868,7 +4829,7 @@ static void commandFuncGuildTextChatRoomRejoin(Command const &, NetworkId const if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextGuildTextChatRoomRejoinCommandAllowed") && (targetObj->getObjVars().getType("timeNextGuildTextChatRoomRejoinCommandAllowed") == DynamicVariable::INT)) { int timeNextGuildTextChatRoomRejoinCommandAllowed = 0; @@ -4913,7 +4874,7 @@ static void commandFuncGuildPickRandomGuildMember(Command const &, NetworkId con if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextGuildPickRandomGuildMemberCommandAllowed") && (targetObj->getObjVars().getType("timeNextGuildPickRandomGuildMemberCommandAllowed") == DynamicVariable::INT)) { int timeNextGuildPickRandomGuildMemberCommandAllowed = 0; @@ -4935,7 +4896,7 @@ static void commandFuncGuildPickRandomGuildMember(Command const &, NetworkId con if (!params.empty()) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(Unicode::toLower(params), tokens, NULL, NULL) && !tokens.empty()) + if (Unicode::tokenize(Unicode::toLower(params), tokens, nullptr, nullptr) && !tokens.empty()) { static Unicode::String const paramsOnline1 = Unicode::narrowToWide("-online"); static Unicode::String const paramsOnline2 = Unicode::narrowToWide("online"); @@ -5074,7 +5035,7 @@ static void commandFuncCityTextChatRoomRejoin(Command const &, NetworkId const & if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextCityTextChatRoomRejoinCommandAllowed") && (targetObj->getObjVars().getType("timeNextCityTextChatRoomRejoinCommandAllowed") == DynamicVariable::INT)) { int timeNextCityTextChatRoomRejoinCommandAllowed = 0; @@ -5120,7 +5081,7 @@ static void commandFuncCityPickRandomCitizen(Command const &, NetworkId const &a if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextCityPickRandomCitizenCommandAllowed") && (targetObj->getObjVars().getType("timeNextCityPickRandomCitizenCommandAllowed") == DynamicVariable::INT)) { int timeNextCityPickRandomCitizenCommandAllowed = 0; @@ -5142,7 +5103,7 @@ static void commandFuncCityPickRandomCitizen(Command const &, NetworkId const &a if (!params.empty()) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(Unicode::toLower(params), tokens, NULL, NULL) && !tokens.empty()) + if (Unicode::tokenize(Unicode::toLower(params), tokens, nullptr, nullptr) && !tokens.empty()) { static Unicode::String const paramsOnline1 = Unicode::narrowToWide("-online"); static Unicode::String const paramsOnline2 = Unicode::narrowToWide("online"); @@ -5267,37 +5228,37 @@ static void commandFuncShowMusicianVisuals(Command const &, NetworkId const &act // ---------------------------------------------------------------------- -static void commandFuncPlaceStructure (const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) +static void commandFuncPlaceStructure(const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) { - Object* const object = NetworkIdManager::getObjectById (actor); + Object* const object = NetworkIdManager::getObjectById(actor); if (!object) { - DEBUG_WARNING (true, ("commandFuncPlaceStructure: PB null actor\n")); + DEBUG_WARNING(true, ("commandFuncPlaceStructure: PB nullptr actor\n")); return; } ServerObject* const serverObject = dynamic_cast (object); if (!serverObject) { - DEBUG_WARNING (true, ("commandFuncPlaceStructure: object is not a server object\n")); + DEBUG_WARNING(true, ("commandFuncPlaceStructure: object is not a server object\n")); return; } size_t pos = 0; - const NetworkId deedNetworkId = nextOidParm (parameters, pos); - const float x = nextFloatParm (parameters, pos); - const float z = nextFloatParm (parameters, pos); - const Vector position (x, 0.f, z); - const int rotation = nextIntParm (parameters, pos); + const NetworkId deedNetworkId = nextOidParm(parameters, pos); + const float x = nextFloatParm(parameters, pos); + const float z = nextFloatParm(parameters, pos); + const Vector position(x, 0.f, z); + const int rotation = nextIntParm(parameters, pos); ScriptParams scriptParameters; - scriptParameters.addParam (actor); - scriptParameters.addParam (deedNetworkId); - scriptParameters.addParam (position); - scriptParameters.addParam (rotation); + scriptParameters.addParam(actor); + scriptParameters.addParam(deedNetworkId); + scriptParameters.addParam(position); + scriptParameters.addParam(rotation); - if (serverObject->getScriptObject ()->trigAllScripts (Scripting::TRIG_PLACE_STRUCTURE, scriptParameters) != SCRIPT_CONTINUE) - DEBUG_REPORT_LOG (true, ("commandFuncPlaceStructure: did not return SCRIPT_CONTINUE\n")); + if (serverObject->getScriptObject()->trigAllScripts(Scripting::TRIG_PLACE_STRUCTURE, scriptParameters) != SCRIPT_CONTINUE) + DEBUG_REPORT_LOG(true, ("commandFuncPlaceStructure: did not return SCRIPT_CONTINUE\n")); } // ---------------------------------------------------------------------- @@ -5356,14 +5317,14 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac if (!sittingOnChair) { // Trying to sit on the ground. - const TerrainObject* const terrainObject = TerrainObject::getConstInstance(); - const CollisionProperty* const collisionProperty = actorObject->getCollisionProperty (); - const bool isOnSolidFloor = collisionProperty && collisionProperty->getFootprint() && collisionProperty->getFootprint()->isOnSolidFloor(); + const TerrainObject* const terrainObject = TerrainObject::getConstInstance(); + const CollisionProperty* const collisionProperty = actorObject->getCollisionProperty(); + const bool isOnSolidFloor = collisionProperty && collisionProperty->getFootprint() && collisionProperty->getFootprint()->isOnSolidFloor(); Vector normal = Vector::unitY; if (terrainObject && actorObject->isInWorldCell() && !isOnSolidFloor) { - const Vector position = actorObject->getPosition_w (); + const Vector position = actorObject->getPosition_w(); float terrainHeight; if (terrainObject->getHeight(position, terrainHeight, normal)) @@ -5372,10 +5333,10 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac float waterHeight; if (terrainObject->getWaterHeight(position, waterHeight)) { - if (waterHeight >terrainHeight) + if (waterHeight > terrainHeight) { // Client is in the water, abort the command. - Chat::sendSystemMessage (*creatureActorObject, SharedStringIds::no_sitting_in_water, Unicode::emptyString); + Chat::sendSystemMessage(*creatureActorObject, SharedStringIds::no_sitting_in_water, Unicode::emptyString); return; } } @@ -5402,7 +5363,6 @@ static void commandFuncSitServer(const Command& /*command*/, const NetworkId& ac //-- Send a SitOnObject message with the chair coordinates. const_cast(creatureActorObject)->sitOnObject(chairCellId, chairPosition_p); } - } // ---------------------------------------------------------------------- @@ -5417,11 +5377,11 @@ static void commandFuncGetAttributes(Command const &, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncGetAttributesBatch(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const & params) +static void commandFuncGetAttributesBatch(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const & params) { size_t curpos = 0; NetworkId obj = nextOidParm(params, curpos); - while(obj != NetworkId::cms_invalid) + while (obj != NetworkId::cms_invalid) { int const clientRevision = nextIntParm(params, curpos); TaskGetAttributes * const task = new TaskGetAttributes(actor, obj, clientRevision); @@ -5432,55 +5392,55 @@ static void commandFuncGetAttributesBatch(Command const &, NetworkId const &acto // ---------------------------------------------------------------------- -static std::string underscoreToSpace (const std::string& source) +static std::string underscoreToSpace(const std::string& source) { std::string result = source; - std::replace (result.begin (), result.end (), '_', ' '); + std::replace(result.begin(), result.end(), '_', ' '); return result; } // ---------------------------------------------------------------------- -static void commandFuncPurchaseTicket (const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) +static void commandFuncPurchaseTicket(const Command& /*command*/, const NetworkId& actor, const NetworkId& /*target*/, const Unicode::String& parameters) { ServerObject* const serverObject = ServerObject::getServerObject(actor); if (!serverObject) { - DEBUG_WARNING (true, ("commandFuncPurchaseTicket: object is not a server object")); + DEBUG_WARNING(true, ("commandFuncPurchaseTicket: object is not a server object")); return; } size_t pos = 0; - const Unicode::String planetName1 = Unicode::narrowToWide (nextStringParm (parameters, pos)); - const Unicode::String travelPoint1 = Unicode::narrowToWide (underscoreToSpace (nextStringParm (parameters, pos))); - const Unicode::String planetName2 = Unicode::narrowToWide (nextStringParm (parameters, pos)); - const Unicode::String travelPoint2 = Unicode::narrowToWide (underscoreToSpace (nextStringParm (parameters, pos))); - const bool roundTrip = nextBoolParm (parameters, pos); - const bool instantTravel = nextBoolParm (parameters, pos); + const Unicode::String planetName1 = Unicode::narrowToWide(nextStringParm(parameters, pos)); + const Unicode::String travelPoint1 = Unicode::narrowToWide(underscoreToSpace(nextStringParm(parameters, pos))); + const Unicode::String planetName2 = Unicode::narrowToWide(nextStringParm(parameters, pos)); + const Unicode::String travelPoint2 = Unicode::narrowToWide(underscoreToSpace(nextStringParm(parameters, pos))); + const bool roundTrip = nextBoolParm(parameters, pos); + const bool instantTravel = nextBoolParm(parameters, pos); ScriptParams scriptParameters; - scriptParameters.addParam (actor); - scriptParameters.addParam (planetName1); - scriptParameters.addParam (travelPoint1); - scriptParameters.addParam (planetName2); - scriptParameters.addParam (travelPoint2); - scriptParameters.addParam (roundTrip); + scriptParameters.addParam(actor); + scriptParameters.addParam(planetName1); + scriptParameters.addParam(travelPoint1); + scriptParameters.addParam(planetName2); + scriptParameters.addParam(travelPoint2); + scriptParameters.addParam(roundTrip); Scripting::TrigId id = instantTravel ? Scripting::TRIG_PURCHASE_TICKET_INSTANT_TRAVEL : Scripting::TRIG_PURCHASE_TICKET; - if (serverObject->getScriptObject ()->trigAllScripts (id, scriptParameters) != SCRIPT_CONTINUE) - DEBUG_REPORT_LOG (true, ("commandFuncPurchaseTicket: did not return SCRIPT_CONTINUE\n")); + if (serverObject->getScriptObject()->trigAllScripts(id, scriptParameters) != SCRIPT_CONTINUE) + DEBUG_REPORT_LOG(true, ("commandFuncPurchaseTicket: did not return SCRIPT_CONTINUE\n")); } //---------------------------------------------------------------------- -static void commandFuncRequestResourceWeights(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestResourceWeights(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestResourceWeights: PB null actor")); + WARNING(true, ("commandFuncRequestResourceWeights: PB nullptr actor")); return; } @@ -5491,12 +5451,12 @@ static void commandFuncRequestResourceWeights(const Command& , const NetworkId& //---------------------------------------------------------------------- -static void commandFuncRequestResourceWeightsBatch(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestResourceWeightsBatch(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { - CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById (actor)); - if (creature == NULL) + CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById(actor)); + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestResourceWeightsBatch: PB null actor")); + WARNING(true, ("commandFuncRequestResourceWeightsBatch: PB nullptr actor")); return; } @@ -5504,7 +5464,7 @@ static void commandFuncRequestResourceWeightsBatch(const Command& , const Networ size_t curpos = 0; schematicCrc = nextIntParm(params, curpos); - while(schematicCrc != -1) + while (schematicCrc != -1) { DraftSchematicObject::requestResourceWeights(*creature, static_cast(schematicCrc)); schematicCrc = nextIntParm(params, curpos); @@ -5513,19 +5473,19 @@ static void commandFuncRequestResourceWeightsBatch(const Command& , const Networ //---------------------------------------------------------------------- -static void commandFuncRequestDraftSlots (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestDraftSlots(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: PB null actor")); + WARNING(true, ("commandFuncRequestDraftSlots: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: no player object for actor ""%s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncRequestDraftSlots: no player object for actor ""%s", actor.getValueString().c_str())); return; } @@ -5533,28 +5493,28 @@ static void commandFuncRequestDraftSlots (const Command& , const NetworkId& acto sscanf(Unicode::wideToNarrow(params).c_str(), "%lu %lu", &serverCrc, &sharedCrc); MessageQueueDraftSlotsQueryResponse * const message = new MessageQueueDraftSlotsQueryResponse(std::make_pair(serverCrc, sharedCrc)); - if (!player->requestDraftSlots(serverCrc, NULL, message)) + if (!player->requestDraftSlots(serverCrc, nullptr, message)) { - WARNING (true, ("commandFuncRequestDraftSlots failed to request draft slots for %u", serverCrc)); + WARNING(true, ("commandFuncRequestDraftSlots failed to request draft slots for %u", serverCrc)); delete message; } } // ---------------------------------------------------------------------- -static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRequestDraftSlotsBatch(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch: PB null actor")); + WARNING(true, ("commandFuncRequestDraftSlotsBatch: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch: no player object for actor ""%s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncRequestDraftSlotsBatch: no player object for actor ""%s", actor.getValueString().c_str())); return; } @@ -5563,29 +5523,29 @@ static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& size_t curpos = 0; std::string serverCrcString = nextStringParm(params, curpos); - if(serverCrcString.empty()) + if (serverCrcString.empty()) return; sscanf(serverCrcString.c_str(), "%lu", &uServerCrc); std::string sharedCrcString = nextStringParm(params, curpos); - if(sharedCrcString.empty()) + if (sharedCrcString.empty()) return; sscanf(sharedCrcString.c_str(), "%lu", &uSharedCrc); bool done = false; - while(uServerCrc != 0 && uSharedCrc != 0 && !done) + while (uServerCrc != 0 && uSharedCrc != 0 && !done) { MessageQueueDraftSlotsQueryResponse * const message = new MessageQueueDraftSlotsQueryResponse(std::make_pair(uServerCrc, uSharedCrc)); - if (!player->requestDraftSlots(uServerCrc, NULL, message)) + if (!player->requestDraftSlots(uServerCrc, nullptr, message)) { - WARNING (true, ("commandFuncRequestDraftSlotsBatch failed to request draft slots for %lu", uServerCrc)); + WARNING(true, ("commandFuncRequestDraftSlotsBatch failed to request draft slots for %lu", uServerCrc)); delete message; } serverCrcString = nextStringParm(params, curpos); - if(serverCrcString.empty()) + if (serverCrcString.empty()) done = true; sscanf(serverCrcString.c_str(), "%lu", &uServerCrc); sharedCrcString = nextStringParm(params, curpos); - if(sharedCrcString.empty()) + if (sharedCrcString.empty()) done = true; sscanf(sharedCrcString.c_str(), "%lu", &uSharedCrc); } @@ -5593,18 +5553,18 @@ static void commandFuncRequestDraftSlotsBatch (const Command& , const NetworkId& // ---------------------------------------------------------------------- -static void commandFuncRequestManfSchematicSlots (const Command& , const NetworkId& actor, const NetworkId& target, const Unicode::String& params) +static void commandFuncRequestManfSchematicSlots(const Command&, const NetworkId& actor, const NetworkId& target, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestDraftSlots: PB null actor")); + WARNING(true, ("commandFuncRequestDraftSlots: PB nullptr actor")); return; } const ManufactureSchematicObject * schematic = dynamic_cast< const ManufactureSchematicObject *>(NetworkIdManager::getObjectById(target)); - if (schematic != NULL) + if (schematic != nullptr) { schematic->requestSlots(*creature); } @@ -5612,19 +5572,19 @@ static void commandFuncRequestManfSchematicSlots (const Command& , const Network // ---------------------------------------------------------------------- -static void commandFuncRequestCraftingSession (const Command& , const NetworkId& actor, const NetworkId& target, const Unicode::String& params) +static void commandFuncRequestCraftingSession(const Command&, const NetworkId& actor, const NetworkId& target, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRequestCraftingSession: PB null actor")); + WARNING(true, ("commandFuncRequestCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncRequestCraftingSession: no player object for actor " + WARNING(true, ("commandFuncRequestCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5637,7 +5597,7 @@ static void commandFuncRequestCraftingSession (const Command& , const NetworkId& // 1 means this request was made on a crafting station versus a crafting tool. uint8 const sequenceId = static_cast(craftingObject && craftingObject->isCraftingStation() ? 1 : 0); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_requestCraftingSession, false, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -5665,19 +5625,19 @@ static void commandFuncRequestCraftingSessionFail(Command const &, NetworkId con // ---------------------------------------------------------------------- -static void commandFuncSelectDraftSchematic (const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncSelectDraftSchematic(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncSelectDraftSchematic: PB null actor")); + WARNING(true, ("commandFuncSelectDraftSchematic: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncSelectDraftSchematic: no player object for actor " + WARNING(true, ("commandFuncSelectDraftSchematic: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5689,19 +5649,19 @@ static void commandFuncSelectDraftSchematic (const Command& , const NetworkId& a // ---------------------------------------------------------------------- -static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncNextCraftingStage(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncNextCraftingStage: PB null actor")); + WARNING(true, ("commandFuncNextCraftingStage: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncNextCraftingStage: no player object for actor " + WARNING(true, ("commandFuncNextCraftingStage: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5709,7 +5669,7 @@ static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor uint8 sequenceId = static_cast(atoi(Unicode::wideToNarrow(params).c_str())); int result = player->goToNextCraftingStage(); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_nextCraftingStage, result, sequenceId); creature->getController()->appendMessage(CM_nextCraftingStageResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -5719,19 +5679,19 @@ static void commandFuncNextCraftingStage(const Command& , const NetworkId& actor // ---------------------------------------------------------------------- -static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCreatePrototype(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncCreatePrototype: PB null actor")); + WARNING(true, ("commandFuncCreatePrototype: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncCreatePrototype: no player object for actor %s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncCreatePrototype: no player object for actor %s", actor.getValueString().c_str())); return; } @@ -5741,7 +5701,7 @@ static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, const bool result = player->createPrototype(realPrototype); - MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse (CM_createPrototype, result, sequenceId); + MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse(CM_createPrototype, result, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | @@ -5753,19 +5713,19 @@ static void commandFuncCreatePrototype(const Command& , const NetworkId& actor, // ---------------------------------------------------------------------- -static void commandFuncCreateManfSchematic(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCreateManfSchematic(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncCreateManfSchematic: PB null actor")); + WARNING(true, ("commandFuncCreateManfSchematic: PB nullptr actor")); return; } PlayerObject * const player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncCreateManfSchematic: no player object for actor %s", actor.getValueString().c_str())); + WARNING(true, ("commandFuncCreateManfSchematic: no player object for actor %s", actor.getValueString().c_str())); return; } @@ -5773,7 +5733,7 @@ static void commandFuncCreateManfSchematic(const Command& , const NetworkId& act const bool result = player->createManufacturingSchematic(); - MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse (CM_createManfSchematic, result, sequenceId); + MessageQueueGenericIntResponse * const response = new MessageQueueGenericIntResponse(CM_createManfSchematic, result, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | @@ -5785,19 +5745,19 @@ static void commandFuncCreateManfSchematic(const Command& , const NetworkId& act // ---------------------------------------------------------------------- -static void commandFuncCancelCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncCancelCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncCancelCraftingSession: PB null actor")); + WARNING(true, ("commandFuncCancelCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncCancelCraftingSession: no player object for actor " + WARNING(true, ("commandFuncCancelCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5807,19 +5767,19 @@ static void commandFuncCancelCraftingSession(const Command& , const NetworkId& a // ---------------------------------------------------------------------- -static void commandFuncStopCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncStopCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncStopCraftingSession: PB null actor")); + WARNING(true, ("commandFuncStopCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncStopCraftingSession: no player object for actor " + WARNING(true, ("commandFuncStopCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5829,19 +5789,19 @@ static void commandFuncStopCraftingSession(const Command& , const NetworkId& act // ---------------------------------------------------------------------- -static void commandFuncRestartCraftingSession(const Command& , const NetworkId& actor, const NetworkId& , const Unicode::String& params) +static void commandFuncRestartCraftingSession(const Command&, const NetworkId& actor, const NetworkId&, const Unicode::String& params) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRestartCraftingSession: PB null actor")); + WARNING(true, ("commandFuncRestartCraftingSession: PB nullptr actor")); return; } PlayerObject * player = PlayerCreatureController::getPlayerObject(creature); - if (player == NULL) + if (player == nullptr) { - WARNING (true, ("commandFuncRestartCraftingSession: no player object for actor " + WARNING(true, ("commandFuncRestartCraftingSession: no player object for actor " "%s", actor.getValueString().c_str())); return; } @@ -5850,7 +5810,7 @@ static void commandFuncRestartCraftingSession(const Command& , const NetworkId& const bool success = player->restartCrafting(); - MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse ( + MessageQueueGenericIntResponse * response = new MessageQueueGenericIntResponse( CM_restartCraftingSession, success, sequenceId); creature->getController()->appendMessage(CM_craftingResult, 0.0f, response, GameControllerMessageFlags::SEND | @@ -5866,7 +5826,7 @@ static void commandFuncSetMatchMakingPersonalId(Command const &, NetworkId const PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { MatchMakingId matchMakingId; matchMakingId.unPackIntString(Unicode::wideToNarrow(params)); @@ -5885,7 +5845,7 @@ static void commandFuncSetMatchMakingCharacterId(Command const &, NetworkId cons PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { MatchMakingId matchMakingId; matchMakingId.unPackIntString(Unicode::wideToNarrow(params)); @@ -5902,7 +5862,7 @@ static void commandFuncAddFriend(Command const &, NetworkId const &actor, Networ { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { size_t pos = 0; std::string name(nextStringParm(params, pos)); @@ -5924,7 +5884,7 @@ static void commandFuncRemoveFriend(Command const &, NetworkId const &actor, Net { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { size_t pos = 0; std::string name(nextStringParm(params, pos)); @@ -5946,7 +5906,7 @@ static void commandFuncGetFriendList(Command const &, NetworkId const &actor, Ne { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { std::string player(Chat::constructChatAvatarId(*serverObject).getFullName()); @@ -5962,7 +5922,7 @@ static void commandFuncAddIgnore(Command const &, NetworkId const &actor, Networ { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { size_t pos = 0; std::string name(nextStringParm(params, pos)); @@ -5984,7 +5944,7 @@ static void commandFuncRemoveIgnore(Command const &, NetworkId const &actor, Net { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { size_t pos = 0; std::string name(nextStringParm(params, pos)); @@ -6006,7 +5966,7 @@ static void commandFuncGetIgnoreList(Command const &, NetworkId const &actor, Ne { ServerObject * const serverObject = ServerObject::getServerObject(actor); - if (serverObject != NULL) + if (serverObject != nullptr) { std::string player(Chat::constructChatAvatarId(*serverObject).getFullName()); @@ -6022,7 +5982,7 @@ static void commandFuncRequestBiography(Command const &, NetworkId const &actor, { CreatureObject * const creatureObject = CreatureObject::getCreatureObject(actor); - if (creatureObject != NULL) + if (creatureObject != nullptr) { BiographyManager::requestBiography(target, creatureObject); } @@ -6038,18 +5998,18 @@ static void commandFuncSetBiography(Command const &, NetworkId const & actor, Ne CreatureObject * const creatureActor = CreatureObject::getCreatureObject(actor); if (!creatureActor) { - WARNING (true, ("commandFuncSetBiography: bad actor")); + WARNING(true, ("commandFuncSetBiography: bad actor")); return; } Client * const clientActor = creatureActor->getClient(); - if(!clientActor) + if (!clientActor) { WARNING(true, ("no Client in commandFuncSetBiography")); return; } - if(!clientActor->isGod()) + if (!clientActor->isGod()) { LOG("CustomerService", ("CheatChannel:%s attempted to set biography data on %s, but is not a God", PlayerObject::getAccountDescription(actor).c_str(), PlayerObject::getAccountDescription(target).c_str())); } @@ -6069,15 +6029,15 @@ static void commandFuncSetBiography(Command const &, NetworkId const & actor, Ne static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const &) { const CreatureObject* const creatureActor = CreatureObject::getCreatureObject(actor); - if (creatureActor == NULL) + if (creatureActor == nullptr) { - WARNING (true, ("commandFuncRequestCharacterSheetInfo: null actor")); + WARNING(true, ("commandFuncRequestCharacterSheetInfo: nullptr actor")); return; } //TODO get the born and played times (once they're in the DB) - int born = 0; - int played = 0; + int born = 0; + int played = 0; //get the bind location Vector bindLoc; @@ -6087,12 +6047,12 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons { creatureActor->getObjVars().getItem("bind.facility", bindId); } - if(bindId != NetworkId::cms_invalid) + if (bindId != NetworkId::cms_invalid) { const ServerObject* const bindObject = ServerObject::getServerObject(bindId); - if (bindObject != NULL) + if (bindObject != nullptr) { - bindLoc = bindObject->getPosition_w(); + bindLoc = bindObject->getPosition_w(); bindPlanet = bindObject->getSceneId(); } } @@ -6142,9 +6102,9 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons houseNetworkId = cityHallOfMayorCity; const ServerObject* const resObject = ServerObject::getServerObject(houseNetworkId); - if (resObject != NULL) + if (resObject != nullptr) { - resLoc = resObject->getPosition_w(); + resLoc = resObject->getPosition_w(); resPlanet = ServerWorld::getSceneId(); } else if (houseNetworkId.isValid() && MessageToQueue::isInstalled()) @@ -6168,7 +6128,7 @@ static void commandFuncRequestCharacterSheetInfo(Command const &, NetworkId cons int lots = creatureActor->getMaxNumberOfLots(); PlayerObject const * const player = PlayerCreatureController::getPlayerObject(creatureActor); - if(player) + if (player) { int lotsUsed = player->getAccountNumLots(); lots -= lotsUsed; @@ -6201,23 +6161,23 @@ static void commandFuncRequestCharacterMatch(Command const &, NetworkId const &a static void commandFuncExtractObject(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { CreatureObject* const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncExtractObject: PB null actor")); + WARNING(true, ("commandFuncExtractObject: PB nullptr actor")); return; } - if (creature->getInventory() == NULL) + if (creature->getInventory() == nullptr) { - WARNING (true, ("commandFuncExtractObject: actor %s has no inventory", + WARNING(true, ("commandFuncExtractObject: actor %s has no inventory", actor.getValueString().c_str())); return; } - FactoryObject* const factory = dynamic_cast(NetworkIdManager::getObjectById (target)); - if (factory == NULL) + FactoryObject* const factory = dynamic_cast(NetworkIdManager::getObjectById(target)); + if (factory == nullptr) { - WARNING (true, ("commandFuncExtractObject: PB null target")); + WARNING(true, ("commandFuncExtractObject: PB nullptr target")); return; } @@ -6233,24 +6193,24 @@ static void commandFuncExtractObject(Command const &, NetworkId const &actor, Ne static void commandFuncRevokeSkill(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { CreatureObject * const creature = CreatureObject::getCreatureObject(actor); - if (creature == NULL) + if (creature == nullptr) { - WARNING (true, ("commandFuncRevokeSkill: PB null actor")); + WARNING(true, ("commandFuncRevokeSkill: PB nullptr actor")); return; } size_t pos = 0; std::string skillName = nextStringParm(params, pos); - const SkillObject * skill = SkillManager::getInstance ().getSkill (skillName); - if (skill == NULL) + const SkillObject * skill = SkillManager::getInstance().getSkill(skillName); + if (skill == nullptr) { - WARNING (true, ("commandFuncRevokeSkill: can't revoke bad skill")); + WARNING(true, ("commandFuncRevokeSkill: can't revoke bad skill")); } else { LOG("CustomerService", ("Skill: God (via cmdfunc) has requested the revocation of skill %s from character %s.", skillName.c_str(), creature->getNetworkId().getValueString().c_str())); - creature->revokeSkill (*skill); + creature->revokeSkill(*skill); } } @@ -6261,7 +6221,7 @@ static void commandFuncSetCurrentSkillTitle(Command const &, NetworkId const &ac CreatureObject * const creatureObject = CreatureObject::getCreatureObject(actor); PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(creatureObject); - if (playerObject != NULL) + if (playerObject != nullptr) { size_t pos = 0; std::string const &title = nextStringParm(params, pos); @@ -6378,8 +6338,8 @@ static void commandFuncSetCurrentSkillTitle(Command const &, NetworkId const &ac { SkillObject const *skillObject = (*iterSkillList); - if ( (skillObject != NULL) - && skillObject->isTitle() + if ((skillObject != nullptr) + && skillObject->isTitle() && (skillObject->getSkillName() == title)) { playerObject->setTitle(title); @@ -6401,17 +6361,17 @@ static void commandFuncSetCurrentSkillTitle(Command const &, NetworkId const &ac static void commandFuncRepair(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { - CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById (actor)); - if (creature == NULL) + CreatureObject* const creature = dynamic_cast(NetworkIdManager::getObjectById(actor)); + if (creature == nullptr) { - WARNING (true, ("commandFuncRepair: PB null actor")); + WARNING(true, ("commandFuncRepair: PB nullptr actor")); return; } - TangibleObject* const object = dynamic_cast(NetworkIdManager::getObjectById (target)); - if (object == NULL) + TangibleObject* const object = dynamic_cast(NetworkIdManager::getObjectById(target)); + if (object == nullptr) { - WARNING (true, ("commandFuncRepair: PB null target")); + WARNING(true, ("commandFuncRepair: PB nullptr target")); return; } } @@ -6424,7 +6384,7 @@ static void commandFuncToggleSearchableByCtsSourceGalaxy(Command const &, Networ PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleSearchableByCtsSourceGalaxy(); } @@ -6438,7 +6398,7 @@ static void commandFuncToggleDisplayLocationInSearchResults(Command const &, Net PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleDisplayLocationInSearchResults(); } @@ -6452,7 +6412,7 @@ static void commandFuncToggleAnonymous(Command const &, NetworkId const &actor, PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleAnonymous(); } @@ -6466,7 +6426,7 @@ static void commandFuncToggleHelper(Command const &, NetworkId const &actor, Net PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleHelper(); } @@ -6480,20 +6440,19 @@ static void commandFuncToggleRolePlay(Command const &, NetworkId const &actor, N PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleRolePlay(); } } - // ---------------------------------------------------------------------- static void commandFuncToggleOutOfCharacter(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleOutOfCharacter(); } @@ -6505,13 +6464,12 @@ static void commandFuncToggleLookingForWork(Command const &, NetworkId const &ac { PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleLookingForWork(); } } - // ---------------------------------------------------------------------- static void commandFuncToggleLookingForGroup(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) @@ -6520,7 +6478,7 @@ static void commandFuncToggleLookingForGroup(Command const &, NetworkId const &a PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleLookingForGroup(); } @@ -6534,7 +6492,7 @@ static void commandFuncToggleAwayFromKeyBoard(Command const &, NetworkId const & PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleAwayFromKeyBoard(); } @@ -6546,7 +6504,7 @@ static void commandFuncToggleDisplayingFactionRank(Command const &, NetworkId co { PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(CreatureObject::getCreatureObject(actor)); - if (playerObject != NULL) + if (playerObject != nullptr) { playerObject->toggleDisplayingFactionRank(); } @@ -6558,7 +6516,7 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId { CreatureObject const * const reportingCreatureObject = CreatureObject::getCreatureObject(actor); - if (reportingCreatureObject != NULL) + if (reportingCreatureObject != nullptr) { if (ReportManager::isThrottled(actor)) { @@ -6584,14 +6542,14 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId Unicode::String const delimiter = Unicode::narrowToWide("|"); Unicode::UnicodeStringVector tokens; - if(Unicode::tokenize(params, tokens, &delimiter) && tokens.size() > 1) + if (Unicode::tokenize(params, tokens, &delimiter) && tokens.size() > 1) { harassingPlayerName = tokens[0]; Unicode::String rest; uint32 numTokens = tokens.size(); - for(uint32 i = 1; i < numTokens; ++i) + for (uint32 i = 1; i < numTokens; ++i) { - if(i != 1) + if (i != 1) { rest.append(delimiter); } @@ -6608,7 +6566,6 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId Chat::sendSystemMessage(*reportingCreatureObject, StringId("system_msg", "report_no_name"), Unicode::emptyString); } - //if (Unicode::getFirstToken(name, curpos, endpos, harassingPlayerName)) //{ @@ -6635,16 +6592,16 @@ static void commandFuncReport(Command const &, NetworkId const &actor, NetworkId static void commandFuncNpcConversationStart(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { ServerObject * const actorObject = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const player = actorObject != NULL ? actorObject->asCreatureObject() : NULL; - if (player == NULL) + CreatureObject * const player = actorObject != nullptr ? actorObject->asCreatureObject() : nullptr; + if (player == nullptr) { DEBUG_WARNING(true, ("commandFuncNpcConversationStart: couldn't find actor")); return; } ServerObject * const npcObject = safe_cast(NetworkIdManager::getObjectById(target)); - TangibleObject * const npc = npcObject != NULL ? npcObject->asTangibleObject() : NULL; - if (npc == NULL) + TangibleObject * const npc = npcObject != nullptr ? npcObject->asTangibleObject() : nullptr; + if (npc == nullptr) { DEBUG_WARNING(true, ("commandFuncNpcConversationStart: Couldn't find npc to converse with")); return; @@ -6659,7 +6616,7 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac return; } } - + std::string const & realParams = Unicode::wideToNarrow(params); if (realParams.size() < 2) { @@ -6670,7 +6627,7 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac const char * const conversationName = &realParams[2]; NpcConversationData::ConversationStarter const starter = static_cast(atoi(realParams.c_str())); - player->startNpcConversation (*npc, conversationName, starter, 0); + player->startNpcConversation(*npc, conversationName, starter, 0); } //---------------------------------------------------------------------- @@ -6678,8 +6635,8 @@ static void commandFuncNpcConversationStart(Command const &, NetworkId const &ac static void commandFuncNpcConversationStop(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { ServerObject * const actorObject = safe_cast(NetworkIdManager::getObjectById(actor)); - TangibleObject * const player = actorObject != NULL ? actorObject->asTangibleObject(): NULL; - if (player == NULL) + TangibleObject * const player = actorObject != nullptr ? actorObject->asTangibleObject() : nullptr; + if (player == nullptr) { DEBUG_WARNING(true, ("commandFuncNpcConversationStop: couldn't find actor")); return; @@ -6693,7 +6650,7 @@ static void commandFuncNpcConversationSelect(Command const &, NetworkId const &a { Object * const actorObject = NetworkIdManager::getObjectById(actor); CreatureObject * const player = dynamic_cast(actorObject); - if (player == NULL) + if (player == nullptr) { DEBUG_WARNING(true, ("commandFuncNpcConversationStop: couldn't find actor")); return; @@ -6706,27 +6663,27 @@ static void commandFuncNpcConversationSelect(Command const &, NetworkId const &a //---------------------------------------------------------------------- -static void commandFuncServerDestroyObject (Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) +static void commandFuncServerDestroyObject(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { - CreatureObject * const player = dynamic_cast (NetworkIdManager::getObjectById (actor)); - if (player == NULL) + CreatureObject * const player = dynamic_cast (NetworkIdManager::getObjectById(actor)); + if (player == nullptr) { - DEBUG_WARNING (true, ("commandFuncServerDestroyObject: couldn't find actor")); + DEBUG_WARNING(true, ("commandFuncServerDestroyObject: couldn't find actor")); return; } - ServerObject * const targetObject = safe_cast(NetworkIdManager::getObjectById (target)); + ServerObject * const targetObject = safe_cast(NetworkIdManager::getObjectById(target)); if (!targetObject) { PlayerObject * p = PlayerCreatureController::getPlayerObject(player); - if(p) + if (p) { p->destroyWaypoint(target); return; } else { - DEBUG_WARNING (true, ("commandFuncServerDestroyObject: couldn't find target")); + DEBUG_WARNING(true, ("commandFuncServerDestroyObject: couldn't find target")); return; } } @@ -6734,18 +6691,18 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a ServerObject const * const topMost = getFirstParentInWorldOrPlayer(targetObject); if (!topMost || topMost->getNetworkId() != actor) { - DEBUG_WARNING (true, ("player tried to delete something not in their inventory")); + DEBUG_WARNING(true, ("player tried to delete something not in their inventory")); return; } ProsePackage pp; - const bool sendResponse = !params.empty (); + const bool sendResponse = !params.empty(); - int const got = targetObject->getGameObjectType (); + int const got = targetObject->getGameObjectType(); if (sendResponse) { - ProsePackageManagerServer::createSimpleProsePackage (*targetObject, SharedStringIds::rsp_object_deleted_prose, pp); - pp.other.stringId = GameObjectTypes::getStringId (got); + ProsePackageManagerServer::createSimpleProsePackage(*targetObject, SharedStringIds::rsp_object_deleted_prose, pp); + pp.other.stringId = GameObjectTypes::getStringId(got); } // Cannot destroy an empty ship pcd while contained by a ship you own @@ -6769,7 +6726,7 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a return; Object const * const currentContainer = ContainerInterface::getContainedByObject(*targetObject); - if(currentContainer && currentContainer->asServerObject() && ( currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron || currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron_recipe ) ) + if (currentContainer && currentContainer->asServerObject() && (currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron || currentContainer->asServerObject()->getGameObjectType() == SharedObjectTemplate::GOT_chronicles_quest_holocron_recipe)) { // Give the player a warning here? return; @@ -6779,10 +6736,10 @@ static void commandFuncServerDestroyObject (Command const &, NetworkId const & a { LOG("CustomerService", ("Deletion:%s is deleting object %s", PlayerObject::getAccountDescription(actor).c_str(), ServerObject::getLogDescription(targetObject).c_str())); if (sendResponse) - Chat::sendSystemMessage (*player, pp); + Chat::sendSystemMessage(*player, pp); } else - WARNING (true, ("commandFuncServerDestroyObject: Error encountered while deleting object %s", target.getValueString ().c_str ())); + WARNING(true, ("commandFuncServerDestroyObject: Error encountered while deleting object %s", target.getValueString().c_str())); } // ---------------------------------------------------------------------- @@ -6792,11 +6749,11 @@ static void commandFuncSetSpokenLanguage(Command const &, NetworkId const &actor Object * const object = NetworkIdManager::getObjectById(actor); CreatureObject * const creatureObject = dynamic_cast(object); - if (creatureObject != NULL) + if (creatureObject != nullptr) { PlayerObject *playerObject = PlayerCreatureController::getPlayerObject(creatureObject); - if (playerObject != NULL) + if (playerObject != nullptr) { size_t pos = 0; int const languageId = nextIntParm(params, pos); @@ -6831,14 +6788,14 @@ static void commandFuncUnstick(Command const &, NetworkId const &actor, NetworkI { Object * const object = NetworkIdManager::getObjectById(actor); CreatureObject * const creatureObject = dynamic_cast(object); - if (creatureObject != NULL) + if (creatureObject != nullptr) { if (!ShipObject::getContainingShipObject(creatureObject)) // no unsticking in ships { PlayerObject * const playerObject = PlayerCreatureController::getPlayerObject(creatureObject); if (playerObject) { - Chat::sendSystemMessageSimple(*creatureObject, SharedStringIds::unstick_in_progress, NULL); + Chat::sendSystemMessageSimple(*creatureObject, SharedStringIds::unstick_in_progress, nullptr); if (!playerObject->getIsUnsticking()) { Vector position = creatureObject->getPosition_p(); @@ -6875,10 +6832,10 @@ static void commandFuncUnstick(Command const &, NetworkId const &actor, NetworkI static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { const CreatureObject * gm = dynamic_cast(NetworkIdManager::getObjectById(actor)); - if(gm) + if (gm) { const Client * gmClient = gm->getClient(); - if(gmClient) + if (gmClient) { bool foundAsPilot = false; const CreatureObject * player = dynamic_cast(NetworkIdManager::getObjectById(target)); @@ -6892,23 +6849,23 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N } } std::string result; - if(player) + if (player) { const Client * client = player->getClient(); - if(client) + if (client) { if (foundAsPilot) - result = "Pilot Character Name : "; + result = "Pilot Character Name : "; else - result = "Character Name : "; + result = "Character Name : "; result += Unicode::wideToNarrow(player->getAssignedObjectName()); result += "\nAccount Name : "; result += client->getAccountName(); result += "\nStation Id : "; char buf[32]; - IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "%d", client->getStationId())); - buf[sizeof(buf)-1] = '\0'; + IGNORE_RETURN(snprintf(buf, sizeof(buf) - 1, "%d", client->getStationId())); + buf[sizeof(buf) - 1] = '\0'; result += buf; result += "\nGame Features : "; result += ClientGameFeature::getDescription(client->getGameFeatures()); @@ -6936,7 +6893,7 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N result += "\nIP Address : "; result += client->getIpAddress(); result += "\nGod Mode : "; - if(client->isGod()) + if (client->isGod()) result += "true"; else result += "false"; @@ -6958,28 +6915,28 @@ static void commandFuncGetAccountInfo(Command const &, NetworkId const &actor, N // ---------------------------------------------------------------------- -static void commandFuncApplyPowerup (Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) +static void commandFuncApplyPowerup(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { - const NetworkId & powerupId = target; - const NetworkId targetOfApplyId (Unicode::wideToNarrow (params)); - ServerObject * const powerup = safe_cast(NetworkIdManager::getObjectById (powerupId)); + const NetworkId & powerupId = target; + const NetworkId targetOfApplyId(Unicode::wideToNarrow(params)); + ServerObject * const powerup = safe_cast(NetworkIdManager::getObjectById(powerupId)); if (powerup) { - const ServerObject * const targetOfApply = safe_cast(NetworkIdManager::getObjectById (targetOfApplyId)); + const ServerObject * const targetOfApply = safe_cast(NetworkIdManager::getObjectById(targetOfApplyId)); if (targetOfApply) { - const int got_targetOfApply = targetOfApply->getGameObjectType (); - const int got_powerup = powerup->getGameObjectType (); + const int got_targetOfApply = targetOfApply->getGameObjectType(); + const int got_powerup = powerup->getGameObjectType(); - if (GameObjectTypes::doesPowerupApply (got_powerup, got_targetOfApply)) + if (GameObjectTypes::doesPowerupApply(got_powerup, got_targetOfApply)) { GameScriptObject * const gso = powerup->getScriptObject(); if (gso) { ScriptParams scriptParams; - scriptParams.addParam (actor); - scriptParams.addParam (targetOfApplyId); + scriptParams.addParam(actor); + scriptParams.addParam(targetOfApplyId); gso->trigAllScripts(Scripting::TRIG_APPLY_POWERUP, scriptParams); } } @@ -6989,20 +6946,20 @@ static void commandFuncApplyPowerup (Command const &, NetworkId const &actor, Ne // ---------------------------------------------------------------------- -static void commandFuncLag (Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) +static void commandFuncLag(Command const &, NetworkId const &actor, NetworkId const & target, Unicode::String const ¶ms) { #if 0 ServerObject * a = safe_cast(NetworkIdManager::getObjectById(actor)); ServerObject * t = safe_cast(NetworkIdManager::getObjectById(target)); - if(! t) + if (!t) { t = a; } - if(t != 0) + if (t != 0) { - if(t->getClient()) + if (t->getClient()) { - if(a && a->getClient()) + if (a && a->getClient()) { GameNetworkMessage const request("LagRequest"); t->getClient()->send(request, true); @@ -7021,7 +6978,7 @@ static void commandFuncLag (Command const &, NetworkId const &actor, NetworkId c // ---------------------------------------------------------------------- -static void commandExecuteKnowledgeBaseMessage (Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandExecuteKnowledgeBaseMessage(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { UNREF(actor); UNREF(params); @@ -7050,7 +7007,7 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act std::string objectTemplateName; bool useTarget = false; - size_t pos = 0; + size_t pos = 0; do { @@ -7062,15 +7019,15 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act } while (!token.empty()); //-- Log attempt. - NetworkId subjectNetworkId = useTarget ? target: actor; + NetworkId subjectNetworkId = useTarget ? target : actor; - LOG("setPlayerAppearance", + LOG("setPlayerAppearance", ("commandFuncSetPlayerAppearance(): command called by actor id=[%s]: attempting to change appearance for player id=[%s], using appearance info from object template=[%s], subject=[%s]", - actor.getValueString().c_str(), - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str(), - useTarget ? "target" : "self" - )); + actor.getValueString().c_str(), + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str(), + useTarget ? "target" : "self" + )); //-- Validate parameters. if (subjectNetworkId == NetworkId::cms_invalid) @@ -7096,11 +7053,11 @@ static void commandFuncSetPlayerAppearance(Command const &, NetworkId const &act // Ensure non-default object template name refers to an existing file. if (!TreeFile::exists(objectTemplateName.c_str())) { - WARNING(true, + WARNING(true, ("commandFuncSetPlayerAppearance(): could not change id=[%s] to non-default object template name=[%s]: object template does not exist", - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str() - )); + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str() + )); return; } } @@ -7124,7 +7081,7 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & std::string objectTemplateName; bool useTarget = false; - size_t pos = 0; + size_t pos = 0; do { @@ -7136,15 +7093,15 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & } while (!token.empty()); //-- Log attempt. - NetworkId subjectNetworkId = useTarget ? target: actor; + NetworkId subjectNetworkId = useTarget ? target : actor; - LOG("setPlayerAppearance", + LOG("setPlayerAppearance", ("commandFuncRevertPlayerAppearance(): command called by actor id=[%s]: attempting to change appearance for player id=[%s], using appearance info from object template=[%s], subject=[%s]", - actor.getValueString().c_str(), - subjectNetworkId.getValueString().c_str(), - objectTemplateName.c_str(), - useTarget ? "target" : "self" - )); + actor.getValueString().c_str(), + subjectNetworkId.getValueString().c_str(), + objectTemplateName.c_str(), + useTarget ? "target" : "self" + )); //-- Validate parameters. if (subjectNetworkId == NetworkId::cms_invalid) @@ -7175,7 +7132,7 @@ static void commandFuncRevertPlayerAppearance(Command const &, NetworkId const & //----------------------------------------------------------------------- -static void commandFuncReconnectToTransferServer(Command const &, NetworkId const &, NetworkId const & , Unicode::String const &) +static void commandFuncReconnectToTransferServer(Command const &, NetworkId const &, NetworkId const &, Unicode::String const &) { GameNetworkMessage const msg("ReconnectToTransferServer"); GameServer::getInstance().sendToCentralServer(msg); @@ -7183,17 +7140,17 @@ static void commandFuncReconnectToTransferServer(Command const &, NetworkId cons //----------------------------------------------------------------------- -static void commandFuncFindFriend(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandFuncFindFriend(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { ServerObject * a = safe_cast(NetworkIdManager::getObjectById(actor)); - if(a && a->getClient()) + if (a && a->getClient()) { size_t pos = 0; - const std::string playerName = nextStringParm (params, pos); + const std::string playerName = nextStringParm(params, pos); CreatureObject * creatureObject = a->asCreatureObject(); - if(creatureObject) + if (creatureObject) { - if(! playerName.empty()) + if (!playerName.empty()) { // break the name down into its subcomponents ChatAvatarId const cav(NameManager::normalizeName(playerName)); @@ -7210,7 +7167,7 @@ static void commandFuncFindFriend(Command const &, NetworkId const &actor, Netwo else { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(creatureObject); - if(playerObject) + if (playerObject) { playerObject->findFriend(cav.name); } @@ -7220,7 +7177,7 @@ static void commandFuncFindFriend(Command const &, NetworkId const &actor, Netwo { // playerName is empty, send an error to requesting client StringId stringId = StringId("ui_cmnty", "friend_location_failed_usage"); - Chat::sendSystemMessage(*creatureObject, stringId, Unicode::emptyString); + Chat::sendSystemMessage(*creatureObject, stringId, Unicode::emptyString); } } } @@ -7233,87 +7190,87 @@ static void commandFuncFormCommand(Command const &, NetworkId const & actor, Net UNREF(target); Unicode::UnicodeStringVector tokens; - IGNORE_RETURN(Unicode::tokenize (params, tokens)); + IGNORE_RETURN(Unicode::tokenize(params, tokens)); - if(tokens.size() == 0) + if (tokens.size() == 0) return; std::string const commandStr = Unicode::wideToNarrow(tokens[0]); FormManager::Command const command = static_cast(atoi(commandStr.c_str())); - switch(command) + switch (command) { - case FormManager::CREATE_OBJECT: + case FormManager::CREATE_OBJECT: + { + if (tokens.size() < 5) + return; + + std::string const templateName = Unicode::wideToNarrow(tokens[1]); + + std::string const & xStr = Unicode::wideToNarrow(tokens[2]); + std::string const & yStr = Unicode::wideToNarrow(tokens[3]); + std::string const & zStr = Unicode::wideToNarrow(tokens[4]); + std::string const & cellStr = Unicode::wideToNarrow(tokens[5]); + NetworkId const cellId(cellStr); + + float const x = static_cast(atof(xStr.c_str())); + float const y = static_cast(atof(yStr.c_str())); + float const z = static_cast(atof(zStr.c_str())); + + //we must have an odd number of tokens left (so that the datamap has a full key->value mapping) + if (tokens.size() % 2 != 0) + return; + + //TODO centralize pack/unpack + FormManager::UnpackedFormData dataMap; + std::vector values; + for (int i = 6; i < static_cast(tokens.size()) - 1; i += 2) { - if(tokens.size() < 5) - return; - - std::string const templateName = Unicode::wideToNarrow(tokens[1]); - - std::string const & xStr = Unicode::wideToNarrow(tokens[2]); - std::string const & yStr = Unicode::wideToNarrow(tokens[3]); - std::string const & zStr = Unicode::wideToNarrow(tokens[4]); - std::string const & cellStr = Unicode::wideToNarrow(tokens[5]); - NetworkId const cellId(cellStr); - - float const x = static_cast(atof(xStr.c_str())); - float const y = static_cast(atof(yStr.c_str())); - float const z = static_cast(atof(zStr.c_str())); - - //we must have an odd number of tokens left (so that the datamap has a full key->value mapping) - if(tokens.size() % 2 != 0) - return; - - //TODO centralize pack/unpack - FormManager::UnpackedFormData dataMap; - std::vector values; - for(int i = 6; i < static_cast(tokens.size()) - 1; i += 2) - { - std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); - std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); - values.clear(); - values.push_back(value); - dataMap[key] = values; - } - - FormManagerServer::handleCreateObjectData(actor, templateName, Vector(x, y, z), cellId, dataMap); - break; + std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); + std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); + values.clear(); + values.push_back(value); + dataMap[key] = values; } - case FormManager::EDIT_OBJECT: + FormManagerServer::handleCreateObjectData(actor, templateName, Vector(x, y, z), cellId, dataMap); + break; + } + + case FormManager::EDIT_OBJECT: + { + if (tokens.size() < 1) + return; + + //we must have an even number of tokens left (so that the datamap has a full key->value mapping) + if (tokens.size() % 2 != 1) + return; + + //TODO centralize pack/unpack + FormManager::UnpackedFormData dataMap; + std::vector values; + for (int i = 1; i < static_cast(tokens.size()) - 1; i += 2) { - if(tokens.size() < 1) - return; - - //we must have an even number of tokens left (so that the datamap has a full key->value mapping) - if(tokens.size() % 2 != 1) - return; - - //TODO centralize pack/unpack - FormManager::UnpackedFormData dataMap; - std::vector values; - for(int i = 1; i < static_cast(tokens.size()) - 1; i += 2) - { - std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); - std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); - values.clear(); - values.push_back(value); - dataMap[key] = values; - } - - FormManagerServer::handleEditObjectData(actor, target, dataMap); - break; + std::string const & key = Unicode::wideToNarrow(tokens[static_cast(i)]); + std::string const & value = Unicode::wideToNarrow(tokens[static_cast(i + 1)]); + values.clear(); + values.push_back(value); + dataMap[key] = values; } - case FormManager::REQUEST_EDIT_OBJECT: - { - FormManagerServer::requestEditObjectDataForClient(actor, target); - break; - } + FormManagerServer::handleEditObjectData(actor, target, dataMap); + break; + } - default: - DEBUG_FATAL(true, ("Unknown command in commandFuncFormCommand")); - break; + case FormManager::REQUEST_EDIT_OBJECT: + { + FormManagerServer::requestEditObjectDataForClient(actor, target); + break; + } + + default: + DEBUG_FATAL(true, ("Unknown command in commandFuncFormCommand")); + break; } } @@ -7322,25 +7279,25 @@ static void commandFuncFormCommand(Command const &, NetworkId const & actor, Net static void commandFuncInstallShipComponents(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { //params for installShipComponent are " " - + Object const * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) { return; } //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); - ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : NULL; - if( !targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7351,17 +7308,17 @@ static void commandFuncInstallShipComponents(Command const &, NetworkId const & size_t pos = 0; NetworkId const & shipId = nextOidParm(params, pos); Object * const shipObj = NetworkIdManager::getObjectById(shipId); - ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : NULL; - ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : NULL; - if(!ship) + ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; + ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); NetworkId const & componentId = nextOidParm(params, pos); Object * const componentObj = NetworkIdManager::getObjectById(componentId); - ServerObject * const componentServerObj = componentObj ? componentObj->asServerObject() : NULL; - TangibleObject * const component = componentServerObj ? componentServerObj->asTangibleObject() : NULL; - if(!component) + ServerObject * const componentServerObj = componentObj ? componentObj->asServerObject() : nullptr; + TangibleObject * const component = componentServerObj ? componentServerObj->asTangibleObject() : nullptr; + if (!component) { return; } @@ -7383,14 +7340,14 @@ static void commandFuncInstallShipComponents(Command const &, NetworkId const & if (containedByObject) { SlottedContainer const * const slottedContainer = ContainerInterface::getSlottedContainer(*containedByObject); - if(slottedContainer) + if (slottedContainer) { SlotId const & slotId = slottedContainer->findFirstSlotIdForObject(component->getNetworkId()); - if(slotId != SlotId::invalid) + if (slotId != SlotId::invalid) { - if(!ContainerInterface::canPlayerManipulateSlot(slotId)) + if (!ContainerInterface::canPlayerManipulateSlot(slotId)) { - StringId cantManipulateId("player_utility", "cannot_manipulate_slot"); + StringId cantManipulateId("player_utility", "cannot_manipulate_slot"); Chat::sendSystemMessage(*actorCreature, cantManipulateId, Unicode::emptyString); return; } @@ -7409,25 +7366,25 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const //params for uninstallShipComponent are " " Object * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) return; ServerObject * const actorInv = actorCreature->getInventory(); - if(!actorInv) + if (!actorInv) return; //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); - ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : NULL; - if(!targetServerObj || - ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) - && (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; + if (!targetServerObj || + ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) + && (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7436,13 +7393,13 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const } ServerObject const * const actorInventoryObject = actorCreature->getInventory(); - if(!actorInventoryObject) + if (!actorInventoryObject) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::shipcomponentinstall_noinventory, Unicode::emptyString); return; } VolumeContainer const * const inventoryContainer = ContainerInterface::getVolumeContainer(*actorInventoryObject); - if(!inventoryContainer) + if (!inventoryContainer) { Chat::sendSystemMessage(*actorCreature, SharedStringIds::shipcomponentinstall_noinventorycontainer, Unicode::emptyString); return; @@ -7456,9 +7413,9 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const size_t pos = 0; NetworkId const & shipId = nextOidParm(params, pos); Object * const shipObj = NetworkIdManager::getObjectById(shipId); - ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : NULL; - ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : NULL; - if(!ship) + ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; + ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); @@ -7466,7 +7423,6 @@ static void commandFuncUninstallShipComponents(Command const &, NetworkId const IGNORE_RETURN(ship->uninstallComponent(actor, slotType, *actorInv)); } - // ---------------------------------------------------------------------- static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) @@ -7474,21 +7430,21 @@ static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkI //params for insertItemIntoShipComponentSlot are " " Object * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + ServerObject * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) return; //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); - ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : NULL; - if(!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7499,14 +7455,14 @@ static void commandFuncInsertItemIntoShipComponentSlot(Command const &, NetworkI size_t pos = 0; NetworkId const & shipId = nextOidParm(params, pos); Object * const shipObj = NetworkIdManager::getObjectById(shipId); - ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : NULL; - ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : NULL; - if(!ship) + ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; + ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; + if (!ship) return; ShipChassisSlotType::Type const slotType = static_cast(nextIntParm(params, pos)); - if(!ship->isSlotInstalled(slotType)) + if (!ship->isSlotInstalled(slotType)) return; NetworkId const componentId = nextOidParm(params, pos); @@ -7527,21 +7483,21 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw //params for associateDroidControlDeviceWithShip are " " Object const * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; + ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; if (!actorCreature) return; //they must be near a space terminal (if not a god) Client const * const client = actorCreature->getClient(); - if(!client) + if (!client) return; - if(!client->isGod()) + if (!client->isGod()) { Object * const targetObj = NetworkIdManager::getObjectById(target); - ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : NULL; - if(!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && - (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe)) ) + ServerObject * const targetServerObj = targetObj ? targetObj->asServerObject() : nullptr; + if (!targetServerObj || ((targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) && + (targetServerObj->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space_npe))) return; } else @@ -7552,9 +7508,9 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw size_t pos = 0; NetworkId const & shipId = nextOidParm(params, pos); Object * const shipObj = NetworkIdManager::getObjectById(shipId); - ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : NULL; - ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : NULL; - if(!ship) + ServerObject * const shipServerObj = shipObj ? shipObj->asServerObject() : nullptr; + ShipObject * const ship = shipServerObj ? shipServerObj->asShipObject() : nullptr; + if (!ship) return; NetworkId const droidControlDeviceId = nextOidParm(params, pos); @@ -7578,12 +7534,12 @@ static void commandFuncAssociateDroidControlDeviceWithShip(Command const &, Netw // ---------------------------------------------------------------------- -static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & ) +static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const &) { Object const * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) return; ServerAsteroidManager::listenforServerAsteroidDebugData(actor); @@ -7591,12 +7547,12 @@ static void commandFuncServerAsteroidDataListen(Command const &, NetworkId const // ---------------------------------------------------------------------- -static void commandFuncServerAsteroidDataStopListening(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & ) +static void commandFuncServerAsteroidDataStopListening(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const &) { Object const * const actorObj = NetworkIdManager::getObjectById(actor); - ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : NULL; - CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + ServerObject const * const actorServerObj = actorObj ? actorObj->asServerObject() : nullptr; + CreatureObject const * const actorCreature = actorServerObj ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) return; ServerAsteroidManager::endListenforServerAsteroidDebugData(actor); @@ -7621,23 +7577,23 @@ static void commandFuncBoosterOff(Command const &, NetworkId const & actor, Netw static void commandFuncSetFormation(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const & params) { Object * const o = NetworkIdManager::getObjectById(actor); - ServerObject * const so = o ? o->asServerObject() : NULL; - CreatureObject * const actorCreature = so ? so->asCreatureObject() : NULL; - if(actorCreature) + ServerObject * const so = o ? o->asServerObject() : nullptr; + CreatureObject * const actorCreature = so ? so->asCreatureObject() : nullptr; + if (actorCreature) { GroupObject * const group = actorCreature->getGroup(); - if(group) + if (group) { - if(group->getGroupLeaderId() == actor) + if (group->getGroupLeaderId() == actor) { std::string paramsNarrow = Unicode::wideToNarrow(params); - if(paramsNarrow == "none") + if (paramsNarrow == "none") { group->setFormationNameCrc(Crc::crcNull); } else { - if(PlayerFormationManager::isValidFormationName(paramsNarrow)) + if (PlayerFormationManager::isValidFormationName(paramsNarrow)) group->setFormationNameCrc(Crc::normalizeAndCalculate(paramsNarrow.c_str())); } } @@ -7676,15 +7632,15 @@ static void commandFuncUnDock(Command const &, NetworkId const & actor, NetworkI { Object * const object = NetworkIdManager::getObjectById(actor); - if (object != NULL) + if (object != nullptr) { ShipObject * const shipObject = ShipObject::getContainingShipObject(object->asServerObject()); - if (shipObject != NULL) + if (shipObject != nullptr) { ShipController * const shipController = dynamic_cast(shipObject->getController()); - if (shipController != NULL) + if (shipController != nullptr) { shipController->unDock(); } @@ -7695,28 +7651,28 @@ static void commandFuncUnDock(Command const &, NetworkId const & actor, NetworkI } else { - WARNING(true, ("commandFuncUnDock() Undock requested on an object(%s) contained by a NULL ShipObject.", object->getDebugInformation().c_str())); + WARNING(true, ("commandFuncUnDock() Undock requested on an object(%s) contained by a nullptr ShipObject.", object->getDebugInformation().c_str())); } } else { - WARNING(true, ("commandFuncUnDock() Undock requested on a NULL object(%s).", actor.getValueString().c_str())); + WARNING(true, ("commandFuncUnDock() Undock requested on a nullptr object(%s).", actor.getValueString().c_str())); } } - + //---------------------------------------------------------------------- static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncLaunchIntoSpace")); return; } - if(!target.isValid()) + if (!target.isValid()) { StringId invalidTargetId("player_utility", "invalid_target"); Chat::sendSystemMessage(*actorCreature, invalidTargetId, Unicode::emptyString); @@ -7725,14 +7681,14 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, //target must be a space terminal Object const * const o = NetworkIdManager::getObjectById(target); - ServerObject const * const so = o ? o->asServerObject() : NULL; - if(!so) + ServerObject const * const so = o ? o->asServerObject() : nullptr; + if (!so) { StringId invalidTargetId("player_utility", "target_not_server_object"); Chat::sendSystemMessage(*actorCreature, invalidTargetId, Unicode::emptyString); return; } - if(so->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) + if (so->getGameObjectType() != SharedObjectTemplate::GOT_terminal_space) { ProsePackage p; p.stringId = StringId("player_utility", "not_space_terminal"); @@ -7744,35 +7700,35 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, } Unicode::UnicodeStringVector tokens; - Unicode::tokenize (params, tokens); - - if(tokens.empty()) + Unicode::tokenize(params, tokens); + + if (tokens.empty()) { Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide("(unlocalized) No parameters."), Unicode::emptyString); return; } NetworkId const shipPCDId(Unicode::wideToNarrow(tokens[0]).c_str()); - if(!shipPCDId.isValid()) + if (!shipPCDId.isValid()) { Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide("(unlocalized) Invalid ship."), Unicode::emptyString); return; } Object * const terminalO = NetworkIdManager::getObjectById(target); - ServerObject * const terminalSO = terminalO ? terminalO->asServerObject() : NULL; - if(terminalSO) + ServerObject * const terminalSO = terminalO ? terminalO->asServerObject() : nullptr; + if (terminalSO) { std::vector networkIds; unsigned int tokenIndex = 1; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { int const numberOfNetworkIds = atoi(Unicode::wideToNarrow(tokens[tokenIndex]).c_str()); for (int i = 0; i < numberOfNetworkIds; ++i) { ++tokenIndex; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { NetworkId const Id(Unicode::wideToNarrow(tokens[tokenIndex])); if (Id.isValid()) @@ -7781,13 +7737,13 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, } } } - } + } ++tokenIndex; //adding an empty string is fine (it means they aren't traveling to another ground starport) std::string strPointPlanetResult; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { strPointPlanetResult = Unicode::wideToNarrow(tokens[tokenIndex]); } @@ -7796,10 +7752,10 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, //adding an empty string is fine (it means they aren't traveling to another ground starport) std::string strPointLocationResult; - if(tokens.size() > tokenIndex) + if (tokens.size() > tokenIndex) { strPointLocationResult = Unicode::wideToNarrow(tokens[tokenIndex]); - std::replace (strPointLocationResult.begin (), strPointLocationResult.end (), '_', ' '); + std::replace(strPointLocationResult.begin(), strPointLocationResult.end(), '_', ' '); } ScriptParams params; @@ -7824,21 +7780,21 @@ static void commandFuncLaunchIntoSpace(Command const &, NetworkId const & actor, static void commandFuncAcceptQuest(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncAcceptQuest")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncAcceptQuest")); return; } uint32 const questCrc = atoi(Unicode::wideToNarrow(params).c_str()); - if(playerObject->getPendingRequestQuestCrc() == questCrc) + if (playerObject->getPendingRequestQuestCrc() == questCrc) { NetworkId const & questGiver = playerObject->getPendingRequestQuestGiver(); playerObject->questActivateQuest(questCrc, questGiver); @@ -7851,30 +7807,30 @@ static void commandFuncAcceptQuest(Command const &, NetworkId const & actor, Net static void commandFuncReceiveReward(Command const &, NetworkId const & actor, NetworkId const & target, Unicode::String const & params) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncReceiveReward")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncReceiveReward")); return; } Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); - - if(sv.empty()) + Unicode::tokenize(params, sv); + + if (sv.empty()) return; uint32 const questCrc = atoi(Unicode::wideToNarrow(sv[0]).c_str()); std::string selectedReward; - if(sv.size() > 1) + if (sv.size() > 1) selectedReward = Unicode::wideToNarrow(sv[1]); - if((playerObject->getPendingRequestQuestCrc() == questCrc) || playerObject->questPlayerCanClaimRewardFor(questCrc)) + if ((playerObject->getPendingRequestQuestCrc() == questCrc) || playerObject->questPlayerCanClaimRewardFor(questCrc)) { playerObject->questGrantQuestReward(questCrc, selectedReward); playerObject->setPendingRequestQuestInformation(0, NetworkId::cms_invalid); @@ -7883,26 +7839,26 @@ static void commandFuncReceiveReward(Command const &, NetworkId const & actor, N //---------------------------------------------------------------------- -static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, NetworkId const & , Unicode::String const & params) +static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, NetworkId const &, Unicode::String const & params) { size_t pos = 0; - + //not currently used, but can distinguish between different quest types int const questSystemType = nextIntParm(params, pos); UNREF(questSystemType); std::string const & questName = nextStringParm(params, pos); - if(QuestManager::isQuestAbandonable(questName)) + if (QuestManager::isQuestAbandonable(questName)) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - if(actorCreature) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + if (actorCreature) { PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(playerObject) + if (playerObject) { Quest const * const q = QuestManager::getQuest(questName); - if(q && playerObject->questHasActiveQuest(q->getId()) && !playerObject->questHasCompletedQuest(q->getId())) + if (q && playerObject->questHasActiveQuest(q->getId()) && !playerObject->questHasCompletedQuest(q->getId())) { LOG("Quest", ("Abandon:%s abandoned quest [%s] with status [0x%08X].\n", PlayerObject::getAccountDescription(actorServerObj->getClient()->getCharacterObjectId()).c_str(), @@ -7915,43 +7871,39 @@ static void commandFuncAbandonQuest(Command const &, NetworkId const & actor, Ne } } - - // ---------------------------------------------------------------------- static void commandFuncExchangeListCredits(Command const &, NetworkId const &actor, NetworkId const &target, Unicode::String const ¶ms) { ServerObject * const actorServerObj = safe_cast(NetworkIdManager::getObjectById(actor)); - CreatureObject * const actorCreature = actorServerObj != NULL ? actorServerObj->asCreatureObject() : NULL; - if(!actorCreature) + CreatureObject * const actorCreature = actorServerObj != nullptr ? actorServerObj->asCreatureObject() : nullptr; + if (!actorCreature) { WARNING(true, ("No actorCreature in commandFuncReceiveReward")); return; } PlayerObject * playerObject = PlayerCreatureController::getPlayerObject(actorCreature); - if(!playerObject) + if (!playerObject) { WARNING(true, ("No playerObject in commandFuncReceiveReward")); return; } Unicode::UnicodeStringVector sv; - Unicode::tokenize (params, sv); - - if(sv.empty()) + Unicode::tokenize(params, sv); + + if (sv.empty()) return; uint32 const credits = (uint32)atoi(Unicode::wideToNarrow(sv[0]).c_str()); - if ( credits <= 0 ) + if (credits <= 0) return; - char message[512]; - sprintf(message,"Listing %ld credits on station exchange.", credits); + sprintf(message, "Listing %ld credits on station exchange.", credits); Chat::sendSystemMessage(*actorCreature, Unicode::narrowToWide(message), Unicode::emptyString); - ExchangeListCreditsMessage const msg(actor, credits, GameServer::getInstance().getProcessId()); - GameServer::getInstance().sendToCentralServer(msg); + GameServer::getInstance().sendToCentralServer(msg); } //----------------------------------------------------------------------- @@ -7975,8 +7927,8 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -7985,8 +7937,8 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -7995,22 +7947,22 @@ static void commandFuncSquelch(Command const &, NetworkId const &actor, NetworkI PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->getSecondsUntilUnsquelched() < 0) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is already squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is already squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Squelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Squelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8044,8 +7996,8 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8054,8 +8006,8 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8064,22 +8016,22 @@ static void commandFuncUnsquelch(Command const &, NetworkId const &actor, Networ PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->getSecondsUntilUnsquelched() == 0) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not currently squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not currently squelched", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Unsquelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Unsquelching %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8113,8 +8065,8 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8123,8 +8075,8 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8133,22 +8085,22 @@ static void commandFuncGrantWarden(Command const &, NetworkId const &actor, Netw PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (p->isWarden()) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is already a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is already a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Granting warden to %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Granting warden to %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8184,8 +8136,8 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net ServerObject * so = dynamic_cast(NetworkIdManager::getObjectById(target)); if (!so) { - snprintf(buffer, sizeof(buffer)-1, "Error! Cannot find object for %s", target.getValueString().c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! Cannot find object for %s", target.getValueString().c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8194,8 +8146,8 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net CreatureObject * c = so->asCreatureObject(); if (!c) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a creature object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } @@ -8204,22 +8156,22 @@ static void commandFuncRevokeWarden(Command const &, NetworkId const &actor, Net PlayerObject * p = PlayerCreatureController::getPlayerObject(c); if (!p) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a player object", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else if (!p->isWarden()) { - snprintf(buffer, sizeof(buffer)-1, "Error! %s (%s) is not a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Error! %s (%s) is not a warden", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); } else { - snprintf(buffer, sizeof(buffer)-1, "Revoking warden from %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "Revoking warden from %s (%s)", target.getValueString().c_str(), Unicode::wideToNarrow(so->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; ConGenericMessage const msg(buffer, 0); gmClient->send(msg, true); @@ -8293,8 +8245,8 @@ static void commandFuncSpammer(Command const &, NetworkId const &actor, NetworkI { // send a messageTo to the target to do apply the /spammer operation char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s %s", actor.getValueString().c_str(), Unicode::wideToNarrow(gm->getAssignedObjectName()).c_str()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s %s", actor.getValueString().c_str(), Unicode::wideToNarrow(gm->getAssignedObjectName()).c_str()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++SpammerReq", @@ -8554,8 +8506,8 @@ static void commandFuncDeputizeWarden(Command const &, NetworkId const &actor, N // send a messageTo to the target to complete the deputize process char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++DeputizeWardenReq", @@ -8617,8 +8569,8 @@ static void commandFuncUndeputizeWarden(Command const &, NetworkId const &actor, // send a messageTo to the target to complete the undeputize process char buffer[1024]; - snprintf(buffer, sizeof(buffer)-1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); - buffer[sizeof(buffer)-1] = '\0'; + snprintf(buffer, sizeof(buffer) - 1, "%s|%lu", gm->getNetworkId().getValueString().c_str(), gmPlayerObject->getStationId()); + buffer[sizeof(buffer) - 1] = '\0'; MessageToQueue::getInstance().sendMessageToC(parsedNetworkId, "C++UndeputizeWardenReq", @@ -8633,7 +8585,7 @@ static void commandFuncUndeputizeWarden(Command const &, NetworkId const &actor, //----------------------------------------------------------------------- -static void commandFuncRemoveBuff(Command const &, NetworkId const &actor, NetworkId const & , Unicode::String const ¶ms) +static void commandFuncRemoveBuff(Command const &, NetworkId const &actor, NetworkId const &, Unicode::String const ¶ms) { CreatureObject * player = dynamic_cast(NetworkIdManager::getObjectById(actor)); if (player) @@ -8680,7 +8632,7 @@ static void commandFuncOccupyUnlockedSlot(Command const &, NetworkId const &acto } // check to see if there is a cooldown is in effect for the command - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!gmClient->isGod() && gm->getObjVars().hasItem("timeNextOccupyVacateUnlockedSlotCommandAllowed") && (gm->getObjVars().getType("timeNextOccupyVacateUnlockedSlotCommandAllowed") == DynamicVariable::INT)) { int timeNextOccupyVacateUnlockedSlotCommandAllowed = 0; @@ -8699,7 +8651,7 @@ static void commandFuncOccupyUnlockedSlot(Command const &, NetworkId const &acto } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting OccupyUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting OccupyUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); // send off request to LoginServer to make this character occupy the unlocked slot GenericValueTypeMessage, uint32> > const occupyUnlockedSlotReq("OccupyUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), GameServer::getInstance().getProcessId())); @@ -8746,7 +8698,7 @@ static void commandFuncVacateUnlockedSlot(Command const &, NetworkId const &acto } // check to see if there is a cooldown is in effect for the command - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!gmClient->isGod() && gm->getObjVars().hasItem("timeNextOccupyVacateUnlockedSlotCommandAllowed") && (gm->getObjVars().getType("timeNextOccupyVacateUnlockedSlotCommandAllowed") == DynamicVariable::INT)) { int timeNextOccupyVacateUnlockedSlotCommandAllowed = 0; @@ -8765,7 +8717,7 @@ static void commandFuncVacateUnlockedSlot(Command const &, NetworkId const &acto } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting VacateUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting VacateUnlockedSlot", PlayerObject::getAccountDescription(gm).c_str())); // send off request to LoginServer to make this character vacate the unlocked slot GenericValueTypeMessage, uint32> > const vacateUnlockedSlotReq("VacateUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), GameServer::getInstance().getProcessId())); @@ -8834,7 +8786,7 @@ static void commandFuncSwapUnlockedSlot(Command const &, NetworkId const &actor, } // check to see if there is a cooldown is in effect for the command - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!gmClient->isGod() && gm->getObjVars().hasItem("timeNextOccupyVacateUnlockedSlotCommandAllowed") && (gm->getObjVars().getType("timeNextOccupyVacateUnlockedSlotCommandAllowed") == DynamicVariable::INT)) { int timeNextOccupyVacateUnlockedSlotCommandAllowed = 0; @@ -8853,7 +8805,7 @@ static void commandFuncSwapUnlockedSlot(Command const &, NetworkId const &actor, } // CS log the request - LOG("CustomerService",("JediUnlockedSlot:%s requesting SwapUnlockedSlot with %s (%s)", PlayerObject::getAccountDescription(gm).c_str(), parsedNetworkId.getValueString().c_str(), NameManager::getInstance().getPlayerFullName(parsedNetworkId).c_str())); + LOG("CustomerService", ("JediUnlockedSlot:%s requesting SwapUnlockedSlot with %s (%s)", PlayerObject::getAccountDescription(gm).c_str(), parsedNetworkId.getValueString().c_str(), NameManager::getInstance().getPlayerFullName(parsedNetworkId).c_str())); // send off request to LoginServer to make this character normal and the target characer unlocked GenericValueTypeMessage, std::pair > > const swapUnlockedSlotReq("SwapUnlockedSlotReq", std::make_pair(std::make_pair(static_cast(gmPlayerObject->getStationId()), actor), std::make_pair(GameServer::getInstance().getProcessId(), parsedNetworkId))); @@ -8902,7 +8854,7 @@ static void commandFuncPickupAllRoomItemsIntoInventory(Command const &, NetworkI return; // don't allow multiple /pickupAllRoomItemsIntoInventory and/or /dropAllInventoryItemsIntoRoom - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); int pickupDropAllItemsOperationTimeout = 0; if (targetObj->getObjVars().getItem("pickupDropAllItemsOperation.timeout", pickupDropAllItemsOperationTimeout) && (pickupDropAllItemsOperationTimeout > timeNow)) { @@ -9051,7 +9003,7 @@ static void commandFuncDropAllInventoryItemsIntoRoom(Command const &, NetworkId return; // don't allow multiple /pickupAllRoomItemsIntoInventory and/or /dropAllInventoryItemsIntoRoom - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); int pickupDropAllItemsOperationTimeout = 0; if (targetObj->getObjVars().getItem("pickupDropAllItemsOperation.timeout", pickupDropAllItemsOperationTimeout) && (pickupDropAllItemsOperationTimeout > timeNow)) { @@ -9255,7 +9207,7 @@ static void commandFuncRestoreDecorationLayout(Command const &, NetworkId const } // don't allow another restore on the pob while one is still in progress - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); int restoreDecorationOperationTimeout = 0; if (targetObj->getObjVars().getItem("restoreDecorationOperation.timeout", restoreDecorationOperationTimeout) && (restoreDecorationOperationTimeout > timeNow)) { @@ -9330,7 +9282,7 @@ static void commandFuncAreaPickRandomPlayer(Command const &, NetworkId const &ac if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextAreaPickRandomPlayerCommandAllowed") && (targetObj->getObjVars().getType("timeNextAreaPickRandomPlayerCommandAllowed") == DynamicVariable::INT)) { int timeNextAreaPickRandomPlayerCommandAllowed = 0; @@ -9352,7 +9304,7 @@ static void commandFuncAreaPickRandomPlayer(Command const &, NetworkId const &ac if (!params.empty()) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(Unicode::toLower(params), tokens, NULL, NULL) && !tokens.empty()) + if (Unicode::tokenize(Unicode::toLower(params), tokens, nullptr, nullptr) && !tokens.empty()) { static Unicode::String const paramsPoint1 = Unicode::narrowToWide("-point"); static Unicode::String const paramsPoint2 = Unicode::narrowToWide("point"); @@ -9477,7 +9429,7 @@ static void commandFuncRoomPickRandomPlayer(Command const &, NetworkId const &ac if (!client) return; - int const timeNow = static_cast(::time(NULL)); + int const timeNow = static_cast(::time(nullptr)); if (!client->isGod() && targetObj->getObjVars().hasItem("timeNextRoomPickRandomPlayerCommandAllowed") && (targetObj->getObjVars().getType("timeNextRoomPickRandomPlayerCommandAllowed") == DynamicVariable::INT)) { int timeNextRoomPickRandomPlayerCommandAllowed = 0; @@ -9498,7 +9450,7 @@ static void commandFuncRoomPickRandomPlayer(Command const &, NetworkId const &ac if (!params.empty()) { Unicode::UnicodeStringVector tokens; - if (Unicode::tokenize(Unicode::toLower(params), tokens, NULL, NULL) && !tokens.empty()) + if (Unicode::tokenize(Unicode::toLower(params), tokens, nullptr, nullptr) && !tokens.empty()) { static Unicode::String const paramsPoint1 = Unicode::narrowToWide("-point"); static Unicode::String const paramsPoint2 = Unicode::narrowToWide("point"); @@ -9600,114 +9552,114 @@ static void commandFuncRoomPickRandomPlayer(Command const &, NetworkId const &ac void CommandCppFuncs::install() { // console style commands - CommandTable::addCppFunction("console_all", commandFuncConsoleAll); - CommandTable::addCppFunction("console_combat", commandFuncConsoleCombat); - CommandTable::addCppFunction("console_craft", commandFuncConsoleCraft); - CommandTable::addCppFunction("console_database", commandFuncConsoleDatabase); - CommandTable::addCppFunction("console_manufacture", commandFuncConsoleManufacture); - CommandTable::addCppFunction("console_money", commandFuncConsoleMoney); - CommandTable::addCppFunction("console_npc", commandFuncConsoleNpc); - CommandTable::addCppFunction("console_object", commandFuncConsoleObject); - CommandTable::addCppFunction("console_objvar", commandFuncConsoleObjvar); - CommandTable::addCppFunction("console_resource", commandFuncConsoleResource); - CommandTable::addCppFunction("console_script", commandFuncConsoleScript); - CommandTable::addCppFunction("console_server", commandFuncConsoleServer); - CommandTable::addCppFunction("console_skill", commandFuncConsoleSkill); + CommandTable::addCppFunction("console_all", commandFuncConsoleAll); + CommandTable::addCppFunction("console_combat", commandFuncConsoleCombat); + CommandTable::addCppFunction("console_craft", commandFuncConsoleCraft); + CommandTable::addCppFunction("console_database", commandFuncConsoleDatabase); + CommandTable::addCppFunction("console_manufacture", commandFuncConsoleManufacture); + CommandTable::addCppFunction("console_money", commandFuncConsoleMoney); + CommandTable::addCppFunction("console_npc", commandFuncConsoleNpc); + CommandTable::addCppFunction("console_object", commandFuncConsoleObject); + CommandTable::addCppFunction("console_objvar", commandFuncConsoleObjvar); + CommandTable::addCppFunction("console_resource", commandFuncConsoleResource); + CommandTable::addCppFunction("console_script", commandFuncConsoleScript); + CommandTable::addCppFunction("console_server", commandFuncConsoleServer); + CommandTable::addCppFunction("console_skill", commandFuncConsoleSkill); // communication commands - CommandTable::addCppFunction("social", commandFuncSocial); - CommandTable::addCppFunction("socialInternal", commandFuncSocialInternal); - CommandTable::addCppFunction("spatialChat", commandFuncSpatialChat); - CommandTable::addCppFunction("spatialChatInternal", commandFuncSpatialChatInternal); - CommandTable::addCppFunction("setMood", commandFuncSetMood); - CommandTable::addCppFunction("setMoodInternal", commandFuncSetMoodInternal); - CommandTable::addCppFunction("systemMessage", commandFuncSystemMessage); -// CommandTable::addCppFunction("combatSpam", commandFuncCombatSpam); + CommandTable::addCppFunction("social", commandFuncSocial); + CommandTable::addCppFunction("socialInternal", commandFuncSocialInternal); + CommandTable::addCppFunction("spatialChat", commandFuncSpatialChat); + CommandTable::addCppFunction("spatialChatInternal", commandFuncSpatialChatInternal); + CommandTable::addCppFunction("setMood", commandFuncSetMood); + CommandTable::addCppFunction("setMoodInternal", commandFuncSetMoodInternal); + CommandTable::addCppFunction("systemMessage", commandFuncSystemMessage); + // CommandTable::addCppFunction("combatSpam", commandFuncCombatSpam); - // admin commands - CommandTable::addCppFunction("admin_setGodMode", commandFuncAdminSetGodMode); - CommandTable::addCppFunction("admin_kick", commandFuncAdminKick); - CommandTable::addCppFunction("admin_planetwarp", commandFuncAdminPlanetwarp); - CommandTable::addCppFunction("admin_teleport", commandFuncAdminTeleport); - CommandTable::addCppFunction("admin_teleportTo", commandFuncAdminTeleportTo); - CommandTable::addCppFunction("admin_listGuilds", commandFuncAdminListGuilds); - CommandTable::addCppFunction("editBank", commandFuncAdminEditBank); - CommandTable::addCppFunction("editStats", commandFuncAdminEditStats); - CommandTable::addCppFunction("editAppearance", commandFuncAdminEditAppearance); - CommandTable::addCppFunction("grantTitle", commandFuncAdminGrantTitle); - CommandTable::addCppFunction("credits", commandFuncAdminCredits); - CommandTable::addCppFunction("getStationName", commandFuncAdminGetStationName); - CommandTable::addCppFunction("emptyMailTarget", commandFuncEmptyMailTarget); - CommandTable::addCppFunction("setPlayerAppearance", commandFuncSetPlayerAppearance); + // admin commands + CommandTable::addCppFunction("admin_setGodMode", commandFuncAdminSetGodMode); + CommandTable::addCppFunction("admin_kick", commandFuncAdminKick); + CommandTable::addCppFunction("admin_planetwarp", commandFuncAdminPlanetwarp); + CommandTable::addCppFunction("admin_teleport", commandFuncAdminTeleport); + CommandTable::addCppFunction("admin_teleportTo", commandFuncAdminTeleportTo); + CommandTable::addCppFunction("admin_listGuilds", commandFuncAdminListGuilds); + CommandTable::addCppFunction("editBank", commandFuncAdminEditBank); + CommandTable::addCppFunction("editStats", commandFuncAdminEditStats); + CommandTable::addCppFunction("editAppearance", commandFuncAdminEditAppearance); + CommandTable::addCppFunction("grantTitle", commandFuncAdminGrantTitle); + CommandTable::addCppFunction("credits", commandFuncAdminCredits); + CommandTable::addCppFunction("getStationName", commandFuncAdminGetStationName); + CommandTable::addCppFunction("emptyMailTarget", commandFuncEmptyMailTarget); + CommandTable::addCppFunction("setPlayerAppearance", commandFuncSetPlayerAppearance); CommandTable::addCppFunction("revertPlayerAppearance", commandFuncRevertPlayerAppearance); // auction commands - CommandTable::addCppFunction("auction_create", commandFuncAuctionCreate); - CommandTable::addCppFunction("auction_create_immediate", commandFuncAuctionCreateImmediate); - CommandTable::addCppFunction("auction_bid", commandFuncAuctionBid); - CommandTable::addCppFunction("auction_cancel", commandFuncAuctionCancel); - CommandTable::addCppFunction("auction_accept", commandFuncAuctionAccept); - CommandTable::addCppFunction("auction_query", commandFuncAuctionQuery); - CommandTable::addCppFunction("auction_retrieve", commandFuncAuctionRetrieve); + CommandTable::addCppFunction("auction_create", commandFuncAuctionCreate); + CommandTable::addCppFunction("auction_create_immediate", commandFuncAuctionCreateImmediate); + CommandTable::addCppFunction("auction_bid", commandFuncAuctionBid); + CommandTable::addCppFunction("auction_cancel", commandFuncAuctionCancel); + CommandTable::addCppFunction("auction_accept", commandFuncAuctionAccept); + CommandTable::addCppFunction("auction_query", commandFuncAuctionQuery); + CommandTable::addCppFunction("auction_retrieve", commandFuncAuctionRetrieve); // cell/building permissions commands - CommandTable::addCppFunction("addBannedPlayer", commandFuncAddBannedPlayer); - CommandTable::addCppFunction("removeBannedPlayer", commandFuncRemoveBannedPlayer); - CommandTable::addCppFunction("addAllowedPlayer", commandFuncAddAllowedPlayer); - CommandTable::addCppFunction("removeAllowedPlayer", commandFuncRemoveAllowedPlayer); - CommandTable::addCppFunction("setPublicState", commandFuncSetPublicState); - CommandTable::addCppFunction("setOwner", commandFuncSetOwner); + CommandTable::addCppFunction("addBannedPlayer", commandFuncAddBannedPlayer); + CommandTable::addCppFunction("removeBannedPlayer", commandFuncRemoveBannedPlayer); + CommandTable::addCppFunction("addAllowedPlayer", commandFuncAddAllowedPlayer); + CommandTable::addCppFunction("removeAllowedPlayer", commandFuncRemoveAllowedPlayer); + CommandTable::addCppFunction("setPublicState", commandFuncSetPublicState); + CommandTable::addCppFunction("setOwner", commandFuncSetOwner); - CommandTable::addCppFunction("setPosture", commandSetPosture); - CommandTable::addCppFunction("duel", commandFuncDuel); - CommandTable::addCppFunction("endDuel", commandFuncEndDuel); + CommandTable::addCppFunction("setPosture", commandSetPosture); + CommandTable::addCppFunction("duel", commandFuncDuel); + CommandTable::addCppFunction("endDuel", commandFuncEndDuel); // ui CommandTable::addCppFunction("setWaypointActiveStatus", commandFuncSetWaypointActiveStatus); - CommandTable::addCppFunction("setWaypointName", commandFuncSetWaypointName); + CommandTable::addCppFunction("setWaypointName", commandFuncSetWaypointName); // harvester - CommandTable::addCppFunction("harvesterActivate", commandFuncHarvesterActivate); - CommandTable::addCppFunction("harvesterDeactivate", commandFuncHarvesterDeactivate); - CommandTable::addCppFunction("harvesterHarvest", commandFuncHarvesterHarvest); - CommandTable::addCppFunction("harvesterSelectResource", commandFuncHarvesterSelectResource); - CommandTable::addCppFunction("harvesterDiscardHopper", commandFuncHarvesterDiscardHopper); - CommandTable::addCppFunction("harvesterMakeCrate", commandFuncHarvesterMakeCrate); - CommandTable::addCppFunction("harvesterGetResourceData", commandFuncHarvesterGetResourceData); + CommandTable::addCppFunction("harvesterActivate", commandFuncHarvesterActivate); + CommandTable::addCppFunction("harvesterDeactivate", commandFuncHarvesterDeactivate); + CommandTable::addCppFunction("harvesterHarvest", commandFuncHarvesterHarvest); + CommandTable::addCppFunction("harvesterSelectResource", commandFuncHarvesterSelectResource); + CommandTable::addCppFunction("harvesterDiscardHopper", commandFuncHarvesterDiscardHopper); + CommandTable::addCppFunction("harvesterMakeCrate", commandFuncHarvesterMakeCrate); + CommandTable::addCppFunction("harvesterGetResourceData", commandFuncHarvesterGetResourceData); // syncronized ui - CommandTable::addCppFunction("synchronizedUiListen" , commandFuncSynchronizedUiListen); - CommandTable::addCppFunction("synchronizedUiStopListening", commandFuncSynchronizedUiStopListening); + CommandTable::addCppFunction("synchronizedUiListen", commandFuncSynchronizedUiListen); + CommandTable::addCppFunction("synchronizedUiStopListening", commandFuncSynchronizedUiStopListening); // resource - CommandTable::addCppFunction("resourceSetName", commandFuncResourceSetName); + CommandTable::addCppFunction("resourceSetName", commandFuncResourceSetName); // resource container CommandTable::addCppFunction("resourceContainerTransfer", commandFuncResourceContainerTransfer); - CommandTable::addCppFunction("resourceContainerSplit", commandFuncResourceContainerSplit); + CommandTable::addCppFunction("resourceContainerSplit", commandFuncResourceContainerSplit); // survey - CommandTable::addCppFunction("makeSurvey", commandFuncMakeSurvey); - CommandTable::addCppFunction("requestSurvey", commandFuncRequestSurvey); - CommandTable::addCppFunction("requestCoreSample", commandFuncRequestCoreSample); + CommandTable::addCppFunction("makeSurvey", commandFuncMakeSurvey); + CommandTable::addCppFunction("requestSurvey", commandFuncRequestSurvey); + CommandTable::addCppFunction("requestCoreSample", commandFuncRequestCoreSample); - CommandTable::addCppFunction("transferItemWeapon", commandFuncTransferWeapon); - CommandTable::addCppFunction("transferItemArmor", commandFuncTransferArmor); - CommandTable::addCppFunction("transferItemMisc", commandFuncTransferMisc); - CommandTable::addCppFunction("openContainer", commandFuncOpenContainer); - CommandTable::addCppFunction("closeContainer", commandFuncCloseContainer); - CommandTable::addCppFunction("openLotteryContainer", commandFuncOpenLotteryContainer); + CommandTable::addCppFunction("transferItemWeapon", commandFuncTransferWeapon); + CommandTable::addCppFunction("transferItemArmor", commandFuncTransferArmor); + CommandTable::addCppFunction("transferItemMisc", commandFuncTransferMisc); + CommandTable::addCppFunction("openContainer", commandFuncOpenContainer); + CommandTable::addCppFunction("closeContainer", commandFuncCloseContainer); + CommandTable::addCppFunction("openLotteryContainer", commandFuncOpenLotteryContainer); CommandTable::addCppFunction("closeLotteryContainer", commandFuncCloseLotteryContainer); - CommandTable::addCppFunction("giveItem", commandFuncGiveItem); + CommandTable::addCppFunction("giveItem", commandFuncGiveItem); // grouping - CommandTable::addCppFunction("groupInvite", commandFuncGroupInvite); - CommandTable::addCppFunction("groupUninvite", commandFuncGroupUninvite); - CommandTable::addCppFunction("groupJoin", commandFuncGroupJoin); - CommandTable::addCppFunction("groupDecline", commandFuncGroupDecline); - CommandTable::addCppFunction("groupDisband", commandFuncGroupDisband); - CommandTable::addCppFunction("kickFromShip", commandFuncKickFromShip); - CommandTable::addCppFunction("groupChat", commandFuncGroupChat); + CommandTable::addCppFunction("groupInvite", commandFuncGroupInvite); + CommandTable::addCppFunction("groupUninvite", commandFuncGroupUninvite); + CommandTable::addCppFunction("groupJoin", commandFuncGroupJoin); + CommandTable::addCppFunction("groupDecline", commandFuncGroupDecline); + CommandTable::addCppFunction("groupDisband", commandFuncGroupDisband); + CommandTable::addCppFunction("kickFromShip", commandFuncKickFromShip); + CommandTable::addCppFunction("groupChat", commandFuncGroupChat); CommandTable::addCppFunction("groupMakeLeader", commandFuncGroupMakeLeader); CommandTable::addCppFunction("groupMakeMasterLooter", commandFuncGroupMakeMasterLooter); CommandTable::addCppFunction("createGroupPickup", commandFuncCreateGroupPickup); @@ -9716,102 +9668,102 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("groupPickRandomGroupMember", commandFuncGroupPickRandomGroupMember); // guilds - CommandTable::addCppFunction("guildChat", commandFuncGuildChat); + CommandTable::addCppFunction("guildChat", commandFuncGuildChat); CommandTable::addCppFunction("guildTextChatRoomRejoin", commandFuncGuildTextChatRoomRejoin); CommandTable::addCppFunction("guildPickRandomGuildMember", commandFuncGuildPickRandomGuildMember); // city - CommandTable::addCppFunction("cityChat", commandFuncCityChat); + CommandTable::addCppFunction("cityChat", commandFuncCityChat); CommandTable::addCppFunction("cityTextChatRoomRejoin", commandFuncCityTextChatRoomRejoin); CommandTable::addCppFunction("cityPickRandomCitizen", commandFuncCityPickRandomCitizen); //chat - CommandTable::addCppFunction("auctionChat", commandFuncAuctionChat); - CommandTable::addCppFunction("planetChat", commandFuncPlanetChat); - + CommandTable::addCppFunction("auctionChat", commandFuncAuctionChat); + CommandTable::addCppFunction("planetChat", commandFuncPlanetChat); + // crafting - CommandTable::addCppFunction("requestResourceWeights", commandFuncRequestResourceWeights); + CommandTable::addCppFunction("requestResourceWeights", commandFuncRequestResourceWeights); CommandTable::addCppFunction("requestResourceWeightsBatch", commandFuncRequestResourceWeightsBatch); - CommandTable::addCppFunction("requestDraftSlots", commandFuncRequestDraftSlots); - CommandTable::addCppFunction("requestDraftSlotsBatch", commandFuncRequestDraftSlotsBatch); + CommandTable::addCppFunction("requestDraftSlots", commandFuncRequestDraftSlots); + CommandTable::addCppFunction("requestDraftSlotsBatch", commandFuncRequestDraftSlotsBatch); CommandTable::addCppFunction("requestManfSchematicSlots", commandFuncRequestManfSchematicSlots); - CommandTable::addCppFunction("requestCraftingSession", commandFuncRequestCraftingSession); - CommandTable::addCppFunction("requestCraftingSessionFail",commandFuncRequestCraftingSessionFail); - CommandTable::addCppFunction("selectDraftSchematic", commandFuncSelectDraftSchematic); - CommandTable::addCppFunction("nextCraftingStage", commandFuncNextCraftingStage); - CommandTable::addCppFunction("createPrototype", commandFuncCreatePrototype); - CommandTable::addCppFunction("createManfSchematic", commandFuncCreateManfSchematic); - CommandTable::addCppFunction("cancelCraftingSession", commandFuncCancelCraftingSession); - CommandTable::addCppFunction("stopCraftingSession", commandFuncStopCraftingSession); - CommandTable::addCppFunction("restartCraftingSession", commandFuncRestartCraftingSession); - CommandTable::addCppFunction("extractObject", commandFuncExtractObject); - CommandTable::addCppFunction("repair", commandFuncRepair); - CommandTable::addCppFunction("factoryCrateSplit", commandFuncFactoryCrateSplit); + CommandTable::addCppFunction("requestCraftingSession", commandFuncRequestCraftingSession); + CommandTable::addCppFunction("requestCraftingSessionFail", commandFuncRequestCraftingSessionFail); + CommandTable::addCppFunction("selectDraftSchematic", commandFuncSelectDraftSchematic); + CommandTable::addCppFunction("nextCraftingStage", commandFuncNextCraftingStage); + CommandTable::addCppFunction("createPrototype", commandFuncCreatePrototype); + CommandTable::addCppFunction("createManfSchematic", commandFuncCreateManfSchematic); + CommandTable::addCppFunction("cancelCraftingSession", commandFuncCancelCraftingSession); + CommandTable::addCppFunction("stopCraftingSession", commandFuncStopCraftingSession); + CommandTable::addCppFunction("restartCraftingSession", commandFuncRestartCraftingSession); + CommandTable::addCppFunction("extractObject", commandFuncExtractObject); + CommandTable::addCppFunction("repair", commandFuncRepair); + CommandTable::addCppFunction("factoryCrateSplit", commandFuncFactoryCrateSplit); // misc - CommandTable::addCppFunction("showDanceVisuals", commandFuncShowDanceVisuals); - CommandTable::addCppFunction("showMusicianVisuals", commandFuncShowMusicianVisuals); - CommandTable::addCppFunction("placeStructure", commandFuncPlaceStructure); - CommandTable::addCppFunction("getAttributes", commandFuncGetAttributes); - CommandTable::addCppFunction("getAttributesBatch", commandFuncGetAttributesBatch); - CommandTable::addCppFunction("sitServer", commandFuncSitServer); - CommandTable::addCppFunction("jumpServer", commandFuncJumpServer); - CommandTable::addCppFunction("purchaseTicket", commandFuncPurchaseTicket); - CommandTable::addCppFunction("addFriend", commandFuncAddFriend); - CommandTable::addCppFunction("removeFriend", commandFuncRemoveFriend); - CommandTable::addCppFunction("getFriendList", commandFuncGetFriendList); - CommandTable::addCppFunction("addIgnore", commandFuncAddIgnore); - CommandTable::addCppFunction("removeIgnore", commandFuncRemoveIgnore); - CommandTable::addCppFunction("getIgnoreList", commandFuncGetIgnoreList); - CommandTable::addCppFunction("requestBiography", commandFuncRequestBiography); - CommandTable::addCppFunction("setBiography", commandFuncSetBiography); + CommandTable::addCppFunction("showDanceVisuals", commandFuncShowDanceVisuals); + CommandTable::addCppFunction("showMusicianVisuals", commandFuncShowMusicianVisuals); + CommandTable::addCppFunction("placeStructure", commandFuncPlaceStructure); + CommandTable::addCppFunction("getAttributes", commandFuncGetAttributes); + CommandTable::addCppFunction("getAttributesBatch", commandFuncGetAttributesBatch); + CommandTable::addCppFunction("sitServer", commandFuncSitServer); + CommandTable::addCppFunction("jumpServer", commandFuncJumpServer); + CommandTable::addCppFunction("purchaseTicket", commandFuncPurchaseTicket); + CommandTable::addCppFunction("addFriend", commandFuncAddFriend); + CommandTable::addCppFunction("removeFriend", commandFuncRemoveFriend); + CommandTable::addCppFunction("getFriendList", commandFuncGetFriendList); + CommandTable::addCppFunction("addIgnore", commandFuncAddIgnore); + CommandTable::addCppFunction("removeIgnore", commandFuncRemoveIgnore); + CommandTable::addCppFunction("getIgnoreList", commandFuncGetIgnoreList); + CommandTable::addCppFunction("requestBiography", commandFuncRequestBiography); + CommandTable::addCppFunction("setBiography", commandFuncSetBiography); CommandTable::addCppFunction("requestWaypointAtPosition", commandFuncRequestWaypointAtPosition); - CommandTable::addCppFunction("serverDestroyObject", commandFuncServerDestroyObject); - CommandTable::addCppFunction("setSpokenLanguage", commandFuncSetSpokenLanguage); - CommandTable::addCppFunction("applyPowerup", commandFuncApplyPowerup); - CommandTable::addCppFunction("report", commandFuncReport); - CommandTable::addCppFunction("resetCooldowns", commandFuncResetCooldowns); - CommandTable::addCppFunction("spewCommandQueue", commandFuncSpewCommandQueue); - CommandTable::addCppFunction("locateStructure", commandFuncLocateStructure); - CommandTable::addCppFunction("locateVendor", commandFuncLocateVendor); - CommandTable::addCppFunction("showCtsHistory", commandFuncShowCtsHistory); + CommandTable::addCppFunction("serverDestroyObject", commandFuncServerDestroyObject); + CommandTable::addCppFunction("setSpokenLanguage", commandFuncSetSpokenLanguage); + CommandTable::addCppFunction("applyPowerup", commandFuncApplyPowerup); + CommandTable::addCppFunction("report", commandFuncReport); + CommandTable::addCppFunction("resetCooldowns", commandFuncResetCooldowns); + CommandTable::addCppFunction("spewCommandQueue", commandFuncSpewCommandQueue); + CommandTable::addCppFunction("locateStructure", commandFuncLocateStructure); + CommandTable::addCppFunction("locateVendor", commandFuncLocateVendor); + CommandTable::addCppFunction("showCtsHistory", commandFuncShowCtsHistory); CommandTable::addCppFunction("pickupAllRoomItemsIntoInventory", commandFuncPickupAllRoomItemsIntoInventory); CommandTable::addCppFunction("dropAllInventoryItemsIntoRoom", commandFuncDropAllInventoryItemsIntoRoom); - CommandTable::addCppFunction("saveDecorationLayout", commandFuncSaveDecorationLayout); - CommandTable::addCppFunction("restoreDecorationLayout", commandFuncRestoreDecorationLayout); - CommandTable::addCppFunction("areaPickRandomPlayer", commandFuncAreaPickRandomPlayer); - CommandTable::addCppFunction("roomPickRandomPlayer", commandFuncRoomPickRandomPlayer); + CommandTable::addCppFunction("saveDecorationLayout", commandFuncSaveDecorationLayout); + CommandTable::addCppFunction("restoreDecorationLayout", commandFuncRestoreDecorationLayout); + CommandTable::addCppFunction("areaPickRandomPlayer", commandFuncAreaPickRandomPlayer); + CommandTable::addCppFunction("roomPickRandomPlayer", commandFuncRoomPickRandomPlayer); // match making - CommandTable::addCppFunction("setMatchMakingPersonalId", commandFuncSetMatchMakingPersonalId); + CommandTable::addCppFunction("setMatchMakingPersonalId", commandFuncSetMatchMakingPersonalId); CommandTable::addCppFunction("setMatchMakingCharacterId", commandFuncSetMatchMakingCharacterId); - CommandTable::addCppFunction("requestCharacterMatch", commandFuncRequestCharacterMatch); + CommandTable::addCppFunction("requestCharacterMatch", commandFuncRequestCharacterMatch); CommandTable::addCppFunction("toggleSearchableByCtsSourceGalaxy", commandFuncToggleSearchableByCtsSourceGalaxy); CommandTable::addCppFunction("toggleDisplayLocationInSearchResults", commandFuncToggleDisplayLocationInSearchResults); - CommandTable::addCppFunction("toggleAnonymous", commandFuncToggleAnonymous); - CommandTable::addCppFunction("toggleHelper", commandFuncToggleHelper); - CommandTable::addCppFunction("toggleRolePlay", commandFuncToggleRolePlay); - CommandTable::addCppFunction("toggleLookingForGroup", commandFuncToggleLookingForGroup); - CommandTable::addCppFunction("toggleAwayFromKeyBoard", commandFuncToggleAwayFromKeyBoard); + CommandTable::addCppFunction("toggleAnonymous", commandFuncToggleAnonymous); + CommandTable::addCppFunction("toggleHelper", commandFuncToggleHelper); + CommandTable::addCppFunction("toggleRolePlay", commandFuncToggleRolePlay); + CommandTable::addCppFunction("toggleLookingForGroup", commandFuncToggleLookingForGroup); + CommandTable::addCppFunction("toggleAwayFromKeyBoard", commandFuncToggleAwayFromKeyBoard); CommandTable::addCppFunction("toggleDisplayingFactionRank", commandFuncToggleDisplayingFactionRank); - CommandTable::addCppFunction("toggleOutOfCharacter", commandFuncToggleOutOfCharacter); - CommandTable::addCppFunction("toggleLookingForWork", commandFuncToggleLookingForWork); + CommandTable::addCppFunction("toggleOutOfCharacter", commandFuncToggleOutOfCharacter); + CommandTable::addCppFunction("toggleLookingForWork", commandFuncToggleLookingForWork); //skill - CommandTable::addCppFunction("revokeSkill", commandFuncRevokeSkill); - CommandTable::addCppFunction("setCurrentSkillTitle", commandFuncSetCurrentSkillTitle); + CommandTable::addCppFunction("revokeSkill", commandFuncRevokeSkill); + CommandTable::addCppFunction("setCurrentSkillTitle", commandFuncSetCurrentSkillTitle); //misc ui - CommandTable::addCppFunction("permissionListModify", commandFuncPermissionListModify); - CommandTable::addCppFunction("requestCharacterSheetInfo", commandFuncRequestCharacterSheetInfo); - CommandTable::addCppFunction("removeBuff", commandFuncRemoveBuff); + CommandTable::addCppFunction("permissionListModify", commandFuncPermissionListModify); + CommandTable::addCppFunction("requestCharacterSheetInfo", commandFuncRequestCharacterSheetInfo); + CommandTable::addCppFunction("removeBuff", commandFuncRemoveBuff); // npc conversation - CommandTable::addCppFunction("npcConversationStart", commandFuncNpcConversationStart); - CommandTable::addCppFunction("npcConversationStop", commandFuncNpcConversationStop); + CommandTable::addCppFunction("npcConversationStart", commandFuncNpcConversationStart); + CommandTable::addCppFunction("npcConversationStop", commandFuncNpcConversationStop); CommandTable::addCppFunction("npcConversationSelect", commandFuncNpcConversationSelect); - CommandTable::addCppFunction("handleUnstick", commandFuncUnstick); - CommandTable::addCppFunction("getAccountInfo", commandFuncGetAccountInfo); + CommandTable::addCppFunction("handleUnstick", commandFuncUnstick); + CommandTable::addCppFunction("getAccountInfo", commandFuncGetAccountInfo); CommandTable::addCppFunction("lag", commandFuncLag); //knowledgebase (i.e. holocron) @@ -9829,8 +9781,8 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("associateDroidControlDeviceWithShip", commandFuncAssociateDroidControlDeviceWithShip); CommandTable::addCppFunction("unassociateDroidControlDeviceWithShip", commandFuncAssociateDroidControlDeviceWithShip); - CommandTable::addCppFunction("serverAsteroidDataListen" , commandFuncServerAsteroidDataListen); - CommandTable::addCppFunction("serverAsteroidDataStopListening", commandFuncServerAsteroidDataStopListening); + CommandTable::addCppFunction("serverAsteroidDataListen", commandFuncServerAsteroidDataListen); + CommandTable::addCppFunction("serverAsteroidDataStopListening", commandFuncServerAsteroidDataStopListening); CommandTable::addCppFunction("boosterOn", commandFuncBoosterOn); CommandTable::addCppFunction("boosterOff", commandFuncBoosterOff); @@ -9844,7 +9796,7 @@ void CommandCppFuncs::install() CommandTable::addCppFunction("abandonQuest", commandFuncAbandonQuest); // exchange - CommandTable::addCppFunction("exchangeListCredits", commandFuncExchangeListCredits); + CommandTable::addCppFunction("exchangeListCredits", commandFuncExchangeListCredits); // squelch CommandTable::addCppFunction("squelch", commandFuncSquelch); @@ -9870,4 +9822,4 @@ void CommandCppFuncs::remove() { } -// ====================================================================== +// ====================================================================== \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp b/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp index d581b8ae..0e3c1b26 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp +++ b/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp @@ -45,12 +45,6 @@ namespace CommandQueueNamespace const bool cs_debug = false; #endif - /** - * @brief used to assign sequence Ids to server-generated commands - * that need to be replicated on the client. - */ - const uint32 cs_sequenceStart = 0x40000000; - /** * @brief the maximum number of combat commands that are allowed in * the queue at any given time. @@ -309,11 +303,11 @@ void CommandQueue::executeCommandQueue() { CommandQueueEntry &entry = *(m_queue.begin()); - // try to recover from having a null command + // try to recover from having a nullptr command // maybe this should result in a fatal error? if ( entry.m_command == 0 ) { - WARNING( true, ( "executeCommandQueue: entry.m_command was NULL! WTF?\n" ) ); + WARNING( true, ( "executeCommandQueue: entry.m_command was nullptr! WTF?\n" ) ); m_queue.pop(); m_state = State_Waiting; m_nextEventTime = 0.f; @@ -387,7 +381,7 @@ void CommandQueue::executeCommandQueue() // switch state might have removed elements from the queue and invalidated entry // so we can't assume that we're still safe - if(!m_queue.empty() && (&(*(m_queue.begin())) == &entry) && m_queue.begin()->m_command != NULL) + if(!m_queue.empty() && (&(*(m_queue.begin())) == &entry) && m_queue.begin()->m_command != nullptr) { handleEntryRemoved(*(m_queue.begin()), true); m_queue.pop(); @@ -458,7 +452,7 @@ void CommandQueue::updateClient(TimerClass timerClass ) { CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); - if ( (creatureOwner == NULL) + if ( (creatureOwner == nullptr) || !creatureOwner->getClient()) { return; @@ -475,7 +469,7 @@ void CommandQueue::updateClient(TimerClass timerClass ) if ( entry.m_command == 0 ) // woah that's bad news! { - WARNING( true, ( "CommandQueue::updateClient(): command was NULL!\n" ) ); + WARNING( true, ( "CommandQueue::updateClient(): command was nullptr!\n" ) ); return; } @@ -539,7 +533,7 @@ void CommandQueue::notifyClient() { CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); - if ( (creatureOwner == NULL) + if ( (creatureOwner == nullptr) || !creatureOwner->getClient()) { return; @@ -555,7 +549,7 @@ void CommandQueue::notifyClient() if ( entry.m_command == 0 ) { - WARNING( true, ( "CommandQueue::notifyClient(): command was NULL!\n" ) ); + WARNING( true, ( "CommandQueue::notifyClient(): command was nullptr!\n" ) ); return; } @@ -612,7 +606,7 @@ bool CommandQueue::doWarmupTrigger(const CommandQueueEntry &entry ) CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); - if (creatureOwner != NULL) + if (creatureOwner != nullptr) { creatureOwner->doWarmupChecks( *entry.m_command, entry.m_targetId, entry.m_params, m_status, m_statusDetail ); @@ -620,7 +614,7 @@ bool CommandQueue::doWarmupTrigger(const CommandQueueEntry &entry ) if ( m_status == Command::CEC_Success ) { - FATAL( entry.m_command == 0, ( "entry had a null command\n" ) ); + FATAL( entry.m_command == 0, ( "entry had a nullptr command\n" ) ); std::vector timeValues; timeValues.push_back( entry.m_command->m_warmTime ); @@ -659,7 +653,7 @@ uint32 CommandQueue::getCurrentCommand() const if ( entry.m_command == 0 ) { - WARNING( true, ( "CommandQueue::getCurrentCommand(): command was NULL!\n" ) ); + WARNING( true, ( "CommandQueue::getCurrentCommand(): command was nullptr!\n" ) ); return 0; } @@ -680,7 +674,7 @@ void CommandQueue::switchState() if ( entry.m_command == 0 ) { - WARNING( true, ( "CommandQueue::switchState(): command was NULL!\n" ) ); + WARNING( true, ( "CommandQueue::switchState(): command was nullptr!\n" ) ); return; } @@ -726,7 +720,7 @@ void CommandQueue::switchState() bool const targetIsAuthoritative = target && target->isAuthoritative(); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n", - entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL", + entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "nullptr", entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0, NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(), getOwner().getNetworkId().getValueString().c_str(), @@ -746,7 +740,7 @@ void CommandQueue::switchState() for (; itEntry != m_queue.end(); ++itEntry) { - REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL")); + REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "nullptr")); } } #endif @@ -838,7 +832,7 @@ void CommandQueue::switchState() bool const targetIsAuthoritative = target && target->isAuthoritative(); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n", - entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL", + entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "nullptr", entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0, NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(), getOwner().getNetworkId().getValueString().c_str(), @@ -858,7 +852,7 @@ void CommandQueue::switchState() for (; itEntry != m_queue.end(); ++itEntry) { - REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL")); + REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "nullptr")); } } #endif @@ -1160,7 +1154,7 @@ void CommandQueue::notifyClientOfCommandRemoval(uint32 sequenceId, float waitTim CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); - if ( (creatureOwner != NULL) + if ( (creatureOwner != nullptr) && creatureOwner->getClient() && (sequenceId != 0)) { @@ -1359,7 +1353,7 @@ void CommandQueue::executeCommand(Command const &command, NetworkId const &targe CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); - if (creatureOwner != NULL) + if (creatureOwner != nullptr) { CreatureController * const creatureController = creatureOwner->getCreatureController(); if (creatureController && creatureController->getSecureTrade()) @@ -1399,7 +1393,7 @@ void CommandQueue::executeCommand(Command const &command, NetworkId const &targe TangibleObject * const tangibleOwner = getServerOwner().asTangibleObject(); - if (tangibleOwner != NULL) + if (tangibleOwner != nullptr) { // Really execute the command - swap targets if necessary, and call // forceExecuteCommand (which will handle messaging if not authoritative) @@ -1440,7 +1434,7 @@ CommandQueue * CommandQueue::getCommandQueue(Object & object) { Property * const property = object.getProperty(getClassPropertyId()); - return (property != NULL) ? (static_cast(property)) : NULL; + return (property != nullptr) ? (static_cast(property)) : nullptr; } // ---------------------------------------------------------------------- diff --git a/engine/server/library/serverGame/src/shared/command/CommandQueue.h b/engine/server/library/serverGame/src/shared/command/CommandQueue.h index bedf3717..03c861e0 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandQueue.h +++ b/engine/server/library/serverGame/src/shared/command/CommandQueue.h @@ -218,7 +218,7 @@ public: void resetCooldowns(); // debug diagnostic - void spew(std::string * output = NULL); + void spew(std::string * output = nullptr); private: CommandQueue(CommandQueue const &); diff --git a/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp b/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp index 4473f70f..b13330b9 100755 --- a/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp +++ b/engine/server/library/serverGame/src/shared/command/CommandQueueEntry.cpp @@ -6,7 +6,6 @@ // // ====================================================================== - #include "serverGame/FirstServerGame.h" #include "serverGame/CommandQueueEntry.h" #include "serverGame/CreatureObject.h" @@ -14,15 +13,15 @@ #include "Archive/ByteStream.h" #include "sharedGame/CommandTable.h" - // ====================================================================== CommandQueueEntry::CommandQueueEntry() : - m_command(&CommandTable::getNullCommand ()), + m_command(&CommandTable::getNullCommand()), m_targetId(NetworkId::cms_invalid), m_params(), m_sequenceId(0), - m_clearable(true) + m_clearable(true), + m_priority() { } @@ -35,8 +34,8 @@ CommandQueueEntry::CommandQueueEntry( uint32 sequenceId, bool clearable, Command::Priority priority, - bool autoAttack ) : - + bool autoAttack) : + m_command(&command), m_targetId(targetId), m_params(params), @@ -64,12 +63,12 @@ CommandQueueEntry &CommandQueueEntry::operator=(CommandQueueEntry const &rhs) { if (&rhs != this) { - m_command = rhs.m_command; //lint !e1555 - m_targetId = rhs.m_targetId; - m_params = rhs.m_params; + m_command = rhs.m_command; //lint !e1555 + m_targetId = rhs.m_targetId; + m_params = rhs.m_params; m_sequenceId = rhs.m_sequenceId; - m_clearable = rhs.m_clearable; - m_priority = rhs.m_priority; + m_clearable = rhs.m_clearable; + m_priority = rhs.m_priority; } return *this; } @@ -78,35 +77,30 @@ CommandQueueEntry &CommandQueueEntry::operator=(CommandQueueEntry const &rhs) namespace Archive { + // ---------------------------------------------------------------------- -// ---------------------------------------------------------------------- + void get(ReadIterator &source, CommandQueueEntry &target) + { + uint32 commandHash; -void get(ReadIterator &source, CommandQueueEntry &target) -{ - uint32 commandHash; + Archive::get(source, commandHash); + Archive::get(source, target.m_targetId); + Archive::get(source, target.m_params); + Archive::get(source, target.m_sequenceId); + Archive::get(source, target.m_clearable); + target.m_command = &CommandTable::getCommand(commandHash); + } - Archive::get(source, commandHash); - Archive::get(source, target.m_targetId); - Archive::get(source, target.m_params); - Archive::get(source, target.m_sequenceId); - Archive::get(source, target.m_clearable); - target.m_command = &CommandTable::getCommand(commandHash); -} + // ---------------------------------------------------------------------- -// ---------------------------------------------------------------------- + void put(ByteStream &target, CommandQueueEntry const &source) + { + Archive::put(target, source.m_command->m_commandHash); + Archive::put(target, source.m_targetId); + Archive::put(target, source.m_params); + Archive::put(target, source.m_sequenceId); + Archive::put(target, source.m_clearable); + } -void put(ByteStream &target, CommandQueueEntry const &source) -{ - Archive::put(target, source.m_command->m_commandHash); - Archive::put(target, source.m_targetId); - Archive::put(target, source.m_params); - Archive::put(target, source.m_sequenceId); - Archive::put(target, source.m_clearable); -} - - - -// ---------------------------------------------------------------------- - - -} // namespace Archive + // ---------------------------------------------------------------------- +} // namespace Archive \ No newline at end of file diff --git a/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesMarket.cpp b/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesMarket.cpp index d2d55dfd..e7ec036b 100755 --- a/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesMarket.cpp +++ b/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesMarket.cpp @@ -201,7 +201,7 @@ namespace CommoditiesMarketNamespace Container::ContainerErrorCode tmp = Container::CEC_Success; ServerObject *bazaarContainer = auctionContainer.getBazaarContainer(); - if (!bazaarContainer || !ContainerInterface::canTransferTo(bazaarContainer, item, NULL, tmp)) + if (!bazaarContainer || !ContainerInterface::canTransferTo(bazaarContainer, item, nullptr, tmp)) { errorCode = ar_INVALID_ITEM_ID; } @@ -246,15 +246,6 @@ namespace CommoditiesMarketNamespace errorCode = ar_ITEM_EQUIPPED; } -#if 0 - const VolumeContainer *vol = ContainerInterface::getVolumeContainer(item); - if (vol && vol->getCurrentVolume() > 0) - { - errorCode = ar_NOT_EMPTY; - } - -#endif - if ((errorCode == ar_OK) && auctionContainer.isVendor() && !auctionContainer.isBazaarTerminal()) { // check to make sure the vendor isn't restricted from accepting this item @@ -326,7 +317,7 @@ bool CommoditiesMarketNamespace::isVendorItemRestriction(ServerObject const & it return false; } - ItemRestriction const * itemRestriction = NULL; + ItemRestriction const * itemRestriction = nullptr; std::map::const_iterator const iterFind = itemRestrictionList.find(itemRestrictionFile); if (iterFind != itemRestrictionList.end()) @@ -653,7 +644,7 @@ static void transferBank(const NetworkId &source, const NetworkId &dest, int32 a } else { -// printf("Transfering %i bank from %Ld to %Ld\n", (int)amount, source.getValue(), dest.getValue()); +// printf("Transfering %i bank from %Ld to %Ld", (int)amount, source.getValue(), dest.getValue()); char buf[100]; sprintf(buf, "%Ld %Ld", (int64)dest.getValue(), (int64)amount); MessageToQueue::getInstance().sendMessageToC(source, "C++ModifyBank", buf, 0, true); @@ -1068,7 +1059,7 @@ void CommoditiesMarket::getCommoditiesServerConnection() if (ObjectIdManager::hasAvailableObjectId()) { s_market = new CommoditiesServerConnection(ConfigServerGame::getCommoditiesServerServiceBindInterface(), static_cast(ConfigServerGame::getCommoditiesServerServiceBindPort())); - s_timeMarketConnectionCreated = ::time(NULL); + s_timeMarketConnectionCreated = ::time(nullptr); } } @@ -1082,10 +1073,10 @@ int CommoditiesMarket::getCommoditiesServerConnectionAgeSeconds() if (s_timeMarketConnectionCreated <= 0) return 0; - if (s_market == NULL) + if (s_market == nullptr) return 0; - return static_cast(::time(NULL) - s_timeMarketConnectionCreated); + return static_cast(::time(nullptr) - s_timeMarketConnectionCreated); } // ---------------------------------------------------------------------- @@ -1102,7 +1093,7 @@ void CommoditiesMarket::install() if (!ConfigServerGame::getCommoditiesMarketEnabled()) return; - FATAL(s_market, ("CommoditiesMarket already installed.\n")); + FATAL(s_market, ("CommoditiesMarket already installed.")); getCommoditiesServerConnection(); time_t t = time(0); @@ -1112,7 +1103,7 @@ void CommoditiesMarket::install() } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send SetGameTime.\n")); + //DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send SetGameTime.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1127,7 +1118,7 @@ void CommoditiesMarket::remove() if (!ConfigServerGame::getCommoditiesMarketEnabled()) return; - //FATAL(!s_market, ("CommoditiesMarket not installed.\n")); + //FATAL(!s_market, ("CommoditiesMarket not installed.")); try { s_market = 0; @@ -1179,10 +1170,7 @@ void CommoditiesMarket::giveTime() else { if (Clock::timeSeconds() - ConfigServerGame::getCommoditiesServerReconnectIntervalSec() > reconnectTime) - { - - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GiveTime.\n")); - + { getCommoditiesServerConnection(); //attempt to reconnect to commodities server reconnectTime = Clock::timeSeconds(); } @@ -1295,7 +1283,7 @@ void CommoditiesMarket::onAddAuction(int sequence, int32 result, const NetworkId CreatureObject * const auctionCreator = dynamic_cast(NetworkIdManager::getObjectById(auctionOwnerId)); ServerObject * const item = dynamic_cast(NetworkIdManager::getObjectById(itemId)); - Client *client = NULL; + Client *client = nullptr; if (auctionCreator) client = auctionCreator->getClient(); @@ -1347,7 +1335,7 @@ void CommoditiesMarket::onAddAuction(int sequence, int32 result, const NetworkId if (container) { Container::ContainerErrorCode tmp = Container::CEC_Success; - bool result = ContainerInterface::transferItemToVolumeContainer(*container,*item, NULL, tmp); + bool result = ContainerInterface::transferItemToVolumeContainer(*container,*item, nullptr, tmp); if (!result) { LOG("CustomerService", ("Auction: Player %s transfer of item (%Ld) to auction container (%Ld) failed with code %d", @@ -1393,7 +1381,7 @@ void CommoditiesMarket::onAddAuction(int sequence, int32 result, const NetworkId } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CancelAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CancelAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } } @@ -1509,7 +1497,7 @@ void CommoditiesMarket::auctionCreate(CreatureObject &owner, ServerObject &item, } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1581,7 +1569,7 @@ void CommoditiesMarket::transferVendorItemFromStockroom(CreatureObject &owner, N else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1756,7 +1744,7 @@ void CommoditiesMarket::auctionCreateImmediate(CreatureObject &owner, ServerObje else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1772,67 +1760,9 @@ void CommoditiesMarket::auctionCreateImmediate(CreatureObject &owner, ServerObje void CommoditiesMarket::auctionCreatePermanent(const std::string &, const ServerObject &, const ServerObject &, BidAmount , const Unicode::String &, bool ) { - if (!ConfigServerGame::getCommoditiesMarketEnabled()) - return; - DEBUG_WARNING(true, ("auctionCreatePermanent has been depricated and shouldn't be used. If you see this WARNING, add a line to catch cheaters in the command in CommandCppFuncs.cpp")); return; - -#if 0 //what the hell is this? - - const NetworkId & itemId = item.getNetworkId(); - int flags = AUCTION_ALWAYS_PRESENT; - if (premium) - { - flags |= AUCTION_PREMIUM_AUCTION; - } - const TangibleObject *tangibleObject = item.asTangibleObject(); - if (tangibleObject && tangibleObject->hasCondition(ServerTangibleObjectTemplate::C_magicItem)) - { - flags |= AUCTION_MAGIC_ITEM; - } - - const Unicode::String objectName = Auction::getItemAuctionName(&item); - - const AuctionToken & token = AuctionTokenServer::createTokenFor(item); - Unicode::String oobData; - OutOfBandPackager::pack(token, 0, oobData); - - ServerObject::AttributeVector attributes; - - //-- I don't know why this cast is necessary, but MSDEV is apparently confused otherwise - static_cast(item).getAttributes(NetworkId::cms_invalid, attributes); - OutOfBandPackager::pack(attributes, 1, oobData); - - OutOfBandPackager::pack(item.getTemplateName(), 2, oobData); - - if (s_market) - { - s_market->AddImmediateAuction( - -1, - ownerName, - price, - 1, - itemId, - objectName.size(), objectName.data(), - item.getGameObjectType(), - ConfigServerGame::getUnclaimedAuctionItemDestroyTimeSec(), - auctionContainer.getNetworkId(), - getLocationString(auctionContainer), - flags, - userDescription.size(), userDescription.data(), - oobData.size(), - oobData); - } - else - { - - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.\n")); - - getCommoditiesServerConnection(); //attempt to reconnect to commodities server - } -#endif } // ---------------------------------------------------------------------- @@ -1892,7 +1822,7 @@ void CommoditiesMarket::auctionBid(CreatureObject &bidder, AuctionId auctionId, else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddBid.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddBid.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1931,7 +1861,7 @@ void CommoditiesMarket::auctionCancel(const NetworkId &playerId, AuctionId aucti else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CancelAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CancelAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -1956,7 +1886,7 @@ void CommoditiesMarket::auctionAccept(CreatureObject &who, AuctionId auctionId) } else { - WARNING(true, ("[Commodities API] : No commodities server connection to send AcceptHighBid.\n")); + WARNING(true, ("[Commodities API] : No commodities server connection to send AcceptHighBid.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } */ @@ -2066,7 +1996,7 @@ void CommoditiesMarket::auctionQueryHeaders( vendorId = zeroNetworkId; else vendorId = vendorObject->getNetworkId(); - DEBUG_REPORT_LOG(true, (" [AuctionQueryHeadersMessage]: container = %s, vendorId = %s\n", container.getValueString().c_str(), vendorId.getValueString().c_str())); + DEBUG_REPORT_LOG(true, (" [AuctionQueryHeadersMessage]: container = %s, vendorId = %s", container.getValueString().c_str(), vendorId.getValueString().c_str())); std::string searchStringPlanet; std::string searchStringRegion; @@ -2101,7 +2031,7 @@ void CommoditiesMarket::auctionQueryHeaders( else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send QueryAuctionHeaders.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send QueryAuctionHeaders.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2153,7 +2083,7 @@ void CommoditiesMarket::getAuctionDetails(CreatureObject &who, const NetworkId & else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetItemDetails.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetItemDetails.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2170,7 +2100,7 @@ void CommoditiesMarket::getVendorValue(ServerObject &container) } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetVendorValue.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetVendorValue.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2189,7 +2119,7 @@ void CommoditiesMarket::createVendorMarket(const CreatureObject &who, ServerObje } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CreateVendorMarket.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CreateVendorMarket.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2213,7 +2143,7 @@ void CommoditiesMarket::destroyVendorMarket(const NetworkId &playerId, ServerObj else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send DestroyVendorMarket.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send DestroyVendorMarket.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2232,7 +2162,7 @@ void CommoditiesMarket::deleteAuctionLocation(const NetworkId& locationId, const } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send DestroyVendorMarket.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send DestroyVendorMarket.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2254,7 +2184,7 @@ void CommoditiesMarket::isVendorOwner(CreatureObject &who, const NetworkId &cont else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetVendorOwner.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetVendorOwner.")); onIsVendorOwner(who.getNetworkId(), zeroNetworkId, zeroNetworkId); getCommoditiesServerConnection(); //attempt to reconnect to commodities server @@ -2536,7 +2466,7 @@ void CommoditiesMarket::checkPendingLoads(const NetworkId &itemId) bool transferAllowed = true; Container::ContainerErrorCode error = Container::CEC_Success; - transferAllowed = ContainerInterface::canTransferTo(targetContainer, *item, NULL, error); + transferAllowed = ContainerInterface::canTransferTo(targetContainer, *item, nullptr, error); if (!transferAllowed) { @@ -2558,7 +2488,7 @@ void CommoditiesMarket::checkPendingLoads(const NetworkId &itemId) } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetItem.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send GetItem.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2585,7 +2515,7 @@ void CommoditiesMarket::checkPendingLoads(const NetworkId &itemId) } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CleanupInvalidItemRetrieval.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send CleanupInvalidItemRetrieval.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } @@ -2603,11 +2533,11 @@ void CommoditiesMarket::onGetItemReply(int32 result, int32 requestId, NetworkId LOG("AuctionRetrieval", ("CommoditiesMarket::received onGetItemReply for loading object %s for retrieval", itemId.getValueString().c_str())); AuctionResult auctionResult = ar_OK; CreatureObject *player = dynamic_cast(NetworkIdManager::getObjectById(itemOwnerId)); - Client *client = player ? player->getClient() : NULL; + Client *client = player ? player->getClient() : nullptr; bool transactionFailed = false; - ServerObject* vendor = NULL; - ServerObject* item = NULL; + ServerObject* vendor = nullptr; + ServerObject* item = nullptr; if (result == ARC_AuctionDoesNotExist) { @@ -2637,7 +2567,7 @@ void CommoditiesMarket::onGetItemReply(int32 result, int32 requestId, NetworkId vendor = safe_cast(ContainerInterface::getContainedByObject(*item)); if (vendor && vendor->getNetworkId() == location) { - bool retval = ContainerInterface::transferItemToVolumeContainer(*inventory, *item, NULL, tmp, false); + bool retval = ContainerInterface::transferItemToVolumeContainer(*inventory, *item, nullptr, tmp, false); if (retval) { @@ -2779,7 +2709,7 @@ void CommoditiesMarket::onIsVendorOwner(const NetworkId & requesterId, const Net ServerObject * const auctionContainer = safe_cast(NetworkIdManager::getObjectById(container)); NetworkId resultContainer = container; - const TangibleObject * resultContainerObject = auctionContainer ? auctionContainer->asTangibleObject() : NULL; + const TangibleObject * resultContainerObject = auctionContainer ? auctionContainer->asTangibleObject() : nullptr; if (auctionContainer) { marketName = getLocationString(*auctionContainer); @@ -2952,7 +2882,7 @@ void CommoditiesMarket::onGetItemDetailsReply(int32 result, int32 requestId, Net OutOfBandBase *base = *it; if (!base) { - WARNING(true, ("NULL OOB Base for Auction Data")); + WARNING(true, ("nullptr OOB Base for Auction Data")); return; } if (base->getTypeId() == OutOfBandPackager::OT_auctionToken) @@ -2979,7 +2909,7 @@ void CommoditiesMarket::onGetItemDetailsReply(int32 result, int32 requestId, Net base = *it; if (!base) { - WARNING(true, ("NULL OOB Base for Auction Data")); + WARNING(true, ("nullptr OOB Base for Auction Data")); return; } if (base->getTypeId() == OutOfBandPackager::OT_objectAttributes) @@ -3007,7 +2937,7 @@ void CommoditiesMarket::onGetItemDetailsReply(int32 result, int32 requestId, Net static const std::string attributeClientSharedTemplateName("ClientSharedTemplateName"); static const std::string attributeAppearanceData("AppearanceData"); - DEBUG_REPORT_LOG(true,("Attribute: %s, %s\n",i->first.c_str(),Unicode::wideToNarrow(i->second).c_str())); + DEBUG_REPORT_LOG(true,("Attribute: %s, %s",i->first.c_str(),Unicode::wideToNarrow(i->second).c_str())); if (i->first==attributeClientSharedTemplateName) details.templateName = Unicode::wideToNarrow(i->second); @@ -3265,7 +3195,7 @@ void CommoditiesMarket::setSalesTax( int32 salesTax, const NetworkId &bankId, Se } else { - WARNING(true, ("[Commodities API] : No commodities server connection to send SetSalesTax.\n")); + WARNING(true, ("[Commodities API] : No commodities server connection to send SetSalesTax.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server } } @@ -3399,12 +3329,12 @@ bool CommoditiesMarket::restoreItem(ServerObject& item, TangibleObject & vendor) } else { - WARNING(true, ("[Commodities API] : Could not create Owner object in restore item.\n")); + WARNING(true, ("[Commodities API] : Could not create Owner object in restore item.")); } } else { - DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.\n")); + DEBUG_WARNING(true, ("[Commodities API] : No commodities server connection to send AddImmediateAuction.")); getCommoditiesServerConnection(); //attempt to reconnect to commodities server @@ -3624,22 +3554,22 @@ void CommoditiesMarket::updateItemTypeMap(int itemTypeMapVersionNumber, int item // get the server template const ObjectTemplate * ot = ObjectTemplateList::fetch(static_cast(itemTemplateId)); - if (ot != NULL) + if (ot != nullptr) { objectName = StringId(std::string(ot->getName())); // get the shared template const ServerObjectTemplate * serverOt = ot->asServerObjectTemplate(); - if (serverOt != NULL) + if (serverOt != nullptr) { const std::string sharedTemplateName(serverOt->getSharedTemplate()); serverOt->releaseReference(); - serverOt = NULL; + serverOt = nullptr; ot = ObjectTemplateList::fetch(sharedTemplateName); - if (ot != NULL) + if (ot != nullptr) { const SharedObjectTemplate * sharedOt = ot->asSharedObjectTemplate(); - if (sharedOt != NULL) + if (sharedOt != nullptr) { gameObjectType = static_cast(sharedOt->getGameObjectType()); StringId const tempObjectName(objectName); @@ -3649,19 +3579,19 @@ void CommoditiesMarket::updateItemTypeMap(int itemTypeMapVersionNumber, int item objectName = tempObjectName; } sharedOt->releaseReference(); - sharedOt = NULL; + sharedOt = nullptr; } else { ot->releaseReference(); - ot = NULL; + ot = nullptr; } } } else { ot->releaseReference(); - ot = NULL; + ot = nullptr; } } else diff --git a/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesServerConnection.cpp b/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesServerConnection.cpp index 1b7b95c9..9489929e 100755 --- a/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesServerConnection.cpp +++ b/engine/server/library/serverGame/src/shared/commoditiesMarket/CommoditiesServerConnection.cpp @@ -74,6 +74,8 @@ #include "serverNetworkMessages/OnQueryVendorItemCountReplyMessage.h" #include "serverNetworkMessages/OnUpdateVendorSearchOptionMessage.h" +#include "sharedFoundation/CrcConstexpr.hpp" + // ====================================================================== CommoditiesServerConnection::CommoditiesServerConnection(const std::string & a, const unsigned short p) : @@ -117,470 +119,490 @@ void CommoditiesServerConnection::onReceive(const Archive::ByteStream & message) ri = message.begin(); - if(msg.isType("OnAddAuctionMessage")) - { - OnAddAuctionMessage oaa_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAddAuctionMessage.\n")); - listener.OnAddAuction(oaa_message.GetResponseId(), oaa_message.GetResultCode(), oaa_message.GetItemId(), oaa_message.GetOwnerId(), oaa_message.GetOwnerName(), oaa_message.GetItemId(), oaa_message.GetVendorId(), NameManager::getInstance().getPlayerFullName(oaa_message.GetVendorId()), oaa_message.GetLocation()); - - } - else if(msg.isType("OnAddBidMessage")) - { - OnAddBidMessage oab_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAddBidMessage.\n")); - listener.OnAddBid(oab_message.GetResponseId(), oab_message.GetResultCode(), oab_message.GetOwnerId(), oab_message.GetItemId(), oab_message.GetBidderId(), oab_message.GetPreviousBidderId(), oab_message.GetBid(), oab_message.GetPreviousBid(), oab_message.GetMaxProxyBid(), oab_message.GetLocation(), NameManager::getInstance().getPlayerFullName(oab_message.GetOwnerId()), NameManager::getInstance().getPlayerFullName(oab_message.GetPreviousBidderId()), oab_message.GetItemNameLength(), oab_message.GetItemName(), oab_message.GetSalesTaxAmount(), oab_message.GetSalesTaxBankId()); - - } - else if(msg.isType("OnCancelAuctionMessage")) - { - OnCancelAuctionMessage oca_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCancelAuctionMessage.\n")); - listener.OnCancelAuction(oca_message.GetResponseId(), oca_message.GetResultCode(), oca_message.GetItemId(), oca_message.GetPlayerId(), oca_message.GetHighBidderId(), oca_message.GetHighBid(), oca_message.GetLocation()); - - } - else if(msg.isType("OnAcceptHighBidMessage")) - { - OnAcceptHighBidMessage oahb_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAcceptHighBidMessage.\n")); - listener.OnAcceptHighBid(oahb_message.GetResponseId(), oahb_message.GetResultCode(), oahb_message.GetItemId(), oahb_message.GetPlayerId()); - - } - else if(msg.isType("OnQueryAuctionHeadersMessage")) - { - OnQueryAuctionHeadersMessage oqah_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnQueryAuctionHeadersMessage.\n")); - listener.OnQueryAuctionHeadersReply(oqah_message.GetResponseId(), oqah_message.GetResultCode(), oqah_message.GetPlayerId(), oqah_message.GetQueryType(), oqah_message.GetNumAuctions(), oqah_message.GetAuctionData(), oqah_message.GetQueryOffset(), oqah_message.HasMorePages()); - - } - else if(msg.isType("OnGetItemDetailsMessage")) - { - OnGetItemDetailsMessage ogid_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : Received OnGetItemDetailsMessage.\n")); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : Result : %d.\n", ogid_message.GetResultCode())); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : ItemId : %s.\n", ogid_message.GetItemId().getValueString().c_str())); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : PlayerId : %s.\n", ogid_message.GetPlayerId().getValueString().c_str())); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : UserDescriptionLength : %d.\n", ogid_message.GetUserDescriptionLength())); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : UserDescription : %s.\n", Unicode::wideToNarrow(ogid_message.GetUserDescription()).c_str())); -// DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobLength : %d.\n", ogid_message.GetOobLength())); -// DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobActualLength : %d.\n", ogid_message.GetOobData().size())); -// DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobData : %s.\n", Unicode::wideToNarrow(ogid_message.GetOobData()).c_str())); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : ResponseId : %d.\n", ogid_message.GetResponseId())); - listener.OnGetItemDetailsReply(ogid_message.GetResponseId(), ogid_message.GetResultCode(), ogid_message.GetPlayerId(), ogid_message.GetItemId(), ogid_message.GetUserDescriptionLength(), ogid_message.GetUserDescription(), ogid_message.GetOobLength(), ogid_message.GetOobData(), ogid_message.GetAttributes()); - - } - else if(msg.isType("OnAuctionExpiredMessage")) - { - OnAuctionExpiredMessage oae_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAuctionExpiredMessage.\n")); - DEBUG_REPORT_LOG(true, (" -- OwnerId = %s, GetOwnerName = %s, BuyerId = %s, GetBuyerName = %s\n", oae_message.GetOwnerId().getValueString().c_str(), - NameManager::getInstance().getPlayerFullName(oae_message.GetOwnerId()).c_str(), - oae_message.GetBuyerId().getValueString().c_str(), - NameManager::getInstance().getPlayerFullName(oae_message.GetBuyerId()).c_str())); - listener.OnAuctionExpired(oae_message.GetItemId(), oae_message.GetOwnerId(), oae_message.IsSold(), oae_message.GetBuyerId(), oae_message.GetBid(), oae_message.GetItemId(), oae_message.GetMaxProxyBid(), oae_message.GetLocation(), oae_message.IsImmediate(), NameManager::getInstance().getPlayerFullName(oae_message.GetOwnerId()), NameManager::getInstance().getPlayerFullName(oae_message.GetBuyerId()), oae_message.GetItemNameLength(), oae_message.GetItemName(), oae_message.GetSendSellerMail()); - - } - else if(msg.isType("OnItemExpiredMessage")) - { - OnItemExpiredMessage oie_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnItemExpiredMessage.\n")); - listener.OnItemExpired(oie_message.GetOwnerId(), oie_message.GetItemId(), - NameManager::getInstance().getPlayerFullName(oie_message.GetOwnerId()), - oie_message.GetItemNameLength(), oie_message.GetItemName(), - oie_message.GetLocationName(), oie_message.GetLocationId()); - - } - else if(msg.isType("OnGetItemMessage")) - { - OnGetItemMessage ogi_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetItemMessage.\n")); - listener.OnGetItemReply(ogi_message.GetResponseId(), ogi_message.GetResultCode(), ogi_message.GetItemId(), ogi_message.GetPlayerId(), ogi_message.GetLocation()); - - } - else if(msg.isType("OnCreateVendorMarketMessage")) - { - OnCreateVendorMarketMessage ocvm_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCreateVendorMarketMessage.\n")); - listener.OnCreateVendorMarket(ocvm_message.GetResponseId(), ocvm_message.GetResultCode(), ocvm_message.GetOwnerId(), ocvm_message.GetLocation()); - - } - else if(msg.isType("OnVendorRefuseItemMessage")) - { - OnVendorRefuseItemMessage ovri_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnVendorRefuseItemMessage.\n")); - listener.OnVendorRefuseItem(ovri_message.GetResponseId(), ovri_message.GetResultCode(), ovri_message.GetItemId(), ovri_message.GetVendorId(), ovri_message.GetItemOwnerId()); - - } - else if(msg.isType("OnGetVendorOwnerMessage")) - { - OnGetVendorOwnerMessage ogvo_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetVendorOwnerMessage.\n")); - listener.OnGetVendorOwner(ogvo_message.GetResponseId(), ogvo_message.GetResultCode(), ogvo_message.GetOwnerId(), - NameManager::getInstance().getPlayerFullName(ogvo_message.GetOwnerId()), - ogvo_message.GetLocation(), ogvo_message.GetRequesterId()); - - } - else if(msg.isType("OnGetVendorValueMessage")) - { - OnGetVendorValueMessage ogvv_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetVendorValueMessage.\n")); - listener.OnGetVendorValue(ogvv_message.GetResponseId(), ogvv_message.GetLocation(), ogvv_message.GetValue()); - - } - else if(msg.isType("OnPermanentAuctionPurchasedMessage")) - { - OnPermanentAuctionPurchasedMessage opa_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnPermanentAuctionPurchasedMessage.\n")); - listener.OnPermanentAuctionPurchased( - opa_message.GetOwnerId(), opa_message.GetBuyerId(), opa_message.GetPrice(), opa_message.GetItemId(), opa_message.GetLocation(), - NameManager::getInstance().getPlayerFullName(opa_message.GetOwnerId()), - NameManager::getInstance().getPlayerFullName(opa_message.GetBuyerId()), - opa_message.GetItemNameLength(), opa_message.GetItemName(), opa_message.GetAttributes()); - - } - else if(msg.isType("OnCleanupInvalidItemRetrievalMessage")) - { - OnCleanupInvalidItemRetrievalMessage ociir_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCleanupInvalidItemRetrievalMessage.\n")); - listener.OnCleanupInvalidItemRetrieval(ociir_message.GetResponseId(), ociir_message.GetItemId(), ociir_message.GetPlayerId(), ociir_message.GetCreatorId(), ociir_message.GetReimburseAmt()); - - } - else if(msg.isType("OnGetPlayerVendorCountMessage")) - { - OnGetPlayerVendorCountMessage ogpvc_message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetPlayerVendorCountMessage.\n")); - CommoditiesMarket::playerVendorCountReply(ogpvc_message.GetPlayerId(), ogpvc_message.GetVendorCount(), ogpvc_message.GetVendorList()); - } - else if (msg.isType("VendorStatusChangeMessage")) - { - VendorStatusChangeMessage vscMessage(ri); - static char * vendorStatus[] = {"Empty", "Not Empty", "Unaccessed", "Endangered", "Removed"}; - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received VendorStatusChangeMessage.\n")); - if (vscMessage.getStatus() >= ARC_VendorStatusEmpty && vscMessage.getStatus() <= ARC_VendorRemoved) - { - LOG("CustomerService", ("Vendor: Vendor %s status changed to %s", vscMessage.getVendorId().getValueString().c_str(), vendorStatus[vscMessage.getStatus() - ARC_VendorStatusEmpty])); + switch (msg.getType()) { + case constcrc("OnAddAuctionMessage"): { + OnAddAuctionMessage oaa_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAddAuctionMessage.\n")); + listener.OnAddAuction(oaa_message.GetResponseId(), oaa_message.GetResultCode(), oaa_message + .GetItemId(), oaa_message.GetOwnerId(), oaa_message.GetOwnerName(), oaa_message + .GetItemId(), oaa_message.GetVendorId(), NameManager::getInstance() + .getPlayerFullName(oaa_message.GetVendorId()), oaa_message.GetLocation()); + break; } - else - { - WARNING(true, ("[Commodities API] : Invalid vendor status %s %d.\n", vscMessage.getVendorId().getValueString().c_str(), vscMessage.getStatus())); + case constcrc("OnAddBidMessage"): { + OnAddBidMessage oab_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAddBidMessage.\n")); + listener.OnAddBid(oab_message.GetResponseId(), oab_message.GetResultCode(), oab_message + .GetOwnerId(), oab_message.GetItemId(), oab_message.GetBidderId(), oab_message + .GetPreviousBidderId(), oab_message.GetBid(), oab_message.GetPreviousBid(), oab_message + .GetMaxProxyBid(), oab_message.GetLocation(), NameManager::getInstance() + .getPlayerFullName(oab_message.GetOwnerId()), NameManager::getInstance() + .getPlayerFullName(oab_message.GetPreviousBidderId()), oab_message.GetItemNameLength(), oab_message + .GetItemName(), oab_message.GetSalesTaxAmount(), oab_message.GetSalesTaxBankId()); + break; } - CommoditiesMarket::vendorStatusChange(vscMessage.getVendorId(), vscMessage.getStatus()); - } - else if (msg.isType("OnQueryVendorItemCountReplyMessage")) - { - OnQueryVendorItemCountReplyMessage qvMessage(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnQueryVendorItemCountReplyMessage.\n")); - CommoditiesMarket::vendorItemCountReply(qvMessage.getVendorId(), qvMessage.getVendorItemCount(), qvMessage.getSearchEnabled()); - } - else if (msg.isType("OnUpdateVendorSearchOptionMessage")) - { - OnUpdateVendorSearchOptionMessage uvsoMessage(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnUpdateVendorSearchOptionMessage.\n")); - ServerObject *player = ServerWorld::findObjectByNetworkId(uvsoMessage.GetPlayerId()); - if (player) - { - StringId const VENDOR_SEARCH_ENABLED("player_structure", "vendor_search_enabled"); - StringId const VENDOR_SEARCH_DISABLED("player_structure", "vendor_search_disabled"); - if (uvsoMessage.GetEnabled()) - Chat::sendSystemMessageSimple(*player , VENDOR_SEARCH_ENABLED, 0); - else - Chat::sendSystemMessageSimple(*player , VENDOR_SEARCH_DISABLED, 0); + case constcrc("OnCancelAuctionMessage"): { + OnCancelAuctionMessage oca_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCancelAuctionMessage.\n")); + listener.OnCancelAuction(oca_message.GetResponseId(), oca_message.GetResultCode(), oca_message + .GetItemId(), oca_message.GetPlayerId(), oca_message.GetHighBidderId(), oca_message + .GetHighBid(), oca_message.GetLocation()); + break; } - } - else if(msg.isType("OnCommodityReplyMessage")) - { - ri = static_cast(msg).getByteStream().begin(); - GenericValueTypeMessage > message(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCommodityReplyMessage.\n")); + case constcrc("OnAcceptHighBidMessage"): { + OnAcceptHighBidMessage oahb_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAcceptHighBidMessage.\n")); + listener.OnAcceptHighBid(oahb_message.GetResponseId(), oahb_message.GetResultCode(), oahb_message + .GetItemId(), oahb_message.GetPlayerId()); + break; + } + case constcrc("OnQueryAuctionHeadersMessage"): { + OnQueryAuctionHeadersMessage oqah_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnQueryAuctionHeadersMessage.\n")); + listener.OnQueryAuctionHeadersReply(oqah_message.GetResponseId(), oqah_message.GetResultCode(), oqah_message + .GetPlayerId(), oqah_message.GetQueryType(), oqah_message.GetNumAuctions(), oqah_message + .GetAuctionData(), oqah_message.GetQueryOffset(), oqah_message.HasMorePages()); + break; + } + case constcrc("OnGetItemDetailsMessage"): { + OnGetItemDetailsMessage ogid_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : Received OnGetItemDetailsMessage.\n")); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : Result : %d.\n", ogid_message + .GetResultCode())); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : ItemId : %s.\n", ogid_message + .GetItemId().getValueString().c_str())); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : PlayerId : %s.\n", ogid_message + .GetPlayerId().getValueString().c_str())); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : UserDescriptionLength : %d.\n", ogid_message + .GetUserDescriptionLength())); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : UserDescription : %s.\n", Unicode::wideToNarrow(ogid_message + .GetUserDescription()).c_str())); + // DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobLength : %d.\n", ogid_message.GetOobLength())); + // DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobActualLength : %d.\n", ogid_message.GetOobData().size())); + // DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : OobData : %s.\n", Unicode::wideToNarrow(ogid_message.GetOobData()).c_str())); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API OnGetItemDetailsMessage] : ResponseId : %d.\n", ogid_message + .GetResponseId())); + listener.OnGetItemDetailsReply(ogid_message.GetResponseId(), ogid_message.GetResultCode(), ogid_message + .GetPlayerId(), ogid_message.GetItemId(), ogid_message.GetUserDescriptionLength(), ogid_message + .GetUserDescription(), ogid_message.GetOobLength(), ogid_message.GetOobData(), ogid_message + .GetAttributes()); + break; + } + case constcrc("OnAuctionExpiredMessage"): { + OnAuctionExpiredMessage oae_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnAuctionExpiredMessage.\n")); + DEBUG_REPORT_LOG(true, (" -- OwnerId = %s, GetOwnerName = %s, BuyerId = %s, GetBuyerName = %s\n", oae_message + .GetOwnerId().getValueString().c_str(), + NameManager::getInstance().getPlayerFullName(oae_message.GetOwnerId()).c_str(), + oae_message.GetBuyerId().getValueString().c_str(), + NameManager::getInstance().getPlayerFullName(oae_message.GetBuyerId()).c_str())); + listener.OnAuctionExpired(oae_message.GetItemId(), oae_message.GetOwnerId(), oae_message + .IsSold(), oae_message.GetBuyerId(), oae_message.GetBid(), oae_message.GetItemId(), oae_message + .GetMaxProxyBid(), oae_message.GetLocation(), oae_message.IsImmediate(), NameManager::getInstance() + .getPlayerFullName(oae_message.GetOwnerId()), NameManager::getInstance() + .getPlayerFullName(oae_message.GetBuyerId()), oae_message.GetItemNameLength(), oae_message + .GetItemName(), oae_message.GetSendSellerMail()); + break; + } + case constcrc("OnItemExpiredMessage"): { + OnItemExpiredMessage oie_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnItemExpiredMessage.\n")); + listener.OnItemExpired(oie_message.GetOwnerId(), oie_message.GetItemId(), + NameManager::getInstance().getPlayerFullName(oie_message.GetOwnerId()), + oie_message.GetItemNameLength(), oie_message.GetItemName(), + oie_message.GetLocationName(), oie_message.GetLocationId()); + break; + } + case constcrc("OnGetItemMessage"): { + OnGetItemMessage ogi_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetItemMessage.\n")); + listener.OnGetItemReply(ogi_message.GetResponseId(), ogi_message.GetResultCode(), ogi_message + .GetItemId(), ogi_message.GetPlayerId(), ogi_message.GetLocation()); + break; + } + case constcrc("OnCreateVendorMarketMessage"): { + OnCreateVendorMarketMessage ocvm_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCreateVendorMarketMessage.\n")); + listener.OnCreateVendorMarket(ocvm_message.GetResponseId(), ocvm_message.GetResultCode(), ocvm_message + .GetOwnerId(), ocvm_message.GetLocation()); + break; + } + case constcrc("OnVendorRefuseItemMessage"): { + OnVendorRefuseItemMessage ovri_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnVendorRefuseItemMessage.\n")); + listener.OnVendorRefuseItem(ovri_message.GetResponseId(), ovri_message.GetResultCode(), ovri_message + .GetItemId(), ovri_message.GetVendorId(), ovri_message.GetItemOwnerId()); + break; + } + case constcrc("OnGetVendorOwnerMessage"): { + OnGetVendorOwnerMessage ogvo_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetVendorOwnerMessage.\n")); + listener.OnGetVendorOwner(ogvo_message.GetResponseId(), ogvo_message.GetResultCode(), ogvo_message + .GetOwnerId(), + NameManager::getInstance().getPlayerFullName(ogvo_message.GetOwnerId()), + ogvo_message.GetLocation(), ogvo_message.GetRequesterId()); + break; + } + case constcrc("OnGetVendorValueMessage"): { + OnGetVendorValueMessage ogvv_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetVendorValueMessage.\n")); + listener.OnGetVendorValue(ogvv_message.GetResponseId(), ogvv_message.GetLocation(), ogvv_message + .GetValue()); + break; + } + case constcrc("OnPermanentAuctionPurchasedMessage"): { + OnPermanentAuctionPurchasedMessage opa_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnPermanentAuctionPurchasedMessage.\n")); + listener.OnPermanentAuctionPurchased( + opa_message.GetOwnerId(), opa_message.GetBuyerId(), opa_message.GetPrice(), opa_message + .GetItemId(), opa_message.GetLocation(), + NameManager::getInstance().getPlayerFullName(opa_message.GetOwnerId()), + NameManager::getInstance().getPlayerFullName(opa_message.GetBuyerId()), + opa_message.GetItemNameLength(), opa_message.GetItemName(), opa_message.GetAttributes()); + break; + } + case constcrc("OnCleanupInvalidItemRetrievalMessage"): { + OnCleanupInvalidItemRetrievalMessage ociir_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCleanupInvalidItemRetrievalMessage.\n")); + listener.OnCleanupInvalidItemRetrieval(ociir_message.GetResponseId(), ociir_message + .GetItemId(), ociir_message.GetPlayerId(), ociir_message.GetCreatorId(), ociir_message + .GetReimburseAmt()); + break; + } + case constcrc("OnGetPlayerVendorCountMessage"): { + OnGetPlayerVendorCountMessage ogpvc_message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnGetPlayerVendorCountMessage.\n")); + CommoditiesMarket::playerVendorCountReply(ogpvc_message.GetPlayerId(), ogpvc_message + .GetVendorCount(), ogpvc_message.GetVendorList()); + break; + } + case constcrc("VendorStatusChangeMessage"): { + VendorStatusChangeMessage vscMessage(ri); + static char *vendorStatus[] = {"Empty", "Not Empty", "Unaccessed", "Endangered", "Removed"}; + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received VendorStatusChangeMessage.\n")); + if (vscMessage.getStatus() >= ARC_VendorStatusEmpty && vscMessage.getStatus() <= ARC_VendorRemoved) { + LOG("CustomerService", ("Vendor: Vendor %s status changed to %s", vscMessage.getVendorId() + .getValueString() + .c_str(), vendorStatus[ + vscMessage.getStatus() - ARC_VendorStatusEmpty])); + } + else { + WARNING(true, ("[Commodities API] : Invalid vendor status %s %d.\n", vscMessage.getVendorId() + .getValueString() + .c_str(), vscMessage + .getStatus())); + } + CommoditiesMarket::vendorStatusChange(vscMessage.getVendorId(), vscMessage.getStatus()); + break; + } + case constcrc("OnQueryVendorItemCountReplyMessage"): { + OnQueryVendorItemCountReplyMessage qvMessage(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnQueryVendorItemCountReplyMessage.\n")); + CommoditiesMarket::vendorItemCountReply(qvMessage.getVendorId(), qvMessage.getVendorItemCount(), qvMessage + .getSearchEnabled()); + break; + } + case constcrc("OnUpdateVendorSearchOptionMessage"): { + OnUpdateVendorSearchOptionMessage uvsoMessage(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnUpdateVendorSearchOptionMessage.\n")); + ServerObject *player = ServerWorld::findObjectByNetworkId(uvsoMessage.GetPlayerId()); + if (player) { + StringId const VENDOR_SEARCH_ENABLED("player_structure", "vendor_search_enabled"); + StringId const VENDOR_SEARCH_DISABLED("player_structure", "vendor_search_disabled"); + if (uvsoMessage.GetEnabled()) { + Chat::sendSystemMessageSimple(*player, VENDOR_SEARCH_ENABLED, 0); + } + else { + Chat::sendSystemMessageSimple(*player, VENDOR_SEARCH_DISABLED, 0); + } + } + break; + } + case constcrc("OnCommodityReplyMessage"): { + ri = static_cast(msg).getByteStream().begin(); + GenericValueTypeMessage > message(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received OnCommodityReplyMessage.\n")); - Chat::sendSystemMessage(message.getValue().first, Unicode::narrowToWide(message.getValue().second), Unicode::String()); - } - else if (msg.isType("CommoditiesItemTypeMap")) - { - GenericValueTypeMessage > > > msg(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesItemTypeMap.\n")); - CommoditiesMarket::updateItemTypeMap(msg.getValue().first, msg.getValue().second); - } - else if (msg.isType("CommoditiesItemTypeAdded")) - { - GenericValueTypeMessage > > msg(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesItemTypeAdded.\n")); - CommoditiesMarket::updateItemTypeMap(msg.getValue().first, msg.getValue().second.first, msg.getValue().second.second); - } - else if (msg.isType("CommoditiesResourceTypeMap")) - { - GenericValueTypeMessage > > > msg(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesResourceTypeMap.\n")); - CommoditiesMarket::updateResourceTypeMap(msg.getValue().first, msg.getValue().second); - } - else if (msg.isType("CommoditiesResourceTypeAdded")) - { - GenericValueTypeMessage > > msg(ri); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesResourceTypeAdded.\n")); - CommoditiesMarket::updateResourceTypeMap(msg.getValue().first, msg.getValue().second.first, msg.getValue().second.second); - } - else if (msg.isType("RequestCommoditiesExcludedGotTypes")) - { - GenericValueTypeMessage msg(ri); - UNREF(msg); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestCommoditiesExcludedGotTypes.\n")); + Chat::sendSystemMessage(message.getValue().first, Unicode::narrowToWide(message.getValue() + .second), Unicode::String()); + break; + } + case constcrc("CommoditiesItemTypeMap"): { + GenericValueTypeMessage < std::pair < int, std::map < int, std::set < int > > > > msg(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesItemTypeMap.\n")); + CommoditiesMarket::updateItemTypeMap(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("CommoditiesItemTypeAdded"): { + GenericValueTypeMessage < std::pair < int, std::pair < int, int > > > msg(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesItemTypeAdded.\n")); + CommoditiesMarket::updateItemTypeMap(msg.getValue().first, msg.getValue().second.first, msg.getValue() + .second.second); + break; + } + case constcrc("CommoditiesResourceTypeMap"): { + GenericValueTypeMessage < std::pair < int, std::map < int, std::set < std::string > > > > msg(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesResourceTypeMap.\n")); + CommoditiesMarket::updateResourceTypeMap(msg.getValue().first, msg.getValue().second); + break; + } + case constcrc("CommoditiesResourceTypeAdded"): { + GenericValueTypeMessage < std::pair < int, std::pair < int, std::string > > > msg(ri); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received CommoditiesResourceTypeAdded.\n")); + CommoditiesMarket::updateResourceTypeMap(msg.getValue().first, msg.getValue().second.first, msg.getValue() + .second + .second); + break; + } + case constcrc("RequestCommoditiesExcludedGotTypes"): { + GenericValueTypeMessage msg(ri); + UNREF(msg); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestCommoditiesExcludedGotTypes.\n")); - GenericValueTypeMessage > reply("ResponseCommoditiesExcludedGotTypes", GameObjectTypes::getTypesExcludedFromCommodities()); - send(reply, true); - } - else if (msg.isType("RequestCommoditiesExcludedResourceClasses")) - { - GenericValueTypeMessage msg(ri); - UNREF(msg); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestCommoditiesExcludedResourceClasses.\n")); + GenericValueTypeMessage > reply("ResponseCommoditiesExcludedGotTypes", GameObjectTypes::getTypesExcludedFromCommodities()); + send(reply, true); + break; + } + case constcrc("RequestCommoditiesExcludedResourceClasses"): { + GenericValueTypeMessage msg(ri); + UNREF(msg); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestCommoditiesExcludedResourceClasses.\n")); - GenericValueTypeMessage > reply("ResponseCommoditiesExcludedResourceClasses", ResourceClassObject::getClassesExcludedFromCommodities()); - send(reply, true); - } - else if (msg.isType("RequestResourceTreeHierarchy")) - { - GenericValueTypeMessage msg(ri); - UNREF(msg); - DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestResourceTreeHierarchy.\n")); + GenericValueTypeMessage > reply("ResponseCommoditiesExcludedResourceClasses", ResourceClassObject::getClassesExcludedFromCommodities()); + send(reply, true); + break; + } + case constcrc("RequestResourceTreeHierarchy"): { + GenericValueTypeMessage msg(ri); + UNREF(msg); + DEBUG_REPORT_LOG(m_commoditiesShowAllDebugInfo, ("[Commodities API] : Received RequestResourceTreeHierarchy.\n")); - ResourceClassObject const * resourceTreeRoot = Universe::getInstance().getResourceTreeRoot(); - if (resourceTreeRoot) - { - std::vector leafChildren; - resourceTreeRoot->getLeafChildren(leafChildren); + ResourceClassObject const *resourceTreeRoot = Universe::getInstance().getResourceTreeRoot(); + if (resourceTreeRoot) { + std::vector < ResourceClassObject const * > leafChildren; + resourceTreeRoot->getLeafChildren(leafChildren); - std::map > resourceTreeHierarchy; - ResourceClassObject const * parent; - for (std::vector::const_iterator iter = leafChildren.begin(); iter != leafChildren.end(); ++iter) - { - std::set & parents = resourceTreeHierarchy[static_cast(Crc::calculate((*iter)->getResourceClassName().c_str()))]; - parent = (*iter)->getParent(); - while (parent) + std::map > resourceTreeHierarchy; + ResourceClassObject const *parent; + for (std::vector < ResourceClassObject const * > ::const_iterator + iter = leafChildren.begin(); + iter != leafChildren.end(); + ++iter) { - parents.insert(static_cast(Crc::calculate(parent->getResourceClassName().c_str()))); + std::set &parents = resourceTreeHierarchy[static_cast(Crc::calculate((*iter) + ->getResourceClassName().c_str()))]; + parent = (*iter)->getParent(); + while (parent) { + parents.insert(static_cast(Crc::calculate(parent->getResourceClassName().c_str()))); - if (parent->isRoot()) - break; + if (parent->isRoot()) { + break; + } - parent = parent->getParent(); + parent = parent->getParent(); + } + } + + GenericValueTypeMessage < std::map < int, std::set < int > > > + reply("ResponseResourceTreeHierarchy", resourceTreeHierarchy); + send(reply, true); + } + break; + } + case constcrc("GetItemAttributeDataRsp"): { + GenericValueTypeMessage < std::pair < std::pair < NetworkId, std::string >, std::string > > + const response(ri); + + ServerObject *const requester = ServerWorld::findObjectByNetworkId(response.getValue().first.first); + if (requester && requester->getClient()) { + if (response.getValue().first.second == std::string("(~!@#$%^&*)system_mesage(*&^%$#@!~)")) { + ConsoleMgr::broadcastString(response.getValue().second, requester->getClient()); + } + else { + GenericValueTypeMessage > const data("SaveTextOnClient", std::make_pair(response + .getValue().first.second, response.getValue().second)); + requester->getClient()->send(data, true); + } + } + break; + } + case constcrc("DisplayStringForPlayer"): { + GenericValueTypeMessage > const response(ri); + + ServerObject *const requester = ServerWorld::findObjectByNetworkId(response.getValue().first); + if (requester && requester->getClient()) { + ConsoleMgr::broadcastString(response.getValue().second, requester->getClient()); + } + break; + } + case constcrc("GetVendorInfoForPlayerRsp"): { + GenericValueTypeMessage < std::pair < std::pair < NetworkId, std::string >, std::map < std::string, + std::vector < std::string > > > > + const response(ri); + + std::vector name; + std::vector location; + std::vector tax; + std::vector taxCityTemp; + std::vector taxCity; + std::vector emptyDate; + std::vector lastAccessDate; + std::vector inactiveDate; + std::vector status; + std::vector searchable; + std::vector entranceCharge; + std::vector itemCount; + std::vector offerCount; + std::vector stockRoomCount; + + std::map < std::string, std::vector < std::string > > ::const_iterator + iterFind = response.getValue().second.find("name"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + name.push_back(iter->c_str()); } } - GenericValueTypeMessage > > reply("ResponseResourceTreeHierarchy", resourceTreeHierarchy); - send(reply, true); - } - } - else if(msg.isType("GetItemAttributeDataRsp")) - { - GenericValueTypeMessage, std::string> > const response(ri); - - ServerObject * const requester = ServerWorld::findObjectByNetworkId(response.getValue().first.first); - if (requester && requester->getClient()) - { - if (response.getValue().first.second == std::string("(~!@#$%^&*)system_mesage(*&^%$#@!~)")) - { - ConsoleMgr::broadcastString(response.getValue().second, requester->getClient()); + iterFind = response.getValue().second.find("location"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + location.push_back(iter->c_str()); + } } - else - { - GenericValueTypeMessage > const data("SaveTextOnClient", std::make_pair(response.getValue().first.second, response.getValue().second)); - requester->getClient()->send(data, true); + + iterFind = response.getValue().second.find("tax"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + tax.push_back(iter->c_str()); + } } - } - } - else if(msg.isType("DisplayStringForPlayer")) - { - GenericValueTypeMessage > const response(ri); - ServerObject * const requester = ServerWorld::findObjectByNetworkId(response.getValue().first); - if (requester && requester->getClient()) - { - ConsoleMgr::broadcastString(response.getValue().second, requester->getClient()); - } - } - else if(msg.isType("GetVendorInfoForPlayerRsp")) - { - GenericValueTypeMessage, std::map > > > const response(ri); - - std::vector name; - std::vector location; - std::vector tax; - std::vector taxCityTemp; - std::vector taxCity; - std::vector emptyDate; - std::vector lastAccessDate; - std::vector inactiveDate; - std::vector status; - std::vector searchable; - std::vector entranceCharge; - std::vector itemCount; - std::vector offerCount; - std::vector stockRoomCount; - - std::map >::const_iterator iterFind = response.getValue().second.find("name"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - name.push_back(iter->c_str()); - } - } - - iterFind = response.getValue().second.find("location"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - location.push_back(iter->c_str()); - } - } - - iterFind = response.getValue().second.find("tax"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - tax.push_back(iter->c_str()); - } - } - - iterFind = response.getValue().second.find("taxCity"); - if (iterFind != response.getValue().second.end()) - { - taxCityTemp = iterFind->second; - NetworkId cityHallId; - int cityId; - std::vector::iterator iterTaxCity; - for (iterTaxCity = taxCityTemp.begin(); iterTaxCity != taxCityTemp.end(); ++iterTaxCity) - { - cityHallId = NetworkId(*iterTaxCity); - if (cityHallId.isValid()) - { - cityId = CityInterface::findCityByCityHall(cityHallId); - if (cityId != 0) - { - *iterTaxCity = CityInterface::getCityInfo(cityId).getCityName(); + iterFind = response.getValue().second.find("taxCity"); + if (iterFind != response.getValue().second.end()) { + taxCityTemp = iterFind->second; + NetworkId cityHallId; + int cityId; + std::vector::iterator iterTaxCity; + for (iterTaxCity = taxCityTemp.begin(); iterTaxCity != taxCityTemp.end(); ++iterTaxCity) { + cityHallId = NetworkId(*iterTaxCity); + if (cityHallId.isValid()) { + cityId = CityInterface::findCityByCityHall(cityHallId); + if (cityId != 0) { + *iterTaxCity = CityInterface::getCityInfo(cityId).getCityName(); + } + else { + *iterTaxCity = ""; + } } - else - { + else { *iterTaxCity = ""; } } - else - { - *iterTaxCity = ""; + + for (iterTaxCity = taxCityTemp.begin(); iterTaxCity != taxCityTemp.end(); ++iterTaxCity) { + taxCity.push_back(iterTaxCity->c_str()); } } - for (iterTaxCity = taxCityTemp.begin(); iterTaxCity != taxCityTemp.end(); ++iterTaxCity) - { - taxCity.push_back(iterTaxCity->c_str()); + iterFind = response.getValue().second.find("emptyDate"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + emptyDate.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("emptyDate"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - emptyDate.push_back(iter->c_str()); + iterFind = response.getValue().second.find("lastAccessDate"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + lastAccessDate.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("lastAccessDate"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - lastAccessDate.push_back(iter->c_str()); + iterFind = response.getValue().second.find("inactiveDate"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + inactiveDate.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("inactiveDate"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - inactiveDate.push_back(iter->c_str()); + iterFind = response.getValue().second.find("status"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + status.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("status"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - status.push_back(iter->c_str()); + iterFind = response.getValue().second.find("searchable"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + searchable.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("searchable"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - searchable.push_back(iter->c_str()); + iterFind = response.getValue().second.find("entranceCharge"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + entranceCharge.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("entranceCharge"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - entranceCharge.push_back(iter->c_str()); + iterFind = response.getValue().second.find("itemCount"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + itemCount.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("itemCount"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - itemCount.push_back(iter->c_str()); + iterFind = response.getValue().second.find("offerCount"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + offerCount.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("offerCount"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - offerCount.push_back(iter->c_str()); + iterFind = response.getValue().second.find("stockRoomCount"); + if (iterFind != response.getValue().second.end()) { + for (std::vector::const_iterator iter = iterFind->second.begin(); + iter != iterFind->second.end(); ++iter) { + stockRoomCount.push_back(iter->c_str()); + } } - } - iterFind = response.getValue().second.find("stockRoomCount"); - if (iterFind != response.getValue().second.end()) - { - for (std::vector::const_iterator iter = iterFind->second.begin(); iter != iterFind->second.end(); ++iter) - { - stockRoomCount.push_back(iter->c_str()); + ScriptParams params; + params.addParam(response.getValue().first.second.c_str(), "summary"); + params.addParam(name, "name"); + params.addParam(location, "location"); + params.addParam(tax, "tax"); + params.addParam(taxCity, "taxCity"); + params.addParam(emptyDate, "emptyDate"); + params.addParam(lastAccessDate, "lastAccessDate"); + params.addParam(inactiveDate, "inactiveDate"); + params.addParam(status, "status"); + params.addParam(searchable, "searchable"); + params.addParam(entranceCharge, "entranceCharge"); + params.addParam(itemCount, "itemCount"); + params.addParam(offerCount, "offerCount"); + params.addParam(stockRoomCount, "stockRoomCount"); + + ScriptDictionaryPtr dictionary; + GameScriptObject::makeScriptDictionary(params, dictionary); + if (dictionary.get() != nullptr) { + dictionary->serialize(); + MessageToQueue::getInstance().sendMessageToJava(response.getValue().first.first, + "getVendorInfoForPlayerRsp", dictionary->getSerializedData(), 0, false); } - } - - ScriptParams params; - params.addParam(response.getValue().first.second.c_str(), "summary"); - params.addParam(name, "name"); - params.addParam(location, "location"); - params.addParam(tax, "tax"); - params.addParam(taxCity, "taxCity"); - params.addParam(emptyDate, "emptyDate"); - params.addParam(lastAccessDate, "lastAccessDate"); - params.addParam(inactiveDate, "inactiveDate"); - params.addParam(status, "status"); - params.addParam(searchable, "searchable"); - params.addParam(entranceCharge, "entranceCharge"); - params.addParam(itemCount, "itemCount"); - params.addParam(offerCount, "offerCount"); - params.addParam(stockRoomCount, "stockRoomCount"); - - ScriptDictionaryPtr dictionary; - GameScriptObject::makeScriptDictionary(params, dictionary); - if (dictionary.get() != NULL) - { - dictionary->serialize(); - MessageToQueue::getInstance().sendMessageToJava(response.getValue().first.first, - "getVendorInfoForPlayerRsp", dictionary->getSerializedData(), 0, false); + break; } } } diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserAi.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserAi.cpp index 65298e93..994b695b 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserAi.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserAi.cpp @@ -74,7 +74,7 @@ CreatureObject * const ConsoleCommandParserAiNamespace::getAiCreatureObject(Crea CreatureObject * const aiCreatureObject = CreatureObject::getCreatureObject(aiNetworkId); - if ( (aiCreatureObject == NULL) + if ( (aiCreatureObject == nullptr) || aiCreatureObject->isPlayerControlled()) { Chat::sendSystemMessage(user, Unicode::narrowToWide(FormattedString<1024>().sprintf("[FAILURE] Unable to resolve %s to an AI", aiNetworkId.getValueString().c_str())), Unicode::emptyString); @@ -113,7 +113,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -121,7 +121,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const aiCreatureObject = getAiCreatureObject(*userCreatureObject, argv); - if (aiCreatureObject == NULL) + if (aiCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -129,7 +129,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { AICreatureController * const aiCreatureController = AICreatureController::asAiCreatureController(aiCreatureObject->getController()); - if (aiCreatureController == NULL) + if (aiCreatureController == nullptr) { Chat::sendSystemMessage(*userCreatureObject, Unicode::narrowToWide(fs.sprintf("[FAILURE] Unable to resolve %s to an AI", aiCreatureObject->getNetworkId().getValueString().c_str())), Unicode::emptyString); result += getErrorMessage(argv[0], ERR_FAIL); @@ -148,7 +148,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -167,7 +167,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri AICreatureController * const aiCreatureController = AICreatureController::getAiCreatureController(targetNetworkId); - if (aiCreatureController == NULL) + if (aiCreatureController == nullptr) { result = Unicode::narrowToWide(fs.sprintf("[FAILURE] Unable to resolve %s to an AI\n", targetNetworkId.getValueString().c_str())); result += getErrorMessage(argv[0], ERR_FAIL); @@ -190,7 +190,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CellProperty const * const cellProperty = creatureOwner->getParentCell(); - if (cellProperty != NULL) + if (cellProperty != nullptr) { Vector const & position_p = creatureOwner->getPosition_p(); @@ -245,13 +245,13 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri TangibleObject const * const hateTargetTangibleObject = TangibleObject::asTangibleObject(hateTarget.getObject()); float const hate = iterHateList->second; std::string hateTargetName; - if (hateTargetTangibleObject != NULL) + if (hateTargetTangibleObject != nullptr) { hateTargetName = Unicode::wideToNarrow(hateTargetTangibleObject->getEncodedObjectName()).c_str(); } else { - hateTargetName = "NULL"; + hateTargetName = "nullptr"; } result += Unicode::narrowToWide(fs.sprintf("%s:%s(%.1f)\n", hateTargetName.c_str(), hateTarget.getValueString().c_str(), hate)); @@ -271,13 +271,13 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri CachedNetworkId const hateTarget(iter->first); TangibleObject const * const hateTargetTangibleObject = TangibleObject::asTangibleObject(hateTarget.getObject()); std::string hateTargetName; - if (hateTargetTangibleObject != NULL) + if (hateTargetTangibleObject != nullptr) { hateTargetName = Unicode::wideToNarrow(hateTargetTangibleObject->getEncodedObjectName()).c_str(); } else { - hateTargetName = "NULL"; + hateTargetName = "nullptr"; } result += Unicode::narrowToWide(fs.sprintf("%s:%s (%.2f, %lu, %lu)\n", hateTargetName.c_str(), hateTarget.getValueString().c_str(), iter->second.first, iter->second.second.first, iter->second.second.second)); @@ -295,7 +295,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -313,7 +313,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri } TangibleObject const * const to = TangibleObject::asTangibleObject(NetworkIdManager::getObjectById(targetNetworkId)); - if (to == NULL) + if (to == nullptr) { result += Unicode::narrowToWide(fs.sprintf("Target %s not found or not TangibleObject\n", targetNetworkId.getValueString().c_str())); } @@ -342,13 +342,13 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri TangibleObject const * const hateTargetTangibleObject = TangibleObject::asTangibleObject(hateTarget.getObject()); float const hate = iterHateList->second; std::string hateTargetName; - if (hateTargetTangibleObject != NULL) + if (hateTargetTangibleObject != nullptr) { hateTargetName = Unicode::wideToNarrow(hateTargetTangibleObject->getEncodedObjectName()).c_str(); } else { - hateTargetName = "NULL"; + hateTargetName = "nullptr"; } result += Unicode::narrowToWide(fs.sprintf("%s:%s(%.1f)\n", hateTargetName.c_str(), hateTarget.getValueString().c_str(), hate)); @@ -368,13 +368,13 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri CachedNetworkId const hateTarget(iter->first); TangibleObject const * const hateTargetTangibleObject = TangibleObject::asTangibleObject(hateTarget.getObject()); std::string hateTargetName; - if (hateTargetTangibleObject != NULL) + if (hateTargetTangibleObject != nullptr) { hateTargetName = Unicode::wideToNarrow(hateTargetTangibleObject->getEncodedObjectName()).c_str(); } else { - hateTargetName = "NULL"; + hateTargetName = "nullptr"; } result += Unicode::narrowToWide(fs.sprintf("%s:%s (%.2f, %lu, %lu)\n", hateTargetName.c_str(), hateTarget.getValueString().c_str(), iter->second.first, iter->second.second.first, iter->second.second.second)); @@ -390,7 +390,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -398,7 +398,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const aiCreatureObject = getAiCreatureObject(*userCreatureObject, argv); - if (aiCreatureObject == NULL) + if (aiCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -416,7 +416,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -424,7 +424,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const aiCreatureObject = getAiCreatureObject(*userCreatureObject, argv); - if (aiCreatureObject == NULL) + if (aiCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } @@ -442,14 +442,14 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } else { NetworkId aiNetworkId; - CreatureObject * aiCreatureObject = NULL; + CreatureObject * aiCreatureObject = nullptr; if (argv.size() > 2) { @@ -458,7 +458,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri aiNetworkId = NetworkId(Unicode::wideToNarrow(argv[1])); aiCreatureObject = CreatureObject::getCreatureObject(aiNetworkId); - if ( (aiCreatureObject != NULL) + if ( (aiCreatureObject != nullptr) && !aiCreatureObject->isPlayerControlled()) { aiCreatureObject->setBaseWalkSpeed(Unicode::toFloat(argv[2])); @@ -471,14 +471,14 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri aiNetworkId = userCreatureObject->getLookAtTarget(); aiCreatureObject = CreatureObject::getCreatureObject(aiNetworkId); - if ( (aiCreatureObject != NULL) + if ( (aiCreatureObject != nullptr) && !aiCreatureObject->isPlayerControlled()) { aiCreatureObject->setBaseWalkSpeed(Unicode::toFloat(argv[1])); } } - if ( (aiCreatureObject == NULL) + if ( (aiCreatureObject == nullptr) || aiCreatureObject->isPlayerControlled()) { Chat::sendSystemMessage(*userCreatureObject, Unicode::narrowToWide(fs.sprintf("[FAILURE] Unable to resolve %s to an AI", aiNetworkId.getValueString().c_str())), Unicode::emptyString); @@ -495,14 +495,14 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject == NULL) + if (userCreatureObject == nullptr) { result += getErrorMessage(argv[0], ERR_FAIL); } else { NetworkId aiNetworkId; - CreatureObject * aiCreatureObject = NULL; + CreatureObject * aiCreatureObject = nullptr; if (argv.size() > 2) { @@ -511,7 +511,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri aiNetworkId = NetworkId(Unicode::wideToNarrow(argv[1])); aiCreatureObject = CreatureObject::getCreatureObject(aiNetworkId); - if ( (aiCreatureObject != NULL) + if ( (aiCreatureObject != nullptr) && !aiCreatureObject->isPlayerControlled()) { aiCreatureObject->setBaseRunSpeed(Unicode::toFloat(argv[2])); @@ -524,14 +524,14 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri aiNetworkId = userCreatureObject->getLookAtTarget(); aiCreatureObject = CreatureObject::getCreatureObject(aiNetworkId); - if ( (aiCreatureObject != NULL) + if ( (aiCreatureObject != nullptr) && !aiCreatureObject->isPlayerControlled()) { aiCreatureObject->setBaseRunSpeed(Unicode::toFloat(argv[1])); } } - if ( (aiCreatureObject == NULL) + if ( (aiCreatureObject == nullptr) || aiCreatureObject->isPlayerControlled()) { Chat::sendSystemMessage(*userCreatureObject, Unicode::narrowToWide(fs.sprintf("[FAILURE] Unable to resolve %s to an AI", aiNetworkId.getValueString().c_str())), Unicode::emptyString); @@ -549,7 +549,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri { CreatureObject * const userCreatureObject = CreatureObject::getCreatureObject(userId); - if (userCreatureObject != NULL) + if (userCreatureObject != nullptr) { NetworkId sparedAiNetworkId; @@ -573,9 +573,9 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri for (int i = 0; i < serverObjectCount; ++i) { ServerObject * const serverObject = ServerWorld::getObject(i); - CreatureObject * const creatureObject = (serverObject != NULL) ? serverObject->asCreatureObject() : NULL; + CreatureObject * const creatureObject = (serverObject != nullptr) ? serverObject->asCreatureObject() : nullptr; - if ( (creatureObject != NULL) + if ( (creatureObject != nullptr) && !creatureObject->isDead() && !creatureObject->isPlayerControlled() && (creatureObject->getNetworkId() != sparedAiNetworkId)) @@ -597,10 +597,10 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri else if (isAbbrev(argv[0], "debug")) { Object * const object = NetworkIdManager::getObjectById(userId); - ServerObject * const serverObject = (object != NULL) ? object->asServerObject() : NULL; + ServerObject * const serverObject = (object != nullptr) ? object->asServerObject() : nullptr; int temp; - if (serverObject != NULL) + if (serverObject != nullptr) { if ( serverObject->getObjVars().getItem("ai_debug_string", temp) && (temp > 0)) @@ -621,7 +621,7 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri Client * const client = serverObject->getClient(); - if (client != NULL) + if (client != nullptr) { AiDebugString aiDebugString; aiDebugString.enableClearClientFlag(); @@ -650,9 +650,9 @@ bool ConsoleCommandParserAi::performParsing(const NetworkId & userId, const Stri else if (isAbbrev(argv[0], "debugText")) { Object * const object = NetworkIdManager::getObjectById(userId); - ServerObject * const serverObject = (object != NULL) ? object->asServerObject() : NULL; + ServerObject * const serverObject = (object != nullptr) ? object->asServerObject() : nullptr; - if (serverObject != NULL) + if (serverObject != nullptr) { AiDebugString::setTextEnabled(!AiDebugString::isTextEnabled()); diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCity.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCity.cpp index 7b4af2ef..5a89f47e 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCity.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCity.cpp @@ -415,7 +415,7 @@ bool ConsoleCommandParserCity::performParsing (const NetworkId & userId, const S } else { - time_t const rawtime = ::time(NULL); + time_t const rawtime = ::time(nullptr); struct tm * timeinfo = ::localtime(&rawtime); timeinfo->tm_year = atoi(Unicode::wideToNarrow(argv[2]).c_str()) - 1900; timeinfo->tm_mon = atoi(Unicode::wideToNarrow(argv[3]).c_str()) - 1; diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCollection.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCollection.cpp index 442bc622..7397c1e8 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCollection.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCollection.cpp @@ -63,21 +63,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -172,21 +172,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -249,21 +249,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -326,21 +326,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -403,21 +403,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -466,21 +466,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -529,21 +529,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -592,21 +592,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -719,21 +719,21 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -776,7 +776,7 @@ bool ConsoleCommandParserCollection::performParsing (const NetworkId & userId, c else if (isCommand (argv [0], "setServerFirstTime")) { - time_t const rawtime = ::time(NULL); + time_t const rawtime = ::time(nullptr); struct tm * timeinfo = ::localtime(&rawtime); timeinfo->tm_year = atoi(Unicode::wideToNarrow(argv[2]).c_str()) - 1900; timeinfo->tm_mon = atoi(Unicode::wideToNarrow(argv[3]).c_str()) - 1; diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraft.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraft.cpp index 6a28b3eb..51b45c94 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraft.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraft.cpp @@ -151,7 +151,7 @@ bool ConsoleCommandParserCraft::performParsing (const NetworkId & userId, const else if (isAbbrev( argv [0], "enableSchematicFilter")) { - if (creatureObject->getClient() == NULL || !creatureObject->getClient()->isGod()) + if (creatureObject->getClient() == nullptr || !creatureObject->getClient()->isGod()) result += getErrorMessage (argv[0], ERR_FAIL); else { @@ -164,7 +164,7 @@ bool ConsoleCommandParserCraft::performParsing (const NetworkId & userId, const else if (isAbbrev( argv [0], "disableSchematicFilter")) { - if (creatureObject->getClient() == NULL || !creatureObject->getClient()->isGod()) + if (creatureObject->getClient() == nullptr || !creatureObject->getClient()->isGod()) result += getErrorMessage (argv[0], ERR_FAIL); else { diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraftStation.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraftStation.cpp index cc9bebd7..e3a443db 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraftStation.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserCraftStation.cpp @@ -53,19 +53,19 @@ bool ConsoleCommandParserCraftStation::performParsing (const NetworkId & userId, { /* // get the station TangibleObject * station = getStation(argv, result); - if (station == NULL) + if (station == nullptr) return true; // get the ingredient NetworkId ingredientId(Unicode::wideToNarrow (argv[2])); ServerObject * object = ServerWorld::findObjectByNetworkId(ingredientId); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_INGREDIENT); return true; } TangibleObject * ingredient = dynamic_cast(object); - if (ingredient == NULL) + if (ingredient == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_INGREDIENT); return true; @@ -82,19 +82,19 @@ bool ConsoleCommandParserCraftStation::performParsing (const NetworkId & userId, { /* // get the station TangibleObject * station = getStation(argv, result); - if (station == NULL) + if (station == nullptr) return true; // get the ingredient NetworkId ingredientId(Unicode::wideToNarrow (argv[2])); ServerObject * object = ServerWorld::findObjectByNetworkId(ingredientId); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_INGREDIENT); return true; } TangibleObject * ingredient = dynamic_cast(object); - if (ingredient == NULL) + if (ingredient == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_INGREDIENT); return true; @@ -112,13 +112,13 @@ bool ConsoleCommandParserCraftStation::performParsing (const NetworkId & userId, /* // get the station NetworkId id(Unicode::wideToNarrow (argv[1])); ServerObject * object = ServerWorld::findObjectByNetworkId(id); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; } TangibleObject * station = dynamic_cast(object); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -144,33 +144,33 @@ bool ConsoleCommandParserCraftStation::performParsing (const NetworkId & userId, /** * Finds the crafting station for a given id. * - * @return the station or NULL on error + * @return the station or nullptr on error */ TangibleObject * ConsoleCommandParserCraftStation::getStation(const StringVector_t & argv, String_t & result) { NetworkId id(Unicode::wideToNarrow (argv[1])); ServerObject * object = ServerWorld::findObjectByNetworkId(id); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); - return NULL; + return nullptr; } TangibleObject * station = dynamic_cast(object); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); - return NULL; + return nullptr; } // make sure the station is a atation and that it isn't in use if (!station->getObjVars().hasItem("crafting.station")) { result += getErrorMessage (argv [0], ERR_INVALID_STATION); - return NULL; + return nullptr; } if (station->getObjVars().hasItem("crafting.crafter")) { result += getErrorMessage (argv [0], ERR_STATION_IN_USE); - return NULL; + return nullptr; } return station; } // ConsoleCommandParserCraftStation::getStation diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserGuild.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserGuild.cpp index f2ca6349..3484d6c2 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserGuild.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserGuild.cpp @@ -1218,17 +1218,17 @@ bool ConsoleCommandParserGuild::performParsing (const NetworkId & userId, const { // new guild leader is not a guild member, so make a guild member first, then make guild leader ServerObject const* o = dynamic_cast(ServerWorld::findObjectByNetworkId(leaderOid)); - CreatureObject const* c = (o ? o->asCreatureObject() : NULL); - PlayerObject const* p = (c ? PlayerCreatureController::getPlayerObject(c) : NULL); - if (o == NULL) + CreatureObject const* c = (o ? o->asCreatureObject() : nullptr); + PlayerObject const* p = (c ? PlayerCreatureController::getPlayerObject(c) : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); } - else if (p == NULL) + else if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); } diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserManufacture.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserManufacture.cpp index 1b405dd1..d8af83e3 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserManufacture.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserManufacture.cpp @@ -64,7 +64,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); ServerObject * ingredient = safe_cast(ingredientId.getObject()); - if (station == NULL || ingredient == NULL) + if (station == nullptr || ingredient == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -77,7 +77,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } ServerObject * hopper = station->getInputHopper(); - if (hopper == NULL) + if (hopper == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -99,7 +99,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); ServerObject * ingredient = safe_cast(ingredientId.getObject()); - if (station == NULL || ingredient == NULL) + if (station == nullptr || ingredient == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -112,7 +112,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } ServerObject * hopper = station->getInputHopper(); - if (hopper == NULL) + if (hopper == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -124,7 +124,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, return true; } - if (playerObject->getInventory() == NULL) + if (playerObject->getInventory() == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -144,7 +144,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -157,14 +157,14 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } ServerObject * hopper = station->getInputHopper(); - if (hopper == NULL) + if (hopper == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } VolumeContainer * container = ContainerInterface::getVolumeContainer(*hopper); - if (container == NULL) + if (container == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -174,7 +174,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, while (iter != container->end()) { const Container::ContainedItem & itemId = *iter; - if (itemId.getObject() != NULL) + if (itemId.getObject() != nullptr) { const ServerObject * item = safe_cast(itemId.getObject()); result += Unicode::narrowToWide("("); @@ -182,7 +182,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, result += Unicode::narrowToWide(") - "); const ResourceContainerObject * crate = dynamic_cast< const ResourceContainerObject *>(item); - if (crate != NULL) + if (crate != nullptr) { char buffer[32]; _itoa(crate->getQuantity(), buffer, 10); @@ -226,7 +226,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); ManufactureSchematicObject * schematic = dynamic_cast(schematicId.getObject()); - if (station == NULL || schematic == NULL) + if (station == nullptr || schematic == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -239,7 +239,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } // if (station->addSchematic(*schematic, playerObject)) - if (station->addSchematic(*schematic, NULL)) + if (station->addSchematic(*schematic, nullptr)) result += getErrorMessage(argv[0], ERR_SUCCESS); else result += getErrorMessage(argv[0], ERR_INVALID_CONTAINER_TRANSFER); @@ -253,7 +253,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -266,9 +266,9 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } ManufactureSchematicObject * schematic = station->getSchematic(); - if (schematic != NULL) + if (schematic != nullptr) { - if (playerObject->getDatapad() == NULL) + if (playerObject->getDatapad() == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -291,7 +291,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -304,7 +304,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, } ManufactureSchematicObject * schematic = station->getSchematic(); - if (schematic != NULL) + if (schematic != nullptr) { result += Unicode::narrowToWide("("); result += Unicode::narrowToWide(schematic->getNetworkId().getValueString()); @@ -325,7 +325,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); } @@ -344,7 +344,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); } @@ -360,7 +360,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, else if (isAbbrev( argv [0], "getObjects")) { ServerObject * myInventory = playerObject->getInventory(); - if (myInventory == NULL) + if (myInventory == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -370,21 +370,21 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } ServerObject * hopper = station->getOutputHopper(); - if (hopper == NULL) + if (hopper == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } VolumeContainer * container = ContainerInterface::getVolumeContainer(*hopper); - if (container == NULL) + if (container == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -394,7 +394,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, while (iter != container->end()) { const Container::ContainedItem & itemId = *iter; - if (itemId.getObject() != NULL) + if (itemId.getObject() != nullptr) { ContainerInterface::transferItemToVolumeContainer (*myInventory, *safe_cast(itemId.getObject()), playerObject, tmp); } @@ -419,21 +419,21 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, ManufactureInstallationObject * station = dynamic_cast(stationId.getObject()); - if (station == NULL) + if (station == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } ServerObject * hopper = station->getOutputHopper(); - if (hopper == NULL) + if (hopper == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } VolumeContainer * container = ContainerInterface::getVolumeContainer(*hopper); - if (container == NULL) + if (container == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -443,7 +443,7 @@ bool ConsoleCommandParserManufacture::performParsing (const NetworkId & userId, while (iter != container->end()) { const Container::ContainedItem & itemId = *iter; - if (itemId.getObject() != NULL) + if (itemId.getObject() != nullptr) { const ServerObject * item = safe_cast(itemId.getObject()); result += Unicode::narrowToWide("("); diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserMoney.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserMoney.cpp index 33801387..feff5d1e 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserMoney.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserMoney.cpp @@ -58,7 +58,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const { NetworkId sourceId(Unicode::wideToNarrow (argv[1])); NetworkId targetId(Unicode::wideToNarrow (argv[2])); - int amount(strtoul(Unicode::wideToNarrow (argv[3]).c_str (), NULL, 10)); + int amount(strtoul(Unicode::wideToNarrow (argv[3]).c_str (), nullptr, 10)); ServerObject* source = dynamic_cast(NetworkIdManager::getObjectById(sourceId)); if (!source) @@ -75,7 +75,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const { NetworkId sourceId(Unicode::wideToNarrow (argv[1])); NetworkId targetId(Unicode::wideToNarrow (argv[2])); - int amount(strtoul(Unicode::wideToNarrow (argv[3]).c_str (), NULL, 10)); + int amount(strtoul(Unicode::wideToNarrow (argv[3]).c_str (), nullptr, 10)); ServerObject* source = dynamic_cast(NetworkIdManager::getObjectById(sourceId)); if (!source) @@ -91,7 +91,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const else if (isAbbrev( argv [0], "namedTransfer")) { NetworkId sourceId(Unicode::wideToNarrow (argv[1])); - int amount(strtol(Unicode::wideToNarrow (argv[3]).c_str (), NULL, 10)); + int amount(strtol(Unicode::wideToNarrow (argv[3]).c_str (), nullptr, 10)); ServerObject* source = dynamic_cast(NetworkIdManager::getObjectById(sourceId)); if (!source) @@ -117,7 +117,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const else if (isAbbrev( argv [0], "withdraw")) { NetworkId sourceId(Unicode::wideToNarrow (argv[1])); - int amount(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), NULL, 10)); + int amount(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), nullptr, 10)); ServerObject* source = dynamic_cast(NetworkIdManager::getObjectById(sourceId)); if (!source) @@ -133,7 +133,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const else if (isAbbrev( argv [0], "deposit")) { NetworkId sourceId(Unicode::wideToNarrow (argv[1])); - int amount(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), NULL, 10)); + int amount(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), nullptr, 10)); ServerObject* source = dynamic_cast(NetworkIdManager::getObjectById(sourceId)); if (!source) @@ -175,7 +175,7 @@ bool ConsoleCommandParserMoney::performParsing (const NetworkId & userId, const } else if (isAbbrev( argv [0], "setGalacticReserve")) { - int const newGalacticReserve(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), NULL, 10)); + int const newGalacticReserve(strtoul(Unicode::wideToNarrow (argv[2]).c_str (), nullptr, 10)); if ((newGalacticReserve < 0) || (newGalacticReserve > ConfigServerGame::getMaxGalacticReserveDepositBillion())) { result += Unicode::narrowToWide(FormattedString<1024>().sprintf("specified galactic reserve balance (%d) must be in the (inclusive) range (0, %d)\n", newGalacticReserve, ConfigServerGame::getMaxGalacticReserveDepositBillion())); diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserNpc.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserNpc.cpp index 929f6413..71f81106 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserNpc.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserNpc.cpp @@ -52,19 +52,19 @@ bool ConsoleCommandParserNpc::performParsing (const NetworkId & userId, const St NetworkId const oid(Unicode::wideToNarrow(argv[1])); ServerObject * const object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject * const npc = object->asTangibleObject(); - if (npc == NULL) + if (npc == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - playerObject->startNpcConversation(*npc, NULL, NpcConversationData::CS_Player, 0); + playerObject->startNpcConversation(*npc, nullptr, NpcConversationData::CS_Player, 0); result += getErrorMessage (argv[0], ERR_SUCCESS); } @@ -82,7 +82,7 @@ bool ConsoleCommandParserNpc::performParsing (const NetworkId & userId, const St else if (isAbbrev( argv [0], "respond")) { TangibleObject * const playerObject = safe_cast(ServerWorld::findObjectByNetworkId(userId)); - int const response = strtol(Unicode::wideToNarrow(argv[1]).c_str (), NULL, 10); + int const response = strtol(Unicode::wideToNarrow(argv[1]).c_str (), nullptr, 10); playerObject->respondToNpc(response); result += getErrorMessage (argv[0], ERR_SUCCESS); } diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObject.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObject.cpp index ed626f69..eafa6994 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObject.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObject.cpp @@ -119,23 +119,23 @@ namespace ConsoleCommandParserObjectNamespace { WARNING(true, ("ConsoleCommandParserObject invalid object template [%s]", templateName.c_str())); ot->releaseReference(); - return NULL; + return nullptr; } if (sot->getId() == ServerShipObjectTemplate::ServerShipObjectTemplate_tag) { SharedObjectTemplate const * const sharedTemplate = safe_cast(ObjectTemplateList::fetch(sot->getSharedTemplate())); - if (NULL == sharedTemplate || + if (nullptr == sharedTemplate || (sharedTemplate->getGameObjectType() != SharedObjectTemplate::GOT_ship_mining_asteroid_dynamic && sharedTemplate->getGameObjectType() != SharedObjectTemplate::GOT_ship_mining_asteroid_static)) { ot->releaseReference(); - return NULL; + return nullptr; } } return sot; } - return NULL; + return nullptr; } void checkBadBuildClusterObject(ServerObject *& o) @@ -523,7 +523,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject const * const obj = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (obj == NULL) + if (obj == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -531,7 +531,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const Client const * const client = obj->getClient(); - if(client == NULL) + if(client == nullptr) { result += Unicode::narrowToWide("specified object is not a client object\n"); return true; @@ -561,7 +561,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const } const char *objectTemplateName = obj->getObjectTemplateName(); - result += Unicode::narrowToWide(FormattedString<512>().sprintf("object %s (%s) has %d total opened objects\n", obj->getNetworkId().getValueString().c_str(), (objectTemplateName ? objectTemplateName : "NULL object template"), opened.size())); + result += Unicode::narrowToWide(FormattedString<512>().sprintf("object %s (%s) has %d total opened objects\n", obj->getNetworkId().getValueString().c_str(), (objectTemplateName ? objectTemplateName : "nullptr object template"), opened.size())); if(!text.empty()) { @@ -615,7 +615,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const ServerObject * const object = dynamic_cast(NetworkIdManager::getObjectById(oid)); if (object) { - uint32 const pid = (strtoul(Unicode::wideToNarrow(argv[2]).c_str (), NULL, 10)); + uint32 const pid = (strtoul(Unicode::wideToNarrow(argv[2]).c_str (), nullptr, 10)); GenericValueTypeMessage > const msg( "RequestAuthTransfer", std::make_pair( @@ -646,9 +646,9 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const } real x,y,z; - x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); - y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); + x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); + y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); ServerObject *newObject = 0; ServerObjectTemplate const * const ot = getObjectTemplateForCreation(tmpString); @@ -656,7 +656,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -706,9 +706,9 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const } real x,y,z; - x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); - y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); + x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); + y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); // check to see if we're in a region we shouldn't be building in if ( ConfigServerGame::getBlockBuildRegionPlacement() ) @@ -726,10 +726,10 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const } real quatW,quatX,quatY,quatZ; - quatW = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), NULL)); - quatX = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), NULL)); - quatY = static_cast(strtod(Unicode::wideToNarrow(argv[7]).c_str(), NULL)); - quatZ = static_cast(strtod(Unicode::wideToNarrow(argv[8]).c_str(), NULL)); + quatW = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), nullptr)); + quatX = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), nullptr)); + quatY = static_cast(strtod(Unicode::wideToNarrow(argv[7]).c_str(), nullptr)); + quatZ = static_cast(strtod(Unicode::wideToNarrow(argv[8]).c_str(), nullptr)); ServerObject * const cell = safe_cast(ContainerInterface::getContainingCellObject(*playerObject)); @@ -739,7 +739,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -809,7 +809,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -886,7 +886,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -934,7 +934,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[2])); ServerObject* object = dynamic_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) { //container does not exist result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); @@ -953,7 +953,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -994,7 +994,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId cellId(Unicode::wideToNarrow(argv[2])); ServerObject* cell = dynamic_cast(NetworkIdManager::getObjectById(cellId)); - if (cell == NULL && cellId != NetworkId::cms_invalid) + if (cell == nullptr && cellId != NetworkId::cms_invalid) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1011,9 +1011,9 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const } real x,y,z; - x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); - z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), NULL)); + x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); + z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), nullptr)); ServerObject *newObject = 0; ServerObjectTemplate const * const ot = getObjectTemplateForCreation(tmpString); @@ -1021,7 +1021,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -1070,22 +1070,22 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const NetworkId cellId(Unicode::wideToNarrow(argv[2])); ServerObject * const cell = safe_cast(NetworkIdManager::getObjectById(cellId)); - if (cell == NULL && cellId != NetworkId::cms_invalid) + if (cell == nullptr && cellId != NetworkId::cms_invalid) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } real x,y,z; - x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); - z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), NULL)); + x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); + z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), nullptr)); real quatW,quatX,quatY,quatZ; - quatW = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), NULL)); - quatX = static_cast(strtod(Unicode::wideToNarrow(argv[7]).c_str(), NULL)); - quatY = static_cast(strtod(Unicode::wideToNarrow(argv[8]).c_str(), NULL)); - quatZ = static_cast(strtod(Unicode::wideToNarrow(argv[9]).c_str(), NULL)); + quatW = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), nullptr)); + quatX = static_cast(strtod(Unicode::wideToNarrow(argv[7]).c_str(), nullptr)); + quatY = static_cast(strtod(Unicode::wideToNarrow(argv[8]).c_str(), nullptr)); + quatZ = static_cast(strtod(Unicode::wideToNarrow(argv[9]).c_str(), nullptr)); ServerObject *newObject = 0; ServerObjectTemplate const * const ot = getObjectTemplateForCreation(tmpString); @@ -1093,7 +1093,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { if (ConfigServerGame::getStripNonFreeAssetsFromPlayersInTutorial() && NewbieTutorial::isInTutorialArea(userObject)) { - std::string sharedTemplate = ot->getSharedTemplate(false); + std::string sharedTemplate = ot->getSharedTemplate(); if (!FileManifest::contains(sharedTemplate.c_str())) { @@ -1165,7 +1165,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* object = dynamic_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1200,7 +1200,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* object = dynamic_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1236,7 +1236,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const const NetworkId oid (Unicode::wideToNarrow(argv[1])); ServerObject* const object = safe_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else if (object->getClient()) result += getErrorMessage(argv[0], ERR_INVALID_USER); @@ -1268,7 +1268,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const ServerObject* const object = safe_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); // ---------- @@ -1279,11 +1279,11 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { ServerObject * object = ServerWorld::getObject(i); - if(object == NULL) continue; + if(object == nullptr) continue; CreatureObject * creature = object->asCreatureObject(); - if(creature == NULL) continue; + if(creature == nullptr) continue; if(creature->getNetworkId() == oid) continue; @@ -1307,11 +1307,11 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { ServerObject * object = ServerWorld::getObject(i); - if(object == NULL) continue; + if(object == nullptr) continue; CreatureObject * creature = object->asCreatureObject(); - if(creature == NULL) continue; + if(creature == nullptr) continue; if(creature->getParentCell() != CellProperty::getWorldCellProperty()) continue; @@ -1331,9 +1331,9 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); Vector pos; - pos.x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); - pos.y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - pos.z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); + pos.x = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); + pos.y = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + pos.z = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); // disallow certain object types from being "move" bool allowMove = true; @@ -1418,7 +1418,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1433,9 +1433,9 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); real r,p,y; - r = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); - p = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); + r = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); + p = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); if (rotateObject(oid, r, p, y)) { result += getErrorMessage(argv[0], ERR_SUCCESS); @@ -1450,7 +1450,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1479,7 +1479,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const // erase keys assigned to this player. s_playerCreatureNameMap.erase(userId); - if (dataTable != NULL) + if (dataTable != nullptr) { StringVector creatureStrings; { @@ -1548,7 +1548,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId const oid(Unicode::wideToNarrow(argv[1])); ServerObject* const o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1580,7 +1580,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - o->deletePobPersistedContents(NULL, DeleteReasons::God); + o->deletePobPersistedContents(nullptr, DeleteReasons::God); result += getErrorMessage(argv[0], ERR_SUCCESS); } else if (isCommand( argv[0], "moveItemInHouseToMe")) @@ -1607,7 +1607,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); TangibleObject* vendor = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (vendor == NULL) + if (vendor == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1621,7 +1621,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); TangibleObject* vendor = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (vendor == NULL) + if (vendor == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1699,13 +1699,13 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); CreatureObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } real scale; - scale = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); + scale = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); o->setMovementScale(scale); result += getErrorMessage(argv[0], ERR_SUCCESS); } @@ -1716,13 +1716,13 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); CreatureObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } real scale; - scale = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), NULL)); + scale = static_cast(strtod(Unicode::wideToNarrow(argv[2]).c_str(), nullptr)); o->setScaleFactor(scale); result += getErrorMessage(argv[0], ERR_SUCCESS); } @@ -1765,7 +1765,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1788,13 +1788,13 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { CachedNetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(oid.getObject()); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } Container const * const container = ContainerInterface::getContainer(*o); - if (container == NULL) + if (container == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1811,7 +1811,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1846,7 +1846,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1881,7 +1881,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = ServerWorld::findObjectByNetworkId(oid); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1914,7 +1914,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); TangibleObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1940,7 +1940,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); const ServerObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -1976,7 +1976,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const ServerMessageForwarding::end(); - if (ObjectTemplateList::reload(templateFile) == NULL) + if (ObjectTemplateList::reload(templateFile) == nullptr) { result += getErrorMessage(argv[0], ERR_TEMPLATE_NOT_LOADED); return true; @@ -1991,7 +1991,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); CreatureObject * creature = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (creature == NULL || !creature->isIncapacitated()) + if (creature == nullptr || !creature->isIncapacitated()) result += Unicode::narrowToWide("no"); else if (creature->isDead()) result += Unicode::narrowToWide("dead"); @@ -2011,11 +2011,11 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const LocationData d; d.name = argv[2]; Vector pos; - pos.x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), NULL)); - pos.y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), NULL)); - pos.z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), NULL)); + pos.x = static_cast(strtod(Unicode::wideToNarrow(argv[3]).c_str(), nullptr)); + pos.y = static_cast(strtod(Unicode::wideToNarrow(argv[4]).c_str(), nullptr)); + pos.z = static_cast(strtod(Unicode::wideToNarrow(argv[5]).c_str(), nullptr)); d.location.setCenter(pos); - float radius = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), NULL)); + float radius = static_cast(strtod(Unicode::wideToNarrow(argv[6]).c_str(), nullptr)); d.location.setRadius(radius); o->addLocationTarget(d); } @@ -2079,7 +2079,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const oid.getObject()); const CreatureObject * creature = dynamic_cast( tangible); - if (creature != NULL) + if (creature != nullptr) { char buffer[1024]; sprintf(buffer, "he:%d, co=%d, ac=%d, st=%d, mi=%d, wi=%d", @@ -2091,7 +2091,7 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const creature->getAttribute(Attributes::Willpower)); result += Unicode::narrowToWide(buffer); } - else if (tangible != NULL) + else if (tangible != nullptr) { char buffer[1024]; sprintf(buffer, "max hp = %d, damage taken = %d", @@ -2156,13 +2156,13 @@ bool ConsoleCommandParserObject::performParsing (const NetworkId & userId, const bool value = strtoul(Unicode::wideToNarrow(argv[2]).c_str(), 0, 10) != 0; ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(actorId)); - CreatureObject * const c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * const c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -2261,7 +2261,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const const char *objectTemplateName = obj->getObjectTemplateName(); - result += Unicode::narrowToWide(FormattedString<512>().sprintf("object %s (%s) has %d total observers (%d observers on this game server)\n", obj->getNetworkId().getValueString().c_str(), (objectTemplateName ? objectTemplateName : "NULL object template"), obj->getObserversCount(), observerList.size())); + result += Unicode::narrowToWide(FormattedString<512>().sprintf("object %s (%s) has %d total observers (%d observers on this game server)\n", obj->getNetworkId().getValueString().c_str(), (objectTemplateName ? objectTemplateName : "nullptr object template"), obj->getObserversCount(), observerList.size())); if (!observers.empty()) { @@ -2560,7 +2560,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const else if(isCommand(argv[0], "setPathLinkDistance")) { - float dist = static_cast(strtod(Unicode::wideToNarrow(argv[1]).c_str(), NULL)); + float dist = static_cast(strtod(Unicode::wideToNarrow(argv[1]).c_str(), nullptr)); CityPathGraphManager::setLinkDistance(dist); @@ -2601,7 +2601,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { CachedNetworkId const oid(Unicode::wideToNarrow(argv[1])); TangibleObject * object = dynamic_cast(oid.getObject()); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else { @@ -2619,7 +2619,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { CachedNetworkId const oid(Unicode::wideToNarrow(argv[1])); TangibleObject * object = dynamic_cast(oid.getObject()); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else { @@ -2653,7 +2653,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const ServerObject * object = dynamic_cast(oid.getObject()); CreatureObject * creature = dynamic_cast(object); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else { @@ -2694,7 +2694,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[1])); CreatureObject *creature = dynamic_cast(NetworkIdManager::getObjectById(oid)); - PlayerObject *player = NULL; + PlayerObject *player = nullptr; if (creature) player = PlayerCreatureController::getPlayerObject(creature); if (player) @@ -2739,7 +2739,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[1])); CreatureObject *creature = dynamic_cast(NetworkIdManager::getObjectById(oid)); - PlayerObject *player = NULL; + PlayerObject *player = nullptr; if (creature) player = PlayerCreatureController::getPlayerObject(creature); if (player) @@ -2864,7 +2864,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); const InstallationObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -2888,7 +2888,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[1])); InstallationObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -2904,7 +2904,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); const InstallationObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -2928,7 +2928,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[1])); InstallationObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -3056,7 +3056,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject *o = safe_cast(NetworkIdManager::getObjectById(oid)); - if (o != NULL && o->asCreatureObject() != NULL && o->isPlayerControlled()) + if (o != nullptr && o->asCreatureObject() != nullptr && o->isPlayerControlled()) { CreatureObject * creatureTarget = o->asCreatureObject(); @@ -3068,7 +3068,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const for (CreatureObject::SkillList::const_iterator i = skills.begin(); i != skills.end(); ++i) { const SkillObject * profession = (*i)->findProfessionForSkill(); - if (profession != NULL) + if (profession != nullptr) professionName = profession->getSkillName(); } } @@ -3317,7 +3317,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId oid (Unicode::wideToNarrow(argv[1])); ServerObject* const object = safe_cast(NetworkIdManager::getObjectById(oid)); - if (object == NULL) + if (object == nullptr) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else if (!object->getClient()) result += getErrorMessage(argv[0], ERR_INVALID_USER); @@ -3346,7 +3346,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId ownerId (Unicode::wideToNarrow(argv[2])); ServerObject * const object = safe_cast(NetworkIdManager::getObjectById(houseId)); - TangibleObject * const tangible = object ? object->asTangibleObject() : NULL; + TangibleObject * const tangible = object ? object->asTangibleObject() : nullptr; if (!tangible) result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); else @@ -3359,7 +3359,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { ServerObject * object = safe_cast(NetworkIdManager::getObjectById(playerObject->getLookAtTarget())); - if (NULL == object) + if (nullptr == object) object = playerObject; RegionMaster::RegionVector rv; @@ -3373,7 +3373,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const for (RegionMaster::RegionVector::const_iterator it = rv.begin(); it != rv.end(); ++it) { Region const * const r = *it; - if (NULL != r) + if (nullptr != r) { _itoa(r->getGeography(), buf, 10); result += Unicode::narrowToWide(buf); @@ -3390,7 +3390,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { ServerObject * const target = safe_cast(NetworkIdManager::getObjectById(playerObject->getLookAtTarget())); - if (NULL == target) + if (nullptr == target) { result += Unicode::narrowToWide("Invalid target"); return true; @@ -3434,7 +3434,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const ServerObject * object = safe_cast(NetworkIdManager::getObjectById(playerObject->getLookAtTarget())); - if (NULL == object) + if (nullptr == object) object = playerObject; Vector const & pos_w = object->getPosition_w(); @@ -3449,7 +3449,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { ServerObject * object = safe_cast(NetworkIdManager::getObjectById(playerObject->getLookAtTarget())); - if (NULL == object) + if (nullptr == object) object = playerObject; Vector const & pos_w = object->getPosition_w(); @@ -3463,7 +3463,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { ServerObject * object = safe_cast(NetworkIdManager::getObjectById(playerObject->getLookAtTarget())); - if (NULL == object) + if (nullptr == object) object = playerObject; Vector const & pos_w = object->getPosition_w(); @@ -3477,7 +3477,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); const ServerObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -3503,7 +3503,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); const ServerObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -3576,13 +3576,13 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject const* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject const* c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject const* c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -3590,7 +3590,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const else { PlayerObject const* p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -3612,8 +3612,8 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject* c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject* c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -3623,7 +3623,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const result += Unicode::narrowToWide("specified object is not authoritative on this game server\n"); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -3631,7 +3631,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const else { PlayerObject* p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -3668,20 +3668,20 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -3755,14 +3755,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject const* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject const* t = o->asTangibleObject(); - if (t == NULL) + if (t == nullptr) { result += Unicode::narrowToWide("specified object is not a tangible object\n"); return true; @@ -3797,14 +3797,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId sourceOid(Unicode::wideToNarrow(argv[1])); ServerObject * sourceSo = dynamic_cast(ServerWorld::findObjectByNetworkId(sourceOid)); - if (sourceSo == NULL) + if (sourceSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", sourceOid.getValueString().c_str())); return true; } TangibleObject * sourceTo = sourceSo->asTangibleObject(); - if (sourceTo == NULL) + if (sourceTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a tangible object\n", sourceOid.getValueString().c_str())); return true; @@ -3812,14 +3812,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const NetworkId targetOid(Unicode::wideToNarrow(argv[2])); ServerObject * targetSo = dynamic_cast(ServerWorld::findObjectByNetworkId(targetOid)); - if (targetSo == NULL) + if (targetSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", targetOid.getValueString().c_str())); return true; } TangibleObject * targetTo = targetSo->asTangibleObject(); - if (targetTo == NULL) + if (targetTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a tangible object\n", targetOid.getValueString().c_str())); return true; @@ -3839,14 +3839,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId sourceOid(Unicode::wideToNarrow(argv[1])); ServerObject * sourceSo = dynamic_cast(ServerWorld::findObjectByNetworkId(sourceOid)); - if (sourceSo == NULL) + if (sourceSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", sourceOid.getValueString().c_str())); return true; } TangibleObject * sourceTo = sourceSo->asTangibleObject(); - if (sourceTo == NULL) + if (sourceTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a tangible object\n", sourceOid.getValueString().c_str())); return true; @@ -3866,14 +3866,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId sourceOid(Unicode::wideToNarrow(argv[1])); ServerObject * sourceSo = dynamic_cast(ServerWorld::findObjectByNetworkId(sourceOid)); - if (sourceSo == NULL) + if (sourceSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", sourceOid.getValueString().c_str())); return true; } TangibleObject * sourceTo = sourceSo->asTangibleObject(); - if (sourceTo == NULL) + if (sourceTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a tangible object\n", sourceOid.getValueString().c_str())); return true; @@ -3891,14 +3891,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId sourceOid(Unicode::wideToNarrow(argv[1])); ServerObject const * sourceSo = dynamic_cast(ServerWorld::findObjectByNetworkId(sourceOid)); - if (sourceSo == NULL) + if (sourceSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", sourceOid.getValueString().c_str())); return true; } CreatureObject const * sourceCo = sourceSo->asCreatureObject(); - if (sourceCo == NULL) + if (sourceCo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a creature object\n", sourceOid.getValueString().c_str())); return true; @@ -3915,14 +3915,14 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId sourceOid(Unicode::wideToNarrow(argv[1])); ServerObject * sourceSo = dynamic_cast(ServerWorld::findObjectByNetworkId(sourceOid)); - if (sourceSo == NULL) + if (sourceSo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is an invalid object\n", sourceOid.getValueString().c_str())); return true; } CreatureObject * sourceCo = sourceSo->asCreatureObject(); - if (sourceCo == NULL) + if (sourceCo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("%s is not a creature object\n", sourceOid.getValueString().c_str())); return true; @@ -3931,7 +3931,7 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const result += Unicode::narrowToWide(FormattedString<512>().sprintf("dumping %s's command queue contents\n", sourceCo->getNetworkId().getValueString().c_str())); CommandQueue * queue = sourceCo->getCommandQueue(); - if (queue != NULL) + if (queue != nullptr) { std::string output; queue->spew(&output); @@ -3947,26 +3947,26 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } - time_t const timeNow = ::time(NULL); + time_t const timeNow = ::time(nullptr); time_t const timeStartInterval = ((p->getChatSpamTimeEndInterval() > 0) ? static_cast(p->getChatSpamTimeEndInterval() - (ConfigServerGame::getChatSpamLimiterIntervalMinutes() * 60)) : 0); if ((timeStartInterval <= 0) || (timeNow < timeStartInterval)) @@ -3986,28 +3986,28 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject const * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject const * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } Client * client = o->getClient(); - if (client == NULL) + if (client == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("specified character object %s (%s) doesn't have a Client object (possible causes are may not be authoritative, or may not be connected)\n", o->getNetworkId().getValueString().c_str(), Unicode::wideToNarrow(o->getAssignedObjectName()).c_str())); return true; @@ -4042,28 +4042,28 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject const * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } Client * client = o->getClient(); - if (client == NULL) + if (client == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("specified character object %s (%s) doesn't have a Client object (possible causes are may not be authoritative, or may not be connected)\n", o->getNetworkId().getValueString().c_str(), Unicode::wideToNarrow(o->getAssignedObjectName()).c_str())); return true; @@ -4083,28 +4083,28 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject const * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } Client * client = o->getClient(); - if (client == NULL) + if (client == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("specified character object %s (%s) doesn't have a Client object (possible causes are may not be authoritative, or may not be connected)\n", o->getNetworkId().getValueString().c_str(), Unicode::wideToNarrow(o->getAssignedObjectName()).c_str())); return true; @@ -4180,12 +4180,12 @@ bool ConsoleCommandParserObject::performParsing2(const NetworkId & userId, const } else { - result += Unicode::narrowToWide(FormattedString<1024>().sprintf("object (%s) getFootprint() returns NULL.\n", oid.getValueString().c_str())); + result += Unicode::narrowToWide(FormattedString<1024>().sprintf("object (%s) getFootprint() returns nullptr.\n", oid.getValueString().c_str())); } } else { - result += Unicode::narrowToWide(FormattedString<1024>().sprintf("object (%s) getCollisionProperty() returns NULL.\n", oid.getValueString().c_str())); + result += Unicode::narrowToWide(FormattedString<1024>().sprintf("object (%s) getCollisionProperty() returns nullptr.\n", oid.getValueString().c_str())); } } else diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObjvar.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObjvar.cpp index e4a928c5..77063e84 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObjvar.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserObjvar.cpp @@ -100,7 +100,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { NetworkId oid (Unicode::wideToNarrow (argv[1])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -224,7 +224,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const // This is now a no-op, but left in to avoid breaking the god client // NetworkId oid (Unicode::wideToNarrow (argv[1])); // ServerObject* object = ServerWorld::findObjectByNetworkId(oid); -// if (object == NULL) +// if (object == nullptr) // { // result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); // return true; @@ -241,7 +241,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { NetworkId oid (Unicode::wideToNarrow(argv[1])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -317,7 +317,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { ServerObject * const userServerObject = ServerWorld::findObjectByNetworkId(userId); - if (userServerObject != NULL) + if (userServerObject != nullptr) { NetworkId specifiedNetworkId; @@ -329,7 +329,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { CreatureObject * const userCreatureObject = CreatureObject::asCreatureObject(userServerObject); - if (userCreatureObject != NULL) + if (userCreatureObject != nullptr) { specifiedNetworkId = userCreatureObject->getLookAtTarget(); } @@ -337,7 +337,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const ServerObject * const specifiedServerObject = ServerWorld::findObjectByNetworkId(specifiedNetworkId); - if (specifiedServerObject != NULL) + if (specifiedServerObject != nullptr) { DynamicVariableList const & objVarList = specifiedServerObject->getObjVars(); FormattedString<1024> fs; @@ -357,7 +357,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { NetworkId oid = NetworkId(Unicode::wideToNarrow(argv[1])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -376,7 +376,7 @@ bool ConsoleCommandParserObjvar::performParsing (const NetworkId & userId, const { NetworkId oid = NetworkId(Unicode::wideToNarrow(argv[1])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserPvp.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserPvp.cpp index d212d0ca..a9f691b6 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserPvp.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserPvp.cpp @@ -103,13 +103,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject const* o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject const* c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject const* c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -117,7 +117,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject const* p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -185,7 +185,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St result += Unicode::narrowToWide(FormattedString<512>().sprintf("lifetime PvP kills: %ld\n",p->getLifetimePvpKills())); result += Unicode::narrowToWide(FormattedString<512>().sprintf("next GCW rating calculation time: %ld",p->getNextGcwRatingCalcTime())); - int32 const now = static_cast(::time(NULL)); + int32 const now = static_cast(::time(nullptr)); if (p->getNextGcwRatingCalcTime() > 0) { if (p->getNextGcwRatingCalcTime() >= now) @@ -223,13 +223,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -237,7 +237,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -259,13 +259,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -273,7 +273,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -295,13 +295,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -309,7 +309,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -331,13 +331,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -345,7 +345,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -369,13 +369,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -383,7 +383,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -405,13 +405,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -419,7 +419,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -441,13 +441,13 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - CreatureObject * c = (o ? o->asCreatureObject() : NULL); - if (o == NULL) + CreatureObject * c = (o ? o->asCreatureObject() : nullptr); + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } - else if (c == NULL) + else if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -455,7 +455,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St else { PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -477,21 +477,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -585,7 +585,7 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -612,21 +612,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -660,21 +660,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -708,21 +708,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -756,21 +756,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -804,21 +804,21 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId oid(Unicode::wideToNarrow(argv[1])); ServerObject * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; @@ -852,14 +852,14 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId const oid(Unicode::wideToNarrow(argv[1])); ServerObject const * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; @@ -874,14 +874,14 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId const actorOid(Unicode::wideToNarrow(argv[1])); ServerObject const * const actorSo = dynamic_cast(ServerWorld::findObjectByNetworkId(actorOid)); - if (actorSo == NULL) + if (actorSo == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject const * const actorTo = actorSo->asTangibleObject(); - if (actorTo == NULL) + if (actorTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("(%s) is not a TangibleObject\n", actorOid.getValueString().c_str())); return true; @@ -889,14 +889,14 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St NetworkId const targetOid(Unicode::wideToNarrow(argv[2])); ServerObject const * const targetSo = dynamic_cast(ServerWorld::findObjectByNetworkId(targetOid)); - if (targetSo == NULL) + if (targetSo == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject const * const targetTo = targetSo->asTangibleObject(); - if (targetTo == NULL) + if (targetTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("(%s) is not a TangibleObject\n", targetOid.getValueString().c_str())); return true; @@ -924,14 +924,14 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St { NetworkId const actorOid(Unicode::wideToNarrow(argv[1])); ServerObject * const actorSo = dynamic_cast(ServerWorld::findObjectByNetworkId(actorOid)); - if (actorSo == NULL) + if (actorSo == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject * const actorTo = actorSo->asTangibleObject(); - if (actorTo == NULL) + if (actorTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("(%s) is not a TangibleObject\n", actorOid.getValueString().c_str())); return true; @@ -939,14 +939,14 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St NetworkId const targetOid(Unicode::wideToNarrow(argv[2])); ServerObject * const targetSo = dynamic_cast(ServerWorld::findObjectByNetworkId(targetOid)); - if (targetSo == NULL) + if (targetSo == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } TangibleObject * const targetTo = targetSo->asTangibleObject(); - if (targetTo == NULL) + if (targetTo == nullptr) { result += Unicode::narrowToWide(FormattedString<512>().sprintf("(%s) is not a TangibleObject\n", targetOid.getValueString().c_str())); return true; @@ -968,28 +968,28 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St NetworkId const oid(Unicode::wideToNarrow(argv[1])); ServerObject const * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject const * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } ShipObject const * const ship = ShipObject::getContainingShipObject(c); - if (ship == NULL) + if (ship == nullptr) { result += Unicode::narrowToWide("specified character object is not in a ship\n"); return true; @@ -1042,28 +1042,28 @@ bool ConsoleCommandParserPvp::performParsing (const NetworkId & userId, const St NetworkId const oid(Unicode::wideToNarrow(argv[1])); ServerObject const * const o = dynamic_cast(ServerWorld::findObjectByNetworkId(oid)); - if (o == NULL) + if (o == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; } CreatureObject const * const c = o->asCreatureObject(); - if (c == NULL) + if (c == nullptr) { result += Unicode::narrowToWide("specified object is not a creature object\n"); return true; } PlayerObject const * const p = PlayerCreatureController::getPlayerObject(c); - if (p == NULL) + if (p == nullptr) { result += Unicode::narrowToWide("specified object is not a character object\n"); return true; } ShipObject const * const ship = ShipObject::getContainingShipObject(c); - if (ship == NULL) + if (ship == nullptr) { result += Unicode::narrowToWide("specified character object is not in a ship\n"); return true; diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserResource.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserResource.cpp index 2d22864d..cde60a8e 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserResource.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserResource.cpp @@ -73,7 +73,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con CachedNetworkId harvester(Unicode::wideToNarrow (argv[1])); ServerObject* harvesterObject = safe_cast(harvester.getObject()); - if (harvesterObject == NULL) + if (harvesterObject == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -90,7 +90,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con CachedNetworkId harvester(Unicode::wideToNarrow (argv[1])); ServerObject* harvesterObject = safe_cast(harvester.getObject()); - if (harvesterObject == NULL) + if (harvesterObject == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -123,7 +123,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con CachedNetworkId harvester(Unicode::wideToNarrow (argv[1])); ServerObject* harvesterObject = safe_cast(harvester.getObject()); - if (harvesterObject == NULL) + if (harvesterObject == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -208,7 +208,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con ResourceContainerObject * const container = dynamic_cast(NetworkIdManager::getObjectById(contId)); std::string const & resourcePath = Unicode::wideToNarrow(argv[2]); ResourceTypeObject * const resType = ServerUniverse::getInstance().getResourceTypeByName(resourcePath); - int const amount = strtol(Unicode::wideToNarrow (argv[3]).c_str (), NULL, 10); + int const amount = strtol(Unicode::wideToNarrow (argv[3]).c_str (), nullptr, 10); NetworkId const source(Unicode::wideToNarrow (argv[4])); if (container && resType) @@ -228,7 +228,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con { NetworkId contId (Unicode::wideToNarrow (argv[1])); ResourceContainerObject* container=dynamic_cast(NetworkIdManager::getObjectById(contId)); - if (container != NULL) + if (container != nullptr) { NetworkId sourceId; if (argv.size() >= 3) @@ -251,7 +251,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con { NetworkId contId (Unicode::wideToNarrow (argv[1])); ResourceContainerObject* container=dynamic_cast(NetworkIdManager::getObjectById(contId)); - if (container != NULL) + if (container != nullptr) { if (container->debugRecycle()) result += getErrorMessage(argv[0], ERR_SUCCESS); @@ -267,7 +267,7 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con CachedNetworkId contId (Unicode::wideToNarrow (argv[1])); ResourceContainerObject* container=dynamic_cast(contId.getObject()); ResourceTypeObject *resType=ServerUniverse::getInstance().getResourceTypeByName(Unicode::wideToNarrow(argv[2])); - int amount=strtol(Unicode::wideToNarrow (argv[3]).c_str (), NULL, 10); + int amount=strtol(Unicode::wideToNarrow (argv[3]).c_str (), nullptr, 10); if (container && resType) { @@ -307,8 +307,8 @@ bool ConsoleCommandParserResource::performParsing (const NetworkId & userId, con { const std::string parentResourceClassName (Unicode::wideToNarrow(argv[1])); const std::string resourceTypeName (Unicode::wideToNarrow(argv[2])); - const int surveyRange = strtol(Unicode::wideToNarrow(argv[3]).c_str(),NULL,10); - const int numPoints = strtol(Unicode::wideToNarrow(argv[4]).c_str(),NULL,10); + const int surveyRange = strtol(Unicode::wideToNarrow(argv[3]).c_str(),nullptr,10); + const int numPoints = strtol(Unicode::wideToNarrow(argv[4]).c_str(),nullptr,10); const Object * player = NetworkIdManager::getObjectById(userId); if (player) diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserScript.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserScript.cpp index a2703595..99f1f236 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserScript.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserScript.cpp @@ -62,7 +62,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow (argv[2])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage (argv [0], ERR_INVALID_OBJECT); return true; @@ -81,7 +81,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const { NetworkId oid(Unicode::wideToNarrow(argv[2])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; @@ -100,7 +100,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const { ServerObject * const userServerObject = ServerWorld::findObjectByNetworkId(userId); - if (userServerObject != NULL) + if (userServerObject != nullptr) { NetworkId specifiedNetworkId; @@ -112,7 +112,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const { CreatureObject * const userCreatureObject = CreatureObject::asCreatureObject(userServerObject); - if (userCreatureObject != NULL) + if (userCreatureObject != nullptr) { specifiedNetworkId = userCreatureObject->getLookAtTarget(); } @@ -120,7 +120,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const ServerObject * const specifiedServerObject = ServerObject::getServerObject(specifiedNetworkId); - if (specifiedServerObject != NULL) + if (specifiedServerObject != nullptr) { ScriptList const & scripts = specifiedServerObject->getScriptObject()->getScripts(); FormattedString<1024> fs; @@ -226,7 +226,7 @@ bool ConsoleCommandParserScript::performParsing (const NetworkId & userId, const // get the object id NetworkId oid(Unicode::wideToNarrow(argv[oidIndex])); ServerObject* object = ServerWorld::findObjectByNetworkId(oid); - if (object == NULL) + if (object == nullptr) { result += getErrorMessage(argv[0], ERR_INVALID_OBJECT); return true; diff --git a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserServer.cpp b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserServer.cpp index f789d127..0e2e490f 100755 --- a/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserServer.cpp +++ b/engine/server/library/serverGame/src/shared/console/ConsoleCommandParserServer.cpp @@ -21,6 +21,7 @@ #include "serverGame/GuildObject.h" #include "serverGame/MessageToQueue.h" #include "serverGame/NameManager.h" +#include "serverGame/ObjectTracker.h" #include "serverGame/PlanetObject.h" #include "serverGame/PlayerCreatureController.h" #include "serverGame/PlayerObject.h" @@ -72,6 +73,8 @@ #include "sharedUtility/DataTableManager.h" #include "serverUtility/FreeCtsDataTable.h" +#include "sharedFoundation/CrcConstexpr.hpp" + #include // ====================================================================== @@ -115,7 +118,7 @@ static const CommandParser::CmdInfo cmds[] = {ms_testStructurePlacement, 1, "