Правила форума Гаранты форума
Размещение рекламы AMX-X компилятор

Здравствуйте, гость Вход | Регистрация

Наши новости:

14-дек
24-апр
10-апр
11-апр

Мониторинг одного сервера

, Помогите доработать функцию
Статус пользователя rafic
сообщение 8.2.2013, 0:34
Сообщение #1
Стаж: 13 лет

Сообщений: 6
Благодарностей: 2
Полезность: 0

Приветствую тебя, дорогой друг!
Недавно захотелось мне вывести статистику моего сервера на сайт и начал я искать скрипт мониторинга. В интернете, да и на этом форуме в соседней теме, куча мощных скриптов мониторинга. Но мне они не к чему, так как у меня всего лишь один сервер.
Решил писать сам, тем более что я веб-разработчик.
Нашел я заветную страничку и погуглив я даже нашел уже готовые функции. Завернув их в класс я получил довольно функциональный инструмент для организации мониторинга.
НО, запустить функцию A2S_RULES - получение настроек сервера, у меня так и не вышло. Кто может сказать почему и что нужно сделать чтобы она заработала? Сейчас она не выводит ничего=(
Скрытый текст
Код
<?

class CS_Server {

    private function cutchar(&$string){
        $char = substr($string, 0, 1);
        $string = substr($string, 1);
        return $char;
    }

    private function cutbyte(&$string){
        $byte = ord(substr($string, 0, 1));
        $string = substr($string, 1);
        return $byte;
    }

    private function cutstring(&$string){
        $str = substr($string, 0, StrPos($string, chr(0)));
        $string = substr($string, StrPos($string, chr(0))+1);
        return $str;
    }

    private function cutshort(&$string){
        $short = substr($string, 0, 2);
        list(,$short) = @unpack("S", $short);
        $string = substr($string, 2);
        return $short;
    }

    private function cutlong(&$string){
        $long = substr($string, 0, 4);
        list(,$long) = @unpack("l", $long);
        $string = substr($string, 4);
        return $long;
    }

    private function pastelong($long){
        return pack("l", $long);
    }

    private function cutfloat(&$string){
        $float = substr($string, 0, 4);
        list(,$float) = @unpack("f", $float);
        $string = substr($string, 4);
        return $float;
    }

    private function request($request,$host,$port){
        $request = "\xFF\xFF\xFF\xFF".$request."\x00";
        $fp = @fsockopen('udp://'.$host, $port);
        if (!$fp) return false;
        @fwrite($fp, $request);
        socket_set_timeout($fp,1);
        $string=fread($fp,1);
        $socket_status=socket_get_status($fp);
        $socket_status=$socket_status["unread_bytes"];
        if ($socket_status == 0){
            @fclose($fp);
            return false;
        }
        $string.=fread($fp,$socket_status);
        @fclose($fp);
        return $string;
    }

    public function A2A_PING($host, $port) {
        $st = $this->request("\x69",$host,$port);
        if (!$st) return false;
        $st = substr($st, 4);
        if (substr($st, 0, 1) != "\x6A") return false; else return true;
    }

    public function A2S_INFO($host, $port) {
        $st = $this->request("\x54Source Engine Query",$host,$port);
        if (!$st) return false;
        $st = substr($st, 4);
        if (substr($st, 0, 1) == "\x49") {
            $result['Type'] = $this->cutchar($st); // Char: 'I' (0x49) - For Source
            $result['Version'] = $this->cutbyte($st); // Byte: Network version
            $result['Server Name'] = $this->cutstring($st); // String: The server's name, eg: "Recoil NZ CS Server #1"
            $result['Map'] = $this->cutstring($st); // String: The current map being played, eg: "de_dust"
            $result['Game Directory'] = $this->cutstring($st); // String: The name of the folder containing the game files, eg: "cstrike"
            $result['Game Description'] = $this->cutstring($st); // String: A friendly string name for the game type, eg: "Counter Strike: Source"
            $result['AppID'] = $this->cutshort($st); // Short: Steam Application ID
            $result['Number of players'] = $this->cutbyte($st); // Byte: The number of players currently on the server
            $result['Maximum players'] = $this->cutbyte($st); // Byte: Maximum allowed players for the server
            $result['Number of bots'] = $this->cutbyte($st); // Byte: Number of bot players currently on the server
            $result['Dedicated'] = $this->cutchar($st); // Char: 'l' for listen, 'd' for dedicated, 'p' for SourceTV
            $result['OS'] = $this->cutchar($st); // Char: Host operating system. 'l' for Linux, 'w' for Windows
            $result['Password'] = $this->cutbyte($st); // Byte: If set to 0x01, a password is required to join this server
            $result['Secure'] = $this->cutbyte($st); // Byte: if set to 0x01, this server is VAC secured
            $result['Game Version'] = $this->cutstring($st); // String: The version of the game, eg: "1.0.0.14"
        } elseif (substr($st, 0, 1) == "\x6D") {
            $result['Type'] = $this->cutchar($st); // Char: 'm' (0x6D) - For GoldSrc
            $result['Game IP'] = $this->cutstring($st); // String: Game Server IP address and port
            $result['Server Name'] = $this->cutstring($st); // String: The server's name, eg: "Recoil NZ CS Server #1"
            $result['Map'] = $this->cutstring($st); // String: The current map being played, eg: "de_dust"
            $result['Game Directory'] = $this->cutstring($st); // String: The name of the folder containing the game files, eg: "cstrike"
            $result['Game Description'] = $this->cutstring($st); // String: A friendly string name for the game type, eg: "Counter  Strike: Source"
            $result['Number of players'] = $this->cutbyte($st); // Byte: The number of players currently on the server
            $result['Maximum players'] = $this->cutbyte($st); // Byte: Maximum allowed players for the server
            $result['Version'] = $this->cutbyte($st); // Byte: Network version
            $result['Dedicated'] = $this->cutchar($st); // Char: 'l' for listen, 'd' for dedicated, 'p' for SourceTV
            $result['OS'] = $this->cutchar($st); // Char: Host operating system. 'l' for Linux, 'w' for Windows
            $result['Password'] = $this->cutbyte($st); // Byte: If set to 0x01, a password is required to join this server
            $result['IsMod'] = $this->cutbyte($st); // Byte: If set to 0x01, this byte is followed by ModInfo
            $result['Secure'] = $this->cutbyte($st); // Byte: if set to 0x01, this server is VAC secured
            $result['Number of bots'] = $this->cutbyte($st); // Byte: Number of bot players currently on the server
            if ($result['IsMod'] == 1) {
                  $result['URLInfo'] = $this->cutstring($st); // String: URL containing information about this mod
                  $result['URLDL'] = $this->cutstring($st); // String: URL to download this mod
                  $result['Nul'] = $this->cutbyte($st); // Byte: 0x00
                  $result['ModVersion'] = $this->cutlong($st); // Long: Version of the installed mod
                  $result['ModSize'] = $this->cutlong($st); // Long: The download size of this mod
                  $result['SvOnly'] = $this->cutbyte($st); // Byte: If 1 this is a server side only mod
                  $result['ClDLL'] = $this->cutbyte($st); // Byte: If 1 this mod has a custom client dll
            }
        } else return false;
        return $result;
    }

    public function A2S_SERVERQUERY_GETCHALLENGE($host, $port){
        $st = $this->request("\x57",$host,$port);
        if (!$st) return false;
        $st = substr($st, 4);
        if (substr($st, 0, 1) != "\x41") return false; else return $this->cutlong(substr($st, 1));
    }

    public function A2S_RULES($host, $port) {
        $challenge = $this->A2S_SERVERQUERY_GETCHALLENGE($host, $port);
        $st = $this->request("\x56".  $this->pastelong($challenge),$host,$port);
        if (!$st) return false;
        $st=substr($st, 4);
        if (substr($st, 0, 1) == "\x41") {
          $orolbi = substr($st, 1);
          $challenge = $this->cutlong($orolbi);
          $st = $this->request("\x56". $this->pastelong($challenge),$host,$port);
          if (!$st) return false;
          $st = substr($st, 4);
        }
        if (substr($st, 0, 1) != "\x45") return false;
        $result['Type'] = $this->cutchar($st); // Char: Should be equal to 'E'
        $result['Num Rules'] = $this->cutshort($st); // Short: The number of rules reported in response
        for ($i = 1; $i <= $result['Num Rules']; $i++) {
          $result['Rule Name'][$i] = $this->cutstring($st); // String: The name of the rule
          $result['Rule Value'][$i] = $this->cutstring($st); // String: The rule's value
        }
        return $result;
    }

    public function A2S_PLAYER($host, $port) {
        $challenge = $this->A2S_SERVERQUERY_GETCHALLENGE($host, $port);
        $st = $this->request("\x55". $this->pastelong($challenge),$host,$port);
        if (!$st) return false;
        $st = substr($st, 4);
        if (substr($st, 0, 1) == "\x41") {

          $orolbi = substr($st, 1);
          $challenge = $this->cutlong($orolbi);
          $st = $this->request("\x55". $this->pastelong($challenge),$host,$port);
          if (!$st) return false;
          $st = substr($st, 4);
        }
        if (substr($st, 0, 1) != "\x44") return false;
        $result['Type'] = $this->cutchar($st); // Char: Should be equal to 'D'
        $result['Num Players'] = $this->cutbyte($st); // Byte: The number of players reported in response
        for ($i = 1; $i <= $result['Num Players']; $i++) {
          $result['Index'][$i] = $this->cutbyte($st); // Byte: The index into [0.. Num Players] for this entry
          $result['Player Name'][$i] = $this->cutstring($st); // String: Player's name
          $result['Kills'][$i] = $this->cutlong($st); // Long: Number of kills this player has
          $result['Time connected'][$i] = $this->cutfloat($st); // Float: The time in seconds this player has been connected
        }
        return $result;
    }
}


$cs_server = new CS_Server;

echo "<br/><br/>";
print_r($cs_server->A2S_INFO("0.0.0.0",27015));
echo "<br/><br/>";
print_r($cs_server->A2S_RULES("0.0.0.0",27015));
echo "<br/><br/>";
print_r($cs_server->A2S_PLAYER("0.0.0.0",27015));
echo "<br/><br/>";
print_r($cs_server->A2A_PING("0.0.0.0",27015));

?>

Конкретно, проблема заключается в том, что функция возвращает false, а не результат. И происходит это вот на этом условии
Код
if (substr($st, 0, 1) != "\x45") return false;

Я не совсем разобрался что оно проверяет, поэтому не могу решить поставленную задачу.

Отредактировал: rafic, - 8.2.2013, 7:23
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   Цитировать сообщение
Статус пользователя jtiq
сообщение 8.2.2013, 8:56
Сообщение #2


Иконка группы

Стаж: 18 лет

Сообщений: 1717
Благодарностей: 767
Полезность: 979

Меценат Меценат

rafic, не парься
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя rafic
сообщение 8.2.2013, 11:15
Сообщение #3
Стаж: 13 лет

Сообщений: 6
Благодарностей: 2
Полезность: 0

Все конечно круто. Но при запуске я получил такое
Проблема:
Цитата
GetInfo: Packet header mismatch. (0x6d)

Что в переводу означает "Несоответствие заголовков пакета".
Решение:
Выставить в параметрах подключения
Код
define( 'SQ_ENGINE',      SourceQuery :: GOLDSOURCE );

и так же в файле \SourceQuery\SourceQuery.class.php выставить
Код
        /**
         * Engines
         */
        const GOLDSOURCE = 1;
        const SOURCE     = 1;


Проблемма:
После проделаных выше изменения у меня запустились функции
Код
        print_r( $Query->GetInfo( ) );
        print_r( $Query->GetPlayers( ) );
, но вот функция
Код
print_r( $Query->GetRules( ) );

выдает ошибку несоответствия заголовка пакетов
Цитата
GetChallenge: Packet header mismatch. (0x49)

Решение:
В разработке... кто знает как решить?

Отредактировал: rafic, - 8.2.2013, 11:51
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
Поблагодарили 1 раз
   + Цитировать сообщение
Статус пользователя jtiq
сообщение 8.2.2013, 13:29
Сообщение #4


Иконка группы

Стаж: 18 лет

Сообщений: 1717
Благодарностей: 767
Полезность: 979

Меценат Меценат

rafic, сервер не отдаёт эти загаловки, либо фаервол так настроен (если линукс), либо дпрото настроить надо

еще можно поменять местами:
print_r( $Query->GetInfo( ) );
print_r( $Query->GetPlayers( ) );
print_r( $Query->GetRules( ) );

есть такой косяк непонятный
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя rafic
сообщение 8.2.2013, 14:26
Сообщение #5
Стаж: 13 лет

Сообщений: 6
Благодарностей: 2
Полезность: 0

Я писал автору и он сказал
Цитата
Get Steam.

Можно попробовать дописать скрипт до работы с Non-Steam серверами. Но я пока не знаю как это сделать=(
Может кто владеет информацией?

Поменять местами не вариант. Функции должны работать отдельно друг от друга, а не находится в зависимости. Но я попробую
Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
Статус пользователя rafic
сообщение 10.2.2013, 16:35
Сообщение #6
Стаж: 13 лет

Сообщений: 6
Благодарностей: 2
Полезность: 0

Цитата(AxuJIJI @ 8.2.2013, 13:29) *
rafic, сервер не отдаёт эти загаловки, либо фаервол так настроен (если линукс), либо дпрото настроить надо

еще можно поменять местами:
print_r( $Query->GetInfo( ) );
print_r( $Query->GetPlayers( ) );
print_r( $Query->GetRules( ) );

есть такой косяк непонятный

А как настроить Dproto на работу с этим классом?
моя версия dropto 0.9.179 со стандартными настройками
Скрытый текст
#
# General rule for modifying this file:
# DONT CHANGE ANYTHING IF YOU DONT KNOW WHAT IT MEANS
#

# ========================================================
# DPROTO CONFIGURATION
# ========================================================

# LoggingMode:
# 1 = Console
# 2 = Log Files
# 3 = Both
LoggingMode = 2


# ========================================================
# AUTHID MANAGEMENT
# ========================================================

# ClientID types (for cid_* options)
# 1: Real (or generated by HW) steam (STEAM_xx:xx:xx)
# 2: Real (or generated by HW) valve (VALVE_xx:xx:xx)
# 3: STEAM_ by IP
# 4: VALVE_ by IP
# 5: Deprecated - client will be rejected
# 6: reserved for future use
# 7: HLTV
# 8: STEAM_ID_LAN
# 9: STEAM_ID_PENDING
# 10: VALVE_ID_LAN
# 11: VALVE_ID_PENDING
# 12: STEAM_666:88:666

# Use these options to set authid's for clients

# for HLTV (default is HLTV [7] )
cid_HLTV = 7

# for p.47 clients that do not support unique id generation (default is STEAM_ID_LAN [8] )
cid_NoSteam47 = 8

# for p.48 clients that do not support unique id generation (default is VALVE_ID_LAN [10] )
cid_NoSteam48 = 10

# For Legit Steam clients (default is real STEAM_xx:xx:xx [1])
cid_Steam = 1

# Client recognized as pending when they sucessfully authorized, but did not get steam id
# REMARK: Actually, it got steamid, but it is useless (STEAM_0:0:0 for example)
# default is STEAM_ID_PENDGIND [9]
cid_SteamPending = 9

# For players having revEmu ( >= 9.74) on client-side:
# default is real STEAM_xx:xx:xx [1]
cid_RevEmu = 1

# For players having SteamClient 2009 / revEmu > 9.82 on client-side:
# default is real STEAM_xx:xx:xx [1]
cid_SC2009 = 1

# For players having old revEmu on client-side:
# default is real STEAM_xx:xx:xx [1]
cid_OldRevEmu = 1

# For players having hCupa's SteamEmu on client-side:
# default is real STEAM_xx:xx:xx [1]
cid_SteamEmu = 1

# For players having AVSMP (Cracked Steam) on client-side:
# default is real STEAM_xx:xx:xx [1]
cid_AVSMP = 1

# For SETTI ServerScanner
# default is STEAM_xx:xx:xx generated by IP [3]
cid_Setti = 3

# For SXEI Clients
# default is real STEAM_xx:xx:xx [1]
cid_SXEI = 1

# EnableSXEIdGeneration (0 / 1)
# Turns on steamid generation based on info sent by sXeI client
# Enable this only if you have sXeI server installed!
EnableSXEIdGeneration = 0

# SC2009_RevCompatMode (0 / 1)
# Enable fix to make steamids generated for SC2009 compatibble with revEmu
SC2009_RevCompatMode = 1

# SteamEmuCompatMode (0 / 1)
# An analog for eSTEAMATiON's EnforceSteamEmuCompatIDMode option.
# Affects only Old RevEmu and SteamEmu emulators.
SteamEmuCompatMode = 1

# OldEstCompatMode (0 / 1)
# Enables/Disables fix for steamids generated by eST in 0.3.1 version.
# Set this to 1 if you want to make steamids generated by eST as in < 0.3.0 versions.
OldEstCompatMode = 0

# IPGen_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by IP
IPGen_Prefix1 = 0

# IPGen_Prefix2 (int)
# STEAM_a:b:c
# second prefix (b) for authids generated by IP
IPGen_Prefix2 = 4

# Native_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by native auth method (Steam)
Native_Prefix1 = 0;

# RevEmu_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by Steamclient 2009
SC2009_Prefix1 = 0;

# RevEmu_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by RevEmu
RevEmu_Prefix1 = 0;

# OldRevEmu_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by old RevEmu
OldRevEmu_Prefix1 = 0;

# SteamEmu_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids generated by SteamEmu
SteamEmu_Prefix1 = 0;

# SteamEmu_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids assigned for AVSMP Clients (Cracked steam)
AVSMP_Prefix1 = 0;

# Setti_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids assigned for Setti server scanner
Setti_Prefix1 = 0;

# SXEI_Prefix1 (int)
# STEAM_a:b:c
# first prefix (a) for authids assigned for sXeI clients
SXEI_Prefix1 = 0;


# Note that banid will use steamid WITHOUT any prefixes!


# ========================================================
# ATTACKS SUPRESSION
# ========================================================

# FakePlayers_ConnectInitiationCheck (seconds)
# Sets the time, in seconds, in which client should initiate
# game session (in other words, send the "new" command) after it has
# been connected. If client did not initiated game session, it will be marked as
# fake and kicked.
# Default is 6 seconds.
# Use 0 to disable this check.
FakePlayers_ConnectInitiationCheck = 6

# FakePlayers_ClientValidationCheck (seconds)
# Sets the time, in seconds, in which client should answer to random unique command
# sent by server. If client did not answered for this command, it will be marked as
# fake and kicked.
# Default is 8 seconds.
# Use 0 to disable this check.
FakePlayers_ClientValidationCheck = 8

# FakePlayers_AntiReconnect (0/1)
# Enables detection of fakeplayers that reconnects quickly (every < 10 seconds)
# before fake players checks have completed.
# This check will work only if FakePlayers_ClientValidationCheck and
# FakePlayers_ConnectInitiationCheck are enabled.
# Default is 1 (ON)
FakePlayers_AntiReconnect = 1

# FakePlayers_BanTime (minutes)
# Dproto will ban IP spamming fakeplayers for time (in minutes) specified in this variable
# use 0 for permanent ban
# use negative vaules to disable ban (fake players will only be kicked)
FakePlayers_BanTime = 120

# ========================================================
# OTHER STUFF
# ========================================================

# DisableNativeAuth (0/1)
# Disables valve/steam auth system.
# For p.47 Based: Server will not connect to auth servers.
# For All: Server will not call authorization functions.
# This is a fix for startup freeze for old (p.47) servers.
DisableNativeAuth = 0

# ServerInfoAnswerType (0/1)
# Sets server answer type for query requests
# 0 = New style (Source Engine)
# 1 = Old Style (Fix favorites list for p.47 clients)
# 2 = Hybrid mode - best solution for now, server is visible anywhere
ServerInfoAnswerType = 2

# Game_Name (string)
# Sets game name displayed for clients
# If Game_Name is empty, native game name will be used
Game_Name =

# Enables fix for proper player id displaing on HLStats server monitoring
# Enable this only if you have HLStats
HLStatsPlayerIdFix = 0

# ExportVersion (0 / 1)
# Enables/Disables exporting of dp_version cvar
# 1 = dp_version cvar will be exported to server rules. It will be visible in server monitoring tools (like HLSW)
# 0 = dp_version cvar will not be exported to server rules.
ExportVersion = 1

# HLTVExcept_IP (ip addr)
# HLTV from this IP will be able to join the server even if cid_HLTV is set to 5 (deprectaed)
HLTVExcept_IP = 127.0.0.1

Перейти в начало страницы         Просмотр профиля    Отправить личное сообщение
   + Цитировать сообщение
  Тема закрытаНачать новую тему
 
0 пользователей и 1 гостей читают эту тему: