No changes

This commit is contained in:
Frank Harris 2025-09-11 13:29:15 -04:00
parent 8680a02b13
commit b6b398f5bf
17374 changed files with 2475441 additions and 0 deletions

1
.deployed-at Normal file
View file

@ -0,0 +1 @@
2025-08-29 15:39:12 UTC

123
.github/copilot-instructions.md vendored Normal file
View file

@ -0,0 +1,123 @@
# Open Game Panel (OGP) ControlPanel
Open Game Panel is a PHP-based web application for managing game servers with Linux/Windows agents and Python documentation tools.
Always reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the info here.
## Working Effectively
- Bootstrap and test the repository:
- `sudo apt-get update && sudo apt-get install -y php mysql-server libxml-parser-perl libpath-class-perl libarchive-extract-perl libdbi-perl libdbd-mysql-perl libxml-simpleobject-perl libproc-daemon-perl liblinux-inotify2-perl libarchive-zip-perl pandoc texlive-xetex python3 python3-yaml`
- `sudo service mysql start`
- `sudo mysql --defaults-file=/etc/mysql/debian.cnf -e "CREATE DATABASE IF NOT EXISTS panel; CREATE USER IF NOT EXISTS 'localuser'@'localhost' IDENTIFIED BY 'testpass'; GRANT ALL PRIVILEGES ON panel.* TO 'localuser'@'localhost'; FLUSH PRIVILEGES;"`
- Edit `/home/runner/work/ControlPanel/ControlPanel/includes/config.inc.php` to set database password to `testpass`
- Test Python guide generation tools:
- `cd /home/runner/work/ControlPanel/ControlPanel && ./tools/generate_all_guides.sh` -- takes 3-10 seconds. NEVER CANCEL. Set timeout to 30+ seconds.
- `python3 tools/validate_guides.py` -- takes under 1 second
- Test PHP web application:
- `cd /home/runner/work/ControlPanel/ControlPanel && php -S localhost:8080 &`
- `curl -I http://localhost:8080` (will show 500 error due to missing database schema - this is expected)
- `pkill -f "php -S"` to stop server
- Test Perl agent syntax:
- `cd /home/runner/work/ControlPanel/ControlPanel/_agent-linux && perl -c ogp_agent.pl` -- should show "syntax OK"
## Validation
- Always test the Python guide generation workflow when making changes to tools/ directory
- ALWAYS run `./tools/generate_all_guides.sh` to validate guide generation changes
- Test PHP syntax with `php -l <file.php>` for any PHP file changes
- Test Perl agent syntax with `perl -c ogp_agent.pl` when modifying agent files
- The web application requires a complete database schema to run properly, but basic connectivity can be tested
## CRITICAL Build & Test Timing
- **Guide generation: 3-10 seconds** - NEVER CANCEL. Set timeout to 30+ seconds minimum
- **Guide validation: Under 1 second** - Set timeout to 15+ seconds
- **Package installation: 5-15 minutes** - NEVER CANCEL. Set timeout to 20+ minutes
- **PDF generation (with LaTeX): 2-5 seconds per document** - NEVER CANCEL
- **Database setup: Under 10 seconds** - Set timeout to 30+ seconds
## Common Tasks
The following are outputs from frequently run commands. Reference them instead of viewing, searching, or running bash commands to save time.
### Repository Structure
```
/home/runner/work/ControlPanel/ControlPanel/
├── index.php # Main web application entry point
├── includes/ # PHP includes and configuration
│ ├── config.inc.php # Database configuration
│ ├── database_mysqli.php # Database abstraction layer
│ └── helpers.php # Utility functions
├── modules/ # Web application modules
├── themes/ # UI themes
├── tools/ # Python guide generation tools
│ ├── generate_all_guides.sh # Main guide generation script
│ ├── generate_server_guides.py # Python guide generator
│ └── validate_guides.py # Guide validation script
├── _agent-linux/ # Linux agent (Perl)
│ ├── ogp_agent.pl # Main agent script
│ └── ogp_agent_run # Agent wrapper script
├── _agent-windows/ # Windows agent
├── data/games/ # YAML game definitions for guides
└── dist/pdfs/ # Generated PDF guides
```
### Dependencies Status
- **PHP 8.3.6**: Available, with MySQLi extension
- **MySQL 8.0**: Available, can be started with `sudo service mysql start`
- **Perl 5.38**: Available, with all required OGP modules installed
- **Python 3.12**: Available, with PyYAML installed
- **Pandoc + XeLaTeX**: Available, for PDF generation
### Guide Generation Workflow
```bash
# Complete workflow (3-10 seconds total)
cd /home/runner/work/ControlPanel/ControlPanel
./tools/generate_all_guides.sh
# Individual steps
python3 tools/generate_server_guides.py # Generate markdown + PDFs
python3 tools/validate_guides.py # Validate output
# Expected output structure:
# docs/games/<game-slug>/index.md # Markdown guides
# dist/pdfs/<game-slug>__Server_Admin_Guide_v1.pdf # PDF guides
# docs/games/_index.md # Index page
# dist/pdfs/manifest.json # Metadata manifest
```
### Agent Testing
```bash
# Test Perl agent syntax (agent requires special permissions to run)
cd /home/runner/work/ControlPanel/ControlPanel/_agent-linux
perl -c ogp_agent.pl
# Expected: "ogp_agent.pl syntax OK"
```
### Database Setup for Testing
```bash
# Basic database setup (already configured)
sudo service mysql start
mysql -u localuser -ptestpass -e "SHOW DATABASES;"
# Should show: information_schema, panel, performance_schema
```
### Web Application Testing
```bash
# Start development server (will show 500 errors without complete DB schema)
cd /home/runner/work/ControlPanel/ControlPanel
php -S localhost:8080 &
curl -I http://localhost:8080 # Test connectivity
pkill -f "php -S" # Stop server
```
## Key Projects in Codebase
1. **Web Panel** (`index.php`, `modules/`, `themes/`): PHP web application for game server management
2. **Linux Agent** (`_agent-linux/`): Perl-based agent for Linux game server management
3. **Windows Agent** (`_agent-windows/`): Windows version of server agent
4. **Guide Tools** (`tools/`): Python scripts for generating comprehensive server admin documentation
5. **Game Definitions** (`data/games/`): YAML files defining game server configurations for guide generation
## Important Notes
- The web application requires complete database schema initialization to run fully (beyond basic connectivity testing)
- Agents require special system permissions and users to run properly in production
- Guide generation tools work independently and can be tested without the web application
- PDF generation requires both pandoc and XeLaTeX (texlive-xetex package)
- All basic syntax checking and connectivity testing works in this environment
- Focus testing on the components that can be fully validated: guide tools, PHP syntax, Perl syntax, and basic connectivity

16
.gitignore vendored Normal file
View file

