Initial Linux agent repository

This commit is contained in:
Frank Harris 2026-06-08 10:48:00 -05:00
commit ff2cb0d399
235 changed files with 40477 additions and 0 deletions

198
ArmaBE/ArmaBE.pm Normal file
View file

@ -0,0 +1,198 @@
# ArmaBE - Perl extension BattlEye ARMA Rcon interface
# Original Source for BattlEye source - https://github.com/Jaegerhaus/BE-RCon-Tools
#
# $Id:$
#
package ArmaBE;
use strict;
use warnings;
use IO::Socket::INET;
# release version
our $VERSION = "0.01";
# create class
sub new {
my $class = shift;
# create object with defaults
my $self = {
hostname => undef,
port => 27015,
password => undef,
timeout => 5,
connected => 0,
authenticated => 0,
socket => undef,
sequence => 0,
};
# create object
bless($self, $class);
# initialize class instances
$self->init();
# parse constructor args
while (my ($key, $val) = splice(@_, 0, 2)) {
$key = lc($key);
if ($key eq "hostname") { $self->hostname($val) }
elsif ($key eq "port") { $self->port($val) }
elsif ($key eq "password") { $self->password($val) }
elsif ($key eq "timeout") { $self->timeout($val) }
else { print STDERR "Unknown attribute: $key\n" }
}
return $self;
}
# initialize class instances
sub init {
my $self = shift;
my $class = ref($self);
# manipulate symbol table.. gotta love perl
no strict "refs";
no warnings;
foreach my $instance (keys %$self) {
*{"${class}::${instance}"} = sub {
my $self = shift;
my $value = shift;
my $ref = \$self->{$instance};
if (defined $value) {
$$ref = $value;
return $self;
} else {
return $$ref;
}
};
}
}
# run a command and return its response
sub run {
my $self = shift;
my $command = shift;
if (!$self->connected()) {
$self->connect();
}
if (!$self->authenticated()) {
$self->authenticate();
}
if ($self->authenticated()) {
my $socket = $self->socket();
print $socket $self->packet("\1\0".$command);
return 1;
} else {
return 0;
}
}
# create tcp socket
sub connect {
my $self = shift;
my $socket = IO::Socket::INET->new(
PeerAddr => $self->hostname(),
PeerPort => $self->port(),
Timeout => $self->timeout(),
Proto => "udp",
) || die "Failed to connect: $!\n";
$self->socket($socket);
$self->connected(1);
}
# authenticate rcon session
sub authenticate {
my $self = shift;
# send authentication packet to server
my $socket = $self->socket();
print $socket $self->packet("\0".$self->password());
my $response = $self->response();
my $authenticated = int(substr($response, -1));
$self->authenticated($authenticated);
}
######################
# PROTOCOL FUNCTIONS #
######################
# rcon command protocol:
# https://www.battleye.com/downloads/BERConProtocol.txt
sub crc32 {
my ($self,$input,$init_value,$polynomial) = @_;
$init_value = 0 unless (defined $init_value);
$polynomial = 0xedb88320 unless (defined $polynomial);
my @lookup_table;
for (my $i=0; $i<256; $i++) {
my $x = $i;
for (my $j=0; $j<8; $j++) {
if ($x & 1) {
$x = ($x >> 1) ^ $polynomial;
} else {
$x = $x >> 1;
}
}
push @lookup_table, $x;
}
my $crc = $init_value ^ 0xffffffff;
foreach my $x (unpack ('C*', $input)) {
$crc = (($crc >> 8) & 0xffffff) ^ $lookup_table[ ($crc ^ $x) & 0xff ];
}
$crc = $crc ^ 0xffffffff;
return $crc;
}
# create a packet of type (AUTH or CMD)
sub packet {
my $self = shift;
my $payload = shift;
my $break = pack('C', 0xff);
my $packet = "BE"
. pack('V', $self->crc32($break . $payload))
. $break
. $payload;
return $packet;
}
# receive packet
sub response {
my $self = shift;
my $payload = $self->read();
return $payload;
}
# read length of bytes from socket with timeout
sub read {
my $self = shift;
my $received;
my $socket = $self->socket();
$socket->recv($received, 9);
return unpack('H*', $received);
}
1;
__END__

339
COPYING Normal file
View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

19
Cfg/Config.pm Normal file
View file

@ -0,0 +1,19 @@
%Cfg::Config = (
logfile => '/home/gameserver/OGP/ogp_agent.log',
listen_port => '12679',
listen_ip => '0.0.0.0',
version => 'v1.4',
key => 'Mvemjsu9p',
steam_license => 'Accept',
sudo_password => 'Inc0rrect!',
web_admin_api_key => '{your_admin_ogp_web_api_key_here}',
web_api_url => '{your_url_to_ogp_api.php}',
steam_dl_limit => '0',
# Resource stats database configuration
stats_db_host => 'mysql.iaregamer.com',
stats_db_user => 'remoteuser',
stats_db_pass => 'Pkloyn7yvpht!',
stats_db_name => 'panel',
stats_table_prefix => 'gsp_',
stats_frequency_minutes => '5',
);

9
Cfg/Preferences.pm Normal file
View file

@ -0,0 +1,9 @@
%Cfg::Preferences = (
screen_log_local => '1',
delete_logs_after => '30',
ogp_manages_ftp => '1',
ftp_method => 'PureFTPd',
ogp_autorestart_server => '1',
protocol_shutdown_waittime => '10',
linux_user_per_game_server => '1',
);

0
Cfg/empty.txt Normal file
View file

230
Crypt/XXTEA.pm Normal file
View file

@ -0,0 +1,230 @@
#/**********************************************************\
#| |
#| The implementation of PHPRPC Protocol 3.0 |
#| |
#| xxtea.pm |
#| |
#| Release 3.0.0 beta |
#| Copyright (c) 2005-2007 by Team-PHPRPC |
#| |
#| WebSite: http://www.phprpc.org/ |
#| http://www.phprpc.net/ |
#| http://www.phprpc.com/ |
#| http://sourceforge.net/projects/php-rpc/ |
#| |
#| Author: Ma Bingyao <andot@ujn.edu.cn> |
#| |
#| This file may be distributed and/or modified under the |
#| terms of the GNU Lesser General Public License (LGPL) |
#| version 3.0 as published by the Free Software Foundation |
#| and appearing in the included file LICENSE. |
#| |
#\**********************************************************/
#
# XXTEA encryption arithmetic module.
#
# Copyright (C) 2006-2007 Ma Bingyao <andot@ujn.edu.cn>
# Version: 1.00
# LastModified: Nov 7, 2007
# This library is free. You can redistribute it and/or modify it.
#
package Crypt::XXTEA;
use bytes;
use integer;
use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT);
$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(xxtea_encrypt xxtea_decrypt);
*encrypt = \&xxtea_encrypt;
*decrypt = \&xxtea_decrypt;
sub _long2str {
my ($v, $w) = @_;
my $len = @{$v};
my $n = ($len - 1) << 2;
if ($w) {
my $m = $v->[$len - 1];
if (($m < $n - 3) || ($m > $n)) {
return 0;
}
$n = $m;
}
my @s = ();
for (my $i = 0; $i < $len; $i++) {
$s[$i] = pack("V", $v->[$i]);
}
if ($w) {
return substr(join('', @s), 0, $n);
}
else {
return join('', @s);
}
}
sub _str2long {
my ($s, $w) = @_;
my @v = unpack("V*", $s. "\0"x((4 - length($s) % 4) & 3));
if ($w) {
$v[@v] = length($s);
}
return @v;
}
sub xxtea_encrypt {
my ($s, $k) = @_;
if ($s eq "") {
return "";
}
my @v = _str2long($s, 1);
my @k = _str2long($k, 0);
if (@k < 4) {
for (my $i = @k; $i < 4; $i++) {
$k[$i] = 0;
}
}
my $n = $#v;
my $z = $v[$n];
my $y = $v[0];
my $delta = 0x9E3779B9;
my $q = 6 + 52 / ($n + 1);
my $sum = 0;
my $e;
my $p;
my $mx;
while (0 < $q--) {
$sum = ($sum + $delta) & 0xffffffff;
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = ((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ (($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z)) & 0xffffffff;
$z = $v[$p] = ($v[$p] + $mx) & 0xffffffff;
}
$y = $v[0];
$mx = ((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ (($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z)) & 0xffffffff;
$z = $v[$n] = ($v[$n] + $mx) & 0xffffffff;
}
return _long2str(\@v, 0);
}
sub xxtea_decrypt {
my ($s, $k) = @_;
if ($s eq "") {
return "";
}
my @v = _str2long($s, 0);
my @k = _str2long($k, 0);
if (@k < 4) {
for (my $i = @k; $i < 4; $i++) {
$k[$i] = 0;
}
}
my $n = $#v;
my $z = $v[$n];
my $y = $v[0];
my $delta = 0x9E3779B9;
my $q = 6 + 52 / ($n + 1);
my $sum = ($q * $delta) & 0xffffffff;
my $e;
my $p;
my $mx;
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = ((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ (($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z)) & 0xffffffff;
$y = $v[$p] = ($v[$p] - $mx) & 0xffffffff;
}
$z = $v[$n];
$mx = ((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ (($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z)) & 0xffffffff;
$y = $v[0] = ($v[0] - $mx) & 0xffffffff;
$sum = ($sum - $delta) & 0xffffffff;
}
return _long2str(\@v, 1);
}
1;
__END__
=head1 NAME
Crypt::XXTEA - XXTEA encryption arithmetic module.
=head1 SYNOPSIS
use Crypt::XXTEA;
=head1 DESCRIPTION
XXTEA is a secure and fast encryption algorithm. It's suitable for web development. This module allows you to encrypt or decrypt a string using the algorithm.
=head1 FUNCTIONS
=over 4
=item xxtea_encrypt
my $ciphertext = xxtea_encrypt($plaintext, $key);
This function encrypts $plaintext using $key and returns the $ciphertext.
=item encrypt
my $ciphertext = Crypt::XXTEA::encrypt($plaintext, $key);
This function is the same as xxtea_encrypt.
=item xxtea_decrypt
my $plaintext = xxtea_decrypt($ciphertext, $key);
This function decrypts $ciphertext using $key and returns the $plaintext.
=item decrypt
my $plaintext = Crypt::XXTEA::decrypt($ciphertext, $key);
This function is the same as xxtea_decrypt.
=back
=head1 EXAMPLE
use Crypt::XXTEA;
my $ciphertext = xxtea_encrypt("Hello XXTEA.", "1234567890abcdef");
my $plaintext = xxtea_decrypt($ciphertext, "1234567890abcdef");
print $plaintext;
$ciphertext = Crypt::XXTEA::encrypt("Hi XXTEA.", "1234567890abcdef");
$plaintext = Crypt::XXTEA::decrypt($ciphertext, "1234567890abcdef");
print $plaintext;
=head1 NOTES
If $plaintext is equal to "", it returns "".
It returns 0 when fails to decrypt.
Only the first 16 bytes of $key is used. if $key is shorter than 16 bytes, it will be padding \0.
The XXTEA algorithm is stronger and faster than Crypt::DES, Crypt::Blowfish & Crypt::IDEA.
=head1 SEE ALSO
Crypt::DES
Crypt::Blowfish
Crypt::IDEA
=head1 COPYRIGHT
The implementation of the XXTEA algorithm was developed by,
and is copyright of, Ma Bingyao (andot@ujn.edu.cn).
=cut

6
DEVELOPMENT Normal file
View file

@ -0,0 +1,6 @@
OGP Agent NOTES:
Before committing code it is recommended to execute perltidy:
$ perltidy -b -gnu ogp_agent.pl

129
EHCP/addAccount.php Normal file
View file

@ -0,0 +1,129 @@
<?php
// Adds users to the database
// Variables
$success = 0;
if (isset($_GET['username'])) {
$ftp_username = $_GET['username'];
}
if (isset($_GET['password'])) {
$ftp_pass = $_GET['password'];
}
if (isset($_GET['dir'])) {
$rDir = $_GET['dir'];
}
if (isset($errors)) {
unset($errors);
}
if (file_exists("config.php")) {
include 'config.php';
} else {
die("config.php must exist within the installation root folder!");
}
include_once 'db_functions.php';
// Did we properly receive the variables from the OGP agent?
if (isset($ftp_username) && isset($ftp_pass) && isset($rDir)) {
// We received all necessary variables. Process what we received.
$errorCount = 0;
$errorInstallInt = 0;
// OGP should be doing this validation... but it's not
// Custom directory validation
if (substr_count($rDir, '/') < 2) {
$errorCount++;
$errors[] = "In order to prevent security risks, users cannot be granted access to the main directories in the root file system of the server.&nbsp; You must go down two directory levels!&nbsp; Example: /games/user1!";
}
if (stripos($rDir, "/") === FALSE || stripos($rDir, "/") != 0) {
$errorCount++;
$errors[] = "You have not chosen a valid directory!";
}
if ($rDir === "/var/www/" || stripos($rDir, "/var/www/") !== FALSE) {
$errorCount++;
$errors[] = "You may not create ftp accounts into the protected EHCP directories using this program.&nbsp; Create these accounts using EHCP software.";
}
if (stripos($rDir, "\\")) {
$errorCount++;
$errors[] = "This is not a Windows machine... use the correct slash character for path...";
}
// If the last character in the path is a slash (/) - Remove it from the string
if (substr_count($rDir, '/') >= 2 && $rDir[strlen($rDir) - 1] == "/") {
$end = strlen($rDir) - 1;
$rDir = substr($rDir, 0, $end);
}
if ($errorCount == 0) {
// Security checks
$ftp_password_db = escapeSQLStr($ftp_pass, $connection);
$ftp_username_db = escapeSQLStr($ftp_username, $connection);
$rDir = escapeSQLStr($rDir, $connection);
$SQL = "SELECT id FROM ftpaccounts WHERE ftpusername = '$ftp_username_db'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
if ($count > 0) {
$errorCount++;
$errors[] = "The FTP username supplied already exists!&nbsp; Please enter another unique username!";
} else {
// Make sure data enter is unique for homedir
$SQL = "SELECT id FROM ftpaccounts WHERE homedir = '$rDir'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
// Insert the data into the
$SQL = "INSERT INTO ftpaccounts (ftpusername, password, homedir) VALUES ('$ftp_username_db', password('$ftp_password_db'), '$rDir')";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$success = 1;
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
if ($errorCount > 0 && $success == 0) {
unset($_POST['createFTP']);
include 'admin/ftpCreateForm.php';
}
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
}
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
// Return value:
echo $success;
?>

83
EHCP/config.php Normal file
View file

@ -0,0 +1,83 @@
<?php
/*
This FTP addon works with EHCP (www.ehcp.net)
It allows OGP - the open game panel - to manage custom FTP user accounts
by own3mall
*/
@include_once "/var/www/new/ehcp/config.php";
/**********************************
* DB Creds *
* ********************************/
// Database credentials change if needed
$server = 'localhost';
$login = 'ehcp';
// Script should detect password automatically from EHCP config file above... but if not, please change the value down here.
if(!isset($dbpass) || empty($dbpass)){
$dbpass = 'changeme';
}
$dbName = 'ehcp';
$debug=false;
/**********************************
* END DB Creds *
* ********************************/
// Log File
$logFile = 'ehcp_ftp_log.txt';
function addToLog($errors) {
global $logFile, $debug;
if (!file_exists($logFile)) {
$createLog = fopen($logFile, 'a+');
if (!$createLog) {
trigger_error("Unable to create EHCP FTP Integration log file! Please create a file named \"ehcp_ftp_log.txt\" in the ogp_agent install directory under the EHCP folder with permissions of 777", E_USER_NOTICE);
}
fclose($createLog);
}
if (!is_writable($logFile)) {
$chPerm = chmod($logFile, 777);
if (!$chPerm) {
trigger_error("The $logFile file is not writable. CHMOD failed. Please manually set the chmod to 777!", E_USER_NOTICE);
}
}
$logContents = file_get_contents($logFile);
foreach ($errors as $err) {
$logContents.= $err . "\n";
if($debug){
trigger_error($err, E_USER_NOTICE);
echo $err . "\n";
}
}
$updateLog = file_put_contents($logFile, $logContents);
if (!$updateLog) {
trigger_error("Unable to write errors to the log file of $logFile", E_USER_NOTICE);
}
}
// Create the database connection
if(function_exists("mysql_connect")){
$connection = mysql_connect($server, $login, $dbpass);
if ($connection) {
mysql_select_db($dbName, $connection);
}
}else{
$connection = mysqli_connect($server, $login, $dbpass, $dbName);
}
if(!$connection){
$errToLog[] = 'Unable to connect to the EHCP MySQL database using provided credentials! Please update your config.php settings!';
addToLog($errToLog);
die('Unable to connect to the EHCP MySQL database using provided credentials! Please update your config.php settings!');
}
?>

53
EHCP/db_functions.php Normal file
View file

@ -0,0 +1,53 @@
<?php
function execSQL($SQL, $connection){
if($connection){
if(function_exists("mysql_query")){
return mysql_query($SQL, $connection);
}else{
return mysqli_query($connection, $SQL);
}
}
return false;
}
function countSQLResult($Result){
if(function_exists("mysql_num_rows")){
return mysql_num_rows($Result);
}else{
return mysqli_num_rows($Result);
}
}
function getSQLError($connection){
if(function_exists("mysql_error")){
return "Error code " . mysql_errno($connection) . ": " . mysql_error($connection);
}else{
return "Error code " . mysqli_errno($connection) . ": " . mysqli_error($connection);
}
}
function getSQLRow($Result){
if(function_exists("mysql_fetch_assoc")){
return mysql_fetch_assoc($Result);
}else{
return mysqli_fetch_assoc($Result);
}
}
function getSQLRowArray($Result){
if(function_exists("mysql_fetch_row")){
return mysql_fetch_row($Result);
}else{
return mysqli_fetch_row($Result);
}
}
function escapeSQLStr($str, $connection){
if(function_exists("mysql_real_escape_string")){
return mysql_real_escape_string($str);
}else{
return mysqli_real_escape_string($connection, $str);
}
}
?>

59
EHCP/delAccount.php Normal file
View file

@ -0,0 +1,59 @@
<?php
if (file_exists("config.php")) {
include 'config.php';
} else {
die("config.php must exist within the installation root folder!");
}
include_once 'db_functions.php';
// Deletes passed in user account from database
// Unless the actual delete command fails, success should be 1... we don't care if the account doesn't exist.
$success = 1;
$errorCount = 0;
if (isset($errors)) {
unset($errors);
}
if (isset($_GET['username'])) {
$userToDelete = $_GET['username'];
}
if (!isset($userToDelete)) {
$errorCount++;
$errors[] = "No username was passed to the form.";
} else {
$SQL = "SELECT ftpusername FROM ftpaccounts WHERE ftpusername = '$userToDelete'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE && countSQLResult($Result) == 1) {
$row = getSQLRowArray($Result);
$unameDeleted = $row[0];
}else{
$errorCount++;
$errors[] = "The specified user $userToDelete does not exist within the databse. No actions were taken!";
}
if (isset($unameDeleted)) {
$SQL = "DELETE FROM ftpaccounts WHERE ftpusername = '$userToDelete'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$success = 1;
} else {
$errorCount++;
$errors[] = getSQLError($connection);
$success = 0;
}
}
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
// Return value:
echo $success;
?>

0
EHCP/ehcp_ftp_log.txt Normal file
View file

66
EHCP/listAllUsers.php Normal file
View file

@ -0,0 +1,66 @@
<?php
// Returns a list of all custom FTP users
// Only custom users are setup when tying into the EHCP FTP API
$countNotNull = 0;
$users_list = "";
$success = 0;
$errorCount = 0;
if (isset($errors)) {
unset($errors);
}
if (!isset($connection)) {
include "config.php";
}
include_once 'db_functions.php';
if (!isset($connection)) {
die("Problem setting up connection!");
} else {
$SQL = "SELECT ftpusername, homedir, domainname, status FROM ftpaccounts";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
if ($count > 0) {
while ($row = getSQLRow($Result)) {
// Only show custom entries... do not allow to modify EHCP accounts.
// domainname field will be NULL for custom FTP entries
if (!empty($row['homedir']) && (empty($row['domainname']) || $row['domainname'] === NULL) && (empty($row['status']) || $row['status'] === NULL)) {
$countNotNull++;
$username = $row['ftpusername'];
$dir = $row['homedir'];
$users_list.= $username . "\t" . $dir . "/./\n";
}
}
if ($countNotNull == 0) {
$errorCount++;
$errors[] = "There are no custom FTP accounts yet in the EHCP database!";
}
} else {
$errorCount++;
$errors[] = "No FTP accounts exist from the ftpaccounts table!";
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
$success = 0;
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
}
// Return the user list
echo $users_list;
?>

66
EHCP/showAccount.php Normal file
View file

@ -0,0 +1,66 @@
<?php
$countNotNull = 0;
$user_details = "";
$success = 0;
$errorCount = 0;
if (isset($errors)) {
unset($errors);
}
if (!isset($connection)) {
include "config.php";
}
include_once 'db_functions.php';
if (isset($_GET['username'])) {
$ftp_account = $_GET['username'];
}
if (!isset($connection)) {
die("Problem setting up connection!");
} else
if (isset($ftp_account)) {
$SQL = "SELECT ftpusername, homedir FROM ftpaccounts WHERE ftpusername = '$ftp_account'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
if ($count == 1) {
if ($row = getSQLRow($Result)) {
// Only show custom entries... do not allow to modify EHCP accounts.
if (!empty($row['homedir'])) {
$countNotNull++;
$username = $row['ftpusername'];
$dir = $row['homedir'];
$user_details.= "Username" . " : " . $username . "\n";
$user_details.= "Directory" . " : " . $dir . "\n";
}
}
if ($countNotNull == 0) {
$errorCount++;
$errors[] = "There are no custom FTP accounts yet in the EHCP database!";
}
} else {
$errorCount++;
$errors[] = "No FTP accounts exist with the given username of $ftp_account";
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
$success = 0;
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
}
// Return the user list
echo $user_details;
?>

11
EHCP/syncftp.php Normal file
View file

@ -0,0 +1,11 @@
<?php
$curDir = getcwd();
if(chdir("/var/www/new/ehcp/")){
require ("classapp.php");
$app = new Application();
$app->connectTodb(); # fill config.php with db user/pass for things to work..
$app->addDaemonOp('syncftp', '', '', '', 'sync ftp for nonstandard homes');
}
chdir($curDir);
?>

144
EHCP/updateInfo.php Normal file
View file

@ -0,0 +1,144 @@
<?php
if (file_exists("config.php")) {
include 'config.php';
} else {
die("config.php must exist within the installation root folder!");
}
include_once 'db_functions.php';
// Updates ftpuser's password
$success = 0;
$errorCount = 0;
if (isset($errors)) {
unset($errors);
}
if (isset($_GET['username'])) {
$ftp_username = $_GET['username'];
}
if (isset($_GET['password'])) {
$arrOfVals = trim($_GET['password']);
}
if (isset($arrOfVals) && !empty($arrOfVals)) {
$arrOfVals = explode("\n", $arrOfVals);
$arrOfVals = array_filter($arrOfVals);
foreach ($arrOfVals as $passIn) {
$passIn = trim($passIn);
// Replace all tabs or spaces
$pattern = '/\s+/';
$passIn = preg_replace($pattern, ' ', $passIn);
$keyAndVal = explode(' ', $passIn);
if (count($keyAndVal) == 2) {
$arr[$keyAndVal[0]] = $keyAndVal[1];
}
if (isset($arr['new_password']) && !empty($arr['new_password'])) {
$ftp_pass = $arr['new_password'];
}
if (isset($arr['Directory']) && !empty($arr['Directory'])) {
$update_dir = $arr['Directory'];
}
if (isset($arr['orig_user']) && !empty($arr['orig_user'])) {
$ftp_old_username = $arr['orig_user'];
}
if (isset($arr['Username']) && !empty($arr['Username'])) {
$ftp_username = $arr['Username'];
}
}
}
if (!isset($ftp_username) || !isset($update_dir)) {
$errorCount++;
$errors[] = "No FTP accounts could be modified! Updated username and homedir were not sent by the panel.";
} else {
if (substr_count($update_dir, '/') < 2) {
$errorCount++;
$errors[] = "In order to prevent security risks, users cannot be granted access to the main directories in the root file system of the server.&nbsp; You must go down two directory levels!&nbsp; Example: /games/user1!";
}
if (stripos($update_dir, "/") === FALSE || stripos($update_dir, "/") != 0) {
$errorCount++;
$errors[] = "You have not chosen a valid directory!";
}
if ($update_dir === "/var/www/" || stripos($update_dir, "/var/www/") !== FALSE) {
$errorCount++;
$errors[] = "You may not create ftp accounts into the protected EHCP directories using this program.&nbsp; Create these accounts using EHCP software.";
}
if (stripos($update_dir, "\\")) {
$errorCount++;
$errors[] = "This is not a Windows machine... use the correct slash character for path...";
}
// If the last character in the path is a slash (/) - Remove it from the string
if (substr_count($update_dir, '/') > 2 && $update_dir[strlen($update_dir) - 1] == "/") {
$end = strlen($update_dir) - 1;
$update_dir = substr($update_dir, 0, $end);
}
if ($errorCount == 0) {
// Security checks
if (isset($ftp_pass)) {
$ftp_password_db = escapeSQLStr($ftp_pass, $connection);
}
$ftp_username_db = escapeSQLStr($ftp_username, $connection);
$SQL = "SELECT * FROM ftpaccounts WHERE ftpusername = '$ftp_username_db'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
if ($count != 1) {
$errorCount++;
$errors[] = "FTP User " . $ftp_username . " does not exist in the database. Account information cannot be updated";
} else {
// Update user's password data into DB:
$SQL = "UPDATE ftpaccounts SET ";
if (isset($ftp_password_db)) {
$SQL.= "password=password('$ftp_password_db'), ";
}
$SQL.= "homedir='$update_dir' WHERE ftpusername='$ftp_username_db'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$success = 1;
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
}
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
// Return value:
echo $success;
?>

76
EHCP/updatePass.php Normal file
View file

@ -0,0 +1,76 @@
<?php
if (file_exists("config.php")) {
include 'config.php';
} else {
die("config.php must exist within the installation root folder!");
}
include_once 'db_functions.php';
// Updates ftpuser's password
$success = 0;
$errorCount = 0;
if (isset($errors)) {
unset($errors);
}
if (isset($_GET['username'])) {
$ftp_username = $_GET['username'];
}
if (isset($_GET['password'])) {
$ftp_pass = trim($_GET['password']);
}
if (!isset($ftp_username) || !isset($ftp_pass)) {
$errorCount++;
$errors[] = "No FTP accounts could be modified! Updated username and password were not sent by the OGP upload functions.";
} else {
if ($errorCount == 0) {
// Security checks
$ftp_password_db = escapeSQLStr($ftp_pass, $connection);
$ftp_username_db = escapeSQLStr($ftp_username, $connection);
$SQL = "SELECT * FROM ftpaccounts WHERE ftpusername = '$ftp_username_db'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$count = countSQLResult($Result);
if ($count != 1) {
$errorCount++;
$errors[] = "The account information was not updated because the FTP username $ftp_old_username never existed in the first place and cannot be modified";
} else {
if ($row = getSQLRow($Result)) {
$recordID = $row['id'];
}
// Update user's password data into DB:
$SQL = "UPDATE ftpaccounts SET password=password('$ftp_password_db') WHERE ftpusername='$ftp_username_db'";
$Result = execSQL($SQL, $connection);
if ($Result !== FALSE) {
$success = 1;
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
}
} else {
$errorCount++;
$errors[] = getSQLError($connection);
}
}
}
// Log errors
if ($errorCount > 0) {
addToLog($errors);
}
// Return value:
echo $success;
?>

View file

@ -0,0 +1,333 @@
use strict;
use warnings;
use lib ".";
use FastDownload::Settings; # Daemon Settings
use Cwd; # Fast way to get the current directory
use Fcntl ':flock'; # Import LOCK_* constants for file locking
use File::Copy; # Simple file copy functions
use Path::Class::File; # Handle files and directories.
use HTTP::Daemon; # Create the Fast Download Daemon.
use URI::Escape; # Translate url code for example: %20 to space
use Socket qw( inet_aton ); # Work with network addresses.
use constant RUN_DIR => getcwd();
use constant FD_DIR => Path::Class::Dir->new(RUN_DIR, 'FastDownload');
use constant FD_ALIASES_DIR => Path::Class::Dir->new(FD_DIR, 'aliases');
use constant FD_PID_FILE => Path::Class::File->new(FD_DIR, 'fd.pid');
use constant FD_LOG_FILE => Path::Class::File->new(FD_DIR, 'fastdownload.log');
### Logger function.
### @param line the line that is put to the log file.
sub logger
{
my $logcmd = $_[0];
my $also_print = 0;
if (@_ == 2)
{
($also_print) = $_[1];
}
$logcmd = localtime() . " $logcmd\n";
if ($also_print == 1)
{
print "$logcmd";
}
open(LOGFILE, '>>', FD_LOG_FILE)
or die("Can't open " . FD_LOG_FILE . " - $!");
flock(LOGFILE, LOCK_EX) or die("Failed to lock log file.");
seek(LOGFILE, 0, 2) or die("Failed to seek to end of file.");
print LOGFILE "$logcmd" or die("Failed to write to log file.");
flock(LOGFILE, LOCK_UN) or die("Failed to unlock log file.");
close(LOGFILE) or die("Failed to close log file.");
}
# Rotate the log file
if (-e FD_LOG_FILE)
{
if (-e FD_LOG_FILE . ".bak")
{
unlink(FD_LOG_FILE . ".bak");
}
logger "Rotating log file";
move(FD_LOG_FILE, FD_LOG_FILE . ".bak");
logger "New log file created";
}
if (open(PIDFILE, '>', FD_PID_FILE))
{
print PIDFILE $$;
close(PIDFILE);
}
$SIG{'PIPE'} = 'IGNORE';
my $fd = HTTP::Daemon->new(LocalAddr=>$FastDownload::Settings{ip},
LocalPort=>$FastDownload::Settings{port},
ReuseAddr=>'1') || die;
logger "Fast Download Daemon Started at: <URL:" . $fd->url . "> - PID $$",1;
my %aliases;
if(-d FD_ALIASES_DIR)
{
if( !opendir(ALIASES, FD_ALIASES_DIR) )
{
logger "Error openning aliases directory " . FD_ALIASES_DIR . ", $!";
}
else
{
while (my $alias = readdir(ALIASES))
{
# Skip . and ..
next if $alias =~ /^\./;
if( !open(ALIAS, '<', Path::Class::Dir->new(FD_ALIASES_DIR, $alias)) )
{
logger "Error reading alias '$alias', $!";
}
else
{
my @file_lines = ();
my $i = 0;
while (<ALIAS>)
{
chomp $_;
$file_lines[$i] = $_;
$i++;
}
close(ALIAS);
$aliases{$alias}{home} = $file_lines[0];
$aliases{$alias}{match_file_extension} = $file_lines[1];
$aliases{$alias}{match_client_ip} = $file_lines[2];
}
}
closedir(ALIASES);
}
}
else
{
logger "Aliases directory '" . FD_ALIASES_DIR . "' does not exist or is inaccessible.";
}
$SIG{CHLD} = 'IGNORE';
while (my $c = $fd->accept) {
my $pid = fork();
if (not defined $pid)
{
logger "Could not allocate resources for Fast Download Client.",1;
}
# Only the forked child goes here.
elsif ($pid == 0)
{
if(%aliases)
{
while(my $r = $c->get_request) {
process_client_request($FastDownload::Settings{listing}, $r, $c);
$c->close;
}
}
else
{
while(my $r = $c->get_request) {
$c->send_error(403,"");
$c->close;
}
}
undef($c);
# Child process must exit.
exit(0);
}
}
sub process_client_request
{
my($listing, $r, $c) = @_;
my @uri_alias = split /\//, $r->uri->path;
if(defined $uri_alias[1])
{
my $alias = $uri_alias[1];
if ($r->method eq 'GET' and defined $aliases{$alias})
{
my $home = $aliases{$alias}{home};
my (@extensions,@subnets);
if(defined $aliases{$alias}{match_file_extension})
{
@extensions = split /,/, $aliases{$alias}{match_file_extension};
}
if(defined $aliases{$alias}{match_client_ip})
{
@subnets = split /,/, $aliases{$alias}{match_client_ip};
}
my $client = getpeername($c);
my ($port, $iaddr) = unpack_sockaddr_in($client);
my $client_ip = inet_ntoa($iaddr);
my $uri = uri_unescape($r->uri->path);
my $escaped_alias = "\/" . $alias;
$uri =~ s/^$escaped_alias//g;
my $location = $home . $uri;
my $is_subnet;
if(!grep {defined($_)} @subnets)
{
$is_subnet = 1;
}
else
{
foreach my $subnet (@subnets)
{
$is_subnet = in_subnet($client_ip, $subnet);
if($is_subnet)
{
last;
}
}
}
if($is_subnet)
{
if(-d $location)
{
my $index = $location . "/" . "index.html";
if(-f $index)
{
$c->send_file_response($index);
}
else
{
if($listing == 1)
{
# Loop through all files and folders
my @dirs = ();
my @bins = ();
my @files = ();
opendir(DIR, $location);
while (my $entry = readdir(DIR))
{
# Skip . and ..
next if $entry =~ /^\./;
my $link_location = $location."/".$entry;
if(-d $link_location)
{
push(@dirs, $entry);
}
elsif(-B $link_location)
{
push(@bins, $entry);
}
else
{
push(@files, $entry);
}
}
closedir(DIR);
@dirs = sort @dirs;
@bins = sort @bins;
@files = sort @files;
my ($content, $href);
foreach my $dir (@dirs)
{
$href = Path::Class::Dir->new($r->uri->path, $dir);
$content .= "<a href='" . $href . "' >".$dir."</a><br>";
}
foreach my $bin (@bins)
{
$href = Path::Class::File->new($r->uri->path, $bin);
$content .= "<a href='" . $href . "' >".$bin."</a><br>";
}
foreach my $file (@files)
{
$href = Path::Class::File->new($r->uri->path, $file);
$content .= "<a href='" . $href . "' >".$file."</a><br>";
}
my $response = HTTP::Response->new(200);
$response->content($content);
$response->header("Content-Type" => "text/html");
$c->send_response($response);
}
else
{
$c->send_error(403,"");
}
}
}
else
{
my @extension = split /\./, $uri;
my $extension = $extension[-1];
if(grep {$_ eq $extension} @extensions or !grep {defined($_)} @extensions)
{
$c->send_file_response($location);
}
else
{
$c->send_error(403,"");
}
}
}
else
{
$c->send_error(403,"");
}
}
else
{
$c->send_error(403,"");
}
}
else
{
$c->send_error(403,"");
}
}
sub ip2long($)
{
return( unpack( 'N', inet_aton(shift) ) );
}
sub in_subnet($$)
{
my $ip = shift;
my $subnet = shift;
my $ip_long = ip2long( $ip );
if( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$| )
{
my $subnet = ip2long($1);
my $mask = ip2long($2);
if( ($ip_long & $mask)==$subnet )
{
return 1;
}
}
elsif( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$| )
{
my $subnet = ip2long($1);
my $bits = $2;
my $mask = -1<<(32-$bits);
$subnet&= $mask;
if( ($ip_long & $mask)==$subnet )
{
return 1;
}
}
elsif( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})$| )
{
my $start_ip = ip2long($1.$2);
my $end_ip = ip2long($1.$3);
if( $start_ip<=$ip_long and $end_ip>=$ip_long )
{
return 1;
}
}
elsif( $subnet=~m|^[\d\*]{1,3}\.[\d\*]{1,3}\.[\d\*]{1,3}\.[\d\*]{1,3}$| )
{
my $search_string = $subnet;
$search_string=~s/\./\\\./g;
$search_string=~s/\*/\.\*/g;
if( $ip=~/^$search_string$/ )
{
return 1;
}
}
return 0;
}

696
File/Copy/Recursive.pm Normal file
View file

@ -0,0 +1,696 @@
package File::Copy::Recursive;
use strict;
BEGIN {
# Keep older versions of Perl from trying to use lexical warnings
$INC{'warnings.pm'} = "fake warnings entry for < 5.6 perl ($])" if $] < 5.006;
}
use warnings;
use Carp;
use File::Copy;
use File::Spec; #not really needed because File::Copy already gets it, but for good measure :)
use vars qw(
@ISA @EXPORT_OK $VERSION $MaxDepth $KeepMode $CPRFComp $CopyLink
$PFSCheck $RemvBase $NoFtlPth $ForcePth $CopyLoop $RMTrgFil $RMTrgDir
$CondCopy $BdTrgWrn $SkipFlop $DirPerms
);
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(fcopy rcopy dircopy fmove rmove dirmove pathmk pathrm pathempty pathrmdir);
$VERSION = '0.38';
$MaxDepth = 0;
$KeepMode = 1;
$CPRFComp = 0;
$CopyLink = eval { local $SIG{'__DIE__'};symlink '',''; 1 } || 0;
$PFSCheck = 1;
$RemvBase = 0;
$NoFtlPth = 0;
$ForcePth = 0;
$CopyLoop = 0;
$RMTrgFil = 0;
$RMTrgDir = 0;
$CondCopy = {};
$BdTrgWrn = 0;
$SkipFlop = 0;
$DirPerms = 0777;
my $samecheck = sub {
return 1 if $^O eq 'MSWin32'; # need better way to check for this on winders...
return if @_ != 2 || !defined $_[0] || !defined $_[1];
return if $_[0] eq $_[1];
my $one = '';
if($PFSCheck) {
$one = join( '-', ( stat $_[0] )[0,1] ) || '';
my $two = join( '-', ( stat $_[1] )[0,1] ) || '';
if ( $one eq $two && $one ) {
carp "$_[0] and $_[1] are identical";
return;
}
}
if(-d $_[0] && !$CopyLoop) {
$one = join( '-', ( stat $_[0] )[0,1] ) if !$one;
my $abs = File::Spec->rel2abs($_[1]);
my @pth = File::Spec->splitdir( $abs );
while(@pth) {
my $cur = File::Spec->catdir(@pth);
last if !$cur; # probably not necessary, but nice to have just in case :)
my $two = join( '-', ( stat $cur )[0,1] ) || '';
if ( $one eq $two && $one ) {
# $! = 62; # Too many levels of symbolic links
carp "Caught Deep Recursion Condition: $_[0] contains $_[1]";
return;
}
pop @pth;
}
}
return 1;
};
my $glob = sub {
my ($do, $src_glob, @args) = @_;
local $CPRFComp = 1;
my @rt;
for my $path ( glob($src_glob) ) {
my @call = [$do->($path, @args)] or return;
push @rt, \@call;
}
return @rt;
};
my $move = sub {
my $fl = shift;
my @x;
if($fl) {
@x = fcopy(@_) or return;
} else {
@x = dircopy(@_) or return;
}
if(@x) {
if($fl) {
unlink $_[0] or return;
} else {
pathrmdir($_[0]) or return;
}
if($RemvBase) {
my ($volm, $path) = File::Spec->splitpath($_[0]);
pathrm(File::Spec->catpath($volm,$path,''), $ForcePth, $NoFtlPth) or return;
}
}
return wantarray ? @x : $x[0];
};
my $ok_todo_asper_condcopy = sub {
my $org = shift;
my $copy = 1;
if(exists $CondCopy->{$org}) {
if($CondCopy->{$org}{'md5'}) {
}
if($copy) {
}
}
return $copy;
};
sub fcopy {
$samecheck->(@_) or return;
if($RMTrgFil && (-d $_[1] || -e $_[1]) ) {
my $trg = $_[1];
if( -d $trg ) {
my @trgx = File::Spec->splitpath( $_[0] );
$trg = File::Spec->catfile( $_[1], $trgx[ $#trgx ] );
}
$samecheck->($_[0], $trg) or return;
if(-e $trg) {
if($RMTrgFil == 1) {
unlink $trg or carp "\$RMTrgFil failed: $!";
} else {
unlink $trg or return;
}
}
}
my ($volm, $path) = File::Spec->splitpath($_[1]);
if($path && !-d $path) {
pathmk(File::Spec->catpath($volm,$path,''), $NoFtlPth);
}
if( -l $_[0] && $CopyLink ) {
carp "Copying a symlink ($_[0]) whose target does not exist"
if !-e readlink($_[0]) && $BdTrgWrn;
symlink readlink(shift()), shift() or return;
} else {
copy(@_) or return;
my @base_file = File::Spec->splitpath($_[0]);
my $mode_trg = -d $_[1] ? File::Spec->catfile($_[1], $base_file[ $#base_file ]) : $_[1];
chmod scalar((stat($_[0]))[2]), $mode_trg if $KeepMode;
}
return wantarray ? (1,0,0) : 1; # use 0's incase they do math on them and in case rcopy() is called in list context = no uninit val warnings
}
sub rcopy {
if (-l $_[0] && $CopyLink) {
goto &fcopy;
}
goto &dircopy if -d $_[0] || substr( $_[0], ( 1 * -1), 1) eq '*';
goto &fcopy;
}
sub rcopy_glob {
$glob->(\&rcopy, @_);
}
sub dircopy {
if($RMTrgDir && -d $_[1]) {
if($RMTrgDir == 1) {
pathrmdir($_[1]) or carp "\$RMTrgDir failed: $!";
} else {
pathrmdir($_[1]) or return;
}
}
my $globstar = 0;
my $_zero = $_[0];
my $_one = $_[1];
if ( substr( $_zero, ( 1 * -1 ), 1 ) eq '*') {
$globstar = 1;
$_zero = substr( $_zero, 0, ( length( $_zero ) - 1 ) );
}
$samecheck->( $_zero, $_[1] ) or return;
if ( !-d $_zero || ( -e $_[1] && !-d $_[1] ) ) {
$! = 20;
return;
}
if(!-d $_[1]) {
pathmk($_[1], $NoFtlPth) or return;
} else {
if($CPRFComp && !$globstar) {
my @parts = File::Spec->splitdir($_zero);
while($parts[ $#parts ] eq '') { pop @parts; }
$_one = File::Spec->catdir($_[1], $parts[$#parts]);
}
}
my $baseend = $_one;
my $level = 0;
my $filen = 0;
my $dirn = 0;
my $recurs; #must be my()ed before sub {} since it calls itself
$recurs = sub {
my ($str,$end,$buf) = @_;
$filen++ if $end eq $baseend;
$dirn++ if $end eq $baseend;
$DirPerms = oct($DirPerms) if substr($DirPerms,0,1) eq '0';
mkdir($end,$DirPerms) or return if !-d $end;
chmod scalar((stat($str))[2]), $end if $KeepMode;
if($MaxDepth && $MaxDepth =~ m/^\d+$/ && $level >= $MaxDepth) {
return ($filen,$dirn,$level) if wantarray;
return $filen;
}
$level++;
my @files;
if ( $] < 5.006 ) {
opendir(STR_DH, $str) or return;
@files = grep( $_ ne '.' && $_ ne '..', readdir(STR_DH));
closedir STR_DH;
}
else {
opendir(my $str_dh, $str) or return;
@files = grep( $_ ne '.' && $_ ne '..', readdir($str_dh));
closedir $str_dh;
}
for my $file (@files) {
my ($file_ut) = $file =~ m{ (.*) }xms;
my $org = File::Spec->catfile($str, $file_ut);
my $new = File::Spec->catfile($end, $file_ut);
if( -l $org && $CopyLink ) {
carp "Copying a symlink ($org) whose target does not exist"
if !-e readlink($org) && $BdTrgWrn;
symlink readlink($org), $new or return;
}
elsif(-d $org) {
$recurs->($org,$new,$buf) if defined $buf;
$recurs->($org,$new) if !defined $buf;
$filen++;
$dirn++;
}
else {
if($ok_todo_asper_condcopy->($org)) {
if($SkipFlop) {
fcopy($org,$new,$buf) or next if defined $buf;
fcopy($org,$new) or next if !defined $buf;
}
else {
fcopy($org,$new,$buf) or return if defined $buf;
fcopy($org,$new) or return if !defined $buf;
}
chmod scalar((stat($org))[2]), $new if $KeepMode;
$filen++;
}
}
}
1;
};
$recurs->($_zero, $_one, $_[2]) or return;
return wantarray ? ($filen,$dirn,$level) : $filen;
}
sub fmove { $move->(1, @_) }
sub rmove {
if (-l $_[0] && $CopyLink) {
goto &fmove;
}
goto &dirmove if -d $_[0] || substr( $_[0], ( 1 * -1), 1) eq '*';
goto &fmove;
}
sub rmove_glob {
$glob->(\&rmove, @_);
}
sub dirmove { $move->(0, @_) }
sub pathmk {
my @parts = File::Spec->splitdir( shift() );
my $nofatal = shift;
my $pth = $parts[0];
my $zer = 0;
if(!$pth) {
$pth = File::Spec->catdir($parts[0],$parts[1]);
$zer = 1;
}
for($zer..$#parts) {
$DirPerms = oct($DirPerms) if substr($DirPerms,0,1) eq '0';
mkdir($pth,$DirPerms) or return if !-d $pth && !$nofatal;
mkdir($pth,$DirPerms) if !-d $pth && $nofatal;
$pth = File::Spec->catdir($pth, $parts[$_ + 1]) unless $_ == $#parts;
}
1;
}
sub pathempty {
my $pth = shift;
return 2 if !-d $pth;
my @names;
my $pth_dh;
if ( $] < 5.006 ) {
opendir(PTH_DH, $pth) or return;
@names = grep !/^\.+$/, readdir(PTH_DH);
}
else {
opendir($pth_dh, $pth) or return;
@names = grep !/^\.+$/, readdir($pth_dh);
}
for my $name (@names) {
my ($name_ut) = $name =~ m{ (.*) }xms;
my $flpth = File::Spec->catdir($pth, $name_ut);
if( -l $flpth ) {
unlink $flpth or return;
}
elsif(-d $flpth) {
pathrmdir($flpth) or return;
}
else {
unlink $flpth or return;
}
}
if ( $] < 5.006 ) {
closedir PTH_DH;
}
else {
closedir $pth_dh;
}
1;
}
sub pathrm {
my $path = shift;
return 2 if !-d $path;
my @pth = File::Spec->splitdir( $path );
my $force = shift;
while(@pth) {
my $cur = File::Spec->catdir(@pth);
last if !$cur; # necessary ???
if(!shift()) {
pathempty($cur) or return if $force;
rmdir $cur or return;
}
else {
pathempty($cur) if $force;
rmdir $cur;
}
pop @pth;
}
1;
}
sub pathrmdir {
my $dir = shift;
if( -e $dir ) {
return if !-d $dir;
}
else {
return 2;
}
pathempty($dir) or return;
rmdir $dir or return;
}
1;
__END__
=head1 NAME
File::Copy::Recursive - Perl extension for recursively copying files and directories
=head1 SYNOPSIS
use File::Copy::Recursive qw(fcopy rcopy dircopy fmove rmove dirmove);
fcopy($orig,$new[,$buf]) or die $!;
rcopy($orig,$new[,$buf]) or die $!;
dircopy($orig,$new[,$buf]) or die $!;
fmove($orig,$new[,$buf]) or die $!;
rmove($orig,$new[,$buf]) or die $!;
dirmove($orig,$new[,$buf]) or die $!;
rcopy_glob("orig/stuff-*", $trg [, $buf]) or die $!;
rmove_glob("orig/stuff-*", $trg [,$buf]) or die $!;
=head1 DESCRIPTION
This module copies and moves directories recursively (or single files, well... singley) to an optional depth and attempts to preserve each file or directory's mode.
=head1 EXPORT
None by default. But you can export all the functions as in the example above and the path* functions if you wish.
=head2 fcopy()
This function uses File::Copy's copy() function to copy a file but not a directory. Any directories are recursively created if need be.
One difference to File::Copy::copy() is that fcopy attempts to preserve the mode (see Preserving Mode below)
The optional $buf in the synopsis if the same as File::Copy::copy()'s 3rd argument
returns the same as File::Copy::copy() in scalar context and 1,0,0 in list context to accomidate rcopy()'s list context on regular files. (See below for more info)
=head2 dircopy()
This function recursively traverses the $orig directory's structure and recursively copies it to the $new directory.
$new is created if necessary (multiple non existant directories is ok (IE foo/bar/baz). The script logically and portably creates all of them if necessary).
It attempts to preserve the mode (see Preserving Mode below) and
by default it copies all the way down into the directory, (see Managing Depth) below.
If a directory is not specified it croaks just like fcopy croaks if its not a file that is specified.
returns true or false, for true in scalar context it returns the number of files and directories copied,
In list context it returns the number of files and directories, number of directories only, depth level traversed.
my $num_of_files_and_dirs = dircopy($orig,$new);
my($num_of_files_and_dirs,$num_of_dirs,$depth_traversed) = dircopy($orig,$new);
Normally it stops and return's if a copy fails, to continue on regardless set $File::Copy::Recursive::SkipFlop to true.
local $File::Copy::Recursive::SkipFlop = 1;
That way it will copy everythgingit can ina directory and won't stop because of permissions, etc...
=head2 rcopy()
This function will allow you to specify a file *or* directory. It calls fcopy() if its a file and dircopy() if its a directory.
If you call rcopy() (or fcopy() for that matter) on a file in list context, the values will be 1,0,0 since no directories and no depth are used.
This is important becasue if its a directory in list context and there is only the initial directory the return value is 1,1,1.
=head2 rcopy_glob()
This function lets you specify a pattern suitable for perl's glob() as the first argument. Subsequently each path returned by perl's glob() gets rcopy()ied.
It returns and array whose items are array refs that contain the return value of each rcopy() call.
It forces behavior as if $File::Copy::Recursive::CPRFComp is true.
=head2 fmove()
Copies the file then removes the original. You can manage the path the original file is in according to $RemvBase.
=head2 dirmove()
Uses dircopy() to copy the directory then removes the original. You can manage the path the original directory is in according to $RemvBase.
=head2 rmove()
Like rcopy() but calls fmove() or dirmove() instead.
=head2 rmove_glob()
Like rcopy_glob() but calls rmove() instead of rcopy()
=head3 $RemvBase
Default is false. When set to true the *move() functions will not only attempt to remove the original file or directory but will remove the given path it is in.
So if you:
rmove('foo/bar/baz', '/etc/');
# "baz" is removed from foo/bar after it is successfully copied to /etc/
local $File::Copy::Recursive::Remvbase = 1;
rmove('foo/bar/baz','/etc/');
# if baz is successfully copied to /etc/ :
# first "baz" is removed from foo/bar
# then "foo/bar is removed via pathrm()
=head4 $ForcePth
Default is false. When set to true it calls pathempty() before any directories are removed to empty the directory so it can be rmdir()'ed when $RemvBase is in effect.
=head2 Creating and Removing Paths
=head3 $NoFtlPth
Default is false. If set to true rmdir(), mkdir(), and pathempty() calls in pathrm() and pathmk() do not return() on failure.
If its set to true they just silently go about their business regardless. This isn't a good idea but its there if you want it.
=head3 $DirPerms
Mode to pass to any mkdir() calls. Defaults to 0777 as per umask()'s POD. Explicitly having this allows older perls to be able to use FCR and might add a bit of flexibility for you.
Any value you set it to should be suitable for oct()
=head3 Path functions
These functions exist soley because they were necessary for the move and copy functions to have the features they do and not because they are of themselves the purpose of this module. That being said, here is how they work so you can understand how the copy and move funtions work and use them by themselves if you wish.
=head4 pathrm()
Removes a given path recursively. It removes the *entire* path so be carefull!!!
Returns 2 if the given path is not a directory.
File::Copy::Recursive::pathrm('foo/bar/baz') or die $!;
# foo no longer exists
Same as:
rmdir 'foo/bar/baz' or die $!;
rmdir 'foo/bar' or die $!;
rmdir 'foo' or die $!;
An optional second argument makes it call pathempty() before any rmdir()'s when set to true.
File::Copy::Recursive::pathrm('foo/bar/baz', 1) or die $!;
# foo no longer exists
Same as:PFSCheck
File::Copy::Recursive::pathempty('foo/bar/baz') or die $!;
rmdir 'foo/bar/baz' or die $!;
File::Copy::Recursive::pathempty('foo/bar/') or die $!;
rmdir 'foo/bar' or die $!;
File::Copy::Recursive::pathempty('foo/') or die $!;
rmdir 'foo' or die $!;
An optional third argument acts like $File::Copy::Recursive::NoFtlPth, again probably not a good idea.
=head4 pathempty()
Recursively removes the given directory's contents so it is empty. returns 2 if argument is not a directory, 1 on successfully emptying the directory.
File::Copy::Recursive::pathempty($pth) or die $!;
# $pth is now an empty directory
=head4 pathmk()
Creates a given path recursively. Creates foo/bar/baz even if foo does not exist.
File::Copy::Recursive::pathmk('foo/bar/baz') or die $!;
An optional second argument if true acts just like $File::Copy::Recursive::NoFtlPth, which means you'd never get your die() if something went wrong. Again, probably a *bad* idea.
=head4 pathrmdir()
Same as rmdir() but it calls pathempty() first to recursively empty it first since rmdir can not remove a directory with contents.
Just removes the top directory the path given instead of the entire path like pathrm(). Return 2 if given argument does not exist (IE its already gone). Return false if it exists but is not a directory.
=head2 Preserving Mode
By default a quiet attempt is made to change the new file or directory to the mode of the old one.
To turn this behavior off set
$File::Copy::Recursive::KeepMode
to false;
=head2 Managing Depth
You can set the maximum depth a directory structure is recursed by setting:
$File::Copy::Recursive::MaxDepth
to a whole number greater than 0.
=head2 SymLinks
If your system supports symlinks then symlinks will be copied as symlinks instead of as the target file.
Perl's symlink() is used instead of File::Copy's copy()
You can customize this behavior by setting $File::Copy::Recursive::CopyLink to a true or false value.
It is already set to true or false dending on your system's support of symlinks so you can check it with an if statement to see how it will behave:
if($File::Copy::Recursive::CopyLink) {
print "Symlinks will be preserved\n";
} else {
print "Symlinks will not be preserved because your system does not support it\n";
}
If symlinks are being copied you can set $File::Copy::Recursive::BdTrgWrn to true to make it carp when it copies a link whose target does not exist. Its false by default.
local $File::Copy::Recursive::BdTrgWrn = 1;
=head2 Removing existing target file or directory before copying.
This can be done by setting $File::Copy::Recursive::RMTrgFil or $File::Copy::Recursive::RMTrgDir for file or directory behavior respectively.
0 = off (This is the default)
1 = carp() $! if removal fails
2 = return if removal fails
local $File::Copy::Recursive::RMTrgFil = 1;
fcopy($orig, $target) or die $!;
# if it fails it does warn() and keeps going
local $File::Copy::Recursive::RMTrgDir = 2;
dircopy($orig, $target) or die $!;
# if it fails it does your "or die"
This should be unnecessary most of the time but its there if you need it :)
=head2 Turning off stat() check
By default the files or directories are checked to see if they are the same (IE linked, or two paths (absolute/relative or different relative paths) to the same file) by comparing the file's stat() info.
It's a very efficient check that croaks if they are and shouldn't be turned off but if you must for some weird reason just set $File::Copy::Recursive::PFSCheck to a false value. ("PFS" stands for "Physical File System")
=head2 Emulating cp -rf dir1/ dir2/
By default dircopy($dir1,$dir2) will put $dir1's contents right into $dir2 whether $dir2 exists or not.
You can make dircopy() emulate cp -rf by setting $File::Copy::Recursive::CPRFComp to true.
NOTE: This only emulates -f in the sense that it does not prompt. It does not remove the target file or directory if it exists.
If you need to do that then use the variables $RMTrgFil and $RMTrgDir described in "Removing existing target file or directory before copying" above.
That means that if $dir2 exists it puts the contents into $dir2/$dir1 instead of $dir2 just like cp -rf.
If $dir2 does not exist then the contents go into $dir2 like normal (also like cp -rf)
So assuming 'foo/file':
dircopy('foo', 'bar') or die $!;
# if bar does not exist the result is bar/file
# if bar does exist the result is bar/file
$File::Copy::Recursive::CPRFComp = 1;
dircopy('foo', 'bar') or die $!;
# if bar does not exist the result is bar/file
# if bar does exist the result is bar/foo/file
You can also specify a star for cp -rf glob type behavior:
dircopy('foo/*', 'bar') or die $!;
# if bar does not exist the result is bar/file
# if bar does exist the result is bar/file
$File::Copy::Recursive::CPRFComp = 1;
dircopy('foo/*', 'bar') or die $!;
# if bar does not exist the result is bar/file
# if bar does exist the result is bar/file
NOTE: The '*' is only like cp -rf foo/* and *DOES NOT EXPAND PARTIAL DIRECTORY NAMES LIKE YOUR SHELL DOES* (IE not like cp -rf fo* to copy foo/*)
=head2 Allowing Copy Loops
If you want to allow:
cp -rf . foo/
type behavior set $File::Copy::Recursive::CopyLoop to true.
This is false by default so that a check is done to see if the source directory will contain the target directory and croaks to avoid this problem.
If you ever find a situation where $CopyLoop = 1 is desirable let me know (IE its a bad bad idea but is there if you want it)
(Note: On Windows this was necessary since it uses stat() to detemine samedness and stat() is essencially useless for this on Windows.
The test is now simply skipped on Windows but I'd rather have an actual reliable check if anyone in Microsoft land would care to share)
=head1 SEE ALSO
L<File::Copy> L<File::Spec>
=head1 TO DO
I am currently working on and reviewing some other modules to use in the new interface so we can lose the horrid globals as well as some other undesirable traits and also more easily make available some long standing requests.
Tests will be easier to do with the new interface and hence the testing focus will shift to the new interface and aim to be comprehensive.
The old interface will work, it just won't be brought in until it is used, so it will add no overhead for users of the new interface.
I'll add this after the latest verision has been out for a while with no new features or issues found :)
=head1 AUTHOR
Daniel Muey, L<http://drmuey.com/cpan_contact.pl>
=head1 COPYRIGHT AND LICENSE
Copyright 2004 by Daniel Muey
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut

285
Frontier/Client.pm Normal file
View file

@ -0,0 +1,285 @@
#
# Copyright (C) 1998 Ken MacLeod
# Frontier::Client is free software; you can redistribute it
# and/or modify it under the same terms as Perl itself.
#
# $Id: Client.pm,v 1.8 2001/10/03 01:30:54 kmacleod Exp $
#
# NOTE: see Net::pRPC for a Perl RPC implementation
use strict;
package Frontier::Client;
use Frontier::RPC2;
use LWP::UserAgent;
use HTTP::Request;
use vars qw{$AUTOLOAD};
sub new {
my $class = shift;
my $self = ($#_ == 0) ? { %{ (shift) } } : { @_ };
bless $self, $class;
die "Frontier::RPC::new: no url defined\n"
if !defined $self->{'url'};
$self->{'ua'} = LWP::UserAgent->new;
$self->{'ua'}->proxy('http', $self->{'proxy'})
if(defined $self->{'proxy'});
$self->{'rq'} = HTTP::Request->new (POST => $self->{'url'});
$self->{'rq'}->header('Content-Type' => 'text/xml');
my @options;
if(defined $self->{'encoding'}) {
push @options, 'encoding' => $self->{'encoding'};
}
if (defined $self->{'use_objects'} && $self->{'use_objects'}) {
push @options, 'use_objects' => $self->{'use_objects'};
}
$self->{'enc'} = Frontier::RPC2->new(@options);
return $self;
}
sub call {
my $self = shift;
my $text = $self->{'enc'}->encode_call(@_);
if ($self->{'debug'}) {
print "---- request ----\n";
print $text;
}
$self->{'rq'}->content($text);
my $response = $self->{'ua'}->request($self->{'rq'});
if (!$response->is_success) {
die $response->status_line . "\n";
}
my $content = $response->content;
if ($self->{'debug'}) {
print "---- response ----\n";
print $content;
}
my $result = $self->{'enc'}->decode($content);
if ($result->{'type'} eq 'fault') {
die "Fault returned from XML RPC Server, fault code " . $result->{'value'}[0]{'faultCode'} . ": "
. $result->{'value'}[0]{'faultString'} . "\n";
}
return $result->{'value'}[0];
}
# shortcuts
sub base64 {
my $self = shift;
return Frontier::RPC2::Base64->new(@_);
}
sub boolean {
my $self = shift;
return Frontier::RPC2::Boolean->new(@_);
}
sub double {
my $self = shift;
return Frontier::RPC2::Double->new(@_);
}
sub int {
my $self = shift;
return Frontier::RPC2::Integer->new(@_);
}
sub string {
my $self = shift;
return Frontier::RPC2::String->new(@_);
}
sub date_time {
my $self = shift;
return Frontier::RPC2::DateTime::ISO8601->new(@_);
}
# something like this could be used to get an effect of
#
# $server->examples_getStateName(41)
#
# instead of
#
# $server->call('examples.getStateName', 41)
#
# for Frontier's
#
# [server].examples.getStateName 41
#
# sub AUTOLOAD {
# my ($pkg, $method) = ($AUTOLOAD =~ m/^(.*::)(.*)$/);
# return if $method eq 'DESTROY';
#
# $method =~ s/__/=/g;
# $method =~ tr/_=/._/;
#
# splice(@_, 1, 0, $method);
#
# goto &call;
# }
=head1 NAME
Frontier::Client - issue Frontier XML RPC requests to a server
=head1 SYNOPSIS
use Frontier::Client;
$server = Frontier::Client->new( I<OPTIONS> );
$result = $server->call($method, @args);
$boolean = $server->boolean($value);
$date_time = $server->date_time($value);
$base64 = $server->base64($value);
$value = $boolean->value;
$value = $date_time->value;
$value = $base64->value;
=head1 DESCRIPTION
I<Frontier::Client> is an XML-RPC client over HTTP.
I<Frontier::Client> instances are used to make calls to XML-RPC
servers and as shortcuts for creating XML-RPC special data types.
=head1 METHODS
=over 4
=item new( I<OPTIONS> )
Returns a new instance of I<Frontier::Client> and associates it with
an XML-RPC server at a URL. I<OPTIONS> may be a list of key, value
pairs or a hash containing the following parameters:
=over 4
=item url
The URL of the server. This parameter is required. For example:
$server = Frontier::Client->new( 'url' => 'http://betty.userland.com/RPC2' );
=item proxy
A URL of a proxy to forward XML-RPC calls through.
=item encoding
The XML encoding to be specified in the XML declaration of outgoing
RPC requests. Incoming results may have a different encoding
specified; XML::Parser will convert incoming data to UTF-8. The
default outgoing encoding is none, which uses XML 1.0's default of
UTF-8. For example:
$server = Frontier::Client->new( 'url' => 'http://betty.userland.com/RPC2',
'encoding' => 'ISO-8859-1' );
=item use_objects
If set to a non-zero value will convert incoming E<lt>i4E<gt>,
E<lt>floatE<gt>, and E<lt>stringE<gt> values to objects instead of
scalars. See int(), float(), and string() below for more details.
=item debug
If set to a non-zero value will print the encoded XML request and the
XML response received.
=back
=item call($method, @args)
Forward a procedure call to the server, either returning the value
returned by the procedure or failing with exception. `C<$method>' is
the name of the server method, and `C<@args>' is a list of arguments
to pass. Arguments may be Perl hashes, arrays, scalar values, or the
XML-RPC special data types below.
=item boolean( $value )
=item date_time( $value )
=item base64( $base64 )
The methods `C<boolean()>', `C<date_time()>', and `C<base64()>' create
and return XML-RPC-specific datatypes that can be passed to
`C<call()>'. Results from servers may also contain these datatypes.
The corresponding package names (for use with `C<ref()>', for example)
are `C<Frontier::RPC2::Boolean>',
`C<Frontier::RPC2::DateTime::ISO8601>', and
`C<Frontier::RPC2::Base64>'.
The value of boolean, date/time, and base64 data can be set or
returned using the `C<value()>' method. For example:
# To set a value:
$a_boolean->value(1);
# To retrieve a value
$base64 = $base64_xml_rpc_data->value();
Note: `C<base64()>' does I<not> encode or decode base64 data for you,
you must use MIME::Base64 or similar module for that.
=item int( 42 );
=item float( 3.14159 );
=item string( "Foo" );
By default, you may pass ordinary Perl values (scalars) to be encoded.
RPC2 automatically converts them to XML-RPC types if they look like an
integer, float, or as a string. This assumption causes problems when
you want to pass a string that looks like "0096", RPC2 will convert
that to an E<lt>i4E<gt> because it looks like an integer. With these
methods, you could now create a string object like this:
$part_num = $server->string("0096");
and be confident that it will be passed as an XML-RPC string. You can
change and retrieve values from objects using value() as described
above.
=back
=head1 SEE ALSO
perl(1), Frontier::RPC2(3)
<http://www.scripting.com/frontier5/xml/code/rpc.html>
=head1 AUTHOR
Ken MacLeod <ken@bitsko.slc.ut.us>
=cut
1;

96
Frontier/Daemon.pm Normal file
View file

@ -0,0 +1,96 @@
#
# Copyright (C) 1998 Ken MacLeod
# Frontier::Daemon is free software; you can redistribute it
# and/or modify it under the same terms as Perl itself.
#
# $Id: Daemon.pm,v 1.5 2001/10/03 01:30:54 kmacleod Exp $
#
# NOTE: see Net::pRPC for a Perl RPC implementation
###
### NOTE: $self is inherited from HTTP::Daemon and the weird access
### comes from there (`${*$self}').
###
use strict;
package Frontier::Daemon;
use vars qw{@ISA};
@ISA = qw{HTTP::Daemon};
use Frontier::RPC2;
use HTTP::Daemon;
use HTTP::Status;
sub new {
my $class = shift; my %args = @_;
my $self = $class->SUPER::new(%args);
return undef unless $self;
${*$self}{'methods'} = $args{'methods'};
${*$self}{'decode'} = new Frontier::RPC2 'use_objects' => $args{'use_objects'};
${*$self}{'response'} = new HTTP::Response 200;
${*$self}{'response'}->header('Content-Type' => 'text/xml');
my $conn;
while ($conn = $self->accept) {
my $rq = $conn->get_request;
if ($rq) {
if ($rq->method eq 'POST' && $rq->url->path eq '/RPC2') {
${*$self}{'response'}->content(${*$self}{'decode'}->serve($rq->content, ${*$self}{'methods'}));
$conn->send_response(${*$self}{'response'});
} else {
$conn->send_error(RC_FORBIDDEN);
}
}
$conn->close;
$conn = undef; # close connection
}
return $self;
}
=head1 NAME
Frontier::Daemon - receive Frontier XML RPC requests
=head1 SYNOPSIS
use Frontier::Daemon;
Frontier::Daemon->new(methods => {
'rpcName' => \&sub_name,
...
});
=head1 DESCRIPTION
I<Frontier::Daemon> is an HTTP/1.1 server that listens on a socket for
incoming requests containing Frontier XML RPC2 method calls.
I<Frontier::Daemon> is a subclass of I<HTTP::Daemon>, which is a
subclass of I<IO::Socket::INET>.
I<Frontier::Daemon> takes a `C<methods>' parameter, a hash that maps
an incoming RPC method name to reference to a subroutine.
I<Frontier::Daemon> takes a `C<use_objects>' parameter that if set to
a non-zero value will convert incoming E<lt>intE<gt>, E<lt>i4E<gt>,
E<lt>floatE<gt>, and E<lt>stringE<gt> values to objects instead of
scalars. See int(), float(), and string() in Frontier::RPC2 for more
details.
=head1 SEE ALSO
perl(1), HTTP::Daemon(3), IO::Socket::INET(3), Frontier::RPC2(3)
<http://www.scripting.com/frontier5/xml/code/rpc.html>
=head1 AUTHOR
Ken MacLeod <ken@bitsko.slc.ut.us>
=cut
1;

View file

@ -0,0 +1,95 @@
package Frontier::Daemon::OGP::Forking;
# $Id: Forking.pm,v 1.6 2004/01/23 19:48:33 tcaine Exp $
use strict;
use vars qw{@ISA $VERSION};
$VERSION = '0.02';
use Frontier::RPC2;
use HTTP::Daemon;
use HTTP::Status;
@ISA = qw{HTTP::Daemon};
# most of this routine comes directly from Frontier::Daemon
sub new {
my $class = shift;
my %args = @_;
my $encoding = delete $args{encoding};
my $self = $class->SUPER::new( %args );
return undef unless $self;
my @options;
push @options, encoding => $encoding
if $encoding;
${*$self}{methods} = $args{methods};
${*$self}{decode} = new Frontier::RPC2(@options);
${*$self}{response} = new HTTP::Response 200;
${*$self}{response}->header( 'Content-Type' => 'text/xml' );
local $SIG{CHLD} = 'IGNORE';
ACCEPT:
while ( my $conn = $self->accept ) {
my $pid = fork;
next ACCEPT if $pid;
if ( not defined $pid ) {
warn "fork() failed: $!";
$conn = undef;
}
else {
my $request = $conn->get_request;
if ($request) {
if ($request->method eq 'POST' && $request->url->path eq '/RPC2') {
${*$self}{'response'}->content(
${*$self}{'decode'}->serve(
$request->content,
${*$self}{'methods'},
)
);
$conn->send_response(${*$self}{'response'});
} else {
$conn->send_error(RC_FORBIDDEN);
}
}
}
exit;
}
}
1;
__END__
=head1 NAME
Frontier::Daemon::Forking - receive Frontier XML RPC requests
=head1 SYNOPSIS
use Frontier::Daemon::Forking;
Frontier::Daemon::Forking->new(
methods => {
rpcName => \&rpcHandler,
},
encoding => 'ISO-8859-1',
);
sub rpcHandler { return 'OK' }
=head1 DESCRIPTION
L<Frontier::Daemon::Forking> is a drop in replacement for L<Frontier::Daemon> when a forking HTTP/1.1 server is needed that listens on a socket for incoming requests containing Frontier XML RPC2 method calls. Most of the code was borrowed from L<Frontier::Daemon>.
=head1 AUTHOR
Todd Caine, tcaine@pobox.com
=head1 SEE ALSO
L<Frontier::RPC2>, L<Frontier::Daemon>, L<HTTP::Daemon>
=cut

701
Frontier/RPC2.pm Normal file
View file

@ -0,0 +1,701 @@
#
# Copyright (C) 1998, 1999 Ken MacLeod
# Frontier::RPC is free software; you can redistribute it
# and/or modify it under the same terms as Perl itself.
#
# $Id: RPC2.pm,v 1.18 2002/08/02 18:35:21 ivan420 Exp $
#
# NOTE: see Storable for marshalling.
use strict;
package Frontier::RPC2;
use XML::Parser;
use vars qw{%scalars %char_entities};
%char_entities = (
'&' => '&amp;',
'<' => '&lt;',
'>' => '&gt;',
'"' => '&quot;',
);
# FIXME I need a list of these
%scalars = (
'base64' => 1,
'boolean' => 1,
'dateTime.iso8601' => 1,
'double' => 1,
'int' => 1,
'i4' => 1,
'string' => 1,
);
sub new {
my $class = shift;
my $self = ($#_ == 0) ? { %{ (shift) } } : { @_ };
bless $self, $class;
if (defined $self->{'encoding'}) {
$self->{'encoding_'} = " encoding=\"$self->{'encoding'}\"";
} else {
$self->{'encoding_'} = "";
}
return $self;
}
sub encode_call {
my $self = shift; my $proc = shift;
my @text;
push @text, <<EOF;
<?xml version="1.0"$self->{'encoding_'}?>
<methodCall>
<methodName>$proc</methodName>
<params>
EOF
push @text, $self->_params([@_]);
push @text, <<EOF;
</params>
</methodCall>
EOF
return join('', @text);
}
sub encode_response {
my $self = shift;
my @text;
push @text, <<EOF;
<?xml version="1.0"$self->{'encoding_'}?>
<methodResponse>
<params>
EOF
push @text, $self->_params([@_]);
push @text, <<EOF;
</params>
</methodResponse>
EOF
return join('', @text);
}
sub encode_fault {
my $self = shift; my $code = shift; my $message = shift;
my @text;
push @text, <<EOF;
<?xml version="1.0"$self->{'encoding_'}?>
<methodResponse>
<fault>
EOF
push @text, $self->_item({faultCode => $code, faultString => $message});
push @text, <<EOF;
</fault>
</methodResponse>
EOF
return join('', @text);
}
sub serve {
my $self = shift; my $xml = shift; my $methods = shift;
my $call;
# FIXME bug in Frontier's XML
$xml =~ s/(<\?XML\s+VERSION)/\L$1\E/;
eval { $call = $self->decode($xml) };
if ($@) {
return $self->encode_fault(1, "error decoding RPC.\n" . $@);
}
if ($call->{'type'} ne 'call') {
return $self->encode_fault(2,"expected RPC \`methodCall', got \`$call->{'type'}'\n");
}
my $method = $call->{'method_name'};
if (!defined $methods->{$method}) {
return $self->encode_fault(3, "no such method \`$method'\n");
}
my $result;
my $eval = eval { $result = &{ $methods->{$method} }(@{ $call->{'value'} }) };
if ($@) {
return $self->encode_fault(4, "error executing RPC \`$method'.\n" . $@);
}
my $response_xml = $self->encode_response($result);
return $response_xml;
}
sub _params {
my $self = shift; my $array = shift;
my @text;
my $item;
foreach $item (@$array) {
push (@text, "<param>",
$self->_item($item),
"</param>\n");
}
return @text;
}
sub _item {
my $self = shift; my $item = shift;
my @text;
my $ref = ref($item);
if (!$ref) {
push (@text, $self->_scalar ($item));
} elsif ($ref eq 'ARRAY') {
push (@text, $self->_array($item));
} elsif ($ref eq 'HASH') {
push (@text, $self->_hash($item));
} elsif ($ref eq 'Frontier::RPC2::Boolean') {
push @text, "<value><boolean>", $item->repr, "</boolean></value>\n";
} elsif ($ref eq 'Frontier::RPC2::String') {
push @text, "<value><string>", $item->repr, "</string></value>\n";
} elsif ($ref eq 'Frontier::RPC2::Integer') {
push @text, "<value><int>", $item->repr, "</int></value>\n";
} elsif ($ref eq 'Frontier::RPC2::Double') {
push @text, "<value><double>", $item->repr, "</double></value>\n";
} elsif ($ref eq 'Frontier::RPC2::DateTime::ISO8601') {
push @text, "<value><dateTime.iso8601>", $item->repr, "</dateTime.iso8601></value>\n";
} elsif ($ref eq 'Frontier::RPC2::Base64') {
push @text, "<value><base64>", $item->repr, "</base64></value>\n";
} elsif ($ref =~ /=HASH\(/) {
push @text, $self->_hash($item);
} elsif ($ref =~ /=ARRAY\(/) {
push @text, $self->_array($item);
} else {
die "can't convert \`$item' to XML\n";
}
return @text;
}
sub _hash {
my $self = shift; my $hash = shift;
my @text = "<value><struct>\n";
my ($key, $value);
while (($key, $value) = each %$hash) {
push (@text,
"<member><name>$key</name>",
$self->_item($value),
"</member>\n");
}
push @text, "</struct></value>\n";
return @text;
}
sub _array {
my $self = shift; my $array = shift;
my @text = "<value><array><data>\n";
my $item;
foreach $item (@$array) {
push @text, $self->_item($item);
}
push @text, "</data></array></value>\n";
return @text;
}
sub _scalar {
my $self = shift; my $value = shift;
# these are from `perldata(1)'
if ($value =~ /^[+-]?\d+$/) {
return ("<value><i4>$value</i4></value>");
} elsif ($value =~ /^(-?(?:\d+(?:\.\d*)?|\.\d+)|([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?)$/) {
return ("<value><double>$value</double></value>");
} else {
$value =~ s/([&<>\"])/$char_entities{$1}/ge;
return ("<value><string>$value</string></value>");
}
}
sub decode {
my $self = shift; my $string = shift;
$self->{'parser'} = XML::Parser->new( Style => ref($self),
'use_objects' => $self->{'use_objects'} );
return $self->{'parser'}->parsestring($string);
}
# shortcuts
sub base64 {
my $self = shift;
return Frontier::RPC2::Base64->new(@_);
}
sub boolean {
my $self = shift;
my $elem = shift;
if($elem == 0 or $elem == 1) {
return Frontier::RPC2::Boolean->new($elem);
} else {
die "error in rendering RPC type \`$elem\' not a boolean\n";
}
}
sub double {
my $self = shift;
my $elem = shift;
# this is from `perldata(1)'
if($elem =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) {
return Frontier::RPC2::Double->new($elem);
} else {
die "error in rendering RPC type \`$elem\' not a double\n";
}
}
sub int {
my $self = shift;
my $elem = shift;
# this is from `perldata(1)'
if($elem =~ /^[+-]?\d+$/) {
return Frontier::RPC2::Integer->new($elem);
} else {
die "error in rendering RPC type \`$elem\' not an int\n";
}
}
sub string {
my $self = shift;
return Frontier::RPC2::String->new(@_);
}
sub date_time {
my $self = shift;
return Frontier::RPC2::DateTime::ISO8601->new(@_);
}
######################################################################
###
### XML::Parser callbacks
###
sub die {
my $expat = shift; my $message = shift;
die $message
. "at line " . $expat->current_line
. " column " . $expat->current_column . "\n";
}
sub init {
my $expat = shift;
$expat->{'rpc_state'} = [];
$expat->{'rpc_container'} = [ [] ];
$expat->{'rpc_member_name'} = [];
$expat->{'rpc_type'} = undef;
$expat->{'rpc_args'} = undef;
}
# FIXME this state machine wouldn't be necessary if we had a DTD.
sub start {
my $expat = shift; my $tag = shift;
my $state = $expat->{'rpc_state'}[-1];
if (!defined $state) {
if ($tag eq 'methodCall') {
$expat->{'rpc_type'} = 'call';
push @{ $expat->{'rpc_state'} }, 'want_method_name';
} elsif ($tag eq 'methodResponse') {
push @{ $expat->{'rpc_state'} }, 'method_response';
} else {
Frontier::RPC2::die($expat, "unknown RPC type \`$tag'\n");
}
} elsif ($state eq 'want_method_name') {
Frontier::RPC2::die($expat, "wanted \`methodName' tag, got \`$tag'\n")
if ($tag ne 'methodName');
push @{ $expat->{'rpc_state'} }, 'method_name';
$expat->{'rpc_text'} = "";
} elsif ($state eq 'method_response') {
if ($tag eq 'params') {
$expat->{'rpc_type'} = 'response';
push @{ $expat->{'rpc_state'} }, 'params';
} elsif ($tag eq 'fault') {
$expat->{'rpc_type'} = 'fault';
push @{ $expat->{'rpc_state'} }, 'want_value';
}
} elsif ($state eq 'want_params') {
Frontier::RPC2::die($expat, "wanted \`params' tag, got \`$tag'\n")
if ($tag ne 'params');
push @{ $expat->{'rpc_state'} }, 'params';
} elsif ($state eq 'params') {
Frontier::RPC2::die($expat, "wanted \`param' tag, got \`$tag'\n")
if ($tag ne 'param');
push @{ $expat->{'rpc_state'} }, 'want_param_name_or_value';
} elsif ($state eq 'want_param_name_or_value') {
if ($tag eq 'value') {
$expat->{'may_get_cdata'} = 1;
$expat->{'rpc_text'} = "";
push @{ $expat->{'rpc_state'} }, 'value';
} elsif ($tag eq 'name') {
push @{ $expat->{'rpc_state'} }, 'param_name';
} else {
Frontier::RPC2::die($expat, "wanted \`value' or \`name' tag, got \`$tag'\n");
}
} elsif ($state eq 'param_name') {
Frontier::RPC2::die($expat, "wanted parameter name data, got tag \`$tag'\n");
} elsif ($state eq 'want_value') {
Frontier::RPC2::die($expat, "wanted \`value' tag, got \`$tag'\n")
if ($tag ne 'value');
$expat->{'rpc_text'} = "";
$expat->{'may_get_cdata'} = 1;
push @{ $expat->{'rpc_state'} }, 'value';
} elsif ($state eq 'value') {
$expat->{'may_get_cdata'} = 0;
if ($tag eq 'array') {
push @{ $expat->{'rpc_container'} }, [];
push @{ $expat->{'rpc_state'} }, 'want_data';
} elsif ($tag eq 'struct') {
push @{ $expat->{'rpc_container'} }, {};
push @{ $expat->{'rpc_member_name'} }, undef;
push @{ $expat->{'rpc_state'} }, 'struct';
} elsif ($scalars{$tag}) {
$expat->{'rpc_text'} = "";
push @{ $expat->{'rpc_state'} }, 'cdata';
} else {
Frontier::RPC2::die($expat, "wanted a data type, got \`$tag'\n");
}
} elsif ($state eq 'want_data') {
Frontier::RPC2::die($expat, "wanted \`data', got \`$tag'\n")
if ($tag ne 'data');
push @{ $expat->{'rpc_state'} }, 'array';
} elsif ($state eq 'array') {
Frontier::RPC2::die($expat, "wanted \`value' tag, got \`$tag'\n")
if ($tag ne 'value');
$expat->{'rpc_text'} = "";
$expat->{'may_get_cdata'} = 1;
push @{ $expat->{'rpc_state'} }, 'value';
} elsif ($state eq 'struct') {
Frontier::RPC2::die($expat, "wanted \`member' tag, got \`$tag'\n")
if ($tag ne 'member');
push @{ $expat->{'rpc_state'} }, 'want_member_name';
} elsif ($state eq 'want_member_name') {
Frontier::RPC2::die($expat, "wanted \`name' tag, got \`$tag'\n")
if ($tag ne 'name');
push @{ $expat->{'rpc_state'} }, 'member_name';
$expat->{'rpc_text'} = "";
} elsif ($state eq 'member_name') {
Frontier::RPC2::die($expat, "wanted data, got tag \`$tag'\n");
} elsif ($state eq 'cdata') {
Frontier::RPC2::die($expat, "wanted data, got tag \`$tag'\n");
} else {
Frontier::RPC2::die($expat, "internal error, unknown state \`$state'\n");
}
}
sub end {
my $expat = shift; my $tag = shift;
my $state = pop @{ $expat->{'rpc_state'} };
if ($state eq 'cdata') {
my $value = $expat->{'rpc_text'};
if ($tag eq 'base64') {
$value = Frontier::RPC2::Base64->new($value);
} elsif ($tag eq 'boolean') {
$value = Frontier::RPC2::Boolean->new($value);
} elsif ($tag eq 'dateTime.iso8601') {
$value = Frontier::RPC2::DateTime::ISO8601->new($value);
} elsif ($expat->{'use_objects'}) {
if ($tag eq 'i4' or $tag eq 'int') {
$value = Frontier::RPC2::Integer->new($value);
} elsif ($tag eq 'float') {
$value = Frontier::RPC2::Float->new($value);
} elsif ($tag eq 'string') {
$value = Frontier::RPC2::String->new($value);
}
}
$expat->{'rpc_value'} = $value;
} elsif ($state eq 'member_name') {
$expat->{'rpc_member_name'}[-1] = $expat->{'rpc_text'};
$expat->{'rpc_state'}[-1] = 'want_value';
} elsif ($state eq 'method_name') {
$expat->{'rpc_method_name'} = $expat->{'rpc_text'};
$expat->{'rpc_state'}[-1] = 'want_params';
} elsif ($state eq 'struct') {
$expat->{'rpc_value'} = pop @{ $expat->{'rpc_container'} };
pop @{ $expat->{'rpc_member_name'} };
} elsif ($state eq 'array') {
$expat->{'rpc_value'} = pop @{ $expat->{'rpc_container'} };
} elsif ($state eq 'value') {
# the rpc_text is a string if no type tags were given
if ($expat->{'may_get_cdata'}) {
$expat->{'may_get_cdata'} = 0;
if ($expat->{'use_objects'}) {
$expat->{'rpc_value'}
= Frontier::RPC2::String->new($expat->{'rpc_text'});
} else {
$expat->{'rpc_value'} = $expat->{'rpc_text'};
}
}
my $container = $expat->{'rpc_container'}[-1];
if (ref($container) eq 'ARRAY') {
push @$container, $expat->{'rpc_value'};
} elsif (ref($container) eq 'HASH') {
$container->{ $expat->{'rpc_member_name'}[-1] } = $expat->{'rpc_value'};
}
}
}
sub char {
my $expat = shift; my $text = shift;
$expat->{'rpc_text'} .= $text;
}
sub proc {
}
sub final {
my $expat = shift;
$expat->{'rpc_value'} = pop @{ $expat->{'rpc_container'} };
return {
value => $expat->{'rpc_value'},
type => $expat->{'rpc_type'},
method_name => $expat->{'rpc_method_name'},
};
}
package Frontier::RPC2::DataType;
sub new {
my $type = shift; my $value = shift;
return bless \$value, $type;
}
# `repr' returns the XML representation of this data, which may be
# different [in the future] from what is returned from `value'
sub repr {
my $self = shift;
return $$self;
}
# sets or returns the usable value of this data
sub value {
my $self = shift;
@_ ? ($$self = shift) : $$self;
}
package Frontier::RPC2::Base64;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
package Frontier::RPC2::Boolean;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
package Frontier::RPC2::Integer;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
package Frontier::RPC2::String;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
sub repr {
my $self = shift;
my $value = $$self;
$value =~ s/([&<>\"])/$Frontier::RPC2::char_entities{$1}/ge;
$value;
}
package Frontier::RPC2::Double;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
package Frontier::RPC2::DateTime::ISO8601;
use vars qw{@ISA};
@ISA = qw{Frontier::RPC2::DataType};
=head1 NAME
Frontier::RPC2 - encode/decode RPC2 format XML
=head1 SYNOPSIS
use Frontier::RPC2;
$coder = Frontier::RPC2->new;
$xml_string = $coder->encode_call($method, @args);
$xml_string = $coder->encode_response($result);
$xml_string = $coder->encode_fault($code, $message);
$call = $coder->decode($xml_string);
$response_xml = $coder->serve($request_xml, $methods);
$boolean_object = $coder->boolean($boolean);
$date_time_object = $coder->date_time($date_time);
$base64_object = $coder->base64($base64);
$int_object = $coder->int(42);
$float_object = $coder->float(3.14159);
$string_object = $coder->string("Foo");
=head1 DESCRIPTION
I<Frontier::RPC2> encodes and decodes XML RPC calls.
=over 4
=item $coder = Frontier::RPC2->new( I<OPTIONS> )
Create a new encoder/decoder. The following option is supported:
=over 4
=item encoding
The XML encoding to be specified in the XML declaration of encoded RPC
requests or responses. Decoded results may have a different encoding
specified; XML::Parser will convert decoded data to UTF-8. The
default encoding is none, which uses XML 1.0's default of UTF-8. For
example:
$server = Frontier::RPC2->new( 'encoding' => 'ISO-8859-1' );
=item use_objects
If set to a non-zero value will convert incoming E<lt>i4E<gt>,
E<lt>floatE<gt>, and E<lt>stringE<gt> values to objects instead of
scalars. See int(), float(), and string() below for more details.
=back
=item $xml_string = $coder->encode_call($method, @args)
`C<encode_call>' converts a method name and it's arguments into an
RPC2 `C<methodCall>' element, returning the XML fragment.
=item $xml_string = $coder->encode_response($result)
`C<encode_response>' converts the return value of a procedure into an
RPC2 `C<methodResponse>' element containing the result, returning the
XML fragment.
=item $xml_string = $coder->encode_fault($code, $message)
`C<encode_fault>' converts a fault code and message into an RPC2
`C<methodResponse>' element containing a `C<fault>' element, returning
the XML fragment.
=item $call = $coder->decode($xml_string)
`C<decode>' converts an XML string containing an RPC2 `C<methodCall>'
or `C<methodResponse>' element into a hash containing three members,
`C<type>', `C<value>', and `C<method_name>'. `C<type>' is one of
`C<call>', `C<response>', or `C<fault>'. `C<value>' is array
containing the parameters or result of the RPC. For a `C<call>' type,
`C<value>' contains call's parameters and `C<method_name>' contains
the method being called. For a `C<response>' type, the `C<value>'
array contains call's result. For a `C<fault>' type, the `C<value>'
array contains a hash with the two members `C<faultCode>' and
`C<faultMessage>'.
=item $response_xml = $coder->serve($request_xml, $methods)
`C<serve>' decodes `C<$request_xml>', looks up the called method name
in the `C<$methods>' hash and calls it, and then encodes and returns
the response as XML.
=item $boolean_object = $coder->boolean($boolean);
=item $date_time_object = $coder->date_time($date_time);
=item $base64_object = $coder->base64($base64);
These methods create and return XML-RPC-specific datatypes that can be
passed to the encoder. The decoder may also return these datatypes.
The corresponding package names (for use with `C<ref()>', for example)
are `C<Frontier::RPC2::Boolean>',
`C<Frontier::RPC2::DateTime::ISO8601>', and
`C<Frontier::RPC2::Base64>'.
You can change and retrieve the value of boolean, date/time, and
base64 data using the `C<value>' method of those objects, i.e.:
$boolean = $boolean_object->value;
$boolean_object->value(1);
Note: `C<base64()>' does I<not> encode or decode base64 data for you,
you must use MIME::Base64 or similar module for that.
=item $int_object = $coder->int(42);
=item $float_object = $coder->float(3.14159);
=item $string_object = $coder->string("Foo");
By default, you may pass ordinary Perl values (scalars) to be encoded.
RPC2 automatically converts them to XML-RPC types if they look like an
integer, float, or as a string. This assumption causes problems when
you want to pass a string that looks like "0096", RPC2 will convert
that to an E<lt>i4E<gt> because it looks like an integer. With these
methods, you could now create a string object like this:
$part_num = $coder->string("0096");
and be confident that it will be passed as an XML-RPC string. You can
change and retrieve values from objects using value() as described
above.
=back
=head1 SEE ALSO
perl(1), Frontier::Daemon(3), Frontier::Client(3)
<http://www.scripting.com/frontier5/xml/code/rpc.html>
=head1 AUTHOR
Ken MacLeod <ken@bitsko.slc.ut.us>
=cut
1;

170
Frontier/Responder.pm Normal file
View file

@ -0,0 +1,170 @@
# File: Repsonder.pm
# based heavily on Ken MacLeod's Frontier::Daemon
# Author: Joe Johnston 7/2000
# Revisions:
# 11/2000 - Cleaned/Add POD. Took out 'use CGI'.
#
# Meant to be called from a CGI process to answer client
# requests and emit the appropriate reponses. See POD for details.
#
# LICENSE: This code is released under the same licensing
# as Perl itself.
#
# Use the code where ever you want, but due credit is appreciated.
package Frontier::Responder;
use strict;
use vars qw/@ISA/;
use Frontier::RPC2;
my $snappy_answer = "Hey, I need to return true, don't I?";
# Class constructor.
# Input: (expects parameters to be passed in as a hash)
# methods => hashref, keys are API procedure names, values are
# subroutine references
#
# Output: blessed reference
sub new {
my $class = shift;
my %args = @_;
my $self = bless {}, (ref $class ? ref $class : $class);
# Store the dispatch table away for future use.
$self->{methods} = $args{methods};
$self->{_decode} = Frontier::RPC2->new();
return $self;
}
# Grabs input from CGI "stream", makes request
# if possible, packs up the response in purddy
# XML
# Input: None
# Output: A XML string suitable for printing from a CGI process
sub answer{
my $self = shift;
# fetch the xml message sent
my $request = get_cgi_request();
unless( defined $request ){
print
"Content-Type: text/txt\n\n";
exit;
}
# Let's figure out the method to execute
# along with its arguments
my $response = $self->{_decode}->serve( $request,
$self->{methods} );
# Ship it!
return
"Content-Type: text/xml \n\n" . $response;
}
# private function. No need to advertise this.
# Remember, this is just XML.
# CGI.pm doesn't grok this.
sub get_cgi_request{
my $in;
if( $ENV{REQUEST_METHOD} eq 'POST' ){
my $len = $ENV{CONTENT_LENGTH};
unless ( read( STDIN, $in, $len ) == $len ){
return;
}
}else{
$in = $ENV{QUERY_STRING};
}
return $in;
}
=pod
=head1 NAME
Frontier::Responder - Create XML-RPC listeners for normal CGI processes
=head1 SYNOPSIS
use Frontier::Responder;
my $res = Frontier::Responder->new( methods => {
add => sub{ $_[0] + $_[1] },
cat => sub{ $_[0] . $_[1] },
},
);
print $res->answer;
=head1 DESCRIPTION
Use I<Frontier::Responder> whenever you need to create an XML-RPC listener
using a standard CGI interface. To be effective, a script using this class
will often have to be put a directory from which a web server is authorized
to execute CGI programs. An XML-RPC listener using this library will be
implementing the API of a particular XML-RPC application. Each remote
procedure listed in the API of the user defined application will correspond
to a hash key that is defined in the C<new> method of a I<Frontier::Responder>
object. This is exactly the way I<Frontier::Daemon> works as well.
In order to process the request and get the response, the C<answer> method
is needed. Its return value is XML ready for printing.
For those new to XML-RPC, here is a brief description of this protocol.
XML-RPC is a way to execute functions on a different
machine. Both the client's request and listeners response are wrapped
up in XML and sent over HTTP. Because the XML-RPC conversation is in
XML, the implementation languages of the server (here called a I<listener>),
and the client can be different. This can be a powerful and simple way
to have very different platforms work together without acrimony. Implicit
in the use of XML-RPC is a contract or API that an XML-RPC listener
implements and an XML-RPC client calls. The API needs to list not only
the various procedures that can be called, but also the XML-RPC datatypes
expected for input and output. Remember that although Perl is permissive
about datatyping, other languages are not. Unforuntately, the XML-RPC spec
doesn't say how to document the API. It is recomended that the author
of a Perl XML-RPC listener should at least use POD to explain the API.
This allows for the programmatic generation of a clean web page.
=head1 METHODS
=over 4
=item new( I<OPTIONS> )
This is the class constructor. As is traditional, it returns
a blessed reference to a I<Frontier::Responder> object. It expects
arguments to be given like a hash (Perl's named parameter mechanism).
To be effective, populate the C<methods> parameter with a hashref
that has API procedure names as keys and subroutine references as
values. See the SYNOPSIS for a sample usage.
=item answer()
In order to parse the request and execute the procedure, this method
must be called. It returns a XML string that contains the procedure's
response. In a typical CGI program, this string will simply be printed
to STDOUT.
=back
=head1 SEE ALSO
perl(1), Frontier::RPC2(3)
<http://www.scripting.com/frontier5/xml/code/rpc.html>
=head1 AUTHOR
Ken MacLeod <ken@bitsko.slc.ut.us> wrote the underlying
RPC library.
Joe Johnston <jjohn@cs.umb.edu> wrote an adaptation
of the Frontier::Daemon class to create this CGI XML-RPC
listener class.
=cut

View file

@ -0,0 +1,36 @@
<?php
error_reporting(0);
require('soap_config.php');
$client = new SoapClient(null, array('location' => $soap_location,
'uri' => $soap_uri,
'trace' => 1,
'exceptions' => 1));
$session_id = $client->login($username,$password);
$client_id = 0;
$username = $_GET['username'];
$password = $_GET['password'];
$dir = $_GET['dir'];
$uid = $_GET['uid'];
$gid = $_GET['gid'];
$params = array(
'server_id' => 1,
'parent_domain_id' => 1,
'username' => $username,
'password' => $password,
'quota_size' => -1,
'active' => 'y',
'uid' => $uid,
'gid' => $gid,
'dir' => $dir,
'quota_files' => -1,
'ul_ratio' => -1,
'dl_ratio' => -1,
'ul_bandwidth' => -1,
'dl_bandwidth' => -1
);
$ftp_id = $client->sites_ftp_user_add($session_id, $client_id, $params);
$client->logout($session_id);
if(!file_exists('ftp_users')) mkdir('ftp_users');
chdir('ftp_users');
file_put_contents($username, $ftp_id);
?>

View file

@ -0,0 +1,15 @@
<?php
error_reporting(0);
require('soap_config.php');
$client = new SoapClient(null, array('location' => $soap_location,
'uri' => $soap_uri,
'trace' => 1,
'exceptions' => 1));
$session_id = $client->login($username,$password);
chdir('ftp_users');
$username = $_GET['username'];
$ftp_user_id = file_get_contents($username);
$client->sites_ftp_user_delete($session_id, $ftp_user_id);
unlink($username);
$client->logout($session_id);
?>

View file

@ -0,0 +1,24 @@
<?php
//error_reporting(0);
require('soap_config.php');
$client = new SoapClient(null, array('location' => $soap_location,
'uri' => $soap_uri,
'trace' => 1,
'exceptions' => 1));
$session_id = $client->login($username,$password);
chdir('ftp_users');
$username = $_GET['username'];
$ftp_user_id = file_get_contents($username);
$ftp_user_record = $client->sites_ftp_user_get($session_id, $ftp_user_id);
if(isset($_GET['type']) AND $_GET['type'] == "detail")
{
foreach($ftp_user_record as $key => $value)
{
echo $key." : ".$value."\n";
}
}
else
{
echo $ftp_user_record['username']."\t".$ftp_user_record['dir']."/./\n";
}
?>

View file

@ -0,0 +1,31 @@
<?php
error_reporting(0);
require('soap_config.php');
$client = new SoapClient(null, array('location' => $soap_location,
'uri' => $soap_uri,
'trace' => 1,
'exceptions' => 1));
$session_id = $client->login($username,$password);
$client_id = 0;
chdir('ftp_users');
$username = $_GET['username'];
$ftp_user_id = file_get_contents($username);
//* Get the ftp user record
$ftp_user_record = $client->sites_ftp_user_get($session_id, $ftp_user_id);
if(isset($_GET['type']) AND $_GET['type'] == "password")
{
$ftp_user_record['password'] = $_GET['password'];
}
else
{
$settings = explode("\n",$_GET['password']);
foreach($settings as $setting)
{
list($key,$value) = explode("\t",$setting);
$ftp_user_record[$key] = $value;
}
}
$client->sites_ftp_user_update($session_id, $client_id, $ftp_user_id, $ftp_user_record);
$client->logout($session_id);
?>

View file

@ -0,0 +1,7 @@
<?php
$username = 'admin';
$password = 'admin';
$soap_location = 'http://127.0.0.1:8080/remote/index.php';
$soap_uri = 'http://127.0.0.1:8080/remote/';
?>

346
KKrcon/HL2.pm Normal file
View file

@ -0,0 +1,346 @@
# HL2 - Perl extension Half-Life 2 (Source) engine Rcon interface
#
# $Id:$
#
package HL2;
use strict;
use warnings;
use IO::Socket;
use IO::Select;
# release version
our $VERSION = "0.05";
# constants for command type
sub CMD { 2 }
sub AUTH { 3 }
# create class
sub new {
my $class = shift;
# create object with defaults
my $self = {
hostname => undef,
port => 27015,
password => undef,
timeout => 5,
connected => 0,
authenticated => 0,
socket => undef,
sequence => 0,
};
# create object
bless($self, $class);
# initialize class instances
$self->init();
# parse constructor args
while (my ($key, $val) = splice(@_, 0, 2)) {
$key = lc($key);
if ($key eq "hostname") { $self->hostname($val) }
elsif ($key eq "port") { $self->port($val) }
elsif ($key eq "password") { $self->password($val) }
elsif ($key eq "timeout") { $self->timeout($val) }
else { print STDERR "Unknown attribute: $key\n" }
}
return $self;
}
# initialize class instances
sub init {
my $self = shift;
my $class = ref($self);
# manipulate symbol table.. gotta love perl
no strict "refs";
no warnings;
foreach my $instance (keys %$self) {
*{"${class}::${instance}"} = sub {
my $self = shift;
my $value = shift;
my $ref = \$self->{$instance};
if (defined $value) {
$$ref = $value;
return $self;
} else {
return $$ref;
}
};
}
}
# run a command and return its response
sub run {
my $self = shift;
my $command = shift;
if (!$self->connected()) {
$self->connect();
}
if (!$self->authenticated()) {
$self->authenticate();
}
my $socket = $self->socket();
if($socket->connected)
{
print $socket $self->packet(CMD, $command);
return $self->response();
}
return;
}
# create tcp socket
sub connect {
my $self = shift;
my $socket = IO::Socket::INET->new(
PeerAddr => $self->hostname(),
PeerPort => $self->port(),
Timeout => $self->timeout(),
Proto => "tcp",
Type => SOCK_STREAM,
) || die "Failed to connect: $!\n";
$self->socket($socket);
$self->connected(1);
}
# authenticate rcon session
sub authenticate {
my $self = shift;
# send authentication packet to server
my $socket = $self->socket();
print $socket $self->packet(AUTH, $self->password());
# auth response sends back an empty packet first
$self->response();
$self->response();
$self->authenticated(1);
}
######################
# PROTOCOL FUNCTIONS #
######################
# rcon command protocol:
# (V)[size] (V)[requestID] (V)[command] (0)[string1] (0)[string2]
#
# rcon response protocol:
# (V)[size] (V)[requestID] (V)[responseID] (0)[string1] (0)[string2]
#
# V = a 32-bit unsigned long int, little-endian (VAX/Intel)
# 0 = null-terminated string
#
# NOTE: string2 appears unused, so our functions ignore it
# create a packet of type (AUTH or CMD)
sub packet {
my $self = shift;
my $type = shift;
my $payload = shift;
# sequence increments, but auth
# packet is 2.. no idea why that is,
# but tcpdump does not lie
my $sequence;
if ($type == AUTH) {
$sequence = 2;
} else {
$sequence = $self->sequence();
# increment for next use
$self->sequence($sequence + 1);
}
my $packet = pack("VV", $sequence, $type) . "$payload\x00\x00";
$packet = pack("V", length($packet)) . $packet;
return $packet;
}
# receive packet
sub response {
my $self = shift;
my $payload = $self->read();
# remove protocol cruft and null terminators
$payload =~ s/\x00{2}$//;
return $payload;
}
# read length of bytes from socket with timeout
sub read {
my $self = shift;
my $length = shift;
my $socket = $self->socket();
my $timeout = $self->timeout();
my $select = IO::Select->new($socket);
my $reply = "";
my $buffer;
my ($size, $request_id, $command_response, $data);
while ($select->can_read(0.5)) {
$socket->recv($buffer, 4, MSG_PEEK);
$size = unpack("V", $buffer);
last if (!defined($size));
$socket->recv($buffer, $size+4, MSG_WAITALL);
($size, $request_id, $command_response, $data) =
unpack('VVVZ*x', $buffer);
$reply .= "$data";
}
return $reply;
}
1;
__END__
=head1 NAME
HL2 - Perl extension Half-Life 2 (Source) engine Rcon interface
=head1 SYNOPSIS
use HL2;
my $rcon = HL2->new(
hostname => "insub.org",
password => "yourpass",
timeout => 3,
);
print $rcon->run("status");
$rcon->run("changelevel de_dust");
=head1 DESCRIPTION
Use this module to send "rcon" (remote control) commands to a
Source server, such as Counter-Strike Source.
=head1 METHODS
=over 4
=item $rcon = HL2->new()
Create a new rcon object. You can specify the hostname,
password and/or timeout in the constructor, or use the class
methods to change them (see SYNOPSIS).
=item $rcon->authenticated()
Returns true if session has succesfully authenticated.
=item $rcon->password()
Returns current password, or sets it. Note that setting
this after authentication will not have any effect unless
you reconnect with $rcon->authenticated(0).
=item $rcon->hostname()
Returns current hostname, or sets it.
=item $rcon->port()
Returns current port, or sets it. Defaults to 27015.
=item $rcon->sequence()
Returns the current command sequence. This starts
at 0 and increases with each call.
=item $rcon->socket()
Returns the IO::Socket object for the session or
creates a new one if none exists.
=item $rcon->timeout()
Returns the TCP response timeout, or sets it. Defaults
to 5.
=item $rcon->connect()
Connects to remote server.
=item $packet = $rcon->packet($type, $payload)
Creats a packet to send to the remote server.
Type should be either CMD or AUTH, e.g.:
print $socket $rcon->packet(AUTH, $rcon->password())
=item $rcon->authenticate()
Authenticates with the rcon server. This is done automatically
when you try to run a command.
=item $response = $rcon->run($command)
Runs a command on the remote server and returns its response
=item $response = $rcon->response()
Reads a response packet from the server. This is called
authomatically when you use run() so you shouldn't need to
use this.
=back
=head1 CAVEATS
This module DOES NOT DO ANY COMMAND VALIDATION. You are responsible for
sending sane commands to the server. If you use this with CGI that allows
internet users to submit console commands, you MUST taint-check this. Users
with RCON access can send anything to the console. I highly recommend that you
restrict what console commands a user can send.
=head1 BUGS
As of this writing, there are some bugs with the rcon server itself.
One such bug is that some output goes to the console instead of to
the rcon client. For example, the command "listid" causes the list
of banned users to spew to the physical console instead of back to
the rcon client, making it effectively useless. If you are not getting
back a response you expected, please verify that it's not going to
the console (run srcds in screen so you can access it) before submitting
a bug report to me about it. Or better yet, submit a bug report to Valve.
Authentication validation is currently unsupported.
=head1 SEE ALSO
http://gruntle.org/projects/
http://insub.org/cs/
=head1 AUTHOR
Chris Jones, E<lt>cjones@gruntle.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2004 by Chris Jones
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut

282
KKrcon/KKrcon.pm Normal file
View file

@ -0,0 +1,282 @@
package KKrcon;
#
# KKrcon Perl Module - execute commands on a remote Half-Life server using Rcon.
# http://kkrcon.sourceforge.net
#
# Synopsis:
#
# use KKrcon;
# $rcon = new KKrcon(Password=>PASSWORD, [Host=>HOST], [Port=>PORT], [Type=>"new"|"old"]);
# $result = $rcon->execute(COMMAND);
# %players = $rcon->getPlayers();
# $player = $rcon->getPlayer(USERID);
#
# Copyright (C) 2000, 2001 Rod May
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
use Socket;
use Sys::Hostname;
# Release version number
$VERSION = "2.11";
##
## Main
##
#
# Constructor
#
sub new
{
my $class_name = shift;
my %params = @_;
my $self = {};
bless($self, $class_name);
my %server_types = (new=>1, old=>2);
# Check parameters
$params{"Host"} = "127.0.0.1" unless($params{"Host"});
$params{"Port"} = 27015 unless($params{"Port"});
$params{"Type"} = "new" unless($params{"Type"});
# Initialise properties
$self->{"rcon_password"} = $params{"Password"}
or die("KKrcon: a Password is required\n");
$self->{"server_host"} = $params{"Host"};
$self->{"server_port"} = int($params{"Port"})
or die("KKrcon: invalid Port \"" . $params{"Port"} . "\"\n");
$self->{"server_type"} = ($server_types{$params{"Type"}} || 1);
$self->{"error"} = "";
# Set up socket parameters
$self->{"_ipaddr"} = gethostbyname($self->{"server_host"})
or die("KKrcon: could not resolve Host \"" . $self->{"server_host"} . "\"\n");
return $self;
}
#
# Execute an Rcon command and return the response
#
sub execute
{
my ($self, $command) = @_;
my $msg;
my $ans;
if ($self->{"server_type"} == 1)
{
# version x.1.0.6+ HL server
$msg = "\xFF\xFF\xFF\xFFchallenge rcon\n\0";
$ans = $self->_sendrecv($msg);
if ($ans =~ /challenge +rcon +(\d+)/)
{
$msg = "\xFF\xFF\xFF\xFFrcon $1 \"" . $self->{"rcon_password"} . "\" $command\0";
$ans = $self->_sendrecv($msg);
}
elsif (!$self->error())
{
$ans = "";
$self->{"error"} = "No challenge response";
}
}
else
{
# QW/Q2/Q3 or old HL server
$msg = "\xFF\xFF\xFF\xFFrcon " . $self->{"rcon_password"} . " $command\n\0";
$ans = $self->_sendrecv($msg);
}
if ($ans =~ /bad rcon_password/i)
{
$self->{"error"} = "Bad Password";
}
return $ans;
}
sub _sendrecv
{
my ($self, $msg) = @_;
my $host = $self->{"server_host"};
my $port = $self->{"server_port"};
my $ipaddr = $self->{"_ipaddr"};
# Open socket
socket(RCON, PF_INET, SOCK_DGRAM, getprotobyname("udp")) or die("KKrcon: socket: $!\n");
my $hispaddr = sockaddr_in($port, $ipaddr);
unless(defined(send(RCON, $msg, 0, $hispaddr)))
{
die("KKrcon: send $ip:$port : $!");
}
my $rin;
vec($rin, fileno(RCON), 1) = 1;
my $ans;
if (select($rin, undef, undef, 10.0)) {
$hispaddr = recv(RCON, $ans, 8192, 0);
if (defined($ans)) {
$ans =~ s/^\xFF\xFF\xFF\xFFprint\n//; # CoD2 response
$ans =~ s/\x00+$//; # trailing crap
$ans =~ s/^\xFF\xFF\xFF\xFFl//; # HL response
$ans =~ s/^\xFF\xFF\xFF\xFFn//; # QW response
$ans =~ s/^\xFF\xFF\xFF\xFF//; # Q2/Q3 response
$ans =~ s/^\xFE\xFF\xFF\xFF.....//; # old HL bug/feature
if (length($ans) > 512) {
my $tmp;
my @explode;
while (select($rin, undef, undef, 0.05)) {
@explode = split(/\n/, $ans);
$explode[$#explode] =~ s/^ //;
$explode[$#explode] = 'X' . $explode[$#explode];
$ans = join("\n", @explode);
$hispaddr = recv(RCON, $tmp, 8192, 0);
if (defined($tmp)) {
$tmp =~ s/^\xFF\xFF\xFF\xFFprint\n//; # CoD2 response
$tmp =~ s/\x00+$//; # trailing crap
$tmp =~ s/^\xFF\xFF\xFF\xFFl//; # HL response
$tmp =~ s/^\xFF\xFF\xFF\xFFn//; # QW response
$tmp =~ s/^\xFF\xFF\xFF\xFF//; # Q2/Q3 response
$tmp =~ s/^\xFE\xFF\xFF\xFF.....//; # old HL bug/feature
$ans .= $tmp;
}
}
}
}
}
# Close socket
close(RCON);
if (!defined($ans)) {
$ans = "";
$self->{"error"} = "Rcon timeout";
}
return $ans;
}
#
# Get error message
#
sub error
{
my ($self) = @_;
return $self->{"error"};
}
#
# Parse "status" command output into player information
#
sub getPlayers
{
my ($self) = @_;
my $status = $self->execute("status");
my @lines = split(/[\r\n]+/, $status);
my %players;
foreach $line (@lines)
{
if ($line =~ /^\#[\s\d]\d\s+
(.+)\s+ # name
(\d+)\s+ # userid
(\d+)\s+ # wonid
([\d-]+)\s+ # frags
([\d:]+)\s+ # time
(\d+)\s+ # ping
(\d+)\s+ # loss
(\S+) # addr
$/x)
{
my $name = $1;
my $userid = $2;
my $wonid = $3;
my $frags = $4;
my $time = $5;
my $ping = $6;
my $loss = $7;
my $address = $8;
$players{$userid} = {
"Name" => $name,
"UserID" => $userid,
"WONID" => $wonid,
"Frags" => $frags,
"Time" => $time,
"Ping" => $ping,
"Loss" => $loss,
"Address" => $address
};
}
}
return %players;
}
#
# Get information about a player by userID
#
sub getPlayer
{
my ($self, $userid) = @_;
my %players = $self->getPlayers();
if (defined($players{$userid}))
{
return $players{$userid};
}
else
{
$self->{"error"} = "No such player # $userid";
return 0;
}
}
1;
# end

544
Minecraft/RCON.pm Normal file
View file

@ -0,0 +1,544 @@
# Minecraft::RCON - RCON remote console for Minecraft
#
# 1.x and above by Ryan Thompson <rjt@cpan.org>
#
# Original (0.1.x) by Fredrik Vold, no copyrights, no rights reserved.
# This is absolutely free software, and you can do with it as you please.
# If you do derive your own work from it, however, it'd be nice with some
# credits to me somewhere in the comments of that work.
#
# Based on http:://wiki.vg/RCON documentation
package Minecraft::RCON;
our $VERSION = '1.03';
use 5.010;
use strict;
use warnings;
no warnings 'uninitialized';
use Term::ANSIColor 3.01;
use IO::Socket 1.18; # autoflush
use Carp;
use constant {
# Packet types
AUTH => 3, # Minecraft RCON login packet type
AUTH_RESPONSE => 2, # Server auth response
AUTH_FAIL => -1, # Auth failure (password invalid)
COMMAND => 2, # Command packet type
RESPONSE_VALUE => 0, # Server response
};
# Minecraft -> ANSI color map
my %COLOR = map { $_->[1] => color($_->[0]) } (
[black => '0'], [blue => '1'], [green => '2'],
[cyan => '3'], [red => '4'], [magenta => '5'],
[yellow => '6'], [white => '7'], [bright_black => '8'],
[bright_blue => '9'], [bright_green => 'a'], [bright_cyan => 'b'],
[bright_red => 'c'], [bright_magenta => 'd'], [yellow => 'e'],
[bright_white => 'f'],
[bold => 'l'], [concealed => 'm'], [underline => 'n'],
[reverse => 'o'], [reset => 'r'],
);
# Defaults for new objects. Override in constructor or with accessors.
sub _DEFAULTS(%) {
(
address => '127.0.0.1',
port => 25575,
password => '',
color_mode => 'strip',
request_id => 0,
# DEPRECATED options
strip_color => undef,
convert_color => undef,
@_, # Subclasses may override
);
}
# DEPRECATED warning text for convenience/consistency
my $DEP = 'deprecated and will be removed in a future release.';
sub new {
my $class = shift;
my %opts = 'HASH' eq ref $_[0] ? %{$_[0]} : @_;
my %DEFAULTS = _DEFAULTS();
# DEPRECATED -- Warn and transition to new option
if ($opts{convert_color}) {
carp "convert_color $DEP\nConverted to color_mode => 'convert'.";
$opts{color_mode} = 'convert';
}
if ($opts{strip_color}) {
carp "strip_color $DEP\nConverted to color_mode => 'strip'.";
$opts{color_mode} = 'strip';
}
my @unknowns = grep { not exists $DEFAULTS{$_} } sort keys %opts;
carp "Ignoring unknown option(s): " . join(', ', @unknowns) if @unknowns;
bless { %DEFAULTS, %opts }, $class;
}
sub connect {
my ($s) = @_;
return 1 if $s->connected;
croak 'Password required' unless length $s->{password};
$s->{socket} = IO::Socket::INET->new(
PeerAddr => $s->{address},
PeerPort => $s->{port},
Proto => 'tcp',
) or croak "Connection to $s->{address}:$s->{port} failed: .$!";
my $id = $s->_next_id;
$s->_send_encode(AUTH, $id, $s->{password});
my ($size,$res_id,$type,$payload) = $s->_recv_decode;
# Force a reconnect if we're about to error out
$s->disconnect unless $type == AUTH_RESPONSE and $id == $res_id;
croak 'RCON authentication failed' if $res_id == AUTH_FAIL;
croak "Expected AUTH_RESPONSE(2), got $type" if $type != AUTH_RESPONSE;
croak "Expected ID $id, got $res_id" if $id != $res_id;
croak "Non-blank payload <$payload>" if length $payload;
return 1;
}
sub connected { $_[0]->{socket} and $_[0]->{socket}->connected }
sub disconnect {
$_[0]->{socket}->shutdown(2) if $_[0]->connected;
delete $_[0]->{socket} if exists $_[0]->{socket};
1;
}
sub command {
my ($s, $command, $mode) = @_;
croak 'Command required' unless length $command;
croak 'Not connected' unless $s->connected;
my $id = $s->_next_id;
my $nonce = 16 + int rand(2 ** 15 - 16); # Avoid 0..15
$s->_send_encode(COMMAND, $id, $command);
$s->_send_encode($nonce, $id, 'nonce');
my $res = '';
while (1) {
my ($size,$res_id,$type,$payload) = $s->_recv_decode;
if ($id != $res_id) {
$s->disconnect;
croak sprintf(
"Desync. Expected %d (0x%4x), got %d (0x%4x). Disconnected.",
$id, $id, $res_id, $res_id
);
}
croak "size:$size id:$id got type $type, not RESPONSE_VALUE(0)"
if $type != RESPONSE_VALUE;
last if $payload eq sprintf 'Unknown request %x', $nonce;
$res .= $payload;
}
$s->color_convert($res, defined $mode ? $mode : $s->{color_mode});
}
sub color_mode {
my ($s, $mode, $code) = @_;
return $s->{color_mode} if not defined $mode;
croak 'Invalid color mode.'
unless $mode =~ /^(strip|convert|ignore)$/;
if ($code) {
my $was = $s->{color_mode};
$s->{color_mode} = $mode;
$code->();
$s->{color_mode} = $was;
} else {
$s->{color_mode} = $mode;
}
}
sub color_convert {
my ($s, $text, $mode) = @_;
$mode = $s->{color_mode} if not defined $mode;
my $re = qr/\x{00A7}(.)/o;
$text =~ s/$re//g if $mode eq 'strip';
$text =~ s/$re/$COLOR{$1}/g if $mode eq 'convert';
$text .= $COLOR{r} if $mode eq 'convert' and $text =~ /\e\[/;
$text;
}
sub DESTROY { $_[0]->disconnect }
#
# DEPRECATED methods
#
sub convert_color {
my ($s, $val) = @_;
carp "convert_color() is $DEP\nUse color_mode('convert') instead";
$s->color_mode('convert') if $val;
$s->color_mode eq 'convert';
}
sub strip_color {
my ($s, $val) = @_;
carp "strip_color() is $DEP\nUse color_mode('strip') instead";
$s->color_mode('strip') if $val;
$s->color_mode eq 'strip';
}
sub address {
carp "address() is $DEP";
$_[0]->{address} = $_[1] if defined $_[1];
$_[0]->{address};
}
sub port {
carp "port() is $DEP";
$_[0]->{port} = $_[1] if defined $_[1];
$_[0]->{port};
}
sub password {
carp "password() is $DEP";
$_[0]->{password} = $_[1] if defined $_[1];
$_[0]->{password};
}
#
# Private helpers
#
# Increment and return the next request ID, wrapping at 2**31-1
sub _next_id { $_[0]->{request_id} = ($_[0]->{request_id} + 1) % 2**31 }
# Form and send a packet of the specified type, request_id and payload
sub _send_encode {
my ($s, $type, $id, $payload) = @_;
confess "Request ID `$id' is not an integer" unless $id =~ /^\d+$/;
$payload = "" unless defined $payload;
my $data = pack('V!V' => $id, $type) . $payload . "\0\0";
$s->{socket}->send(pack(V => length $data) . $data);
}
# Grab a single packet.
sub _recv_decode {
my ($s) = @_;
confess "_recv_decode when not connected" unless $s->connected;
local $_; $s->{socket}->recv($_, 4);
my $size = unpack 'V';
$_ = '';
my $frags = 0;
croak "Zero length packet" unless $size;
while ($size > length) {
my $buf;
$s->{socket}->recv($buf, $size);
$_ .= $buf;
$frags++;
}
croak 'Packet too short. ' . length($_) . ' < 10' if 10 > length($_);
croak "Received packet missing terminator" unless s/\0\0$//;
$size, unpack 'V!V(A*)';
}
1;
__END__
=head1 NAME
Minecraft::RCON - RCON remote console communication with Minecraft servers
=head1 VERSION
Version 1.03
=head1 SYNOPSIS
use Minecraft::RCON;
my $rcon = Minecraft::RCON->new( { password => 'secret' } );
eval { $rcon->connect };
die "Connection failed: $@" if $@;
my $response;
eval { $response = $rcon->command('help') };
say $@ ? "Error: $@" : "Response: $response";
$rcon->disconnect;
=head1 DESCRIPTION
C<Minecraft::RCON> provides a nice object interface for talking to Mojang AB's
game Minecraft. Intended for use with their multiplayer servers, specifically
I<your> multiplayer server, as you will need the correct RCON password, and
RCON must be enabled on said server.
=head1 CONSTRUCTOR
=head2 new( %options )
Create a new RCON object. Note we do not connect automatically; see
C<connect()> for that. The properties and their defaults are shown below:
my $rcon = Minecraft::RCON->new({
address => '127.0.0.1',
port => 25575,
password => '',
color_mode => 'strip',
error_mode => 'error',
});
We will C<carp()> but not die in the event that any unknown options are
provided.
=over 4
=item address
The hostname or IP address to connect to.
=item port
The TCP port number to connect to.
=item password
The plaintext password used to authenticate. This password must match the
C<rcon.password=> line in the F<server.properties> file for your server.
=item color_mode
The color mode controls how C<Minecraft::RCON> handles color codes sent back
by the Minecraft server. It must be one of C<strip>, C<convert>, or C<ignore>.
constants. See C<color_mode()> for more information.
=back
=head1 METHODS
=head2 connect
eval { $rcon->connect }; # $@ will be set on error
Attempt to connect to the configured address and port, and issue the
configured password for authentication.
If already connected, returns C<undef> (nothing to be done).
This method will C<croak> if the connection fails for any reason.
Otherwise, returns a true value.
=head2 connected
say "We are connected!" if $rcon->connected;
Returns true if we have a connected socket, false otherwise. Note that we have
no way to tell if there is a misbehaving Minecraft server on the other
side of that socket, so it is entirely possible for this command (or
C<connect()>) to succeed, but C<command()> calls to fail.
=head2 disconnect
$rcon->disconnect;
Disconnects from the server by closing the socket. Always succeeds.
=head2 command( $command, [ $color_mode ] )
my $response = $rcon->command("data get block $x $y $z");
my $ansi = $rcon->command('list', 'convert');
Sends the C<$command> to the Minecraft server, and synchronously waits for the
response. This method is capable of handling fragmented responses (spread over
several response packets), and will concatenate them all before returning the
result.
The resulting server response will have its color codes stripped, converted,
or ignored, according to the current C<color_mode()> setting, unless a
C<$color_mode> is given, which will override the current setting for this
command only.
=head2 color_mode( $color_mode, [ $code ] )
$rcon->color_mode('strip');
When a command response is received, the color codes it contains can be
stripped, converted to ANSI, or left alone, depending on this setting.
C<$color_mode> is optional, unless C<$code> is also specified.
The valid modes are as follows:
=over 10
=item strip
Strip any color codes, returning the plaintext.
=item convert
Convert any color codes to the equivalent ANSI escape sequences, suitable for
display in a terminal.
=item ignore
Ignore color codes, returning the full command response verbatim.
=back
The current mode will be returned.
If C<$code> is specified and is a C<CODE> ref, C<color_mode()> will apply the
new color mode, run C<$code-E<gt>()>, and then restore the original color
mode. This is useful when you use one color mode most of the time, but have
sections of code requiring a different mode:
Example usage:
# Color mode is 'convert'
$rcon->color_mode(strip => sub {
my $plaintext = $rcon->command('...');
});
But see also C<command($cmd, $mode)> for running single commands with
another color mode.
=head2 color_convert( $string, [ $color_mode ] )
my $response = $rcon->command('list');
my ($strip, $ansi) = map { $rcon->color_convert($response, $_) }
qw<strip convert>;
This method is used internally by C<command()> to convert command responses as
configured in the object. However, C<color_convert()> itself may be useful in
some applications where a stripped version of the response may be needed for
parsing, while an ANSI version may be desired for display to a terminal, for
example, without having to run the command itself (with possible side-effects)
a second time. For C<color_convert()> to do anything meaningful, your object's
C<color_mode> should be set to C<ignore>.
=head1 ERROR HANDLING
This module C<croak>s (see L<Carp>) for almost all errors.
When an error does not affect control flow, we will C<carp> instead.
Thus, C<command()> and C<connect()>, at minimum, should be wrapped in block
C<eval>:
eval { $result = $rcon->command('list'); };
warn "I don't know who is online because: $@" if $@;
If a little extra syntactic sugar is desired, you can use an exception handler
like L<Try::Tiny> instead:
use Try::Tiny;
try {
$result = $rcon->command('list');
} catch {
warn "I don't know who is online because: $_";
}
=head1 DEPRECATED METHODS
The following methods have been deprecated. They will issue a warning to
STDOUT when called, and will be removed in a future release.
=head2 convert_color ( $enable )
If C<$enable> is a true value, change the color mode to C<convert>.
Returns 1 if the current color mode is C<convert>, undef otherwise.
B<Deprecated.> Use C<color_mode('convert')> instead.
=head2 strip_color
If C<$enable> is a true value, change the color mode to C<strip>.
Returns 1 if the current color mode is C<strip>, undef otherwise.
B<Deprecated.> Use C<color_mode('strip')> instead.
=head1 SUPPORT
=over 4
=item L<https://github.com/rjt-pl/Minecraft-RCON.git>: Source code repository
=item L<https://github.com/rjt-pl/Minecraft-RCON/issues>: Bug reports and feature requests
=back
=head1 SEE ALSO
=over 4
=item L<Net::RCON::Minecraft> for an alternative API
=item L<Terminal::ANSIColor>, L<IO::Socket::INET>
=item L<https://developer.valvesoftware.com/wiki/Source_RCON_Protocol>
=item L<https://wiki.vg/RCON>
=back
=head1 AFFILIATION WITH MOJANG
I<Note from original author, Fredrik Vold:>
I am in no way affiliated with Mojang or the development of Minecraft.
I'm simply a fan of their work, and a server admin myself. I needed
some RCON magic for my servers website, and there was no perl module.
It is important that everyone using this module understands that if
Mojang changes the way RCON works, I won't be notified any sooner than
anyone else, and I have no special avenue of connection with them.
=head1 AUTHORS
=over 4
=item B<Ryan Thompson> C<E<lt>rjt@cpan.orgE<gt>>
Addition of unit test suite, fragmentation support, and other improvements.
This program is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.
L<http://dev.perl.org/licenses/artistic.html>
=item B<Fredrik Vold> C<E<lt>fredrik@webkonsept.comE<gt>>
Original (0.1.x) author.
No copyright claimed, no rights reserved.
You are absolutely free to do as you wish with this code, but mentioning me in
your comments or whatever would be nice.
Minecraft is a trademark of Mojang AB. Name used in accordance with my
interpretation of L<http://www.minecraft.net/terms>, to the best of my
knowledge.
=back

37
README.md Normal file
View file

@ -0,0 +1,37 @@
# GSP Linux Agent
Perl-based agent that receives signed RPC calls from the GameServer Panel (GSP) and launches customer servers on Linux hosts. It replaces the upstream OGP agent with our service wrappers, stats hooks, and documentation.
## Features
- TLS-ready RPC listener (default port 12679/TCP)
- GNU Screen process management + PID tracking
- SteamCMD helpers for installing/updating games
- Optional resource stats reporting to MySQL
- Systemd service definitions and bootstrap scripts
## Install (Ubuntu example)
```bash
sudo apt update
sudo apt install -y git curl rsync screen perl libxml-parser-perl libpath-class-perl
sudo git clone https://github.com/GameServerPanel/GSP-Agent-Linux.git /opt/gsp-agent
cd /opt/gsp-agent
sudo bash install.sh
sudo bash agent_conf.sh -s "root-password" -u ogp_agent
```
After running `agent_conf.sh`, edit `/home/ogp_agent/Cfg/Config.pm` so `listen_ip`, `listen_port`, `key`, and `web_api_url` match the server entry you created inside the GSP web panel.
## Documentation
Offline instructions, upgrade notes, and troubleshooting tips live under [`documentation/agent-guide.md`](documentation/agent-guide.md). Import that file into your wiki if you need a browsable version.
## Related projects
- [GSP](https://github.com/GameServerPanel/GSP) The web panel that issues commands to this agent.
- [GSP-Agent-Windows](https://github.com/GameServerPanel/GSP-Agent-Windows) Windows counterpart with Task Scheduler wrappers.
## Contributing
Pull requests are welcome. Please keep Perl code formatted with `perltidy`, validate new service files on a staging host, and document behavior changes in `documentation/agent-guide.md`.

1915
Schedule/Cron.pm Normal file

File diff suppressed because it is too large Load diff

205
Time/CTime.pm Normal file
View file

@ -0,0 +1,205 @@
package Time::CTime;
require 5.000;
use Time::Timezone;
use Time::CTime;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(ctime asctime strftime);
@EXPORT_OK = qw(asctime_n ctime_n @DoW @MoY @DayOfWeek @MonthOfYear);
use strict;
# constants
use vars qw(@DoW @DayOfWeek @MoY @MonthOfYear %strftime_conversion $VERSION);
use vars qw($template $sec $min $hour $mday $mon $year $wday $yday $isdst);
$VERSION = 2011.0505;
CONFIG: {
@DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
@DayOfWeek = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
@MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@MonthOfYear = qw(January February March April May June
July August September October November December);
%strftime_conversion = (
'%', sub { '%' },
'a', sub { $DoW[$wday] },
'A', sub { $DayOfWeek[$wday] },
'b', sub { $MoY[$mon] },
'B', sub { $MonthOfYear[$mon] },
'c', sub { asctime_n($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst, "") },
'd', sub { sprintf("%02d", $mday); },
'D', sub { sprintf("%02d/%02d/%02d", $mon+1, $mday, $year%100) },
'e', sub { sprintf("%2d", $mday); },
'f', sub { fracprintf ("%3.3f", $sec); },
'F', sub { fracprintf ("%6.6f", $sec); },
'h', sub { $MoY[$mon] },
'H', sub { sprintf("%02d", $hour) },
'I', sub { sprintf("%02d", $hour % 12 || 12) },
'j', sub { sprintf("%03d", $yday + 1) },
'k', sub { sprintf("%2d", $hour); },
'l', sub { sprintf("%2d", $hour % 12 || 12) },
'm', sub { sprintf("%02d", $mon+1); },
'M', sub { sprintf("%02d", $min) },
'n', sub { "\n" },
'o', sub { sprintf("%d%s", $mday, (($mday < 20 && $mday > 3) ? 'th' : ($mday%10 == 1 ? "st" : ($mday%10 == 2 ? "nd" : ($mday%10 == 3 ? "rd" : "th"))))) },
'p', sub { $hour > 11 ? "PM" : "AM" },
'r', sub { sprintf("%02d:%02d:%02d %s", $hour % 12 || 12, $min, $sec, $hour > 11 ? 'PM' : 'AM') },
'R', sub { sprintf("%02d:%02d", $hour, $min) },
'S', sub { sprintf("%02d", $sec) },
't', sub { "\t" },
'T', sub { sprintf("%02d:%02d:%02d", $hour, $min, $sec) },
'U', sub { wkyr(0, $wday, $yday) },
'v', sub { sprintf("%2d-%s-%4d", $mday, $MoY[$mon], $year+1900) },
'w', sub { $wday },
'W', sub { wkyr(1, $wday, $yday) },
'y', sub { sprintf("%02d",$year%100) },
'Y', sub { $year + 1900 },
'x', sub { sprintf("%02d/%02d/%02d", $mon + 1, $mday, $year%100) },
'X', sub { sprintf("%02d:%02d:%02d", $hour, $min, $sec) },
'Z', sub { &tz2zone(undef,undef,$isdst) }
# z sprintf("%+03d%02d", $offset / 3600, ($offset % 3600)/60);
);
}
sub fracprintf {
my($t,$s) = @_;
my($p) = sprintf($t, $s-int($s));
$p=~s/^0+//;
$p;
}
sub asctime_n {
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst, $TZname) = @_;
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst, $TZname) = localtime($sec) unless defined $min;
$year += 1900;
$TZname .= ' '
if $TZname;
sprintf("%s %s %2d %2d:%02d:%02d %s%4d",
$DoW[$wday], $MoY[$mon], $mday, $hour, $min, $sec, $TZname, $year);
}
sub asctime
{
return asctime_n(@_)."\n";
}
# is this formula right?
sub wkyr {
my($wstart, $wday, $yday) = @_;
$wday = ($wday + 7 - $wstart) % 7;
return int(($yday - $wday + 13) / 7 - 1);
}
# ctime($time)
sub ctime {
my($time) = @_;
asctime(localtime($time), &tz2zone(undef,$time));
}
sub ctime_n {
my($time) = @_;
asctime_n(localtime($time), &tz2zone(undef,$time));
}
# strftime($template, @time_struct)
#
# Does not support locales
sub strftime {
local ($template, $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = @_;
undef $@;
$template =~ s/%([%aAbBcdDefFhHIjklmMnopQrRStTUvwWxXyYZ])/&{$Time::CTime::strftime_conversion{$1}}()/egs;
die $@ if $@;
return $template;
}
1;
__END__
=head1 NAME
Time::CTime -- format times ala POSIX asctime
=head1 SYNOPSIS
use Time::CTime
print ctime(time);
print asctime(localtime(time));
print strftime(template, localtime(time));
=head2 strftime conversions
%% PERCENT
%a day of the week abbr
%A day of the week
%b month abbr
%B month
%c ctime format: Sat Nov 19 21:05:57 1994
%d DD
%D MM/DD/YY
%e numeric day of the month
%f floating point seconds (milliseconds): .314
%F floating point seconds (microseconds): .314159
%h month abbr
%H hour, 24 hour clock, leading 0's)
%I hour, 12 hour clock, leading 0's)
%j day of the year
%k hour
%l hour, 12 hour clock
%m month number, starting with 1, leading 0's
%M minute, leading 0's
%n NEWLINE
%o ornate day of month -- "1st", "2nd", "25th", etc.
%p AM or PM
%r time format: 09:05:57 PM
%R time format: 21:05
%S seconds, leading 0's
%t TAB
%T time format: 21:05:57
%U week number, Sunday as first day of week
%v DD-Mon-Year
%w day of the week, numerically, Sunday == 0
%W week number, Monday as first day of week
%x date format: 11/19/94
%X time format: 21:05:57
%y year (2 digits)
%Y year (4 digits)
%Z timezone in ascii. eg: PST
=head1 DESCRIPTION
This module provides routines to format dates. They correspond
to the libc routines. &strftime() supports a pretty good set of
conversions -- more than most C libraries.
strftime supports a pretty good set of conversions.
The POSIX module has very similar functionality. You should consider
using it instead if you do not have allergic reactions to system
libraries.
=head1 GENESIS
Written by David Muir Sharnoff <muir@idiom.org>.
The starting point for this package was a posting by
Paul Foley <paul@ascent.com>
=head1 LICENSE
Copyright (C) 1996-2010 David Muir Sharnoff.
Copyright (C) 2011 Google, Inc.
License hereby
granted for anyone to use, modify or redistribute this module at
their own risk. Please feed useful changes back to cpan@dave.sharnoff.org.

83
Time/DaysInMonth.pm Normal file
View file

@ -0,0 +1,83 @@
package Time::DaysInMonth;
use Carp;
require 5.000;
@ISA = qw(Exporter);
@EXPORT = qw(days_in is_leap);
@EXPORT_OK = qw(%mltable);
use strict;
use vars qw($VERSION %mltable);
$VERSION = 99.1117;
CONFIG: {
%mltable = qw(
1 31
3 31
4 30
5 31
6 30
7 31
8 31
9 30
10 31
11 30
12 31);
}
sub days_in
{
# Month is 1..12
my ($year, $month) = @_;
return $mltable{$month+0} unless $month == 2;
return 28 unless &is_leap($year);
return 29;
}
sub is_leap
{
my ($year) = @_;
return 0 unless $year % 4 == 0;
return 1 unless $year % 100 == 0;
return 0 unless $year % 400 == 0;
return 1;
}
1;
__END__
=head1 NAME
Time::DaysInMonth -- simply report the number of days in a month
=head1 SYNOPSIS
use Time::DaysInMonth;
$days = days_in($year, $month_1_to_12);
$leapyear = is_leap($year);
=head1 DESCRIPTION
DaysInMonth is simply a package to report the number of days in
a month. That's all it does. Really!
=head1 AUTHOR
David Muir Sharnoff <muir@idiom.org>
=head1 BUGS
This only deals with the "modern" calendar. Look elsewhere for
historical time and date support.
=head1 LICENSE
Copyright (C) 1996-1999 David Muir Sharnoff. License hereby
granted for anyone to use, modify or redistribute this module at
their own risk. Please feed useful changes back to muir@idiom.org.

224
Time/JulianDay.pm Normal file
View file

@ -0,0 +1,224 @@
package Time::JulianDay;
require 5.000;
use Carp;
use Time::Timezone;
@ISA = qw(Exporter);
@EXPORT = qw(julian_day inverse_julian_day day_of_week
jd_secondsgm jd_secondslocal
jd_timegm jd_timelocal
gm_julian_day local_julian_day
);
@EXPORT_OK = qw($brit_jd);
use strict;
use integer;
# constants
use vars qw($brit_jd $jd_epoch $jd_epoch_remainder $VERSION);
$VERSION = 2011.0505;
# calculate the julian day, given $year, $month and $day
sub julian_day
{
my($year, $month, $day) = @_;
my($tmp);
use Carp;
# confess() unless defined $day;
$tmp = $day - 32075
+ 1461 * ( $year + 4800 - ( 14 - $month ) / 12 )/4
+ 367 * ( $month - 2 + ( ( 14 - $month ) / 12 ) * 12 ) / 12
- 3 * ( ( $year + 4900 - ( 14 - $month ) / 12 ) / 100 ) / 4
;
return($tmp);
}
sub gm_julian_day
{
my($secs) = @_;
my($sec, $min, $hour, $mon, $year, $day, $month);
($sec, $min, $hour, $day, $mon, $year) = gmtime($secs);
$month = $mon + 1;
$year += 1900;
return julian_day($year, $month, $day)
}
sub local_julian_day
{
my($secs) = @_;
my($sec, $min, $hour, $mon, $year, $day, $month);
($sec, $min, $hour, $day, $mon, $year) = localtime($secs);
$month = $mon + 1;
$year += 1900;
return julian_day($year, $month, $day)
}
sub day_of_week
{
my ($jd) = @_;
return (($jd + 1) % 7); # calculate weekday (0=Sun,6=Sat)
}
# The following defines the first day that the Gregorian calendar was used
# in the British Empire (Sep 14, 1752). The previous day was Sep 2, 1752
# by the Julian Calendar. The year began at March 25th before this date.
$brit_jd = 2361222;
# Usage: ($year,$month,$day) = &inverse_julian_day($julian_day)
sub inverse_julian_day
{
my($jd) = @_;
my($jdate_tmp);
my($m,$d,$y);
carp("warning: julian date $jd pre-dates British use of Gregorian calendar\n")
if ($jd < $brit_jd);
$jdate_tmp = $jd - 1721119;
$y = (4 * $jdate_tmp - 1)/146097;
$jdate_tmp = 4 * $jdate_tmp - 1 - 146097 * $y;
$d = $jdate_tmp/4;
$jdate_tmp = (4 * $d + 3)/1461;
$d = 4 * $d + 3 - 1461 * $jdate_tmp;
$d = ($d + 4)/4;
$m = (5 * $d - 3)/153;
$d = 5 * $d - 3 - 153 * $m;
$d = ($d + 5) / 5;
$y = 100 * $y + $jdate_tmp;
if($m < 10) {
$m += 3;
} else {
$m -= 9;
++$y;
}
return ($y, $m, $d);
}
{
my($sec, $min, $hour, $day, $mon, $year) = gmtime(0);
$year += 1900;
if ($year == 1970 && $mon == 0 && $day == 1) {
# standard unix time format
$jd_epoch = 2440588;
} else {
$jd_epoch = julian_day($year, $mon+1, $day);
}
$jd_epoch_remainder = $hour*3600 + $min*60 + $sec;
}
sub jd_secondsgm
{
my($jd, $hr, $min, $sec) = @_;
my($r) = (($jd - $jd_epoch) * 86400
+ $hr * 3600 + $min * 60
- $jd_epoch_remainder);
no integer;
return ($r + $sec);
use integer;
}
sub jd_secondslocal
{
my($jd, $hr, $min, $sec) = @_;
my $jds = jd_secondsgm($jd, $hr, $min, $sec);
return $jds - tz_local_offset($jds);
}
# this uses a 0-11 month to correctly reverse localtime()
sub jd_timelocal
{
my ($sec,$min,$hours,$mday,$mon,$year) = @_;
$year += 1900 unless $year > 1000;
my $jd = julian_day($year, $mon+1, $mday);
my $jds = jd_secondsgm($jd, $hours, $min, $sec);
return $jds - tz_local_offset($jds);
}
# this uses a 0-11 month to correctly reverse gmtime()
sub jd_timegm
{
my ($sec,$min,$hours,$mday,$mon,$year) = @_;
$year += 1900 unless $year > 1000;
my $jd = julian_day($year, $mon+1, $mday);
return jd_secondsgm($jd, $hours, $min, $sec);
}
1;
__END__
=head1 NAME
Time::JulianDay -- Julian calendar manipulations
=head1 SYNOPSIS
use Time::JulianDay
$jd = julian_day($year, $month_1_to_12, $day)
$jd = local_julian_day($seconds_since_1970);
$jd = gm_julian_day($seconds_since_1970);
($year, $month_1_to_12, $day) = inverse_julian_day($jd)
$dow = day_of_week($jd)
print (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[$dow];
$seconds_since_jan_1_1970 = jd_secondslocal($jd, $hour, $min, $sec)
$seconds_since_jan_1_1970 = jd_secondsgm($jd, $hour, $min, $sec)
$seconds_since_jan_1_1970 = jd_timelocal($sec,$min,$hours,$mday,$month_0_to_11,$year)
$seconds_since_jan_1_1970 = jd_timegm($sec,$min,$hours,$mday,$month_0_to_11,$year)
=head1 DESCRIPTION
JulianDay is a package that manipulates dates as number of days since
some time a long time ago. It's easy to add and subtract time
using julian days...
The day_of_week returned by day_of_week() is 0 for Sunday, and 6 for
Saturday and everything else is in between.
=head1 ERRATA
Time::JulianDay is not a correct implementation. There are two
problems. The first problem is that Time::JulianDay only works
with integers. Julian Day can be fractional to represent time
within a day. If you call inverse_julian_day() with a non-integer
time, it will often give you an incorrect result.
The second problem is that Julian Days start at noon rather than
midnight. The julian_day() function returns results that are too
large by 0.5.
What to do about these problems is currently open for debate. I'm
tempted to leave the current functions alone and add a second set
with more accurate behavior.
There is another implementation in Astro::Time that may be more accurate.
=head1 GENESIS
Written by David Muir Sharnoff <cpan@dave.sharnoff.org> with help from
previous work by
Kurt Jaeger aka PI <zrzr0111@helpdesk.rus.uni-stuttgart.de>
based on postings from: Ian Miller <ian_m@cix.compulink.co.uk>;
Gary Puckering <garyp%cognos.uucp@uunet.uu.net>
based on Collected Algorithms of the ACM ?;
and the unknown-to-me author of Time::Local.
=head1 LICENSE
Copyright (C) 1996-1999 David Muir Sharnoff. License hereby
granted for anyone to use, modify or redistribute this module at
their own risk. Please feed useful changes back to cpan@dave.sharnoff.org.

1258
Time/ParseDate.pm Normal file

File diff suppressed because it is too large Load diff

329
Time/Timezone.pm Normal file
View file

@ -0,0 +1,329 @@
package Time::Timezone;
require 5.002;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(tz2zone tz_local_offset tz_offset tz_name);
@EXPORT_OK = qw();
use Carp;
use strict;
# Parts stolen from code by Paul Foley <paul@ascent.com>
use vars qw($VERSION);
$VERSION = 2006.0814;
sub tz2zone
{
my($TZ, $time, $isdst) = @_;
use vars qw(%tzn_cache);
$TZ = defined($ENV{'TZ'}) ? ( $ENV{'TZ'} ? $ENV{'TZ'} : 'GMT' ) : ''
unless $TZ;
# Hack to deal with 'PST8PDT' format of TZ
# Note that this can't deal with all the esoteric forms, but it
# does recognize the most common: [:]STDoff[DST[off][,rule]]
if (! defined $isdst) {
my $j;
$time = time() unless $time;
($j, $j, $j, $j, $j, $j, $j, $j, $isdst) = localtime($time);
}
if (defined $tzn_cache{$TZ}->[$isdst]) {
return $tzn_cache{$TZ}->[$isdst];
}
if ($TZ =~ /^
( [^:\d+\-,] {3,} )
( [+-] ?
\d {1,2}
( : \d {1,2} ) {0,2}
)
( [^\d+\-,] {3,} )?
/x
) {
$TZ = $isdst ? $4 : $1;
$tzn_cache{$TZ} = [ $1, $4 ];
} else {
$tzn_cache{$TZ} = [ $TZ, $TZ ];
}
return $TZ;
}
sub tz_local_offset
{
my ($time) = @_;
$time = time() unless $time;
return &calc_off($time);
}
sub calc_off
{
my ($time) = @_;
my (@l) = localtime($time);
my (@g) = gmtime($time);
my $off;
$off = $l[0] - $g[0]
+ ($l[1] - $g[1]) * 60
+ ($l[2] - $g[2]) * 3600;
# subscript 7 is yday.
if ($l[7] == $g[7]) {
# done
} elsif ($l[7] == $g[7] + 1) {
$off += 86400;
} elsif ($l[7] == $g[7] - 1) {
$off -= 86400;
} elsif ($l[7] < $g[7]) {
# crossed over a year boundary!
# localtime is beginning of year, gmt is end
# therefore local is ahead
$off += 86400;
} else {
$off -= 86400;
}
return $off;
}
# constants
# The rest of the file originally comes from Graham Barr <bodg@tiuk.ti.com>
#
# Some references:
# http://www.weltzeituhr.com/laender/zeitzonen_e.shtml
# http://www.worldtimezone.com/wtz-names/timezonenames.html
# http://www.timegenie.com/timezones.php
CONFIG: {
use vars qw(%dstZone %zoneOff %dstZoneOff %Zone);
%dstZone = (
"brst" => -2*3600, # Brazil Summer Time (East Daylight)
"adt" => -3*3600, # Atlantic Daylight
"edt" => -4*3600, # Eastern Daylight
"cdt" => -5*3600, # Central Daylight
"mdt" => -6*3600, # Mountain Daylight
"pdt" => -7*3600, # Pacific Daylight
"ydt" => -8*3600, # Yukon Daylight
"hdt" => -9*3600, # Hawaii Daylight
"bst" => +1*3600, # British Summer
"mest" => +2*3600, # Middle European Summer
"met dst" => +2*3600, # Middle European Summer
"sst" => +2*3600, # Swedish Summer
"fst" => +2*3600, # French Summer
"eest" => +3*3600, # Eastern European Summer
"cest" => +2*3600, # Central European Daylight
"wadt" => +8*3600, # West Australian Daylight
"kdt" => +10*3600, # Korean Daylight
# "cadt" => +10*3600+1800, # Central Australian Daylight
"eadt" => +11*3600, # Eastern Australian Daylight
"nzdt" => +13*3600, # New Zealand Daylight
);
# not included due to ambiguity:
# IST Indian Standard Time +5.5
# Ireland Standard Time 0
# Israel Standard Time +2
# IDT Ireland Daylight Time +1
# Israel Daylight Time +3
# AMST Amazon Standard Time / -3
# Armenia Standard Time +8
# BST Brazil Standard -3
%Zone = (
"gmt" => 0, # Greenwich Mean
"ut" => 0, # Universal (Coordinated)
"utc" => 0,
"wet" => 0, # Western European
"wat" => -1*3600, # West Africa
"azost" => -1*3600, # Azores Standard Time
"cvt" => -1*3600, # Cape Verde Time
"at" => -2*3600, # Azores
"fnt" => -2*3600, # Brazil Time (Extreme East - Fernando Noronha)
"ndt" => -2*3600-1800,# Newfoundland Daylight
"art" => -3*3600, # Argentina Time
# For completeness. BST is also British Summer, and GST is also Guam Standard.
# "gst" => -3*3600, # Greenland Standard
"nft" => -3*3600-1800,# Newfoundland
# "nst" => -3*3600-1800,# Newfoundland Standard
"mnt" => -4*3600, # Brazil Time (West Standard - Manaus)
"ewt" => -4*3600, # U.S. Eastern War Time
"ast" => -4*3600, # Atlantic Standard
"bot" => -4*3600, # Bolivia Time
"vet" => -4*3600, # Venezuela Time
"est" => -5*3600, # Eastern Standard
"cot" => -5*3600, # Colombia Time
"act" => -5*3600, # Brazil Time (Extreme West - Acre)
"pet" => -5*3600, # Peru Time
"cst" => -6*3600, # Central Standard
"cest" => +2*3600, # Central European Summer
"mst" => -7*3600, # Mountain Standard
"pst" => -8*3600, # Pacific Standard
"yst" => -9*3600, # Yukon Standard
"hst" => -10*3600, # Hawaii Standard
"cat" => -10*3600, # Central Alaska
"ahst" => -10*3600, # Alaska-Hawaii Standard
"taht" => -10*3600, # Tahiti Time
"nt" => -11*3600, # Nome
"idlw" => -12*3600, # International Date Line West
"cet" => +1*3600, # Central European
"mez" => +1*3600, # Central European (German)
"met" => +1*3600, # Middle European
"mewt" => +1*3600, # Middle European Winter
"swt" => +1*3600, # Swedish Winter
"set" => +1*3600, # Seychelles
"fwt" => +1*3600, # French Winter
"west" => +1*3600, # Western Europe Summer Time
"eet" => +2*3600, # Eastern Europe, USSR Zone 1
"ukr" => +2*3600, # Ukraine
"sast" => +2*3600, # South Africa Standard Time
"bt" => +3*3600, # Baghdad, USSR Zone 2
"eat" => +3*3600, # East Africa Time
# "it" => +3*3600+1800,# Iran
"irst" => +3*3600+1800,# Iran Standard Time
"zp4" => +4*3600, # USSR Zone 3
"msd" => +4*3600, # Moscow Daylight Time
"sct" => +4*3600, # Seychelles Time
"zp5" => +5*3600, # USSR Zone 4
"azst" => +5*3600, # Azerbaijan Summer Time
"mvt" => +5*3600, # Maldives Time
"uzt" => +5*3600, # Uzbekistan Time
"ist" => +5*3600+1800,# Indian Standard
"zp6" => +6*3600, # USSR Zone 5
"lkt" => +6*3600, # Sri Lanka Time
"pkst" => +6*3600, # Pakistan Summer Time
"yekst" => +6*3600, # Yekaterinburg Summer Time
# For completeness. NST is also Newfoundland Stanard, and SST is also Swedish Summer.
# "nst" => +6*3600+1800,# North Sumatra
# "sst" => +7*3600, # South Sumatra, USSR Zone 6
"wast" => +7*3600, # West Australian Standard
"ict" => +7*3600, # Indochina Time
"wit" => +7*3600, # Western Indonesia Time
# "jt" => +7*3600+1800,# Java (3pm in Cronusland!)
"cct" => +8*3600, # China Coast, USSR Zone 7
"wst" => +8*3600, # West Australian Standard
"hkt" => +8*3600, # Hong Kong
"bnt" => +8*3600, # Brunei Darussalam Time
"cit" => +8*3600, # Central Indonesia Time
"myt" => +8*3600, # Malaysia Time
"pht" => +8*3600, # Philippines Time
"sgt" => +8*3600, # Singapore Time
"jst" => +9*3600, # Japan Standard, USSR Zone 8
"kst" => +9*3600, # Korean Standard
# "cast" => +9*3600+1800,# Central Australian Standard
"east" => +10*3600, # Eastern Australian Standard
"gst" => +10*3600, # Guam Standard, USSR Zone 9
"nct" => +11*3600, # New Caledonia Time
"nzt" => +12*3600, # New Zealand
"nzst" => +12*3600, # New Zealand Standard
"fjt" => +12*3600, # Fiji Time
"idle" => +12*3600, # International Date Line East
);
%zoneOff = reverse(%Zone);
%dstZoneOff = reverse(%dstZone);
# Preferences
$zoneOff{0} = 'gmt';
$dstZoneOff{3600} = 'bst';
}
sub tz_offset
{
my ($zone, $time) = @_;
return &tz_local_offset() unless($zone);
$time = time() unless $time;
my(@l) = localtime($time);
my $dst = $l[8];
$zone = lc $zone;
if ($zone =~ /^([\-\+]\d{3,4})$/) {
my $sign = $1 < 0 ? -1 : 1 ;
my $v = abs(0 + $1);
return $sign * 60 * (int($v / 100) * 60 + ($v % 100));
} elsif (exists $dstZone{$zone} && ($dst || !exists $Zone{$zone})) {
return $dstZone{$zone};
} elsif(exists $Zone{$zone}) {
return $Zone{$zone};
}
undef;
}
sub tz_name
{
my ($off, $time) = @_;
$time = time() unless $time;
my(@l) = localtime($time);
my $dst = $l[8];
if (exists $dstZoneOff{$off} && ($dst || !exists $zoneOff{$off})) {
return $dstZoneOff{$off};
} elsif (exists $zoneOff{$off}) {
return $zoneOff{$off};
}
sprintf("%+05d", int($off / 60) * 100 + $off % 60);
}
1;
__END__
=head1 NAME
Time::Timezone -- miscellaneous timezone manipulations routines
=head1 SYNOPSIS
use Time::Timezone;
print tz2zone();
print tz2zone($ENV{'TZ'});
print tz2zone($ENV{'TZ'}, time());
print tz2zone($ENV{'TZ'}, undef, $isdst);
$offset = tz_local_offset();
$offset = tz_offset($TZ);
=head1 DESCRIPTION
This is a collection of miscellaneous timezone manipulation routines.
C<tz2zone()> parses the TZ environment variable and returns a timezone
string suitable for inclusion in L<date>-like output. It optionally takes
a timezone string, a time, and a is-dst flag.
C<tz_local_offset()> determines the offset from GMT time in seconds. It
only does the calculation once.
C<tz_offset()> determines the offset from GMT in seconds of a specified
timezone.
C<tz_name()> determines the name of the timezone based on its offset
=head1 AUTHORS
Graham Barr <bodg@tiuk.ti.com>
David Muir Sharnoff <muir@idiom.org>
Paul Foley <paul@ascent.com>
=head1 LICENSE
David Muir Sharnoff disclaims any copyright and puts his contribution
to this module in the public domain.

732
agent_conf.sh Normal file
View file

@ -0,0 +1,732 @@
#!/bin/bash
#
# OGP - Open Game Panel
# Copyright (C) Copyright (C) 2008 - 2013 The OGP Development Team
#
# http://www.opengamepanel.org/
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
####################
# FUNCTIONs #
####################
function indexOf(){
# $1 = search string
# $2 = string or char to find
# Returns -1 if not found
x="${1%%$2*}"
[[ $x = $1 ]] && echo -1 || echo ${#x}
}
#####################
# CODE ##########
#####################
if [ $EUID -ne 0 -a "$(uname -o)" != "Cygwin" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
usage()
{
cat << EOF
Usage: $0 option
OPTIONS:
-s password Set the password for the agent's user (Linux)
-p password Set the password for cyg_server user (Windows)
-u ogpuser Set the username of the ogp user
EOF
}
while getopts "hs:p:u" OPTION
do
case $OPTION in
s)
sudo_password=$OPTARG
;;
p)
cs_psw=$OPTARG
;;
u)
agent_user=$OPTARG
;;
?)
exit
;;
esac
done
if [ -z $1 ]
then
usage
exit
fi
if [ "$(uname -o)" == "Cygwin" ]; then
if [ -z $cs_psw ]
then
echo "Must use -p argument instead of -s."
exit
fi
else
if [ -z $sudo_password ]
then
echo "Must use -s argument instead of -p."
exit
fi
fi
readonly DEFAULT_PORT=12679
readonly DEFAULT_IP=0.0.0.0
readonly DEFAULT_FTP_PORT=21
readonly DEFAULT_FTP_PASV_RANGE=40000:50000
readonly AGENT_VERSION='v1.4'
failed()
{
echo "ERROR: ${1}"
exit 1
}
agent_home="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cfgfile=${agent_home}/Cfg/Config.pm
prefsfile=${agent_home}/Cfg/Preferences.pm
bashprefsfile=${agent_home}/Cfg/bash_prefs.cfg
overwrite_config=1
if [ -e ${cfgfile} ]; then
while [ 1 ]
do
echo "Overwrite old configuration?"
echo -n "(yes/no) [Default yes]: "
read octmp
if [ "$octmp" == "yes" -o -z "$octmp" ]
then
break
elif [ "$octmp" == "no" ]
then
overwrite_config=0
break
else
echo "You need to type 'yes', 'no' or leave empty for default value [yes]."
fi
done
fi
if [ "X${overwrite_config}" == "X1" ]
then
if [ -z "$sudo_password" ]; then
if [ -f "$cfgfile" ]; then
sudo_password=`awk '/sudo_password/{print $3}' $cfgfile|sed -e "s#\('\)\(.*\)\(',\)#\2#"`
fi
fi
echo "#######################################################################"
echo ""
echo "OGP agent uses basic encryption to prevent unauthorized users from connecting"
echo "Enter a string of alpha-numeric characters for example 'abcd12345'"
echo "**** NOTE - Use the same key in your Open Game Panel webpage config file - they must match *****"
echo ""
while [ -z "${key}" ]
do
echo -n "Set encryption key: "
read key
done
echo
echo "Set the listen port for the agent. The default should be fine for everyone."
echo "However, if you want to change it that can be done here, otherwise just press Enter."
echo -n "Set listen port [Default ${DEFAULT_PORT}]: "
read port
if [ -z "${port}" ]
then
port=$DEFAULT_PORT
fi
echo
echo "Set the listen IP for the agent."
echo "Use ${DEFAULT_IP} to bind on all interfaces."
echo -n "Set listen IP [Default ${DEFAULT_IP}]: "
read ip
if [ -z "${ip}" ]
then
ip=$DEFAULT_IP
fi
while [ 1 ]
do
echo
echo "For some games the OGP panel is using Steam client."
echo "This client has its own license that you need to agree before continuing."
echo "This agreement is available at http://store.steampowered.com/subscriber_agreement/"
echo;
echo "Do you accept the terms of Steam(tm) Subscriber Agreement?"
echo -n "(Accept|Reject): "
read steam_license
if [ "$steam_license" == "Accept" -o "$steam_license" == "Reject" ]
then
break;
fi
echo "You need to type either 'Accept' or 'Reject'."
done
echo "Writing Config file - $cfgfile"
# Prompt for resource stats MySQL settings
echo
echo "Configure Resource Stats MySQL Database Connection:"
echo -n "Stats DB Host [Default 127.0.0.1]: "
read stats_db_host
if [ -z "$stats_db_host" ]; then stats_db_host='127.0.0.1'; fi
echo -n "Stats DB User [Default panel_user]: "
read stats_db_user
if [ -z "$stats_db_user" ]; then stats_db_user='panel_user'; fi
echo -n "Stats DB Password [Default REPLACE_ME]: "
read stats_db_pass
if [ -z "$stats_db_pass" ]; then stats_db_pass='REPLACE_ME'; fi
echo -n "Stats DB Name [Default panel_database]: "
read stats_db_name
if [ -z "$stats_db_name" ]; then stats_db_name='panel_database'; fi
echo -n "Stats Table Prefix [Default gsp_]: "
read stats_table_prefix
if [ -z "$stats_table_prefix" ]; then stats_table_prefix='gsp_'; fi
echo -n "Stats Frequency Minutes [Default 5]: "
read stats_frequency_minutes
if [ -z "$stats_frequency_minutes" ]; then stats_frequency_minutes='5'; fi
echo "%Cfg::Config = (
logfile => '${agent_home}/ogp_agent.log',
listen_port => '${port}',
listen_ip => '${ip}',
version => '${AGENT_VERSION}',
key => '${key}',
steam_license => '${steam_license}',
sudo_password => '${sudo_password}',
web_admin_api_key => '{your_admin_ogp_web_api_key_here}',
web_api_url => '{your_url_to_ogp_api.php}',
steam_dl_limit => '0',
# Resource stats database configuration
stats_db_host => '${stats_db_host}',
stats_db_user => '${stats_db_user}',
stats_db_pass => '${stats_db_pass}',
stats_db_name => '${stats_db_name}',
stats_table_prefix => '${stats_table_prefix}',
stats_frequency_minutes => '${stats_frequency_minutes}',
);" > $cfgfile
if [ $? != 0 ]
then
failed "Failed to write config file."
else
chmod 600 ${cfgfile} || failed "Failed to chmod ${cfgfile} to 600."
fi
echo;
while [ 1 ]
do
echo "The agent should be updated when the service is restarted or started?"
echo -n "(yes|no) [Default yes]: "
read auto_update
if [ "${auto_update}" == "yes" -o "${auto_update}" == "no" -o -z "${auto_update}" ]
then
if [ "${auto_update}" == "yes" ]
then
autoUpdate=1
elif [ -z "${auto_update}" ]
then
autoUpdate=1
else
autoUpdate=0
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [yes]."
done
echo;
while [ 1 ]
do
echo "The agent should backup the server log files in the game server directory?"
echo -n "(yes|no) [Default yes]: "
read log_local_copy
if [ "${log_local_copy}" == "yes" -o "${log_local_copy}" == "no" -o -z "${log_local_copy}" ]
then
if [ "${log_local_copy}" == "yes" ]
then
logLocalCopy=1
elif [ -z "${log_local_copy}" ]
then
logLocalCopy=1
else
logLocalCopy=0
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [yes]."
done
echo;
echo "After how many days should be deleted the old backups of server's logs?"
echo -n "[Default 30]: "
read delete_logs_after
case ${delete_logs_after} in
''|*[!0-9]*) deleteLogsAfter=30 ;;
*) deleteLogsAfter=${delete_logs_after} ;;
esac
echo;
while [ 1 ]
do
echo "The agent should automatically restart game servers if they crash?"
echo -n "(yes|no) [Default yes]: "
read auto_restart
if [ "${auto_restart}" == "yes" -o "${auto_restart}" == "no" -o -z "${auto_restart}" ]
then
if [ "${auto_restart}" == "yes" ]
then
autoRestart=1
elif [ -z "${auto_restart}" ]
then
autoRestart=1
else
autoRestart=0
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [yes]."
done
echo;
while [ 1 ]
do
echo "Should Open Game Panel create and manage FTP accounts?"
echo -n "(yes|no) [Default yes]: "
read manage_ftp
if [ "${manage_ftp}" == "yes" -o "${manage_ftp}" == "no" -o -z "${manage_ftp}" ]
then
if [ "${manage_ftp}" == "yes" ]
then
ogpManagesFTP=1
elif [ -z "${manage_ftp}" ]
then
ogpManagesFTP=1
else
ogpManagesFTP=0
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [yes]."
done
echo;
# Only ask these install questions if users want OGP to manage FTP accounts
if [ "$ogpManagesFTP" == "1" ]
then
if [ "$(uname -o)" != "Cygwin" ]; then
while [ 1 ]
do
echo "If you are running ISPConfig 3 in this machine the agent"
echo "can use it to create FTP accounts instead of using Pure-FTPd."
echo "Would you like to configure this agent to use the API of ISPConfig 3?"
echo -n "(yes|no) [Default no]: "
read IspConfig
if [ "${IspConfig}" == "yes" -o "${IspConfig}" == "no" -o -z "${IspConfig}" ]
then
if [ "${IspConfig}" == "yes" ]
then
ftpMethod="IspConfig"
else
IspConfig="no"
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [no]."
done
if [ "${IspConfig}" == "yes" ]
then
while [ 1 ]
do
echo "Do you use HTTPS to access to your ISPConfig 3 Panel?"
echo -n "(yes|no) [Default no]: "
read https
if [ "${https}" == "yes" -o "${https}" == "no" -o -z "${https}" ]
then
if [ "${https}" == "yes" ]
then
secure="s"
else
secure=""
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [no]."
done
echo -n "What port do you use to connect to your ISPConfig 3 Panel? [Default 8080]: "
read setport
case ${setport} in
''|*[!0-9]*) port=8080 ;;
*) port=${setport} ;;
esac
echo -n "Enter an user name to sing in remotelly (Remote user): "
read remote_login_username
echo -n "Enter password (Remote user): "
read remote_login_password
echo -e "<?php\n\$username = '${remote_login_username}';" > ${agent_home}/IspConfig/soap_config.php
echo "\$password = '${remote_login_password}';" >> ${agent_home}/IspConfig/soap_config.php
echo "\$soap_location = 'http${secure}://127.0.0.1:${port}/remote/index.php';" >> ${agent_home}/IspConfig/soap_config.php
echo -e "\$soap_uri = 'http${secure}://127.0.0.1:${port}/remote/';\n?>" >> ${agent_home}/IspConfig/soap_config.php
else
while [ 1 ]
do
echo;
echo "If you have installed the Easy Hosting Control Panel (EHCP - www.ehcpforce.tk),"
echo "the agent can use it to create FTP accounts instead of using Pure-FTPd."
echo "Would you like to configure this agent to use the API of EHCP?"
echo -n "(yes|no) [Default no]: "
read ehcp
if [ "${ehcp}" == "yes" -o "${ehcp}" == "no" -o -z "${ehcp}" ]
then
if [ "${ehcp}" == "yes" ]
then
ftpMethod="EHCP"
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [no]."
done
if [ "${ehcp}" == "yes" ]
then
echo "Please enter the MySQL database password for the ehcp user"
echo -n "(created during the install of EHCP): "
read ehcpDB
ehcpConf=${agent_home}/EHCP/config.php
sed -i "s/changeme/${ehcpDB}/" $ehcpConf
else
while [ 1 ]
do
echo;
echo "The agent can use ProFTPd to create FTP accounts."
echo "Would you like to configure this agent to use the ProFTPd?"
echo -n "(yes|no) [Default no]: "
read proftpd
if [ "${proftpd}" == "yes" -o "${proftpd}" == "no" -o -z "${proftpd}" ]
then
if [ "${proftpd}" == "yes" ]
then
ftpMethod="proftpd"
fi
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [no]."
done
if [ "${proftpd}" == "yes" ]
then
echo "Please enter the path for proFTPd configuration file"
echo -n "[Default /etc/proftpd/proftpd.conf]: "
read proFTPdConfFile
if [ -z $proFTPdConfFile ]
then
proFTPdConfFile="/etc/proftpd/proftpd.conf"
if [ ! -e "$proFTPdConfFile" ]; then
proFTPdConfFile="/etc/proftpd.conf"
fi
fi
proFTPdConfPath=$(dirname ${proFTPdConfFile})
while [ 1 ]
do
if [ ! -e $proFTPdConfFile ]
then
echo "The file ${proFTPdConfFile} does not exists,"
echo "what you want to do, reenter it or ignore and continue?"
echo "If your answer is 'ignore' is meant that you will install proFTPd later."
echo -n "(reenter|ignore): "
read answer
if [ "${answer}" == "reenter" -o "${answer}" == "ignore" ]
then
if [ "${answer}" == "reenter" ]
then
echo "Reenter proFTPd's configuration file path:"
read proFTPdConfFile
continue
elif [ "${answer}" == "ignore" ]
then
echo "You will need to append this to ${proFTPdConfFile} once you've installed proftpd:"
bold=`tput bold`
normal=`tput sgr0`
echo -e "\n\n${bold}RequireValidShell off\nAuthUserFile ${proFTPdConfPath}/ftpd.passwd\nAuthGroupFile ${proFTPdConfPath}/ftpd.group${normal}\n\n"
break
fi
fi
echo "You need to type 'reenter' or 'ignore'."
else
if egrep -iq "LoadModule\s*mod_auth_file.c" ${proFTPdConfFile}
then
sed -i "s/\s*#\s*LoadModule\s*mod_auth_file.c/LoadModule mod_auth_file.c/g" ${proFTPdConfFile}
else
echo -e "LoadModule mod_auth_file.c" >> ${proFTPdConfFile}
fi
if egrep -iq "^\s*AuthOrder.*" ${proFTPdConfFile}
then
if egrep -iq "^\s*AuthOrder.*mod_auth_file.c" ${proFTPdConfFile}
then
false
else
sed -ri "s/(^\s*AuthOrder.*)/\1 mod_auth_file.c/g" ${proFTPdConfFile}
fi
else
echo -e "AuthOrder mod_auth_file.c" >> ${proFTPdConfFile}
fi
if egrep -iq "RequireValidShell.*" ${proFTPdConfFile}
then
sed -i "s#RequireValidShell.*#RequireValidShell off#g" ${proFTPdConfFile}
else
echo -e "RequireValidShell off" >> ${proFTPdConfFile}
fi
if egrep -iq "AuthUserFile.*" ${proFTPdConfFile}
then
sed -i "s#AuthUserFile.*#AuthUserFile ${proFTPdConfPath}/ftpd.passwd#g" ${proFTPdConfFile}
else
echo -e "AuthUserFile "${proFTPdConfPath}"/ftpd.passwd" >> ${proFTPdConfFile}
fi
if egrep -iq "AuthGroupFile.*" ${proFTPdConfFile}
then
sed -i "s#AuthGroupFile.*#AuthGroupFile ${proFTPdConfPath}/ftpd.group#g" ${proFTPdConfFile}
else
echo -e "AuthGroupFile "${proFTPdConfPath}"/ftpd.group" >> ${proFTPdConfFile}
fi
# Allow global overwrite (http://opengamepanel.org/forum/viewthread.php?thread_id=5202)
if egrep -iq "AllowOverwrite.*" ${proFTPdConfFile}
then
sed -i "s#AllowOverwrite.*#AllowOverwrite yes#g" ${proFTPdConfFile}
else
echo -e "<Global>\nAllowOverwrite yes\n</Global>" >> ${proFTPdConfFile}
fi
if [ ! -e "${proFTPdConfPath}/ftpd.group" ]
then
touch ${proFTPdConfPath}/ftpd.group
fi
if [ ! -e "${proFTPdConfPath}/ftpd.passwd" ]
then
touch ${proFTPdConfPath}/ftpd.passwd
fi
ftpd_user=$(grep -oP '^User\s+\K.+' ${proFTPdConfFile})
ftpd_group=$(grep -oP '^Group\s+\K.+' ${proFTPdConfFile})
if [ -z "$agent_user" ]; then
agent_user=$(grep -oP 'agent_user=\K.+' /etc/init.d/ogp_agent)
fi
if [ ! -z "$ftpd_user" ] && [ ! -z "$ftpd_group" ] && [ ! -z "$agent_user" ]
then
if [ "$(groups $agent_user|grep $ftpd_group)" == "" ]
then
usermod -aG $ftpd_group $agent_user
fi
if [ -e "${proFTPdConfPath}/ftpd.passwd" -a -e "${proFTPdConfPath}/ftpd.group" ]
then
chmod 640 ${proFTPdConfPath}/ftpd.*
chown -f $ftpd_user:$ftpd_group ${proFTPdConfPath}/ftpd.*
fi
fi
break
fi
done
if [ -e "/etc/init.d/proftpd" ]
then
/etc/init.d/proftpd restart
else
echo "If proftpd is running, to apply the changes, you must restart the service."
fi
else
ftpMethod="PureFTPd"
fi
fi
fi
else
if uname -a|grep -q "x86_64"
then
FZ="yes"
else
while [ 1 ]
do
echo;
echo "If you have installed the FileZilla Server,"
echo "the agent can use it to create FTP accounts instead of using Pure-FTPd."
echo "Would you like to configure this agent to use it?"
echo -n "(yes|no) [Default no]: "
read FZ
if [ "${FZ}" == "yes" -o "${FZ}" == "no" -o -z "${FZ}" ]
then
break;
fi
echo "You need to type 'yes', 'no' or leave empty for default value [no].";
done
fi
if [ "${FZ}" == "yes" ]; then
ftpMethod="FZ"
PF=$(cmd /Q /C echo %PROGRAMFILES\(X86\)% | sed 's/\r$//')
if [ "X${PF}" == "X" ];then PF=$(cmd /Q /C echo %PROGRAMFILES% | sed 's/\r$//'); fi
echo;
echo "Please enter the path for FileZilla server executable file"
echo -n "[Default ${PF}\\FileZilla Server\\FileZilla server.exe]: "
read -r FZ_EXE
if [ -z "${FZ_EXE}" ]
then
FZ_EXE="${PF}\\FileZilla Server\\FileZilla server.exe"
fi
echo;
echo "Please enter the path for FileZilla server xml file"
echo -n "[Default ${PF}\\FileZilla Server\\FileZilla Server.xml]: "
read -r FZ_XML
if [ -z "${FZ_XML}" ]
then
FZ_XML="${PF}\\FileZilla Server\\FileZilla server.xml"
fi
FZ_EXE=$(cygpath -u "$FZ_EXE")
FZ_XML=$(cygpath -u "$FZ_XML")
FZconf=${agent_home}/Cfg/FileZilla.pm
echo -e "%Cfg::FileZilla = (\n\tfz_exe => '${FZ_EXE}',\n\tfz_xml => '${FZ_XML}'\n);" > ${FZconf}
if [ $? != 0 ]
then
failed "Failed to write FileZilla configuration file."
fi
if [ ! -z "$cs_psw" ]; then
UD=$(cmd /Q /C echo %USERDOMAIN% | sed 's/\r$//')
net stop "FileZilla Server"
sc config "FileZilla Server" obj= "${UD}\cyg_server" password= "$cs_psw" type= own
net start "FileZilla Server"
fi
else
if uname -a|grep -qv "x86_64"
then
ftpMethod="PureFTPd"
echo;
echo "Set the listen IP for the PureFTPd."
echo "Default is (${DEFAULT_IP}) to bind on all interfaces."
echo -n "Set listen IP [Default ${DEFAULT_IP}]: "
read ftp_ip
if [ -z "${ftp_ip}" ]
then
ftp_ip=$DEFAULT_IP
fi
echo
echo "Set the listen port for PureFTPd. The default should be fine for everyone."
echo "However, if you want to change it that can be done here, otherwise just press Enter."
echo -n "Set listen port [Default ${DEFAULT_FTP_PORT}]: "
read port
if [ -z "${ftp_port}" ]
then
ftp_port=$DEFAULT_FTP_PORT
fi
echo
echo "Passive-mode downloads."
echo "This is especially useful if the server is behind a firewall."
echo -n "Use only ports in the range?(yes|no)[Default no]: "
read passive_ftp
if [ -z "${passive_ftp}" -o "${passive_ftp}" != "yes" ]
then
ftp_pasv_range=""
else
echo "Enter passive ports range separated by colon (<first port>:<last port>)."
echo -n "[Default ${DEFAULT_FTP_PASV_RANGE}]: "
read ftp_pasv_range
if [ -z "${ftp_pasv_range}" ]
then
ftp_pasv_range=$DEFAULT_FTP_PASV_RANGE
fi
fi
fi
fi
fi
fi
if [ "${ftpMethod}" == "PureFTPd" ]
then
run_pureftpd=1
else
run_pureftpd=0
fi
echo "Writing Preferences file - $prefsfile"
prefs="%Cfg::Preferences = (\n"
prefs="${prefs}\tscreen_log_local => '${logLocalCopy}',\n"
prefs="${prefs}\tdelete_logs_after => '${deleteLogsAfter}',\n"
prefs="${prefs}\togp_manages_ftp => '${ogpManagesFTP}',\n"
prefs="${prefs}\tftp_method => '${ftpMethod}',\n"
prefs="${prefs}\togp_autorestart_server => '${autoRestart}',\n"
prefs="${prefs}\tprotocol_shutdown_waittime => '10',\n"
prefs="${prefs}\tlinux_user_per_game_server => '1',\n"
if [ "X${proftpd}" == "Xyes" ]
then
prefs="${prefs}\tproftpd_conf_path => '${proFTPdConfPath}',\n"
fi
prefs="${prefs});"
echo -e $prefs > $prefsfile
if [ $? != 0 ]
then
failed "Failed to write preferences file."
fi
echo "Writing bash script preferences file - $bashprefsfile"
echo -e "agent_auto_update=${autoUpdate}\nrun_pureftpd=${run_pureftpd}\nftp_port=${ftp_port}\nftp_ip=${ftp_ip}\nftp_pasv_range=${ftp_pasv_range}" > $bashprefsfile
if [ $? != 0 ]
then
failed "Failed to write MISC configuration file used by bash scripts."
fi
# Ensure all config files are owned by the installation owner
if [ -n "$agent_user" ]; then
# Ensure agent_user is valid and not root
if id "$agent_user" >/dev/null 2>&1 && [ "$agent_user" != "root" ]; then
chown "$agent_user" "$cfgfile" "$prefsfile" "$bashprefsfile" 2>/dev/null
fi
fi
fi

View file

@ -0,0 +1,79 @@
-- phpMyAdmin SQL Dump
-- version 4.9.5deb2
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Sep 14, 2025 at 05:31 PM
-- Server version: 5.7.42-log
-- PHP Version: 7.4.3-4ubuntu2.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `panel`
--
-- --------------------------------------------------------
--
-- Table structure for table `gsp_machine_samples`
--
CREATE TABLE `gsp_machine_samples` (
`id` bigint(20) NOT NULL,
`machine_id` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`ts` datetime NOT NULL,
`load1` decimal(6,2) DEFAULT NULL,
`load5` decimal(6,2) DEFAULT NULL,
`load15` decimal(6,2) DEFAULT NULL,
`cpu_pct` decimal(6,2) DEFAULT NULL,
`mem_used_bytes` bigint(20) DEFAULT NULL,
`mem_total_bytes` bigint(20) DEFAULT NULL,
`mem_used_pct` decimal(6,2) DEFAULT NULL,
`swap_used_bytes` bigint(20) DEFAULT NULL,
`swap_total_bytes` bigint(20) DEFAULT NULL,
`disk_path` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`disk_total_bytes` bigint(20) DEFAULT NULL,
`disk_used_bytes` bigint(20) DEFAULT NULL,
`disk_used_pct` decimal(6,2) DEFAULT NULL,
`net_iface` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`rx_bytes` bigint(20) DEFAULT NULL,
`tx_bytes` bigint(20) DEFAULT NULL,
`iface_speed_mbps` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `gsp_machine_samples`
--
ALTER TABLE `gsp_machine_samples`
ADD PRIMARY KEY (`id`),
ADD KEY `idx_machine_ts` (`machine_id`,`ts`),
ADD KEY `idx_ts` (`ts`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `gsp_machine_samples`
--
ALTER TABLE `gsp_machine_samples`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

63
db/gsp_machines.sql Normal file
View file

@ -0,0 +1,63 @@
-- phpMyAdmin SQL Dump
-- version 4.9.5deb2
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Sep 14, 2025 at 05:30 PM
-- Server version: 5.7.42-log
-- PHP Version: 7.4.3-4ubuntu2.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `panel`
--
-- --------------------------------------------------------
--
-- Table structure for table `gsp_machines`
--
CREATE TABLE `gsp_machines` (
`id` int(11) NOT NULL,
`machine_id` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`hostname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`ip` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `gsp_machines`
--
ALTER TABLE `gsp_machines`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `uniq_machine` (`machine_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `gsp_machines`
--
ALTER TABLE `gsp_machines`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View file

@ -0,0 +1,77 @@
-- phpMyAdmin SQL Dump
-- version 4.9.5deb2
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Sep 14, 2025 at 05:31 PM
-- Server version: 5.7.42-log
-- PHP Version: 7.4.3-4ubuntu2.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `panel`
--
-- --------------------------------------------------------
--
-- Table structure for table `gsp_process_samples`
--
CREATE TABLE `gsp_process_samples` (
`id` bigint(20) NOT NULL,
`machine_id` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`ts` datetime NOT NULL,
`server_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`server_path` varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL,
`pid` int(11) NOT NULL,
`proc_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`cmd` text COLLATE utf8mb4_unicode_ci,
`cpu_pct` decimal(7,2) DEFAULT NULL,
`rss_bytes` bigint(20) DEFAULT NULL,
`vms_bytes` bigint(20) DEFAULT NULL,
`mem_pct` decimal(6,2) DEFAULT NULL,
`io_read_bytes` bigint(20) DEFAULT NULL,
`io_write_bytes` bigint(20) DEFAULT NULL,
`open_fds` int(11) DEFAULT NULL,
`listening_ports` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`folder_size_bytes` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `gsp_process_samples`
--
ALTER TABLE `gsp_process_samples`
ADD PRIMARY KEY (`id`),
ADD KEY `idx_proc_server` (`machine_id`,`server_name`,`ts`),
ADD KEY `idx_proc_pid` (`machine_id`,`pid`,`ts`),
ADD KEY `idx_ts` (`ts`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `gsp_process_samples`
--
ALTER TABLE `gsp_process_samples`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

306
db/php_aggregator.php Normal file
View file

@ -0,0 +1,306 @@
<?php
// stats_aggregate.php — call: ?machine=HOSTNAME_OR_ID[&format=html]
/********** CONFIG (panel DB) **********/
$db = [
'host' => 'localhost',
'user' => 'localuser',
'pass' => 'Pkloyn7yvpht!',
'name' => 'panel'
];
$TABLE_PREFIX = 'gsp_';
$AUTO_REFRESH_SECONDS = 30; // set 0 to disable auto-refresh
/***************************************/
$mysqli = @new mysqli($db['host'], $db['user'], $db['pass'], $db['name']);
if ($mysqli->connect_errno) {
http_response_code(500);
echo "<pre>DB connect failed: " . htmlspecialchars($mysqli->connect_error) . "</pre>";
exit;
}
$mysqli->set_charset("utf8mb4");
function q($mysqli, $sql, $params=[]) {
$stmt = $mysqli->prepare($sql);
if(!$stmt){ throw new Exception($mysqli->error); }
if(!empty($params)) {
// infer types (all strings for simplicity)
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
$stmt->close();
return $rows;
}
function fmt_bytes($b) {
if ($b===null) return '—';
$u = ['B','KB','MB','GB','TB','PB']; $i=0;
while ($b>=1024 && $i<count($u)-1) { $b/=1024; $i++; }
return sprintf('%.1f %s', $b, $u[$i]);
}
function pct_class($p) {
if ($p===null) return 'bar';
if ($p>=80) return 'bar danger';
if ($p>=60) return 'bar warn';
return 'bar ok';
}
function pct($v) { return $v===null ? '—' : sprintf('%.1f%%', $v); }
function num0($v) { return $v===null ? '—' : number_format($v,0); }
$machine = isset($_GET['machine']) ? trim($_GET['machine']) : '';
$windows = ['1h'=>1, '24h'=>24, '7d'=>168];
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>GSP Stats Dashboard<?php if ($machine) {
$title_machine_info = q($mysqli, "SELECT hostname FROM {$TABLE_PREFIX}machines WHERE machine_id = ?", [$machine]);
$title_hostname = $title_machine_info ? $title_machine_info[0]['hostname'] : $machine;
echo " ".htmlspecialchars($title_hostname);
} ?></title>
<?php if ($AUTO_REFRESH_SECONDS>0): ?>
<meta http-equiv="refresh" content="<?= (int)$AUTO_REFRESH_SECONDS ?>">
<?php endif; ?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root { --bg:#0b0f14; --panel:#121821; --muted:#9bb0c3; --text:#e6eef6; --ok:#1f9d55; --warn:#d4a017; --danger:#d9534f; --accent:#4ea1ff; }
body{background:var(--bg);color:var(--text);font:14px/1.45 system-ui,Segoe UI,Roboto,Helvetica,Arial,sans-serif;margin:0;padding:24px;}
a{color:var(--accent);text-decoration:none}
h1,h2,h3{margin:0 0 12px 0}
.wrap{max-width:1200px;margin:0 auto}
.topbar{display:flex;align-items:center;gap:12px;margin-bottom:16px}
.card{background:var(--panel);border-radius:14px;padding:16px;box-shadow:0 2px 12px rgba(0,0,0,.25)}
.grid{display:grid;grid-template-columns:repeat(12,1fr);gap:16px}
.col-3{grid-column:span 3} .col-4{grid-column:span 4} .col-6{grid-column:span 6} .col-12{grid-column:span 12}
.muted{color:var(--muted)}
.pill{display:inline-block;padding:2px 8px;border-radius:999px;background:#1a2330;color:#cfe2ff;border:1px solid #2a3a52}
.kpi{font-size:22px;font-weight:700}
.barwrap{background:#0e141d;border-radius:10px;height:12px;overflow:hidden}
.bar{height:100%;display:block;width:0%;transition:width .5s ease;background:var(--ok)}
.bar.warn{background:var(--warn)} .bar.danger{background:var(--danger)}
table{width:100%;border-collapse:separate;border-spacing:0 8px}
thead th{font-weight:600;color:#bcd; text-align:left; padding:8px}
tbody td{padding:8px;background:var(--panel)}
tbody tr{border-radius:10px}
tbody tr td:first-child{border-top-left-radius:10px;border-bottom-left-radius:10px}
tbody tr td:last-child{border-top-right-radius:10px;border-bottom-right-radius:10px}
.right{text-align:right}
.small{font-size:12px}
.row{display:flex;gap:10px;flex-wrap:wrap}
.btn{display:inline-block;padding:8px 10px;border:1px solid #2a3a52;border-radius:10px;background:#0e141d;color:#dfeaff}
.btn.active{background:#1a2330}
.split{display:flex;gap:16px;flex-wrap:wrap}
.split > div{flex:1 1 280px}
.subtle{opacity:.8}
.hdr{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
.sep{height:1px;background:#223143;margin:16px 0}
.mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace}
</style>
</head>
<body>
<div class="wrap">
<div class="topbar">
<h1>GSP Stats Dashboard</h1>
<span class="pill"><?= $AUTO_REFRESH_SECONDS>0 ? "auto-refresh {$AUTO_REFRESH_SECONDS}s" : "manual refresh" ?></span>
<a class="btn" href="?">All machines</a>
<?php if($machine): ?>
<a class="btn" href="?machine=<?= urlencode($machine) ?>">Refresh</a>
<a class="btn" target="_blank" href="stats_aggregate.php?machine=<?= urlencode($machine) ?>">View raw JSON</a>
<?php endif; ?>
</div>
<?php
try {
if (!$machine) {
// list machines with last-ts
$rows = q($mysqli, "SELECT m.machine_id, m.hostname,
(SELECT MAX(ts) FROM {$TABLE_PREFIX}machine_samples s WHERE s.machine_id=m.machine_id) AS last_ts
FROM {$TABLE_PREFIX}machines m ORDER BY m.created_at DESC");
echo '<div class="grid">';
foreach ($rows as $r) {
// Get latest machine sample for this machine to show current status
$latest_sample = q($mysqli, "SELECT cpu_pct, mem_used_pct, disk_used_pct, load1 FROM {$TABLE_PREFIX}machine_samples WHERE machine_id=? ORDER BY ts DESC LIMIT 1", [$r['machine_id']]);
$sample = $latest_sample ? $latest_sample[0] : null;
echo '<div class="col-4 card">';
echo '<div class="hdr"><h3 class="mono">'.htmlspecialchars($r['hostname']).'</h3><span class="muted">'.htmlspecialchars($r['machine_id']).'</span></div>';
echo '<div class="small muted">Last sample: '.htmlspecialchars($r['last_ts'] ?: '—').'</div>';
// Show current resource usage if available
if ($sample) {
echo '<div class="row" style="margin-top:8px;gap:8px;">';
echo '<div style="flex:1"><div class="small muted">CPU</div><div class="small">'.pct($sample['cpu_pct']).'</div></div>';
echo '<div style="flex:1"><div class="small muted">MEM</div><div class="small">'.pct($sample['mem_used_pct']).'</div></div>';
echo '<div style="flex:1"><div class="small muted">DISK</div><div class="small">'.pct($sample['disk_used_pct']).'</div></div>';
if ($sample['load1'] !== null) {
echo '<div style="flex:1"><div class="small muted">LOAD</div><div class="small">'.number_format((float)$sample['load1'], 1).'</div></div>';
}
echo '</div>';
}
echo '<div style="margin-top:10px"><a class="btn" href="?machine='.urlencode($r['machine_id']).'">Open</a></div>';
echo '</div>';
}
echo '</div>';
echo '</div></body></html>'; exit;
}
// LAST sample
$last = q($mysqli, "SELECT * FROM {$TABLE_PREFIX}machine_samples WHERE machine_id=? ORDER BY ts DESC LIMIT 1", [$machine]);
$last = $last ? $last[0] : null;
// Windows
$agg = [];
foreach($windows as $label=>$hours){
$aggM = q($mysqli, "SELECT
COUNT(*) n,
AVG(cpu_pct) cpu_avg,
AVG(mem_used_pct) mem_avg,
AVG(disk_used_pct) disk_avg
FROM {$TABLE_PREFIX}machine_samples
WHERE machine_id=? AND ts >= (NOW() - INTERVAL {$hours} HOUR)", [$machine]);
$netRows = q($mysqli, "SELECT ts, rx_bytes, tx_bytes, iface_speed_mbps
FROM {$TABLE_PREFIX}machine_samples
WHERE machine_id=? AND ts >= (NOW() - INTERVAL {$hours} HOUR)
ORDER BY ts ASC", [$machine]);
$net = ['avg_rx_Bps'=>null,'avg_tx_Bps'=>null,'avg_total_Bps'=>null,'avg_util_pct'=>null];
if (count($netRows)>=2) {
$first = $netRows[0]; $lastn = $netRows[count($netRows)-1];
$secs = max(1, strtotime($lastn['ts']) - strtotime($first['ts']));
$rx_bps = ((int)$lastn['rx_bytes'] - (int)$first['rx_bytes']) / $secs;
$tx_bps = ((int)$lastn['tx_bytes'] - (int)$first['tx_bytes']) / $secs;
$speed_mbps = $lastn['iface_speed_mbps'] ? (int)$lastn['iface_speed_mbps'] : null;
$util_pct = null;
if ($speed_mbps && $speed_mbps>0) {
$capacity_Bps = ($speed_mbps * 1000000) / 8.0;
$util_pct = (($rx_bps + $tx_bps) / $capacity_Bps) * 100.0;
}
$net = ['avg_rx_Bps'=>$rx_bps,'avg_tx_Bps'=>$tx_bps,'avg_total_Bps'=>$rx_bps+$tx_bps,'avg_util_pct'=>$util_pct];
}
$aggS = q($mysqli, "SELECT server_name,
AVG(cpu_pct) cpu_avg,
AVG(mem_pct) mem_avg,
MAX(folder_size_bytes) folder_size_bytes
FROM {$TABLE_PREFIX}process_samples
WHERE machine_id=? AND ts >= (NOW() - INTERVAL {$hours} HOUR)
GROUP BY server_name
ORDER BY server_name ASC", [$machine]);
$agg[$label] = ['machine'=>$aggM[0], 'net'=>$net, 'servers'=>$aggS];
}
} catch (Throwable $e) {
echo '<div class="card">Error: '.htmlspecialchars($e->getMessage()).'</div></div></body></html>'; exit;
}
?>
<div class="grid">
<div class="col-12 card">
<div class="hdr">
<?php
// Get machine info to show hostname prominently
$machine_info = q($mysqli, "SELECT hostname FROM {$TABLE_PREFIX}machines WHERE machine_id = ?", [$machine]);
$hostname = $machine_info ? $machine_info[0]['hostname'] : $machine;
?>
<h2><?= htmlspecialchars($hostname) ?></h2>
<div class="muted small">Machine ID: <?= htmlspecialchars($machine) ?> • Last sample: <?= htmlspecialchars($last['ts'] ?? '—') ?> • IF: <?= htmlspecialchars($last['net_iface'] ?? '—') ?></div>
</div>
<div class="split">
<div>
<div class="muted small">CPU (last)</div>
<div class="kpi"><?= pct($last ? (float)$last['cpu_pct'] : null) ?></div>
<div class="barwrap"><span class="<?= pct_class($last ? (float)$last['cpu_pct'] : null) ?>" style="width:<?= $last? min(100,max(0,(float)$last['cpu_pct'])):0 ?>%"></span></div>
</div>
<div>
<div class="muted small">Memory used (last)</div>
<div class="kpi"><?= pct($last ? (float)$last['mem_used_pct'] : null) ?></div>
<div class="barwrap"><span class="<?= pct_class($last ? (float)$last['mem_used_pct'] : null) ?>" style="width:<?= $last? min(100,max(0,(float)$last['mem_used_pct'])):0 ?>%"></span></div>
</div>
<div>
<div class="muted small">Disk used (last)</div>
<div class="kpi"><?= pct($last ? (float)$last['disk_used_pct'] : null) ?></div>
<div class="barwrap"><span class="<?= pct_class($last ? (float)$last['disk_used_pct'] : null) ?>" style="width:<?= $last? min(100,max(0,(float)$last['disk_used_pct'])):0 ?>%"></span></div>
<div class="small subtle mono"><?= htmlspecialchars($last['disk_path'] ?? '') ?> • used <?= fmt_bytes($last['disk_used_bytes'] ?? null) ?> / <?= fmt_bytes($last['disk_total_bytes'] ?? null) ?></div>
</div>
<div>
<div class="muted small">Load average (last)</div>
<?php $load1 = $last ? (float)$last['load1'] : null; ?>
<div class="kpi"><?= $load1 !== null ? number_format($load1, 1) : '—' ?></div>
<div class="small subtle mono">1min: <?= $load1 !== null ? number_format($load1, 1) : '—' ?> • 5min: <?= $last && $last['load5'] !== null ? number_format((float)$last['load5'], 1) : '—' ?> • 15min: <?= $last && $last['load15'] !== null ? number_format((float)$last['load15'], 1) : '—' ?></div>
</div>
<div>
<div class="muted small">Net avg util (1h)</div>
<?php $nu = $agg['1h']['net']['avg_util_pct']; ?>
<div class="kpi"><?= $nu===null?'—':sprintf('%.1f%%',$nu) ?></div>
<div class="barwrap"><span class="<?= pct_class($nu) ?>" style="width:<?= $nu!==null ? min(100,max(0,$nu)) : 0 ?>%"></span></div>
<div class="small subtle mono">rx <?= fmt_bytes($agg['1h']['net']['avg_rx_Bps']) ?>/s • tx <?= fmt_bytes($agg['1h']['net']['avg_tx_Bps']) ?>/s</div>
</div>
</div>
</div>
<?php foreach ($windows as $label=>$hours): $m=$agg[$label]['machine']; ?>
<div class="col-12 card">
<div class="hdr">
<h3>Window: <?= htmlspecialchars($label) ?></h3>
<div class="row">
<span class="small muted">AVG CPU</span>
<div class="barwrap" style="width:160px;"><span class="<?= pct_class($m['cpu_avg']) ?>" style="width:<?= $m['cpu_avg']!==null?min(100,max(0,$m['cpu_avg'])):0 ?>%"></span></div>
<span class="small"><?= pct($m['cpu_avg']) ?></span>
<span class="small muted" style="margin-left:14px;">AVG MEM</span>
<div class="barwrap" style="width:160px;"><span class="<?= pct_class($m['mem_avg']) ?>" style="width:<?= $m['mem_avg']!==null?min(100,max(0,$m['mem_avg'])):0 ?>%"></span></div>
<span class="small"><?= pct($m['mem_avg']) ?></span>
<span class="small muted" style="margin-left:14px;">AVG DISK</span>
<div class="barwrap" style="width:160px;"><span class="<?= pct_class($m['disk_avg']) ?>" style="width:<?= $m['disk_avg']!==null?min(100,max(0,$m['disk_avg'])):0 ?>%"></span></div>
<span class="small"><?= pct($m['disk_avg']) ?></span>
</div>
</div>
<div class="sep"></div>
<div class="tablewrap">
<table>
<thead>
<tr>
<th>Server</th>
<th class="right">CPU avg</th>
<th style="width:220px"></th>
<th class="right">Mem avg</th>
<th style="width:220px"></th>
<th class="right">Folder size</th>
</tr>
</thead>
<tbody>
<?php
$rows = $agg[$label]['servers'];
if (!$rows) {
echo '<tr><td colspan="6" class="small muted">No server samples in this window.</td></tr>';
} else {
foreach ($rows as $s) {
$cpu = $s['cpu_avg']!==null ? (float)$s['cpu_avg'] : null;
$mem = $s['mem_avg']!==null ? (float)$s['mem_avg'] : null;
echo '<tr>';
echo '<td class="mono">'.htmlspecialchars($s['server_name']).'</td>';
echo '<td class="right">'.pct($cpu).'</td>';
echo '<td><div class="barwrap"><span class="'.pct_class($cpu).'" style="width:'.($cpu!==null?min(100,max(0,$cpu)):0).'%"></span></div></td>';
echo '<td class="right">'.pct($mem).'</td>';
echo '<td><div class="barwrap"><span class="'.pct_class($mem).'" style="width:'.($mem!==null?min(100,max(0,$mem)):0).'%"></span></div></td>';
echo '<td class="right">'.fmt_bytes($s['folder_size_bytes']).'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,72 @@
# Linux Agent Operations Guide
Packaged copy of the instructions we keep in the staff wiki so you can view them offline or import them into any other knowledge base.
## Purpose
The Linux agent (`ogp_agent.pl`) exposes the RPC endpoint that allows the GameServer Panel to install, start, stop, and monitor game servers on Linux hosts. Every host that runs customer games must run this service.
## Supported platforms
- Ubuntu 20.04/22.04/24.04 LTS
- Debian 11/12
- Rocky/AlmaLinux 8+
- Any modern distribution with Perl 5.30+, GNU Screen, and rsync
## Installation (Ubuntu example)
```bash
sudo apt update
sudo apt install -y git curl rsync screen perl libxml-parser-perl libpath-class-perl libarchive-zip-perl libhttp-daemon-perl
sudo git clone https://github.com/GameServerPanel/GSP-Agent-Linux.git /opt/gsp-agent
cd /opt/gsp-agent
sudo bash install.sh
sudo bash agent_conf.sh -s "root-password" -u ogp_agent
```
`agent_conf.sh` writes `/home/ogp_agent/Cfg/Config.pm`. Set:
| Key | Description |
| --- | ----------- |
| `listen_ip` | Interface to bind (use `0.0.0.0` unless you want to restrict access). |
| `listen_port` | TCP port exposed to the panel. Default is `12679`. |
| `key` | Shared secret copied from the panel → Administration → Game Servers. |
| `web_api_url` | HTTPS URL to `ogp_api.php` on the panel. |
| `stats_db_*` | Optional MySQL credentials for the resource stats cron. |
## Service management
```bash
sudo cp systemd/ogp_agent.service /etc/systemd/system/
sudo sed -i "s#{OGP_AGENT_PATH}#/opt/gsp-agent#g" /etc/systemd/system/ogp_agent.service
sudo systemctl daemon-reload
sudo systemctl enable --now ogp_agent
```
Logs live next to the binaries (`/opt/gsp-agent/ogp_agent.log`). Individual game servers stream to their own `console.log` files inside each home folder.
## Firewall checklist
1. Allow inbound TCP on the agent port.
2. Allow inbound/outbound UDP/TCP for the games you host.
3. Allow outbound HTTPS to the panel so the agent can talk to `ogp_api.php`.
## Upgrades
1. `cd /opt/gsp-agent && git pull`
2. Stop the service (`sudo systemctl stop ogp_agent`).
3. Re-run `bash install.sh` if new files were added.
4. Start the service (`sudo systemctl start ogp_agent`).
5. Verify the panel shows the agent as “online”.
## Troubleshooting
- `tail -f ogp_agent.log` handshake failures usually mean the encryption key or port mismatches the panel entry.
- `journalctl -u ogp_agent` capture Perl stack traces and missing dependency errors.
- `screen -ls` confirm customer servers are running in screen sessions.
- `nc -vz panel.example.com 12679` from the panel host ensures the agent port is reachable.
## Related docs
- [`GSP/documentation/admin-guide.md`](https://github.com/GameServerPanel/GSP/tree/main/documentation) Panel-side instructions plus XML authoring notes.
- [`GSP-Agent-Windows/documentation/agent-guide.md`](https://github.com/GameServerPanel/GSP-Agent-Windows/tree/main/documentation/agent-guide.md) Windows counterpart.

6
extPatterns.txt Normal file
View file

@ -0,0 +1,6 @@
cfg
conf
ini
gam
properties
txt

43
includes/ogp_agent.init Normal file
View file

@ -0,0 +1,43 @@
#!/bin/bash
# Generic Init script if we can't find what kind of Linux we're on
agent_dir=OGP_AGENT_DIR
agent_user=OGP_USER
# Start function.
start() {
echo "Starting OGP Agent..."
cd $agent_dir
su -c "screen -d -m -t ogp_agent -c ogp_screenrc -S ogp_agent ./ogp_agent_run -pidfile ogp_agent_run.pid" $agent_user &> $agent_dir/ogp_agent.svc &
echo
}
# Stop function.
stop() {
echo "Stopping OGP Agent..."
kill `cat $agent_dir/ogp_agent_run.pid`
}
restart() {
stop
start
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
*)
echo "Usage: ogp_agent {start|stop|restart}"
exit 1
;;
esac
exit 0;

138
includes/ogp_agent.init.dbn Normal file
View file

@ -0,0 +1,138 @@
#!/bin/bash
#
### BEGIN INIT INFO
# Provides: ogp_agent
# Required-Start: $all
# Required-Stop: $all
# Should-Start: $all
# Should-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop the OGP Agent
# Description: Start and stop the OGP Agent
### END INIT INFO
#
agent_dir=OGP_AGENT_DIR
agent_user=OGP_USER
#
# main()
#
if [ "X`whoami`" != "Xroot" ]
then
exit 1
fi
start() {
if [ -e "$agent_dir/ogp_agent_run.pid" ]
then
pid=$(cat $agent_dir/ogp_agent_run.pid)
out=$(kill -0 $pid > /dev/null 2>&1)
if [ $? == 0 ]
then
return 1
fi
fi
# Lets the agent user to use sudo to enable FTP accounts and use renice and taskset.
if [ "$( groups $agent_user | grep "\bsudo\b" )" == "" ]
then
if [ "$( egrep -i "^sudo" /etc/group )" == "" ]
then
groupadd sudo >/dev/null 2>&1
fi
usermod -aG sudo $agent_user >/dev/null 2>&1
fi
user_id=$(id -u $agent_user)
group_id=$(id -g $agent_user)
out=$(chown -Rf $user_id:$group_id $agent_dir >/dev/null 2>&1)
# Lets the agent user to attach screens.
if [ "$(groups $agent_user|grep -o "\stty\s")" == "" ]
then
usermod -aG tty $agent_user >/dev/null 2>&1
fi
out=$(chmod g+rw /dev/pts/* >/dev/null 2>&1)
out=$(chmod g+rw /dev/tty* >/dev/null 2>&1)
# Check the FTP status
if [ -f "/etc/init.d/pure-ftpd" ] && [ -d "/etc/pure-ftpd/conf" ]
then
echo no > /etc/pure-ftpd/conf/PAMAuthentication
echo no > /etc/pure-ftpd/conf/UnixAuthentication
echo yes > /etc/pure-ftpd/conf/CreateHomeDir
if [ ! -f /etc/pure-ftpd/pureftpd.passwd ]
then
touch /etc/pure-ftpd/pureftpd.passwd
fi
if [ ! -f /etc/pureftpd.passwd ]
then
ln -s /etc/pure-ftpd/pureftpd.passwd /etc/pureftpd.passwd
fi
if [ ! -f /etc/pure-ftpd/auth/50pure ]
then
ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/50pure
fi
if [ ! -f /etc/pureftpd.pdb ]
then
ln -s /etc/pure-ftpd/pureftpd.pdb /etc/pureftpd.pdb
fi
out=$(pure-pw mkdb >/dev/null 2>&1)
out=$(service pure-ftpd force-reload >/dev/null 2>&1)
fi
cd $agent_dir
out=$(su -c "screen -d -m -t ogp_agent -c ogp_screenrc -S ogp_agent ./ogp_agent_run -pidfile ogp_agent_run.pid" $agent_user >/dev/null 2>&1)
return 0
}
stop() {
if [ -e "$agent_dir/ogp_agent_run.pid" ]
then
pid=$(cat $agent_dir/ogp_agent_run.pid)
kill -0 $pid > /dev/null 2>&1
if [ $? == 0 ]
then
kill $pid >/dev/null 2>&1
return $?
fi
else
return 1
fi
return 0
}
case "${1:-''}" in
'start')
start
RETVAL=$?
;;
'stop')
stop
RETVAL=$?
;;
'restart')
stop
sleep 1
start
RETVAL=$?
;;
*)
echo "Usage: service ogp_agent start|stop|restart"
exit 1
;;
esac
if [ ! -z "$RETVAL" ]; then
exit $RETVAL
else
exit 1
fi

View file

@ -0,0 +1,25 @@
#!/sbin/runscript
# Distributed under the terms of the GNU General Public License v2
# GF: Config is in $agent_dir/Cfg/Config.pm
agent_dir=OGP_AGENT_DIR
agent_user=OGP_USER
depend() {
need net
}
start() {
ebegin "Starting OGP Agent"
start-stop-daemon --verbose --chdir $agent_dir --start --background --user $agent_user -e PWD="$agent_dir" --exec screen -d -m -t ogp_agent -c ogp_screenrc -S ogp_agent ./ogp_agent_run -pidfile ogp_agent_run.pid
eend $? "Failed to start OGP Agent"
}
stop() {
ebegin "Stopping OGP Agent"
start-stop-daemon --stop --quiet --pidfile $agent_dir/ogp_agent_run.pid
eend $? "Failed to stop OGP Agent"
}

153
includes/ogp_agent.init.rh Normal file
View file

@ -0,0 +1,153 @@
#!/bin/sh
#
# Startup/shutdown script for the OGP Agent.
#
# Linux chkconfig stuff:
#
# chkconfig: 2345 88 10
# description: Startup/shutdown script for the OGP Agent
agent_dir=OGP_AGENT_DIR
agent_user=OGP_USER
service=ogp_agent
# Source function library.
if [ -f /etc/rc.d/init.d/functions ] ; then
. /etc/rc.d/init.d/functions
elif [ -f /etc/init.d/functions ] ; then
. /etc/init.d/functions
fi
if [ "$( whoami )" != "root" ]
then
if [ -f "/usr/bin/sudo" ] && [ "$( groups $agent_user | grep "\bsudo\b" )" != "" ]
then
sudo /etc/init.d/ogp_agent ${1:-''}
exit
else
echo "Permission denied."
exit
fi
fi
start() {
echo -n "Starting OGP Agent: "
if [ -e "$agent_dir/ogp_agent_run.pid" ]; then
PID=`cat $agent_dir/ogp_agent_run.pid`
RET=$(kill -s 0 $PID &> /dev/null; echo $?)
if [ $RET -eq 0 ]; then
echo -n "already running."
return 1
fi
fi
# Lets the agent user to use sudo to enable FTP accounts and use renice and taskset.
if [ "$( cat /etc/group | grep "^sudo" )" == "" ]
then
groupadd sudo &> /dev/null
fi
if [ "$( cat /etc/sudoers | grep "^%sudo" )" == "" ]
then
echo '%sudo ALL=(ALL) ALL' >> /etc/sudoers
fi
if [ "$( groups $agent_user | grep "\bsudo\b" )" == "" ]
then
usermod -a -G sudo $agent_user &> /dev/null
fi
group=`groups $agent_user | awk '{ print $3 }'`;
# Had to add the "|| true" part to the end of the below command due to chown causing the entire bash script to exit on failure in case of protected files (that have chattr +i applied)
# http://unix.stackexchange.com/questions/118217/chmod-silent-mode-how-force-exit-code-0-in-spite-of-error
chown -Rf $agent_user:$group $agent_dir &> /dev/null || true
# Lets the agent user to attach screens.
if [ "$( groups $agent_user | grep "\btty\b" )" == "" ]
then
usermod -a -G tty $agent_user &> /dev/null
fi
chmod g+rw /dev/pts/* &> /dev/null
chmod g+rw /dev/tty* &> /dev/null
# Give access for ifconfig to the user of the agent
if [ ! -f /usr/bin/ifconfig ]
then
ln -s /sbin/ifconfig /usr/bin/ifconfig
fi
# Check the FTP status
if [ -f "/etc/init.d/pure-ftpd" ]
then
if [ "$( cat /etc/pure-ftpd/pure-ftpd.conf | grep "^PureDB" )" == "" ]
then
sed -i 's|.*PureDB.*|PureDB /etc/pure-ftpd/pureftpd.pdb|' /etc/pure-ftpd/pure-ftpd.conf
sed -i 's|.*BrokenClientsCompatibility.*|BrokenClientsCompatibility yes|' /etc/pure-ftpd/pure-ftpd.conf
sed -i 's|.*NoAnonymous.*|NoAnonymous yes|' /etc/pure-ftpd/pure-ftpd.conf
sed -i 's|.*PAMAuthentication.*|PAMAuthentication no|' /etc/pure-ftpd/pure-ftpd.conf
sed -i 's|.*CreateHomeDir.*|CreateHomeDir yes|' /etc/pure-ftpd/pure-ftpd.conf
pure-pw mkdb &> /dev/null
service pure-ftpd restart &> /dev/null
fi
PURE_STATUS=`service pure-ftpd status`
if test $? -ne 0
then
service pure-ftpd restart &> /dev/null
fi
fi
cd $agent_dir
su -c "screen -d -m -t ogp_agent -c ogp_screenrc -S ogp_agent ./ogp_agent_run -pidfile ogp_agent_run.pid" $agent_user &> $agent_dir/ogp_agent.svc &
echo -n "started successfully."
bold=`tput bold`
normal=`tput sgr0`
echo
echo "Use ${bold}sudo su -c 'screen -S ogp_agent -r' $agent_user${normal} to attach the agent screen,"
echo "and ${bold}ctrl+A+D${normal} to detach it."
return 0
}
stop() {
# Stop daemon
echo -n "Stopping OGP Agent: "
if [ -f $agent_dir/ogp_agent_run.pid ]
then
PID=`cat $agent_dir/ogp_agent_run.pid`
RET=$(kill $PID &> /dev/null; echo $?)
if [ $RET -ne 0 ]; then
echo -n "not running."
else
echo -n "stopped successfully."
fi
else
echo -n "PID file not found ($agent_dir/ogp_agent_run.pid)"
fi
echo
return 0
}
case "$1" in
start)
start
RETVAL=$?
;;
stop)
stop
RETVAL=$?
;;
restart)
stop
${!}
start
RETVAL=$?
;;
*)
echo "Usage: service ogp_agent start|stop|restart"
RETVAL=1
echo
;;
esac
exit $RETVAL

351
install.sh Normal file
View file

@ -0,0 +1,351 @@
#!/bin/bash
#
# OGP - Open Game Panel
# Copyright (C) Copyright (C) 2008 - 2013 The OGP Development Team
#
# http://www.opengamepanel.org/
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Parameters can be passed into the install.sh script to automate OGP updates
# $1 = Operation Type (Used as opType)
# $2 = OGP User (Used as ogpAgentUser)
# $3 = OGP User Sudo Pass (Used as ogpUserPass)
# $4 = Install Path (Used as ogpInsPath)
####################
# FUNCTIONs #
####################
detectSystemD(){
# Ops require sudo
initProcessStr=$(ps -p 1 | awk '{print $4}' | tail -n 1)
if [ "$initProcessStr" == "systemd" ]; then
systemdPresent=1
if [ -e "/lib/systemd/system" ]; then
SystemDDir="/lib/systemd/system"
elif [ -e "/etc/systemd/system" ]; then
SystemDDir="/etc/systemd/system"
else
checkDir=$(ps -eaf|grep '[s]ystemd' | head -n 1 | awk '{print $8}' | grep -o ".*systemd/")
if [ -e "${checkDir}system" ]; then
SystemDDir="$checkDir"
else
# Can't find systemd dir
systemdPresent=
SystemDDir=
fi
fi
fi
}
copySystemDInit(){
AGENTDIR=${agent_home}
sudoPass=${sudo_password}
if [ -e "${AGENTDIR}/systemd/ogp_agent.service" ]; then
if [ ! -z "$systemdPresent" ] && [ ! -z "$SystemDDir" ]; then
echo -e "systemd detected as the init system with a directory of $SystemDDir. Updating OGP agent to use systemd service init script."
if [ -e "/etc/init.d/ogp_agent" ] && [ ! -e "${AGENTDIR}/ogp_agent_init" ]; then
echo -e "Taking care of existing OGP files."
echo "$sudoPass" | sudo -S -p "" service ogp_agent stop
# Kill any remaining ogp agent process
ogpPID=$(ps -ef | grep -v grep | grep ogp_agent.pl | head -n 1 | awk '{print $3}')
if [ ! -z "$ogpPID" ]; then
echo "$sudoPass" | sudo -S -p "" kill -9 "$ogpPID"
fi
echo "$sudoPass" | sudo -S -p "" cp "/etc/init.d/ogp_agent" "${AGENTDIR}/ogp_agent_init"
echo "$sudoPass" | sudo -S -p "" chmod +x "${AGENTDIR}/ogp_agent_init"
echo "$sudoPass" | sudo -S -p "" update-rc.d ogp_agent disable
echo "$sudoPass" | sudo -S -p "" chkconfig ogp_agent off
echo "$sudoPass" | sudo -S -p "" rm -rf "/etc/init.d/ogp_agent"
fi
if [ ! -e "$SystemDDir/ogp_agent.service" ]; then
echo -e "Copying ogp_agent systemd service file to $SystemDDir"
echo "$sudoPass" | sudo -S -p "" cp "${AGENTDIR}/systemd/ogp_agent.service" "$SystemDDir"
echo "$sudoPass" | sudo -S -p "" sed -i "s#{OGP_AGENT_PATH}#$AGENTDIR#g" "${SystemDDir}/ogp_agent.service"
fi
fi
fi
}
#####################
# CODE ##########
#####################
# Parameter notifications
if [ ! -z "$1" ]; then
echo -n "Received operation type of $1 as a parameter."
opType="$1"
fi
if [ ! -z "$2" ]; then
echo -n "Received OGP user of $2 as a parameter."
ogpAgentUser="$2"
fi
if [ ! -z "$3" ]; then
echo -n "Received OGP sudo password of $3 as a parameter."
ogpUserPass="$3"
fi
if [ ! -z "$4" ]; then
echo -n "Received OGP agent path of $4 as a parameter."
ogpInsPath="$4"
fi
failed()
{
echo "ERROR: ${1}"
exit 1
}
if [ "X`which screen &> /dev/null;echo $?`" != "X0" ]; then
failed "You need to install software called 'screen', before you can install OGP agent.";
fi
if [ "X`which sed &> /dev/null;echo $?`" != "X0" ]; then
failed "You need to install software called 'sed', before you can install OGP agent.";
fi
echo
clear
echo "#######################################################################"
echo "# OGP Agent installation and configuration"
echo "# This program will:"
echo "# Create ${DEFAULT_AGENT_HOME} or user defined directory"
echo "# Copy ogp_agent files to ${DEFAULT_AGENT_HOME} or user defined dir"
echo "# Copy the ogp_agent init script to /etc/init.d or user defined dir"
echo "# Create an initial configuration file"
echo "# Thank you for using OGP. http://www.opengamepanel.org/"
echo "#######################################################################"
echo
if [ "X`which rsync &> /dev/null;echo $?`" != "X0" ]; then
echo "*** WARNING **** missing rsync client. It is not required, but needed to use the rsync game installer";
fi
if [ "X`whoami`" != "Xroot" ]
then
echo
echo "Detected non-root install..."
username=`whoami`
echo -n "Enter sudo password: ";
read sudo_password;
else
echo "Next you need to type the username of the user that owns the agent homes.";
echo "This user must own (have access to) all the game home directories that you"
echo "want to run with this agent and must to be in sudoers list so it can perform"
echo "administrative tasks.";echo
while [ 1 ]
do
if [ ! -z "$ogpAgentUser" ] ; then
username="$ogpAgentUser"
else
echo -n "Enter user name: ";
read username;
fi
if [ -z "$ogpUserPass" ] ; then
echo -n "Enter user password: ";
read sudo_password;
else
sudo_password="$ogpUserPass"
fi
if [ -z "${username}" ]
then
echo "Username can not be empty.";echo
continue;
fi
if [ "Xroot" == "X${username}" ]
then
echo "'${username}' can not be used as user for agent.";echo
continue;
fi
ID_OF_USER=`id -u ${username} 2> /dev/null`
if [ $? != 0 ]
then
echo "User with entered username (${username}) does not exist.";echo
continue;
fi
break;
done
fi
detectSystemD
readonly AGENT_USER_HOME="`cat /etc/passwd | grep "^${username}:" | cut -d':' -f6`/OGP/"
echo
echo "Next the directory for the agent needs to be chosen. The default directory";
echo "Should be fine in most of the cases."
echo
if [ -z "$ogpInsPath" ]; then
echo "Where do you want to install the agent?"
echo -n "[Default is ${AGENT_USER_HOME}]: "
read agent_home
else
agent_home="$ogpInsPath"
fi
if [ -z "${agent_home}" ]
then
agent_home=$AGENT_USER_HOME
fi
# Try to prevent users from doing damage to their systems.
case ${agent_home} in
/bin*|/boot*|/dev*|/etc*|/lib*|/proc*|/root*|/sbin*|/sys*|/)
failed "The agent home can not be ${agent_home}";
;;
esac
echo "Agent install dir is ${agent_home}"
echo
agent_home=${agent_home%/}
if [ ! -e ${agent_home} ]
then
mkdir -p ${agent_home} || failed "Failed to create the directory (${agent_home}) for agent."
elif [ ! -w ${agent_home} ]
then
failed "You do not have write permissions to the directory you assigned as agent home (${agent_home})."
fi
if [ "X`whoami`" == "Xroot" ];
then
readonly DEFAULT_INIT_DIR="/etc/init.d/"
else
readonly DEFAULT_INIT_DIR="${agent_home}/"
fi
if [ -z "$systemdPresent" ]; then
if [ "X`uname`" != "XLinux" ]
then
echo
echo "Detected non-Linux platform..."
echo "Where do you want to put the init scripts?"
echo -n "[Default ${DEFAULT_INIT_DIR}]: "
read init_dir
fi
if [ -z "$opType" ]; then
echo "Where do you want to put the init scripts?"
echo -n "[Default ${DEFAULT_INIT_DIR}]:"
read init_dir
fi
else
init_dir=${agent_home}
fi
if [ -z "${init_dir}" ]
then
init_dir=${DEFAULT_INIT_DIR}
fi
init_dir=${init_dir%/}
echo "Copying all files and folders to installation directory..."
# Use rsync if available, otherwise fallback to find/cp
if command -v rsync >/dev/null 2>&1; then
rsync -a --exclude install.sh ./ "${agent_home}/" || failed "Failed to copy files with rsync to ${agent_home}."
else
find . -mindepth 1 -not -name install.sh -exec cp -rf --parents {} "${agent_home}/" \;
fi
# Create the directory for configs.
mkdir -p ${agent_home}/Cfg || failed "Failed to create ${agent_home}/Cfg dir."
echo
if [ -e /etc/gentoo-release ]
then
echo "Copying ogp_agent.init.gentoo to $init_dir - Gentoo Specific Init"
init_file_template='includes/ogp_agent.init.gentoo'
elif [ -e /etc/sysconfig ] && [ ! -e /etc/debian_version ]
then
echo "Copying ogp_agent.init.rh to $init_dir - Redhat Style Init (also SuSE, and Mandrake)"
init_file_template='includes/ogp_agent.init.rh'
elif [ -e /etc/debian_version ]
then
echo "Copying ogp_agent.init.dbn to $init_dir - Debian Style Init"
init_file_template='includes/ogp_agent.init.dbn'
else
echo "Copying the generic init script because I don't know what kind of Linux distro this is"
init_file_template='includes/ogp_agent.init'
fi
init_file=${init_dir}/ogp_agent
cp -f $init_file_template $init_file || failed "Failed to create init file ($init_file)."
# Next we replace the OGP_AGENT_DIR with the actual dir in init file.
sed -i "s|OGP_AGENT_DIR|${agent_home}|" ${init_file} || failed "Failed to modify init file ($init_file)."
sed -i "s|OGP_USER|${username}|" ${init_file} || failed "Failed to modify init file ($init_file)."
chmod a+x $init_file
if [ "$init_dir" == "$agent_home" ] && [ ! -z "$systemdPresent" ]; then
init_file=${init_dir}/ogp_agent_init
mv ${init_dir}/ogp_agent ${init_dir}/ogp_agent_init
copySystemDInit
fi
echo;
echo "Changing files owner to user ${username}...";
# Group of the files in agent_home can differ from the user so
# lets leave them as they are. So no chown user:group here.
chown --preserve-root -R ${username} ${agent_home} || failed "Failed to chmod the agent_home ${agent_home} for user ${username}."
echo "Setting Permissions on files in ${agent_home}..."
if [ -e "${init_dir}/ogp_agent" ]; then
chmod 750 ${init_dir}/ogp_agent || failed "Failed to chmod ${init_dir}/ogp_agent to 750."
fi
if [ -e "${init_dir}/ogp_agent_init" ]; then
chmod 750 ${init_dir}/ogp_agent_init || failed "Failed to chmod ${init_dir}/ogp_agent_init to 750."
fi
chmod 750 ${agent_home}/ogp_agent.pl || failed "Failed to chmod ${agent_home}/ogp_agent.pl to 750."
chmod 750 ${agent_home}/ogp_agent_run || failed "Failed to chmod ${agent_home}/ogp_agent_run to 750."
echo "Install Successful!"
echo "Now configuring..."
echo ""
# Run the configuration script
chmod +x ${agent_home}/agent_conf.sh
if [ -z "$opType" ]; then
bash ${agent_home}/agent_conf.sh -s $sudo_password -u $username
fi
echo "Attempting to start the Open Game Panel (OGP) agent..."
systemctl daemon-reload
chkconfig ogp_agent on
rc-update add ogp_agent default
update-rc.d ogp_agent defaults
systemctl enable ogp_agent.service
service ogp_agent restart
echo;
echo "OGP installation complete!"
echo
exit 0

68
install_agent_prereqs.sh Normal file
View file

@ -0,0 +1,68 @@
#!/bin/bash
# OGP Agent Prerequisites Installer for Ubuntu 22.04+
# This script installs all required packages for running OGP Agent
# Usage: sudo bash install_agent_prereqs.sh
set -e
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root (use sudo)"
exit 1
fi
# Update package lists
apt-get update
# Install core required packages from original prerequisites
apt-get install -y \
libxml-parser-perl \
libpath-class-perl \
perl-modules \
screen \
rsync \
sudo \
e2fsprogs \
unzip \
subversion \
libarchive-extract-perl \
pure-ftpd \
libarchive-zip-perl \
libc6 \
libgcc1 \
git \
curl \
libhttp-daemon-perl
# Install 32-bit compatibility libraries (may fail on some systems, continue anyway)
apt-get install -y libc6-i386 || echo "Warning: Could not install libc6-i386"
apt-get install -y libgcc1:i386 || echo "Warning: Could not install libgcc1:i386"
apt-get install -y lib32gcc1 || echo "Warning: Could not install lib32gcc1"
# Install additional modern packages for current OGP agent
apt-get install -y \
libdbi-perl \
libdbd-mysql-perl \
libfrontier-rpc-perl \
libfile-copy-recursive-perl \
libcrypt-xxtea-perl \
libschedule-cron-perl \
libmime-base64-perl \
libgetopt-long-descriptive-perl \
libio-compress-perl \
libcompress-raw-zlib-perl \
libfile-find-rule-perl \
libfile-basename-perl \
libfcgi-perl \
libwww-perl
# Optional: For FTP management (pure-ftpd already installed above)
# apt-get install -y proftpd-basic
# Optional: For web panel integration
apt-get install -y apache2 php php-mysql || echo "Warning: Optional web packages could not be installed"
# Done
echo "All required packages for OGP Agent have been installed."
echo "Note: Some 32-bit compatibility libraries may not be available on all systems."
echo "This is normal for modern 64-bit only distributions."

5958
ogp_agent.pl Normal file

File diff suppressed because it is too large Load diff

411
ogp_agent_run Normal file
View file

@ -0,0 +1,411 @@
#!/bin/bash
#
#
# A wrapper script for the OGP agent perl script.
# Performs auto-restarting of the agent on crash. You can
# extend this to log crashes and more.
#
# The ogp_agent_run script should be at the top level of the agent tree
# Make sure we are in that directory since the script assumes this is the case
#####################
# Important VARS #
#####################
AGENTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BASH_PREFS_CONF="$AGENTDIR/Cfg/bash_prefs.cfg"
REPONAME=OGP-Agent-Linux
GitHubUsername="OpenGamePanel"
#####################
# FUNCTIONS #
#####################
setupOGPDirPerms(){
chmod -Rf ug+rw $AGENTDIR 2>/dev/null
if [ -d "$AGENTDIR/steamcmd" ]; then
chmod ug+x $AGENTDIR/steamcmd/linux32/* 2>/dev/null
chmod ug+x $AGENTDIR/steamcmd/*.sh 2>/dev/null
fi
if [ -d "$AGENTDIR/screenlogs" ]; then
chmod -Rf ug=rwx $AGENTDIR/screenlogs
fi
chmod ug+x $AGENTDIR/ogp_agent.pl 2>/dev/null
chmod ug+x $AGENTDIR/ogp_agent_run 2>/dev/null
chmod ug+x $AGENTDIR/agent_conf.sh 2>/dev/null
if test `id -u` -eq 0; then
echo
echo
echo "************** WARNING ***************"
echo "Running OGP's agent as root "
echo "is highly discouraged. It is generally"
echo "unnecessary to use root privileges to "
echo "execute the agent. "
echo "**************************************"
echo
echo
timeout=10
while test $timeout -gt 0; do
echo -n "The agent will continue to launch in $timeout seconds\r"
timeout=`expr $timeout - 1`
sleep 1
done
fi
}
ogpGitCleanup(){
echo "Cleaning up..."
rm -Rf ${REPONAME}-* &> /dev/null
if [ -e "ogp_agent_latest.zip" ]; then
rm -f "ogp_agent_latest.zip"
fi
}
getSudoPassword(){
sudoPass=$(cat "$AGENTDIR/Cfg/Config.pm" | grep -o "sudo_password.*" | grep -ow "[^sudo_password( \)*=>( \)*].*" | grep -o "[^'].*[^',]")
}
detectSystemD(){
replaceSystemDService=false
# Ops require sudo
if [ ! -z "$sudoPass" ]; then
initProcessStr=$(ps -p 1 | awk '{print $4}' | tail -n 1)
if [ "$initProcessStr" == "systemd" ]; then
systemdPresent=1
if [ -e "/lib/systemd/system" ]; then
SystemDDir="/lib/systemd/system"
elif [ -e "/etc/systemd/system" ]; then
SystemDDir="/etc/systemd/system"
else
checkDir=$(ps -eaf|grep '[s]ystemd' | head -n 1 | awk '{print $8}' | grep -o ".*systemd/")
if [ -e "${checkDir}system" ]; then
SystemDDir="$checkDir"
else
# Can't find systemd dir
systemdPresent=
SystemDDir=
fi
fi
fi
if [ -e "${AGENTDIR}/systemd/ogp_agent.service" ]; then
if [ ! -z "$systemdPresent" ] && [ ! -z "$SystemDDir" ]; then
echo -e "systemd detected as the init system with a directory of $SystemDDir."
if [ -e "/etc/init.d/ogp_agent" ] && [ ! -e "${AGENTDIR}/ogp_agent_init" ]; then
echo -e "Taking care of existing OGP files."
# Kill any remaining ogp agent process
ogpPID=$(ps -ef | grep -v grep | grep ogp_agent.pl | head -n 1 | awk '{print $3}')
if [ ! -z "$ogpPID" ]; then
echo "$sudoPass" | sudo -S -p "" kill -9 "$ogpPID"
fi
echo "$sudoPass" | sudo -S -p "" cp "/etc/init.d/ogp_agent" "${AGENTDIR}/ogp_agent_init"
echo "$sudoPass" | sudo -S -p "" chmod +x "${AGENTDIR}/ogp_agent_init"
echo "$sudoPass" | sudo -S -p "" update-rc.d ogp_agent disable
echo "$sudoPass" | sudo -S -p "" chkconfig ogp_agent off
echo "$sudoPass" | sudo -S -p "" rm -rf "/etc/init.d/ogp_agent"
replaceSystemDService=true
fi
# Update service to use oneshot and not forking
if [ -e "$SystemDDir/ogp_agent.service" ]; then
# Check to see if it's using oneshot
usingOneShot=$(echo "$sudoPass" | sudo -S -p "" cat "$SystemDDir/ogp_agent.service" | grep -o "oneshot")
if [ -z "$usingOneShot" ]; then
replaceSystemDService=true
fi
fi
if [ ! -e "$SystemDDir/ogp_agent.service" ] || [ "$replaceSystemDService" = true ]; then
echo -e "Updating OGP agent systemd service init script."
echo -e "Copying ogp_agent systemd service file to $SystemDDir"
echo "$sudoPass" | sudo -S -p "" cp "${AGENTDIR}/systemd/ogp_agent.service" "$SystemDDir"
echo "$sudoPass" | sudo -S -p "" sed -i "s#{OGP_AGENT_PATH}#$AGENTDIR#g" "${SystemDDir}/ogp_agent.service"
echo "$sudoPass" | sudo -S -p "" systemctl daemon-reload
echo "$sudoPass" | sudo -S -p "" systemctl enable ogp_agent.service
echo "$sudoPass" | sudo -S -p "" service ogp_agent restart
exit 0
fi
fi
fi
fi
}
init() {
RESTART="yes"
AGENT="$AGENTDIR/ogp_agent.pl"
TIMEOUT=10 # time to wait after a crash (in seconds)
PID_FILE=""
# Should we perform an automatic update?
if [ -e $BASH_PREFS_CONF ]
then
source "$BASH_PREFS_CONF"
if [ "$agent_auto_update" -eq "1" ]
then
AUTO_UPDATE="yes"
fi
# Use custom github update address
if [ ! -z "$github_update_username" ]; then
REVISIONTest=`curl -s https://github.com/${github_update_username}/${REPONAME}/commits/master.atom | egrep -o "([a-f0-9]{40})" | awk 'NR==1{print $1}'`
if [ ! -z "$REVISIONTest" ]; then
GitHubUsername=${github_update_username}
fi
fi
else
AUTO_UPDATE="yes"
fi
while test $# -gt 0; do
case "$1" in
"-pidfile")
PID_FILE="$2"
PID_FILE_SET=1
echo $$ > $PID_FILE
shift ;;
esac
shift
done
if test ! -f "$AGENT"; then
echo "ERROR: '$AGENT' not found, exiting"
quit 1
elif test ! -x "$AGENT"; then
# Could try chmod but dont know what we will be
# chmoding so just fail.
echo "ERROR: '$AGENT' not executable, exiting"
quit 1
fi
CMD="perl $AGENT"
}
syntax () {
# Prints script syntax
echo "Syntax:"
echo "$0"
}
checkDepends() {
CURL=`which curl 2>/dev/null`
if test "$?" -gt 0; then
echo "WARNING: Failed to locate curl binary."
else
echo "INFO: Located curl: $CURL"
fi
UNZIP=`which unzip 2>/dev/null`
if test "$?" -gt 0; then
echo "WARNING: Failed to locate unzip binary."
else
echo "INFO: Located unzip: $UNZIP"
fi
}
update() {
# Check to see if limited ogpuser exists
generateOGPLimitedUser
# Run the update
if test -n "$AUTO_UPDATE"; then
if [ -z "$CURL" -o -z "$UNZIP" ]; then
checkDepends
fi
if [ -f "$CURL" -a -x "$CURL" ] && [ -f "$UNZIP" -a -x "$UNZIP" ]; then
cd $AGENTDIR
if [ ! -d tmp ]; then
mkdir tmp
fi
cd tmp
REVISION=`curl -s https://github.com/${GitHubUsername}/${REPONAME}/commits/master.atom | egrep -o "([a-f0-9]{40})" | awk 'NR==1{print $1}'`
curl -Os https://raw.githubusercontent.com/${GitHubUsername}/${REPONAME}/${REVISION}/ogp_agent_run
currentOGPAgentRunContent=$(cat "./ogp_agent_run")
# Check to make sure ogp_agent_run downloaded successfully from GitHub before we attempt to replace it.
# This should fix random 404 people have been experiencing
if [ -s "./ogp_agent_run" ] && [ "$(echo "$currentOGPAgentRunContent" | head -n 1)" != "404: Not Found" ] && [ ! -z "$(echo "$currentOGPAgentRunContent" | grep "ogp_agent.pl")" ]; then
diff ./ogp_agent_run $AGENTDIR/ogp_agent_run &>/dev/null
if test $? -ne 0; then
cp -f ./ogp_agent_run $AGENTDIR/ogp_agent_run &> /dev/null
if test $? -eq 0; then
cd $AGENTDIR
chmod ug+x ogp_agent_run 2>/dev/null
echo "`date`: The agent updater has been changed, relaunching..."
rm -Rf tmp
./ogp_agent_run
exit 0
fi
fi
fi
cd $AGENTDIR
CURRENT=$(cat $AGENTDIR/Cfg/Config.pm | grep version | grep -Eo '[0-9a-f]{40}')
if [ "$CURRENT" == "$REVISION" ]; then
echo "The agent is up to date."
else
URL=https://github.com/${GitHubUsername}/${REPONAME}/archive/${REVISION}.zip
HEAD=$(curl -L -s --head -w "%{http_code}" "$URL" -o "ogp_agent_latest.zip")
if [ "$HEAD" == "200" ]; then
echo "Updating agent using curl."
curl -L -s "$URL" -o "ogp_agent_latest.zip"
if test $? -ne 0; then
echo "`date`: curl failed to download the update package."
else
unzip -oq "ogp_agent_latest.zip"
if test $? -ne 0; then
echo "`date`: Unable to unzip the update package."
ogpGitCleanup
else
cd ${REPONAME}-${REVISION}
cp -avf systemd Frontier ArmaBE Minecraft Schedule Time FastDownload php-query ogp_agent.pl ogp_screenrc ogp_screenrc_bk ogp_agent_run agent_conf.sh $AGENTDIR &> /dev/null
if test $? -ne 0; then
echo "`date`: The agent files cannot be overwritten."
cd ..
ogpGitCleanup
echo "Agent update failed."
else
if test ! -d "$AGENTDIR/IspConfig"; then
cp -Rf IspConfig $AGENTDIR/IspConfig &> /dev/null
fi
if test ! -d "$AGENTDIR/EHCP"; then
cp -Rf EHCP $AGENTDIR/EHCP &> /dev/null
fi
if test ! -f "$AGENTDIR/Cfg/Preferences.pm"; then
cp -f Cfg/Preferences.pm $AGENTDIR/Cfg/Preferences.pm &> /dev/null
fi
echo "Fixing permissions..."
chmod ug+x $AGENTDIR/ogp_agent.pl &> /dev/null
chmod ug+x $AGENTDIR/ogp_agent_run &> /dev/null
chmod ug+x $AGENTDIR/agent_conf.sh &> /dev/null
cd ..
ogpGitCleanup
sed -i "s/version.*/version => '${REVISION}',/" $AGENTDIR/Cfg/Config.pm
echo "Agent updated successfully."
fi
fi
fi
else
echo "There is a update available (${REVISION}) but the download source is not ready.";
echo "Try again later."
fi
fi
else
echo "Update failed."
fi
fi
return 0
}
run() {
getSudoPassword
restrictAccess
update
detectSystemD
if test -n "$RESTART" ; then
echo "Agent will auto-restart if there is a crash."
#loop forever
while true
do
# Run
$CMD
echo "`date`: Agent restart in $TIMEOUT seconds"
# don't thrash the hard disk if the agent dies, wait a little
sleep $TIMEOUT
done # while true
else
$CMD
fi
}
quit() {
# Exits with the give error code, 1
# if none specified.
# exit code 2 also prints syntax
exitcode="$1"
# default to failure
if test -z "$exitcode"; then
exitcode=1
fi
case "$exitcode" in
0)
echo "`date`: OGP Agent Quit" ;;
2)
syntax ;;
*)
echo "`date`: OGP Agent Failed" ;;
esac
# Remove pid file
if test -n "$PID_FILE" && test -f "$PID_FILE" ; then
# The specified pid file
rm -f $PID_FILE
fi
# reset SIGINT and then kill ourselves properly
trap - 2
kill -2 $$
}
function generatePassword(){
if [ ! -z "$1" ]; then
PLENGTH="$1"
else
PLENGTH="10"
fi
#rPass=$(date +%s | sha256sum | base64 | head -c "$PLENGTH")
rPass=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1 | head -c "$PLENGTH")
}
function generateOGPLimitedUser(){
ogpUSER="ogp_server_runner"
echo "$sudoPass" | sudo -S -p "<prompt>" id -u "$ogpUSER"
if [ $? -eq 1 ]; then
echo "Creating ogp limited user for running servers and additional security..."
echo "$sudoPass" | sudo -S -p "<prompt>" groupdel ${ogpUSER}
echo "$sudoPass" | sudo -S -p "<prompt>" groupadd ${ogpUSER}
generatePassword "15"
ogpPass="$rPass"
echo "$sudoPass" | sudo -S -p "<prompt>" useradd --home "/home/$ogpUSER" -g ${ogpUSER} -m "$ogpUSER"
echo "$sudoPass" | sudo -S -p "<prompt>" sh -c "echo '${ogpUSER}:${ogpPass}' | chpasswd"
# Use /bin/bash shell by default per request from Omano
echo "$sudoPass" | sudo -S -p "<prompt>" usermod -s /bin/bash ${ogpUSER}
echo "$sudoPass" | sudo -S -p "<prompt>" sh -c "echo 'limited_ogp_user=${ogpUSER}
password=${ogpPass}' > /root/ogp_server_runner_info"
agentUser="$(whoami)"
echo "$sudoPass" | sudo -S -p "<prompt>" usermod -a -G "$ogpUSER" "$agentUser"
# Reload perms so we don't have to reboot system for new group to apply right now...
echo "$sudoPass" | sudo -S -p "<prompt>" exec su -l "$agentUser"
fi
# Set servers to run under their own user by default:
hasLinuxUser=$(cat "$AGENTDIR/Cfg/Preferences.pm" | grep -o "linux_user_per_game_server")
if [ -z "$hasLinuxUser" ]; then
sed -i "\$i \\\\tlinux_user_per_game_server => '1'," "$AGENTDIR/Cfg/Preferences.pm"
fi
}
function restrictAccess(){
echo "$sudoPass" | sudo -S -p "<prompt>" chmod 750 "$AGENTDIR/Cfg/Config.pm"
echo "$sudoPass" | sudo -S -p "<prompt>" chmod 750 "$AGENTDIR/Cfg/Preferences.pm"
echo "$sudoPass" | sudo -S -p "<prompt>" chmod 750 "$AGENTDIR/Cfg/bash_prefs.cfg"
}
#####################
# MAIN APP CODE #
#####################
# Setup OGP and Read Preferences
setupOGPDirPerms
# Initialise
init $*
# Run
run
# Quit normally
quit 0

8
ogp_screenrc Normal file
View file

@ -0,0 +1,8 @@
startup_message off
hardstatus on
hardstatus alwayslastline '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}[%{W}%n%f %t%?(%u)%?%{=b kR}]%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{=b C}[ %D %m/%d %C%a ]%{W}'
# Default scroll back 100
defscrollback 100
deflog on
logfile /home/gameserver/OGP/screenlogs/screenlog.%t

7
ogp_screenrc_bk Normal file
View file

@ -0,0 +1,7 @@
startup_message off
hardstatus on
hardstatus alwayslastline '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}[%{W}%n%f %t%?(%u)%?%{=b kR}]%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{=b C}[ %D %m/%d %C%a ]%{W}'
# Default scroll back 100
defscrollback 100
deflog on
logfile $PWD/screenlogs/screenlog.%t

View file

@ -0,0 +1,60 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
/**
* A simple PSR-4 spec auto loader to allow GameQ to function the same as if it were loaded via Composer
*
* To use this just include this file in your script and the GameQ namespace will be made available
*
* i.e. require_once('/path/to/src/GameQ/Autoloader.php');
*
* See: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
*
* @codeCoverageIgnore
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'GameQ\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . DIRECTORY_SEPARATOR;
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});

526
php-query/gameq/Buffer.php Normal file
View file

@ -0,0 +1,526 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
namespace GameQ;
use GameQ\Exception\Protocol as Exception;
/**
* Class Buffer
*
* Read specific byte sequences from a provided string or Buffer
*
* @package GameQ
*
* @author Austin Bischoff <austin@codebeard.com>
* @author Aidan Lister <aidan@php.net>
* @author Tom Buskens <t.buskens@deviation.nl>
*/
class Buffer
{
/**
* Constants for the byte code types we need to read as
*/
const NUMBER_TYPE_BIGENDIAN = 'be',
NUMBER_TYPE_LITTLEENDIAN = 'le',
NUMBER_TYPE_MACHINE = 'm';
/**
* The number type we use for reading integers. Defaults to little endian
*
* @type string
*/
private $number_type = self::NUMBER_TYPE_LITTLEENDIAN;
/**
* The original data
*
* @type string
*/
private $data;
/**
* The original data
*
* @type int
*/
private $length;
/**
* Position of pointer
*
* @type int
*/
private $index = 0;
/**
* Constructor
*
* @param string $data
* @param string $number_type
*/
public function __construct($data, $number_type = self::NUMBER_TYPE_LITTLEENDIAN)
{
$this->number_type = $number_type;
$this->data = $data;
$this->length = strlen($data);
}
/**
* Return all the data
*
* @return string The data
*/
public function getData()
{
return $this->data;
}
/**
* Return data currently in the buffer
*
* @return string The data currently in the buffer
*/
public function getBuffer()
{
return substr($this->data, $this->index);
}
/**
* Returns the number of bytes in the buffer
*
* @return int Length of the buffer
*/
public function getLength()
{
return max($this->length - $this->index, 0);
}
/**
* Read from the buffer
*
* @param int $length
*
* @return string
* @throws \GameQ\Exception\Protocol
*/
public function read($length = 1)
{
if (($length + $this->index) > $this->length) {
throw new Exception("Unable to read length={$length} from buffer. Bad protocol format or return?");
}
$string = substr($this->data, $this->index, $length);
$this->index += $length;
return $string;
}
/**
* Read the last character from the buffer
*
* Unlike the other read functions, this function actually removes
* the character from the buffer.
*
* @return string
*/
public function readLast()
{
$len = strlen($this->data);
$string = $this->data[strlen($this->data) - 1];
$this->data = substr($this->data, 0, $len - 1);
$this->length -= 1;
return $string;
}
/**
* Look at the buffer, but don't remove
*
* @param int $length
*
* @return string
*/
public function lookAhead($length = 1)
{
return substr($this->data, $this->index, $length);
}
/**
* Skip forward in the buffer
*
* @param int $length
*/
public function skip($length = 1)
{
$this->index += $length;
}
/**
* Jump to a specific position in the buffer,
* will not jump past end of buffer
*
* @param $index
*/
public function jumpto($index)
{
$this->index = min($index, $this->length - 1);
}
/**
* Get the current pointer position
*
* @return int
*/
public function getPosition()
{
return $this->index;
}
/**
* Read from buffer until delimiter is reached
*
* If not found, return everything
*
* @param string $delim
*
* @return string
* @throws \GameQ\Exception\Protocol
*/
public function readString($delim = "\x00")
{
// Get position of delimiter
$len = strpos($this->data, $delim, min($this->index, $this->length));
// If it is not found then return whole buffer
if ($len === false) {
return $this->read(strlen($this->data) - $this->index);
}
// Read the string and remove the delimiter
$string = $this->read($len - $this->index);
++$this->index;
return $string;
}
/**
* Reads a pascal string from the buffer
*
* @param int $offset Number of bits to cut off the end
* @param bool $read_offset True if the data after the offset is to be read
*
* @return string
* @throws \GameQ\Exception\Protocol
*/
public function readPascalString($offset = 0, $read_offset = false)
{
// Get the proper offset
$len = $this->readInt8();
$offset = max($len - $offset, 0);
// Read the data
if ($read_offset) {
return $this->read($offset);
} else {
return substr($this->read($len), 0, $offset);
}
}
/**
* Read from buffer until any of the delimiters is reached
*
* If not found, return everything
*
* @param $delims
* @param null|string &$delimfound
*
* @return string
* @throws \GameQ\Exception\Protocol
*
* @todo: Check to see if this is even used anymore
*/
public function readStringMulti($delims, &$delimfound = null)
{
// Get position of delimiters
$pos = [];
foreach ($delims as $delim) {
if ($index = strpos($this->data, $delim, min($this->index, $this->length))) {
$pos[] = $index;
}
}
// If none are found then return whole buffer
if (empty($pos)) {
return $this->read(strlen($this->data) - $this->index);
}
// Read the string and remove the delimiter
sort($pos);
$string = $this->read($pos[0] - $this->index);
$delimfound = $this->read();
return $string;
}
/**
* Read an 8-bit unsigned integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt8()
{
$int = unpack('Cint', $this->read(1));
return $int['int'];
}
/**
* Read and 8-bit signed integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt8Signed()
{
$int = unpack('cint', $this->read(1));
return $int['int'];
}
/**
* Read a 16-bit unsigned integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt16()
{
// Change the integer type we are looking up
switch ($this->number_type) {
case self::NUMBER_TYPE_BIGENDIAN:
$type = 'nint';
break;
case self::NUMBER_TYPE_LITTLEENDIAN:
$type = 'vint';
break;
default:
$type = 'Sint';
}
$int = unpack($type, $this->read(2));
return $int['int'];
}
/**
* Read a 16-bit signed integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt16Signed()
{
// Read the data into a string
$string = $this->read(2);
// For big endian we need to reverse the bytes
if ($this->number_type == self::NUMBER_TYPE_BIGENDIAN) {
$string = strrev($string);
}
$int = unpack('sint', $string);
unset($string);
return $int['int'];
}
/**
* Read a 32-bit unsigned integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt32($length = 4)
{
// Change the integer type we are looking up
$littleEndian = null;
switch ($this->number_type) {
case self::NUMBER_TYPE_BIGENDIAN:
$type = 'N';
$littleEndian = false;
break;
case self::NUMBER_TYPE_LITTLEENDIAN:
$type = 'V';
$littleEndian = true;
break;
default:
$type = 'L';
}
// read from the buffer and append/prepend empty bytes for shortened int32
$corrected = $this->read($length);
// Unpack the number
$int = unpack($type . 'int', self::extendBinaryString($corrected, 4, $littleEndian));
return $int['int'];
}
/**
* Read a 32-bit signed integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt32Signed()
{
// Read the data into a string
$string = $this->read(4);
// For big endian we need to reverse the bytes
if ($this->number_type == self::NUMBER_TYPE_BIGENDIAN) {
$string = strrev($string);
}
$int = unpack('lint', $string);
unset($string);
return $int['int'];
}
/**
* Read a 64-bit unsigned integer
*
* @return int
* @throws \GameQ\Exception\Protocol
*/
public function readInt64()
{
// We have the pack 64-bit codes available. See: http://php.net/manual/en/function.pack.php
if (version_compare(PHP_VERSION, '5.6.3') >= 0 && PHP_INT_SIZE == 8) {
// Change the integer type we are looking up
switch ($this->number_type) {
case self::NUMBER_TYPE_BIGENDIAN:
$type = 'Jint';
break;
case self::NUMBER_TYPE_LITTLEENDIAN:
$type = 'Pint';
break;
default:
$type = 'Qint';
}
$int64 = unpack($type, $this->read(8));
$int = $int64['int'];
unset($int64);
} else {
if ($this->number_type == self::NUMBER_TYPE_BIGENDIAN) {
$high = $this->readInt32();
$low = $this->readInt32();
} else {
$low = $this->readInt32();
$high = $this->readInt32();
}
// We have to determine the number via bitwise
$int = ($high << 32) | $low;
unset($low, $high);
}
return $int;
}
/**
* Read a 32-bit float
*
* @return float
* @throws \GameQ\Exception\Protocol
*/
public function readFloat32()
{
// Read the data into a string
$string = $this->read(4);
// For big endian we need to reverse the bytes
if ($this->number_type == self::NUMBER_TYPE_BIGENDIAN) {
$string = strrev($string);
}
$float = unpack('ffloat', $string);
unset($string);
return $float['float'];
}
private static function extendBinaryString($input, $length = 4, $littleEndian = null)
{
if (is_null($littleEndian)) {
$littleEndian = self::isLittleEndian();
}
$extension = str_repeat(pack($littleEndian ? 'V' : 'N', 0b0000), $length - strlen($input));
if ($littleEndian) {
return $input . $extension;
} else {
return $extension . $input;
}
}
private static function isLittleEndian()
{
return 0x00FF === current(unpack('v', pack('S', 0x00FF)));
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
namespace GameQ\Exception;
/**
* Exception
*
* @author Austin Bischoff <austin@codebeard.com>
*/
class Protocol extends \Exception
{
}

View file

@ -0,0 +1,30 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
namespace GameQ\Exception;
/**
* Exception
*
* @author Austin Bischoff <austin@codebeard.com>
*/
class Query extends \Exception
{
}

View file

@ -0,0 +1,30 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
namespace GameQ\Exception;
/**
* Exception
*
* @author Austin Bischoff <austin@codebeard.com>
*/
class Server extends \Exception
{
}

View file

@ -0,0 +1,63 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Filters;
use GameQ\Server;
/**
* Abstract base class which all filters must inherit
*
* @author Austin Bischoff <austin@codebeard.com>
*/
abstract class Base
{
/**
* Holds the options for this instance of the filter
*
* @type array
*/
protected $options = [];
/**
* Construct
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->options = $options;
}
public function getOptions()
{
return $this->options;
}
/**
* Apply the filter to the data
*
* @param array $result
* @param \GameQ\Server $server
*
* @return mixed
*/
abstract public function apply(array $result, Server $server);
}

View file

@ -0,0 +1,133 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Filters;
use GameQ\Server;
/**
* Class Normalize
*
* @package GameQ\Filters
*/
class Normalize extends Base
{
/**
* Holds the protocol specific normalize information
*
* @type array
*/
protected $normalize = [];
/**
* Apply this filter
*
* @param array $result
* @param \GameQ\Server $server
*
* @return array
*/
public function apply(array $result, Server $server)
{
// No result passed so just return
if (empty($result)) {
return $result;
}
//$data = [ ];
//$data['raw'][$server->id()] = $result;
// Grab the normalize for this protocol for the specific server
$this->normalize = $server->protocol()->getNormalize();
// Do general information
$result = array_merge($result, $this->check('general', $result));
// Do player information
if (isset($result['players']) && count($result['players']) > 0) {
// Iterate
foreach ($result['players'] as $key => $player) {
$result['players'][$key] = array_merge($player, $this->check('player', $player));
}
} else {
$result['players'] = [];
}
// Do team information
if (isset($result['teams']) && count($result['teams']) > 0) {
// Iterate
foreach ($result['teams'] as $key => $team) {
$result['teams'][$key] = array_merge($team, $this->check('team', $team));
}
} else {
$result['teams'] = [];
}
//$data['filtered'][$server->id()] = $result;
/*file_put_contents(
sprintf('%s/../../../tests/Filters/Providers/Normalize/%s_1.json', __DIR__, $server->protocol()->getProtocol()),
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR)
);*/
// Return the normalized result
return $result;
}
/**
* Check a section for normalization
*
* @param $section
* @param $data
*
* @return array
*/
protected function check($section, $data)
{
// Normalized return array
$normalized = [];
if (isset($this->normalize[$section]) && !empty($this->normalize[$section])) {
foreach ($this->normalize[$section] as $property => $raw) {
// Default the value for the new key as null
$value = null;
if (is_array($raw)) {
// Iterate over the raw property we want to use
foreach ($raw as $check) {
if (array_key_exists($check, $data)) {
$value = $data[$check];
break;
}
}
} else {
// String
if (array_key_exists($raw, $data)) {
$value = $data[$raw];
}
}
$normalized['gq_' . $property] = $value;
}
}
return $normalized;
}
}

View file

@ -0,0 +1,121 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Filters;
use GameQ\Server;
/**
* Class Secondstohuman
*
* This class converts seconds into a human readable time string 'hh:mm:ss'. This is mainly for converting
* a player's connected time into a readable string. Note that most game servers DO NOT return a player's connected
* time. Source (A2S) based games generally do but not always. This class can also be used to convert other time
* responses into readable time
*
* @package GameQ\Filters
* @author Austin Bischoff <austin@codebeard.com>
*/
class Secondstohuman extends Base
{
/**
* The options key for setting the data key(s) to look for to convert
*/
const OPTION_TIMEKEYS = 'timekeys';
/**
* The result key added when applying this filter to a result
*/
const RESULT_KEY = 'gq_%s_human';
/**
* Holds the default 'time' keys from the response array. This is key is usually 'time' from A2S responses
*
* @var array
*/
protected $timeKeysDefault = ['time'];
/**
* Secondstohuman constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
// Check for passed keys
if (!array_key_exists(self::OPTION_TIMEKEYS, $options)) {
// Use default
$options[self::OPTION_TIMEKEYS] = $this->timeKeysDefault;
} else {
// Used passed key(s) and make sure it is an array
$options[self::OPTION_TIMEKEYS] = (!is_array($options[self::OPTION_TIMEKEYS])) ?
[$options[self::OPTION_TIMEKEYS]] : $options[self::OPTION_TIMEKEYS];
}
parent::__construct($options);
}
/**
* Apply this filter to the result data
*
* @param array $result
* @param Server $server
*
* @return array
*/
public function apply(array $result, Server $server)
{
// Send the results off to be iterated and return the updated result
return $this->iterate($result);
}
/**
* Home grown iterate function. Would like to replace this with an internal PHP method(s) but could not find a way
* to make the iterate classes add new keys to the response. They all seemed to be read-only.
*
* @todo: See if there is a more internal way of handling this instead of foreach looping and recursive calling
*
* @param array $result
*
* @return array
*/
protected function iterate(array &$result)
{
// Iterate over the results
foreach ($result as $key => $value) {
// Offload to itself if we have another array
if (is_array($value)) {
// Iterate and update the result
$result[$key] = $this->iterate($value);
} elseif (in_array($key, $this->options[self::OPTION_TIMEKEYS])) {
// Make sure the value is a float (throws E_WARNING in PHP 7.1+)
$value = floatval($value);
// We match one of the keys we are wanting to convert so add it and move on
$result[sprintf(self::RESULT_KEY, $key)] = sprintf(
"%02d:%02d:%02d",
floor($value / 3600),
($value / 60) % 60,
$value % 60
);
}
}
return $result;
}
}

View file

@ -0,0 +1,118 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Filters;
use GameQ\Server;
/**
* Class Strip Colors
*
* Strip color codes from UT and Quake based games
*
* @package GameQ\Filters
*/
class Stripcolors extends Base
{
/**
* Apply this filter
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @param array $result
* @param \GameQ\Server $server
*
* @return array
*/
public function apply(array $result, Server $server)
{
// No result passed so just return
if (empty($result)) {
return $result;
}
//$data = [];
//$data['raw'][ $server->id() ] = $result;
// Switch based on the base (not game) protocol
switch ($server->protocol()->getProtocol()) {
case 'quake2':
case 'quake3':
case 'doom3':
array_walk_recursive($result, [$this, 'stripQuake']);
break;
case 'unreal2':
case 'ut3':
case 'gamespy3': //not sure if gamespy3 supports ut colors but won't hurt
case 'gamespy2':
array_walk_recursive($result, [$this, 'stripUnreal']);
break;
case 'source':
array_walk_recursive($result, [$this, 'stripSource']);
break;
case 'gta5m':
array_walk_recursive($result, [$this, 'stripQuake']);
break;
}
/*$data['filtered'][ $server->id() ] = $result;
file_put_contents(
sprintf(
'%s/../../../tests/Filters/Providers/Stripcolors\%s_1.json',
__DIR__,
$server->protocol()->getProtocol()
),
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR)
);*/
// Return the stripped result
return $result;
}
/**
* Strip color codes from quake based games
*
* @param string $string
*/
protected function stripQuake(&$string)
{
$string = preg_replace('#(\^.)#', '', $string);
}
/**
* Strip color codes from Source based games
*
* @param string $string
*/
protected function stripSource(&$string)
{
$string = strip_tags($string);
}
/**
* Strip color codes from Unreal based games
*
* @param string $string
*/
protected function stripUnreal(&$string)
{
$string = preg_replace('/\x1b.../', '', $string);
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Filters;
use GameQ\Server;
/**
* Class Test
*
* This is a test filter to be used for testing purposes only.
*
* @package GameQ\Filters
*/
class Test extends Base
{
/**
* Apply the filter. For this we just return whatever is sent
*
* @SuppressWarnings(PHPMD)
*
* @param array $result
* @param \GameQ\Server $server
*
* @return array
*/
public function apply(array $result, Server $server)
{
return $result;
}
}

659
php-query/gameq/GameQ.php Normal file
View file

@ -0,0 +1,659 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ;
use GameQ\Exception\Protocol as ProtocolException;
use GameQ\Exception\Query as QueryException;
/**
* Base GameQ Class
*
* This class should be the only one that is included when you use GameQ to query
* any games servers.
*
* Requirements: See wiki or README for more information on the requirements
* - PHP 5.4.14+
* * Bzip2 - http://www.php.net/manual/en/book.bzip2.php
*
* @author Austin Bischoff <austin@codebeard.com>
*
* @property bool $debug
* @property string $capture_packets_file
* @property int $stream_timeout
* @property int $timeout
* @property int $write_wait
*/
class GameQ
{
/*
* Constants
*/
const PROTOCOLS_DIRECTORY = __DIR__ . '/Protocols';
/* Static Section */
/**
* Holds the instance of itself
*
* @type self
*/
protected static $instance = null;
/**
* Create a new instance of this class
*
* @return \GameQ\GameQ
*/
public static function factory()
{
// Create a new instance
self::$instance = new self();
// Return this new instance
return self::$instance;
}
/* Dynamic Section */
/**
* Default options
*
* @type array
*/
protected $options = [
'debug' => false,
'timeout' => 3, // Seconds
'filters' => [
// Default normalize
'normalize_d751713988987e9331980363e24189ce' => [
'filter' => 'normalize',
'options' => [],
],
],
// Advanced settings
'stream_timeout' => 200000, // See http://www.php.net/manual/en/function.stream-select.php for more info
'write_wait' => 500,
// How long (in micro-seconds) to pause between writing to server sockets, helps cpu usage
// Used for generating protocol test data
'capture_packets_file' => null,
];
/**
* Array of servers being queried
*
* @type array
*/
protected $servers = [];
/**
* The query library to use. Default is Native
*
* @type string
*/
protected $queryLibrary = 'GameQ\\Query\\Native';
/**
* Holds the instance of the queryLibrary
*
* @type \GameQ\Query\Core|null
*/
protected $query = null;
/**
* GameQ constructor.
*
* Do some checks as needed so this will operate
*/
public function __construct()
{
// Check for missing utf8_encode function
if (!function_exists('utf8_encode')) {
throw new \Exception("PHP's utf8_encode() function is required - "
. "http://php.net/manual/en/function.utf8-encode.php. Check your php installation.");
}
}
/**
* Get an option's value
*
* @param mixed $option
*
* @return mixed|null
*/
public function __get($option)
{
return isset($this->options[$option]) ? $this->options[$option] : null;
}
/**
* Set an option's value
*
* @param mixed $option
* @param mixed $value
*
* @return bool
*/
public function __set($option, $value)
{
$this->options[$option] = $value;
return true;
}
public function getServers()
{
return $this->servers;
}
public function getOptions()
{
return $this->options;
}
/**
* Chainable call to __set, uses set as the actual setter
*
* @param mixed $var
* @param mixed $value
*
* @return $this
*/
public function setOption($var, $value)
{
// Use magic
$this->{$var} = $value;
return $this; // Make chainable
}
/**
* Add a single server
*
* @param array $server_info
*
* @return $this
*/
public function addServer(array $server_info = [])
{
// Add and validate the server
$this->servers[uniqid()] = new Server($server_info);
return $this; // Make calls chainable
}
/**
* Add multiple servers in a single call
*
* @param array $servers
*
* @return $this
*/
public function addServers(array $servers = [])
{
// Loop through all the servers and add them
foreach ($servers as $server_info) {
$this->addServer($server_info);
}
return $this; // Make calls chainable
}
/**
* Add a set of servers from a file or an array of files.
* Supported formats:
* JSON
*
* @param array $files
*
* @return $this
* @throws \Exception
*/
public function addServersFromFiles($files = [])
{
// Since we expect an array let us turn a string (i.e. single file) into an array
if (!is_array($files)) {
$files = [$files];
}
// Iterate over the file(s) and add them
foreach ($files as $file) {
// Check to make sure the file exists and we can read it
if (!file_exists($file) || !is_readable($file)) {
continue;
}
// See if this file is JSON
if (($servers = json_decode(file_get_contents($file), true)) === null
&& json_last_error() !== JSON_ERROR_NONE
) {
// Type not supported
continue;
}
// Add this list of servers
$this->addServers($servers);
}
return $this;
}
/**
* Clear all of the defined servers
*
* @return $this
*/
public function clearServers()
{
// Reset all the servers
$this->servers = [];
return $this; // Make Chainable
}
/**
* Add a filter to the processing list
*
* @param string $filterName
* @param array $options
*
* @return $this
*/
public function addFilter($filterName, $options = [])
{
// Create the filter hash so we can run multiple versions of the same filter
$filterHash = sprintf('%s_%s', strtolower($filterName), md5(json_encode($options)));
// Add the filter
$this->options['filters'][$filterHash] = [
'filter' => strtolower($filterName),
'options' => $options,
];
unset($filterHash);
return $this;
}
/**
* Remove an added filter
*
* @param string $filterHash
*
* @return $this
*/
public function removeFilter($filterHash)
{
// Make lower case
$filterHash = strtolower($filterHash);
// Remove this filter if it has been defined
if (array_key_exists($filterHash, $this->options['filters'])) {
unset($this->options['filters'][$filterHash]);
}
unset($filterHash);
return $this;
}
/**
* Return the list of applied filters
*
* @return array
*/
public function listFilters()
{
return $this->options['filters'];
}
/**
* Main method used to actually process all of the added servers and return the information
*
* @return array
* @throws \Exception
*/
public function process()
{
// Initialize the query library we are using
$class = new \ReflectionClass($this->queryLibrary);
// Set the query pointer to the new instance of the library
$this->query = $class->newInstance();
unset($class);
// Define the return
$results = [];
// @todo: Add break up into loop to split large arrays into smaller chunks
// Do server challenge(s) first, if any
$this->doChallenges();
// Do packets for server(s) and get query responses
$this->doQueries();
// Now we should have some information to process for each server
foreach ($this->servers as $server) {
/* @var $server \GameQ\Server */
// Parse the responses for this server
$result = $this->doParseResponse($server);
// Apply the filters
$result = array_merge($result, $this->doApplyFilters($result, $server));
// Sort the keys so they are alphabetical and nicer to look at
ksort($result);
// Add the result to the results array
$results[$server->id()] = $result;
}
return $results;
}
/**
* Do server challenges, where required
*/
protected function doChallenges()
{
// Initialize the sockets for reading
$sockets = [];
// By default we don't have any challenges to process
$server_challenge = false;
// Do challenge packets
foreach ($this->servers as $server_id => $server) {
/* @var $server \GameQ\Server */
// This protocol has a challenge packet that needs to be sent
if ($server->protocol()->hasChallenge()) {
// We have a challenge, set the flag
$server_challenge = true;
// Let's make a clone of the query class
$socket = clone $this->query;
// Set the information for this query socket
$socket->set(
$server->protocol()->transport(),
$server->ip,
$server->port_query,
$this->timeout
);
try {
// Now write the challenge packet to the socket.
$socket->write($server->protocol()->getPacket(Protocol::PACKET_CHALLENGE));
// Add the socket information so we can reference it easily
$sockets[(int)$socket->get()] = [
'server_id' => $server_id,
'socket' => $socket,
];
} catch (QueryException $exception) {
// Check to see if we are in debug, if so bubble up the exception
if ($this->debug) {
throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
}
}
unset($socket);
// Let's sleep shortly so we are not hammering out calls rapid fire style hogging cpu
usleep($this->write_wait);
}
}
// We have at least one server with a challenge, we need to listen for responses
if ($server_challenge) {
// Now we need to listen for and grab challenge response(s)
$responses = call_user_func_array(
[$this->query, 'getResponses'],
[$sockets, $this->timeout, $this->stream_timeout]
);
// Iterate over the challenge responses
foreach ($responses as $socket_id => $response) {
// Back out the server_id we need to update the challenge response for
$server_id = $sockets[$socket_id]['server_id'];
// Make this into a buffer so it is easier to manipulate
$challenge = new Buffer(implode('', $response));
// Grab the server instance
/* @var $server \GameQ\Server */
$server = $this->servers[$server_id];
// Apply the challenge
$server->protocol()->challengeParseAndApply($challenge);
// Add this socket to be reused, has to be reused in GameSpy3 for example
$server->socketAdd($sockets[$socket_id]['socket']);
// Clear
unset($server);
}
}
}
/**
* Run the actual queries and get the response(s)
*/
protected function doQueries()
{
// Initialize the array of sockets
$sockets = [];
// Iterate over the server list
foreach ($this->servers as $server_id => $server) {
/* @var $server \GameQ\Server */
// Invoke the beforeSend method
$server->protocol()->beforeSend($server);
// Get all the non-challenge packets we need to send
$packets = $server->protocol()->getPacket('!' . Protocol::PACKET_CHALLENGE);
if (count($packets) == 0) {
// Skip nothing else to do for some reason.
continue;
}
// Try to use an existing socket
if (($socket = $server->socketGet()) === null) {
// Let's make a clone of the query class
$socket = clone $this->query;
// Set the information for this query socket
$socket->set(
$server->protocol()->transport(),
$server->ip,
$server->port_query,
$this->timeout
);
}
try {
// Iterate over all the packets we need to send
foreach ($packets as $packet_data) {
// Now write the packet to the socket.
$socket->write($packet_data);
// Let's sleep shortly so we are not hammering out calls rapid fire style
usleep($this->write_wait);
}
unset($packets);
// Add the socket information so we can reference it easily
$sockets[(int)$socket->get()] = [
'server_id' => $server_id,
'socket' => $socket,
];
} catch (QueryException $exception) {
// Check to see if we are in debug, if so bubble up the exception
if ($this->debug) {
throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
}
continue;
}
// Clean up the sockets, if any left over
$server->socketCleanse();
}
// Now we need to listen for and grab response(s)
$responses = call_user_func_array(
[$this->query, 'getResponses'],
[$sockets, $this->timeout, $this->stream_timeout]
);
// Iterate over the responses
foreach ($responses as $socket_id => $response) {
// Back out the server_id
$server_id = $sockets[$socket_id]['server_id'];
// Grab the server instance
/* @var $server \GameQ\Server */
$server = $this->servers[$server_id];
// Save the response from this packet
$server->protocol()->packetResponse($response);
unset($server);
}
// Now we need to close all of the sockets
foreach ($sockets as $socketInfo) {
/* @var $socket \GameQ\Query\Core */
$socket = $socketInfo['socket'];
// Close the socket
$socket->close();
unset($socket);
}
unset($sockets);
}
/**
* Parse the response for a specific server
*
* @param \GameQ\Server $server
*
* @return array
* @throws \Exception
*/
protected function doParseResponse(Server $server)
{
try {
// @codeCoverageIgnoreStart
// We want to save this server's response to a file (useful for unit testing)
if (!is_null($this->capture_packets_file)) {
file_put_contents(
$this->capture_packets_file,
implode(PHP_EOL . '||' . PHP_EOL, $server->protocol()->packetResponse())
);
}
// @codeCoverageIgnoreEnd
// Get the server response
$results = $server->protocol()->processResponse();
// Check for online before we do anything else
$results['gq_online'] = (count($results) > 0);
} catch (ProtocolException $e) {
// Check to see if we are in debug, if so bubble up the exception
if ($this->debug) {
throw new \Exception($e->getMessage(), $e->getCode(), $e);
}
// We ignore this server
$results = [
'gq_online' => false,
];
}
// Now add some default stuff
$results['gq_address'] = (isset($results['gq_address'])) ? $results['gq_address'] : $server->ip();
$results['gq_port_client'] = $server->portClient();
$results['gq_port_query'] = (isset($results['gq_port_query'])) ? $results['gq_port_query'] : $server->portQuery();
$results['gq_protocol'] = $server->protocol()->getProtocol();
$results['gq_type'] = (string)$server->protocol();
$results['gq_name'] = $server->protocol()->nameLong();
$results['gq_transport'] = $server->protocol()->transport();
// Process the join link
if (!isset($results['gq_joinlink']) || empty($results['gq_joinlink'])) {
$results['gq_joinlink'] = $server->getJoinLink();
}
return $results;
}
/**
* Apply any filters to the results
*
* @param array $results
* @param \GameQ\Server $server
*
* @return array
*/
protected function doApplyFilters(array $results, Server $server)
{
// Loop over the filters
foreach ($this->options['filters'] as $filterOptions) {
// Try to do this filter
try {
// Make a new reflection class
$class = new \ReflectionClass(sprintf('GameQ\\Filters\\%s', ucfirst($filterOptions['filter'])));
// Create a new instance of the filter class specified
$filter = $class->newInstanceArgs([$filterOptions['options']]);
// Apply the filter to the data
$results = $filter->apply($results, $server);
} catch (\ReflectionException $exception) {
// Invalid, skip it
continue;
}
}
return $results;
}
}

View file

@ -0,0 +1,82 @@
<?php
global $settings;
// Skip server queries if there are too many total servers
if(isset($_SESSION))
$num_of_servers = $db->getNumberOfOwnedServersPerUser( $_SESSION['user_id'] );
else
$num_of_servers = 0;
if(isset($settings['query_num_servers_stop']) && is_numeric($settings['query_num_servers_stop']))
$numberservers_to_skip_query = $settings['query_num_servers_stop'];
else
$numberservers_to_skip_query = 15;
if($num_of_servers < $numberservers_to_skip_query)
{
if ( $server_home['use_nat'] == 1 )
$internal_query_ip = $server_home['agent_ip'];
else
$internal_query_ip = $server_home['ip'];
$query_cache_life = ( isset($settings['query_cache_life']) and is_numeric($settings['query_cache_life']) )? $settings['query_cache_life'] : 30;
$ip_id = $db->getIpIdByIp($server_home['ip']);
$statusCache = $db->getServerStatusCache($ip_id,$port);
if( !empty($statusCache) AND date('YmdHis',$statusCache['date_timestamp'] + $query_cache_life) >= date('YmdHis') )
{
$results = $statusCache;
}
else
{
require_once 'protocol/GameQ/Autoloader.php';
$port = $server_home['port'];
$query_port = get_query_port($server_xml, $port);
$gq = new \GameQ\GameQ();
$server = array(
'id' => 'server',
'type' => $server_xml->gameq_query_name,
'host' => $internal_query_ip . ":" . $query_port,
);
$gq->addServer($server);
$gq->setOption('timeout', 4);
$gq->setOption('debug', FALSE);
$gq->addFilter('normalise');
$results = $gq->process();
$db->saveServerStatusCache($ip_id,$port,$results);
}
if($results['server']['gq_online'] == 1)
{
$status = "online";
// Some functions to print the results
$players = $results['server']['gq_numplayers'];
$playersmax = $results['server']['gq_maxplayers'];
$name = $results['server']['gq_hostname'];
$map = preg_replace("/[^a-z0-9_]/", "_", strtolower(@(string)$results['server']['gq_mapname']));
//----------+ patches for voice servers (ts2, ts3, ventrilo)
if(!$map)$map = $results['server']['gq_type'];
if(!$players)$players = 0;
@$stats_players += $players; // COUNT VISIBLE NUMBER OF PLAYERS
@$stats_maxplayers += $playersmax; // COUNT VISIBLE NUMBER OF SLOTS
if ( $results['server']['gq_numplayers'] > 0 )
$player_list = print_player_list_gameq($results['server']['players'],$players,$playersmax);
if(isset($results['gq_joinlink']) and $results['gq_joinlink'] != "")
$address = "<a href='$results[gq_joinlink]'>$ip:$port</a>";
elseif($server_xml->installer == 'steamcmd')
$address = "<a href='steam://connect/$internal_query_ip:$port'>$ip:$port</a>";
else
$address = "$ip:$port";
$playersList = $results['server']['players'];
$maplocation = get_map_path($query_name,$mod,$map);
}
else
$status = "half";
}
else
{
$status = "half";
$notifications = get_lang_f('queries_disabled_by_setting_disable_queries_after',$numberservers_to_skip_query,$num_of_servers);
}
?>

View file

@ -0,0 +1,500 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
namespace GameQ;
/**
* Handles the core functionality for the protocols
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
*
* @author Austin Bischoff <austin@codebeard.com>
*/
abstract class Protocol
{
/**
* Constants for class states
*/
const STATE_TESTING = 1;
const STATE_BETA = 2;
const STATE_STABLE = 3;
const STATE_DEPRECATED = 4;
/**
* Constants for packet keys
*/
const PACKET_ALL = 'all'; // Some protocols allow all data to be sent back in one call.
const PACKET_BASIC = 'basic';
const PACKET_CHALLENGE = 'challenge';
const PACKET_CHANNELS = 'channels'; // Voice servers
const PACKET_DETAILS = 'details';
const PACKET_INFO = 'info';
const PACKET_PLAYERS = 'players';
const PACKET_STATUS = 'status';
const PACKET_RULES = 'rules';
const PACKET_VERSION = 'version';
/**
* Transport constants
*/
const TRANSPORT_UDP = 'udp';
const TRANSPORT_TCP = 'tcp';
const TRANSPORT_SSL = 'ssl';
const TRANSPORT_TLS = 'tls';
/**
* Short name of the protocol
*
* @type string
*/
protected $name = 'unknown';
/**
* The longer, fancier name for the protocol
*
* @type string
*/
protected $name_long = 'unknown';
/**
* The difference between the client port and query port
*
* @type int
*/
protected $port_diff = 0;
/**
* The transport method to use to actually send the data
* Default is UDP
*
* @type string
*/
protected $transport = self::TRANSPORT_UDP;
/**
* The protocol type used when querying the server
*
* @type string
*/
protected $protocol = 'unknown';
/**
* Holds the valid packet types this protocol has available.
*
* @type array
*/
protected $packets = [];
/**
* Holds the response headers and the method to use to process them.
*
* @type array
*/
protected $responses = [];
/**
* Holds the list of methods to run when parsing the packet response(s) data. These
* methods should provide all the return information.
*
* @type array
*/
protected $process_methods = [];
/**
* The packet responses received
*
* @type array
*/
protected $packets_response = [];
/**
* Holds the instance of the result class
*
* @type null
*/
protected $result = null;
/**
* Options for this protocol
*
* @type array
*/
protected $options = [];
/**
* Define the state of this class
*
* @type int
*/
protected $state = self::STATE_STABLE;
/**
* Holds specific normalize settings
*
* @todo: Remove this ugly bulk by moving specific ones to their specific game(s)
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => [
'listenserver',
'dedic',
'bf2dedicated',
'netserverdedicated',
'bf2142dedicated',
'dedicated',
],
'gametype' => ['ggametype', 'sigametype', 'matchtype'],
'hostname' => ['svhostname', 'servername', 'siname', 'name'],
'mapname' => ['map', 'simap'],
'maxplayers' => ['svmaxclients', 'simaxplayers', 'maxclients', 'max_players'],
'mod' => ['game', 'gamedir', 'gamevariant'],
'numplayers' => ['clients', 'sinumplayers', 'num_players'],
'password' => ['protected', 'siusepass', 'sineedpass', 'pswrd', 'gneedpass', 'auth', 'passsord'],
],
// Indvidual
'player' => [
'name' => ['nick', 'player', 'playername', 'name'],
'kills' => ['kills'],
'deaths' => ['deaths'],
'score' => ['kills', 'frags', 'skill', 'score'],
'ping' => ['ping'],
],
// Team
'team' => [
'name' => ['name', 'teamname', 'team_t'],
'score' => ['score', 'score_t'],
],
];
/**
* Quick join link
*
* @type string
*/
protected $join_link = '';
/**
* @param array $options
*/
public function __construct(array $options = [])
{
// Set the options for this specific instance of the class
$this->options = $options;
}
/**
* String name of this class
*
* @return string
*/
public function __toString()
{
return $this->name;
}
/**
* Get the port difference between the server's client (game) and query ports
*
* @return int
*/
public function portDiff()
{
return $this->port_diff;
}
/**
* "Find" the query port based off of the client port and port_diff
*
* This method is meant to be overloaded for more complex maths or lookup tables
*
* @param int $clientPort
*
* @return int
*/
public function findQueryPort($clientPort)
{
return $clientPort + $this->port_diff;
}
/**
* Return the join_link as defined by the protocol class
*
* @return string
*/
public function joinLink()
{
return $this->join_link;
}
/**
* Short (callable) name of this class
*
* @return string
*/
public function name()
{
return $this->name;
}
/**
* Long name of this class
*
* @return string
*/
public function nameLong()
{
return $this->name_long;
}
/**
* Return the status of this Protocol Class
*
* @return int
*/
public function state()
{
return $this->state;
}
/**
* Return the protocol property
*
* @return string
*/
public function getProtocol()
{
return $this->protocol;
}
/**
* Get/set the transport type for this protocol
*
* @param string|null $type
*
* @return string
*/
public function transport($type = null)
{
// Act as setter
if (!is_null($type)) {
$this->transport = $type;
}
return $this->transport;
}
/**
* Set the options for the protocol call
*
* @param array $options
*
* @return array
*/
public function options($options = [])
{
// Act as setter
if (!empty($options)) {
$this->options = $options;
}
return $this->options;
}
/*
* Packet Section
*/
/**
* Return specific packet(s)
*
* @param array $type
*
* @return array
*/
public function getPacket($type = [])
{
$packets = [];
// We want an array of packets back
if (is_array($type) && !empty($type)) {
// Loop the packets
foreach ($this->packets as $packet_type => $packet_data) {
// We want this packet
if (in_array($packet_type, $type)) {
$packets[$packet_type] = $packet_data;
}
}
} elseif ($type == '!challenge') {
// Loop the packets
foreach ($this->packets as $packet_type => $packet_data) {
// Dont want challenge packets
if ($packet_type != self::PACKET_CHALLENGE) {
$packets[$packet_type] = $packet_data;
}
}
} elseif (is_string($type)) {
// Return specific packet type
$packets = $this->packets[$type];
} else {
// Return all packets
$packets = $this->packets;
}
// Return the packets
return $packets;
}
/**
* Get/set the packet response
*
* @param array|null $response
*
* @return array
*/
public function packetResponse(array $response = null)
{
// Act as setter
if (!empty($response)) {
$this->packets_response = $response;
}
return $this->packets_response;
}
/*
* Challenge section
*/
/**
* Determine whether or not this protocol has a challenge needed before querying
*
* @return bool
*/
public function hasChallenge()
{
return (isset($this->packets[self::PACKET_CHALLENGE]) && !empty($this->packets[self::PACKET_CHALLENGE]));
}
/**
* Parse the challenge response and add it to the buffer items that need it.
* This should be overloaded by extending class
*
* @codeCoverageIgnore
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param \GameQ\Buffer $challenge_buffer
*
* @return bool
*/
public function challengeParseAndApply(Buffer $challenge_buffer)
{
return true;
}
/**
* Apply the challenge string to all the packets that need it.
*
* @param string $challenge_string
*
* @return bool
*/
protected function challengeApply($challenge_string)
{
// Let's loop through all the packets and append the challenge where it is needed
foreach ($this->packets as $packet_type => $packet) {
$this->packets[$packet_type] = sprintf($packet, $challenge_string);
}
return true;
}
/**
* Get the normalize settings for the protocol
*
* @return array
*/
public function getNormalize()
{
return $this->normalize;
}
/*
* General
*/
/**
* Generic method to allow protocol classes to do work right before the query is sent
*
* @codeCoverageIgnore
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param \GameQ\Server $server
*/
public function beforeSend(Server $server)
{
}
/**
* Method called to process query response data. Each extending class has to have one of these functions.
*
* @return mixed
*/
abstract public function processResponse();
}

View file

@ -0,0 +1,53 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Aa3
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Aa3 extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'aa3';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "America's Army 3";
/**
* Query port = client_port + 18243
*
* client_port default 8777
* query_port default 27020
*
* @type int
*/
protected $port_diff = 18243;
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Aapg
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Aapg extends Aa3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'aapg';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "America's Army: Proving Grounds";
}

View file

@ -0,0 +1,51 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class ARK: Survival Evolved
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Arkse extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'arkse';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "ARK: Survival Evolved";
/**
* query_port = client_port + 19238
* 27015 = 7777 + 19238
*
* @type int
*/
protected $port_diff = 19238;
}

View file

@ -0,0 +1,43 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Arma
*
* @package GameQ\Protocols
*
* @author Wilson Jesus <>
*/
class Arma extends Gamespy2
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'arma';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "ArmA Armed Assault";
}

View file

@ -0,0 +1,221 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Buffer;
use GameQ\Result;
/**
* Class Armed Assault 3
*
* Rules protocol reference: https://community.bistudio.com/wiki/Arma_3_ServerBrowserProtocol2
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
* @author Memphis017 <https://github.com/Memphis017>
*/
class Arma3 extends Source
{
// Base DLC names
const BASE_DLC_KART = 'Karts';
const BASE_DLC_MARKSMEN = 'Marksmen';
const BASE_DLC_HELI = 'Helicopters';
const BASE_DLC_CURATOR = 'Curator';
const BASE_DLC_EXPANSION = 'Expansion';
const BASE_DLC_JETS = 'Jets';
const BASE_DLC_ORANGE = 'Laws of War';
const BASE_DLC_ARGO = 'Malden';
const BASE_DLC_TACOPS = 'Tac-Ops';
const BASE_DLC_TANKS = 'Tanks';
const BASE_DLC_CONTACT = 'Contact';
const BASE_DLC_ENOCH = 'Contact (Platform)';
// Special
const BASE_DLC_AOW = 'Art of War';
// Creator DLC names
const CREATOR_DLC_GM = 'Global Mobilization';
const CREATOR_DLC_VN = 'S.O.G. Prairie Fire';
const CREATOR_DLC_CSLA = 'ČSLA - Iron Curtain';
const CREATOR_DLC_WS = 'Western Sahara';
/**
* DLC Flags/Bits as defined in the documentation.
*
* @see https://community.bistudio.com/wiki/Arma_3:_ServerBrowserProtocol3
*
* @var array
*/
protected $dlcFlags = [
0b0000000000000001 => self::BASE_DLC_KART,
0b0000000000000010 => self::BASE_DLC_MARKSMEN,
0b0000000000000100 => self::BASE_DLC_HELI,
0b0000000000001000 => self::BASE_DLC_CURATOR,
0b0000000000010000 => self::BASE_DLC_EXPANSION,
0b0000000000100000 => self::BASE_DLC_JETS,
0b0000000001000000 => self::BASE_DLC_ORANGE,
0b0000000010000000 => self::BASE_DLC_ARGO,
0b0000000100000000 => self::BASE_DLC_TACOPS,
0b0000001000000000 => self::BASE_DLC_TANKS,
0b0000010000000000 => self::BASE_DLC_CONTACT,
0b0000100000000000 => self::BASE_DLC_ENOCH,
0b0001000000000000 => self::BASE_DLC_AOW,
0b0010000000000000 => 'Unknown',
0b0100000000000000 => 'Unknown',
0b1000000000000000 => 'Unknown',
];
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'arma3';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Arma3";
/**
* Query port = client_port + 1
*
* @type int
*/
protected $port_diff = 1;
/**
* Process the rules since Arma3 changed their response for rules
*
* @param Buffer $buffer
*
* @return array
* @throws \GameQ\Exception\Protocol
*/
protected function processRules(Buffer $buffer)
{
// Total number of packets, burn it
$buffer->readInt16();
// Will hold the data string
$data = '';
// Loop until we run out of strings
while ($buffer->getLength()) {
// Burn the delimiters (i.e. \x01\x04\x00)
$buffer->readString();
// Add the data to the string, we are reassembling it
$data .= $buffer->readString();
}
// Restore escaped sequences
$data = str_replace(["\x01\x01", "\x01\x02", "\x01\x03"], ["\x01", "\x00", "\xFF"], $data);
// Make a new buffer with the reassembled data
$responseBuffer = new Buffer($data);
// Kill the old buffer, should be empty
unset($buffer, $data);
// Set the result to a new result instance
$result = new Result();
// Get results
$result->add('rules_protocol_version', $responseBuffer->readInt8()); // read protocol version
$result->add('overflow', $responseBuffer->readInt8()); // Read overflow flags
$dlcByte = $responseBuffer->readInt8(); // Grab DLC byte 1 and use it later
$dlcByte2 = $responseBuffer->readInt8(); // Grab DLC byte 2 and use it later
$dlcBits = ($dlcByte2 << 8) | $dlcByte; // concatenate DLC bits to 16 Bit int
// Grab difficulty so we can man handle it...
$difficulty = $responseBuffer->readInt8();
// Process difficulty
$result->add('3rd_person', $difficulty >> 7);
$result->add('advanced_flight_mode', ($difficulty >> 6) & 1);
$result->add('difficulty_ai', ($difficulty >> 3) & 3);
$result->add('difficulty_level', $difficulty & 3);
unset($difficulty);
// Crosshair
$result->add('crosshair', $responseBuffer->readInt8());
// Loop over the base DLC bits so we can pull in the info for the DLC (if enabled)
foreach ($this->dlcFlags as $dlcFlag => $dlcName) {
// Check that the DLC bit is enabled
if (($dlcBits & $dlcFlag) === $dlcFlag) {
// Add the DLC to the list
$result->addSub('dlcs', 'name', $dlcName);
$result->addSub('dlcs', 'hash', dechex($responseBuffer->readInt32()));
}
}
// Read the mount of mods, these include DLC as well as Creator DLC and custom modifications
$modCount = $responseBuffer->readInt8();
// Add mod count
$result->add('mod_count', $modCount);
// Loop over the mods
while ($modCount) {
// Read the mods hash
$result->addSub('mods', 'hash', dechex($responseBuffer->readInt32()));
// Get the information byte containing DLC flag and steamId length
$infoByte = $responseBuffer->readInt8();
// Determine isDLC by flag, first bit in upper nibble
$result->addSub('mods', 'dlc', ($infoByte & 0b00010000) === 0b00010000);
// Read the steam id of the mod/CDLC (might be less than 4 bytes)
$result->addSub('mods', 'steam_id', $responseBuffer->readInt32($infoByte & 0x0F));
// Read the name of the mod
$result->addSub('mods', 'name', $responseBuffer->readPascalString(0, true) ?: 'Unknown');
--$modCount;
}
// No longer needed
unset($dlcByte, $dlcByte2, $dlcBits);
// Get the signatures count
$signatureCount = $responseBuffer->readInt8();
$result->add('signature_count', $signatureCount);
// Make signatures array
$signatures = [];
// Loop until we run out of signatures
for ($x = 0; $x < $signatureCount; $x++) {
$signatures[] = $responseBuffer->readPascalString(0, true);
}
// Add as a simple array
$result->add('signatures', $signatures);
unset($responseBuffer, $signatureCount, $signatures, $x);
return $result->fetch();
}
}

View file

@ -0,0 +1,50 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Armedassault2oa
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Armedassault2oa extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = "armedassault2oa";
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Armed Assault 2: Operation Arrowhead";
/**
* Query port = client_port + 1
*
* @type int
*/
protected $port_diff = 1;
}

View file

@ -0,0 +1,32 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Armed assault 3 dummy Protocol Class
*
* Added for backward compatibility, please update to class arma3
*
* @deprecated v3.0.10
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Armedassault3 extends Arma3
{
}

View file

@ -0,0 +1,217 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Protocol;
use GameQ\Buffer;
use GameQ\Result;
/**
* All-Seeing Eye Protocol class
*
* @author Marcel Bößendörfer <m.boessendoerfer@marbis.net>
* @author Austin Bischoff <austin@codebeard.com>
*/
class Ase extends Protocol
{
/**
* Array of packets we want to look up.
* Each key should correspond to a defined method in this or a parent class
*
* @type array
*/
protected $packets = [
self::PACKET_ALL => "s",
];
/**
* The query protocol used to make the call
*
* @type string
*/
protected $protocol = 'ase';
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'ase';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "All-Seeing Eye";
/**
* The client join link
*
* @type string
*/
protected $join_link = null;
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => 'dedicated',
'gametype' => 'gametype',
'hostname' => 'servername',
'mapname' => 'map',
'maxplayers' => 'max_players',
'mod' => 'game_dir',
'numplayers' => 'num_players',
'password' => 'password',
],
// Individual
'player' => [
'name' => 'name',
'score' => 'score',
'team' => 'team',
'ping' => 'ping',
'time' => 'time',
],
];
/**
* Process the response
*
* @return array
* @throws \GameQ\Exception\Protocol
*/
public function processResponse()
{
// Create a new buffer
$buffer = new Buffer(implode('', $this->packets_response));
// Check for valid response
if ($buffer->getLength() < 4) {
throw new \GameQ\Exception\Protocol(sprintf('%s The response from the server was empty.', __METHOD__));
}
// Read the header
$header = $buffer->read(4);
// Verify header
if ($header !== 'EYE1') {
throw new \GameQ\Exception\Protocol(sprintf('%s The response header "%s" does not match expected "EYE1"', __METHOD__, $header));
}
// Create a new result
$result = new Result();
// Variables
$result->add('gamename', $buffer->readPascalString(1, true));
$result->add('port', $buffer->readPascalString(1, true));
$result->add('servername', $buffer->readPascalString(1, true));
$result->add('gametype', $buffer->readPascalString(1, true));
$result->add('map', $buffer->readPascalString(1, true));
$result->add('version', $buffer->readPascalString(1, true));
$result->add('password', $buffer->readPascalString(1, true));
$result->add('num_players', $buffer->readPascalString(1, true));
$result->add('max_players', $buffer->readPascalString(1, true));
$result->add('dedicated', 1);
// Offload the key/value pair processing
$this->processKeyValuePairs($buffer, $result);
// Offload processing player and team info
$this->processPlayersAndTeams($buffer, $result);
unset($buffer);
return $result->fetch();
}
/*
* Internal methods
*/
/**
* Handles processing the extra key/value pairs for server settings
*
* @param \GameQ\Buffer $buffer
* @param \GameQ\Result $result
*/
protected function processKeyValuePairs(Buffer &$buffer, Result &$result)
{
// Key / value pairs
while ($buffer->getLength()) {
$key = $buffer->readPascalString(1, true);
// If we have an empty key, we've reached the end
if (empty($key)) {
break;
}
// Otherwise, add the pair
$result->add(
$key,
$buffer->readPascalString(1, true)
);
}
unset($key);
}
/**
* Handles processing the player and team data into a usable format
*
* @param \GameQ\Buffer $buffer
* @param \GameQ\Result $result
*/
protected function processPlayersAndTeams(Buffer &$buffer, Result &$result)
{
// Players and team info
while ($buffer->getLength()) {
// Get the flags
$flags = $buffer->readInt8();
// Get data according to the flags
if ($flags & 1) {
$result->addPlayer('name', $buffer->readPascalString(1, true));
}
if ($flags & 2) {
$result->addPlayer('team', $buffer->readPascalString(1, true));
}
if ($flags & 4) {
$result->addPlayer('skin', $buffer->readPascalString(1, true));
}
if ($flags & 8) {
$result->addPlayer('score', $buffer->readPascalString(1, true));
}
if ($flags & 16) {
$result->addPlayer('ping', $buffer->readPascalString(1, true));
}
if ($flags & 32) {
$result->addPlayer('time', $buffer->readPascalString(1, true));
}
}
}
}

View file

@ -0,0 +1,55 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Atlas
*
* @package GameQ\Protocols
* @author Wilson Jesus <>
*/
class Atlas extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'atlas';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Atlas";
/**
* query_port = client_port + 51800
* 57561 = 5761 + 51800
*
* this is the default value for the stock game server, both ports
* can be independently changed from the stock ones,
* making the port_diff logic useless.
*
* @type int
*/
protected $port_diff = 51800;
}

View file

@ -0,0 +1,48 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Avorion Protocol Class
*
* @package GameQ\Protocols
*/
class Avorion extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'avorion';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Avorion";
/**
* query_port = client_port + 1
*
* @type int
* protected $port_diff = 1;
*/
}

View file

@ -0,0 +1,49 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Barotrauma Protocol Class
*
* @package GameQ\Protocols
* @author Jesse Lukas <eranio@g-one.org>
*/
class Barotrauma extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'barotrauma';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Barotrauma";
/**
* query_port = client_port + 1
*
* @type int
*/
protected $port_diff = 1;
}

View file

@ -0,0 +1,68 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Battalion 1944
*
* @package GameQ\Protocols
* @author TacTicToe66 <https://github.com/TacTicToe66>
*/
class Batt1944 extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'batt1944';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battalion 1944";
/**
* query_port = client_port + 3
*
* @type int
*/
protected $port_diff = 3;
/**
* Normalize main fields
*
* @var array
*/
protected $normalize = [
// General
'general' => [
// target => source
'gametype' => 'bat_gamemode_s',
'hostname' => 'bat_name_s',
'mapname' => 'bat_map_s',
'maxplayers' => 'bat_max_players_i',
'numplayers' => 'bat_player_count_s',
'password' => 'bat_has_password_s',
],
];
}

View file

@ -0,0 +1,88 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Battlefield 1942
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bf1942 extends Gamespy
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bf1942';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield 1942";
/**
* query_port = client_port + 8433
* 23000 = 14567 + 8433
*
* @type int
*/
protected $port_diff = 8433;
/**
* The client join link
*
* @type string
*/
protected $join_link = "bf1942://%s:%d";
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => 'dedicated',
'gametype' => 'gametype',
'hostname' => 'hostname',
'mapname' => 'mapname',
'maxplayers' => 'maxplayers',
'numplayers' => 'numplayers',
'password' => 'password',
],
// Individual
'player' => [
'name' => 'playername',
'kills' => 'kills',
'deaths' => 'deaths',
'ping' => 'ping',
'score' => 'score',
],
'team' => [
'name' => 'teamname',
],
];
}

View file

@ -0,0 +1,98 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Battlefield 2
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bf2 extends Gamespy3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bf2';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield 2";
/**
* query_port = client_port + 8433
* 29900 = 16567 + 13333
*
* @type int
*/
protected $port_diff = 13333;
/**
* The client join link
*
* @type string
*/
protected $join_link = "bf2://%s:%d";
/**
* BF2 has a different query packet to send than "normal" Gamespy 3
*
* @var array
*/
protected $packets = [
self::PACKET_ALL => "\xFE\xFD\x00\x10\x20\x30\x40\xFF\xFF\xFF\x01",
];
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => 'dedicated',
'gametype' => 'gametype',
'hostname' => 'hostname',
'mapname' => 'mapname',
'maxplayers' => 'maxplayers',
'numplayers' => 'numplayers',
'password' => 'password',
],
// Individual
'player' => [
'name' => 'player',
'kills' => 'score',
'deaths' => 'deaths',
'ping' => 'ping',
'score' => 'score',
],
'team' => [
'name' => 'team',
'score' => 'score',
],
];
}

View file

@ -0,0 +1,348 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Protocol;
use GameQ\Buffer;
use GameQ\Result;
use GameQ\Exception\Protocol as Exception;
/**
* Battlefield 3 Protocol Class
*
* Good place for doc status and info is http://www.fpsadmin.com/forum/showthread.php?t=24134
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bf3 extends Protocol
{
/**
* Array of packets we want to query.
*
* @type array
*/
protected $packets = [
self::PACKET_STATUS => "\x00\x00\x00\x21\x1b\x00\x00\x00\x01\x00\x00\x00\x0a\x00\x00\x00serverInfo\x00",
self::PACKET_VERSION => "\x00\x00\x00\x22\x18\x00\x00\x00\x01\x00\x00\x00\x07\x00\x00\x00version\x00",
self::PACKET_PLAYERS =>
"\x00\x00\x00\x23\x24\x00\x00\x00\x02\x00\x00\x00\x0b\x00\x00\x00listPlayers\x00\x03\x00\x00\x00\x61ll\x00",
];
/**
* Use the response flag to figure out what method to run
*
* @type array
*/
protected $responses = [
1627389952 => "processDetails", // a
1644167168 => "processVersion", // b
1660944384 => "processPlayers", // c
];
/**
* The transport mode for this protocol is TCP
*
* @type string
*/
protected $transport = self::TRANSPORT_TCP;
/**
* The query protocol used to make the call
*
* @type string
*/
protected $protocol = 'bf3';
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bf3';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield 3";
/**
* The client join link
*
* @type string
*/
protected $join_link = null;
/**
* query_port = client_port + 22000
* 47200 = 25200 + 22000
*
* @type int
*/
protected $port_diff = 22000;
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => 'dedicated',
'hostname' => 'hostname',
'mapname' => 'map',
'maxplayers' => 'max_players',
'numplayers' => 'num_players',
'password' => 'password',
],
'player' => [
'name' => 'name',
'score' => 'score',
'ping' => 'ping',
],
'team' => [
'score' => 'tickets',
],
];
/**
* Process the response for the StarMade server
*
* @return array
* @throws \GameQ\Exception\Protocol
*/
public function processResponse()
{
// Holds the results sent back
$results = [];
// Holds the processed packets after having been reassembled
$processed = [];
// Start up the index for the processed
$sequence_id_last = 0;
foreach ($this->packets_response as $packet) {
// Create a new buffer
$buffer = new Buffer($packet);
// Each "good" packet begins with sequence_id (32-bit)
$sequence_id = $buffer->readInt32();
// Sequence id is a response
if (array_key_exists($sequence_id, $this->responses)) {
$processed[$sequence_id] = $buffer->getBuffer();
$sequence_id_last = $sequence_id;
} else {
// This is a continuation of the previous packet, reset the buffer and append
$buffer->jumpto(0);
// Append
$processed[$sequence_id_last] .= $buffer->getBuffer();
}
}
unset($buffer, $sequence_id_last, $sequence_id);
// Iterate over the combined packets and do some work
foreach ($processed as $sequence_id => $data) {
// Create a new buffer
$buffer = new Buffer($data);
// Get the length of the packet
$packetLength = $buffer->getLength();
// Check to make sure the expected length matches the real length
// Subtract 4 for the sequence_id pulled out earlier
if ($packetLength != ($buffer->readInt32() - 4)) {
throw new Exception(__METHOD__ . " packet length does not match expected length!");
}
// Now we need to call the proper method
$results = array_merge(
$results,
call_user_func_array([$this, $this->responses[$sequence_id]], [$buffer])
);
}
return $results;
}
/*
* Internal Methods
*/
/**
* Decode the buffer into a usable format
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function decode(Buffer $buffer)
{
$items = [];
// Get the number of words in this buffer
$itemCount = $buffer->readInt32();
// Loop over the number of items
for ($i = 0; $i < $itemCount; $i++) {
// Length of the string
$buffer->readInt32();
// Just read the string
$items[$i] = $buffer->readString();
}
return $items;
}
/**
* Process the server details
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processDetails(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
// Server is always dedicated
$result->add('dedicated', 1);
// These are the same no matter what mode the server is in
$result->add('hostname', $items[1]);
$result->add('num_players', (int)$items[2]);
$result->add('max_players', (int)$items[3]);
$result->add('gametype', $items[4]);
$result->add('map', $items[5]);
$result->add('roundsplayed', (int)$items[6]);
$result->add('roundstotal', (int)$items[7]);
$result->add('num_teams', (int)$items[8]);
// Set the current index
$index_current = 9;
// Pull the team count
$teamCount = $result->get('num_teams');
// Loop for the number of teams found, increment along the way
for ($id = 1; $id <= $teamCount; $id++, $index_current++) {
// Shows the tickets
$result->addTeam('tickets', $items[$index_current]);
// We add an id so we know which team this is
$result->addTeam('id', $id);
}
// Get and set the rest of the data points.
$result->add('targetscore', (int)$items[$index_current]);
$result->add('online', 1); // Forced true, it seems $words[$index_current + 1] is always empty
$result->add('ranked', (int)$items[$index_current + 2]);
$result->add('punkbuster', (int)$items[$index_current + 3]);
$result->add('password', (int)$items[$index_current + 4]);
$result->add('uptime', (int)$items[$index_current + 5]);
$result->add('roundtime', (int)$items[$index_current + 6]);
// Added in R9
$result->add('ip_port', $items[$index_current + 7]);
$result->add('punkbuster_version', $items[$index_current + 8]);
$result->add('join_queue', (int)$items[$index_current + 9]);
$result->add('region', $items[$index_current + 10]);
$result->add('pingsite', $items[$index_current + 11]);
$result->add('country', $items[$index_current + 12]);
// Added in R29, No docs as of yet
$result->add('quickmatch', (int)$items[$index_current + 13]); // Guessed from research
unset($items, $index_current, $teamCount, $buffer);
return $result->fetch();
}
/**
* Process the server version
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processVersion(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
$result->add('version', $items[2]);
unset($buffer, $items);
return $result->fetch();
}
/**
* Process the players
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processPlayers(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
// Number of data points per player
$numTags = $items[1];
// Grab the tags for each player
$tags = array_slice($items, 2, $numTags);
// Get the player count
$playerCount = $items[$numTags + 2];
// Iterate over the index until we run out of players
for ($i = 0, $x = $numTags + 3; $i < $playerCount; $i++, $x += $numTags) {
// Loop over the player tags and extract the info for that tag
foreach ($tags as $index => $tag) {
$result->addPlayer($tag, $items[($x + $index)]);
}
}
return $result->fetch();
}
}

View file

@ -0,0 +1,114 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Buffer;
use GameQ\Result;
/**
* Battlefield 4 Protocol class
*
* Good place for doc status and info is http://battlelog.battlefield.com/bf4/forum/view/2955064768683911198/
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bf4 extends Bf3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bf4';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield 4";
/**
* Handle processing details since they are different than BF3
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processDetails(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
// Server is always dedicated
$result->add('dedicated', 1);
// These are the same no matter what mode the server is in
$result->add('hostname', $items[1]);
$result->add('num_players', (int) $items[2]);
$result->add('max_players', (int) $items[3]);
$result->add('gametype', $items[4]);
$result->add('map', $items[5]);
$result->add('roundsplayed', (int) $items[6]);
$result->add('roundstotal', (int) $items[7]);
$result->add('num_teams', (int) $items[8]);
// Set the current index
$index_current = 9;
// Pull the team count
$teamCount = $result->get('num_teams');
// Loop for the number of teams found, increment along the way
for ($id = 1; $id <= $teamCount; $id++, $index_current++) {
// Shows the tickets
$result->addTeam('tickets', $items[$index_current]);
// We add an id so we know which team this is
$result->addTeam('id', $id);
}
// Get and set the rest of the data points.
$result->add('targetscore', (int) $items[$index_current]);
$result->add('online', 1); // Forced true, it seems $words[$index_current + 1] is always empty
$result->add('ranked', (int) $items[$index_current + 2]);
$result->add('punkbuster', (int) $items[$index_current + 3]);
$result->add('password', (int) $items[$index_current + 4]);
$result->add('uptime', (int) $items[$index_current + 5]);
$result->add('roundtime', (int) $items[$index_current + 6]);
$result->add('ip_port', $items[$index_current + 7]);
$result->add('punkbuster_version', $items[$index_current + 8]);
$result->add('join_queue', (int) $items[$index_current + 9]);
$result->add('region', $items[$index_current + 10]);
$result->add('pingsite', $items[$index_current + 11]);
$result->add('country', $items[$index_current + 12]);
//$result->add('quickmatch', (int) $items[$index_current + 13]); Supposed to be here according to R42 but is not
$result->add('blaze_player_count', (int) $items[$index_current + 13]);
$result->add('blaze_game_state', (int) $items[$index_current + 14]);
unset($items, $index_current, $teamCount, $buffer);
return $result->fetch();
}
}

View file

@ -0,0 +1,326 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Protocol;
use GameQ\Buffer;
use GameQ\Result;
use GameQ\Exception\Protocol as Exception;
/**
* Battlefield Bad Company 2 Protocol Class
*
* NOTE: There are no qualifiers to the response packets sent back from the server as to which response packet
* belongs to which query request. For now this class assumes the responses are in the same order as the order in
* which the packets were sent to the server. If this assumption turns out to be wrong there is easy way to tell which
* response belongs to which query. Hopefully this assumption will hold true as it has in my testing.
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bfbc2 extends Protocol
{
/**
* Array of packets we want to query.
*
* @type array
*/
protected $packets = [
self::PACKET_VERSION => "\x00\x00\x00\x00\x18\x00\x00\x00\x01\x00\x00\x00\x07\x00\x00\x00version\x00",
self::PACKET_STATUS => "\x00\x00\x00\x00\x1b\x00\x00\x00\x01\x00\x00\x00\x0a\x00\x00\x00serverInfo\x00",
self::PACKET_PLAYERS => "\x00\x00\x00\x00\x24\x00\x00\x00\x02\x00\x00\x00\x0b\x00\x00\x00listPlayers\x00\x03\x00\x00\x00\x61ll\x00",
];
/**
* Use the response flag to figure out what method to run
*
* @type array
*/
protected $responses = [
"processVersion",
"processDetails",
"processPlayers",
];
/**
* The transport mode for this protocol is TCP
*
* @type string
*/
protected $transport = self::TRANSPORT_TCP;
/**
* The query protocol used to make the call
*
* @type string
*/
protected $protocol = 'bfbc2';
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bfbc2';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield Bad Company 2";
/**
* The client join link
*
* @type string
*/
protected $join_link = null;
/**
* query_port = client_port + 29321
* 48888 = 19567 + 29321
*
* @type int
*/
protected $port_diff = 29321;
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'dedicated' => 'dedicated',
'hostname' => 'hostname',
'mapname' => 'map',
'maxplayers' => 'max_players',
'numplayers' => 'num_players',
'password' => 'password',
],
'player' => [
'name' => 'name',
'score' => 'score',
'ping' => 'ping',
],
'team' => [
'score' => 'tickets',
],
];
/**
* Process the response for the StarMade server
*
* @return array
* @throws \GameQ\Exception\Protocol
*/
public function processResponse()
{
//print_r($this->packets_response);
// Holds the results sent back
$results = [];
// Iterate over the response packets
// @todo: This protocol has no packet ordering, ids or anyway to identify which packet coming back belongs to which initial call.
foreach ($this->packets_response as $i => $packet) {
// Create a new buffer
$buffer = new Buffer($packet);
// Burn first 4 bytes, same across all packets
$buffer->skip(4);
// Get the packet length
$packetLength = $buffer->getLength();
// Check to make sure the expected length matches the real length
// Subtract 4 for the header burn
if ($packetLength != ($buffer->readInt32() - 4)) {
throw new Exception(__METHOD__ . " packet length does not match expected length!");
}
// We assume the packets are coming back in the same order as sent, this maybe incorrect...
$results = array_merge(
$results,
call_user_func_array([$this, $this->responses[$i]], [$buffer])
);
}
unset($buffer, $packetLength);
return $results;
}
/*
* Internal Methods
*/
/**
* Decode the buffer into a usable format
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function decode(Buffer $buffer)
{
$items = [];
// Get the number of words in this buffer
$itemCount = $buffer->readInt32();
// Loop over the number of items
for ($i = 0; $i < $itemCount; $i++) {
// Length of the string
$buffer->readInt32();
// Just read the string
$items[$i] = $buffer->readString();
}
return $items;
}
/**
* Process the server details
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processDetails(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
// Server is always dedicated
$result->add('dedicated', 1);
// These are the same no matter what mode the server is in
$result->add('hostname', $items[1]);
$result->add('num_players', (int)$items[2]);
$result->add('max_players', (int)$items[3]);
$result->add('gametype', $items[4]);
$result->add('map', $items[5]);
$result->add('roundsplayed', (int)$items[6]);
$result->add('roundstotal', (int)$items[7]);
$result->add('num_teams', (int)$items[8]);
// Set the current index
$index_current = 9;
// Pull the team count
$teamCount = $result->get('num_teams');
// Loop for the number of teams found, increment along the way
for ($id = 1; $id <= $teamCount; $id++, $index_current++) {
// Shows the tickets
$result->addTeam('tickets', $items[$index_current]);
// We add an id so we know which team this is
$result->addTeam('id', $id);
}
// Get and set the rest of the data points.
$result->add('targetscore', (int)$items[$index_current]);
$result->add('online', 1); // Forced true, shows accepting players
$result->add('ranked', (($items[$index_current + 2] == 'true') ? 1 : 0));
$result->add('punkbuster', (($items[$index_current + 3] == 'true') ? 1 : 0));
$result->add('password', (($items[$index_current + 4] == 'true') ? 1 : 0));
$result->add('uptime', (int)$items[$index_current + 5]);
$result->add('roundtime', (int)$items[$index_current + 6]);
$result->add('mod', $items[$index_current + 7]);
$result->add('ip_port', $items[$index_current + 9]);
$result->add('punkbuster_version', $items[$index_current + 10]);
$result->add('join_queue', (($items[$index_current + 11] == 'true') ? 1 : 0));
$result->add('region', $items[$index_current + 12]);
unset($items, $index_current, $teamCount, $buffer);
return $result->fetch();
}
/**
* Process the server version
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processVersion(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
$result->add('version', $items[2]);
unset($buffer, $items);
return $result->fetch();
}
/**
* Process the players
*
* @param \GameQ\Buffer $buffer
*
* @return array
*/
protected function processPlayers(Buffer $buffer)
{
// Decode into items
$items = $this->decode($buffer);
// Set the result to a new result instance
$result = new Result();
// Number of data points per player
$numTags = $items[1];
// Grab the tags for each player
$tags = array_slice($items, 2, $numTags);
// Get the player count
$playerCount = $items[$numTags + 2];
// Iterate over the index until we run out of players
for ($i = 0, $x = $numTags + 3; $i < $playerCount; $i++, $x += $numTags) {
// Loop over the player tags and extract the info for that tag
foreach ($tags as $index => $tag) {
$result->addPlayer($tag, $items[($x + $index)]);
}
}
return $result->fetch();
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Battlefield Hardline Protocol class
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Bfh extends Bf4
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'bfh';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Battlefield Hardline";
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Blackmesa Protocol Class
*
* @package GameQ\Protocols
* @author Jesse Lukas <eranio@g-one.org>
*/
class Blackmesa extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'blackmesa';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Black Mesa";
}

View file

@ -0,0 +1,50 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Brink
*
* @package GameQ\Protocols
*
* @author Wilson Jesus <>
*/
class Brink extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'brink';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Brink";
/**
* query_port = client_port + 1
*
* @type int
*/
protected $port_diff = 1;
}

View file

@ -0,0 +1,199 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Buffer;
use GameQ\Exception\Protocol as Exception;
use GameQ\Protocol;
use GameQ\Result;
use GameQ\Server;
use GameQ\Protocols\Http;
/**
* GTA Five M Protocol Class
*
* Server base can be found at https://fivem.net/
*
* Based on code found at https://github.com/LiquidObsidian/fivereborn-query
*
* @author Austin Bischoff <austin@codebeard.com>
*
* Adding FiveM Player List by
* @author Jesse Lukas <eranio@g-one.org>
*/
class Cfx extends Protocol
{
/**
* Array of packets we want to look up.
* Each key should correspond to a defined method in this or a parent class
*
* @type array
*/
protected $packets = [
self::PACKET_STATUS => "\xFF\xFF\xFF\xFFgetinfo xxx",
];
/**
* Use the response flag to figure out what method to run
*
* @type array
*/
protected $responses = [
"\xFF\xFF\xFF\xFFinfoResponse" => "processStatus",
];
/**
* The query protocol used to make the call
*
* @type string
*/
protected $protocol = 'cfx';
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'cfx';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "CitizenFX";
/**
* Holds the Player list so we can overwrite it back
*
* @var string
*/
protected $PlayerList = [];
/**
* Normalize settings for this protocol
*
* @type array
*/
protected $normalize = [
// General
'general' => [
// target => source
'gametype' => 'gametype',
'hostname' => 'hostname',
'mapname' => 'mapname',
'maxplayers' => 'sv_maxclients',
'mod' => 'gamename',
'numplayers' => 'clients',
'password' => 'privateClients',
],
];
/**
* Get FiveM players list using a sub query
*/
public function beforeSend(Server $server)
{
$GameQ = new \GameQ\GameQ();
$GameQ->addServer([
'type' => 'cfxplayers',
'host' => "$server->ip:$server->port_query",
]);
$results = $GameQ->process();
$this->PlayerList = isset($results[0]) && isset($results[0][0]) ? $results[0][0] : [];
}
/**
* Process the response
*
* @return array
* @throws \GameQ\Exception\Protocol
*/
public function processResponse()
{
// In case it comes back as multiple packets (it shouldn't)
$buffer = new Buffer(implode('', $this->packets_response));
// Figure out what packet response this is for
$response_type = $buffer->readString(PHP_EOL);
// Figure out which packet response this is
if (empty($response_type) || !array_key_exists($response_type, $this->responses)) {
throw new Exception(__METHOD__ . " response type '{$response_type}' is not valid");
}
// Offload the call
$results = call_user_func_array([$this, $this->responses[$response_type]], [$buffer]);
return $results;
}
/*
* Internal methods
*/
/**
* Handle processing the status response
*
* @param Buffer $buffer
*
* @return array
*/
protected function processStatus(Buffer $buffer)
{
// Set the result to a new result instance
$result = new Result();
// Lets peek and see if the data starts with a \
if ($buffer->lookAhead(1) == '\\') {
// Burn the first one
$buffer->skip(1);
}
// Explode the data
$data = explode('\\', $buffer->getBuffer());
// No longer needed
unset($buffer);
$itemCount = count($data);
// Now lets loop the array
for ($x = 0; $x < $itemCount; $x += 2) {
// Set some local vars
$key = $data[$x];
$val = $data[$x + 1];
if (in_array($key, ['challenge'])) {
continue; // skip
}
// Regular variable so just add the value.
$result->add($key, $val);
}
// Add result of sub http-protocol if available
if ($this->PlayerList) {
$result->add('players', $this->PlayerList);
}
return $result->fetch();
}
}

View file

@ -0,0 +1,110 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Exception\Protocol as Exception;
use GameQ\Protocols\Http;
/**
* GTA Five M Protocol Class
*
* Server base can be found at https://fivem.net/
*
* Based on code found at https://github.com/LiquidObsidian/fivereborn-query
*
* @author Austin Bischoff <austin@codebeard.com>
*
* Adding FiveM Player List by
* @author Jesse Lukas <eranio@g-one.org>
*/
class CFXPlayers extends Http
{
/**
* Holds the real ip so we can overwrite it back
*
* @var string
*/
protected $realIp = null;
/**
* Holds the real port so we can overwrite it back
*
* @var int
*/
protected $realPortQuery = null;
/**
* Packets to send
*
* @var array
*/
protected $packets = [
self::PACKET_STATUS => "GET /players.json HTTP/1.0\r\nAccept: */*\r\n\r\n", // Player List
];
/**
* The protocol being used
*
* @var string
*/
protected $protocol = 'cfxplayers';
/**
* String name of this protocol class
*
* @var string
*/
protected $name = 'cfxplayers';
/**
* Longer string name of this protocol class
*
* @var string
*/
protected $name_long = "cfxplayers";
/**
* Process the response
*
* @return array
* @throws Exception
*/
public function processResponse()
{
// Make sure we have any players
if (empty($this->packets_response)) {
return [];
}
// Implode and rip out the JSON
preg_match('/\{(.*)\}/ms', implode('', $this->packets_response), $matches);
// Return should be JSON, let's validate
if (!isset($matches[0]) || ($json = json_decode($matches[0], true)) === null) {
throw new Exception(__METHOD__ . " JSON response from Stationeers protocol is invalid.");
}
// Return json as it should already be well formed
return [
'players' => $json,
];
}
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Citadel Protocol Class
*
* @package GameQ\Protocols
* @author Jesse Lukas <eranio@g-one.org>
*/
class Citadel extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'citadel';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Citadel";
}

View file

@ -0,0 +1,43 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Call of Duty Protocol Class
*
* @package GameQ\Protocols
*
* @author Wilson Jesus <>
*/
class Cod extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'cod';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty";
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Call of Duty 2 Protocol Class
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Cod2 extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'cod2';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty 2";
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Call of Duty 4 Protocol Class
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Cod4 extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'cod4';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty 4";
}

View file

@ -0,0 +1,89 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
use GameQ\Buffer;
use GameQ\Result;
/**
* Call of Duty: Modern Warfare 2 Protocol Class
*
* @package GameQ\Protocols
* @author Wilson Jesus <>
*/
class Codmw2 extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'codmw2';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty: Modern Warfare 2";
protected function processPlayers(Buffer $buffer)
{
// Temporarily cache players in order to remove last
$players = [];
// Loop until we are out of data
while ($buffer->getLength()) {
// Make a new buffer with this block
$playerInfo = new Buffer($buffer->readString("\x0A"));
// Read player info
$player = [
'frags' => $playerInfo->readString("\x20"),
'ping' => $playerInfo->readString("\x20"),
];
// Skip first "
$playerInfo->skip(1);
// Add player name, encoded
$player['name'] = utf8_encode(trim(($playerInfo->readString('"'))));
// Add player
$players[] = $player;
}
// Remove last, empty player
array_pop($players);
// Set the result to a new result instance
$result = new Result();
// Add players
$result->add('players', $players);
// Add Playercount
$result->add('clients', count($players));
// Clear
unset($buffer, $players);
return $result->fetch();
}
}

View file

@ -0,0 +1,50 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Codmw3
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Codmw3 extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'codmw3';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty: Modern Warfare 3";
/**
* query_port = client_port + 2
*
* @type int
*/
protected $port_diff = 2;
}

View file

@ -0,0 +1,43 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Call of Duty United Offensive Class
*
* @package GameQ\Protocols
*
* @author Wilson Jesus <>
*/
class Coduo extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'coduo';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty: United Offensive";
}

View file

@ -0,0 +1,43 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Call of Duty World at War Class
*
* @package GameQ\Protocols
* @author naXe <naxeify@gmail.com>
* @author Austin Bischoff <austin@codebeard.com>
*/
class Codwaw extends Quake3
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'codwaw';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Call of Duty: World at War";
}

View file

@ -0,0 +1,42 @@
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Protocols;
/**
* Class Conanexiles
*
* @package GameQ\Protocols
* @author Austin Bischoff <austin@codebeard.com>
*/
class Conanexiles extends Source
{
/**
* String name of this protocol class
*
* @type string
*/
protected $name = 'conanexiles';
/**
* Longer string name of this protocol class
*
* @type string
*/
protected $name_long = "Conan Exiles";
}

Some files were not shown because too many files have changed in this diff Show more