diff --git a/.clang-format b/.clang-format index ef9dd2df23c..bc16580bfed 100644 --- a/.clang-format +++ b/.clang-format @@ -1,33 +1,275 @@ ---- + # https://clang.llvm.org/docs/ClangFormatStyleOptions.html -# We base things of WebKit + Allman braces -# BasedOnStyle: WebKit +--- +Language: Cpp AccessModifierOffset: -4 -AlignConsecutiveMacros: true -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true -AlignTrailingComments: true +AlignAfterOpenBracket: DontAlign +AlignArrayOfStructures: Left +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: None -AlwaysBreakTemplateDeclarations: true +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: None +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AttributeMacros: +- __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: None +BreakArrays: false +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Allman +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeComma -# This is just to make clang-format chill out! Use your best judgement! +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: MultiLine ColumnLimit: 0 -CompactNamespaces: 'false' +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false ConstructorInitializerIndentWidth: 0 -Cpp11BracedListStyle: 'false' -IndentCaseLabels: 'true' +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: +- foreach +- Q_FOREACH +- BOOST_FOREACH +IfMacros: +- KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: +- Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false +- Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +- Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true IndentWidth: 4 -KeepEmptyLinesAtTheStartOfBlocks: 'false' -Language: Cpp +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: false + AtStartOfFile: false +LambdaBodyIndentation: OuterScope +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MainIncludeChar: Quote +MaxEmptyLinesToKeep: 1 NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Left +ReferenceAlignment: Left ReflowComments: true -SortIncludes: 'true' -SortUsingDeclarations: 'true' +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 1 -Standard: Cpp11 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: +- Q_EMIT +StatementMacros: +- Q_UNUSED +- QT_REQUIRE_VERSION +TableGenBreakInsideDAGArg: DontBreak +TabWidth: 8 UseTab: Never - +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: +- BOOST_PP_STRINGIZE +- CF_SWIFT_NAME +- NS_SWIFT_NAME +- PP_STRINGIZE +- STRINGIZE ... diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2f880694790..7f481345a8c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,13 +3,13 @@ name: "build" on: pull_request: types: - - opened - - synchronize - - reopened + - opened + - synchronize + - reopened push: branches: - - base - - everything + - base + - everything concurrency: group: ${{ github.workflow }}-${{ github.ref || github.run_id }} @@ -95,28 +95,28 @@ jobs: exit 1 fi exit 0 - - name: Run CPP Formatting Checks (clang-format-18) + - name: Run CPP Formatting Checks (clang-format-19) if: always() run: | - clang-format-18 -version + clang-format -version touch cpp_formatting_checks.txt for changed_file in ${{ steps.changed-files.outputs.all }}; do if [[ -f $changed_file ]]; then if [[ $changed_file == *.cpp || $changed_file == *.h ]]; then - clang-format-18 -style=file -i ${changed_file} + python3 tools/run_clang_format.py ${changed_file} fi fi done git diff >> cpp_formatting_checks.txt git diff --color >> cpp_formatting_checks_color.txt - - name: Upload CPP Formatting Diff (clang-format-18) + - name: Upload CPP Formatting Diff (clang-format-19) if: hashFiles('cpp_formatting_checks.txt') != '' uses: actions/upload-artifact@v4 with: name: clang_format_diff path: | cpp_formatting_checks.txt - - name: Report CPP Formatting Checks (clang-format-18) + - name: Report CPP Formatting Checks (clang-format-19) if: always() run: | if [ -s cpp_formatting_checks_color.txt ] @@ -124,7 +124,7 @@ jobs: echo "" echo "You have errors in your C++ code formatting." echo "Please see below in red for the incorrect formatting, and in green for the correct formatting." - echo "You can either fix the formatting by hand or use clang-format." + echo "You can either fix the formatting by hand, use clang-format manually, using the diff file above, or the tools/run_clang_format.py script." echo "(You can safely ignore warnings about \$TERM and tput)" echo "" cat cpp_formatting_checks_color.txt | diff-so-fancy || true @@ -330,32 +330,32 @@ jobs: env: MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - name: Cache 'build' folder - uses: actions/cache@v4 - with: - path: build - key: ${{ runner.os }}-msvc64d - - name: Configure CMake - shell: cmd - run: | - mkdir -p build - cmake -S . -B build -A x64 -DCMAKE_BUILD_TYPE=Debug - - name: Build - shell: cmd - run: | - cmake --build build -j4 - - name: Archive Executables - uses: actions/upload-artifact@v4 - with: - name: windows_executables - path: | - xi_connect.exe - xi_map.exe - xi_search.exe - xi_world.exe + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Cache 'build' folder + uses: actions/cache@v4 + with: + path: build + key: ${{ runner.os }}-msvc64d + - name: Configure CMake + shell: cmd + run: | + mkdir -p build + cmake -S . -B build -A x64 -DCMAKE_BUILD_TYPE=Debug + - name: Build + shell: cmd + run: | + cmake --build build -j4 + - name: Archive Executables + uses: actions/upload-artifact@v4 + with: + name: windows_executables + path: | + xi_connect.exe + xi_map.exe + xi_search.exe + xi_world.exe Windows_64bit_Release_Tracy_Modules: needs: Sanity_Checks @@ -363,61 +363,61 @@ jobs: env: MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\ steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - name: Cache 'build' folder - uses: actions/cache@v4 - with: - path: build - key: ${{ runner.os }}-msvc64-t - - name: Enable Modules - shell: bash - run: | - python3 << EOF - with open("modules/init.txt", "w") as f: - f.write("custom\n") - f.write("era\n") - f.write("example\n") - f.write("renamer\n") - EOF - - name: Configure CMake - shell: cmd - run: | - mkdir -p build - cmake -S . -B build -A x64 -DCMAKE_BUILD_TYPE=Release -DENABLE_TRACY=ON - - name: Build - shell: cmd - run: | - cmake --build build -j4 - - name: Archive Executables - uses: actions/upload-artifact@v4 - with: - name: windows_modules_executables - path: | - xi_connect.exe - xi_map.exe - xi_search.exe - xi_world.exe - + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Cache 'build' folder + uses: actions/cache@v4 + with: + path: build + key: ${{ runner.os }}-msvc64-t + - name: Enable Modules + shell: bash + run: | + python3 << EOF + with open("modules/init.txt", "w") as f: + f.write("custom\n") + f.write("era\n") + f.write("example\n") + f.write("renamer\n") + EOF + - name: Configure CMake + shell: cmd + run: | + mkdir -p build + cmake -S . -B build -A x64 -DCMAKE_BUILD_TYPE=Release -DENABLE_TRACY=ON + - name: Build + shell: cmd + run: | + cmake --build build -j4 + - name: Archive Executables + uses: actions/upload-artifact@v4 + with: + name: windows_modules_executables + path: | + xi_connect.exe + xi_map.exe + xi_search.exe + xi_world.exe + MacOS_64bit: needs: Sanity_Checks # https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md runs-on: macos-15 steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - name: Install Dependencies (Brew) - run: | - brew install mariadb zeromq zmq luajit - - name: Configure CMake - run: | - mkdir -p build - cmake -S . -B build - - name: Build - run: | - cmake --build build -j4 + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install Dependencies (Brew) + run: | + brew install mariadb zeromq zmq luajit + - name: Configure CMake + run: | + mkdir -p build + cmake -S . -B build + - name: Build + run: | + cmake --build build -j4 Full_Startup_Checks_Linux: runs-on: ubuntu-24.04 @@ -429,7 +429,7 @@ jobs: MYSQL_DATABASE: xidb MYSQL_ROOT_PASSWORD: root ports: - - 3306:3306 + - 3306:3306 options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=10s --health-retries=10 steps: - uses: actions/checkout@v4 @@ -598,7 +598,7 @@ jobs: MYSQL_DATABASE: xidb MYSQL_ROOT_PASSWORD: root ports: - - 3306:3306 + - 3306:3306 options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=10s --health-retries=10 steps: - uses: actions/checkout@v4 @@ -688,7 +688,7 @@ jobs: path: . - uses: zach2good/setup-mariadb@v1 with: - database: xidb + database: xidb - name: Copy settings run: | cp settings/default/* settings/ @@ -724,7 +724,7 @@ jobs: path: . - uses: zach2good/setup-mariadb@v1 with: - database: xidb + database: xidb - name: Copy settings run: | cp settings/default/* settings/ diff --git a/modules/renamer/cpp/renamer.cpp b/modules/renamer/cpp/renamer.cpp index 3765b38d670..222f9466e04 100644 --- a/modules/renamer/cpp/renamer.cpp +++ b/modules/renamer/cpp/renamer.cpp @@ -7,7 +7,7 @@ extern std::function #endif -Application::Application(std::string const& serverName, int argc, char** argv) +Application::Application(const std::string& serverName, int argc, char** argv) : m_ServerName(serverName) , m_RequestExit(false) , gArgParser(std::make_unique(argv[0])) diff --git a/src/common/application.h b/src/common/application.h index fbcb07ec10c..961a24f57db 100644 --- a/src/common/application.h +++ b/src/common/application.h @@ -31,7 +31,7 @@ class Application { public: - Application(std::string const& serverName, int argc, char** argv); + Application(const std::string& serverName, int argc, char** argv); virtual ~Application() = default; Application(const Application&) = delete; diff --git a/src/common/async.cpp b/src/common/async.cpp index ce8030458a6..8d0a2b44ebb 100644 --- a/src/common/async.cpp +++ b/src/common/async.cpp @@ -28,7 +28,7 @@ Async::Async() { } -void Async::submit(std::function const& func) +void Async::submit(const std::function& func) { // clang-format off this->schedule([func]() diff --git a/src/common/async.h b/src/common/async.h index de108d6cf40..1ecfd87850b 100644 --- a/src/common/async.h +++ b/src/common/async.h @@ -31,7 +31,7 @@ class Async : public Singleton, private ts::task_system { public: - void submit(std::function const& func); + void submit(const std::function& func); protected: Async(); diff --git a/src/common/circular_buffer.h b/src/common/circular_buffer.h index 6199124c917..a91fa0af994 100644 --- a/src/common/circular_buffer.h +++ b/src/common/circular_buffer.h @@ -22,9 +22,9 @@ class CircularBuffer public: CircularBuffer(std::size_t max_size) : buffer(std::unique_ptr(new T[max_size])) - , max_size(max_size){}; + , max_size(max_size) {}; - void enqueue(T const& item) + void enqueue(const T& item) { std::lock_guard lock(mutex); diff --git a/src/common/console_service.cpp b/src/common/console_service.cpp index d21fa5c6536..36b358bce7a 100644 --- a/src/common/console_service.cpp +++ b/src/common/console_service.cpp @@ -273,7 +273,7 @@ ConsoleService::~ConsoleService() // NOTE: If you capture things in this function, make sure they're protected (locked or atomic)! // NOTE: If you're going to print, use fmt::print, rather than ShowInfo etc. -void ConsoleService::RegisterCommand(std::string const& name, std::string const& description, std::function&)> func) +void ConsoleService::RegisterCommand(const std::string& name, const std::string& description, std::function&)> func) { std::lock_guard lock(m_consoleInputBottleneck); diff --git a/src/common/console_service.h b/src/common/console_service.h index f1c40cbf1e2..7ee8d95ae46 100644 --- a/src/common/console_service.h +++ b/src/common/console_service.h @@ -56,7 +56,7 @@ class ConsoleService // NOTE: If you capture things in this function, make sure they're protected (locked or atomic)! // NOTE: If you're going to print, use fmt::print, rather than ShowInfo etc. - void RegisterCommand(std::string const& name, std::string const& description, std::function&)> func); + void RegisterCommand(const std::string& name, const std::string& description, std::function&)> func); // Call this to stop processing commands void stop(); diff --git a/src/common/database.cpp b/src/common/database.cpp index c485aab9567..e62394ca7b5 100644 --- a/src/common/database.cpp +++ b/src/common/database.cpp @@ -36,13 +36,13 @@ namespace // Replacement map similar to str_replace in PHP const std::unordered_map replacements = { - { '\\', "\\\\" }, - { '\0', "\\0" }, - { '\n', "\\n" }, - { '\r', "\\r" }, - { '\'', "\\'" }, - { '\"', "\\\"" }, - { '\x1a', "\\Z" } + { '\\', "\\\\" }, + { '\0', "\\0" }, + { '\n', "\\n" }, + { '\r', "\\r" }, + { '\'', "\\'" }, + { '\"', "\\\"" }, + { '\x1a', "\\Z" } }; const std::vector connectionIssues = { @@ -119,7 +119,7 @@ mutex_guarded& db::detail::getState() return state; } -auto db::detail::timer(std::string const& query) -> xi::final_action> +auto db::detail::timer(const std::string& query) -> xi::final_action> { // clang-format off const auto start = hires_clock::now(); @@ -142,7 +142,7 @@ auto db::detail::timer(std::string const& query) -> xi::final_action std::unique_ptr +auto db::queryStr(const std::string& rawQuery) -> std::unique_ptr { TracyZoneScoped; TracyZoneString(rawQuery); @@ -190,7 +190,7 @@ auto db::queryStr(std::string const& rawQuery) -> std::unique_ptr std::string +auto db::escapeString(const std::string& str) -> std::string { std::string escapedStr; diff --git a/src/common/database.h b/src/common/database.h index c0fc78ce4d2..7b2b1cc8152 100644 --- a/src/common/database.h +++ b/src/common/database.h @@ -56,7 +56,7 @@ namespace db class ResultSetWrapper; } - auto escapeString(std::string const& str) -> std::string; + auto escapeString(const std::string& str) -> std::string; auto getConnection() -> std::unique_ptr; @@ -150,7 +150,7 @@ namespace db }; template - void extractFromBlob(WrapperPtrT const& rset, std::string const& blobKey, T& destination); + void extractFromBlob(const WrapperPtrT& rset, const std::string& blobKey, T& destination); namespace detail { @@ -349,7 +349,7 @@ namespace db // template - friend void db::extractFromBlob(WrapperPtrT const& rset, std::string const& blobKey, T& destination); + friend void db::extractFromBlob(const WrapperPtrT& rset, const std::string& blobKey, T& destination); private: std::unique_ptr resultSet; @@ -457,7 +457,7 @@ namespace db binder(stmt, counter, blobs, std::forward(rest)...); } - auto timer(std::string const& query) -> xi::final_action>; + auto timer(const std::string& query) -> xi::final_action>; auto isConnectionIssue(const std::exception& e) -> bool; } // namespace detail @@ -466,7 +466,7 @@ namespace db // @param query The query string to execute. // @return A unique pointer to the result set of the query. // @note Everything in database-land is 1-indexed, not 0-indexed. - auto queryStr(std::string const& rawQuery) -> std::unique_ptr; + auto queryStr(const std::string& rawQuery) -> std::unique_ptr; // @brief Execute a query with the given query string and sprintf-style arguments. // @param query The query string to execute. @@ -474,7 +474,7 @@ namespace db // @return A unique pointer to the result set of the query. // @note Everything in database-land is 1-indexed, not 0-indexed. template - auto query(std::string const& query, Args&&... args) -> std::unique_ptr + auto query(const std::string& query, Args&&... args) -> std::unique_ptr { TracyZoneScoped; try @@ -498,7 +498,7 @@ namespace db // @note If the query hasn't been seen before it will generate a prepared statement for it to be used immediately and in the future. // @note Everything in database-land is 1-indexed, not 0-indexed. template - auto preparedStmt(std::string const& rawQuery, Args&&... args) -> std::unique_ptr + auto preparedStmt(const std::string& rawQuery, Args&&... args) -> std::unique_ptr { TracyZoneScoped; TracyZoneString(rawQuery); @@ -570,7 +570,7 @@ namespace db // @note This is a workaround for the fact that MariaDB's C++ connector hasn't yet implemented ResultSet::rowUpdated(), ResultSet::rowInserted(), // and ResultSet::rowDeleted(). template - auto preparedStmtWithAffectedRows(std::string const& rawQuery, Args&&... args) -> std::pair, std::size_t> + auto preparedStmtWithAffectedRows(const std::string& rawQuery, Args&&... args) -> std::pair, std::size_t> { TracyZoneScoped; TracyZoneString(rawQuery); @@ -660,7 +660,7 @@ namespace db // @param blobKey The key of the blob in the result set. // @param destination The struct to extract the blob into. template - void extractFromBlob(WrapperPtrT const& rset, std::string const& blobKey, T& destination) + void extractFromBlob(const WrapperPtrT& rset, const std::string& blobKey, T& destination) { static_assert(std::is_trivially_copyable_v, "T must be trivially copyable"); @@ -687,7 +687,7 @@ namespace db // @brief Escape a string for use in a query. // @param str The string to escape. // @return The escaped string. - auto escapeString(std::string const& str) -> std::string; + auto escapeString(const std::string& str) -> std::string; // @brief Get the database schema. // @return The database schema. diff --git a/src/common/debug_linux.cpp b/src/common/debug_linux.cpp index 9680e933e2f..770b370a7d8 100644 --- a/src/common/debug_linux.cpp +++ b/src/common/debug_linux.cpp @@ -65,9 +65,7 @@ void dumpBacktrace(int signal) void debug::init() { - struct rlimit core_limits - { - }; + struct rlimit core_limits{}; core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &core_limits); diff --git a/src/common/filewatcher.cpp b/src/common/filewatcher.cpp index 47878f06a8e..95fe2e92bbe 100644 --- a/src/common/filewatcher.cpp +++ b/src/common/filewatcher.cpp @@ -28,7 +28,7 @@ #include #include -Filewatcher::Filewatcher(std::vector const& paths) +Filewatcher::Filewatcher(const std::vector& paths) #ifdef USE_GENERIC_FILEWATCHER : fileWatcherImpl(std::make_unique(true)) #else @@ -53,7 +53,7 @@ Filewatcher::~Filewatcher() } // cppcheck-suppress passedByValue -void Filewatcher::handleFileAction(efsw::WatchID watchid, std::string const& dir, std::string const& filename, efsw::Action action, std::string oldFilename) +void Filewatcher::handleFileAction(efsw::WatchID watchid, const std::string& dir, const std::string& filename, efsw::Action action, std::string oldFilename) { TracySetThreadName("Filewatcher Thread"); TracyZoneScoped; @@ -97,7 +97,7 @@ auto Filewatcher::getChangedLuaFiles() -> std::vector> results; results.reserve(actions.size()); - for (auto const& [path, action] : actions) + for (const auto& [path, action] : actions) { results.emplace_back(path, action); } diff --git a/src/common/filewatcher.h b/src/common/filewatcher.h index 9606db5b0e1..c291f2d5a34 100644 --- a/src/common/filewatcher.h +++ b/src/common/filewatcher.h @@ -34,13 +34,13 @@ class Filewatcher : public efsw::FileWatchListener { public: - Filewatcher(std::vector const& paths); + Filewatcher(const std::vector& paths); ~Filewatcher() override; DISALLOW_COPY_AND_MOVE(Filewatcher); // efsw::FileWatchListener - void handleFileAction(efsw::WatchID watchid, std::string const& dir, std::string const& filename, efsw::Action action, std::string oldFilename) override; + void handleFileAction(efsw::WatchID watchid, const std::string& dir, const std::string& filename, efsw::Action action, std::string oldFilename) override; enum class Action { diff --git a/src/common/logging.cpp b/src/common/logging.cpp index 281f48c8238..83d2ccee688 100755 --- a/src/common/logging.cpp +++ b/src/common/logging.cpp @@ -127,7 +127,7 @@ namespace logging "trace", }; - void InitializeLog(std::string const& serverName, std::string const& logFile, bool appendDate) + void InitializeLog(const std::string& serverName, const std::string& logFile, bool appendDate) { ServerName = serverName; @@ -168,7 +168,7 @@ namespace logging spdlog::shutdown(); } - void SetPattern(std::string const& str) + void SetPattern(const std::string& str) { // https://github.com/gabime/spdlog/wiki/3.-Custom-formatting auto formatter = std::make_unique(); @@ -180,7 +180,7 @@ namespace logging spdlog::set_formatter(std::move(formatter)); } - void AddBacktrace(std::string const& str) + void AddBacktrace(const std::string& str) { BacktraceBuffer.enqueue(str); } diff --git a/src/common/logging.h b/src/common/logging.h index 693cf66ebd2..5c5cfa7f332 100644 --- a/src/common/logging.h +++ b/src/common/logging.h @@ -53,12 +53,12 @@ namespace settings namespace logging { - void InitializeLog(std::string const& serverName, std::string const& logFile, bool appendDate); + void InitializeLog(const std::string& serverName, const std::string& logFile, bool appendDate); void ShutDown(); - void SetPattern(std::string const& str); + void SetPattern(const std::string& str); - void AddBacktrace(std::string const& str); + void AddBacktrace(const std::string& str); auto GetBacktrace() -> std::vector; } // namespace logging diff --git a/src/common/lua.cpp b/src/common/lua.cpp index 645a22ac3c4..cd86764b491 100644 --- a/src/common/lua.cpp +++ b/src/common/lua.cpp @@ -135,7 +135,7 @@ std::string lua_to_string_depth(const sol::object& obj, std::size_t depth) // Stringify everything first std::vector stringVec; - for (auto const& [keyObj, valObj] : table) + for (const auto& [keyObj, valObj] : table) { if (keyObj.get_type() == sol::type::string) { @@ -206,7 +206,7 @@ void lua_print(sol::variadic_args va) std::string lua_fmt(const std::string& fmtStr, sol::variadic_args va) { fmt::dynamic_format_arg_store store; - for (auto const& arg : va) + for (const auto& arg : va) { switch (arg.get_type()) { diff --git a/src/common/mmo.h b/src/common/mmo.h index 3084efa365c..729ef6e5776 100644 --- a/src/common/mmo.h +++ b/src/common/mmo.h @@ -662,7 +662,7 @@ class char_mini m_zone = 0; m_nation = 0; }; - ~char_mini(){}; + ~char_mini() {}; }; // https://github.com/atom0s/XiPackets/tree/main/world/client/0x000A diff --git a/src/common/settings.cpp b/src/common/settings.cpp index 2ed105b085e..ac11aea0d5a 100644 --- a/src/common/settings.cpp +++ b/src/common/settings.cpp @@ -39,7 +39,7 @@ namespace settings // so we can pass them to the lua settings properly typed. bool isNumber(const std::string& stringValue) { - for (char const c : stringValue) + for (const char c : stringValue) { if (std::isdigit(c) == 0) { @@ -58,7 +58,7 @@ namespace settings void init() { // Load defaults - for (auto const& entry : sorted_directory_iterator("./settings/default/")) + for (const auto& entry : sorted_directory_iterator("./settings/default/")) { auto path = entry.relative_path(); auto isLua = path.extension() == ".lua"; @@ -121,7 +121,7 @@ namespace settings } // Load user settings - for (auto const& entry : sorted_directory_iterator("./settings/")) + for (const auto& entry : sorted_directory_iterator("./settings/")) { auto path = entry.relative_path(); auto isLua = path.extension() == ".lua"; diff --git a/src/common/socket.cpp b/src/common/socket.cpp index 02075b3c100..35aca80617d 100644 --- a/src/common/socket.cpp +++ b/src/common/socket.cpp @@ -182,9 +182,9 @@ time_t stall_time = 60; int32 makeConnection(uint32 ip, uint16 port, int32 type) { TracyZoneScoped; - struct sockaddr_in remote_address - { - }; + + struct sockaddr_in remote_address{}; + int32 fd = 0; int32 result = 0; @@ -204,14 +204,12 @@ int32 makeConnection(uint32 ip, uint16 port, int32 type) if (fd >= MAX_FD) { // socket number too big ShowError("make_connection: New socket #%d is greater than can we handle! Increase the value of MAX_FD (currently %d) for your OS to fix this!", - fd, MAX_FD); + fd, MAX_FD); sClose(fd); return -1; } - struct linger opt - { - }; + struct linger opt{}; opt.l_onoff = 0; // SO_DONTLINGER opt.l_linger = 0; // Do not care if (sSetsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&opt, sizeof(opt))) @@ -422,7 +420,7 @@ static int connect_check_(uint32 ip) int connect_ok = 0; // Search the allow list - for (auto const& entry : access_allow) + for (const auto& entry : access_allow) { if ((ip & entry.mask) == (entry.ip & entry.mask)) { @@ -430,16 +428,16 @@ static int connect_check_(uint32 ip) { ShowInfo( fmt::format("connect_check: Found match from allow list:{} IP:{} Mask:{}", - ip2str(ip), - ip2str(entry.ip), - ip2str(entry.mask))); + ip2str(ip), + ip2str(entry.ip), + ip2str(entry.mask))); } is_allowip = 1; break; } } // Search the deny list - for (auto const& entry : access_deny) + for (const auto& entry : access_deny) { if ((ip & entry.mask) == (entry.ip & entry.mask)) { @@ -447,9 +445,9 @@ static int connect_check_(uint32 ip) { ShowInfo( fmt::format("connect_check: Found match from deny list:{} IP:{} Mask:{}", - ip2str(ip), - ip2str(entry.ip), - ip2str(entry.mask))); + ip2str(ip), + ip2str(entry.ip), + ip2str(entry.mask))); } is_denyip = 1; break; @@ -598,10 +596,10 @@ int access_ipmask(const char* str, AccessControl* acc) else { if (((n = sscanf(str, "%u.%u.%u.%u/%u.%u.%u.%u", a, a + 1, a + 2, a + 3, m, m + 1, m + 2, m + 3)) != 8 && // not an ip + standard mask - (n = sscanf(str, "%u.%u.%u.%u/%u", a, a + 1, a + 2, a + 3, m)) != 5 && // not an ip + bit mask - (n = sscanf(str, "%u.%u.%u.%u", a, a + 1, a + 2, a + 3)) != 4) || // not an ip - a[0] > 255 || - a[1] > 255 || a[2] > 255 || a[3] > 255 || // invalid ip + (n = sscanf(str, "%u.%u.%u.%u/%u", a, a + 1, a + 2, a + 3, m)) != 5 && // not an ip + bit mask + (n = sscanf(str, "%u.%u.%u.%u", a, a + 1, a + 2, a + 3)) != 4) + || // not an ip + a[0] > 255 || a[1] > 255 || a[2] > 255 || a[3] > 255 || // invalid ip (n == 8 && (m[0] > 255 || m[1] > 255 || m[2] > 255 || m[3] > 255)) || // invalid standard mask (n == 5 && m[0] > 32)) { // invalid bit mask @@ -785,7 +783,7 @@ int connect_client(int listen_fd, sockaddr_in& client_address) if (fd >= MAX_FD) { // socket number too big ShowError("connect_client: New socket #%d is greater than can we handle! Increase the value of MAX_FD (currently %d) for your OS to fix this!", - fd, MAX_FD); + fd, MAX_FD); sClose(fd); return -1; } @@ -809,9 +807,8 @@ int connect_client(int listen_fd, sockaddr_in& client_address) int32 makeListenBind_tcp(const char* ip, uint16 port, RecvFunc connect_client) { TracyZoneScoped; - struct sockaddr_in server_address - { - }; + struct sockaddr_in server_address{}; + int fd = 0; int result = 0; @@ -834,7 +831,7 @@ int32 makeListenBind_tcp(const char* ip, uint16 port, RecvFunc connect_client) if (fd >= MAX_FD) { // socket number too big ShowError("make_listen_bind: New socket #%d is greater than can we handle! Increase the value of MAX_FD (currently %d) for your OS to fix this!", - fd, MAX_FD); + fd, MAX_FD); sClose(fd); return -1; } @@ -927,7 +924,7 @@ void do_close_tcp(int32 fd) /// The access list that we are parsing for individual entries. /// std::vector collection that contains all AccessControl entries. /// -std::vector get_access_list(std::string const& access_list) +std::vector get_access_list(const std::string& access_list) { // with the provided comma delimited access list, we will convert into a // vector of string entries @@ -1210,9 +1207,8 @@ void set_nonblocking(int fd, unsigned long yes) int32 makeBind_udp(uint32 ip, uint16 port) { TracyZoneScoped; - struct sockaddr_in server_address - { - }; + struct sockaddr_in server_address{}; + int fd = 0; int result = 0; @@ -1232,7 +1228,7 @@ int32 makeBind_udp(uint32 ip, uint16 port) if (fd >= MAX_FD) { // socket number too big ShowError("make_listen_bind: New socket #%d is greater than can we handle! Increase the value of MAX_FD (currently %d) for your OS to fix this!", - fd, MAX_FD); + fd, MAX_FD); sClose(fd); return -1; } diff --git a/src/common/socket.h b/src/common/socket.h index aa5886d6896..37d23bc55a3 100644 --- a/src/common/socket.h +++ b/src/common/socket.h @@ -155,9 +155,9 @@ int sSocket(int af, int type, int protocol); #endif -#define TOB(n) ((uint8)((n)&std::numeric_limits::max())) -#define TOW(n) ((uint16)((n)&std::numeric_limits::max())) -#define TOL(n) ((uint32)((n)&std::numeric_limits::max())) +#define TOB(n) ((uint8)((n) & std::numeric_limits::max())) +#define TOW(n) ((uint16)((n) & std::numeric_limits::max())) +#define TOL(n) ((uint32)((n) & std::numeric_limits::max())) enum class socket_type { diff --git a/src/common/sql.cpp b/src/common/sql.cpp index 8e625ce4641..90c847e7a26 100644 --- a/src/common/sql.cpp +++ b/src/common/sql.cpp @@ -42,10 +42,10 @@ std::atomic gProcessLoaded = false; SqlConnection::SqlConnection() : SqlConnection(settings::get("network.SQL_LOGIN").c_str(), - settings::get("network.SQL_PASSWORD").c_str(), - settings::get("network.SQL_HOST").c_str(), - settings::get("network.SQL_PORT"), - settings::get("network.SQL_DATABASE").c_str()) + settings::get("network.SQL_PASSWORD").c_str(), + settings::get("network.SQL_HOST").c_str(), + settings::get("network.SQL_PORT"), + settings::get("network.SQL_DATABASE").c_str()) { // Just forwarding the default credentials to the next constructor } @@ -288,7 +288,7 @@ size_t SqlConnection::EscapeString(char* out_to, const char* from) return EscapeStringLen(out_to, from, strlen(from)); } -std::string SqlConnection::EscapeString(std::string const& input) +std::string SqlConnection::EscapeString(const std::string& input) { TracyZoneScoped; std::string escaped_full_string; diff --git a/src/common/sql.h b/src/common/sql.h index 69afea15bb5..a8f297c7bcc 100644 --- a/src/common/sql.h +++ b/src/common/sql.h @@ -142,7 +142,7 @@ class SqlConnection /// Escapes a string. /// /// @return The escaped string - std::string EscapeString(std::string const& input); + std::string EscapeString(const std::string& input); /// Executes a query. /// Any previous result is freed. @@ -201,7 +201,7 @@ class SqlConnection /// Establishes keepalive (periodic ping) on the connection /// /// @return the keepalive timer id, or INVALID_TIMER - int32 Keepalive(std::string const& keepalive_name); + int32 Keepalive(const std::string& keepalive_name); /// Gets the data of a column. /// The data remains valid until the next row is fetched or the result is freed. diff --git a/src/common/string.h b/src/common/string.h index 6788a003bff..90948dffd31 100644 --- a/src/common/string.h +++ b/src/common/string.h @@ -50,7 +50,7 @@ namespace marshal buffer[std::min(index, capacity - 1)] = '\0'; } - void assign(std::string const& text) + void assign(const std::string& text) { auto index = std::min(text.length(), capacity); std::copy_n(text.begin(), index, buffer); @@ -66,16 +66,16 @@ namespace marshal // Copy template - string(string const& other) + string(const string& other) : string(std::string(other)) { } - string(char const* text) + string(const char* text) : string(std::string(text)) { } - string(std::string const& text) + string(const std::string& text) { assign(text); } @@ -115,17 +115,17 @@ namespace marshal return buffer + capacity; } - char const* cbegin() + const char* cbegin() { return buffer; } - char const* cend() + const char* cend() { return buffer + capacity; } - char const* data() + const char* data() { return buffer; } @@ -141,13 +141,13 @@ namespace marshal // Stream operators template - friend std::ostream operator<<(std::ostream& stream, string const& str); + friend std::ostream operator<<(std::ostream& stream, const string& str); template friend std::istream operator>>(std::istream& stream, string& str); }; template - std::ostream& operator<<(std::ostream& stream, string const& str) + std::ostream& operator<<(std::ostream& stream, const string& str) { return stream << std::string(str); } diff --git a/src/common/taskmgr.cpp b/src/common/taskmgr.cpp index d45e732f691..8900604f04f 100644 --- a/src/common/taskmgr.cpp +++ b/src/common/taskmgr.cpp @@ -38,7 +38,7 @@ CTaskMgr::~CTaskMgr() } } -CTaskMgr::CTask* CTaskMgr::AddTask(std::string const& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval) +CTaskMgr::CTask* CTaskMgr::AddTask(const std::string& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval) { TracyZoneScoped; return AddTask(new CTask(InitName, InitTick, std::move(InitData), InitType, InitFunc, InitInterval)); @@ -51,7 +51,7 @@ CTaskMgr::CTask* CTaskMgr::AddTask(CTask* PTask) return PTask; } -void CTaskMgr::RemoveTask(std::string const& TaskName) +void CTaskMgr::RemoveTask(const std::string& TaskName) { TracyZoneScoped; // m_TaskList is a priority_queue, so we can't directly pull members out of it. diff --git a/src/common/taskmgr.h b/src/common/taskmgr.h index 2a102d3fc98..b28fd3b35e0 100644 --- a/src/common/taskmgr.h +++ b/src/common/taskmgr.h @@ -60,10 +60,10 @@ class CTaskMgr : public Singleton }; CTask* AddTask(CTask*); - CTask* AddTask(std::string const& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval = 1s); + CTask* AddTask(const std::string& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval = 1s); duration DoTimer(time_point tick); - void RemoveTask(std::string const& TaskName); + void RemoveTask(const std::string& TaskName); protected: CTaskMgr() = default; @@ -75,13 +75,13 @@ class CTaskMgr : public Singleton class CTaskMgr::CTask { public: - CTask(std::string const& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval = 1s) + CTask(const std::string& InitName, time_point InitTick, std::any InitData, TASKTYPE InitType, TaskFunc_t InitFunc, duration InitInterval = 1s) : m_name(InitName) , m_type(InitType) , m_tick(InitTick) , m_interval(InitInterval) , m_data(InitData) - , m_func(InitFunc){}; + , m_func(InitFunc) {}; std::string m_name; TASKTYPE m_type; diff --git a/src/common/timer.cpp b/src/common/timer.cpp index 29fa5d61313..04fa204f668 100644 --- a/src/common/timer.cpp +++ b/src/common/timer.cpp @@ -94,17 +94,12 @@ static uint32 tick() // return (uint32)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK); // -#elif (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK) /* posix compliant */) || \ - (defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 500005 /* FreeBSD >= 5.1.0 */) - struct timespec tval - { - }; +#elif (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK) /* posix compliant */) || (defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 500005 /* FreeBSD >= 5.1.0 */) + struct timespec tval{}; clock_gettime(CLOCK_MONOTONIC, &tval); return tval.tv_sec * 1000 + tval.tv_nsec / 1000000; #else - struct timeval tval - { - }; + struct timeval tval{}; gettimeofday(&tval, nullptr); return tval.tv_sec * 1000 + tval.tv_usec / 1000; #endif diff --git a/src/common/utils.cpp b/src/common/utils.cpp index 33f4bcb5788..89cb8329657 100644 --- a/src/common/utils.cpp +++ b/src/common/utils.cpp @@ -37,25 +37,6 @@ #include #endif -//-------------------------------------------------- -// Return numerical value of a switch configuration -// on/off, english, franais, deutsch, espaol -//-------------------------------------------------- -int config_switch(const char* str) -{ - if (strcmpi(str, "true") == 0 || strcmpi(str, "on") == 0 || strcmpi(str, "yes") == 0 || strcmpi(str, "oui") == 0 || strcmpi(str, "ja") == 0 || - strcmpi(str, "si") == 0) - { - return 1; - } - if (strcmpi(str, "false") == 0 || strcmpi(str, "off") == 0 || strcmpi(str, "no") == 0 || strcmpi(str, "non") == 0 || strcmpi(str, "nein") == 0) - { - return 0; - } - - return (int)strtol(str, nullptr, 0); -} - int32 checksum(unsigned char* buf, uint32 buflen, char checkhash[16]) { unsigned char hash[16]; @@ -740,7 +721,7 @@ std::string UnpackSoultrapperName(uint8 input[]) return output; } -std::string escape(std::string const& s) +std::string escape(const std::string& s) { std::size_t n = s.length(); std::string escaped; @@ -756,7 +737,7 @@ std::string escape(std::string const& s) return escaped; } -std::vector split(std::string const& s, std::string const& delimiter) +std::vector split(const std::string& s, const std::string& delimiter) { std::size_t pos_start = 0; std::size_t pos_end = 0; @@ -776,7 +757,7 @@ std::vector split(std::string const& s, std::string const& delimite return res; } -std::string to_lower(std::string const& s) +std::string to_lower(const std::string& s) { // clang-format off std::string data = s; @@ -789,7 +770,7 @@ std::string to_lower(std::string const& s) return data; } -std::string to_upper(std::string const& s) +std::string to_upper(const std::string& s) { // clang-format off std::string data = s; @@ -803,7 +784,7 @@ std::string to_upper(std::string const& s) } // https://stackoverflow.com/questions/313970/how-to-convert-an-instance-of-stdstring-to-lower-case -std::string trim(std::string const& str, std::string const& whitespace) +std::string trim(const std::string& str, const std::string& whitespace) { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) @@ -830,17 +811,17 @@ void rtrim(std::string& s) } // Returns true if the given str matches the given pattern using standard regex -bool matches(std::string const& target, std::string const& pattern) +bool matches(const std::string& target, const std::string& pattern) { return std::regex_match(target, std::regex(pattern)); } -bool starts_with(std::string const& target, std::string const& pattern) +bool starts_with(const std::string& target, const std::string& pattern) { return target.rfind(pattern, 0) != std::string::npos; } -std::string replace(std::string const& target, std::string const& search, std::string const& replace) +std::string replace(const std::string& target, const std::string& search, const std::string& replace) { try { @@ -939,12 +920,12 @@ void crash() *ptr = 0xDEAD; } -std::unique_ptr utils::openFile(std::string const& path, std::string const& mode) +std::unique_ptr utils::openFile(const std::string& path, const std::string& mode) { return std::unique_ptr(fopen(path.c_str(), mode.c_str())); } -std::string utils::toASCII(std::string const& target, unsigned char replacement) +std::string utils::toASCII(const std::string& target, unsigned char replacement) { std::string out; out.reserve(target.size()); diff --git a/src/common/utils.h b/src/common/utils.h index afadbb37806..26a473d7909 100644 --- a/src/common/utils.h +++ b/src/common/utils.h @@ -40,7 +40,6 @@ constexpr size_t SignatureStringLength = 16; // encoded signature string size // constexpr size_t LinkshellStringLength = 20; // encoded linkshell string size // 19 characters + null terminator int32 checksum(uint8* buf, uint32 buflen, char checkhash[16]); -int config_switch(const char* str); bool bin2hex(char* output, unsigned char* input, size_t count); float distance(const position_t& A, const position_t& B, bool ignoreVertical = false); // distance between positions. Use only horizontal plane (x and z) if ignoreVertical is set. @@ -89,15 +88,15 @@ void DecodeStringSignature(const std::string& signature, char* target); void PackSoultrapperName(std::string name, uint8 output[]); std::string UnpackSoultrapperName(uint8 input[]); -auto escape(std::string const& s) -> std::string; -auto split(std::string const& s, std::string const& delimiter = " ") -> std::vector; -auto to_lower(std::string const& s) -> std::string; -auto to_upper(std::string const& s) -> std::string; +auto escape(const std::string& s) -> std::string; +auto split(const std::string& s, const std::string& delimiter = " ") -> std::vector; +auto to_lower(const std::string& s) -> std::string; +auto to_upper(const std::string& s) -> std::string; auto trim(const std::string& str, const std::string& whitespace = " \t") -> std::string; void rtrim(std::string& s); -bool matches(std::string const& target, std::string const& pattern); -bool starts_with(std::string const& target, std::string const& pattern); -auto replace(std::string const& target, std::string const& search, std::string const& replace) -> std::string; +bool matches(const std::string& target, const std::string& pattern); +bool starts_with(const std::string& target, const std::string& pattern); +auto replace(const std::string& target, const std::string& search, const std::string& replace) -> std::string; look_t stringToLook(std::string str); @@ -123,8 +122,8 @@ std::set sorted_directory_iterator(std::string path_name) namespace utils { - auto openFile(std::string const& path, std::string const& mode) -> std::unique_ptr; - auto toASCII(std::string const& target, unsigned char replacement = '\0') -> std::string; + auto openFile(const std::string& path, const std::string& mode) -> std::unique_ptr; + auto toASCII(const std::string& target, unsigned char replacement = '\0') -> std::string; } // namespace utils // clang-format off diff --git a/src/common/vana_time.cpp b/src/common/vana_time.cpp index 916edaabc97..27c0627904f 100644 --- a/src/common/vana_time.cpp +++ b/src/common/vana_time.cpp @@ -268,8 +268,7 @@ uint8 CVanaTime::getRSELocation() const TIMETYPE CVanaTime::SyncTime() { - m_vanaDate = (uint32)(this->getVanaTime() / 60.0 * 25) + - 886 * VTIME_YEAR; // convert vana time (from SE epoch in earth seconds) to vanadiel minutes and add 886 vana years + m_vanaDate = (uint32)(this->getVanaTime() / 60.0 * 25) + 886 * VTIME_YEAR; // convert vana time (from SE epoch in earth seconds) to vanadiel minutes and add 886 vana years m_vYear = m_vanaDate / VTIME_YEAR; m_vMon = (m_vanaDate / VTIME_MONTH) % 12 + 1; diff --git a/src/common/zlib.cpp b/src/common/zlib.cpp index c54f35d7fa0..8e22a687e6f 100644 --- a/src/common/zlib.cpp +++ b/src/common/zlib.cpp @@ -9,9 +9,7 @@ #include #include -#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || (defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN) || \ - defined(__BIG_ENDIAN__) || defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || defined(_MIBSEB) || defined(__MIBSEB) || \ - defined(__MIBSEB__) +#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || (defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__) #define XI_BIG_ENDIAN 1 #else #define XI_BIG_ENDIAN 0 @@ -40,7 +38,7 @@ #endif // Resolve the next address in jump table (0 == no jump, 1 == next address) -#define JMPBIT(table, i) (((table)[(i) / 8] >> ((i)&7)) & 1) +#define JMPBIT(table, i) (((table)[(i) / 8] >> ((i) & 7)) & 1) struct zlib_jump { @@ -65,7 +63,7 @@ static void swap32_if_be(const uint32* v, const size_t memb) #endif } -static bool read_to_vector(std::string const& filename, std::vector& vec) +static bool read_to_vector(const std::string& filename, std::vector& vec) { auto fp = utils::openFile(filename, "rb"); if (!fp) diff --git a/src/login/auth_session.cpp b/src/login/auth_session.cpp index 0c2d48d3552..91f110d35c2 100644 --- a/src/login/auth_session.cpp +++ b/src/login/auth_session.cpp @@ -51,11 +51,8 @@ namespace constexpr bool isBcryptHash(const std::string& passHash) { - return std::size(passHash) == 60 && - passHash[0] == '$' && - passHash[1] == '2' && - (passHash[2] == 'a' || passHash[2] == 'b' || passHash[2] == 'y' || passHash[2] == 'x') && // bcrypt hash versions - passHash[3] == '$'; + return std::size(passHash) == 60 && passHash[0] == '$' && passHash[1] == '2' && (passHash[2] == 'a' || passHash[2] == 'b' || passHash[2] == 'y' || passHash[2] == 'x') && // bcrypt hash versions + passHash[3] == '$'; } } // namespace @@ -243,7 +240,7 @@ void auth_session::read_func() FROM accounts_sessions JOIN accounts \ ON accounts_sessions.accid = accounts.id \ WHERE accounts.id = %d", - accountID); + accountID); if (rset && rset->rowsCount() == 1) { @@ -333,7 +330,7 @@ void auth_session::read_func() if (!settings::get("login.ACCOUNT_CREATION")) { ShowWarningFmt("login_parse: New account attempt <{}> but is disabled in settings.", - username); + username); ref(data_, 0) = LOGIN_ERROR_CREATE_DISABLED; do_write(1); return; @@ -379,7 +376,7 @@ void auth_session::read_func() const auto rset2 = db::query("INSERT INTO accounts(id,login,password,timecreate,timelastmodify,status,priv) \ VALUES(%d,'%s','%s','%s',NULL,%d,%d)", - accid, username, BCrypt::generateHash(password), strtimecreate, ACCOUNT_STATUS_CODE::NORMAL, ACCOUNT_PRIVILEGE_CODE::USER); + accid, username, BCrypt::generateHash(password), strtimecreate, ACCOUNT_STATUS_CODE::NORMAL, ACCOUNT_PRIVILEGE_CODE::USER); if (!rset2) { ref(data_, 0) = LOGIN_ERROR_CREATE; @@ -457,7 +454,7 @@ void auth_session::read_func() const auto rset = db::query("SELECT accounts.id, accounts.status \ FROM accounts \ WHERE accounts.login = '%s'", - username); + username); if (rset == nullptr || rset->rowsCount() == 0) { ShowWarningFmt("login_parse: user <{}> could not be found using the provided information. Aborting.", username); @@ -496,7 +493,7 @@ void auth_session::read_func() db::query("UPDATE accounts SET accounts.timelastmodify = NULL WHERE accounts.id = %d", accid); const auto rset2 = db::query("UPDATE accounts SET accounts.password = '%s' WHERE accounts.id = %d", - BCrypt::generateHash(updated_password), accid); + BCrypt::generateHash(updated_password), accid); if (!rset2) { ShowWarningFmt("login_parse: Error trying to update password in database for user <{}>.", username); diff --git a/src/login/cert_helpers.h b/src/login/cert_helpers.h index bebdf0e84c6..2ae7541aa55 100644 --- a/src/login/cert_helpers.h +++ b/src/login/cert_helpers.h @@ -106,9 +106,9 @@ namespace certificateHelpers /* X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char*)"CA", -1, -1, 0);*/ X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, - (unsigned char*)"LSB self-signed certificate for login server", -1, -1, 0); + (unsigned char*)"LSB self-signed certificate for login server", -1, -1, 0); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, - commonNameIpAddr, -1, -1, 0); + commonNameIpAddr, -1, -1, 0); X509_set_issuer_name(x509, name); diff --git a/src/login/connect_server.cpp b/src/login/connect_server.cpp index eb8b0972656..1bc2063399e 100644 --- a/src/login/connect_server.cpp +++ b/src/login/connect_server.cpp @@ -50,9 +50,7 @@ ConnectServer::ConnectServer(int argc, char** argv) // clang-format on #ifndef _WIN32 - struct rlimit limits - { - }; + struct rlimit limits{}; uint32 newRLimit = 10240; @@ -129,9 +127,7 @@ void ConnectServer::periodicCleanup(const asio::error_code& error, asio::steady_ session_t& session = sessionIterator->second; // If it's been 15 minutes, erase it from the session list - if (!session.data_session && - !session.view_session && - (server_clock::now() - session.authorizedTime) > std::chrono::minutes(15)) + if (!session.data_session && !session.view_session && (server_clock::now() - session.authorizedTime) > std::chrono::minutes(15)) { sessionIterator = ipAddrIterator->second.erase(sessionIterator); } diff --git a/src/login/data_session.cpp b/src/login/data_session.cpp index 7d458bdc78a..72b87083cb3 100644 --- a/src/login/data_session.cpp +++ b/src/login/data_session.cpp @@ -74,8 +74,7 @@ void data_session::read_func() return; } - const char* pfmtQuery = - "SELECT charid, charname, pos_zone, pos_prevzone, mjob,\ + const char* pfmtQuery = "SELECT charid, charname, pos_zone, pos_prevzone, mjob,\ race, face, head, body, hands, legs, feet, main, sub,\ war, mnk, whm, blm, rdm, thf, pld, drk, bst, brd, rng,\ sam, nin, drg, smn, blu, cor, pup, dnc, sch, geo, run, \ @@ -268,7 +267,7 @@ void data_session::read_func() const auto rset = db::query("SELECT zoneip, zoneport, zoneid, pos_prevzone, gmlevel, accid, charname \ FROM zone_settings, chars \ WHERE IF(pos_zone = 0, zoneid = pos_prevzone, zoneid = pos_zone) AND charid = %u AND accid = %u", - charid, session.accountID); + charid, session.accountID); if (rset && rset->rowsCount() && rset->next()) { ZoneID = rset->get("zoneid"); @@ -299,7 +298,7 @@ void data_session::read_func() characterSelectionResponse.server_id = (charid >> 16) & 0xFF; // Looks wrong? shouldn't this be a server index? ShowInfo(fmt::format("data_session: zoneid:({}), zoneip:({}), zoneport:({}) for char:({})", - ZoneID, loginHelpers::ip2str(ntohl(ZoneIP)), ZonePort, charid)); + ZoneID, loginHelpers::ip2str(ntohl(ZoneIP)), ZonePort, charid)); // Check the number of sessions uint16 sessionCount = 0; @@ -307,7 +306,7 @@ void data_session::read_func() const auto rset0 = db::query("SELECT COUNT(client_addr) \ FROM accounts_sessions \ WHERE client_addr = %u", - accountIP); + accountIP); if (rset0 && rset0->rowsCount() != 0 && rset0->next()) { sessionCount = rset0->get("COUNT(client_addr)"); @@ -317,7 +316,7 @@ void data_session::read_func() const auto rset1 = db::query("SELECT * \ FROM accounts_sessions \ WHERE accid = %u AND client_port != '0'", - session.accountID); + session.accountID); if (rset1 && rset1->rowsCount() != 0 && rset1->next()) { hasActiveSession = true; @@ -327,7 +326,7 @@ void data_session::read_func() const auto rset2 = db::query("SELECT * \ FROM accounts_sessions \ WHERE accid = %u AND client_port = '0' AND last_zoneout_time >= SUBTIME(NOW(), \"00:00:30\")", - session.accountID); + session.accountID); if (rset2 && rset2->rowsCount() != 0 && rset2->next()) { hasActiveSession = true; @@ -338,7 +337,7 @@ void data_session::read_func() const auto rset3 = db::query("SELECT UNIX_TIMESTAMP(exception) \ FROM ip_exceptions \ WHERE accid = %u", - session.accountID); + session.accountID); if (rset3 && rset3->rowsCount() != 0 && rset3->next()) { exceptionTime = rset3->get("UNIX_TIMESTAMP(exception)"); @@ -388,8 +387,8 @@ void data_session::read_func() if (!db::query("INSERT INTO accounts_sessions(accid,charid,session_key,server_addr,server_port,client_addr, version_mismatch) " "VALUES(%u,%u,x'%s',%u,%u,%u,%u)", - session.accountID, charid, session_key, ZoneIP, ZonePort, accountIP, - session.versionMismatch ? 1 : 0)) + session.accountID, charid, session_key, ZoneIP, ZonePort, accountIP, + session.versionMismatch ? 1 : 0)) { if (auto data = session.view_session.get()) { @@ -454,7 +453,7 @@ void data_session::read_func() if (!db::query("INSERT INTO account_ip_record(login_time,accid,charid,client_ip) \ VALUES ('%s', %u, %u, '%s')", - timeAndDate, session.accountID, charid, loginHelpers::ip2str(accountIP))) + timeAndDate, session.accountID, charid, loginHelpers::ip2str(accountIP))) { ShowError("data_session: Could not write info to account_ip_record."); } diff --git a/src/login/login_helpers.cpp b/src/login/login_helpers.cpp index 8beaac17de9..47d07aa4725 100644 --- a/src/login/login_helpers.cpp +++ b/src/login/login_helpers.cpp @@ -31,17 +31,19 @@ namespace loginHelpers return authenticatedSessions_; } - bool isStringMalformed(std::string const& str, std::size_t max_length) + bool isStringMalformed(const std::string& str, std::size_t max_length) { const bool isEmpty = str.empty(); const bool isTooLong = str.size() > max_length; - const bool hasInvalidChar = std::any_of(str.cbegin(), str.cend(), [](char const& c) - { return c < 0x20; }); + const bool hasInvalidChar = std::any_of(str.cbegin(), str.cend(), [](const char& c) + { + return c < 0x20; + }); return isEmpty || isTooLong || hasInvalidChar; } - session_t& get_authenticated_session(std::string const& ipAddr, std::string const& sessionHash) + session_t& get_authenticated_session(const std::string& ipAddr, const std::string& sessionHash) { return authenticatedSessions_[ipAddr][sessionHash]; // NOTE: Will construct if doesn't exist } @@ -90,21 +92,21 @@ namespace loginHelpers uint16 mask = EXPANSION_DISPLAY::BASE_GAME; std::map expansions = { - { "login.RISE_OF_ZILART", EXPANSION_DISPLAY::RISE_OF_ZILART }, - { "login.CHAINS_OF_PROMATHIA", EXPANSION_DISPLAY::CHAINS_OF_PROMATHIA }, + { "login.RISE_OF_ZILART", EXPANSION_DISPLAY::RISE_OF_ZILART }, + { "login.CHAINS_OF_PROMATHIA", EXPANSION_DISPLAY::CHAINS_OF_PROMATHIA }, { "login.TREASURES_OF_AHT_URGHAN", EXPANSION_DISPLAY::TREASURES_OF_AHT_URGHAN }, - { "login.WINGS_OF_THE_GODDESS", EXPANSION_DISPLAY::WINGS_OF_THE_GODDESS }, - { "login.A_CRYSTALLINE_PROPHECY", EXPANSION_DISPLAY::A_CRYSTALLINE_PROPHECY }, - { "login.A_MOOGLE_KUPOD_ETAT", EXPANSION_DISPLAY::A_MOOGLE_KUPOD_ETAT }, - { "login.A_SHANTOTTO_ASCENSION", EXPANSION_DISPLAY::A_SHANTOTTO_ASCENSION }, - { "login.VISIONS_OF_ABYSSEA", EXPANSION_DISPLAY::VISIONS_OF_ABYSSEA }, - { "login.SCARS_OF_ABYSSEA", EXPANSION_DISPLAY::SCARS_OF_ABYSSEA }, - { "login.HEROES_OF_ABYSSEA", EXPANSION_DISPLAY::HEROES_OF_ABYSSEA }, - { "login.SEEKERS_OF_ADOULIN", EXPANSION_DISPLAY::SEEKERS_OF_ADOULIN }, + { "login.WINGS_OF_THE_GODDESS", EXPANSION_DISPLAY::WINGS_OF_THE_GODDESS }, + { "login.A_CRYSTALLINE_PROPHECY", EXPANSION_DISPLAY::A_CRYSTALLINE_PROPHECY }, + { "login.A_MOOGLE_KUPOD_ETAT", EXPANSION_DISPLAY::A_MOOGLE_KUPOD_ETAT }, + { "login.A_SHANTOTTO_ASCENSION", EXPANSION_DISPLAY::A_SHANTOTTO_ASCENSION }, + { "login.VISIONS_OF_ABYSSEA", EXPANSION_DISPLAY::VISIONS_OF_ABYSSEA }, + { "login.SCARS_OF_ABYSSEA", EXPANSION_DISPLAY::SCARS_OF_ABYSSEA }, + { "login.HEROES_OF_ABYSSEA", EXPANSION_DISPLAY::HEROES_OF_ABYSSEA }, + { "login.SEEKERS_OF_ADOULIN", EXPANSION_DISPLAY::SEEKERS_OF_ADOULIN }, }; // apply the expansion masks where available - for (auto const& expansion : expansions) + for (const auto& expansion : expansions) { if (settings::get(expansion.first)) { @@ -119,7 +121,7 @@ namespace loginHelpers uint16 mask = 0; std::map features = { - { "login.SECURE_TOKEN", FEATURE_DISPLAY::SECURE_TOKEN }, // This needs to be broken out into auth calls once TOTP is supported + { "login.SECURE_TOKEN", FEATURE_DISPLAY::SECURE_TOKEN }, // This needs to be broken out into auth calls once TOTP is supported { "login.MOG_WARDROBE_3", FEATURE_DISPLAY::MOG_WARDROBE_3 }, { "login.MOG_WARDROBE_4", FEATURE_DISPLAY::MOG_WARDROBE_4 }, { "login.MOG_WARDROBE_5", FEATURE_DISPLAY::MOG_WARDROBE_5 }, @@ -129,7 +131,7 @@ namespace loginHelpers }; // apply the feature masks where available - for (auto const& feature : features) + for (const auto& feature : features) { if (settings::get(feature.first)) { @@ -143,28 +145,28 @@ namespace loginHelpers int32 saveCharacter(uint32 accid, uint32 charid, char_mini* createchar) { if (!db::query("INSERT INTO chars(charid,accid,charname,pos_zone,nation) VALUES(%u,%u,'%s',%u,%u)", - charid, accid, str(createchar->m_name), createchar->m_zone, createchar->m_nation)) + charid, accid, str(createchar->m_name), createchar->m_zone, createchar->m_nation)) { ShowDebug(fmt::format("lobby_ccsave: char<{}>, accid: {}, charid: {}", str(createchar->m_name), accid, charid)); return -1; } if (!db::query("INSERT INTO char_look(charid,face,race,size) VALUES(%u,%u,%u,%u)", - charid, createchar->m_look.face, createchar->m_look.race, createchar->m_look.size)) + charid, createchar->m_look.face, createchar->m_look.race, createchar->m_look.size)) { ShowDebug(fmt::format("lobby_cLook: char<{}>, charid: {}", str(createchar->m_name), charid)); return -1; } if (!db::query("INSERT INTO char_stats(charid,mjob) VALUES(%u,%u)", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { ShowDebug(fmt::format("lobby_cStats: charid: {}", charid)); return -1; } if (!db::query("INSERT INTO char_exp(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } @@ -175,31 +177,31 @@ namespace loginHelpers } if (!db::query("INSERT INTO char_jobs(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } if (!db::query("INSERT INTO char_points(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } if (!db::query("INSERT INTO char_unlocks(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } if (!db::query("INSERT INTO char_profile(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } if (!db::query("INSERT INTO char_storage(charid) VALUES(%u) ON DUPLICATE KEY UPDATE charid = charid", - charid, createchar->m_mjob)) + charid, createchar->m_mjob)) { return -1; } @@ -217,7 +219,7 @@ namespace loginHelpers if (settings::get("main.NEW_CHARACTER_CUTSCENE")) { if (!db::query("INSERT INTO char_vars(charid, varname, value) VALUES(%u, '%s', %u)", - charid, "HQuest[newCharacterCS]notSeen", 1)) + charid, "HQuest[newCharacterCS]notSeen", 1)) { return -1; } @@ -243,7 +245,7 @@ namespace loginHelpers if (mjob != createchar.m_mjob) { ShowInfo(fmt::format("{} attempted to create invalid starting job {} substituting {}", - session.requestedNewCharacterName, mjob, createchar.m_mjob)); + session.requestedNewCharacterName, mjob, createchar.m_mjob)); } createchar.m_nation = ref(buf, 54); @@ -316,7 +318,7 @@ namespace loginHelpers } } - std::string getHashFromPacket(std::string const& ip_str, char* data) + std::string getHashFromPacket(const std::string& ip_str, char* data) { std::string hash = std::string(data + 12, 16); diff --git a/src/login/login_helpers.h b/src/login/login_helpers.h index 9b5ed035d71..8fdf6799671 100644 --- a/src/login/login_helpers.h +++ b/src/login/login_helpers.h @@ -78,9 +78,9 @@ namespace loginHelpers UNUSED_FEATURE_9 = 0x8000, }; - bool isStringMalformed(std::string const& str, std::size_t max_length); + bool isStringMalformed(const std::string& str, std::size_t max_length); - session_t& get_authenticated_session(std::string const& ipAddr, std::string const& sessionHash); + session_t& get_authenticated_session(const std::string& ipAddr, const std::string& sessionHash); // hostname/ip conversion functions std::string ip2str(uint32 ip); @@ -100,5 +100,5 @@ namespace loginHelpers void PrintPacket(const char* data, uint32 size); - std::string getHashFromPacket(std::string const& ip_str, char* data); + std::string getHashFromPacket(const std::string& ip_str, char* data); } // namespace loginHelpers diff --git a/src/login/view_session.cpp b/src/login/view_session.cpp index fd124f5d6af..283effd8b84 100644 --- a/src/login/view_session.cpp +++ b/src/login/view_session.cpp @@ -58,7 +58,7 @@ void view_session::read_func() uint32 accountID = 0; const auto rset = db::query("SELECT accid FROM chars WHERE charid = %u AND charname = '%s' LIMIT 1", - requestedCharacterID, requestedCharacter); + requestedCharacterID, requestedCharacter); if (rset && rset->rowsCount() != 0 && rset->next()) { accountID = rset->get("accid"); @@ -115,7 +115,7 @@ void view_session::read_func() uint32 charID = ref(data_, 0x20); ShowInfo(fmt::format("attempt to delete char:<{}> from ip:<{}>", - charID, ipAddress)); + charID, ipAddress)); uint32 accountID = 0; @@ -137,7 +137,7 @@ void view_session::read_func() // This allows character recovery. db::query("UPDATE chars SET accid = 0, original_accid = %i WHERE charid = %i AND accid = %i", - session.accountID, charID, session.accountID); + session.accountID, charID, session.accountID); } break; case 0x21: // 33: Registering character name onto the lobby server @@ -223,14 +223,13 @@ void view_session::read_func() // (optional) Check if the name is in use by NPC or Mob entities if (settings::get("login.DISABLE_MOB_NPC_CHAR_NAMES")) { - auto query = - "WITH results AS " - "( " - " SELECT polutils_name AS `name` FROM npc_list " - " UNION " - " SELECT packet_name AS `name` FROM mob_pools " - ") " - "SELECT * FROM results WHERE REPLACE(REPLACE(UPPER(`name`), '-', ''), '_', '') LIKE REPLACE(REPLACE(UPPER('%s'), '-', ''), '_', '')"; + auto query = "WITH results AS " + "( " + " SELECT polutils_name AS `name` FROM npc_list " + " UNION " + " SELECT packet_name AS `name` FROM mob_pools " + ") " + "SELECT * FROM results WHERE REPLACE(REPLACE(UPPER(`name`), '-', ''), '_', '') LIKE REPLACE(REPLACE(UPPER('%s'), '-', ''), '_', '')"; const auto rset1 = db::query(query, nameStr); if (!rset1) @@ -249,7 +248,7 @@ void view_session::read_func() if (auto badWordsList = loginSettingsTable.get_or("BANNED_WORDS_LIST", sol::lua_nil); badWordsList.valid()) { auto potentialName = to_upper(nameStr); - for (auto const& entry : badWordsList) + for (const auto& entry : badWordsList) { auto badWord = to_upper(entry.second.as()); if (potentialName.find(badWord) != std::string::npos) diff --git a/src/search/data_loader.cpp b/src/search/data_loader.cpp index 3ac1f3fa6ae..3b40b13d814 100644 --- a/src/search/data_loader.cpp +++ b/src/search/data_loader.cpp @@ -110,7 +110,7 @@ std::vector CDataLoader::GetAHItemsToCategory(uint8 AHCategoryID, const "WHERE aH = %u " "GROUP BY item_basic.itemid " "%s", - selectFrom, AHCategoryID, OrderByString); + selectFrom, AHCategoryID, OrderByString); auto rset = db::query(fmtQuery); if (rset && rset->rowsCount()) @@ -242,17 +242,16 @@ std::list CDataLoader::GetPlayersList(search_req sr, int* count) filterQry.append(fmt::sprintf(" AND (seacom_type & 0xF0) = %u", sr.commentType, sr.commentType)); } - std::string fmtQuery = - "SELECT charid, partyid, charname, pos_zone, pos_prevzone, nation, rank_sandoria, rank_bastok, " - "rank_windurst, race, mjob, sjob, mlvl, slvl, languages, settings, seacom_type, disconnecting, gmHiddenEnabled " - "FROM accounts_sessions " - "LEFT JOIN accounts_parties USING (charid) " - "LEFT JOIN chars USING (charid) " - "LEFT JOIN char_look USING (charid) " - "LEFT JOIN char_stats USING (charid) " - "LEFT JOIN char_profile USING(charid) " - "LEFT JOIN char_flags USING(charid) " - "WHERE charname IS NOT NULL "; + std::string fmtQuery = "SELECT charid, partyid, charname, pos_zone, pos_prevzone, nation, rank_sandoria, rank_bastok, " + "rank_windurst, race, mjob, sjob, mlvl, slvl, languages, settings, seacom_type, disconnecting, gmHiddenEnabled " + "FROM accounts_sessions " + "LEFT JOIN accounts_parties USING (charid) " + "LEFT JOIN chars USING (charid) " + "LEFT JOIN char_look USING (charid) " + "LEFT JOIN char_stats USING (charid) " + "LEFT JOIN char_profile USING(charid) " + "LEFT JOIN char_flags USING(charid) " + "WHERE charname IS NOT NULL "; fmtQuery.append(filterQry); fmtQuery.append(" ORDER BY charname ASC"); @@ -482,18 +481,17 @@ std::list CDataLoader::GetPartyList(uint32 PartyID, uint32 Allian { std::list PartyList; - const char* query = - "SELECT charid, partyid, charname, pos_zone, nation, rank_sandoria, rank_bastok, rank_windurst, race, settings, mjob, sjob, mlvl, slvl, languages, seacom_type, disconnecting " - "FROM accounts_sessions " - "LEFT JOIN accounts_parties USING(charid) " - "LEFT JOIN chars USING(charid) " - "LEFT JOIN char_look USING(charid) " - "LEFT JOIN char_stats USING(charid) " - "LEFT JOIN char_profile USING(charid) " - "LEFT JOIN char_flags USING(charid) " - "WHERE IF (allianceid <> 0, allianceid IN (SELECT allianceid FROM accounts_parties WHERE charid = %u) , partyid = %u) " - "ORDER BY charname ASC " - "LIMIT 64"; + const char* query = "SELECT charid, partyid, charname, pos_zone, nation, rank_sandoria, rank_bastok, rank_windurst, race, settings, mjob, sjob, mlvl, slvl, languages, seacom_type, disconnecting " + "FROM accounts_sessions " + "LEFT JOIN accounts_parties USING(charid) " + "LEFT JOIN chars USING(charid) " + "LEFT JOIN char_look USING(charid) " + "LEFT JOIN char_stats USING(charid) " + "LEFT JOIN char_profile USING(charid) " + "LEFT JOIN char_flags USING(charid) " + "WHERE IF (allianceid <> 0, allianceid IN (SELECT allianceid FROM accounts_parties WHERE charid = %u) , partyid = %u) " + "ORDER BY charname ASC " + "LIMIT 64"; auto rset = db::query(query, (!AllianceID ? PartyID : AllianceID), (!PartyID ? AllianceID : PartyID)); if (rset && rset->rowsCount()) @@ -745,7 +743,7 @@ void CDataLoader::ExpireAHItems(uint16 expireAgeInDays) const auto query2 = fmt::format("INSERT INTO delivery_box (charid, charname, box, itemid, itemsubid, quantity, senderid, sender) VALUES " "({}, '{}', 1, {}, 0, {}, 0, 'AH-Jeuno')", - listing.sellerID, listing.sellerName, listing.itemID, listing.ahStack == 1 ? listing.itemStack : 1); + listing.sellerID, listing.sellerName, listing.itemID, listing.ahStack == 1 ? listing.itemStack : 1); const auto [rset2, affectedRows] = db::preparedStmtWithAffectedRows(query2); if (rset2 && affectedRows > 0) diff --git a/src/search/packets/search_comment.cpp b/src/search/packets/search_comment.cpp index ccf4a54f5d7..b572e8aea76 100644 --- a/src/search/packets/search_comment.cpp +++ b/src/search/packets/search_comment.cpp @@ -1,11 +1,10 @@ - -#include "search_comment.h" +#include "search_comment.h" #include "common/logging.h" #include "common/socket.h" #include "common/utils.h" -SearchCommentPacket::SearchCommentPacket(uint32 playerId, std::string const& comment) +SearchCommentPacket::SearchCommentPacket(uint32 playerId, const std::string& comment) { ref(data, 0x08) = 154; // Search comment packet size ref(data, 0x0A) = 0x80; // Search server packet diff --git a/src/search/packets/search_comment.h b/src/search/packets/search_comment.h index 7f8dffae613..bb3d2e5b3af 100644 --- a/src/search/packets/search_comment.h +++ b/src/search/packets/search_comment.h @@ -1,5 +1,4 @@ - -#ifndef _SEARCH_COMMENT_PACKET_H_ +#ifndef _SEARCH_COMMENT_PACKET_H_ #define _SEARCH_COMMENT_PACKET_H_ #include "common/cbasetypes.h" @@ -8,7 +7,7 @@ class SearchCommentPacket { public: - SearchCommentPacket(uint32 playerId, std::string const& comment); + SearchCommentPacket(uint32 playerId, const std::string& comment); uint8* GetData(); uint16 GetSize(); diff --git a/src/search/search.cpp b/src/search/search.cpp index ea9e17cdbb9..72047aed181 100755 --- a/src/search/search.cpp +++ b/src/search/search.cpp @@ -95,7 +95,7 @@ struct SearchCommInfo uint16 port; }; -void TaskManagerThread(bool const& requestExit); +void TaskManagerThread(const bool& requestExit); int32 ah_cleanup(time_point tick, CTaskMgr::CTask* PTask); @@ -132,7 +132,7 @@ std::string socketToString(SOCKET socket) return std::string(ipstr); } -bool isSocketInUse(std::string const& ipAddressStr) +bool isSocketInUse(const std::string& ipAddressStr) { // clang-format off if (gIPAddressWhitelist.read([ipAddressStr](auto const& ipWhitelist) @@ -153,7 +153,7 @@ bool isSocketInUse(std::string const& ipAddressStr) // clang-format on } -void removeSocketFromSet(std::string const& ipAddressStr) +void removeSocketFromSet(const std::string& ipAddressStr) { // clang-format off if (gIPAddressWhitelist.read([ipAddressStr](auto const& ipWhitelist) @@ -174,7 +174,7 @@ void removeSocketFromSet(std::string const& ipAddressStr) // clang-format on } -void addSocketToSet(std::string const& ipAddressStr) +void addSocketToSet(const std::string& ipAddressStr) { // clang-format off if (gIPAddressWhitelist.read([ipAddressStr](auto const& ipWhitelist) @@ -263,9 +263,7 @@ int32 main(int32 argc, char** argv) SOCKET ClientSocket = INVALID_SOCKET; struct addrinfo* result = nullptr; - struct addrinfo hints - { - }; + struct addrinfo hints{}; #ifdef WIN32 // Initialize Winsock @@ -375,11 +373,11 @@ int32 main(int32 argc, char** argv) { ShowInfo("AH task to return items older than %u days is running", expireDays); CTaskMgr::getInstance()->AddTask("ah_cleanup", server_clock::now(), nullptr, CTaskMgr::TASK_INTERVAL, ah_cleanup, - std::chrono::seconds(settings::get("search.EXPIRE_INTERVAL"))); + std::chrono::seconds(settings::get("search.EXPIRE_INTERVAL"))); } sol::table accessWhitelist = lua["xi"]["settings"]["search"]["ACCESS_WHITELIST"].get_or_create(); - for (auto const& [_, value] : accessWhitelist) + for (const auto& [_, value] : accessWhitelist) { // clang-format off auto str = value.as(); @@ -616,7 +614,7 @@ void TCPComm(SOCKET socket) } ShowInfo("Search Request: %s (%u), size: %u, ip: %s", - searchTypeToString(PTCPRequest.getPacketType()), PTCPRequest.getPacketType(), PTCPRequest.getSize(), clientIP); + searchTypeToString(PTCPRequest.getPacketType()), PTCPRequest.getPacketType(), PTCPRequest.getSize(), clientIP); switch (PTCPRequest.getPacketType()) { @@ -1117,7 +1115,7 @@ search_req _HandleSearchRequest(CTCPRequestPacket& PTCPRequest) * * ************************************************************************/ -void TaskManagerThread(bool const& requestExit) +void TaskManagerThread(const bool& requestExit) { duration next; while (!requestExit) diff --git a/src/search/tcp_request.cpp b/src/search/tcp_request.cpp index 7f111df30ad..5d0d9fc166f 100644 --- a/src/search/tcp_request.cpp +++ b/src/search/tcp_request.cpp @@ -54,8 +54,12 @@ CTCPRequestPacket::CTCPRequestPacket(SOCKET* socket) , m_socket(socket) , blowfish(blowfish_t()) { - uint8 keys[24] = { 0x30, 0x73, 0x3D, 0x6D, 0x3C, 0x31, 0x49, 0x5A, 0x32, 0x7A, 0x42, 0x43, - 0x63, 0x38, 0x7B, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + // clang-format off + uint8 keys[24] = { + 0x30, 0x73, 0x3D, 0x6D, 0x3C, 0x31, 0x49, 0x5A, 0x32, 0x7A, 0x42, 0x43, + 0x63, 0x38, 0x7B, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + // clang-format on memcpy(&key[0], &keys[0], 24); } diff --git a/src/world/conquest_system.cpp b/src/world/conquest_system.cpp index 6362ea22d39..a8f2e1521d3 100644 --- a/src/world/conquest_system.cpp +++ b/src/world/conquest_system.cpp @@ -70,9 +70,9 @@ bool ConquestSystem::handleMessage(HandleableMessage&& message) default: { ShowDebug(fmt::format("Message: unknown conquest type received: {} from {}:{}", - static_cast(conquestMsgType), - message.from_addr.s_addr, - message.from_port)); + static_cast(conquestMsgType), + message.from_addr.s_addr, + message.from_port)); } break; } @@ -223,7 +223,7 @@ bool ConquestSystem::updateInfluencePoints(int points, unsigned int nation, REGI auto rset2 = db::query("UPDATE conquest_system SET sandoria_influence = %d, bastok_influence = %d, " "windurst_influence = %d, beastmen_influence = %d WHERE region_id = %u", - influences[0], influences[1], influences[2], influences[3], static_cast(region)); + influences[0], influences[1], influences[2], influences[3], static_cast(region)); return !rset2; } diff --git a/src/world/conquest_system.h b/src/world/conquest_system.h index 13d521d73ee..4bd6487a90e 100644 --- a/src/world/conquest_system.h +++ b/src/world/conquest_system.h @@ -61,8 +61,8 @@ class ConquestSystem : public IMessageHandler private: bool updateInfluencePoints(int points, unsigned int nation, REGION_TYPE region); - auto getRegionalInfluences() -> std::vector const; - auto getRegionControls() -> std::vector const; + auto getRegionalInfluences() -> const std::vector; + auto getRegionControls() -> const std::vector; void sendTallyStartMsg(); void sendInfluencesMsg(bool shouldUpdateZones, uint64 ipp = 0xFFFF); diff --git a/src/world/message_server.cpp b/src/world/message_server.cpp index 2602f3dbc7b..8bd1855e039 100644 --- a/src/world/message_server.cpp +++ b/src/world/message_server.cpp @@ -140,7 +140,7 @@ void message_server_parse(MSGSERVTYPE type, zmq::message_t* extra, zmq::message_ } ShowDebug(fmt::format("Message: Received message {} ({}) from {}:{}", - msgTypeToStr(type), static_cast(type), str(from_address), from_port)); + msgTypeToStr(type), static_cast(type), str(from_address), from_port)); while (rset->next()) { @@ -315,7 +315,7 @@ void message_server_parse(MSGSERVTYPE type, zmq::message_t* extra, zmq::message_ } } -void message_server_listen(bool const& requestExit) +void message_server_listen(const bool& requestExit) { while (!requestExit) { @@ -396,7 +396,7 @@ void cache_zone_settings() std::copy(yellMapEndpointSet.begin(), yellMapEndpointSet.end(), std::back_inserter(yellMapEndpoints)); } -void message_server_init(bool const& requestExit) +void message_server_init(const bool& requestExit) { TracySetThreadName("Message Server (ZMQ)"); @@ -409,8 +409,8 @@ void message_server_init(bool const& requestExit) zSocket->set(zmq::sockopt::rcvtimeo, 500); auto server = fmt::format("tcp://{}:{}", - settings::get("network.ZMQ_IP"), - settings::get("network.ZMQ_PORT")); + settings::get("network.ZMQ_IP"), + settings::get("network.ZMQ_PORT")); ShowInfo("Starting ZMQ Server on %s", server.c_str()); diff --git a/src/world/message_server.h b/src/world/message_server.h index 27468e632c7..e3a18828912 100644 --- a/src/world/message_server.h +++ b/src/world/message_server.h @@ -35,12 +35,12 @@ void queue_message_broadcast(MSGSERVTYPE type, zmq::message_t* extra, zmq::messa auto pop_external_processing_message() -> std::optional; -void message_server_init(bool const& requestExit); +void message_server_init(const bool& requestExit); void message_server_close(); struct message_server_wrapper_t { - message_server_wrapper_t(std::atomic_bool const& requestExit) + message_server_wrapper_t(const std::atomic_bool& requestExit) : m_thread(std::make_unique(std::bind(message_server_init, std::ref(requestExit)))) { } diff --git a/tools/requirements.txt b/tools/requirements.txt index 2f6d1307b68..30f7c1d8bfb 100644 --- a/tools/requirements.txt +++ b/tools/requirements.txt @@ -9,3 +9,4 @@ regex argparse requests bcrypt +clang-format diff --git a/tools/run_clang_format.bat b/tools/run_clang_format.bat deleted file mode 100644 index 923fe6e29c1..00000000000 --- a/tools/run_clang_format.bat +++ /dev/null @@ -1,7 +0,0 @@ -REM Run from repo root -REM Uses clang-format-15 - -for /r %cd%\src\ %%f in (*.cpp) do clang-format -style=file -i %%f -for /r %cd%\src\ %%f in (*.h) do clang-format -style=file -i %%f -for /r %cd%\modules\ %%f in (*.cpp) do clang-format -style=file -i %%f -for /r %cd%\modules\ %%f in (*.h) do clang-format -style=file -i %%f diff --git a/tools/run_clang_format.py b/tools/run_clang_format.py new file mode 100644 index 00000000000..3afa7fef664 --- /dev/null +++ b/tools/run_clang_format.py @@ -0,0 +1,73 @@ +# Run from repo root + +import os +import subprocess +import sys + +# Set exe +CLANG_FORMAT = os.path.join("tools", "clang-format.exe") + +# If a filename is provided use that, otherwise try and format the whole src and modules directories +target = None +if len(sys.argv) > 1: + target = sys.argv[1] + + if not os.path.exists(target): + print(f"Error: {target} not found") + sys.exit(1) + +if not target: + print("No target provided, formatting all files in src/ and modules/") + target = "all" + +# Check if clang-format exists +if not os.path.exists(CLANG_FORMAT): + print("clang-format not found in tools directory, looking in PATH"), + try: + result = subprocess.run( + ["clang-format", "--version"], capture_output=True, text=True, check=True + ) + print("Found clang-format in PATH") + CLANG_FORMAT = "clang-format" + except subprocess.CalledProcessError as e: + print(f"Error running clang-format: {e}") + sys.exit(1) + +# Ensure we're using clang-format-19 +print("Checking clang-format version...") +try: + result = subprocess.run( + [CLANG_FORMAT, "--version"], capture_output=True, text=True, check=True + ) + CLANG_FORMAT_VERSION = result.stdout.strip() + if "version 19" not in CLANG_FORMAT_VERSION: + print( + f"Error: clang-format version 19.x.x is required (got: {CLANG_FORMAT_VERSION})" + ) + sys.exit(1) +except subprocess.CalledProcessError as e: + print(f"Error running clang-format: {e}") + sys.exit(1) + +# Format files in src/ and modules/ directories +if target == "all": + print("Formatting src/ files...") + for root, _, files in os.walk("src"): + for file in files: + if file.endswith(".h") or file.endswith(".cpp"): + filename = os.path.join(root, file) + print(f"Formatting {filename}") + subprocess.run([CLANG_FORMAT, "-style=file", "-i", filename]) + + print("Formatting modules/ files...") + for root, _, files in os.walk("modules"): + for file in files: + if file.endswith(".h") or file.endswith(".cpp"): + filename = os.path.join(root, file) + print(f"Formatting {filename}") + subprocess.run([CLANG_FORMAT, "-style=file", "-i", filename]) +else: # Format single file + print(f"Formatting {target}") + subprocess.run([CLANG_FORMAT, "-style=file", "-i", target]) + +print("Done!") diff --git a/tools/run_clang_format.sh b/tools/run_clang_format.sh deleted file mode 100644 index eabcab5babe..00000000000 --- a/tools/run_clang_format.sh +++ /dev/null @@ -1,3 +0,0 @@ -# Run from repo root -for f in $(find src/ -name '*.h' -or -name '*.cpp'); do clang-format-15 -style=file -i $f; done -for f in $(find modules/ -name '*.h' -or -name '*.cpp'); do clang-format-15 -style=file -i $f; done