@ -0,0 +1,16 @@
*.log
*.tmp
cache/
tmp/
sessions/
*.tar
*.tar.gz
*.zip
*.bak
node_modules/
vendor/*/cache/
.env
.env.*
config.local.php
!_agent-linux/**
!_agent-windows/**

BIN
.google.html.swp Normal file

Binary file not shown.

3
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"git.ignoreLimitWarning": true
}

View file

@ -0,0 +1 @@
C00B1E58F75CE6808CC4795102B679F3B304AF55B1D7758CC960761B8417CAFA comodoca.com 626d7df153d26

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.

View file

@ -0,0 +1 @@
2025-08-29 15:39:12 UTC

View file

@ -0,0 +1,123 @@
name: Build Game PDFs
on:
workflow_dispatch:
inputs:
commit_pdfs:
description: 'Commit PDFs back to repository'
required: false
default: 'true'
type: boolean
push:
branches: [main]
paths:
- 'all_hostable_games_union.csv'
- 'scripts/build_pdfs.py'
- 'scripts/clean.py'
- 'scripts/quality_control.py'
- 'templates/game_guide.md'
- '.github/workflows/build-game-pdfs.yml'
jobs:
build-pdfs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.12'
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y pandoc wkhtmltopdf
- name: Install Python dependencies
run: |
pip install pandas PyYAML
- name: Clean previous output
run: |
python3 scripts/clean.py
- name: Generate all game guides and PDFs
run: |
python3 scripts/build_pdfs.py
- name: Run quality control validation
run: |
python3 scripts/quality_control.py
- name: Generate statistics
run: |
echo "## Build Statistics" >> $GITHUB_STEP_SUMMARY
echo "- **Markdown files:** $(find out/md -name '*.md' | wc -l)" >> $GITHUB_STEP_SUMMARY
echo "- **PDF files:** $(find out/pdfs -name '*.pdf' | wc -l)" >> $GITHUB_STEP_SUMMARY
echo "- **Total PDF size:** $(du -sh out/pdfs/ | cut -f1)" >> $GITHUB_STEP_SUMMARY
echo "- **Generated:** $(date)" >> $GITHUB_STEP_SUMMARY
# Check for quality issues
if [ -f out/pdfs/quality_report.json ]; then
ERRORS=$(jq -r '.total_errors' out/pdfs/quality_report.json)
WARNINGS=$(jq -r '.total_warnings' out/pdfs/quality_report.json)
echo "- **Quality:** $ERRORS errors, $WARNINGS warnings" >> $GITHUB_STEP_SUMMARY
if [ "$ERRORS" -gt "0" ]; then
echo "❌ Quality validation failed with $ERRORS errors" >> $GITHUB_STEP_SUMMARY
exit 1
else
echo "✅ Quality validation passed" >> $GITHUB_STEP_SUMMARY
fi
fi
- name: Upload PDF artifacts
uses: actions/upload-artifact@v4
with:
name: game-server-guides-pdfs
path: out/pdfs/
retention-days: 30
- name: Upload Markdown artifacts
uses: actions/upload-artifact@v4
with:
name: game-server-guides-markdown
path: out/md/
retention-days: 30
- name: Commit PDFs to repository
if: github.event_name == 'workflow_dispatch' && github.event.inputs.commit_pdfs == 'true' || github.event_name == 'push'
run: |
# Configure git
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
# Create docs/pdfs directory if it doesn't exist
mkdir -p docs/pdfs
# Copy PDFs to docs directory
cp out/pdfs/*.pdf docs/pdfs/ 2>/dev/null || true
cp out/pdfs/manifest.json docs/pdfs/ 2>/dev/null || true
cp out/pdfs/quality_report.json docs/pdfs/ 2>/dev/null || true
# Add and commit changes
git add docs/pdfs/
# Check if there are changes to commit
if ! git diff --staged --quiet; then
GAME_COUNT=$(find out/pdfs -name '*.pdf' | wc -l)
git commit -m "docs: regenerate exhaustive self-hosting PDFs for $GAME_COUNT games
- Generated $(date)
- Total PDFs: $GAME_COUNT
- Quality validated: $(jq -r '.total_errors' out/pdfs/quality_report.json 2>/dev/null || echo '0') errors
- All guides are hosting-agnostic and self-hosting focused"
git push
echo "✅ PDFs committed to repository" >> $GITHUB_STEP_SUMMARY
else
echo " No changes to commit" >> $GITHUB_STEP_SUMMARY
fi

22
ControlPanel/.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
*.log
*.tmp
cache/
tmp/
sessions/
*.tar
*.tar.gz
*.zip
*.bak
node_modules/
vendor/*/cache/
.env
.env.*
config.local.php
!_agent-linux/**
!_agent-windows/**
# PDF Generation temporary directories
out/
scripts/__pycache__/
test_generation.py
__pycache__/

Binary file not shown.

View file

@ -0,0 +1 @@
C00B1E58F75CE6808CC4795102B679F3B304AF55B1D7758CC960761B8417CAFA comodoca.com 626d7df153d26

339
ControlPanel/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.

View file

@ -0,0 +1,363 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* PHP implementation of XXTEA encryption algorithm.
*
* XXTEA is a secure and fast encryption algorithm, suitable for web
* development.
*
* PHP versions 4 and 5
*
* LICENSE: This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* @category Encryption
* @package Crypt_XXTEA
* @author Wudi Liu <wudicgi@gmail.com>
* @author Ma Bingyao <andot@ujn.edu.cn>
* @copyright 2005-2008 Coolcode.CN
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version CVS: $Id: XXTEA.php,v 1.3 2008/03/06 11:38:45 wudicgi Exp $
* @link http://pear.php.net/package/Crypt_XXTEA
*/
/**
* Needed for error handling
*/
require_once 'PEAR.php';
// {{{ constants
define('CRYPT_XXTEA_DELTA', 0x9E3779B9);
// }}}
/**
* The main class
*
* @category Encryption
* @package Crypt_XXTEA
* @author Wudi Liu <wudicgi@gmail.com>
* @author Ma Bingyao <andot@ujn.edu.cn>
* @copyright 2005-2008 Coolcode.CN
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: 0.9.0
* @link http://pear.php.net/package/Crypt_XXTEA
*/
class Crypt_XXTEA {
// {{{ properties
/**
* The long integer array of secret key
*
* @access private
*
* @var array
*/
var $_key;
// }}}
// {{{ setKey()
/**
* Sets the secret key
*
* The key must be non-empty, and not more than 16 characters or 4 long values
*
* @access public
*
* @param mixed $key the secret key (string or long integer array)
*
* @return bool true on success, PEAR_Error on failure
*/
function setKey($key) {
if (is_string($key)) {
$k = $this->_str2long($key, false);
} elseif (is_array($key)) {
$k = $key;
} else {
return PEAR::raiseError('The secret key must be a string or long integer array.');
}
if (count($k) > 4) {
return PEAR::raiseError('The secret key cannot be more than 16 characters or 4 long values.');
} elseif (count($k) == 0) {
return PEAR::raiseError('The secret key cannot be empty.');
} elseif (count($k) < 4) {
for ($i = count($k); $i < 4; $i++) {
$k[$i] = 0;
}
}
$this->_key = $k;
return true;
}
// }}}
// {{{ encrypt()
/**
* Encrypts a plain text
*
* As the XXTEA encryption algorithm is designed for encrypting and decrypting
* the long integer array type of data, there is not a standard that defines
* how to convert between long integer array and text or binary data for it.
* So this package provides the ability to encrypt and decrypt the long integer
* arrays directly to satisfy the requirement for working with other
* implementations. And at the same time, for convenience, it also provides
* the ability to process strings, which uses its own method to group the text
* into array.
*
* @access public
*
* @param mixed $plaintext the plain text (string or long integer array)
*
* @return mixed the cipher text as the same type as the parameter $plaintext
* on success, PEAR_Error on failure
*/
function encrypt($plaintext) {
if ($this->_key == null) {
return PEAR::raiseError('Secret key is undefined.');
}
if (is_string($plaintext)) {
return $this->_encryptString($plaintext);
} elseif (is_array($plaintext)) {
return $this->_encryptArray($plaintext);
} else {
return PEAR::raiseError('The plain text must be a string or long integer array.');
}
}
// }}}
// {{{ decrypt()
/**
* Decrypts a cipher text
*
* @access public
*
* @param mixed $chipertext the cipher text (string or long integer array)
*
* @return mixed the plain text as the same type as the parameter $chipertext
* on success, PEAR_Error on failure
*/
function decrypt($chipertext) {
if ($this->_key == null) {
return PEAR::raiseError('Secret key is undefined.');
}
if (is_string($chipertext)) {
return $this->_decryptString($chipertext);
} elseif (is_array($chipertext)) {
return $this->_decryptArray($chipertext);
} else {
return PEAR::raiseError('The chiper text must be a string or long integer array.');
}
}
// }}}
// {{{ _encryptString()
/**
* Encrypts a string
*
* @access private
*
* @param string $str the string to encrypt
*
* @return string the string type of the cipher text on success,
* PEAR_Error on failure
*/
function _encryptString($str) {
if ($str == '') {
return '';
}
$v = $this->_str2long($str, true);
$v = $this->_encryptArray($v);
return $this->_long2str($v, false);
}
// }}}
// {{{ _encryptArray()
/**
* Encrypts a long integer array
*
* @access private
*
* @param array $v the long integer array to encrypt
*
* @return array the array type of the cipher text on success,
* PEAR_Error on failure
*/
function _encryptArray($v) {
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$q = floor(6 + 52 / ($n + 1));
$sum = 0;
while (0 < $q--) {
$sum = $this->_int32($sum + CRYPT_XXTEA_DELTA);
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = $this->_int32((($z >> 5 & 0x07FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ $this->_int32(($sum ^ $y) + ($this->_key[$p & 3 ^ $e] ^ $z));
$z = $v[$p] = $this->_int32($v[$p] + $mx);
}
$y = $v[0];
$mx = $this->_int32((($z >> 5 & 0x07FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ $this->_int32(($sum ^ $y) + ($this->_key[$p & 3 ^ $e] ^ $z));
$z = $v[$n] = $this->_int32($v[$n] + $mx);
}
return $v;
}
// }}}
// {{{ _decryptString()
/**
* Decrypts a string
*
* @access private
*
* @param string $str the string to decrypt
*
* @return string the string type of the plain text on success,
* PEAR_Error on failure
*/
function _decryptString($str) {
if ($str == '') {
return '';
}
$v = $this->_str2long($str, false);
$v = $this->_decryptArray($v);
return $this->_long2str($v, true);
}
// }}}
// {{{ _encryptArray()
/**
* Decrypts a long integer array
*
* @access private
*
* @param array $v the long integer array to decrypt
*
* @return array the array type of the plain text on success,
* PEAR_Error on failure
*/
function _decryptArray($v) {
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$q = floor(6 + 52 / ($n + 1));
$sum = $this->_int32($q * CRYPT_XXTEA_DELTA);
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = $this->_int32((($z >> 5 & 0x07FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ $this->_int32(($sum ^ $y) + ($this->_key[$p & 3 ^ $e] ^ $z));
$y = $v[$p] = $this->_int32($v[$p] - $mx);
}
$z = $v[$n];
$mx = $this->_int32((($z >> 5 & 0x07FFFFFF) ^ $y << 2) + (($y >> 3 & 0x1FFFFFFF) ^ $z << 4)) ^ $this->_int32(($sum ^ $y) + ($this->_key[$p & 3 ^ $e] ^ $z));
$y = $v[0] = $this->_int32($v[0] - $mx);
$sum = $this->_int32($sum - CRYPT_XXTEA_DELTA);
}
return $v;
}
// }}}
// {{{ _long2str()
/**
* Converts long integer array to string
*
* @access private
*
* @param array $v the long integer array
* @param bool $w whether the given array contains the length of
* original plain text
*
* @return string the string
*/
function _long2str($v, $w) {
$len = count($v);
$s = '';
for ($i = 0; $i < $len; $i++) {
$s .= pack('V', $v[$i]);
}
if ($w) {
return substr($s, 0, $v[$len - 1]);
} else {
return $s;
}
}
// }}}
// {{{ _str2long()
/**
* Converts string to long integer array
*
* @access private
*
* @param string $s the string
* @param bool $w whether to append the length of string to array
*
* @return string the long integer array
*/
function _str2long($s, $w) {
$v = array_values(unpack('V*', $s.str_repeat("\0", (4-strlen($s)%4)&3)));
if ($w) {
$v[] = strlen($s);
}
return $v;
}
// }}}
// {{{ _int32()
/**
* Corrects long integer value
*
* Because a number beyond the bounds of the integer type will be automatically
* interpreted as a float, the simulation of integer overflow is needed.
*
* @access private
*
* @param int $n the integer
*
* @return int the correct integer
*/
function _int32($n) {
while ($n >= 2147483648) $n -= 4294967296;
while ($n <= -2147483649) $n += 4294967296;
return (int)$n;
}
// }}}
}
?>

255
ControlPanel/FAQ.RSS Normal file
View file

@ -0,0 +1,255 @@
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Game Server FAQ</title>
<link>https://gameservers.world/faq</link>
<description>Comprehensive game server configuration and troubleshooting guide</description>
<dc:language>en</dc:language>
<pubDate>Tue, 02 Sep 2025 21:29:01 GMT</pubDate>
<item>
<title>Config Files</title>
<category>7 Days to Die</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- serverconfig.xml — Main server configuration: world name, ports, passwords, game settings. Paths: ./&lt;br&gt;&lt;br&gt;- Data/Worlds/&amp;lt;worldname&amp;gt;/ — World save data. Paths: ./Data/Worlds/&lt;br&gt;&lt;br&gt;- logs/output_log.txt — Server log file. Paths: ./logs/&lt;br&gt;&lt;br&gt;- Mods/ — Server mods directory. Paths: ./Mods/&lt;br&gt;&lt;br&gt;- Data/Config/ — Game configuration files. Paths: ./Data/Config/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>7 Days to Die</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;7DaysToDieServer.exe -logfile logs/output_log.txt -configfile=serverconfig.xml -dedicated&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 26900)&lt;br&gt;&lt;br&gt;- Web Interface (TCP) — configurable (default 8080)&lt;br&gt;&lt;br&gt;- Web Interface (TCP) — configurable (default 8081)&lt;br&gt;&lt;br&gt;- Telnet (TCP) — configurable (default 8082)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-logfile — Log file path. Type: path, Default: logs/output_log.txt&lt;br&gt;&lt;br&gt;-configfile — Server configuration file. Type: path, Default: serverconfig.xml&lt;br&gt;&lt;br&gt;-dedicated — Run as dedicated server. Type: bool, Default: &lt;br&gt;&lt;br&gt;-quit — Quit after loading (for testing). Type: bool, Default: &lt;br&gt;&lt;br&gt;-batchmode — Run in batch mode. Type: bool, Default: &lt;br&gt;&lt;br&gt;-nographics — Run without graphics. Type: bool, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>7 Days to Die</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not starting — verify serverconfig.xml syntax. Check file permissions. Review output_log.txt for errors.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — open UDP game port and TCP web ports. Verify password settings. Check Steam authentication.&lt;br&gt;&lt;br&gt;- World won&#x27;t load — verify world name in serverconfig.xml. Check save file integrity. Restore from backup if corrupted.&lt;br&gt;&lt;br&gt;- Performance issues — reduce MaxChunkAge and SaveDataLimit. Monitor RAM usage. Adjust MaxSpawnedZombies.&lt;br&gt;&lt;br&gt;- Telnet/web interface not working — verify ports are open. Check ControlPanelEnabled and TelnetEnabled settings.&lt;br&gt;&lt;br&gt;- Memory leaks — restart server regularly. Monitor for large save files. Clean up old backups.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Ark: Survival Evolved</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- ShooterGame/Saved/Config/WindowsServer/GameUserSettings.ini — Main server settings: rates, multipliers, PvP settings. Paths: ShooterGame/Saved/Config/WindowsServer/&lt;br&gt;&lt;br&gt;- ShooterGame/Saved/Config/WindowsServer/Game.ini — Advanced game configuration and overrides. Paths: ShooterGame/Saved/Config/WindowsServer/&lt;br&gt;&lt;br&gt;- ShooterGame/Saved/SavedArks/ — World save files. Paths: ShooterGame/Saved/SavedArks/&lt;br&gt;&lt;br&gt;- ShooterGame/Content/Mods/ — Downloaded workshop mods. Paths: ShooterGame/Content/Mods/&lt;br&gt;&lt;br&gt;- ShooterGame/Binaries/Win64/BattlEye/BEServer_x64.cfg — BattlEye configuration. Paths: ShooterGame/Binaries/Win64/BattlEye/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Ark: Survival Evolved</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;ShooterGameServer.exe TheIsland?listen?SessionName=MyServer?ServerPassword=mypass?ServerAdminPassword=adminpass?Port=7777?QueryPort=27015?MaxPlayers=20&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 7777)&lt;br&gt;&lt;br&gt;- Raw UDP Port (UDP) — GP+1 (default 7778)&lt;br&gt;&lt;br&gt;- Query Port (UDP) — configurable (default 27015)&lt;br&gt;&lt;br&gt;- RCON Port (TCP) — configurable (default 32330)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;TheIsland — Map name (TheIsland, Ragnarok, TheCenter, etc.). Type: string, Default: TheIsland&lt;br&gt;&lt;br&gt;?listen — Enable server listening mode. Type: bool, Default: &lt;br&gt;&lt;br&gt;?SessionName — Server name in browser. Type: string, Default: MyServer&lt;br&gt;&lt;br&gt;?ServerPassword — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;?ServerAdminPassword — Admin password. Type: string, Default: &lt;br&gt;&lt;br&gt;?Port — Game port. Type: int, Default: 7777&lt;br&gt;&lt;br&gt;?QueryPort — Steam query port. Type: int, Default: 27015&lt;br&gt;&lt;br&gt;?RCONPort — RCON port. Type: int, Default: 32330&lt;br&gt;&lt;br&gt;?MaxPlayers — Maximum players. Type: int, Default: 20&lt;br&gt;&lt;br&gt;?DifficultyOffset — Difficulty multiplier. Type: float, Default: 0.2&lt;br&gt;&lt;br&gt;?ServerPVE — PvE mode. Type: bool, Default: false&lt;br&gt;&lt;br&gt;?AllowFlyerCarryPvE — Allow flyer carry in PvE. Type: bool, Default: false&lt;br&gt;&lt;br&gt;-automanagedmods — Auto-manage workshop mods. Type: bool, Default: &lt;br&gt;&lt;br&gt;-mods — Workshop mod IDs (comma separated). Type: string, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Ark: Survival Evolved</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible — open UDP 7777, 7778 and query port. Verify ?SessionName parameter. Check Steam server list.&lt;br&gt;&lt;br&gt;- Mods not downloading — use -automanagedmods flag. Verify workshop mod IDs in -mods parameter. Check Steam Workshop connectivity.&lt;br&gt;&lt;br&gt;- Save corruption — backup SavedArks folder regularly. Monitor disk space. Avoid force-stopping during saves.&lt;br&gt;&lt;br&gt;- Performance issues — reduce ?MaxPlayers and difficulty settings. Monitor RAM usage (8GB+ recommended). Optimize GameUserSettings.ini rates.&lt;br&gt;&lt;br&gt;- Players timing out — adjust network settings in GameUserSettings.ini. Check server CPU usage and network stability.&lt;br&gt;&lt;br&gt;- BattlEye kicks — update BattlEye. Configure whitelist properly. Check for mod compatibility issues.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Ark: Survival Evolved</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop mods: -mods=ID1,ID2,ID3&lt;br&gt;&lt;br&gt;- Auto-management: -automanagedmods (recommended)&lt;br&gt;&lt;br&gt;- Mod download path: ShooterGame/Content/Mods/&lt;br&gt;&lt;br&gt;- Manual installation: copy mod files to Content/Mods/&lt;br&gt;&lt;br&gt;- Mod updates: handled automatically with -automanagedmods&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Arma 3</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- server.cfg — Main server configuration: hostname, password, missions, admin settings. Paths: ./server.cfg&lt;br&gt;&lt;br&gt;- basic.cfg — Basic network and performance settings. Paths: ./basic.cfg&lt;br&gt;&lt;br&gt;- &amp;lt;profiles&amp;gt;/Users/&amp;lt;name&amp;gt;/&amp;lt;name&amp;gt;.Arma3Profile — Server profile with difficulty settings. Paths: &amp;lt;profiles&amp;gt;/Users/&amp;lt;name&amp;gt;/&lt;br&gt;&lt;br&gt;- &amp;lt;profiles&amp;gt;/arma3server_*.rpt — Server log files. Paths: &amp;lt;profiles&amp;gt;/&lt;br&gt;&lt;br&gt;- mpmissions/*.pbo — Multiplayer mission files. Paths: ./mpmissions/&lt;br&gt;&lt;br&gt;- keys/*.bikey — Mod signature keys. Paths: ./keys/&lt;br&gt;&lt;br&gt;- BattlEye/BEServer_x64.cfg — BattlEye configuration. Paths: ./BattlEye/&lt;br&gt;&lt;br&gt;- @ModName/addons/*.pbo — Mod content files. Paths: @ModName/addons/&lt;br&gt;&lt;br&gt;- @ModName/keys/*.bikey — Mod signature keys. Paths: @ModName/keys/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Arma 3</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;arma3server_x64.exe -ip=0.0.0.0 -port=2302 -config=server.cfg -cfg=basic.cfg -profiles=profiles -name=server -serverMod=&quot;@ACE;@CBA_A3&quot; -mod=&quot;&quot; -world=empty -autoinit&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 2302)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 2303)&lt;br&gt;&lt;br&gt;- Steam master (UDP) — GP+2 (default 2304)&lt;br&gt;&lt;br&gt;- BattlEye RCon (TCP) — configurable (often GP+4) (default 2306)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-ip — Bind address. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;-port — Base game UDP port. Type: int, Default: 2302&lt;br&gt;&lt;br&gt;-config — Server configuration file. Type: path, Default: server.cfg&lt;br&gt;&lt;br&gt;-cfg — Basic configuration file. Type: path, Default: basic.cfg&lt;br&gt;&lt;br&gt;-profiles — Profile directory. Type: path, Default: profiles&lt;br&gt;&lt;br&gt;-name — Profile name. Type: string, Default: server&lt;br&gt;&lt;br&gt;-serverMod — Server-side mods (semicolon separated). Type: string, Default: &lt;br&gt;&lt;br&gt;-mod — Client mods (semicolon separated). Type: string, Default: &lt;br&gt;&lt;br&gt;-world — World to preload (use &#x27;empty&#x27; for faster start). Type: string, Default: &lt;br&gt;&lt;br&gt;-autoinit — Auto-initialize server. Type: bool, Default: &lt;br&gt;&lt;br&gt;-loadMissionToMemory — Load mission into memory. Type: bool, Default: &lt;br&gt;&lt;br&gt;-noSound — Disable sound. Type: bool, Default: &lt;br&gt;&lt;br&gt;-malloc — Memory allocator DLL. Type: path, Default: &lt;br&gt;&lt;br&gt;-maxMem — Maximum memory in MB. Type: int, Default: auto&lt;br&gt;&lt;br&gt;-cpuCount — CPU core count hint. Type: int, Default: auto&lt;br&gt;&lt;br&gt;-exThreads — Extra threads (typical 3-7). Type: int, Default: auto&lt;br&gt;&lt;br&gt;-enableHT — Enable hyper-threading. Type: bool, Default: &lt;br&gt;&lt;br&gt;-hugepages — Enable huge pages. Type: bool, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Arma 3</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible — open UDP 2302, 2303, 2304. Set reportingIP in server.cfg. Check Windows Firewall and router NAT settings.&lt;br&gt;&lt;br&gt;- Mods not loading — verify mod paths in -serverMod/-mod. Check for missing dependencies. Ensure .bikey files match in keys/ folder.&lt;br&gt;&lt;br&gt;- BattlEye kicks players — update BattlEye files. Check BEServer_x64.cfg for correct settings. Verify signature checks are properly configured.&lt;br&gt;&lt;br&gt;- Performance issues — use -malloc=system or tbbmalloc_bi_x64.dll. Adjust -exThreads (try 3-7). Reduce viewDistance and AI count in missions.&lt;br&gt;&lt;br&gt;- Memory crashes — increase -maxMem setting. Use 64-bit server executable. Monitor RAM usage and reduce large mods if necessary.&lt;br&gt;&lt;br&gt;- Mission won&#x27;t load — verify .pbo files in mpmissions/. Check requiredAddons in mission.sqm. Test mission in editor first.&lt;br&gt;&lt;br&gt;- Workshop sync issues — ensure Steam Workshop integration is configured. Check mod compatibility between server and client versions.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Arma 3</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop content path: !Workshop (Steam Workshop integration)&lt;br&gt;&lt;br&gt;- Server-side workshop loading: -serverMod=&quot;!Workshop&quot;&lt;br&gt;&lt;br&gt;- Client workshop content: -mod=&quot;!Workshop&quot;&lt;br&gt;&lt;br&gt;- Workshop mod format: @workshopID or !Workshop&lt;br&gt;&lt;br&gt;- Automatic updates: handled by Steam integration&lt;br&gt;&lt;br&gt;- Cache location: Steam/steamapps/workshop/content/107410/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Arma2 Operation Arrowhead</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- server.cfg — Main server rules: hostname, password, passwordAdmin, maxPlayers, motd, voteMissionPlayers, voteThreshold, verifySignatures, equalModRequired, kickDuplicate, persistent, reportingIP, logFile, mission rotation. Paths: ./server.cfg, &amp;lt;root&amp;gt;/server.cfg&lt;br&gt;&lt;br&gt;- basic.cfg — Network &amp; bandwidth tuning: MinBandwidth, MaxBandwidth, MaxMsgSend, MinErrorToSend, MinErrorToSendNear, MaxSizeGuaranteed, MaxSizeNonGuaranteed, WindowSize, WindowCargoSize, MaxCustomFileSize, adapter, 3D_Performance, terrainGrid, viewDistance. Paths: ./basic.cfg&lt;br&gt;&lt;br&gt;- Users/&amp;lt;name&amp;gt;/&amp;lt;name&amp;gt;.Arma2OAProfile — Difficulty &amp; preferences profile. Paths: &amp;lt;profiles&amp;gt;/Users/&amp;lt;name&amp;gt;/&lt;br&gt;&lt;br&gt;- Users/&amp;lt;name&amp;gt;/&amp;lt;name&amp;gt;.vars.Arma2OAProfile — Profile variables. Paths: &amp;lt;profiles&amp;gt;/Users/&amp;lt;name&amp;gt;/&lt;br&gt;&lt;br&gt;- arma2oaserver.RPT — Runtime log and error messages. Paths: &amp;lt;profiles&amp;gt;/&lt;br&gt;&lt;br&gt;- mpmissions/*.pbo — Mission files (e.g., co@xx_example.Chernarus.pbo, DayZ_Epoch_11.Chernarus.pbo). Paths: ./mpmissions/&lt;br&gt;&lt;br&gt;- keys/*.bikey — Signature keys for allowed mods (must match client .bisign). Paths: ./keys/&lt;br&gt;&lt;br&gt;- BattlEye/BEServer.cfg — RConPassword, RConPort (TCP), optional RConIP. Paths: ./BattlEye/&lt;br&gt;&lt;br&gt;- BattlEye/bans.txt — Bans list. Paths: ./BattlEye/&lt;br&gt;&lt;br&gt;- BattlEye/*.txt — Filters: scripts.txt, createvehicle.txt, remoteexec.txt, publicvariable.txt, setvariable.txt, addweaponcargo.txt. Paths: ./BattlEye/&lt;br&gt;&lt;br&gt;- @DayZ_Epoch_Server/addons/dayz_server.pbo — DayZ Epoch server logic. Paths: @DayZ_Epoch_Server/addons/&lt;br&gt;&lt;br&gt;- instance_&amp;lt;ID&amp;gt;_&amp;lt;Map&amp;gt;/config.cfg — DayZ instance config: host, port, names, passwords. Paths: ./&lt;br&gt;&lt;br&gt;- instance_&amp;lt;ID&amp;gt;_&amp;lt;Map&amp;gt;/HiveExt.ini — MySQL connection, hive mode, time control. Paths: ./&lt;br&gt;&lt;br&gt;- BEC/Config/Config.cfg — BEC general configuration. Paths: BEC/Config/&lt;br&gt;&lt;br&gt;- BEC/Config/Scheduler.xml — BEC restarts/messages scheduler. Paths: BEC/Config/&lt;br&gt;&lt;br&gt;- BEC/Config/Admins.xml — BEC admin definitions. Paths: BEC/Config/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Arma2 Operation Arrowhead</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;arma2oaserver.exe -ip=0.0.0.0 -port=2302 -config=server.cfg -cfg=basic.cfg -profiles=profiles -name=server -world=empty -mod=&quot;@CBA&quot; -nosplash -noPause&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 2302)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 2303)&lt;br&gt;&lt;br&gt;- Master/aux (UDP) — GP+2 (default 2304)&lt;br&gt;&lt;br&gt;- Aux/voice (UDP) — GP+3 (default 2305)&lt;br&gt;&lt;br&gt;- BattlEye RCon (TCP) — configurable (often GP+4) (default 2306)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-ip — Bind address. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;-port — Base game UDP port. Type: int, Default: 2302&lt;br&gt;&lt;br&gt;-config — Server rules/missions config file. Type: path, Default: server.cfg&lt;br&gt;&lt;br&gt;-cfg — Network &amp; bandwidth config file. Type: path, Default: basic.cfg&lt;br&gt;&lt;br&gt;-profiles — Root for Users, RPT, logs, ranking. Type: path, Default: profiles&lt;br&gt;&lt;br&gt;-name — Profile folder name under Users. Type: string, Default: server&lt;br&gt;&lt;br&gt;-mod — Mod load order (semicolon separated). Type: string, Default: &lt;br&gt;&lt;br&gt;-world — Preload world (use &#x27;empty&#x27; for faster start). Type: string, Default: &lt;br&gt;&lt;br&gt;-nosplash — Skip splash screens. Type: bool, Default: &lt;br&gt;&lt;br&gt;-noPause — Prevent pause when window loses focus. Type: bool, Default: &lt;br&gt;&lt;br&gt;-par — Read additional parameters from text file. Type: path, Default: &lt;br&gt;&lt;br&gt;-cpuCount — Hint CPU core count. Type: int, Default: auto&lt;br&gt;&lt;br&gt;-exThreads — Extra worker threads (I/O/geometry), 0=auto, typical 3-7. Type: int, Default: auto&lt;br&gt;&lt;br&gt;-maxMem — Cap process RAM usage in MB. Type: int, Default: auto&lt;br&gt;&lt;br&gt;-malloc — Custom memory allocator DLL. Type: path, Default: &lt;br&gt;&lt;br&gt;-winxp — Legacy thread model for old OS. Type: bool, Default: &lt;br&gt;&lt;br&gt;-noLogs — Reduce logging (not recommended). Type: bool, Default: &lt;br&gt;&lt;br&gt;-netlog — Produce legacy network log (debug, impacts perf). Type: bool, Default: &lt;br&gt;&lt;br&gt;-showScriptErrors — Print SQF script errors. Type: bool, Default: &lt;br&gt;&lt;br&gt;-ranking — Write MP ranking/stats file in profiles. Type: path, Default: &lt;br&gt;&lt;br&gt;-pid — Write PID to file for watchdogs. Type: path, Default: &lt;br&gt;&lt;br&gt;-bepath — Explicit BattlEye folder. Type: path, Default: BattlEye&lt;br&gt;&lt;br&gt;-checkSignatures — Enforce signature checks via CLI. Type: bool, Default: &lt;br&gt;&lt;br&gt;-beta — Load OA beta build paths. Type: path, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Arma2 Operation Arrowhead</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Not visible in server browser — open UDP GP, GP+1, GP+2, GP+3 on firewall/NAT. Set reportingIP in server.cfg. Verify ISP or host does not block UDP. Check arma2oaserver.RPT for errors.&lt;br&gt;&lt;br&gt;- BattlEye RCon cannot connect — check BattlEye/BEServer.cfg for RConPassword and RConPort, open that TCP port, and verify no extra BOM/whitespace in the file.&lt;br&gt;&lt;br&gt;- Players get &#x27;Signature check failed&#x27; — put matching .bikey files in keys/. Ensure clients load the same mod versions. Set verifySignatures=2 in server.cfg.&lt;br&gt;&lt;br&gt;- DayZ/Epoch database errors — validate HiveExt.ini (host, db, user, pass). Confirm MySQL reachability and firewall. Check arma2oaserver.RPT and HiveExt.log for exact error lines.&lt;br&gt;&lt;br&gt;- High desync / rubber-banding — tune basic.cfg: MaxMsgSend, MinErrorToSend, MinErrorToSendNear, MaxSizeGuaranteed/NonGuaranteed. Reduce AI count and viewDistance in missions. Avoid -noLogs so you have RPTs.&lt;br&gt;&lt;br&gt;- Server crashes or hangs on boot — remove recently added mods, start with only @CBA. Check missing dependencies in RPT. Verify adequate disk space and that the -mod order is correct.&lt;br&gt;&lt;br&gt;- Players stuck on &#x27;Waiting for host&#x27; — mismatch between mission addons and server mods. Repack mission PBO with correct requiredAddons, confirm signatures, and clear client cache.&lt;br&gt;&lt;br&gt;- Mod signature mismatch — ensure .bikey in keys/ matches the .bisign in mod files. Re-download mod if corrupted. Check mod version alignment between server and clients.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Counter-Strike: Global Offensive</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- server.cfg — Main server configuration: hostname, rcon_password, sv_password, mp_timelimit, mp_roundtime, mp_maxrounds, sv_cheats, etc.. Paths: csgo/cfg/server.cfg&lt;br&gt;&lt;br&gt;- autoexec.cfg — Server autoexec configuration executed on startup. Paths: csgo/cfg/autoexec.cfg&lt;br&gt;&lt;br&gt;- gamemode_casual.cfg — Casual game mode settings. Paths: csgo/cfg/gamemode_casual.cfg&lt;br&gt;&lt;br&gt;- gamemode_competitive.cfg — Competitive game mode settings. Paths: csgo/cfg/gamemode_competitive.cfg&lt;br&gt;&lt;br&gt;- gamemode_armsrace.cfg — Arms Race game mode settings. Paths: csgo/cfg/gamemode_armsrace.cfg&lt;br&gt;&lt;br&gt;- gamemode_demolition.cfg — Demolition game mode settings. Paths: csgo/cfg/gamemode_demolition.cfg&lt;br&gt;&lt;br&gt;- gamemode_deathmatch.cfg — Deathmatch game mode settings. Paths: csgo/cfg/gamemode_deathmatch.cfg&lt;br&gt;&lt;br&gt;- maplist.txt — Available maps list. Paths: csgo/maplist.txt&lt;br&gt;&lt;br&gt;- mapcycle.txt — Map rotation cycle. Paths: csgo/mapcycle.txt&lt;br&gt;&lt;br&gt;- gamemodes.txt — Game modes configuration. Paths: csgo/gamemodes.txt&lt;br&gt;&lt;br&gt;- admins_simple.ini — SourceMod admin definitions. Paths: csgo/addons/sourcemod/configs/admins_simple.ini&lt;br&gt;&lt;br&gt;- databases.cfg — SourceMod database connections. Paths: csgo/addons/sourcemod/configs/databases.cfg&lt;br&gt;&lt;br&gt;- core.cfg — SourceMod core settings. Paths: csgo/addons/sourcemod/configs/core.cfg&lt;br&gt;&lt;br&gt;- sourcemod.cfg — SourceMod plugin settings. Paths: csgo/cfg/sourcemod/sourcemod.cfg&lt;br&gt;&lt;br&gt;- metamod.vdf — MetaMod:Source configuration. Paths: csgo/addons/metamod.vdf&lt;br&gt;&lt;br&gt;- banned_user.cfg — Banned users list. Paths: csgo/cfg/banned_user.cfg&lt;br&gt;&lt;br&gt;- banned_ip.cfg — Banned IP addresses. Paths: csgo/cfg/banned_ip.cfg&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Counter-Strike: Global Offensive</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;srcds.exe -game csgo -console -usercon +game_type 0 +game_mode 1 +mapgroup mg_active +map de_dust2 -port 27015 +ip 0.0.0.0 -maxplayers_override 16&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 27015)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 27016)&lt;br&gt;&lt;br&gt;- SourceTV (UDP) — GP+5 (default 27020)&lt;br&gt;&lt;br&gt;- RCON (TCP) — GP (same as game port) (default 27015)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-game — Game directory name. Type: string, Default: csgo&lt;br&gt;&lt;br&gt;-console — Enable console output. Type: bool, Default: &lt;br&gt;&lt;br&gt;-usercon — Enable user console. Type: bool, Default: &lt;br&gt;&lt;br&gt;-port — Game port (UDP). Type: int, Default: 27015&lt;br&gt;&lt;br&gt;+ip — Bind IP address. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;-maxplayers_override — Max players (overrides map limit). Type: int, Default: 16&lt;br&gt;&lt;br&gt;+map — Starting map. Type: string, Default: de_dust2&lt;br&gt;&lt;br&gt;+mapgroup — Map group for rotation. Type: string, Default: mg_active&lt;br&gt;&lt;br&gt;+game_type — Game type (0=Classic Casual/Competitive). Type: int, Default: 0&lt;br&gt;&lt;br&gt;+game_mode — Game mode (0=Casual, 1=Competitive). Type: int, Default: 1&lt;br&gt;&lt;br&gt;-tickrate — Server tickrate (64 or 128). Type: int, Default: 64&lt;br&gt;&lt;br&gt;-threads — Number of worker threads. Type: int, Default: auto&lt;br&gt;&lt;br&gt;+sv_setsteamaccount — Steam Game Server Login Token (GSLT). Type: string, Default: &lt;br&gt;&lt;br&gt;+rcon_password — RCON password. Type: string, Default: &lt;br&gt;&lt;br&gt;+hostname — Server name. Type: string, Default: &lt;br&gt;&lt;br&gt;+sv_password — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;-insecure — Disable VAC (for testing only). Type: bool, Default: &lt;br&gt;&lt;br&gt;-nobots — Disable bots. Type: bool, Default: &lt;br&gt;&lt;br&gt;+tv_enable — Enable SourceTV. Type: int, Default: 1&lt;br&gt;&lt;br&gt;+tv_port — SourceTV port. Type: int, Default: 27020&lt;br&gt;&lt;br&gt;+sv_lan — LAN mode (0=Internet, 1=LAN). Type: int, Default: 0&lt;br&gt;&lt;br&gt;-authkey — Steam Web API key for workshop. Type: string, Default: &lt;br&gt;&lt;br&gt;+host_workshop_collection — Workshop collection ID. Type: string, Default: &lt;br&gt;&lt;br&gt;+workshop_start_map — Workshop map ID to start with. Type: string, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Counter-Strike: Global Offensive</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible in browser — open UDP 27015 (game) and 27016 (query) ports. Set +sv_lan 0. Verify Steam Game Server Login Token (+sv_setsteamaccount) is valid and not banned.&lt;br&gt;&lt;br&gt;- VAC authentication error — ensure server has valid GSLT. Remove -insecure flag. Check VAC status at steamstat.us. Restart Steam service if needed.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect with &#x27;Server is not responding&#x27; — check firewall allows UDP 27015. Verify +ip setting matches server&#x27;s public IP. Test with sv_lan 1 for LAN testing.&lt;br&gt;&lt;br&gt;- RCON connection refused — ensure rcon_password is set in server.cfg. Open TCP 27015 (or custom rcon_password port). Check for firewall blocking TCP connections.&lt;br&gt;&lt;br&gt;- Workshop maps won&#x27;t download — verify -authkey is valid Steam Web API key. Check +host_workshop_collection ID exists and is public. Ensure adequate disk space.&lt;br&gt;&lt;br&gt;- High latency/lag issues — reduce server fps_max if CPU limited. Check network bandwidth with net_graph. Consider lowering tickrate from 128 to 64. Monitor sv output for performance warnings.&lt;br&gt;&lt;br&gt;- SourceMod plugins not loading — verify metamod.vdf exists and points to correct MetaMod binary. Check addons/sourcemod/logs/errors_*.log for specific plugin errors.&lt;br&gt;&lt;br&gt;- Bots filling server — set bot_quota 0 in server.cfg. Use mp_autoteambalance 0 and mp_limitteams 0 to prevent auto-balancing with bots.&lt;br&gt;&lt;br&gt;- Map cycle not working — verify mapcycle.txt has correct map names. Use mp_mapcycle_empty_waittime to control map change timing. Check for workshop map format (workshop/mapid).&lt;br&gt;&lt;br&gt;- Memory leaks or crashes — update to latest srcds version. Check addons/sourcemod/logs/errors_*.log for plugin issues. Monitor RAM usage and set appropriate -maxplayers_override.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Counter-Strike: Global Offensive</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop content stored in: csgo/maps/workshop/&lt;br&gt;&lt;br&gt;- Collection setup: +host_workshop_collection COLLECTION_ID&lt;br&gt;&lt;br&gt;- Start with workshop map: +workshop_start_map MAP_ID&lt;br&gt;&lt;br&gt;- API key required: -authkey YOUR_STEAM_WEB_API_KEY&lt;br&gt;&lt;br&gt;- Map format in mapcycle: workshop/123456789&lt;br&gt;&lt;br&gt;- Auto-update: workshop content updates on map change&lt;br&gt;&lt;br&gt;- Cache location: steamcmd/steamapps/workshop/content/730/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>DayZ</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- serverDZ.cfg — Main server configuration: hostname, password, maxPlayers, missions. Paths: ./&lt;br&gt;&lt;br&gt;- &amp;lt;profiles&amp;gt;/DayZServer_x64_*.log — Server log files. Paths: &amp;lt;profiles&amp;gt;/&lt;br&gt;&lt;br&gt;- &amp;lt;profiles&amp;gt;/BattlEye/BEServer_x64.cfg — BattlEye configuration. Paths: &amp;lt;profiles&amp;gt;/BattlEye/&lt;br&gt;&lt;br&gt;- mpmissions/dayzOffline.chernarusplus/ — Mission folder with configuration. Paths: ./mpmissions/&lt;br&gt;&lt;br&gt;- mpmissions/*/db/ — Mission database and storage. Paths: ./mpmissions/*/&lt;br&gt;&lt;br&gt;- @ModName/ — Mod directories. Paths: ./&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>DayZ</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;DayZServer_x64.exe -config=serverDZ.cfg -port=2302 -profiles=profiles -dologs -adminlog -netlog -freezecheck&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 2302)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 2303)&lt;br&gt;&lt;br&gt;- Steam master (UDP) — GP+2 (default 2304)&lt;br&gt;&lt;br&gt;- BattlEye RCon (TCP) — configurable (default 2306)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-config — Server configuration file. Type: path, Default: serverDZ.cfg&lt;br&gt;&lt;br&gt;-port — Game port. Type: int, Default: 2302&lt;br&gt;&lt;br&gt;-profiles — Profile directory. Type: path, Default: profiles&lt;br&gt;&lt;br&gt;-dologs — Enable detailed logging. Type: bool, Default: &lt;br&gt;&lt;br&gt;-adminlog — Enable admin action logging. Type: bool, Default: &lt;br&gt;&lt;br&gt;-netlog — Enable network logging. Type: bool, Default: &lt;br&gt;&lt;br&gt;-freezecheck — Enable freeze detection. Type: bool, Default: &lt;br&gt;&lt;br&gt;-scriptDebug — Enable script debugging. Type: bool, Default: &lt;br&gt;&lt;br&gt;-filePatching — Enable file patching. Type: bool, Default: &lt;br&gt;&lt;br&gt;-mod — Client mods (semicolon separated). Type: string, Default: &lt;br&gt;&lt;br&gt;-serverMod — Server-side mods (semicolon separated). Type: string, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>DayZ</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not starting — verify serverDZ.cfg syntax. Check mission folder exists. Review DayZServer_x64_*.log for errors.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — open UDP 2302, 2303, 2304. Verify password setting. Check BattlEye status.&lt;br&gt;&lt;br&gt;- Mods not loading — verify mod paths and names. Check for mod conflicts. Ensure client and server mod versions match.&lt;br&gt;&lt;br&gt;- Database errors — check mission database permissions. Verify adequate disk space. Monitor for corruption.&lt;br&gt;&lt;br&gt;- Performance issues — reduce player count and loot spawns. Monitor CPU and RAM usage. Optimize server hardware.&lt;br&gt;&lt;br&gt;- BattlEye issues — update BattlEye files. Configure BEServer_x64.cfg properly. Check for mod compatibility.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>DayZ</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop mod format: @workshop_id&lt;br&gt;&lt;br&gt;- Steam Workshop integration: automatic with Steam subscriptions&lt;br&gt;&lt;br&gt;- Mod loading: -mod=&quot;@mod1;@mod2&quot; for client mods&lt;br&gt;&lt;br&gt;- Server mods: -serverMod=&quot;@servermod1;@servermod2&quot;&lt;br&gt;&lt;br&gt;- Workshop cache: Steam/steamapps/workshop/content/221100/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Garry&#x27;s Mod</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- garrysmod/cfg/server.cfg — Main server configuration: hostname, rcon_password, sv_password, gamemode settings, etc.. Paths: garrysmod/cfg/&lt;br&gt;&lt;br&gt;- garrysmod/cfg/autoexec.cfg — Auto-executed configuration on server start. Paths: garrysmod/cfg/&lt;br&gt;&lt;br&gt;- garrysmod/settings/users.txt — User access/admin definitions. Paths: garrysmod/settings/&lt;br&gt;&lt;br&gt;- garrysmod/data/ulib/users.txt — ULib user permissions (if ULX installed). Paths: garrysmod/data/ulib/&lt;br&gt;&lt;br&gt;- garrysmod/data/ulib/groups.txt — ULib group definitions. Paths: garrysmod/data/ulib/&lt;br&gt;&lt;br&gt;- garrysmod/addons/ulx/lua/ulx/modules/ — ULX admin command modules. Paths: garrysmod/addons/ulx/lua/ulx/modules/&lt;br&gt;&lt;br&gt;- garrysmod/lua/autorun/server/ — Server-side Lua autorun scripts. Paths: garrysmod/lua/autorun/server/&lt;br&gt;&lt;br&gt;- garrysmod/gamemodes/&amp;lt;gamemode&amp;gt;/gamemode/ — Gamemode Lua files. Paths: garrysmod/gamemodes/&lt;br&gt;&lt;br&gt;- garrysmod/addons/ — Addon folders (legacy format). Paths: garrysmod/addons/&lt;br&gt;&lt;br&gt;- garrysmod/workshop.lua — Workshop addon loading script. Paths: garrysmod/&lt;br&gt;&lt;br&gt;- garrysmod/cfg/mapcycle.txt — Map rotation cycle. Paths: garrysmod/cfg/&lt;br&gt;&lt;br&gt;- garrysmod/cfg/maplist.txt — Available maps list. Paths: garrysmod/cfg/&lt;br&gt;&lt;br&gt;- garrysmod/data/sv.db — Server database (SQLite). Paths: garrysmod/data/&lt;br&gt;&lt;br&gt;- garrysmod/data/&amp;lt;gamemode&amp;gt;/ — Gamemode-specific data files. Paths: garrysmod/data/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Garry&#x27;s Mod</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;srcds.exe -console -game garrysmod +gamemode sandbox +map gm_flatgrass +maxplayers 16 -port 27015 +ip 0.0.0.0&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 27015)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 27016)&lt;br&gt;&lt;br&gt;- ClientPort (UDP) — 27005 (fixed) (default 27005)&lt;br&gt;&lt;br&gt;- SourceTV (UDP) — GP+5 (default 27020)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-console — Enable console output. Type: bool, Default: &lt;br&gt;&lt;br&gt;-game — Game directory. Type: string, Default: garrysmod&lt;br&gt;&lt;br&gt;+gamemode — Starting gamemode. Type: string, Default: sandbox&lt;br&gt;&lt;br&gt;+map — Starting map. Type: string, Default: gm_flatgrass&lt;br&gt;&lt;br&gt;+maxplayers — Maximum players. Type: int, Default: 16&lt;br&gt;&lt;br&gt;-port — Game port (UDP). Type: int, Default: 27015&lt;br&gt;&lt;br&gt;+ip — Bind IP address. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;+hostname — Server name. Type: string, Default: &lt;br&gt;&lt;br&gt;+rcon_password — RCON password. Type: string, Default: &lt;br&gt;&lt;br&gt;+sv_password — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;-authkey — Steam Web API key for workshop. Type: string, Default: &lt;br&gt;&lt;br&gt;+host_workshop_collection — Workshop collection ID. Type: string, Default: &lt;br&gt;&lt;br&gt;+sv_setsteamaccount — Steam Game Server Login Token. Type: string, Default: &lt;br&gt;&lt;br&gt;-tickrate — Server tickrate. Type: int, Default: 66&lt;br&gt;&lt;br&gt;-threads — Worker threads. Type: int, Default: auto&lt;br&gt;&lt;br&gt;+sv_lan — LAN mode (0=Internet, 1=LAN). Type: int, Default: 0&lt;br&gt;&lt;br&gt;+sv_region — Server region code. Type: int, Default: 255&lt;br&gt;&lt;br&gt;+exec — Execute config file on start. Type: string, Default: server.cfg&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Garry&#x27;s Mod</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible in browser — open UDP 27015 (game) and 27016 (query) ports. Set +sv_lan 0. Verify Steam Game Server Login Token (+sv_setsteamaccount) if using workshop content.&lt;br&gt;&lt;br&gt;- Workshop addons not downloading — ensure -authkey (Steam Web API key) is valid. Verify +host_workshop_collection ID exists and is public. Check steamcmd workshop download logs.&lt;br&gt;&lt;br&gt;- Lua errors on startup — check garrysmod/console.log for specific error messages. Verify addon compatibility with current GMod version. Remove conflicting addons.&lt;br&gt;&lt;br&gt;- Players stuck downloading — reduce workshop collection size. Verify fastdl server if using custom content. Check network stability for large addon downloads.&lt;br&gt;&lt;br&gt;- ULX/ULib not working — ensure proper installation in garrysmod/addons/. Check data/ulib/ permissions. Verify users.txt and groups.txt syntax.&lt;br&gt;&lt;br&gt;- Gamemode won&#x27;t load — verify gamemode folder structure in garrysmod/gamemodes/. Check init.lua and cl_init.lua files. Monitor console for Lua errors.&lt;br&gt;&lt;br&gt;- High CPU/memory usage — identify problematic addons via server monitoring. Remove inefficient Lua scripts. Consider reducing tickrate from 66 to 33.&lt;br&gt;&lt;br&gt;- Database errors — check garrysmod/data/sv.db integrity. Verify disk space and permissions. Some addons may require MySQL instead of SQLite.&lt;br&gt;&lt;br&gt;- Map changes fail — verify maps exist in garrysmod/maps/. Check mapcycle.txt syntax. Ensure workshop maps are properly downloaded.&lt;br&gt;&lt;br&gt;- Custom content missing — setup FastDL server for custom maps/materials. Verify resource.AddWorkshop() calls in Lua scripts. Check client sv_downloadurl setting.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Garry&#x27;s Mod</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop collection setup: +host_workshop_collection COLLECTION_ID&lt;br&gt;&lt;br&gt;- API key required: -authkey YOUR_STEAM_WEB_API_KEY&lt;br&gt;&lt;br&gt;- Workshop content cached in: steamcmd/steamapps/workshop/content/4000/&lt;br&gt;&lt;br&gt;- Lua workshop loading: resource.AddWorkshop(&#x27;ADDON_ID&#x27;)&lt;br&gt;&lt;br&gt;- Auto-download: workshop addons download automatically to clients&lt;br&gt;&lt;br&gt;- Collection limits: keep collections under 50 addons for better performance&lt;br&gt;&lt;br&gt;- Workshop script: garrysmod/workshop.lua for manual addon loading&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Minecraft</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- server.properties — Main server configuration: level-name, gamemode, difficulty, max-players, server-port, motd, spawn-protection, etc.. Paths: ./&lt;br&gt;&lt;br&gt;- eula.txt — Minecraft EULA acceptance (must be set to true). Paths: ./&lt;br&gt;&lt;br&gt;- whitelist.json — Whitelisted players (if white-list=true). Paths: ./&lt;br&gt;&lt;br&gt;- ops.json — Server operators with admin permissions. Paths: ./&lt;br&gt;&lt;br&gt;- banned-players.json — Banned players list. Paths: ./&lt;br&gt;&lt;br&gt;- banned-ips.json — Banned IP addresses list. Paths: ./&lt;br&gt;&lt;br&gt;- server-icon.png — Server icon (64x64 PNG). Paths: ./&lt;br&gt;&lt;br&gt;- world/ — Default world folder (level-name in server.properties). Paths: ./world/&lt;br&gt;&lt;br&gt;- world_nether/ — Nether dimension folder. Paths: ./world_nether/&lt;br&gt;&lt;br&gt;- world_the_end/ — End dimension folder. Paths: ./world_the_end/&lt;br&gt;&lt;br&gt;- logs/latest.log — Current server log file. Paths: ./logs/&lt;br&gt;&lt;br&gt;- logs/debug.log — Debug log file (if enabled). Paths: ./logs/&lt;br&gt;&lt;br&gt;- usercache.json — User UUID cache. Paths: ./&lt;br&gt;&lt;br&gt;- bukkit.yml — Bukkit configuration (if using Bukkit/Spigot/Paper). Paths: ./&lt;br&gt;&lt;br&gt;- spigot.yml — Spigot configuration (if using Spigot/Paper). Paths: ./&lt;br&gt;&lt;br&gt;- paper.yml — Paper configuration (if using Paper). Paths: ./&lt;br&gt;&lt;br&gt;- plugins/ — Bukkit/Spigot/Paper plugins folder. Paths: ./plugins/&lt;br&gt;&lt;br&gt;- config/ — Forge mod configuration files. Paths: ./config/&lt;br&gt;&lt;br&gt;- mods/ — Forge mods folder. Paths: ./mods/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Minecraft</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;java -Xmx4G -Xms4G -jar server.jar nogui&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (TCP) — GP (default 25565)&lt;br&gt;&lt;br&gt;- Query Port (UDP) — GP (same port) (default 25565)&lt;br&gt;&lt;br&gt;- RCON Port (TCP) — configurable (default 25575)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-Xmx — Maximum heap memory allocation. Type: string, Default: 4G&lt;br&gt;&lt;br&gt;-Xms — Initial heap memory allocation. Type: string, Default: 4G&lt;br&gt;&lt;br&gt;-jar — Server JAR file path. Type: path, Default: server.jar&lt;br&gt;&lt;br&gt;nogui — Run without GUI (recommended for servers). Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:+UseG1GC — Use G1 garbage collector (recommended). Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:+ParallelRefProcEnabled — Enable parallel reference processing. Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:MaxGCPauseMillis — Maximum GC pause time in milliseconds. Type: int, Default: 200&lt;br&gt;&lt;br&gt;-XX:+UnlockExperimentalVMOptions — Unlock experimental JVM options. Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:+DisableExplicitGC — Disable explicit garbage collection. Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:+AlwaysPreTouch — Pre-touch memory pages during JVM initialization. Type: bool, Default: &lt;br&gt;&lt;br&gt;-XX:G1NewSizePercent — G1 new generation size percentage. Type: int, Default: 30&lt;br&gt;&lt;br&gt;-XX:G1MaxNewSizePercent — G1 maximum new generation size percentage. Type: int, Default: 40&lt;br&gt;&lt;br&gt;-XX:G1HeapRegionSize — G1 heap region size. Type: string, Default: 8m&lt;br&gt;&lt;br&gt;-XX:G1ReservePercent — G1 reserve percentage. Type: int, Default: 20&lt;br&gt;&lt;br&gt;-XX:G1HeapWastePercent — G1 heap waste percentage. Type: int, Default: 5&lt;br&gt;&lt;br&gt;-XX:G1MixedGCCountTarget — G1 mixed GC count target. Type: int, Default: 4&lt;br&gt;&lt;br&gt;-XX:InitiatingHeapOccupancyPercent — G1 initiating heap occupancy percentage. Type: int, Default: 15&lt;br&gt;&lt;br&gt;-XX:G1MixedGCLiveThresholdPercent — G1 mixed GC live threshold percentage. Type: int, Default: 90&lt;br&gt;&lt;br&gt;-XX:G1RSetUpdatingPauseTimePercent — G1 RSet updating pause time percentage. Type: int, Default: 5&lt;br&gt;&lt;br&gt;-XX:SurvivorRatio — Survivor space ratio. Type: int, Default: 32&lt;br&gt;&lt;br&gt;-Dlog4j2.formatMsgNoLookups — Disable Log4j2 lookups (security). Type: bool, Default: true&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Minecraft</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server won&#x27;t start — verify Java installation (java -version). Check server.jar file integrity. Ensure EULA is accepted (eula=true in eula.txt).&lt;br&gt;&lt;br&gt;- Out of memory errors — increase -Xmx value. Monitor actual memory usage. Consider upgrading server RAM or reducing view-distance in server.properties.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — open port 25565 (TCP). Verify server-ip in server.properties. Check firewall settings. Ensure online-mode matches client authentication.&lt;br&gt;&lt;br&gt;- World generation lag — reduce view-distance and simulation-distance in server.properties. Use Paper server for better performance. Pre-generate world chunks.&lt;br&gt;&lt;br&gt;- Plugin errors — check logs/ folder for specific error messages. Verify plugin compatibility with server version. Update outdated plugins.&lt;br&gt;&lt;br&gt;- Chunk loading issues — restart server to clear memory. Check world corruption with region file tools. Consider reducing max-world-size.&lt;br&gt;&lt;br&gt;- High CPU usage — optimize server.properties (view-distance, simulation-distance, max-tick-time). Use performance mods like Lithium. Monitor TPS with /tps command.&lt;br&gt;&lt;br&gt;- Database connection errors — verify MySQL/PostgreSQL connection details in plugin configs. Check database server status and network connectivity.&lt;br&gt;&lt;br&gt;- Whitelist not working — ensure white-list=true in server.properties. Verify UUIDs in whitelist.json. Use /whitelist add command to add players properly.&lt;br&gt;&lt;br&gt;- Backup/save issues — stop server before manual backups. Use save-all command before copying world files. Check disk space and permissions for world folders.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Rust</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/cfg/server.cfg — Main server configuration file with console commands. Paths: server/&amp;lt;identity&amp;gt;/cfg/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/cfg/users.cfg — User permissions and groups (Oxide/uMod). Paths: server/&amp;lt;identity&amp;gt;/cfg/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/oxide/config/DefaultGroups.json — Default permission groups (Oxide/uMod). Paths: server/&amp;lt;identity&amp;gt;/oxide/config/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/oxide/config/Oxide.json — Oxide framework configuration. Paths: server/&amp;lt;identity&amp;gt;/oxide/config/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/oxide/data/ — Plugin data files. Paths: server/&amp;lt;identity&amp;gt;/oxide/data/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/oxide/plugins/ — Oxide plugin files (.cs). Paths: server/&amp;lt;identity&amp;gt;/oxide/plugins/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/oxide/lang/ — Plugin language files. Paths: server/&amp;lt;identity&amp;gt;/oxide/lang/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/UserPersistence.db — Player data SQLite database. Paths: server/&amp;lt;identity&amp;gt;/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/proceduralmap.*.*.map — Generated map file. Paths: server/&amp;lt;identity&amp;gt;/&lt;br&gt;&lt;br&gt;- server/&amp;lt;identity&amp;gt;/proceduralmap.*.*.sav — World save file. Paths: server/&amp;lt;identity&amp;gt;/&lt;br&gt;&lt;br&gt;- bans.cfg — Banned players list. Paths: ./&lt;br&gt;&lt;br&gt;- start_server.bat — Windows server startup script. Paths: ./&lt;br&gt;&lt;br&gt;- start_server.sh — Linux server startup script. Paths: ./&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Rust</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;RustDedicated.exe -batchmode -load -nographics +server.hostname &quot;My Rust Server&quot; +server.port 28015 +server.identity &quot;my_server_identity&quot; +rcon.port 28016 +rcon.password &quot;your_rcon_password&quot; +server.maxplayers 100 +server.worldsize 4000 +server.seed 12345&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 28015)&lt;br&gt;&lt;br&gt;- RCON Port (TCP) — GP+1 (default 28016)&lt;br&gt;&lt;br&gt;- Query Port (UDP) — GP+2 (default 28017)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-batchmode — Run in batch mode (no GUI). Type: bool, Default: &lt;br&gt;&lt;br&gt;-load — Load the save file on startup. Type: bool, Default: &lt;br&gt;&lt;br&gt;-nographics — Disable graphics rendering. Type: bool, Default: &lt;br&gt;&lt;br&gt;+server.hostname — Server name displayed in browser. Type: string, Default: My Rust Server&lt;br&gt;&lt;br&gt;+server.port — Game port (UDP). Type: int, Default: 28015&lt;br&gt;&lt;br&gt;+server.identity — Server identity folder name. Type: string, Default: my_server_identity&lt;br&gt;&lt;br&gt;+server.maxplayers — Maximum number of players. Type: int, Default: 100&lt;br&gt;&lt;br&gt;+server.worldsize — World size (1000-4000). Type: int, Default: 4000&lt;br&gt;&lt;br&gt;+server.seed — World generation seed. Type: int, Default: 12345&lt;br&gt;&lt;br&gt;+rcon.port — RCON port (TCP). Type: int, Default: 28016&lt;br&gt;&lt;br&gt;+rcon.password — RCON password. Type: string, Default: &lt;br&gt;&lt;br&gt;+rcon.ip — RCON bind IP. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;+rcon.web — Enable web RCON (0/1). Type: int, Default: 1&lt;br&gt;&lt;br&gt;+server.level — Map name or &#x27;Procedural Map&#x27;. Type: string, Default: Procedural Map&lt;br&gt;&lt;br&gt;+server.description — Server description. Type: string, Default: &lt;br&gt;&lt;br&gt;+server.url — Server website URL. Type: string, Default: &lt;br&gt;&lt;br&gt;+server.headerimage — Server header image URL. Type: string, Default: &lt;br&gt;&lt;br&gt;+server.logoimage — Server logo image URL. Type: string, Default: &lt;br&gt;&lt;br&gt;+server.saveinterval — Auto-save interval in seconds. Type: int, Default: 300&lt;br&gt;&lt;br&gt;+server.globalchat — Enable global chat. Type: bool, Default: true&lt;br&gt;&lt;br&gt;+server.stability — Enable structural stability. Type: bool, Default: true&lt;br&gt;&lt;br&gt;+server.radiation — Enable radiation. Type: bool, Default: true&lt;br&gt;&lt;br&gt;+server.pve — Player vs Environment mode. Type: bool, Default: false&lt;br&gt;&lt;br&gt;+decay.scale — Decay rate multiplier. Type: float, Default: 1&lt;br&gt;&lt;br&gt;+craft.instant — Instant crafting. Type: bool, Default: false&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Rust</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible in browser — open UDP 28015 (game) and UDP 28017 (query) ports. Verify +server.port matches opened port. Check Steam server list refresh.&lt;br&gt;&lt;br&gt;- RCON connection failed — ensure +rcon.password is set and +rcon.port is open (TCP). Verify firewall allows TCP connections on RCON port.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — check server.maxplayers not exceeded. Verify Steam authentication servers are online. Monitor server console for connection errors.&lt;br&gt;&lt;br&gt;- High memory usage/crashes — reduce server.worldsize if needed. Monitor Oxide plugin memory usage. Restart server regularly during high population periods.&lt;br&gt;&lt;br&gt;- Oxide plugins not loading — verify .cs files are in oxide/plugins/. Check oxide/logs/ for compilation errors. Ensure plugin dependencies are installed.&lt;br&gt;&lt;br&gt;- World generation fails — change server.seed value. Ensure adequate disk space (4000 worldsize needs ~2GB). Check server console for terrain generation errors.&lt;br&gt;&lt;br&gt;- Save corruption — backup save files regularly. Use server.saveinterval appropriately. Monitor disk I/O during save operations.&lt;br&gt;&lt;br&gt;- Performance issues — reduce server.worldsize and maxplayers. Disable unnecessary Oxide plugins. Monitor server.fps and gc.collect in console.&lt;br&gt;&lt;br&gt;- Decay not working — verify decay.scale setting. Check structural stability settings. Some items may have different decay rates in configuration.&lt;br&gt;&lt;br&gt;- Chat/communication issues — verify server.globalchat setting. Check Oxide chat plugins for conflicts. Monitor player.chat and say commands in console.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Squad</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- SquadGame/ServerConfig/Server.cfg — Main server configuration. Paths: SquadGame/ServerConfig/&lt;br&gt;&lt;br&gt;- SquadGame/ServerConfig/Rcon.cfg — RCON configuration. Paths: SquadGame/ServerConfig/&lt;br&gt;&lt;br&gt;- SquadGame/ServerConfig/MapRotation.cfg — Map rotation settings. Paths: SquadGame/ServerConfig/&lt;br&gt;&lt;br&gt;- SquadGame/ServerConfig/Admins.cfg — Admin Steam IDs. Paths: SquadGame/ServerConfig/&lt;br&gt;&lt;br&gt;- SquadGame/ServerConfig/Bans.cfg — Banned player list. Paths: SquadGame/ServerConfig/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Squad</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;SquadGameServer.exe Mutaha -Port=7787 -QueryPort=27165 -RCON=21114 -log&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 7787)&lt;br&gt;&lt;br&gt;- Query Port (UDP) — configurable (default 27165)&lt;br&gt;&lt;br&gt;- RCON Port (TCP) — configurable (default 21114)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;Mutaha — Starting map/layer. Type: string, Default: Mutaha&lt;br&gt;&lt;br&gt;-Port — Game port. Type: int, Default: 7787&lt;br&gt;&lt;br&gt;-QueryPort — Steam query port. Type: int, Default: 27165&lt;br&gt;&lt;br&gt;-RCON — RCON port. Type: int, Default: 21114&lt;br&gt;&lt;br&gt;-log — Enable logging. Type: bool, Default: &lt;br&gt;&lt;br&gt;-LOCALLOGTIMES — Use local time in logs. Type: bool, Default: &lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Squad</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible — open UDP game port and query port. Verify Steam Game Server Login Token in Server.cfg.&lt;br&gt;&lt;br&gt;- RCON not working — check Rcon.cfg for password and IP settings. Open TCP RCON port. Verify firewall settings.&lt;br&gt;&lt;br&gt;- Map rotation issues — check MapRotation.cfg syntax. Verify layer names are correct. Test individual maps first.&lt;br&gt;&lt;br&gt;- Admin commands not working — verify Steam ID64 format in Admins.cfg. Check admin level permissions.&lt;br&gt;&lt;br&gt;- Performance problems — monitor CPU usage. Reduce max players if needed. Check memory consumption.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Squad</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Mod support: limited workshop integration&lt;br&gt;&lt;br&gt;- Custom maps: place in SquadGame/Content/Maps/&lt;br&gt;&lt;br&gt;- Workshop mods: handled through Steam integration&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Team Fortress 2</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- tf/cfg/server.cfg — Main server configuration: hostname, rcon_password, sv_password, mp_timelimit, etc.. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/autoexec.cfg — Auto-executed configuration on server start. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/mapcycle.txt — Map rotation cycle. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/maplist.txt — Available maps list. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/pure_server_whitelist.txt — Pure server file whitelist. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/banned_user.cfg — Banned users list. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/cfg/banned_ip.cfg — Banned IP addresses. Paths: tf/cfg/&lt;br&gt;&lt;br&gt;- tf/addons/sourcemod/configs/admins_simple.ini — SourceMod admin definitions. Paths: tf/addons/sourcemod/configs/&lt;br&gt;&lt;br&gt;- tf/addons/sourcemod/configs/databases.cfg — SourceMod database connections. Paths: tf/addons/sourcemod/configs/&lt;br&gt;&lt;br&gt;- tf/addons/metamod.vdf — MetaMod:Source configuration. Paths: tf/addons/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Team Fortress 2</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;srcds.exe -game tf -console +sv_pure 1 +map ctf_2fort +maxplayers 24 -port 27015 +ip 0.0.0.0&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 27015)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 27016)&lt;br&gt;&lt;br&gt;- SourceTV (UDP) — GP+5 (default 27020)&lt;br&gt;&lt;br&gt;- RCON (TCP) — GP (same as game port) (default 27015)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-game — Game directory. Type: string, Default: tf&lt;br&gt;&lt;br&gt;-console — Enable console output. Type: bool, Default: &lt;br&gt;&lt;br&gt;+sv_pure — Pure server mode (0=off, 1=on, 2=whitelist). Type: int, Default: 1&lt;br&gt;&lt;br&gt;+map — Starting map. Type: string, Default: ctf_2fort&lt;br&gt;&lt;br&gt;+maxplayers — Maximum players. Type: int, Default: 24&lt;br&gt;&lt;br&gt;-port — Game port (UDP). Type: int, Default: 27015&lt;br&gt;&lt;br&gt;+ip — Bind IP address. Type: ip, Default: 0.0.0.0&lt;br&gt;&lt;br&gt;+hostname — Server name. Type: string, Default: &lt;br&gt;&lt;br&gt;+rcon_password — RCON password. Type: string, Default: &lt;br&gt;&lt;br&gt;+sv_password — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;+sv_setsteamaccount — Steam Game Server Login Token. Type: string, Default: &lt;br&gt;&lt;br&gt;-tickrate — Server tickrate. Type: int, Default: 66&lt;br&gt;&lt;br&gt;+sv_lan — LAN mode (0=Internet, 1=LAN). Type: int, Default: 0&lt;br&gt;&lt;br&gt;+sv_region — Server region code. Type: int, Default: 255&lt;br&gt;&lt;br&gt;+exec — Execute config file on start. Type: string, Default: server.cfg&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Team Fortress 2</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible in browser — open UDP 27015 (game) and 27016 (query) ports. Set +sv_lan 0. Verify Steam Game Server Login Token (+sv_setsteamaccount) if required.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — check +maxplayers setting. Verify Steam authentication servers are online. Monitor server console for connection errors.&lt;br&gt;&lt;br&gt;- Pure server violations — update pure_server_whitelist.txt with allowed custom files. Set sv_pure 0 to disable or sv_pure 2 for strict whitelist mode.&lt;br&gt;&lt;br&gt;- SourceMod plugins not loading — verify metamod.vdf exists and points to correct MetaMod binary. Check addons/sourcemod/logs/errors_*.log for specific plugin errors.&lt;br&gt;&lt;br&gt;- Map cycle not working — verify mapcycle.txt has correct map names. Use mp_timelimit to control map change timing. Check for custom map requirements.&lt;br&gt;&lt;br&gt;- High CPU/performance issues — reduce server fps_max if CPU limited. Monitor net_graph for network performance. Consider reducing maxplayers for better performance.&lt;br&gt;&lt;br&gt;- VAC authentication error — ensure server has valid GSLT if using ranked mode. Remove any modifications that might trigger VAC.&lt;br&gt;&lt;br&gt;- Bots filling server — use tf_bot_quota 0 to disable bots. Configure tf_bot_auto_vacate for automatic bot removal when players join.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Terraria</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- serverconfig.txt — Server configuration file with all settings. Paths: ./&lt;br&gt;&lt;br&gt;- Worlds/&amp;lt;worldname&amp;gt;.wld — World save file. Paths: ./Worlds/&lt;br&gt;&lt;br&gt;- tshock/ — TShock server mod directory (if using TShock). Paths: ./tshock/&lt;br&gt;&lt;br&gt;- tshock/config.json — TShock configuration. Paths: ./tshock/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Terraria</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;TerrariaServer.exe -config serverconfig.txt&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (TCP) — GP (default 7777)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-config — Server configuration file. Type: path, Default: serverconfig.txt&lt;br&gt;&lt;br&gt;-port — Server port. Type: int, Default: 7777&lt;br&gt;&lt;br&gt;-players — Max players. Type: int, Default: 8&lt;br&gt;&lt;br&gt;-pass — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;-world — World file path. Type: path, Default: &lt;br&gt;&lt;br&gt;-autocreate — Auto-create world (1=small, 2=medium, 3=large). Type: int, Default: 1&lt;br&gt;&lt;br&gt;-worldname — World name for auto-creation. Type: string, Default: World&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Terraria</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server won&#x27;t start — verify serverconfig.txt exists and has correct syntax. Check world file path if specified.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — open TCP port 7777. Verify server is not in single-player mode. Check password settings.&lt;br&gt;&lt;br&gt;- World corruption — backup .wld files regularly. Avoid force-stopping during saves. Check disk space.&lt;br&gt;&lt;br&gt;- TShock not working — ensure TShock is properly installed. Check tshock/config.json for errors. Verify permissions.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Unturned</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Servers/&amp;lt;ServerName&amp;gt;/Server/Commands.dat — Server configuration: port, name, password, mode. Paths: Servers/&amp;lt;ServerName&amp;gt;/Server/&lt;br&gt;&lt;br&gt;- Servers/&amp;lt;ServerName&amp;gt;/Workshop/ — Workshop mod configurations. Paths: Servers/&amp;lt;ServerName&amp;gt;/&lt;br&gt;&lt;br&gt;- Servers/&amp;lt;ServerName&amp;gt;/Rocket/ — RocketMod plugin directory. Paths: Servers/&amp;lt;ServerName&amp;gt;/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Unturned</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;Unturned.exe -batchmode -nographics +LanServer/MyServer&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 27015)&lt;br&gt;&lt;br&gt;- Steam query (UDP) — GP+1 (default 27016)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-batchmode — Run in batch mode. Type: bool, Default: &lt;br&gt;&lt;br&gt;-nographics — Run without graphics. Type: bool, Default: &lt;br&gt;&lt;br&gt;+LanServer/ — Server name/directory. Type: string, Default: MyServer&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Unturned</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not starting — verify Commands.dat syntax. Check server name matches directory. Review logs for errors.&lt;br&gt;&lt;br&gt;- Workshop mods not loading — verify Workshop.json configuration. Check mod subscriptions. Restart server after changes.&lt;br&gt;&lt;br&gt;- RocketMod plugins not working — ensure Rocket.Unturned.dll is installed. Check plugin compatibility with game version.&lt;br&gt;</content:encoded>
</item>
<item>
<title>Steam Workshop</title>
<category>Unturned</category>
<content:encoded>&lt;strong&gt;Steam Workshop Configuration&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Workshop configuration: Servers/ServerName/Workshop/Workshop.json&lt;br&gt;&lt;br&gt;- File IDs: list workshop item IDs in Workshop.json&lt;br&gt;&lt;br&gt;- Auto-download: workshop content downloads automatically&lt;br&gt;</content:encoded>
</item>
<item>
<title>Config Files</title>
<category>Valheim</category>
<content:encoded>&lt;strong&gt;Configuration Files&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- start_headless_server.bat — Windows server startup script. Paths: ./&lt;br&gt;&lt;br&gt;- start_server.sh — Linux server startup script. Paths: ./&lt;br&gt;&lt;br&gt;- adminlist.txt — Server administrator Steam IDs. Paths: ./&lt;br&gt;&lt;br&gt;- bannedlist.txt — Banned player Steam IDs. Paths: ./&lt;br&gt;&lt;br&gt;- permittedlist.txt — Permitted player Steam IDs (if using whitelist). Paths: ./&lt;br&gt;&lt;br&gt;- &amp;lt;savedir&amp;gt;/worlds_local/&amp;lt;world&amp;gt;.db — World database file. Paths: &amp;lt;savedir&amp;gt;/worlds_local/&lt;br&gt;&lt;br&gt;- &amp;lt;savedir&amp;gt;/worlds_local/&amp;lt;world&amp;gt;.fwl — World metadata file. Paths: &amp;lt;savedir&amp;gt;/worlds_local/&lt;br&gt;&lt;br&gt;- &amp;lt;savedir&amp;gt;/characters/ — Player character data. Paths: &amp;lt;savedir&amp;gt;/characters/&lt;br&gt;</content:encoded>
</item>
<item>
<title>Startup Parameters</title>
<category>Valheim</category>
<content:encoded>&lt;strong&gt;Default Command Line&lt;/strong&gt;&lt;br&gt;&lt;br&gt;valheim_server.exe -nographics -batchmode -name &quot;My Valheim Server&quot; -port 2456 -world &quot;MyWorld&quot; -password &quot;mypassword&quot; -public 1&lt;br&gt;&lt;br&gt;&lt;strong&gt;Port Scheme&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Game Port (GP) (UDP) — GP (default 2456)&lt;br&gt;&lt;br&gt;- Game Port 2 (UDP) — GP+1 (default 2457)&lt;br&gt;&lt;br&gt;- Game Port 3 (UDP) — GP+2 (default 2458)&lt;br&gt;&lt;br&gt;&lt;strong&gt;Command Line Flags&lt;/strong&gt;&lt;br&gt;&lt;br&gt;-nographics — Run without graphics. Type: bool, Default: &lt;br&gt;&lt;br&gt;-batchmode — Run in batch mode. Type: bool, Default: &lt;br&gt;&lt;br&gt;-name — Server name displayed in browser. Type: string, Default: My Valheim Server&lt;br&gt;&lt;br&gt;-port — Base server port. Type: int, Default: 2456&lt;br&gt;&lt;br&gt;-world — World name/save file. Type: string, Default: MyWorld&lt;br&gt;&lt;br&gt;-password — Server password. Type: string, Default: &lt;br&gt;&lt;br&gt;-public — Public server (0=private, 1=public). Type: int, Default: 1&lt;br&gt;&lt;br&gt;-savedir — Save directory path. Type: path, Default: &lt;br&gt;&lt;br&gt;-logFile — Log file path. Type: path, Default: &lt;br&gt;&lt;br&gt;-saveinterval — Auto-save interval in seconds. Type: int, Default: 1800&lt;br&gt;&lt;br&gt;-backups — Number of backup saves to keep. Type: int, Default: 4&lt;br&gt;&lt;br&gt;-backupshort — Short backup interval in seconds. Type: int, Default: 300&lt;br&gt;&lt;br&gt;-backuplong — Long backup interval in seconds. Type: int, Default: 3600&lt;br&gt;</content:encoded>
</item>
<item>
<title>Troubleshooting</title>
<category>Valheim</category>
<content:encoded>&lt;strong&gt;Common Issues and Solutions&lt;/strong&gt;&lt;br&gt;&lt;br&gt;- Server not visible — open UDP ports 2456, 2457, 2458. Verify -public 1 setting. Check Steam server list refresh.&lt;br&gt;&lt;br&gt;- Players can&#x27;t connect — verify password matches. Check Steam authentication. Monitor server console for connection errors.&lt;br&gt;&lt;br&gt;- World won&#x27;t load — verify world name in -world parameter. Check save directory permissions. Restore from backup if corrupted.&lt;br&gt;&lt;br&gt;- Performance issues — reduce player count. Monitor RAM usage (minimum 4GB recommended). Check for mod conflicts.&lt;br&gt;&lt;br&gt;- Save corruption — enable regular backups with -backups setting. Monitor disk space. Avoid force-stopping server during saves.&lt;br&gt;&lt;br&gt;- Admin commands not working — verify Steam ID in adminlist.txt is correct. Restart server after modifying admin list.&lt;br&gt;&lt;br&gt;- Memory leaks — restart server regularly. Monitor memory usage over time. Update to latest game version.&lt;br&gt;</content:encoded>
</item>
</channel>
</rss>

674
ControlPanel/LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2022 oNdsen <https://ondsen.ch/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

1994
ControlPanel/Parsedown.php Normal file

File diff suppressed because it is too large Load diff

22
ControlPanel/README.md Normal file
View file

@ -0,0 +1,22 @@
# OGP-AdminLTE
AdminLTE Theme adapted for OpenGamePanel
### Features
- [x] Installs a Theme Database for User specific Theme Settings
- [x] Responsive
- [x] Dark and Light Mode Switcher
- [x] Custom Dashboard with additional Rows (all Boxes are movable!)
- [x] Custom Server Overview (with Chart & Cronjob)
- [x] Custom FTP Style
- [x] Custom Shop Style
- [x] User specific Avatars (will also load other User Avatars if needed)
- [x] Maintenance Notification on Login Screen
- [x] Custom Logo Upload
### Images
![This is an image](../main/adminlte_dark.png)
![This is an image](../main/adminlte_light.png)
![This is an image](../main/adminlte_online-servers.png)
![This is an image](../main/adminlte_shop.png)
![This is an image](../main/adminlte_maintenance.png)
![This is an image](../main/adminlte_support_chat.png)

25
ControlPanel/README.txt Normal file
View file

@ -0,0 +1,25 @@
Hi guys!
EXIM as smarthost is only needed for hosts with dynamically assigned IP because it avoids to be blocked by some mail servers like hotmail.
Upload all files.
Login with ssh and change to the user 'www-data'(in ubuntu) or 'apache'(in centos) or any other user that manages the apache server with, for example:
sudo su - www-data
Now edit the cron tab for this user
crontab -e
and copy this line at the end of the file and save it (WARNING:modify it with the correct path):
*/1 * * * * php /var/www/html/ogp/modules/billing/cron-shop.php
Now this script searches for expired game homes every minute, and wil stop and remove them if they are expired.
If you would like to do this at midnight every day instead of every minute you should use
0 0 * * * php /var/www/html/ogp/modules/billing/cron-shop.php
TIP: Searching in google, for example, "cron every month" you will find the correct code to search expired homes and remove them every month.

View file

@ -0,0 +1,94 @@
# Comprehensive Server Admin Guide System
This directory contains the complete server admin guide generation system that creates exhaustive documentation for all supported games.
## Quick Start
Generate all guides and PDFs:
```bash
./tools/generate_all_guides.sh
```
## Components
### Core Scripts
- **`generate_server_guides.py`** - Main generator that creates Markdown guides and PDFs
- **`validate_guides.py`** - Quality validation ensuring guides meet exhaustive standards
- **`generate_all_guides.sh`** - Complete workflow automation script
### Data Sources
- **`data/games/*.yml`** - YAML files containing exhaustive game data
- **`game_titles.txt`** - Reference file listing all supported games
### Generated Output
- **`docs/games/<slug>/index.md`** - Comprehensive Markdown guide for each game
- **`dist/pdfs/<slug>__Server_Admin_Guide_v1.pdf`** - PDF version of each guide
- **`docs/games/_index.md`** - Index page listing all games with links
- **`dist/pdfs/manifest.json`** - Machine-readable metadata manifest
## Features
### Exhaustive Coverage
Each guide includes:
- **Complete startup parameters** (minimum 10 flags with defaults, types, descriptions, examples)
- **Full port mapping** with protocols and relationships to base Game Port
- **All configuration files** (minimum 8 entries with paths for Windows/Linux)
- **Steam Workshop integration** (where supported)
- **Deep troubleshooting** with specific fixes and file/flag references
- **Management procedures** (RCON, backups, updates, performance tuning)
### Quality Gates
- Validates required H2 sections: Quick Start, Port Map, Startup Parameters (EXHAUSTIVE), Configuration Files (ALL), Steam Workshop, Management, Troubleshooting (Deep), Appendices
- Ensures minimum content standards (10+ startup flags, 8+ config files)
- Checks for placeholder content (TODO, TBD, etc.)
- Validates file structure and cross-references
### Current Status
- ✅ **14 games processed** with comprehensive guides
- ✅ **14 PDF files generated** (60-70KB each, comprehensive content)
- ✅ **All quality gates passing** (no critical errors)
- ✅ **Zero placeholder content** (all TODO items resolved)
### Enhanced Examples
- **Counter-Strike: Global Offensive**: 30 startup flags, 17 config files, complete SourceMod integration
- **7 Days to Die**: 15 startup flags, 10 config files, Unity engine specifics
## Extending the System
### Adding New Games
1. Create `data/games/new-game.yml` following the schema
2. Include minimum 10 startup flags and 8 config entries
3. Run `./tools/generate_all_guides.sh` to generate and validate
### Schema Requirements
```yaml
name: "Official Game Name"
supports_workshop: true/false
appid: 123456
engine: "Engine Name"
linuxgsm_support: true
ogp_support: true
startup:
default_command: 'server.exe -flags'
ports: [...] # Complete port mapping
flags: [...] # Minimum 10 flags with examples
configs: [...] # Minimum 8 config files
troubleshooting: [...] # Deep technical issues
workshop: {...} # If workshop supported
```
## Dependencies
- Python 3.6+
- Pandoc with XeLaTeX
- PyYAML
Install with:
```bash
sudo apt install pandoc texlive-xetex
pip install pyyaml
```
This system fulfills the requirement for "exhaustive" server admin guides that serve as complete "one-stop" documentation for every game we host.

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__

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.

View file

@ -0,0 +1,12 @@
%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',
);

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',
);

View file

@ -0,0 +1,5 @@
agent_auto_update=0
run_pureftpd=1
ftp_port=
ftp_ip=
ftp_pasv_range=

View 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

View file

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

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;
?>

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!');
}
?>

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);
}
}
?>

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;
?>

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;
?>

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;
?>

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);
?>

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;
?>

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;
}

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

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;

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

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;

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/';
?>

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

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

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

File diff suppressed because it is too large Load diff

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.

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.

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.

File diff suppressed because it is too large Load diff

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.

View file

@ -0,0 +1,694 @@
#!/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"
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',
);" > $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
fi

View file

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

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;

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"
}

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

View file

@ -0,0 +1,347 @@
#!/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 files..."
cp -avf systemd Crypt EHCP FastDownload File Frontier IspConfig KKrcon php-query Schedule Time ogp_agent.pl ogp_screenrc ogp_agent_run agent_conf.sh extPatterns.txt ${agent_home}/ || failed "Failed to copy agent files to ${agent_home}."
# 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

View file

@ -0,0 +1,4 @@
Thu Aug 28 13:08:29 2025 New log file created
Thu Aug 28 13:08:29 2025 Reading startup flags from /home/gameserver/OGP/startups
Thu Aug 28 13:08:29 2025 Open Game Panel - Agent started - v1.4 - port 12679 - PID 8284
Thu Aug 28 13:08:30 2025 Error reading tasks file No such file or directory

View file

@ -0,0 +1,9 @@
Thu Aug 28 13:03:57 2025 The Steam client, steamcmd, does not exist yet, installing...
Thu Aug 28 13:03:57 2025 Downloading the Steam client from http://media.steampowered.com/client/steamcmd_linux.tar.gz to '/home/gameserver/OGP/steamcmd/steamcmd_linux.tar.gz'.
Thu Aug 28 13:03:57 2025 Uncompressing /home/gameserver/OGP/steamcmd/steamcmd_linux.tar.gz
Thu Aug 28 13:03:57 2025 Uncompression called for file /home/gameserver/OGP/steamcmd/steamcmd_linux.tar.gz to dir /home/gameserver/OGP/steamcmd.
Thu Aug 28 13:03:57 2025 File uncompressed/extracted successfully.
Thu Aug 28 13:03:57 2025 Creating the startups directory /home/gameserver/OGP/startups
Thu Aug 28 13:03:57 2025 Open Game Panel - Agent started - v1.4 - port 12679 - PID 8129
Thu Aug 28 13:03:58 2025 Error reading tasks file No such file or directory
Thu Aug 28 13:08:29 2025 Rotating log file

View file

@ -0,0 +1 @@
8284

File diff suppressed because it is too large Load diff

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

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

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 $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;
}
});

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;
}
}

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',
],
];
}

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