Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?PHP
- /**
- * Created by Gachl
- * admin@bloodisgood.org
- * Please give credit where credit belongs.
- *
- * Resources used:
- * * http://php.net/pack
- * * https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
- * * My own Rust server
- *
- * License: http://creativecommons.org/licenses/by-nc-sa/4.0/
- */
- class RustRcon
- {
- private $debug = false; // activate this flag if you want to see verbose communication
- private $read_timeout = 2; // 2 seconds read timeout
- private $packet_id = 0;
- private $stream;
- public function Connect($server, $port, $rcon_password)
- {
- $error = 0;
- $errorstring = "";
- $this->stream = @fsockopen("tcp://$server", intval($port), $error, $errorstring);
- if ($error !== 0 || $errorstring !== "")
- throw new Exception("Could not connect to rust server: Error($error) $errorstring.");
- stream_set_timeout($this->stream, 1); // don't take too long for requests
- $auth = $this->internal_send(++$this->packet_id, 3, $rcon_password);
- $this->read(); $this->read(); // discard auth messages (throws error on rcon pass)
- }
- public function Disconnect()
- {
- fclose($this->stream);
- }
- public function Send($command)
- {
- $this->internal_send(++$this->packet_id, 2, $command);
- $response[] = $this->read();
- while ($response[count($response) - 1] != null) // read the shit out of the server
- $response[] = $this->read();
- return $response;
- }
- private function internal_send($packet_id, $packet_type, $packet_body)
- {
- $request = pack('VV', $packet_id, $packet_type) . $packet_body . "\x00\x00";
- $request = Pack('V', strlen($request)) . $request;
- if ($this->debug)
- {
- echo "> LEN " . strlen($request) . "\n" .
- "> ID $packet_id\n" .
- "> TYPE $packet_type\n" .
- "> BODY $packet_body\n\n\n";
- }
- fwrite($this->stream, $request); // Give no shits about how much data was sent
- }
- private function read()
- {
- // wait 100 cycles if feof (unlikely)
- $i = 0;
- while (feof($this->stream))
- {
- if (++$i > 100)
- return null; // nope.
- }
- // try to read the packet size n times before aborting (n seconds)
- $szr = fread($this->stream, 4);
- $i = 0;
- while (strlen($szr) == 0)
- {
- if (++$i > $this->read_timeout)
- return null; // more nope.
- $szr = fread($this->stream, 4);
- }
- // Let's do this
- $size = unpack('V', $szr);
- $id = unpack('V', fread($this->stream, 4));
- $type = unpack('V', fread($this->stream, 4));
- $body = fread($this->stream, $size[1] - 8);
- if ($this->debug)
- {
- echo "< LEN ${size[1]}\n" .
- "< ID ${id[1]}" . ($id[1] == 0xffffffff ? ' (-1)' : '') . "\n" .
- "< TYPE ${type[1]}\n" .
- "< BODY " . $body . "\n\n\n";
- }
- if ($id[1] == 0xffffffff)
- throw new Exception("Rcon password invalid.");
- return $body;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement