og-linuxgsm/lgsm/modules/query_gsquery.py
Daniel Gibbs fef128fb7d
fix (alerts): Alerts on update uses the old game server version not the new one (#4854)
* feat: refactor update comparison output for consistency and clarity

- Replaced direct echo statements with fn_print functions for uniformity in output formatting across multiple update scripts.
- Ensured lockfile creation uses the correct syntax for variable expansion.
- Moved lock file to the same location to ensure monitor doesnt reboot at the wrong time
- Updated remote build information display to enhance readability and maintain consistency in logging.
- Removed unnecessary echo commands to streamline the output process.

* Refactor remote build version handling across multiple modules

- Updated variable names from 'remotebuildversion' to 'remotebuild' for consistency.
- Adjusted logic to check for remote build availability using the new variable name.
- Modified output messages to reflect the change in variable naming.
- Ensured all modules (update_mc.sh, update_mcb.sh, update_mta.sh, update_pmc.sh, update_ts3.sh, update_ut99.sh, update_vints.sh, update_xnt.sh) are aligned with the new naming convention for better readability and maintainability.

* fix(alert): resolve issue with servername not always being listed in title

* Moved `info_distro.sh`, `info_game.sh`, and `info_messages.sh` calls to the top of the `fn_alert_log` function for better clarity.
* Updated `alerticon` assignment to maintain consistency in alert information handling.

* fix(alert_discord): remove "More info" field from Discord alert JSON

* Eliminated the "More info" field to streamline the alert message.
* This change enhances the clarity of the alert by focusing on essential information.

* fix(alert): improve update alert messaging for clarity

* Updated alert messages in `fn_alert_update` and `fn_alert_update_failed` for better readability.
* Changed alert action from `update-request` to `update-restart-request` in `fn_monitor_check_update_source`.

* remove inline

* fix(alert): Correct grammar in update alert message

* Changed "an LinuxGSM update" to "a LinuxGSM update" for grammatical accuracy.

* typo

* fix(alert_discord): Add inline property to "Is my Game Server Online?" field

* Ensures proper formatting of the Discord alert message.
* Improves the display of the server status information.

* fix(pd): increase timeout for termbin.com connection

* fix(alert_discord): reorder fields in Discord alert JSON

* Changed the order of fields in the Discord alert JSON structure.
* Updated the "More info" and "Is my Game Server Online?" fields for better clarity.

* revert back to factorio.com

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Standardizes alert messages across platforms

Ensures consistency in alert messages across Discord, NTFY,
Pushover, Rocketchat, Slack, and Telegram.

Updates Discord alerts to include server hostname and time,
removes redundant formatting.

Standardizes plain-text alert formatting for NTFY.

Refactors Pushover messages to use consistent HTML formatting.

Streamlines Rocketchat and Slack messages by removing duplicate
server info and adding optional link support.

* Removes Hostname from alert messages

Removes the Hostname field from various alert messages (Discord, Gotify, IFTTT, ntfy, Pushbullet, Pushover, Rocketchat, Slack, Telegram).

The hostname was deemed redundant or unnecessary in the context of these alerts.

Relates to #4696

* Configures shellcheckrc filename

Configures the Super-Linter action to use `.shellcheckrc` as the
BASH_FILE_NAME. This ensures that shellcheck uses the correct
configuration file for bash script linting.

Fixes #4696

* Disables shellcheck errors and removes variable

Disables specific shellcheck errors to allow certain coding
patterns and removes an unused variable from the super-linter
workflow. This improves the linter's signal-to-noise ratio
and reduces unnecessary checks.

Relates to #4696

* Fixes and improves server list validation scripts

Addresses issues in the server list validation scripts:

- Fixes potential issues with parsing curl custom arguments in telegram alerts.
- Corrects the shortname array generation.
- Implements more robust checks for validating game icons.
- Ensures the consistency of server counts across different CSV files.

* Fixes glibc check and mod selection logic

Corrects glibc version comparison to properly handle version strings.

Improves mod installation and removal by validating user input
against available options, providing a more robust selection process.
This prevents errors caused by invalid mod names and enhances the
user experience.

Updates arithmetic expression syntax for better compatibility.

* Fixes cache control for dev-debug mode

Updates the handling of cache control headers in dev-debug mode.
The `nocache` variable is changed to an array to correctly pass multiple headers to `curl`.
This resolves issues with cached versions of files being used when dev-debug is enabled, ensuring that the latest versions are always fetched.

Fixes #4696

* Allows spaces in steamcmdcommand variable

Parses steamcmdcommand as an array to allow spaces in the
variable.

This prevents issues when the user wants to pass arguments
with spaces to the steamcmd executable.

* Addresses various script improvements

Addresses multiple improvements across various scripts:

- Fixes Valheim unstripped_corlib override by commenting out the lines in the config files.
- Improves process identification for source and goldsrc engines using `pgrep`.
- Enhances backup file identification using `find` with `-maxdepth 1` and `-type f`.
- Fixes glibc version comparison logic in multiple files.
- Improves UT2K4 key installation script by using printf for writing the key to the file.
- Corrects the mod info extraction logic to correctly identify mod entries.
- Improves amxmodx file installation/removal logic to prevent duplicate entries.
- Fixes server info retrieval to handle spaces in the server list.

Relates to #4696

* Fixes mono repo install exit code check

Corrects the mono repo install exit code check to use the dedicated monorepoexitcode variable, ensuring accurate error detection.

Updates the exit trap to preserve the original exit status, preventing potential loss of information when handling script termination.

* Refactors and reorders core modules

Improves module loading by reordering and refactoring the core modules.

This change addresses inconsistencies and improves the overall structure
of how core modules are handled within the system.
Some fix scripts were renamed to match the module name.

* Makes scripts executable

Changes file permissions to make shell scripts executable.
This ensures that the scripts can be run directly.

Addresses a pre-existing issue.
Related to #4696

* Adds explicit permissions to workflows

Specifies explicit permissions for GitHub Actions workflows to enhance security and control access to resources.

This ensures that each workflow only has the necessary permissions, following the principle of least privilege.

* Fixes output redirection and URL parsing

Corrects output redirection in GitHub Actions workflows by enclosing the $GITHUB_OUTPUT variable in quotes, preventing potential issues with variable expansion.

Ensures proper URL parsing in workflows by enclosing the URL within quotes, addressing potential parsing errors.

Fixes #4696

* Applies code formatting for consistency

Applies Prettier formatting to the codebase for improved
readability and consistency.

Addresses minor code style inconsistencies across several files.

* Fixes minor formatting and logic issues

Addresses various minor issues including:

- Standardizes indentation in `.editorconfig` for different file types.
- Simplifies Prettier configuration.
- Updates image links in `README.md`.
- Ensures newline character at end of `.csv` files.
- Corrects a conditional statement in `command_fastdl.sh`.
- Corrects a conditional statement in `info_messages.sh`.
- Updates server query protocols in `query_gsquery.py`.

* Configures and disables linters

Adds YAML linting configuration and disables unnecessary
linters to streamline the CI/CD process and reduce
noise from irrelevant checks.

* Improves documentation and linting

Updates documentation links to be enclosed in angle brackets, preventing markdown rendering issues.

Configures markdownlint to align with repository standards and avoid common false positives.

The updated links in the documentation ensure they are correctly interpreted by markdown parsers, improving user experience.

The markdownlint configuration fine-tunes linting rules to better match the project's existing style and conventions, reducing noise from irrelevant warnings.

* Fixes typos and improves code consistency

Addresses various typos and inconsistencies across multiple files,
enhancing code readability and maintainability.

Adds codespell and flake8 configurations for linting.

Relates to #4696

* Excludes workflow files from Prettier formatting

Prevents Prettier from formatting workflow files due to GitHub token restrictions, as the token used by the Prettier auto-commit action lacks permissions to update files within the `.github/workflows/` directory.

* chore(prettier): format code

* Updates Super-Linter configuration

Improves Super-Linter's reliability by switching to linting the entire codebase instead of relying on git history. This change also addresses potential transient fetch failures from GitHub.

Additionally, this commit expands the ignored paths in codespell and disables some linters to improve performance and reduce false positives.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: dgibbs64 <dgibbs64@users.noreply.github.com>
2026-03-12 22:37:36 +00:00

211 lines
6.3 KiB
Python

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# LinuxGSM query_gsquery.py module
# Author: Daniel Gibbs
# Contributors: https://linuxgsm.com/contrib
# Website: https://linuxgsm.com
# Description: Allows querying of various game servers.
"""Query game servers using a set of lightweight UDP protocols."""
import argparse
import socket
import sys
engine_types = (
"protocol-valve",
"protocol-quake2",
"protocol-quake3",
"protocol-gamespy1",
"protocol-unreal2",
"ut3",
"minecraft",
"minecraftbe",
"jc2m",
"mumbleping",
"soldat",
"teeworlds",
)
class GSQuery:
"""Game server query dispatcher."""
server_response_timeout = 2
default_buffer_length = 1024
sourcequery = (
"protocol-valve",
"avalanche3.0",
"barotrauma",
"madness",
"quakelive",
"realvirtuality",
"refractor",
"source",
"goldsrc",
"spark",
"starbound",
"unity3d",
"unreal4",
"wurm",
)
idtech2query = ("protocol-quake2", "idtech2", "quake", "iw2.0")
idtech3query = ("protocol-quake3", "iw3.0", "ioquake3", "qfusion")
minecraftquery = ("minecraft", "lwjgl2")
minecraftbequery = ("minecraftbe",)
jc2mquery = ("jc2m",)
mumblequery = ("mumbleping",)
soldatquery = ("soldat",)
twquery = ("teeworlds",)
unrealquery = ("protocol-gamespy1", "unreal")
unreal2query = ("protocol-unreal2", "unreal2")
unreal3query = ("ut3", "unreal3")
def __init__(self, arguments):
"""Create a query instance from parsed CLI args."""
self.argument = arguments
#
if self.argument.engine in self.sourcequery:
self.query_prompt_string = b"\xff\xff\xff\xffTSource Engine Query\0"
elif self.argument.engine in self.idtech2query:
self.query_prompt_string = b"\xff\xff\xff\xffstatus\x00"
elif self.argument.engine in self.idtech3query:
self.query_prompt_string = b"\xff\xff\xff\xffgetstatus"
elif self.argument.engine in self.jc2mquery:
self.query_prompt_string = b"\xfe\xfd\x09\x10\x20\x30\x40"
elif self.argument.engine in self.minecraftquery:
self.query_prompt_string = b"\xfe\xfd\x09\x3d\x54\x1f\x93"
elif self.argument.engine in self.minecraftbequery:
self.query_prompt_string = (
b"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00"
b"\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
)
elif self.argument.engine in self.mumblequery:
self.query_prompt_string = (
b"\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08"
)
elif self.argument.engine in self.soldatquery:
self.query_prompt_string = b"\x69\x00"
elif self.argument.engine in self.twquery:
self.query_prompt_string = b"\x04\x00\x00\xff\xff\xff\xff\x05" + bytearray(
511
)
elif self.argument.engine in self.unrealquery:
self.query_prompt_string = b"\x5c\x69\x6e\x66\x6f\x5c"
elif self.argument.engine in self.unreal2query:
self.query_prompt_string = b"\x79\x00\x00\x00\x00"
elif self.argument.engine in self.unreal3query:
self.query_prompt_string = b"\xfe\xfd\x09\x00\x00\x00\x00"
self.connected = False
self.response = None
@staticmethod
def fatal_error(error_message, error_code=1):
"""Write an error message to stderr and exit."""
sys.stderr.write("ERROR: " + str(error_message) + "\n")
sys.exit(error_code)
@staticmethod
def exit_success(success_message=""):
"""Write a success message to stdout and exit."""
sys.stdout.write("OK: " + str(success_message) + "\n")
sys.exit(0)
def responding(self):
"""Send a single UDP query and print the response."""
# Connect.
connection = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection.settimeout(self.server_response_timeout)
try:
self.connected = connection.connect(
(self.argument.address, int(self.argument.port))
)
except socket.timeout:
self.fatal_error("Request timed out", 1)
except OSError:
self.fatal_error("Unable to connect", 1)
# Send.
connection.send(self.query_prompt_string)
# Receive.
try:
self.response = connection.recv(self.default_buffer_length)
except socket.error:
self.fatal_error("Unable to receive", 2)
connection.close()
# Response.
if self.response is None:
self.fatal_error("No response", 3)
if len(self.response) < 5:
sys.exit("Short response.", 3)
else:
self.exit_success(str(self.response))
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Allows querying of various game servers.",
usage="usage: python3 %(prog)s [options]",
add_help=False,
)
parser.add_argument(
"-a",
"--address",
type=str,
required=True,
help="The IPv4 address of the server.",
)
parser.add_argument(
"-p",
"--port",
type=int,
required=True,
help="The IPv4 port of the server.",
)
parser.add_argument(
"-e",
"--engine",
metavar="ENGINE",
choices=engine_types,
help="Engine type: " + " ".join(engine_types),
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Display verbose output.",
)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="Display debugging output.",
)
parser.add_argument(
"-V",
"--version",
action="version",
version="%(prog)s 0.0.1",
help="Display version and exit.",
)
parser.add_argument("-h", "--help", action="help", help="Display help and exit.")
return parser.parse_args()
def main():
"""CLI entrypoint."""
arguments = parse_args()
server = GSQuery(arguments)
server.responding()
if __name__ == "__main__":
main()