mirror of
https://github.com/EQEmu/Server.git
synced 2026-05-22 20:33:01 +00:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b83fafb745 | |||
| bcc42edb16 | |||
| 0eba5f2990 | |||
| c70bdc6b70 | |||
| 6a25f30441 | |||
| 825dbc9e9a | |||
| a5f35bf32a | |||
| c09ab507dd | |||
| 483ca9996b | |||
| 122f1cd02d | |||
| e0d4f9ecd1 | |||
| cb72ad4d0f | |||
| 98f4e570e7 | |||
| 6532a81b80 | |||
| b0f591540c | |||
| ac07e7d578 | |||
| 40ef387496 | |||
| c9a79af79b | |||
| 1a71237dc2 | |||
| f990292660 | |||
| e72f1e855f | |||
| 3bc9e4bc24 | |||
| 22aef8ad79 | |||
| bf84fcd908 | |||
| 0c5779d2de | |||
| 2270bd267d | |||
| feec425be9 | |||
| dd5ef6523f | |||
| c69b9a95b7 |
@@ -1,5 +0,0 @@
|
||||
base/
|
||||
!base/*.json
|
||||
override/
|
||||
repo/
|
||||
cache/
|
||||
@@ -1,9 +0,0 @@
|
||||
# This is a "dev" image for running eqemu in development, also for dev containers
|
||||
ARG USERNAME=user-name-goes-here
|
||||
ARG USER_UID=1000
|
||||
ARG USER_GID=$USER_UID
|
||||
|
||||
FROM --platform=linux/arm64 mcr.microsoft.com/devcontainers/base:debian
|
||||
RUN sudo apt update && sudo apt install -y --no-install-recommends build-essential libtool cmake curl debconf-utils git libluabind-dev libsodium-dev liblua5.2-0 liblua5.2-dev libmariadb-dev libssl-dev minizip make mariadb-client locales nano open-vm-tools unzip uuid-dev iputils-ping wget libcurl4-openssl-dev gdb libyaml-cpp-dev ccache ninja-build pv mariadb-server libperl-dev libjson-perl libio-stringy-perl liblua5.1-dev libluabind-dev libboost-dev mariadb-server valgrind telnet libgoogle-perftools-dev google-perftools
|
||||
|
||||
USER $USERNAME
|
||||
@@ -1,9 +0,0 @@
|
||||
# This is a "dev" image for running eqemu in development, also for dev containers
|
||||
ARG USERNAME=user-name-goes-here
|
||||
ARG USER_UID=1000
|
||||
ARG USER_GID=$USER_UID
|
||||
|
||||
FROM mcr.microsoft.com/devcontainers/base:debian
|
||||
RUN sudo apt update && sudo apt install -y --no-install-recommends build-essential libtool cmake curl debconf-utils git libluabind-dev libsodium-dev liblua5.2-0 liblua5.2-dev libmariadb-dev libssl-dev minizip make mariadb-client locales nano open-vm-tools unzip uuid-dev iputils-ping wget libcurl4-openssl-dev gdb libyaml-cpp-dev ccache ninja-build pv mariadb-server libperl-dev libjson-perl libio-stringy-perl liblua5.1-dev libluabind-dev libboost-dev mariadb-server valgrind telnet libgoogle-perftools-dev google-perftools
|
||||
|
||||
USER $USERNAME
|
||||
@@ -1,228 +0,0 @@
|
||||
# Build binaries: make cmake, make build
|
||||
# One time initial setup (or to reset db): make prep, make inject-mariadb, make maps
|
||||
# Update custom db edits: make inject-custom
|
||||
# Start up server: make shared, make login, make world, make zone
|
||||
# in game, stop combat spam #logs set gmsay 79 0
|
||||
# in game, stop loot spam #logs set gmsay 69 0
|
||||
NAME := eqemu-server
|
||||
|
||||
.PHONY: prep
|
||||
prep: is-vscode
|
||||
@echo "Preparing build/bin for usage..."
|
||||
|
||||
@echo "Prepping folders..."
|
||||
@mkdir -p .devcontainer/override
|
||||
@mkdir -p .devcontainer/repo
|
||||
@mkdir -p .devcontainer/cache
|
||||
@mkdir -p build/bin/logs
|
||||
@mkdir -p build/bin/shared
|
||||
@mkdir -p build/bin/assets
|
||||
|
||||
@echo "Applying overrides..."
|
||||
@if [ ! -f .devcontainer/override/eqemu_config.json ]; then cp .devcontainer/base/eqemu_config.json .devcontainer/override/eqemu_config.json; fi
|
||||
@if [ -f build/bin/eqemu_config.json ]; then unlink build/bin/eqemu_config.json; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/override/eqemu_config.json eqemu_config.json
|
||||
@if [ ! -f .devcontainer/override/login.json ]; then cp .devcontainer/base/login.json .devcontainer/override/login.json; fi
|
||||
@if [ -f build/bin/login.json ]; then unlink build/bin/login.json; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/override/login.json login.json
|
||||
|
||||
@echo "Cloning repositories..."
|
||||
cd .devcontainer/repo && if [ ! -d "quests" ]; then cd ../../.devcontainer/repo/ && git clone https://github.com/ProjectEQ/projecteqquests.git quests; fi
|
||||
cd .devcontainer/repo && if [ ! -d "eqemu-definitions" ]; then cd ../../.devcontainer/repo/ && git clone https://github.com/xackery/eqemu-definitions.git eqemu-definitions; fi
|
||||
cd .devcontainer/repo && if [ ! -d "maps" ]; then cd ../../ && make maps; fi
|
||||
@if [ -d build/bin/quests ]; then unlink build/bin/quests; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/quests quests
|
||||
@if [ -d build/bin/maps ]; then unlink build/bin/maps; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/maps maps
|
||||
@if [ -d build/bin/eqemu-definitions ]; then unlink build/bin/eqemu-definitions; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/eqemu-definitions eqemu-definitions
|
||||
@mkdir -p build/bin/quests/mods
|
||||
|
||||
@echo "Applying base links..."
|
||||
cp -R -u -p utils/patches .devcontainer/base/
|
||||
@if [ -d build/bin/assets/patches ]; then unlink build/bin/assets/patches; fi
|
||||
cd build/bin/assets && ln -s ../../../.devcontainer/base/patches patches
|
||||
@if [ -d build/bin/lua_modules ]; then unlink build/bin/lua_modules; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/quests/lua_modules lua_modules
|
||||
@if [ -d build/bin/mods ]; then unlink build/bin/mods; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/quests/mods mods
|
||||
@if [ -d build/bin/plugins ]; then unlink build/bin/plugins; fi
|
||||
cd build/bin && ln -s ../../.devcontainer/repo/quests/plugins plugins
|
||||
|
||||
@echo "Eqemu is prepared. Edit build/bin/eqemu_config.json to configure."
|
||||
|
||||
is-vscode:
|
||||
@if [ -z "$$REMOTE_CONTAINERS" ]; then \
|
||||
echo "Not running in VS Code devcontainer"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
clean: is-vscode
|
||||
rm -rf build
|
||||
|
||||
.PHONY: maps
|
||||
maps: is-vscode
|
||||
@echo "Downloading maps..."
|
||||
@mkdir -p .devcontainer/repo/maps
|
||||
@cd .devcontainer/repo/maps && wget -nc https://github.com/EQEmu/maps/archive/refs/heads/master.zip
|
||||
@cd .devcontainer/repo/maps && unzip -o master.zip
|
||||
@cd .devcontainer/repo/maps && mv maps-master/* .
|
||||
@cd .devcontainer/repo/maps && rm -rf maps-master
|
||||
@echo "Maps downloaded."
|
||||
|
||||
# Runs tests
|
||||
.PHONY: test
|
||||
test: is-vscode
|
||||
cd build/bin && ./tests
|
||||
|
||||
# Runs login binary
|
||||
.PHONY: login
|
||||
login: is-vscode check-mariadb
|
||||
cd build/bin && ./loginserver
|
||||
|
||||
.PHONY: hotfix
|
||||
hotfix: shared
|
||||
|
||||
# Runs shared_memory binary
|
||||
.PHONY: shared
|
||||
shared: is-vscode check-mariadb
|
||||
cd build/bin && ./shared_memory
|
||||
|
||||
# Runs zone binary
|
||||
.PHONY: zone
|
||||
zone: is-vscode check-mariadb
|
||||
@find build/bin/logs/zone/ -type f -name 'zone*.log' -exec rm -f {} +
|
||||
cd build/bin && ./zone
|
||||
|
||||
check-mariadb: is-vscode
|
||||
@if ! sudo service mariadb status | grep -q 'active (running)'; then \
|
||||
sudo service mariadb start; \
|
||||
fi
|
||||
|
||||
# Runs world binary
|
||||
.PHONY: world
|
||||
world: is-vscode check-mariadb
|
||||
@find build/bin/logs/ -type f -name 'world*.log' -exec rm -f {} +
|
||||
cd build/bin && ./world
|
||||
|
||||
# Runs ucs binary
|
||||
.PHONY: ucs
|
||||
ucs: is-vscode check-mariadb
|
||||
@find build/bin/logs/ -type f -name 'ucs*.log' -exec rm -f {} +
|
||||
cd build/bin && ./ucs
|
||||
|
||||
# Runs queryserv binary
|
||||
.PHONY: queryserv
|
||||
queryserv: is-vscode check-mariadb
|
||||
@find build/bin/logs/ -type f -name 'query_server*.log' -exec rm -f {} +
|
||||
cd build/bin && ./queryserv
|
||||
|
||||
reset-content:
|
||||
@echo "Resetting content tables in database peq..."
|
||||
cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_content.sql"
|
||||
|
||||
valgrind-%: is-vscode
|
||||
cd build/bin && valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=logs/$*.valgrind.log ./$*
|
||||
|
||||
# Start mariaDB standalone
|
||||
.PHONY: mariadb
|
||||
mariadb:
|
||||
@sudo service mariadb start
|
||||
|
||||
.PHONY: inject-mariadb
|
||||
inject-mariadb:
|
||||
-sudo service mariadb start
|
||||
-mkdir -p .devcontainer/cache/db/
|
||||
-sudo mariadb -e 'DROP DATABASE IF EXISTS peq;'
|
||||
-sudo mariadb -e 'CREATE DATABASE peq;'
|
||||
-sudo mariadb -e "CREATE USER IF NOT EXISTS 'peq'@'127.0.0.1' IDENTIFIED BY 'peqpass';"
|
||||
-sudo mariadb -e "GRANT ALL PRIVILEGES ON *.* TO 'peq'@'127.0.0.1';"
|
||||
ifeq (,$(wildcard .devcontainer/cache/db/db.sql.zip))
|
||||
@echo ".devcontainer/cache/db.sql.zip not found. Downloading database from https://db.eqemu.dev/latest"
|
||||
wget -nc https://db.eqemu.dev/latest -O .devcontainer/cache/db/db.sql.zip
|
||||
-cd .devcontainer/cache/db && unzip db.sql.zip
|
||||
endif
|
||||
@echo "Sourcing db may take a while, please wait..."
|
||||
|
||||
@cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_content.sql"
|
||||
@cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_login.sql"
|
||||
@cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_player.sql"
|
||||
@# deprecated cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_queryserv.sql"
|
||||
@cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_state.sql"
|
||||
@cd .devcontainer/cache/db/peq-dump && sudo mariadb --database peq -e "source create_tables_system.sql"
|
||||
|
||||
@echo "MariaDB is now injected."
|
||||
|
||||
.PHONY: gm-%
|
||||
gm-%: is-vscode
|
||||
sudo mariadb --database peq -e "UPDATE account SET status=255 WHERE name = '$*';"
|
||||
@echo "Account $* is now a GM. /camp to have it go into effect."
|
||||
|
||||
depends: is-vscode
|
||||
sudo apt install graphviz pip time
|
||||
pip3 install graphviz
|
||||
mkdir -p build/depends
|
||||
@if [ ! -f "build/depends/dependency_graph.py" ]; then \
|
||||
wget https://raw.githubusercontent.com/pvigier/dependency-graph/master/dependency_graph.py -O build/depends/dependency_graph.py; \
|
||||
fi
|
||||
@echo "Generating dependency graphs (This may take a while)..."
|
||||
@echo "Login..."
|
||||
time python3 build/depends/dependency_graph.py -f png login build/depends/login.dot
|
||||
@echo "World..."
|
||||
time python3 build/depends/dependency_graph.py -f png world build/depends/world.dot
|
||||
@echo "Zone..."
|
||||
time python3 build/depends/dependency_graph.py -f png zone build/depends/zone.dot
|
||||
@echo "Common..."
|
||||
time python3 build/depends/dependency_graph.py -f png common build/depends/common.dot
|
||||
|
||||
backup: is-vscode
|
||||
@mkdir -p build/bin/backup
|
||||
cd build/bin && ./world database:dump --compress --player-tables --state-tables --system-tables --query-serv-tables
|
||||
|
||||
restore-%: is-vscode
|
||||
@if [ -z "$*" ]; then \
|
||||
echo "Please provide a backup file to restore from. Example: make restore-backup.sql"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "Restoring from backup $*"
|
||||
@sudo mariadb --database peq -e "$*"
|
||||
|
||||
|
||||
cpu-zone: is-vscode
|
||||
ifeq ($(findstring .devcontainer,$(CURDIR)),.devcontainer)
|
||||
@echo "This makefile is not intended to be run from the .devcontainer directory."
|
||||
exit
|
||||
endif
|
||||
@cd build/bin && mkdir -p tmp
|
||||
cd build/bin && CPUPROFILE=prof.out ./zone
|
||||
|
||||
pprof-zone: is-vscode
|
||||
ifeq ($(findstring .devcontainer,$(CURDIR)),.devcontainer)
|
||||
@echo "This makefile is not intended to be run from the .devcontainer directory."
|
||||
exit
|
||||
endif
|
||||
cd build/bin && google-pprof --pdf zone prof.out > prof.pdf
|
||||
|
||||
pprof-gv-zone: is-vscode
|
||||
ifeq ($(findstring .devcontainer,$(CURDIR)),.devcontainer)
|
||||
@echo "This makefile is not intended to be run from the .devcontainer directory."
|
||||
exit
|
||||
endif
|
||||
cd build/bin && google-pprof --gv zone prof.out > prof.gv
|
||||
|
||||
heap-zone: is-vscode
|
||||
ifeq ($(findstring .devcontainer,$(CURDIR)),.devcontainer)
|
||||
@echo "This makefile is not intended to be run from the .devcontainer directory."
|
||||
exit
|
||||
endif
|
||||
@cd build/bin && mkdir -p tmp
|
||||
cd build/bin && HEAPPROFILE=prof.out ./zone
|
||||
|
||||
|
||||
.PHONY: pull
|
||||
pull:
|
||||
git pull
|
||||
@if [ ! -d "quests" ]; then git clone https://github.com/rebuildeq/quests.git quests; fi
|
||||
cd quests && git pull
|
||||
@if [ ! -d "eqemu-definitions" ]; then git clone https://github.com/xackery/eqemu-definitions.git eqemu-definitions; fi
|
||||
cd eqemu-definitions && git pull
|
||||
@@ -1,73 +0,0 @@
|
||||
{
|
||||
"server": {
|
||||
"zones": {
|
||||
"defaultstatus": "0",
|
||||
"ports": {
|
||||
"low": "7000",
|
||||
"high": "7400"
|
||||
}
|
||||
},
|
||||
"qsdatabase": {
|
||||
"host": "127.0.0.1",
|
||||
"port": "3306",
|
||||
"username": "peq",
|
||||
"password": "peqpass",
|
||||
"db": "peq"
|
||||
},
|
||||
"chatserver": {
|
||||
"port": "7778",
|
||||
"host": ""
|
||||
},
|
||||
"mailserver": {
|
||||
"host": "",
|
||||
"port": "7778"
|
||||
},
|
||||
"webinterface": {
|
||||
"port": "9081"
|
||||
},
|
||||
"world": {
|
||||
"longname": "New Devbox",
|
||||
"address": "192.168.1.100",
|
||||
"localaddress": "192.168.1.100",
|
||||
"loginserver1": {
|
||||
"account": "",
|
||||
"password": "",
|
||||
"legacy": 0,
|
||||
"host": "login.projecteq.net",
|
||||
"port": "5998"
|
||||
},
|
||||
"tcp": {
|
||||
"ip": "127.0.0.1",
|
||||
"port": "9001"
|
||||
},
|
||||
"telnet": {
|
||||
"ip": "0.0.0.0",
|
||||
"port": "9000",
|
||||
"enabled": "true"
|
||||
},
|
||||
"key": "random-generate-here",
|
||||
"http": {
|
||||
"port": "9080",
|
||||
"enabled": "true",
|
||||
"mimefile": "mime.types"
|
||||
},
|
||||
"shortname": "dev"
|
||||
},
|
||||
"database": {
|
||||
"db": "peq",
|
||||
"host": "127.0.0.1",
|
||||
"port": "3306",
|
||||
"username": "peq",
|
||||
"password": "peqpass"
|
||||
},
|
||||
"files": {
|
||||
"opcodes": "assets/patches/opcodes.conf",
|
||||
"mail_opcodes": "assets/patches/mail_opcodes.conf"
|
||||
},
|
||||
"directories": {
|
||||
"patches": "assets/patches/",
|
||||
"opcodes": "assets/patches/",
|
||||
"plugins": "quests/plugins/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"database": {
|
||||
"host": "127.0.0.1",
|
||||
"port": "3306",
|
||||
"db": "peq",
|
||||
"user": "peq",
|
||||
"password": "peqpass"
|
||||
},
|
||||
"account": {
|
||||
"auto_create_accounts": true
|
||||
},
|
||||
"worldservers": {
|
||||
"unregistered_allowed": true,
|
||||
"reject_duplicate_servers": false
|
||||
},
|
||||
"web_api": {
|
||||
"enabled": true,
|
||||
"port": 6000
|
||||
},
|
||||
"security": {
|
||||
"mode": 14,
|
||||
"allow_password_login": true,
|
||||
"allow_token_login": true
|
||||
},
|
||||
"logging": {
|
||||
"trace": false,
|
||||
"world_trace": false,
|
||||
"dump_packets_in": false,
|
||||
"dump_packets_out": false
|
||||
},
|
||||
"client_configuration": {
|
||||
"titanium_port": 5998,
|
||||
"titanium_opcodes": "assets/patches/login_opcodes.conf",
|
||||
"sod_port": 5999,
|
||||
"sod_opcodes": "assets/patches/login_opcodes_sod.conf"
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
|
||||
// README at: https://github.com/devcontainers/templates/tree/main/src/ubuntu
|
||||
{
|
||||
"name": "eqemu",
|
||||
"build": {
|
||||
"dockerfile": "Dockerfile.debian.dev"
|
||||
},
|
||||
"appPort": [
|
||||
"5998:5998/udp",
|
||||
"7000:7000/udp",
|
||||
"7001:7001/udp",
|
||||
"7002:7002/udp",
|
||||
"7003:7003/udp",
|
||||
"7004:7004/udp",
|
||||
"7005:7005/udp",
|
||||
"9000:9000/udp",
|
||||
"9001:9001/udp"
|
||||
],
|
||||
"forwardPorts": [
|
||||
3306
|
||||
],
|
||||
"remoteEnv": {
|
||||
"LOCALWSF": "${localWorkspaceFolder}",
|
||||
"CONTAINERWSF": "${containerWorkspaceFolder}"
|
||||
},
|
||||
"containerUser": "vscode",
|
||||
// add ptrace
|
||||
"runArgs": [
|
||||
"--cap-add=SYS_PTRACE",
|
||||
"--security-opt",
|
||||
"seccomp=unconfined"
|
||||
],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-vscode.cpptools-extension-pack",
|
||||
"vilicvane.sensitive-replace",
|
||||
"maattdd.gitless",
|
||||
"bibhasdn.unique-lines",
|
||||
"GitHub.copilot",
|
||||
"xackery.make-magic",
|
||||
"Gruntfuggly.todo-tree",
|
||||
"ms-vscode.cmake-tools",
|
||||
"sumneko.lua"
|
||||
],
|
||||
"settings": {
|
||||
"Lua.runtime.version": "Lua 5.1",
|
||||
"Lua.workspace.library": [
|
||||
"/src/repo/eqemu-definitions"
|
||||
],
|
||||
"Lua.diagnostics.disable": [
|
||||
"lowercase-global"
|
||||
],
|
||||
"cmake.statusbar.advanced": {
|
||||
"kit": {
|
||||
"visibility": "hidden"
|
||||
},
|
||||
"debug": {
|
||||
"visibility": "hidden"
|
||||
},
|
||||
"buildTarget": {
|
||||
"visibility": "compact"
|
||||
},
|
||||
"launch": {
|
||||
"visibility": "hidden"
|
||||
},
|
||||
"ctest": {
|
||||
"visibility": "icon"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
"source=${localWorkspaceFolder}/.devcontainer/Makefile,target=/src/Makefile,type=bind,consistency=cached"
|
||||
],
|
||||
|
||||
"workspaceFolder": "/src",
|
||||
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind,consistency=cached"
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
# EditorConfig is awesome: http://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
[*]
|
||||
insert_final_newline = true
|
||||
|
||||
# Matches multiple files with brace expansion notation
|
||||
# Set default charset
|
||||
[*.{js,py}]
|
||||
charset = utf-8
|
||||
|
||||
[*.cpp]
|
||||
indent_style = tab
|
||||
[*.h]
|
||||
indent_style = tab
|
||||
|
||||
# Tab indentation (no size specified)
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
+4
-1
@@ -20,4 +20,7 @@
|
||||
*.css text
|
||||
*.js text
|
||||
*.types text
|
||||
*.pdf binary
|
||||
|
||||
*.vcproj text merge=union
|
||||
*.csproj text merge=union
|
||||
*.sln text merge=union eol=crlf
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
name: Build
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- develop
|
||||
pull_request:
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Setup ccache
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
with:
|
||||
key: ${{ runner.os }}-ccache
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential ninja-build ccache uuid-dev
|
||||
|
||||
- name: Restore vcpkg Cache
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
build/vcpkg_installed
|
||||
submodules/vcpkg/downloads
|
||||
key: ${{ runner.os }}-vcpkg-${{ hashFiles('vcpkg.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-${{ hashFiles('vcpkg.json') }}-
|
||||
${{ runner.os }}-vcpkg-
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
|
||||
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
|
||||
-DEQEMU_BUILD_TESTS=ON \
|
||||
-DEQEMU_BUILD_LOGIN=ON \
|
||||
-DEQEMU_BUILD_LUA=ON \
|
||||
-DEQEMU_BUILD_PERL=ON \
|
||||
-DEQEMU_BUILD_CLIENT_FILES=ON
|
||||
|
||||
- name: Build
|
||||
run: cmake --build build --parallel
|
||||
|
||||
- name: Test
|
||||
working-directory: build
|
||||
run: ./bin/tests
|
||||
|
||||
windows:
|
||||
name: Windows
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DOWNLOADS: ${{ github.workspace }}\submodules\vcpkg\downloads
|
||||
VCPKG_BINARY_SOURCES: 'clear;files,${{ github.workspace }}\vcpkg_archives,readwrite'
|
||||
steps:
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Enable long paths
|
||||
run: git config --global core.longpaths true
|
||||
|
||||
- name: Setup MSVC environment
|
||||
uses: TheMrMilchmann/setup-msvc-dev@v4
|
||||
with:
|
||||
arch: x64
|
||||
|
||||
- name: Restore vcpkg Cache
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
${{ env.VCPKG_DOWNLOADS }}
|
||||
${{ github.workspace }}/vcpkg_archives
|
||||
key: ${{ runner.os }}-vcpkg-${{ hashFiles('vcpkg.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-
|
||||
|
||||
- name: Configure
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake -S . -B build -G "Visual Studio 17 2022" -A x64 `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DEQEMU_BUILD_TESTS=ON `
|
||||
-DEQEMU_BUILD_LOGIN=ON `
|
||||
-DEQEMU_BUILD_LUA=ON `
|
||||
-DEQEMU_BUILD_ZLIB=ON `
|
||||
-DEQEMU_BUILD_CLIENT_FILES=ON
|
||||
|
||||
- name: Build
|
||||
shell: pwsh
|
||||
run: cmake --build build --config Release --target ALL_BUILD -- /m
|
||||
|
||||
- name: Test
|
||||
working-directory: build
|
||||
run: ./bin/Release/tests.exe
|
||||
+17
-42
@@ -17,55 +17,30 @@
|
||||
*.out
|
||||
*.app
|
||||
|
||||
.bash_history
|
||||
|
||||
# CMake
|
||||
CMakeCache.txt
|
||||
CMakeFiles
|
||||
Makefile
|
||||
cmake_install.cmake
|
||||
install_manifest.txt
|
||||
[Bb]uild*/
|
||||
[Bb]uild/
|
||||
[Bb]uild32/
|
||||
[Bb]uild64/
|
||||
[Bb]uild_32/
|
||||
[Bb]uild_64/
|
||||
deploy/server/
|
||||
x64/
|
||||
x86/
|
||||
log/
|
||||
logs/
|
||||
vcpkg/
|
||||
perl/
|
||||
|
||||
.idea/*
|
||||
*cbp
|
||||
docker/db
|
||||
|
||||
submodules/*
|
||||
cmake-build-debug/
|
||||
|
||||
.nfs.*
|
||||
|
||||
# Visual Studio and CMAKE Generated Files
|
||||
/.vs/
|
||||
*.vcxproj
|
||||
*.vcxproj.filters
|
||||
*.vcxproj.user
|
||||
*.cmake
|
||||
*.ilk
|
||||
*.pdb
|
||||
*.sln
|
||||
*.dir/
|
||||
libs/
|
||||
bin/
|
||||
/Win32
|
||||
/x64
|
||||
/client_files/**/CMakeFiles/
|
||||
|
||||
.idea
|
||||
|
||||
# Clangd Generated Files.
|
||||
compile_flags.txt
|
||||
.cache/
|
||||
|
||||
# Build pipeline
|
||||
!utils/scripts/build/
|
||||
!utils/scripts/build/should-release/should-release
|
||||
!utils/scripts/build/should-release/should-release.exe
|
||||
|
||||
# CMake Files
|
||||
cmake-build-relwithdebinfo/*
|
||||
skill-caps.diff
|
||||
# Protobuf generated files
|
||||
*.pb.cc
|
||||
*.pb.h
|
||||
protobuf/csharp/*
|
||||
protobuf/go/*
|
||||
protobuf/java/*
|
||||
protobuf/python/*
|
||||
.vscode
|
||||
@@ -1,6 +0,0 @@
|
||||
[submodule "submodules/websocketpp"]
|
||||
path = submodules/websocketpp
|
||||
url = https://github.com/zaphoyd/websocketpp.git
|
||||
[submodule "submodules/vcpkg"]
|
||||
path = submodules/vcpkg
|
||||
url = https://github.com/microsoft/vcpkg.git
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
language: cpp
|
||||
compiler: gcc
|
||||
sudo: false
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- gcc-4.8
|
||||
- g++-4.8
|
||||
- libmysqlclient-dev
|
||||
- libperl-dev
|
||||
- libboost-dev
|
||||
- liblua5.1-0-dev
|
||||
- zlib1g-dev
|
||||
- uuid-dev
|
||||
- libssl-dev
|
||||
install:
|
||||
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.8" CC="gcc-4.8"; fi
|
||||
script:
|
||||
- cmake -G "Unix Makefiles" -DEQEMU_BUILD_TESTS=ON -DEQEMU_ENABLE_BOTS=ON -DEQEMU_BUILD_LOGIN=ON
|
||||
- make -j2
|
||||
- ./bin/tests
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- stable
|
||||
notifications:
|
||||
email: false
|
||||
irc:
|
||||
channels: "irc.eqemulator.net#eqemucoders"
|
||||
os: linux
|
||||
Vendored
-23
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${default}",
|
||||
"${workspaceFolder}/submodules/fmt/include",
|
||||
"${workspaceFolder}/submodules/cereal/include",
|
||||
"${workspaceFolder}/submodules/glm",
|
||||
"${workspaceFolder}/submodules/libuv/include"
|
||||
],
|
||||
"defines": [
|
||||
"LUA_EQEMU=1"
|
||||
],
|
||||
"compilerPath": "/usr/bin/gcc",
|
||||
"cStandard": "c17",
|
||||
"cppStandard": "gnu++17",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.cmake-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
Vendored
-173
@@ -1,173 +0,0 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "(gdb) attach",
|
||||
"type": "cppdbg",
|
||||
"request": "attach",
|
||||
"program": "${workspaceFolder}/build/bin/world",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) shared_memory",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/shared_memory",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) world",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/world",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) zone",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/zone",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"args": [
|
||||
"",
|
||||
],
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) zone neriakb",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/zone",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"args": [
|
||||
"neriakb",
|
||||
],
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) login",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/loginserver",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) ucs",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/ucs",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "(gdb) queryserv",
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/build/bin/queryserv",
|
||||
"cwd": "${workspaceFolder}/build/bin",
|
||||
"MIMode": "gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Enable pretty-printing for gdb",
|
||||
"text": "-enable-pretty-printing",
|
||||
"ignoreFailures": true
|
||||
},
|
||||
{
|
||||
"description": "Set Disassembly Flavor to Intel",
|
||||
"text": "-gdb-set disassembly-flavor intel",
|
||||
"ignoreFailures": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
-111
@@ -1,111 +0,0 @@
|
||||
{
|
||||
"editor.detectIndentation": false,
|
||||
"editor.insertSpaces": false,
|
||||
"editor.tabSize": 4,
|
||||
"editor.autoIndent": "full",
|
||||
"editor.trimAutoWhitespace": true,
|
||||
"files.trimTrailingWhitespace": true,
|
||||
//"editor.formatOnSave": true,
|
||||
"search.exclude": {
|
||||
"dependencies": false,
|
||||
},
|
||||
"C_Cpp.default.includePath": [
|
||||
"/usr/include/x86_64-linux-gnu",
|
||||
"/usr/include/lua5.2",
|
||||
"/usr/include/mariadb",
|
||||
"${workspaceFolder}/dependencies/curl_x64/include",
|
||||
"${workspaceFolder}/dependencies/fmt/include",
|
||||
"${workspaceFolder}/dependencies/glm",
|
||||
"${workspaceFolder}/dependencies/libuv/include",
|
||||
"${workspaceFolder}/dependencies/sol2",
|
||||
"${workspaceFolder}/dependencies/zlibng"
|
||||
],
|
||||
"telemetry.enableTelemetry": false,
|
||||
"cmake.skipConfigureIfCachePresent": true,
|
||||
"cmake.configureOnOpen": false,
|
||||
"files.associations": {
|
||||
"*.ipp": "cpp",
|
||||
"functional": "cpp",
|
||||
"string": "cpp",
|
||||
"iostream": "cpp",
|
||||
"map": "cpp",
|
||||
"fstream": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"utility": "cpp",
|
||||
"cstring": "cpp",
|
||||
"*.tcc": "cpp",
|
||||
"cctype": "cpp",
|
||||
"clocale": "cpp",
|
||||
"cmath": "cpp",
|
||||
"csignal": "cpp",
|
||||
"cstdarg": "cpp",
|
||||
"cstddef": "cpp",
|
||||
"cstdio": "cpp",
|
||||
"cstdlib": "cpp",
|
||||
"ctime": "cpp",
|
||||
"cwchar": "cpp",
|
||||
"cwctype": "cpp",
|
||||
"any": "cpp",
|
||||
"array": "cpp",
|
||||
"atomic": "cpp",
|
||||
"strstream": "cpp",
|
||||
"bit": "cpp",
|
||||
"bitset": "cpp",
|
||||
"chrono": "cpp",
|
||||
"codecvt": "cpp",
|
||||
"compare": "cpp",
|
||||
"complex": "cpp",
|
||||
"concepts": "cpp",
|
||||
"condition_variable": "cpp",
|
||||
"coroutine": "cpp",
|
||||
"cstdint": "cpp",
|
||||
"deque": "cpp",
|
||||
"forward_list": "cpp",
|
||||
"list": "cpp",
|
||||
"set": "cpp",
|
||||
"unordered_map": "cpp",
|
||||
"unordered_set": "cpp",
|
||||
"vector": "cpp",
|
||||
"exception": "cpp",
|
||||
"algorithm": "cpp",
|
||||
"iterator": "cpp",
|
||||
"memory": "cpp",
|
||||
"memory_resource": "cpp",
|
||||
"numeric": "cpp",
|
||||
"optional": "cpp",
|
||||
"random": "cpp",
|
||||
"ratio": "cpp",
|
||||
"regex": "cpp",
|
||||
"source_location": "cpp",
|
||||
"string_view": "cpp",
|
||||
"system_error": "cpp",
|
||||
"tuple": "cpp",
|
||||
"future": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"iomanip": "cpp",
|
||||
"iosfwd": "cpp",
|
||||
"istream": "cpp",
|
||||
"limits": "cpp",
|
||||
"mutex": "cpp",
|
||||
"new": "cpp",
|
||||
"numbers": "cpp",
|
||||
"ostream": "cpp",
|
||||
"semaphore": "cpp",
|
||||
"sstream": "cpp",
|
||||
"stdexcept": "cpp",
|
||||
"stop_token": "cpp",
|
||||
"streambuf": "cpp",
|
||||
"thread": "cpp",
|
||||
"cfenv": "cpp",
|
||||
"cinttypes": "cpp",
|
||||
"typeindex": "cpp",
|
||||
"typeinfo": "cpp",
|
||||
"valarray": "cpp",
|
||||
"variant": "cpp",
|
||||
"csetjmp": "cpp",
|
||||
"charconv": "cpp",
|
||||
"format": "cpp",
|
||||
"ranges": "cpp",
|
||||
"span": "cpp"
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
# Guide To Building From Source Without Installer
|
||||
|
||||
This guide is far from exhaustive, you should expect to have some experience with building C++ code before considering compiling the code from scratch. You should instead consider using the installer scripts if you don't want to hack on the code directly.
|
||||
|
||||
### CMake
|
||||
|
||||
EQEmu uses CMake as the build system on all platforms. You will need CMake 3.20 or higher to build from source.
|
||||
|
||||
### Dependencies
|
||||
|
||||
The following libraries are required to build from source:
|
||||
- uuid (unix)
|
||||
|
||||
The following libraries are not strictly required but in many cased recommended.
|
||||
- [Perl](https://www.perl.org/ "Perl") (Required for Perl Quest Scripting)
|
||||
|
||||
##### Windows
|
||||
If you wish to use Perl then you should use whichever version of Perl you have installed on the target system.
|
||||
|
||||
##### Linux
|
||||
For Linux you simply can install the dependencies from your package manager, below is an example of doing it on Ubuntu using apt-get.
|
||||
|
||||
sudo apt-get install libperl-dev uuid-dev
|
||||
|
||||
### Running CMake
|
||||
|
||||
##### Windows
|
||||
The following is a modified command our automated build server uses to run CMake via the release vcpkg export and its toolchain file.
|
||||
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -G "Visual Studio 15 2022 Win64" -DEQEMU_BUILD_TESTS=ON -DEQEMU_BUILD_LOGIN=ON ..
|
||||
|
||||
##### Linux
|
||||
Similarly to Windows running CMake on Linux is simple it just uses a different generator.
|
||||
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -G "Unix Makefiles" -DEQEMU_BUILD_TESTS=ON -DEQEMU_BUILD_LOGIN=ON ..
|
||||
|
||||
### Building
|
||||
|
||||
##### Windows
|
||||
Inside the build directory a file EQEmu.sln should be produced by a successful run of the CMake command. You can either open this with Visual Studio or build it directly with MSBuild via the command line.
|
||||
|
||||
msbuild EQEmu.sln /p:Configuration=Release
|
||||
|
||||
##### Linux
|
||||
From the build directory you can simply call make to build.
|
||||
|
||||
For example.
|
||||
|
||||
make -j4
|
||||
-5157
File diff suppressed because it is too large
Load Diff
+427
-159
@@ -1,192 +1,460 @@
|
||||
cmake_minimum_required(VERSION 3.20.0)
|
||||
#EQEmu CMake
|
||||
#Variables used:
|
||||
#EQEMU_DISABLE_CRT_SECURE_WARNINGS
|
||||
#EQEMU_FAST_FLOATINGPOINT
|
||||
#EQEMU_ENABLE_CRASH_LOGGING
|
||||
#EQEMU_DISABLE_SAFESEH
|
||||
#EQEMU_BUILD_MSVC_MP
|
||||
#EQEMU_DEBUG_LEVEL
|
||||
#EQEMU_LOG_LEVEL_STATUS
|
||||
#EQEMU_LOG_LEVEL_NORMAL
|
||||
#EQEMU_LOG_LEVEL_ERROR
|
||||
#EQEMU_LOG_LEVEL_DEBUG
|
||||
#EQEMU_LOG_LEVEL_QUEST
|
||||
#EQEMU_LOG_LEVEL_COMMANDS
|
||||
#EQEMU_LOG_LEVEL_CRASH
|
||||
#EQEMU_DEPOP_INVALIDATES_CACHE
|
||||
#EQEMU_ENABLE_BOTS
|
||||
#EQEMU_DISABLE_LOGSYS
|
||||
#EQEMU_COMMANDS_LOGGING
|
||||
#EQEMU_BUILD_SERVER
|
||||
#EQEMU_BUILD_LOGIN
|
||||
#EQEMU_BUILD_TESTS
|
||||
#EQEMU_BUILD_PERL
|
||||
#EQEMU_BUILD_LUA
|
||||
#EQEMU_SANITIZE_LUA_LIBS
|
||||
#EQEMU_BUILD_CLIENT_FILES
|
||||
#EQEMU_USE_MAP_MMFS
|
||||
#EQEMU_MAP_DIR
|
||||
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/" ${CMAKE_MODULE_PATH})
|
||||
#We set a fairly new version (as of 2013) because I found finding perl was a bit... buggy on older ones
|
||||
#Can change this if you really want but you should upgrade!
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.12)
|
||||
|
||||
if(NOT CMAKE_TOOLCHAIN_FILE)
|
||||
if(DEFINED ENV{VCPKG_ROOT})
|
||||
message(STATUS "Using vcpkg from VCPKG_ROOT")
|
||||
set(CMAKE_TOOLCHAIN_FILE
|
||||
"$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
|
||||
CACHE FILEPATH "Vcpkg toolchain file"
|
||||
)
|
||||
else()
|
||||
message(STATUS "Using vcpkg submodule")
|
||||
set(CMAKE_TOOLCHAIN_FILE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/submodules/vcpkg/scripts/buildsystems/vcpkg.cmake"
|
||||
CACHE FILEPATH "Vcpkg toolchain file"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
#FindMySQL is located here so lets make it so CMake can find it
|
||||
SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/" ${CMAKE_MODULE_PATH})
|
||||
|
||||
# Uncomment to generate just the standard Debug and Release configurations
|
||||
#set(CMAKE_BUILD_TYPE "Debug")
|
||||
#set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE)
|
||||
#Our project name is EQEmu
|
||||
PROJECT(EQEmu)
|
||||
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
#Default build type is set to RelWithDebInfo for generators that honor that like makefiles
|
||||
IF(NOT CMAKE_BUILD_TYPE)
|
||||
SET(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE)
|
||||
ENDIF(NOT CMAKE_BUILD_TYPE)
|
||||
|
||||
set(dummy "${CMAKE_C_COMPILER}")
|
||||
#Add our various windows definitions
|
||||
IF(MSVC OR MINGW)
|
||||
ADD_DEFINITIONS(-D_WINDOWS)
|
||||
IF(CMAKE_CL_64)
|
||||
ADD_DEFINITIONS(-DWIN64)
|
||||
ELSE(CMAKE_CL_64)
|
||||
ADD_DEFINITIONS(-DWIN32)
|
||||
ENDIF(CMAKE_CL_64)
|
||||
ENDIF(MSVC OR MINGW)
|
||||
|
||||
project(EQEmu
|
||||
VERSION 24.10.3
|
||||
LANGUAGES CXX
|
||||
)
|
||||
# include dirs are universal
|
||||
SET(NATS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/nats")
|
||||
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
#Try to find protobuf automatically
|
||||
FIND_PACKAGE(Protobuf QUIET)
|
||||
#IF(NOT PROTOBUF_FOUND)
|
||||
SET(Protobuf_DIR "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/protobuf" CACHE PATH "Root protobuf directory" FORCE)
|
||||
SET(PROTOBUF_FOUND TRUE CACHE BOOL "" FORCE)
|
||||
IF(MSVC)
|
||||
IF(CMAKE_CL_64)
|
||||
SET(Protobuf_INCLUDE_DIR "${Protobuf_DIR}/windows/x64/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_SRC_ROOT_FOLDER "${Protobuf_DIR}/windows/x64/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_PROTOC_EXECUTABLE "${Protobuf_DIR}/windows/x64/bin/protoc.exe" CACHE PATH "Executable path" FORCE)
|
||||
SET(Protobuf_LIBRARY_DEBUG "${Protobuf_DIR}/windows/x64/lib/libprotobufd.lib" CACHE PATH "Root protobuf directory" FORCE)
|
||||
SET(Protobuf_LIBRARY_RELEASE "${Protobuf_DIR}/windows/x64/lib/libprotobufd.lib" CACHE PATH "Root protobuf directory" FORCE)
|
||||
ELSE(CMAKE_CL_64)
|
||||
SET(Protobuf_INCLUDE_DIR "${Protobuf_DIR}/windows/x86/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_SRC_ROOT_FOLDER "${Protobuf_DIR}/windows/x86/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_PROTOC_EXECUTABLE "${Protobuf_DIR}/windows/x86/bin/protoc.exe" CACHE PATH "Executable path" FORCE)
|
||||
SET(Protobuf_LIBRARY_DEBUG "${Protobuf_DIR}/windows/x86/lib/libprotobufd.lib" CACHE PATH "Root protobuf directory" FORCE)
|
||||
SET(Protobuf_LIBRARY_RELEASE "${Protobuf_DIR}/windows/x86/lib/libprotobufd.lib" CACHE PATH "Root protobuf directory" FORCE)
|
||||
ENDIF(CMAKE_CL_64)
|
||||
ELSE(MSVC)
|
||||
IF(CMAKE_CL_64)
|
||||
SET(Protobuf_INCLUDE_DIR "${Protobuf_DIR}/linux/x86/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_SRC_ROOT_FOLDER "${Protobuf_DIR}/linux/x86/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_PROTOC_EXECUTABLE "${Protobuf_DIR}/linux/x86/bin/protoc" CACHE PATH "Executable path" FORCE)
|
||||
SET(Protobuf_LIBRARY_DEBUG "${Protobuf_DIR}/linux/x86/lib/libprotobuf.so.16" CACHE PATH "Root protobuf directory" FORCE)
|
||||
SET(Protobuf_LIBRARY_RELEASE "${Protobuf_DIR}/linux/x86/lib/libprotobuf.so.16" CACHE PATH "Root protobuf directory" FORCE)
|
||||
ELSE(CMAKE_CL_64)
|
||||
SET(Protobuf_INCLUDE_DIR "${Protobuf_DIR}/linux/x64/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_SRC_ROOT_FOLDER "${Protobuf_DIR}/linux/x64/include" CACHE PATH "Include dir" FORCE)
|
||||
SET(Protobuf_PROTOC_EXECUTABLE "${Protobuf_DIR}/linux/x64/bin/protoc" CACHE PATH "Executable path" FORCE)
|
||||
SET(Protobuf_LIBRARY_DEBUG "${Protobuf_DIR}/linux/x64/lib/libprotobuf.so.16" CACHE PATH "Root protobuf directory" FORCE)
|
||||
SET(Protobuf_LIBRARY_RELEASE "${Protobuf_DIR}/linux/x64/lib/libprotobuf.so.16" CACHE PATH "Root protobuf directory" FORCE)
|
||||
ENDIF(CMAKE_CL_64)
|
||||
ENDIF()
|
||||
IF(NOT Protobuf_LIBRARY_DEBUG)
|
||||
MESSAGE(ERROR "Protobuf library was not found in ${Protobuf_LIBRARY_DEBUG}. Please download the depenencies and extract them as noted.")
|
||||
ENDIF()
|
||||
FILE(COPY ${Protobuf_LIBRARY_DEBUG} DESTINATION ${CMAKE_HOME_DIRECTORY}/bin)
|
||||
#ENDIF()
|
||||
|
||||
#explicitly set CMP0167 for Find Boost
|
||||
if(POLICY CMP0167)
|
||||
cmake_policy(SET CMP0167 NEW)
|
||||
endif()
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${Protobuf_INCLUDE_DIR}")
|
||||
|
||||
option(EQEMU_BUILD_PCH "Build with precompiled headers" ON)
|
||||
IF(MSVC)
|
||||
IF(CMAKE_CL_64)
|
||||
SET(NATS_INCLUDE_DIR "${NATS_ROOT}/windows/x64/include")
|
||||
SET(NATS_LIBRARY_DEBUG "${NATS_ROOT}/windows/x64/lib/nats.lib")
|
||||
ELSE(CMAKE_CL_64)
|
||||
SET(NATS_INCLUDE_DIR "${NATS_ROOT}/windows/x86/include")
|
||||
SET(NATS_LIBRARY_DEBUG "${NATS_ROOT}/windows/x86/lib/nats.lib")
|
||||
ENDIF(CMAKE_CL_64)
|
||||
ELSE(MSVC)
|
||||
IF(CMAKE_CL_64)
|
||||
SET(NATS_INCLUDE_DIR "${NATS_ROOT}/linux/x86/include")
|
||||
SET(NATS_LIBRARY_DEBUG "${NATS_ROOT}/linux/x86/lib/libnats.so")
|
||||
ELSE(CMAKE_CL_64)
|
||||
SET(NATS_INCLUDE_DIR "${NATS_ROOT}/linux/x64/include")
|
||||
SET(NATS_LIBRARY_DEBUG "${NATS_ROOT}/linux/x64/lib/libnats.so")
|
||||
ENDIF(CMAKE_CL_64)
|
||||
ENDIF()
|
||||
IF(${NATS_LIBRARY_DEBUG})
|
||||
MESSAGE(ERROR " NATS library was not found in ${NATS_LIBRARY_DEBUG}/libnats.so. Please download the depenencies and extract them as noted.")
|
||||
ENDIF()
|
||||
FILE(COPY ${NATS_LIBRARY_DEBUG} DESTINATION ${CMAKE_HOME_DIRECTORY}/bin)
|
||||
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
IF(MSVC)
|
||||
#Set our default locations for zlib/mysql based on x86/x64
|
||||
IF(CMAKE_CL_64)
|
||||
SET(ZLIB_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/zlib_x64")
|
||||
SET(MYSQL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/mysql_x64")
|
||||
SET(LUA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/luaj_x64")
|
||||
SET(OPENSSL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/openssl_x64")
|
||||
SET(SODIUM_INCLUDE_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/include")
|
||||
IF(MSVC_VERSION GREATER 1800)
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/x64/Release/v140/dynamic")
|
||||
ELSEIF(MSVC_VERSION EQUAL 1800)
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/x64/Release/v120/dynamic")
|
||||
ELSE()
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/x64/Release/v110/dynamic")
|
||||
ENDIF()
|
||||
ELSE(CMAKE_CL_64)
|
||||
SET(ZLIB_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/zlib_x86")
|
||||
SET(MYSQL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/mysql_x86")
|
||||
SET(LUA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/luaj_x86")
|
||||
SET(SODIUM_INCLUDE_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/include")
|
||||
SET(OPENSSL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/openssl_x86")
|
||||
SET(NATS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/nats_x86")
|
||||
IF(MSVC_VERSION GREATER 1800)
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/Win32/Release/v140/dynamic")
|
||||
ELSEIF(MSVC_VERSION EQUAL 1800)
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/Win32/Release/v120/dynamic")
|
||||
ELSE()
|
||||
SET(SODIUM_LIBRARY_HINTS "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/libsodium/Win32/Release/v110/dynamic")
|
||||
ENDIF()
|
||||
ENDIF(CMAKE_CL_64)
|
||||
|
||||
if(MSVC)
|
||||
# Always build with debug symbols
|
||||
add_compile_options("$<$<CONFIG:RELEASE>:/Zi>")
|
||||
add_link_options("$<$<CONFIG:RELEASE>:/DEBUG /OPT:REF /OPT:ICF>")
|
||||
#disable CRT warnings on windows cause they're annoying as shit and we use C functions everywhere
|
||||
OPTION(EQEMU_DISABLE_CRT_SECURE_WARNINGS "Disable Secure CRT Warnings" ON)
|
||||
IF(EQEMU_DISABLE_CRT_SECURE_WARNINGS)
|
||||
ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS)
|
||||
ENDIF(EQEMU_DISABLE_CRT_SECURE_WARNINGS)
|
||||
|
||||
add_compile_options(/bigobj /MP)
|
||||
add_compile_definitions(_CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN CRASH_LOGGING)
|
||||
#fast FP if you'd like it
|
||||
OPTION(EQEMU_FAST_FLOATINGPOINT "Use MSVC /fp:fast option" ON)
|
||||
IF(EQEMU_FAST_FLOATINGPOINT)
|
||||
ADD_DEFINITIONS(/fp:fast)
|
||||
ENDIF(EQEMU_FAST_FLOATINGPOINT)
|
||||
|
||||
option(EQEMU_MSVC_DEBUG_CRT "Use the debug CRT on MSVC debug builds" OFF)
|
||||
if(EQEMU_MSVC_DEBUG_CRT)
|
||||
add_compile_definitions(_CRT_DBG_MAP_ALLOC)
|
||||
endif()
|
||||
else()
|
||||
add_compile_options("$<$<CONFIG:RELEASE>:-g>")
|
||||
#crash logging currently only works on windows x86/x64
|
||||
OPTION(EQEMU_ENABLE_CRASH_LOGGING "Enable crash logging" ON)
|
||||
IF(EQEMU_ENABLE_CRASH_LOGGING)
|
||||
ADD_DEFINITIONS(-DCRASH_LOGGING)
|
||||
ENDIF(EQEMU_ENABLE_CRASH_LOGGING)
|
||||
|
||||
add_compile_definitions(HAS_UNION_SEMUN)
|
||||
endif()
|
||||
#Disable safe SEH or not?
|
||||
OPTION(EQEMU_DISABLE_SAFESEH "Disable Safe SEH (Needed for Strawberry Perl)" OFF)
|
||||
IF(EQEMU_DISABLE_SAFESEH)
|
||||
SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /SAFESEH:NO")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /SAFESEH:NO")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /SAFESEH:NO")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /SAFESEH:NO")
|
||||
SET(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} /SAFESEH:NO")
|
||||
SET(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "${CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL} /SAFESEH:NO")
|
||||
SET(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /SAFESEH:NO")
|
||||
SET(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /SAFESEH:NO")
|
||||
SET(CMAKE_MODULE_LINKER_FLAGS_DEBUG "${CMAKE_MODULE_LINKER_FLAGS_DEBUG} /SAFESEH:NO")
|
||||
SET(CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL "${CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL} /SAFESEH:NO")
|
||||
SET(CMAKE_MODULE_LINKER_FLAGS_RELEASE "${CMAKE_MODULE_LINKER_FLAGS_RELEASE} /SAFESEH:NO")
|
||||
SET(CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO} /SAFESEH:NO")
|
||||
ENDIF(EQEMU_DISABLE_SAFESEH)
|
||||
|
||||
OPTION(EQEMU_BUILD_MSVC_MP "Enable build with multiple processes." ON)
|
||||
IF(EQEMU_BUILD_MSVC_MP)
|
||||
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
|
||||
ENDIF(EQEMU_BUILD_MSVC_MP)
|
||||
|
||||
#We want to compile /MT not /MD so we change that
|
||||
FOREACH(flag_var CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO)
|
||||
IF(${flag_var} MATCHES "/MD")
|
||||
STRING(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
|
||||
ENDIF(${flag_var} MATCHES "/MD")
|
||||
ENDFOREACH(flag_var)
|
||||
|
||||
ADD_DEFINITIONS(-DNOMINMAX)
|
||||
ELSE(MSVC)
|
||||
|
||||
|
||||
#Normally set by perl but we don't use the perl flags anymore so we set it.
|
||||
ADD_DEFINITIONS(-DHAS_UNION_SEMUN)
|
||||
ENDIF(MSVC)
|
||||
|
||||
#FreeBSD support
|
||||
if(UNIX)
|
||||
if(CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
|
||||
add_compile_definitions(FREEBSD)
|
||||
add_compile_definitions(_GLIBCXX_USE_C99)
|
||||
set(FREEBSD TRUE)
|
||||
endif()
|
||||
if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
|
||||
add_compile_definitions(DARWIN)
|
||||
set(DARWIN TRUE)
|
||||
endif()
|
||||
endif()
|
||||
IF(UNIX)
|
||||
IF(CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
|
||||
ADD_DEFINITIONS(-DFREEBSD)
|
||||
ADD_DEFINITIONS(-D_GLIBCXX_USE_C99)
|
||||
SET(FREEBSD TRUE)
|
||||
ENDIF(CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
|
||||
IF(CMAKE_SYSTEM_NAME MATCHES "Darwin")
|
||||
ADD_DEFINITIONS(-DDARWIN)
|
||||
SET(DARWIN TRUE)
|
||||
ENDIF(CMAKE_SYSTEM_NAME MATCHES "Darwin")
|
||||
ENDIF(UNIX)
|
||||
|
||||
find_package(Boost REQUIRED COMPONENTS dynamic_bitset foreach tuple CONFIG REQUIRED)
|
||||
find_package(cereal CONFIG REQUIRED)
|
||||
find_package(fmt CONFIG REQUIRED)
|
||||
find_package(glm CONFIG REQUIRED)
|
||||
find_package(unofficial-libmariadb CONFIG REQUIRED)
|
||||
find_package(libuv CONFIG REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(recastnavigation CONFIG REQUIRED)
|
||||
find_package(ZLIB REQUIRED)
|
||||
find_package(LuaJit REQUIRED)
|
||||
find_package(unofficial-sodium CONFIG REQUIRED)
|
||||
find_package(PerlLibs)
|
||||
#debug level, 5 is default. Most people wont ever change this but it's there if you want to
|
||||
SET(EQEMU_DEBUG_LEVEL 5 CACHE STRING "EQEmu debug level:
|
||||
0 - Quiet mode Errors to file Status and Normal ignored
|
||||
1 - Status and Normal to console, Errors to logfile
|
||||
2 - Status, Normal, and Error to console and logfile
|
||||
3 - Light debug release errors and status
|
||||
4 - Moderate debug release errors and status
|
||||
5 - Maximum debug release errors and status
|
||||
10 - More errors than you ever wanted to see"
|
||||
)
|
||||
|
||||
message(STATUS "**************************************************")
|
||||
message(STATUS "* Library Detection *")
|
||||
message(STATUS "**************************************************")
|
||||
SET(EQEMU_LOG_LEVEL_STATUS 2 CACHE STRING "EQEmu logging level for [Status]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
if(MARIADB_FOUND)
|
||||
message(STATUS "* MariaDB: FOUND *")
|
||||
else()
|
||||
message(STATUS "* MariaDB: MISSING *")
|
||||
endif()
|
||||
SET(EQEMU_LOG_LEVEL_NORMAL 3 CACHE STRING "EQEmu logging level for [Normal]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
if(ZLIB_FOUND)
|
||||
message(STATUS "* ZLIB: FOUND *")
|
||||
else()
|
||||
message(STATUS "* ZLIB: MISSING *")
|
||||
endif()
|
||||
SET(EQEMU_LOG_LEVEL_ERROR 2 CACHE STRING "EQEmu logging level for [Error]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
if(LuaJit_FOUND)
|
||||
message(STATUS "* LuaJIT: FOUND *")
|
||||
else()
|
||||
message(STATUS "* LuaJIT: MISSING *")
|
||||
endif()
|
||||
SET(EQEMU_LOG_LEVEL_DEBUG 3 CACHE STRING "EQEmu logging level for [Debug]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
if(PerlLibs_FOUND)
|
||||
message(STATUS "* Perl: FOUND *")
|
||||
else()
|
||||
message(STATUS "* Perl: MISSING *")
|
||||
endif()
|
||||
SET(EQEMU_LOG_LEVEL_QUEST 2 CACHE STRING "EQEmu logging level for [Quest]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
if(OpenSSL_FOUND)
|
||||
message(STATUS "* OpenSSL: FOUND *")
|
||||
else()
|
||||
message(STATUS "* OpenSSL: MISSING *")
|
||||
endif()
|
||||
SET(EQEMU_LOG_LEVEL_COMMANDS 1 CACHE STRING "EQEmu logging level for [Commands]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
message(STATUS "PERL_INCLUDE_PATH: ${PERL_INCLUDE_PATH}")
|
||||
message(STATUS "PERL_LIBRARY: ${PERL_LIBRARY}")
|
||||
message(STATUS "PERL_INCLUDE_DIR: ${PERL_INCLUDE_DIR}")
|
||||
message(STATUS "PERL_INCLUDE_DIRS: ${PERL_INCLUDE_DIRS}")
|
||||
message(STATUS "PERL_LIBRARIES: ${PERL_LIBRARIES}")
|
||||
message(STATUS "PERL_VERSION: ${PERL_VERSION}")
|
||||
message(STATUS "**************************************************")
|
||||
SET(EQEMU_LOG_LEVEL_CRASH 3 CACHE STRING "EQEmu logging level for [Crash]:
|
||||
0 - Disabled
|
||||
1 - Ouput to File Enabled
|
||||
2 - Output to stdout Enabled
|
||||
3 - Output to File and stdout Enabled
|
||||
8 - Output to stderr Enabled
|
||||
9 - Output to File and stderr Enabled
|
||||
11 - Output to File, stdout and stderr Enabled"
|
||||
)
|
||||
|
||||
#options
|
||||
option(EQEMU_BUILD_SERVER "Build the game server." ON)
|
||||
option(EQEMU_BUILD_LOGIN "Build the login server." ON)
|
||||
option(EQEMU_BUILD_TESTS "Build utility tests." OFF)
|
||||
option(EQEMU_BUILD_CLIENT_FILES "Build Client Import/Export Data Programs." ON)
|
||||
MARK_AS_ADVANCED(EQEMU_LOG_LEVEL_STATUS EQEMU_LOG_LEVEL_NORMAL EQEMU_LOG_LEVEL_ERROR EQEMU_LOG_LEVEL_DEBUG EQEMU_LOG_LEVEL_QUEST EQEMU_LOG_LEVEL_COMMANDS EQEMU_LOG_LEVEL_CRASH)
|
||||
|
||||
if(PerlLibs_FOUND)
|
||||
option(EQEMU_BUILD_PERL "Build Perl parser." ON)
|
||||
#NPC Types Cache Behavior
|
||||
OPTION(EQEMU_DEPOP_INVALIDATES_CACHE "#repop invalidates the npc_types cache (will cause a larger database hit on #repop but is more convienent)." ON)
|
||||
|
||||
if(EQEMU_BUILD_PERL)
|
||||
set(PERL_LIBRARY_TYPE " Perl")
|
||||
else()
|
||||
set(PERL_LIBRARY_TYPE " Missing")
|
||||
endif()
|
||||
else()
|
||||
set(PERL_LIBRARY_TYPE "Disabled")
|
||||
endif()
|
||||
#Bots are a compile time option so on/off
|
||||
OPTION(EQEMU_ENABLE_BOTS "Enable Bots" OFF)
|
||||
|
||||
message(STATUS "")
|
||||
message(STATUS "**************************************************")
|
||||
message(STATUS "* Library Usage *")
|
||||
message(STATUS "**************************************************")
|
||||
message(STATUS "* Database: MariaDB *")
|
||||
message(STATUS "* TLS: OpenSSL *")
|
||||
message(STATUS "* Lua: LuaJIT *")
|
||||
message(STATUS "* Perl: ${PERL_LIBRARY_TYPE} *")
|
||||
message(STATUS "* zlib: ZLIB *")
|
||||
message(STATUS "**************************************************")
|
||||
#Disable entire _mlog system (excludes trade/command logs)
|
||||
OPTION(EQEMU_DISABLE_LOGSYS "Disable Logging INI System" ON)
|
||||
|
||||
#Enable GM Command log system
|
||||
OPTION(EQEMU_COMMANDS_LOGGING "Enable GM Command logs" ON)
|
||||
|
||||
IF(EQEMU_COMMANDS_LOGGING)
|
||||
ADD_DEFINITIONS(-DCOMMANDS_LOGGING)
|
||||
ENDIF(EQEMU_COMMANDS_LOGGING)
|
||||
|
||||
IF(EQEMU_DISABLE_LOGSYS)
|
||||
ADD_DEFINITIONS(-DDISABLE_LOGSYS)
|
||||
ENDIF(EQEMU_DISABLE_LOGSYS)
|
||||
|
||||
IF(EQEMU_ENABLE_BOTS)
|
||||
ADD_DEFINITIONS(-DBOTS)
|
||||
ENDIF(EQEMU_ENABLE_BOTS)
|
||||
|
||||
#What to build
|
||||
OPTION(EQEMU_BUILD_SERVER "Build the game server." ON)
|
||||
OPTION(EQEMU_BUILD_LOGIN "Build the login server." OFF)
|
||||
OPTION(EQEMU_BUILD_HC "Build the headless client." OFF)
|
||||
OPTION(EQEMU_BUILD_TESTS "Build utility tests." OFF)
|
||||
OPTION(EQEMU_BUILD_PERL "Build Perl parser." ON)
|
||||
OPTION(EQEMU_BUILD_LUA "Build Lua parser." ON)
|
||||
OPTION(EQEMU_BUILD_CLIENT_FILES "Build Client Import/Export Data Programs." ON)
|
||||
|
||||
#C++11 stuff
|
||||
IF(NOT MSVC)
|
||||
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
|
||||
IF("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
|
||||
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-reserved-user-defined-literal")
|
||||
ENDIF()
|
||||
ENDIF(NOT MSVC)
|
||||
|
||||
#Various definitions
|
||||
IF(EQEMU_BUILD_PERL)
|
||||
ADD_DEFINITIONS(-DEMBPERL)
|
||||
ADD_DEFINITIONS(-DEMBPERL_PLUGIN)
|
||||
ENDIF(EQEMU_BUILD_PERL)
|
||||
IF(EQEMU_BUILD_LUA)
|
||||
ADD_DEFINITIONS(-DLUA_EQEMU)
|
||||
ENDIF(EQEMU_BUILD_LUA)
|
||||
|
||||
OPTION(EQEMU_USE_MAP_MMFS "Create and use Zone Map MMF files." OFF)
|
||||
IF(EQEMU_USE_MAP_MMFS)
|
||||
ADD_DEFINITIONS(-DUSE_MAP_MMFS)
|
||||
ENDIF(EQEMU_USE_MAP_MMFS)
|
||||
|
||||
SET(EQEMU_MAP_DIR "./Maps" CACHE STRING "The dir that maps, water maps, and paths are located in.")
|
||||
|
||||
ADD_DEFINITIONS(-DEQDEBUG=${EQEMU_DEBUG_LEVEL})
|
||||
ADD_DEFINITIONS(-DINVERSEXY)
|
||||
ADD_DEFINITIONS(-DFIELD_ITEMS)
|
||||
ADD_DEFINITIONS(-DMAP_DIR="${EQEMU_MAP_DIR}")
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_STATUS=${EQEMU_LOG_LEVEL_STATUS})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_NORMAL=${EQEMU_LOG_LEVEL_NORMAL})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_ERROR=${EQEMU_LOG_LEVEL_ERROR})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_DEBUG=${EQEMU_LOG_LEVEL_DEBUG})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_QUEST=${EQEMU_LOG_LEVEL_QUEST})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_COMMANDS=${EQEMU_LOG_LEVEL_COMMANDS})
|
||||
ADD_DEFINITIONS(-DLOG_LEVEL_CRASH=${EQEMU_LOG_LEVEL_CRASH})
|
||||
ADD_DEFINITIONS(-DGLM_FORCE_RADIANS)
|
||||
|
||||
#Find everything we need
|
||||
FIND_PACKAGE(ZLIB REQUIRED)
|
||||
FIND_PACKAGE(MySQL REQUIRED)
|
||||
IF(EQEMU_BUILD_PERL)
|
||||
FIND_PACKAGE(PerlLibs REQUIRED)
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${PERL_INCLUDE_PATH}")
|
||||
ENDIF(EQEMU_BUILD_PERL)
|
||||
|
||||
SET(SERVER_LIBS common debug ${MySQL_LIBRARY_DEBUG} optimized ${MySQL_LIBRARY_RELEASE} ${ZLIB_LIBRARY} libuv fmt ${NATS_LIBRARY_DEBUG} ${PROTOBUF_LIBRARY_DEBUG})
|
||||
|
||||
FIND_PACKAGE(Sodium REQUIRED)
|
||||
IF(SODIUM_FOUND)
|
||||
OPTION(EQEMU_ENABLE_SECURITY "Use Encryption For TCP Connections" ON)
|
||||
IF(EQEMU_ENABLE_SECURITY)
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${SODIUM_INCLUDE_DIRS}")
|
||||
ADD_DEFINITIONS(-DENABLE_SECURITY)
|
||||
SET(SERVER_LIBS ${SERVER_LIBS} ${SODIUM_LIBRARIES})
|
||||
ENDIF()
|
||||
ENDIF()
|
||||
|
||||
IF(WIN32)
|
||||
SET(SERVER_LIBS ${SERVER_LIBS} "ws2_32" "psapi" "iphlpapi" "userenv")
|
||||
ENDIF()
|
||||
|
||||
IF(UNIX)
|
||||
SET(SERVER_LIBS ${SERVER_LIBS} ${CMAKE_DL_LIBS} "z" "m" "pthread")
|
||||
IF(NOT DARWIN)
|
||||
SET(SERVER_LIBS ${SERVER_LIBS} "rt")
|
||||
ENDIF()
|
||||
SET(SERVER_LIBS ${SERVER_LIBS} "uuid")
|
||||
ENDIF()
|
||||
|
||||
IF(EQEMU_BUILD_LUA)
|
||||
FIND_PACKAGE(EQLua51 REQUIRED)
|
||||
SET(Boost_USE_STATIC_LIBS OFF)
|
||||
SET(Boost_USE_MULTITHREADED ON)
|
||||
SET(Boost_USE_STATIC_RUNTIME OFF)
|
||||
SET(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/boost")
|
||||
|
||||
FIND_PACKAGE(Boost REQUIRED)
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${LUA_INCLUDE_DIR}" "${Boost_INCLUDE_DIRS}")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/luabind")
|
||||
|
||||
OPTION(EQEMU_SANITIZE_LUA_LIBS "Sanitize Lua Libraries (Remove OS and IO standard libraries from being able to run)." ON)
|
||||
IF(EQEMU_SANITIZE_LUA_LIBS)
|
||||
ADD_DEFINITIONS(-DSANITIZE_LUA_LIBS)
|
||||
ENDIF(EQEMU_SANITIZE_LUA_LIBS)
|
||||
ENDIF(EQEMU_BUILD_LUA)
|
||||
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${ZLIB_INCLUDE_DIRS}")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${MySQL_INCLUDE_DIR}")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${NATS_INCLUDE_DIR}")
|
||||
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/common/glm")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/libs/cereal")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/libs/libuv/include" )
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/libs/libuv/src")
|
||||
INCLUDE_DIRECTORIES(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/libs/format")
|
||||
|
||||
|
||||
option(EQEMU_BUILD_LUA "Build Lua parser." ON)
|
||||
IF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC)
|
||||
ADD_SUBDIRECTORY(common)
|
||||
ADD_SUBDIRECTORY(libs)
|
||||
ENDIF(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_HC)
|
||||
IF(EQEMU_BUILD_SERVER)
|
||||
ADD_SUBDIRECTORY(shared_memory)
|
||||
ADD_SUBDIRECTORY(world)
|
||||
ADD_SUBDIRECTORY(zone)
|
||||
ADD_SUBDIRECTORY(ucs)
|
||||
ADD_SUBDIRECTORY(queryserv)
|
||||
ADD_SUBDIRECTORY(eqlaunch)
|
||||
ENDIF(EQEMU_BUILD_SERVER)
|
||||
IF(EQEMU_BUILD_LOGIN)
|
||||
ADD_SUBDIRECTORY(loginserver)
|
||||
ENDIF(EQEMU_BUILD_LOGIN)
|
||||
|
||||
if(EQEMU_BUILD_SERVER OR EQEMU_BUILD_LOGIN OR EQEMU_BUILD_TESTS OR EQEMU_BUILD_CLIENT_FILES)
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(libs)
|
||||
else()
|
||||
message(FATAL_ERROR "No targets were selected to build, we must build at least one target.")
|
||||
endif()
|
||||
IF(EQEMU_BUILD_HC)
|
||||
ADD_SUBDIRECTORY(hc)
|
||||
ENDIF(EQEMU_BUILD_HC)
|
||||
|
||||
if(EQEMU_BUILD_SERVER)
|
||||
add_subdirectory(shared_memory)
|
||||
add_subdirectory(world)
|
||||
add_subdirectory(zone)
|
||||
add_subdirectory(ucs)
|
||||
add_subdirectory(queryserv)
|
||||
add_subdirectory(eqlaunch)
|
||||
endif()
|
||||
IF(EQEMU_BUILD_TESTS)
|
||||
ADD_SUBDIRECTORY(tests)
|
||||
ENDIF(EQEMU_BUILD_TESTS)
|
||||
|
||||
if(EQEMU_BUILD_LOGIN)
|
||||
add_subdirectory(loginserver)
|
||||
endif()
|
||||
|
||||
if(EQEMU_BUILD_TESTS)
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
if(EQEMU_BUILD_CLIENT_FILES)
|
||||
add_subdirectory(client_files)
|
||||
endif()
|
||||
IF(EQEMU_BUILD_CLIENT_FILES)
|
||||
ADD_SUBDIRECTORY(client_files)
|
||||
ENDIF(EQEMU_BUILD_CLIENT_FILES)
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
{
|
||||
"version": 3,
|
||||
"cmakeMinimumRequired": {
|
||||
"major": 3,
|
||||
"minor": 20,
|
||||
"patch": 0
|
||||
},
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "linux",
|
||||
"displayName": "Linux-Ninja",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"EQEMU_BUILD_TESTS": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "linux-clang",
|
||||
"displayName": "Linux-Ninja (Clang)",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"EQEMU_BUILD_TESTS": "ON",
|
||||
"CMAKE_C_COMPILER": "clang",
|
||||
"CMAKE_CXX_COMPILER": "clang++"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "linux-ccache",
|
||||
"displayName": "Linux-Ninja (Ccache)",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"CMAKE_C_COMPILER_LAUNCHER": "ccache",
|
||||
"CMAKE_CXX_COMPILER_LAUNCHER": "ccache",
|
||||
"EQEMU_BUILD_TESTS": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "linux-clang-ccache",
|
||||
"displayName": "Linux-Ninja (Clang, Ccache)",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"CMAKE_C_COMPILER_LAUNCHER": "ccache",
|
||||
"CMAKE_CXX_COMPILER_LAUNCHER": "ccache",
|
||||
"EQEMU_BUILD_TESTS": "ON",
|
||||
"CMAKE_C_COMPILER": "clang",
|
||||
"CMAKE_CXX_COMPILER": "clang++"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "win-msvc-2022",
|
||||
"displayName": "Windows MSVC (VS 2022)",
|
||||
"generator": "Visual Studio 17 2022",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"architecture": { "value": "x64" },
|
||||
"cacheVariables": {
|
||||
"EQEMU_BUILD_TESTS": "ON"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "win-msvc-2026",
|
||||
"displayName": "Windows MSVC (VS 2026)",
|
||||
"generator": "Visual Studio 18 2026",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"architecture": { "value": "x64" },
|
||||
"cacheVariables": {
|
||||
"EQEMU_BUILD_TESTS": "ON"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
We expect contributors and community members to act professionally and respectfully, and we expect our forums and Discord channels to be dignified environments that expand the community and enhance the learning experience for new members.
|
||||
|
||||
Specifically:
|
||||
|
||||
* Respect people, their ideas, and their work.
|
||||
* Be kind. Be courteous. Be welcoming.
|
||||
* Listen. Consider and acknowledge people's points before responding.
|
||||
* Be respectful of differing viewpoints and experience levels.
|
||||
* Accept constructive criticism and work together toward decisions.
|
||||
* Focus on what is best for the community and users.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of violent threats, trolling, insulting/derogatory comments, abusive or discriminatory language, or personal attacks.
|
||||
* Public or private harassment.
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission.
|
||||
* Conduct which could reasonably be considered inappropriate in a professional setting.
|
||||
* Advocating for or encouraging any of the above behaviors.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, forum posts, Discord messages, and other contributions that are not aligned with this code of conduct.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project.
|
||||
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser 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
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
-675
@@ -1,675 +0,0 @@
|
||||
# GNU GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc.
|
||||
<https://fsf.org/>
|
||||
|
||||
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>.
|
||||
@@ -1,150 +1,72 @@
|
||||
<h1 align="center">EQEmulator Server Platform</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/user-attachments/assets/11942e15-b512-402d-a619-0543c7f1151e" style="border-radius: 10px;">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<b>EQEmulator - A Fan-Made Project Honoring a Legendary MMORPG</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/EQEmu/EQEmu/actions/workflows/build.yaml"><img src="https://github.com/EQEmu/EQEmu/actions/workflows/build.yaml/badge.svg"></a>
|
||||
<a href="https://github.com/EQEmu/EQEmu/graphs/contributors"><img src="https://img.shields.io/github/contributors/EQEmu/EQEmu" alt="Contributors"></a>
|
||||
<a href="https://discord.gg/QHsm7CD"><img src="https://img.shields.io/discord/212663220849213441?label=Discord&logo=discord&color=7289DA" alt="Discord"></a>
|
||||
<a href="https://docs.eqemu.dev"><img src="https://img.shields.io/badge/docs-MkDocs%20Powered-blueviolet" alt="Docs"></a>
|
||||
<a href="./LICENSE.md"><img src="https://img.shields.io/github/license/EQEmu/EQEmu" alt="License"></a>
|
||||
<a href="https://github.com/EQEmu/EQEmu/releases"><img src="https://img.shields.io/github/v/release/EQEmu/EQEmu" alt="Latest Release"></a>
|
||||
<a href="https://github.com/EQEmu/EQEmu/releases"><img src="https://img.shields.io/github/release-date/EQEmu/EQEmu" alt="Release Date"></a>
|
||||
<img src="https://img.shields.io/github/downloads/EQEmu/EQEmu/total.svg" alt="Github All Releases"></a>
|
||||
<img src="https://img.shields.io/github/issues-pr-closed/eqemu/server" alt="GitHub Issues or Pull Requests">
|
||||
<img src="https://img.shields.io/docker/pulls/akkadius/eqemu-server" alt="Docker Pulls">
|
||||
<img src="https://jb.gg/badges/official-plastic.svg" alt="Official">
|
||||
|
||||
</p>
|
||||
# EQEmulator Core Server
|
||||
|Travis CI (Linux)|Appveyor (Windows) |
|
||||
|:---:|:---:|
|
||||
|[](https://travis-ci.org/EQEmu/Server) |[](https://ci.appveyor.com/project/KimLS/server/branch/master) |
|
||||
|
||||
***
|
||||
|
||||
<p align="center">
|
||||
EQEmulator is a <b>passion-driven</b>, <b>open source server emulator</b> project dedicated to preserving and celebrating the legacy of a groundbreaking classic MMORPG.
|
||||
</p>
|
||||
**EQEmulator is a custom completely from-scratch open source server implementation for EverQuest built mostly on C++**
|
||||
* MySQL/MariaDB is used as the database engine (over 200+ tables)
|
||||
* Perl and LUA are both supported scripting languages for NPC/Player/Quest oriented events
|
||||
* Open source database (Project EQ) has content up to expansion OoW (included in server installs)
|
||||
* Game server environments and databases can be heavily customized to create all new experiences
|
||||
* Hundreds of Quests/events created and maintained by Project EQ
|
||||
|
||||
<p align="center">
|
||||
For over two decades and continuing, EQEmulator has served as a <strong>fan tribute</strong>, providing tools and technology that allow players to explore, customize, and experience the legendary game's iconic gameplay in new ways. This project exists solely out of <strong>deep admiration</strong> for the original developers, artists, designers, and visionaries who created one of the most influential online worlds of all time.
|
||||
</p>
|
||||
## Server Installs
|
||||
| |Windows|Linux|
|
||||
|:---:|:---:|:---:|
|
||||
|**Install Count**|||
|
||||
### > Windows
|
||||
* [Install](https://github.com/EQEmu/Server/wiki/Windows-Server)
|
||||
|
||||
<p align="center">
|
||||
We do not claim ownership of the original game or its assets. <strong>All credit and respect belong to the original creators and Daybreak Game Company</strong>, whose work continues to inspire generations of players and developers alike.
|
||||
</p>
|
||||
### > Debian/Ubuntu/CentOS/Fedora
|
||||
* You can use curl or wget to kick off the installer (whichever your OS has)
|
||||
> curl -O https://raw.githubusercontent.com/EQEmu/Server/master/utils/scripts/linux_installer/install.sh install.sh && chmod 755 install.sh && ./install.sh
|
||||
|
||||
<p align="center">
|
||||
EQEmulator has for over 20 years and always will be a <strong>fan-based, non-commercial open-source effort</strong> made by players, for players—preserving the legacy of the game while empowering community-driven creativity, learning and joy that the game and its creators has so strongly inspired in us all.
|
||||
</p>
|
||||
> wget --no-check-certificate https://raw.githubusercontent.com/EQEmu/Server/master/utils/scripts/linux_installer/install.sh -O install.sh && chmod 755 install.sh && ./install.sh
|
||||
|
||||
***
|
||||
|
||||
<h3 align="center">
|
||||
Technical Overview & Reverse Engineering Effort
|
||||
</h1>
|
||||
|
||||
<p align="center">EQEmulator represents <strong>over two decades of collaborative reverse engineering</strong>, building the server from the ground up without access to the original source code. This effort was achieved entirely through <strong>community-driven analysis, network protocol decoding, and in-game behavioral research</strong>.</p>
|
||||
|
||||
<h1 align="center">
|
||||
💡 How We Did It
|
||||
</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/user-attachments/assets/b6b48cf7-f64a-4497-9750-71f442a3d132" height="300px">
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<strong>Reverse Engineering</strong>
|
||||
Every system, packet, opcode, and game mechanic has been reconstructed through countless hours of live packet sniffing, client disassembly, and in-game experimentation by dedicated contributors over the years.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
No proprietary code or server sources were ever used.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
All implementations are the result of clean-room engineering.
|
||||
</p>
|
||||
|
||||
|
||||
<h1 align="center">
|
||||
🛠️ Technology Stack
|
||||
</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/user-attachments/assets/df5ea809-86c5-439d-a8fa-651fb04ba477" style="border-radius: 10px">
|
||||
</p>
|
||||
|
||||
**C++ Core Engine**
|
||||
|
||||
* High-performance networking and gameplay logic built in C++
|
||||
* Cross-platform support for Linux and Windows
|
||||
|
||||
**MySQL / MariaDB Backend**
|
||||
|
||||
* Fully structured schema with over 200+ tables
|
||||
* Supports content customization, expansions, and custom worlds
|
||||
|
||||
**Scripting Engine**
|
||||
|
||||
* Native support for **Perl** and **Lua** scripting
|
||||
* Powerfully extendable for quests, NPC behaviors, and custom events
|
||||
|
||||
**Open Source Content Database**
|
||||
|
||||
* Includes ProjectEQ’s world data up through *Dragons of Norrath*
|
||||
* 100% customizable to create entirely new game worlds
|
||||
|
||||
<h1 align="center">
|
||||
🚀 Why It Matters
|
||||
</h1>
|
||||
|
||||
<p align="center">🧬 EQEmulator stands as a <strong>technical preservation project</strong>, ensuring that the magic of classic and custom servers lives on for future generations of players, tinkerers, and game designers.
|
||||
</p>
|
||||
|
||||
> We humbly acknowledge and thank the original developers for creating one of the most influential online experiences in gaming history.
|
||||
|
||||
<h1 align="center">
|
||||
🧑💻🖥️ Supported Clients
|
||||
</h1>
|
||||
## Supported Clients
|
||||
|
||||
|Titanium Edition|Secrets of Faydwer|Seeds of Destruction|Underfoot|Rain of Fear|
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
|<img src="http://i.imgur.com/hrwDxoM.jpg" height="150">|<img src="http://i.imgur.com/cRDW5tn.png" height="150">|<img src="http://i.imgur.com/V48kuVn.jpg" height="150">|<img src="http://i.imgur.com/IJQ0XMa.jpg" height="150">|<img src="http://i.imgur.com/OMpHkKa.png" height="100">|
|
||||
|
||||
## 📚 Resources
|
||||
## Bug Reports <img src="http://i.imgur.com/daf1Vjw.png" height="20">
|
||||
* Please use the [issue tracker](https://github.com/EQEmu/Server/issues) provided by GitHub to send us bug
|
||||
reports or feature requests.
|
||||
* The [EQEmu Forums](http://www.eqemulator.org/forums/) are also a place to submit and get help with bugs.
|
||||
|
||||
| Resource | Badges | Link |
|
||||
|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|
|
||||
| **EQEmulator Docs** | [](https://docs.eqemu.dev) | [docs.eqemu.dev](https://docs.eqemu.dev/) |
|
||||
| **Discord Community**| [](https://discord.gg/QHsm7CD) | [Join Discord](https://discord.gg/QHsm7CD) |
|
||||
| **Latest Release** | [](https://github.com/EQEmu/EQEmu/releases) <br> [](https://github.com/EQEmu/EQEmu/releases) <br> [](https://github.com/EQEmu/EQEmu/releases) | [View Releases](https://github.com/EQEmu/EQEmu/releases) |
|
||||
| **License** | [](./LICENSE.md) | [View License](./LICENSE.md) |
|
||||
| **Build Status** | [](https://github.com/EQEmu/EQEmu/actions/workflows/build.yaml) | [View Build Status](https://github.com/EQEmu/EQEmu/actions/workflows/build.yaml) |
|
||||
| **Docker Pulls** | [](https://hub.docker.com/r/akkadius/eqemu-server) | [Docker Hub](https://hub.docker.com/r/akkadius/eqemu-server) |
|
||||
| **Contributions** | [](https://github.com/EQEmu/EQEmu/pulls?q=is%3Apr+is%3Aclosed) | [Closed PRs & Issues](https://github.com/EQEmu/EQEmu/pulls?q=is%3Apr+is%3Aclosed) |
|
||||
## Contributions <img src="http://image.flaticon.com/icons/png/512/25/25231.png" width="20">
|
||||
|
||||
## 🛠️ Getting Started
|
||||
* The preferred way to contribute is to fork the repo and submit a pull request on
|
||||
GitHub. If you need help with your changes, you can always post on the forums or
|
||||
try Discord. You can also post unified diffs (`git diff` should do the trick) on the
|
||||
[Server Code Submissions](http://www.eqemulator.org/forums/forumdisplay.php?f=669)
|
||||
forum, although pull requests will be much quicker and easier on all parties.
|
||||
|
||||
If you want to set up your own EQEmulator server, please refer to the current [server installation guides](https://docs.eqemu.dev/#server-installation). We've had 100,000s of players and developers use our guides to set up their own servers, and we hope you will too!
|
||||
## Contact <img src="http://gamerescape.com/wp-content/uploads/2015/06/discord.png" height="20">
|
||||
|
||||
## 🗂️ Related Repositories
|
||||
- Discord Channel: https://discord.gg/QHsm7CD
|
||||
- **User Discord Channel**: `#general`
|
||||
- **Developer Discord Channel**: `#eqemucoders`
|
||||
|
||||
| Repository | Description |
|
||||
|--------------------|----------------------------------------------------------------------------------|
|
||||
| [ProjectEQ Quests](https://github.com/ProjectEQ/projecteqquests) | Official quests and event scripts for ProjectEQ |
|
||||
| [Maps](https://github.com/EQEmu/maps) | EQEmu-compatible zone maps |
|
||||
| [Installer Resources](https://github.com/Akkadius/EQEmuInstall) | Scripts and assets for setting up EQEmu servers |
|
||||
| [Zone Utilities](https://github.com/EQEmu/zone-utilities) | Utilities for parsing, rendering, and manipulating EQ zone files |
|
||||
## Resources
|
||||
- [EQEmulator Forums](http://www.eqemulator.org/forums)
|
||||
- [EQEmulator Wiki](https://github.com/EQEmu/Server/wiki)
|
||||
|
||||
## Related Repositories
|
||||
* [ProjectEQ Quests](https://github.com/ProjectEQ/projecteqquests)
|
||||
* [Maps](https://github.com/Akkadius/EQEmuMaps)
|
||||
* [Installer Resources](https://github.com/Akkadius/EQEmuInstall)
|
||||
* [Zone Utilities](https://github.com/EQEmu/zone-utilities) - Various utilities and libraries for parsing, rendering and manipulating EQ Zone files.
|
||||
|
||||
## Contributors
|
||||
## Other License Info
|
||||
|
||||
<a href="https://github.com/EQEmu/EQEmu/graphs/contributors">
|
||||
<img src="https://contributors-img.firebaseapp.com/image?repo=EQEmu/EQEmu" />
|
||||
</a>
|
||||
* The server code and utilities are released under **GPLv3**
|
||||
* We also include some small libraries for convienence that may be under different licensing
|
||||
* SocketLib - GPL LibXML
|
||||
* zlib - zlib license
|
||||
* MariaDB/MySQL - GPL
|
||||
* GPL Perl - GPL / ActiveState (under the assumption that this is a free project)
|
||||
* CPPUnit - GLP StringUtilities - Apache
|
||||
* LUA - MIT
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# Security Policy - Reporting Vulnerabilities
|
||||
|
||||
When reporting active hacks, exploits and other vulnerabilities, please describe how to reproduce said report and if you can provide context into a possible solution
|
||||
+492
-990
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,4 @@
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
|
||||
|
||||
add_subdirectory(import)
|
||||
add_subdirectory(export)
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
set(export_sources
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
|
||||
|
||||
SET(export_sources
|
||||
main.cpp
|
||||
)
|
||||
|
||||
set(export_headers
|
||||
SET(export_headers
|
||||
)
|
||||
|
||||
add_executable(export_client_files ${export_sources} ${export_headers})
|
||||
ADD_EXECUTABLE(export_client_files ${export_sources} ${export_headers})
|
||||
|
||||
install(TARGETS export_client_files RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
|
||||
INSTALL(TARGETS export_client_files RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
|
||||
|
||||
target_link_libraries(export_client_files common)
|
||||
TARGET_LINK_LIBRARIES(export_client_files ${SERVER_LIBS})
|
||||
|
||||
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
|
||||
set_property(TARGET export_client_files PROPERTY FOLDER executables/tools)
|
||||
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
|
||||
|
||||
+169
-137
@@ -1,203 +1,235 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2013 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#include "common/content/world_content_service.h"
|
||||
#include "common/crash.h"
|
||||
#include "common/eqemu_config.h"
|
||||
#include "common/eqemu_logsys.h"
|
||||
#include "common/events/player_event_logs.h"
|
||||
#include "common/evolving_items.h"
|
||||
#include "common/file.h"
|
||||
#include "common/path_manager.h"
|
||||
#include "common/platform.h"
|
||||
#include "common/repositories/base_data_repository.h"
|
||||
#include "common/repositories/db_str_repository.h"
|
||||
#include "common/repositories/skill_caps_repository.h"
|
||||
#include "common/repositories/spells_new_repository.h"
|
||||
#include "common/rulesys.h"
|
||||
#include "common/shareddb.h"
|
||||
#include "common/skill_caps.h"
|
||||
#include "common/strings.h"
|
||||
#include "common/zone_store.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "../../common/eqemu_logsys.h"
|
||||
#include "../../common/global_define.h"
|
||||
#include "../../common/shareddb.h"
|
||||
#include "../../common/eqemu_config.h"
|
||||
#include "../../common/platform.h"
|
||||
#include "../../common/crash.h"
|
||||
#include "../../common/rulesys.h"
|
||||
#include "../../common/string_util.h"
|
||||
|
||||
EQEmuLogSys LogSys;
|
||||
|
||||
void ExportSpells(SharedDatabase *db);
|
||||
void ExportSkillCaps(SharedDatabase *db);
|
||||
void ExportBaseData(SharedDatabase *db);
|
||||
void ExportDBStrings(SharedDatabase *db);
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int main(int argc, char **argv) {
|
||||
RegisterExecutablePlatform(ExePlatformClientExport);
|
||||
EQEmuLogSys::Instance()->LoadLogSettingsDefaults();
|
||||
LogSys.LoadLogSettingsDefaults();
|
||||
set_exception_handler();
|
||||
|
||||
PathManager::Instance()->Init();
|
||||
|
||||
LogInfo("Client Files Export Utility");
|
||||
if (!EQEmuConfig::LoadConfig()) {
|
||||
LogError("Unable to load configuration file");
|
||||
Log(Logs::General, Logs::Status, "Client Files Export Utility");
|
||||
if(!EQEmuConfig::LoadConfig()) {
|
||||
Log(Logs::General, Logs::Error, "Unable to load configuration file.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto Config = EQEmuConfig::get();
|
||||
|
||||
SharedDatabase database;
|
||||
SharedDatabase content_db;
|
||||
|
||||
LogInfo("Connecting to database");
|
||||
if (!database.Connect(
|
||||
Config->DatabaseHost.c_str(),
|
||||
Config->DatabaseUsername.c_str(),
|
||||
Config->DatabasePassword.c_str(),
|
||||
Config->DatabaseDB.c_str(),
|
||||
Config->DatabasePort
|
||||
)) {
|
||||
LogError("Unable to connect to the database, cannot continue without a database connection");
|
||||
Log(Logs::General, Logs::Status, "Connecting to database...");
|
||||
if(!database.Connect(Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(),
|
||||
Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) {
|
||||
Log(Logs::General, Logs::Error, "Unable to connect to the database, cannot continue without a "
|
||||
"database connection");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-tenancy: Content database
|
||||
*/
|
||||
if (!Config->ContentDbHost.empty()) {
|
||||
if (!content_db.Connect(
|
||||
Config->ContentDbHost.c_str() ,
|
||||
Config->ContentDbUsername.c_str(),
|
||||
Config->ContentDbPassword.c_str(),
|
||||
Config->ContentDbName.c_str(),
|
||||
Config->ContentDbPort
|
||||
)) {
|
||||
LogError("Cannot continue without a content database connection");
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
content_db.SetMySQL(database);
|
||||
}
|
||||
/* Register Log System and Settings */
|
||||
database.LoadLogSettings(LogSys.log_settings);
|
||||
LogSys.StartFileLogs();
|
||||
|
||||
EQEmuLogSys::Instance()->SetDatabase(&database)
|
||||
->SetLogPath(PathManager::Instance()->GetLogPath())
|
||||
->LoadLogDatabaseSettings()
|
||||
->StartFileLogs();
|
||||
|
||||
std::string export_type;
|
||||
|
||||
if (argv[1]) {
|
||||
export_type = argv[1];
|
||||
}
|
||||
|
||||
if (Strings::EqualFold(export_type, "spells")) {
|
||||
ExportSpells(&content_db);
|
||||
return 0;
|
||||
} else if (Strings::EqualFold(export_type, "skills")) {
|
||||
ExportSkillCaps(&content_db);
|
||||
return 0;
|
||||
} else if (Strings::EqualFold(export_type, "basedata") || Strings::EqualFold(export_type, "base_data")) {
|
||||
ExportBaseData(&content_db);
|
||||
return 0;
|
||||
} else if (Strings::EqualFold(export_type, "dbstr") || Strings::EqualFold(export_type, "dbstring")) {
|
||||
ExportDBStrings(&database);
|
||||
return 0;
|
||||
}
|
||||
|
||||
ExportSpells(&content_db);
|
||||
ExportSkillCaps(&content_db);
|
||||
ExportBaseData(&content_db);
|
||||
ExportSpells(&database);
|
||||
ExportSkillCaps(&database);
|
||||
ExportBaseData(&database);
|
||||
ExportDBStrings(&database);
|
||||
|
||||
EQEmuLogSys::Instance()->CloseFileLogs();
|
||||
LogSys.CloseFileLogs();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ExportSpells(SharedDatabase* db)
|
||||
{
|
||||
std::ofstream file(fmt::format("{}/export/spells_us.txt", PathManager::Instance()->GetServerPath()));
|
||||
if (!file || !file.is_open()) {
|
||||
LogError("Unable to open export/spells_us.txt to write, skipping.");
|
||||
void ExportSpells(SharedDatabase *db) {
|
||||
Log(Logs::General, Logs::Status, "Exporting Spells...");
|
||||
|
||||
FILE *f = fopen("export/spells_us.txt", "w");
|
||||
if(!f) {
|
||||
Log(Logs::General, Logs::Error, "Unable to open export/spells_us.txt to write, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& lines = SpellsNewRepository::GetSpellFileLines(*db);
|
||||
const std::string query = "SELECT * FROM spells_new ORDER BY id";
|
||||
auto results = db->QueryDatabase(query);
|
||||
|
||||
const std::string& file_string = Strings::Implode("\n", lines);
|
||||
if(results.Success()) {
|
||||
for (auto row = results.begin(); row != results.end(); ++row) {
|
||||
std::string line;
|
||||
unsigned int fields = results.ColumnCount();
|
||||
for(unsigned int i = 0; i < fields; ++i) {
|
||||
if(i != 0) {
|
||||
line.push_back('^');
|
||||
}
|
||||
|
||||
file << file_string;
|
||||
if(row[i] != nullptr) {
|
||||
line += row[i];
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
fprintf(f, "%s\n", line.c_str());
|
||||
}
|
||||
} else {
|
||||
}
|
||||
|
||||
LogInfo("Exported [{}] Spell{}", lines.size(), lines.size() != 1 ? "s" : "");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ExportSkillCaps(SharedDatabase* db)
|
||||
{
|
||||
std::ofstream file(fmt::format("{}/export/SkillCaps.txt", PathManager::Instance()->GetServerPath()));
|
||||
if (!file || !file.is_open()) {
|
||||
LogError("Unable to open export/SkillCaps.txt to write, skipping.");
|
||||
bool SkillUsable(SharedDatabase *db, int skill_id, int class_id) {
|
||||
|
||||
bool res = false;
|
||||
|
||||
std::string query = StringFormat("SELECT max(cap) FROM skill_caps WHERE class=%d AND skillID=%d",
|
||||
class_id, skill_id);
|
||||
auto results = db->QueryDatabase(query);
|
||||
if(!results.Success()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (results.RowCount() == 0)
|
||||
return false;
|
||||
|
||||
auto row = results.begin();
|
||||
if(row[0] && atoi(row[0]) > 0)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
int GetSkill(SharedDatabase *db, int skill_id, int class_id, int level) {
|
||||
|
||||
std::string query = StringFormat("SELECT cap FROM skill_caps WHERE class=%d AND skillID=%d AND level=%d",
|
||||
class_id, skill_id, level);
|
||||
auto results = db->QueryDatabase(query);
|
||||
if (!results.Success()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (results.RowCount() == 0)
|
||||
return 0;
|
||||
|
||||
auto row = results.begin();
|
||||
return atoi(row[0]);
|
||||
}
|
||||
|
||||
void ExportSkillCaps(SharedDatabase *db) {
|
||||
Log(Logs::General, Logs::Status, "Exporting Skill Caps...");
|
||||
|
||||
FILE *f = fopen("export/SkillCaps.txt", "w");
|
||||
if(!f) {
|
||||
Log(Logs::General, Logs::Error, "Unable to open export/SkillCaps.txt to write, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& lines = SkillCapsRepository::GetSkillCapFileLines(*db);
|
||||
for(int cl = 1; cl <= 16; ++cl) {
|
||||
for(int skill = 0; skill <= 77; ++skill) {
|
||||
if(SkillUsable(db, skill, cl)) {
|
||||
int previous_cap = 0;
|
||||
for(int level = 1; level <= 100; ++level) {
|
||||
int cap = GetSkill(db, skill, cl, level);
|
||||
if(cap < previous_cap) {
|
||||
cap = previous_cap;
|
||||
}
|
||||
|
||||
const std::string& file_string = Strings::Implode("\n", lines);
|
||||
fprintf(f, "%d^%d^%d^%d^0\n", cl, skill, level, cap);
|
||||
previous_cap = cap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
file << file_string;
|
||||
|
||||
file.close();
|
||||
|
||||
LogInfo("Exported [{}] Skill Cap{}", lines.size(), lines.size() != 1 ? "s" : "");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ExportBaseData(SharedDatabase *db)
|
||||
{
|
||||
std::ofstream file(fmt::format("{}/export/BaseData.txt", PathManager::Instance()->GetServerPath()));
|
||||
if (!file || !file.is_open()) {
|
||||
LogError("Unable to open export/BaseData.txt to write, skipping.");
|
||||
void ExportBaseData(SharedDatabase *db) {
|
||||
Log(Logs::General, Logs::Status, "Exporting Base Data...");
|
||||
|
||||
FILE *f = fopen("export/BaseData.txt", "w");
|
||||
if(!f) {
|
||||
Log(Logs::General, Logs::Error, "Unable to open export/BaseData.txt to write, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& lines = BaseDataRepository::GetBaseDataFileLines(*db);
|
||||
const std::string query = "SELECT * FROM base_data ORDER BY level, class";
|
||||
auto results = db->QueryDatabase(query);
|
||||
if(results.Success()) {
|
||||
for (auto row = results.begin();row != results.end();++row) {
|
||||
std::string line;
|
||||
unsigned int fields = results.ColumnCount();
|
||||
for(unsigned int rowIndex = 0; rowIndex < fields; ++rowIndex) {
|
||||
if(rowIndex != 0)
|
||||
line.push_back('^');
|
||||
|
||||
const std::string& file_string = Strings::Implode("\n", lines);
|
||||
if(row[rowIndex] != nullptr) {
|
||||
line += row[rowIndex];
|
||||
}
|
||||
}
|
||||
|
||||
file << file_string;
|
||||
fprintf(f, "%s\n", line.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
|
||||
LogInfo("Exported [{}] Base Data Entr{}", lines.size(), lines.size() != 1 ? "ies" : "y");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ExportDBStrings(SharedDatabase *db)
|
||||
{
|
||||
std::ofstream file(fmt::format("{}/export/dbstr_us.txt", PathManager::Instance()->GetServerPath()));
|
||||
if (!file || !file.is_open()) {
|
||||
LogError("Unable to open export/dbstr_us.txt to write, skipping.");
|
||||
void ExportDBStrings(SharedDatabase *db) {
|
||||
Log(Logs::General, Logs::Status, "Exporting DB Strings...");
|
||||
|
||||
FILE *f = fopen("export/dbstr_us.txt", "w");
|
||||
if(!f) {
|
||||
Log(Logs::General, Logs::Error, "Unable to open export/dbstr_us.txt to write, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& lines = DbStrRepository::GetDBStrFileLines(*db);
|
||||
fprintf(f, "Major^Minor^String(New)\n");
|
||||
const std::string query = "SELECT * FROM db_str ORDER BY id, type";
|
||||
auto results = db->QueryDatabase(query);
|
||||
if(results.Success()) {
|
||||
for(auto row = results.begin(); row != results.end(); ++row) {
|
||||
std::string line;
|
||||
unsigned int fields = results.ColumnCount();
|
||||
for(unsigned int rowIndex = 0; rowIndex < fields; ++rowIndex) {
|
||||
if(rowIndex != 0)
|
||||
line.push_back('^');
|
||||
|
||||
const std::string& file_string = Strings::Implode("\n", lines);
|
||||
if(row[rowIndex] != nullptr) {
|
||||
line += row[rowIndex];
|
||||
}
|
||||
}
|
||||
|
||||
file << file_string;
|
||||
fprintf(f, "%s\n", line.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
|
||||
LogInfo("Exported [{}] Database String{}", lines.size(), lines.size() != 1 ? "s" : "");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
set(import_sources
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
|
||||
|
||||
SET(import_sources
|
||||
main.cpp
|
||||
)
|
||||
|
||||
set(import_headers
|
||||
SET(import_headers
|
||||
)
|
||||
|
||||
add_executable(import_client_files ${import_sources} ${import_headers})
|
||||
ADD_EXECUTABLE(import_client_files ${import_sources} ${import_headers})
|
||||
|
||||
install(TARGETS import_client_files RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
|
||||
INSTALL(TARGETS import_client_files RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
|
||||
|
||||
target_link_libraries(import_client_files common)
|
||||
TARGET_LINK_LIBRARIES(import_client_files ${SERVER_LIBS})
|
||||
|
||||
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
|
||||
set_property(TARGET import_client_files PROPERTY FOLDER executables/tools)
|
||||
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
|
||||
|
||||
+91
-121
@@ -1,34 +1,31 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2013 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#include "common/content/world_content_service.h"
|
||||
#include "common/crash.h"
|
||||
#include "common/eqemu_config.h"
|
||||
#include "common/eqemu_logsys.h"
|
||||
#include "common/events/player_event_logs.h"
|
||||
#include "common/evolving_items.h"
|
||||
#include "common/file.h"
|
||||
#include "common/path_manager.h"
|
||||
#include "common/platform.h"
|
||||
#include "common/repositories/base_data_repository.h"
|
||||
#include "common/rulesys.h"
|
||||
#include "common/shareddb.h"
|
||||
#include "common/strings.h"
|
||||
#include "common/zone_store.h"
|
||||
|
||||
#include "../../common/eqemu_logsys.h"
|
||||
#include "../../common/global_define.h"
|
||||
#include "../../common/shareddb.h"
|
||||
#include "../../common/eqemu_config.h"
|
||||
#include "../../common/platform.h"
|
||||
#include "../../common/crash.h"
|
||||
#include "../../common/rulesys.h"
|
||||
#include "../../common/string_util.h"
|
||||
|
||||
EQEmuLogSys LogSys;
|
||||
|
||||
void ImportSpells(SharedDatabase *db);
|
||||
void ImportSkillCaps(SharedDatabase *db);
|
||||
@@ -37,64 +34,36 @@ void ImportDBStrings(SharedDatabase *db);
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
RegisterExecutablePlatform(ExePlatformClientImport);
|
||||
EQEmuLogSys::Instance()->LoadLogSettingsDefaults();
|
||||
LogSys.LoadLogSettingsDefaults();
|
||||
set_exception_handler();
|
||||
|
||||
PathManager::Instance()->Init();
|
||||
|
||||
LogInfo("Client Files Import Utility");
|
||||
Log(Logs::General, Logs::Status, "Client Files Import Utility");
|
||||
if(!EQEmuConfig::LoadConfig()) {
|
||||
LogError("Unable to load configuration file.");
|
||||
Log(Logs::General, Logs::Error, "Unable to load configuration file.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto Config = EQEmuConfig::get();
|
||||
|
||||
SharedDatabase database;
|
||||
SharedDatabase content_db;
|
||||
|
||||
LogInfo("Connecting to database");
|
||||
if (!database.Connect(
|
||||
Config->DatabaseHost.c_str(),
|
||||
Config->DatabaseUsername.c_str(),
|
||||
Config->DatabasePassword.c_str(),
|
||||
Config->DatabaseDB.c_str(),
|
||||
Config->DatabasePort
|
||||
)) {
|
||||
LogError("Unable to connect to the database, cannot continue without a database connection");
|
||||
Log(Logs::General, Logs::Status, "Connecting to database...");
|
||||
if(!database.Connect(Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(),
|
||||
Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) {
|
||||
Log(Logs::General, Logs::Error, "Unable to connect to the database, cannot continue without a "
|
||||
"database connection");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi-tenancy: Content database
|
||||
*/
|
||||
if (!Config->ContentDbHost.empty()) {
|
||||
if (!content_db.Connect(
|
||||
Config->ContentDbHost.c_str() ,
|
||||
Config->ContentDbUsername.c_str(),
|
||||
Config->ContentDbPassword.c_str(),
|
||||
Config->ContentDbName.c_str(),
|
||||
Config->ContentDbPort
|
||||
)) {
|
||||
LogError("Cannot continue without a content database connection");
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
content_db.SetMySQL(database);
|
||||
}
|
||||
database.LoadLogSettings(LogSys.log_settings);
|
||||
LogSys.StartFileLogs();
|
||||
|
||||
EQEmuLogSys::Instance()->SetDatabase(&database)
|
||||
->SetLogPath(PathManager::Instance()->GetLogPath())
|
||||
->LoadLogDatabaseSettings()
|
||||
->StartFileLogs();
|
||||
|
||||
ImportSpells(&content_db);
|
||||
ImportSkillCaps(&content_db);
|
||||
ImportBaseData(&content_db);
|
||||
ImportSpells(&database);
|
||||
ImportSkillCaps(&database);
|
||||
ImportBaseData(&database);
|
||||
ImportDBStrings(&database);
|
||||
|
||||
EQEmuLogSys::Instance()->CloseFileLogs();
|
||||
|
||||
LogSys.CloseFileLogs();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -128,11 +97,10 @@ bool IsStringField(int i) {
|
||||
}
|
||||
|
||||
void ImportSpells(SharedDatabase *db) {
|
||||
LogInfo("Importing Spells");
|
||||
std::string file = fmt::format("{}/import/spells_us.txt", PathManager::Instance()->GetServerPath());
|
||||
FILE *f = fopen(file.c_str(), "r");
|
||||
Log(Logs::General, Logs::Status, "Importing Spells...");
|
||||
FILE *f = fopen("import/spells_us.txt", "r");
|
||||
if(!f) {
|
||||
LogError("Unable to open {} to read, skipping.", file);
|
||||
Log(Logs::General, Logs::Error, "Unable to open import/spells_us.txt to read, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -151,8 +119,8 @@ void ImportSpells(SharedDatabase *db) {
|
||||
}
|
||||
}
|
||||
|
||||
std::string escaped = ::Strings::Escape(buffer);
|
||||
auto split = Strings::Split(escaped, '^');
|
||||
std::string escaped = ::EscapeString(buffer);
|
||||
auto split = SplitString(escaped, '^');
|
||||
int line_columns = (int)split.size();
|
||||
|
||||
std::string sql;
|
||||
@@ -205,24 +173,23 @@ void ImportSpells(SharedDatabase *db) {
|
||||
|
||||
spells_imported++;
|
||||
if(spells_imported % 1000 == 0) {
|
||||
LogInfo("[{}] spells imported", spells_imported);
|
||||
Log(Logs::General, Logs::Status, "%d spells imported.", spells_imported);
|
||||
}
|
||||
}
|
||||
|
||||
if(spells_imported % 1000 != 0) {
|
||||
LogInfo("[{}] spells imported", spells_imported);
|
||||
Log(Logs::General, Logs::Status, "%d spells imported.", spells_imported);
|
||||
}
|
||||
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ImportSkillCaps(SharedDatabase *db) {
|
||||
LogInfo("Importing Skill Caps");
|
||||
Log(Logs::General, Logs::Status, "Importing Skill Caps...");
|
||||
|
||||
std::string file = fmt::format("{}/import/SkillCaps.txt", PathManager::Instance()->GetServerPath());
|
||||
FILE *f = fopen(file.c_str(), "r");
|
||||
FILE *f = fopen("import/SkillCaps.txt", "r");
|
||||
if(!f) {
|
||||
LogError("Unable to open {} to read, skipping.", file);
|
||||
Log(Logs::General, Logs::Error, "Unable to open import/SkillCaps.txt to read, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -231,17 +198,17 @@ void ImportSkillCaps(SharedDatabase *db) {
|
||||
|
||||
char buffer[2048];
|
||||
while(fgets(buffer, 2048, f)) {
|
||||
auto split = Strings::Split(buffer, '^');
|
||||
auto split = SplitString(buffer, '^');
|
||||
|
||||
if(split.size() < 4) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int class_id, skill_id, level, cap;
|
||||
class_id = Strings::ToInt(split[0].c_str());
|
||||
skill_id = Strings::ToInt(split[1].c_str());
|
||||
level = Strings::ToInt(split[2].c_str());
|
||||
cap = Strings::ToInt(split[3].c_str());
|
||||
class_id = atoi(split[0].c_str());
|
||||
skill_id = atoi(split[1].c_str());
|
||||
level = atoi(split[2].c_str());
|
||||
cap = atoi(split[3].c_str());
|
||||
|
||||
std::string sql = StringFormat("INSERT INTO skill_caps(class, skillID, level, cap) VALUES(%d, %d, %d, %d)",
|
||||
class_id, skill_id, level, cap);
|
||||
@@ -252,54 +219,57 @@ void ImportSkillCaps(SharedDatabase *db) {
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ImportBaseData(SharedDatabase *db)
|
||||
{
|
||||
LogInfo("Importing Base Data");
|
||||
void ImportBaseData(SharedDatabase *db) {
|
||||
Log(Logs::General, Logs::Status, "Importing Base Data...");
|
||||
|
||||
const std::string& file_name = fmt::format("{}/import/BaseData.txt", PathManager::Instance()->GetServerPath());
|
||||
|
||||
const auto& file_contents = File::GetContents(file_name);
|
||||
if (!file_contents.error.empty()) {
|
||||
LogError("{}", file_contents.error);
|
||||
FILE *f = fopen("import/BaseData.txt", "r");
|
||||
if(!f) {
|
||||
Log(Logs::General, Logs::Error, "Unable to open import/BaseData.txt to read, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
db->QueryDatabase("DELETE FROM base_data");
|
||||
std::string delete_sql = "DELETE FROM base_data";
|
||||
db->QueryDatabase(delete_sql);
|
||||
|
||||
std::vector<BaseDataRepository::BaseData> v;
|
||||
char buffer[2048];
|
||||
while(fgets(buffer, 2048, f)) {
|
||||
auto split = SplitString(buffer, '^');
|
||||
|
||||
auto e = BaseDataRepository::NewEntity();
|
||||
|
||||
for (const auto& line: Strings::Split(file_contents.contents, "\n")) {
|
||||
const auto& line_data = Strings::Split(line, '^');
|
||||
|
||||
if (line_data.size() < 10) {
|
||||
if(split.size() < 10) {
|
||||
continue;
|
||||
}
|
||||
|
||||
e.level = static_cast<uint8_t>(Strings::ToUnsignedInt(line_data[0]));
|
||||
e.class_ = static_cast<uint8_t>(Strings::ToUnsignedInt(line_data[1]));
|
||||
e.hp = Strings::ToFloat(line_data[2]);
|
||||
e.mana = Strings::ToFloat(line_data[3]);
|
||||
e.end = Strings::ToFloat(line_data[4]);
|
||||
e.hp_regen = Strings::ToFloat(line_data[5]);
|
||||
e.end_regen = Strings::ToFloat(line_data[6]);
|
||||
e.hp_fac = Strings::ToFloat(line_data[7]);
|
||||
e.mana_fac = Strings::ToFloat(line_data[8]);
|
||||
e.end_fac = Strings::ToFloat(line_data[9]);
|
||||
std::string sql;
|
||||
int level, class_id;
|
||||
double hp, mana, end, unk1, unk2, hp_fac, mana_fac, end_fac;
|
||||
|
||||
v.emplace_back(e);
|
||||
level = atoi(split[0].c_str());
|
||||
class_id = atoi(split[1].c_str());
|
||||
hp = atof(split[2].c_str());
|
||||
mana = atof(split[3].c_str());
|
||||
end = atof(split[4].c_str());
|
||||
unk1 = atof(split[5].c_str());
|
||||
unk2 = atof(split[6].c_str());
|
||||
hp_fac = atof(split[7].c_str());
|
||||
mana_fac = atof(split[8].c_str());
|
||||
end_fac = atof(split[9].c_str());
|
||||
|
||||
sql = StringFormat("INSERT INTO base_data(level, class, hp, mana, end, unk1, unk2, hp_fac, "
|
||||
"mana_fac, end_fac) VALUES(%d, %d, %f, %f, %f, %f, %f, %f, %f, %f)",
|
||||
level, class_id, hp, mana, end, unk1, unk2, hp_fac, mana_fac, end_fac);
|
||||
|
||||
db->QueryDatabase(sql);
|
||||
}
|
||||
|
||||
BaseDataRepository::InsertMany(*db, v);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void ImportDBStrings(SharedDatabase *db) {
|
||||
LogInfo("Importing DB Strings");
|
||||
Log(Logs::General, Logs::Status, "Importing DB Strings...");
|
||||
|
||||
std::string file = fmt::format("{}/import/dbstr_us.txt", PathManager::Instance()->GetServerPath());
|
||||
FILE *f = fopen(file.c_str(), "r");
|
||||
FILE *f = fopen("import/dbstr_us.txt", "r");
|
||||
if(!f) {
|
||||
LogError("Unable to open {} to read, skipping.", file);
|
||||
Log(Logs::General, Logs::Error, "Unable to open import/dbstr_us.txt to read, skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -321,7 +291,7 @@ void ImportDBStrings(SharedDatabase *db) {
|
||||
}
|
||||
}
|
||||
|
||||
auto split = Strings::Split(buffer, '^');
|
||||
auto split = SplitString(buffer, '^');
|
||||
|
||||
if(split.size() < 2) {
|
||||
continue;
|
||||
@@ -330,12 +300,12 @@ void ImportDBStrings(SharedDatabase *db) {
|
||||
std::string sql;
|
||||
int id, type;
|
||||
std::string value;
|
||||
|
||||
id = Strings::ToInt(split[0].c_str());
|
||||
type = Strings::ToInt(split[1].c_str());
|
||||
|
||||
|
||||
id = atoi(split[0].c_str());
|
||||
type = atoi(split[1].c_str());
|
||||
|
||||
if(split.size() >= 3) {
|
||||
value = ::Strings::Escape(split[2]);
|
||||
value = ::EscapeString(split[2]);
|
||||
}
|
||||
|
||||
sql = StringFormat("INSERT INTO db_str(id, type, value) VALUES(%u, %u, '%s')",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
#CMake - Cross Platform Makefile Generator
|
||||
#Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source and binary forms, with or without
|
||||
#modification, are permitted provided that the following conditions
|
||||
#are met:
|
||||
#
|
||||
#* Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
#
|
||||
#* Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
#
|
||||
#* Neither the names of Kitware, Inc., the Insight Software Consortium,
|
||||
# nor the names of their contributors may be used to endorse or promote
|
||||
# products derived from this software without specific prior written
|
||||
# permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
#A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
#HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
#SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
#LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
#THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
# This module defines
|
||||
# LUA51_FOUND, if false, do not try to link to Lua
|
||||
# LUA_LIBRARIES
|
||||
# LUA_INCLUDE_DIR, where to find lua.h
|
||||
# LUA_VERSION_STRING, the version of Lua found (since CMake 2.8.8)
|
||||
|
||||
IF(LUA_ROOT)
|
||||
FIND_PATH(LUA_INCLUDE_DIR
|
||||
NAMES lua.h
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATHS
|
||||
${LUA_ROOT}
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw
|
||||
/opt/local
|
||||
/opt/csw
|
||||
/opt
|
||||
PATH_SUFFIXES include/lua51 include/lua5.1 include/lua include src
|
||||
)
|
||||
|
||||
FIND_LIBRARY(LUA_LIBRARY
|
||||
NAMES lua51 lua5.1 lua-5.1 lua
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATHS
|
||||
${LUA_ROOT}
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw
|
||||
/opt/local
|
||||
/opt/csw
|
||||
/opt
|
||||
PATH_SUFFIXES lib bin
|
||||
)
|
||||
ELSE(LUA_ROOT)
|
||||
FIND_PATH(LUA_INCLUDE_DIR
|
||||
NAMES lua.h
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATHS
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw
|
||||
/opt/local
|
||||
/opt/csw
|
||||
/opt
|
||||
PATH_SUFFIXES include/lua51 include/lua5.1 include/lua include
|
||||
)
|
||||
|
||||
FIND_LIBRARY(LUA_LIBRARY
|
||||
NAMES lua51 lua5.1 lua-5.1 lua
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATHS
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw
|
||||
/opt/local
|
||||
/opt/csw
|
||||
/opt
|
||||
PATH_SUFFIXES lib bin
|
||||
)
|
||||
ENDIF(LUA_ROOT)
|
||||
|
||||
IF(LUA_LIBRARY)
|
||||
# include the math library for Unix
|
||||
IF(UNIX AND NOT APPLE)
|
||||
FIND_LIBRARY(LUA_MATH_LIBRARY m)
|
||||
SET(LUA_LIBRARIES "${LUA_LIBRARY};${LUA_MATH_LIBRARY}" CACHE STRING "Lua Libraries")
|
||||
# For Windows and Mac, don't need to explicitly include the math library
|
||||
ELSE()
|
||||
SET( LUA_LIBRARIES "${LUA_LIBRARY}" CACHE STRING "Lua Libraries")
|
||||
ENDIF()
|
||||
ENDIF()
|
||||
|
||||
IF(LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h")
|
||||
FILE(STRINGS "${LUA_INCLUDE_DIR}/lua.h" lua_version_str REGEX "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua .+\"")
|
||||
|
||||
STRING(REGEX REPLACE "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([^\"]+)\".*" "\\1" LUA_VERSION_STRING "${lua_version_str}")
|
||||
UNSET(lua_version_str)
|
||||
ENDIF()
|
||||
|
||||
INCLUDE(FindPackageHandleStandardArgs)
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua51
|
||||
REQUIRED_VARS LUA_LIBRARIES LUA_INCLUDE_DIR
|
||||
VERSION_VAR LUA_VERSION_STRING)
|
||||
|
||||
MARK_AS_ADVANCED(LUA_INCLUDE_DIR LUA_LIBRARIES LUA_LIBRARY LUA_MATH_LIBRARY)
|
||||
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
|
||||
# file Copyright.txt or https://cmake.org/licensing for details.
|
||||
# Modified from the FindLua51 that comes with CMake
|
||||
|
||||
#[=======================================================================[.rst:
|
||||
FindLuaJit
|
||||
---------
|
||||
|
||||
|
||||
|
||||
Locate LuaJit library This module defines
|
||||
|
||||
::
|
||||
|
||||
LUAJIT_FOUND, if false, do not try to link to Lua
|
||||
LUAJIT_LIBRARIES
|
||||
LUAJIT_INCLUDE_DIR, where to find lua.h
|
||||
LUAJIT_VERSION_STRING, the version of Lua found (since CMake 2.8.8)
|
||||
|
||||
|
||||
|
||||
Note that the expected include convention is
|
||||
|
||||
::
|
||||
|
||||
#include "lua.h"
|
||||
|
||||
and not
|
||||
|
||||
::
|
||||
|
||||
#include <lua/lua.h>
|
||||
|
||||
This is because, the lua location is not standardized and may exist in
|
||||
locations other than lua/
|
||||
#]=======================================================================]
|
||||
|
||||
find_path(LUAJIT_INCLUDE_DIR lua.h
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATH_SUFFIXES include/luajit include/luajit-2.0 include/luajit-2.1 include
|
||||
PATHS
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw # Fink
|
||||
/opt/local # DarwinPorts
|
||||
/opt/csw # Blastwave
|
||||
/opt
|
||||
)
|
||||
|
||||
find_library(LUAJIT_LIBRARY
|
||||
NAMES luajit51 luajit5.1 luajit-5.1 luajit lua51
|
||||
HINTS
|
||||
ENV LUA_DIR
|
||||
PATH_SUFFIXES lib
|
||||
PATHS
|
||||
~/Library/Frameworks
|
||||
/Library/Frameworks
|
||||
/sw
|
||||
/opt/local
|
||||
/opt/csw
|
||||
/opt
|
||||
)
|
||||
|
||||
if(LUAJIT_LIBRARY)
|
||||
# include the math library for Unix
|
||||
if(UNIX AND NOT APPLE AND NOT BEOS AND NOT HAIKU)
|
||||
find_library(LUAJIT_MATH_LIBRARY m)
|
||||
set( LUAJIT_LIBRARIES "${LUAJIT_LIBRARY};${LUAJIT_MATH_LIBRARY}" CACHE STRING "Lua Libraries")
|
||||
# For Windows and Mac, don't need to explicitly include the math library
|
||||
else()
|
||||
set( LUAJIT_LIBRARIES "${LUAJIT_LIBRARY}" CACHE STRING "Lua Libraries")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(LUAJIT_INCLUDE_DIR AND EXISTS "${LUAJIT_INCLUDE_DIR}/lua.h")
|
||||
file(STRINGS "${LUAJIT_INCLUDE_DIR}/lua.h" lua_version_str REGEX "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua .+\"")
|
||||
|
||||
string(REGEX REPLACE "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([^\"]+)\".*" "\\1" LUAJIT_VERSION_STRING "${lua_version_str}")
|
||||
unset(lua_version_str)
|
||||
endif()
|
||||
|
||||
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
|
||||
# handle the QUIETLY and REQUIRED arguments and set LUAJIT_FOUND to TRUE if
|
||||
# all listed variables are TRUE
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LuaJit
|
||||
REQUIRED_VARS LUAJIT_LIBRARIES LUAJIT_INCLUDE_DIR
|
||||
VERSION_VAR LUAJIT_VERSION_STRING)
|
||||
|
||||
mark_as_advanced(LUAJIT_INCLUDE_DIR LUAJIT_LIBRARIES LUAJIT_LIBRARY LUAJIT_MATH_LIBRARY)
|
||||
@@ -0,0 +1,87 @@
|
||||
# - Find mysqlclient
|
||||
#
|
||||
# -*- cmake -*-
|
||||
#
|
||||
# Find the native MySQL includes and library
|
||||
#
|
||||
# MySQL_INCLUDE_DIR - where to find mysql.h, etc.
|
||||
# MySQL_LIBRARIES - List of libraries when using MySQL.
|
||||
# MySQL_FOUND - True if MySQL found.
|
||||
# The following can be used as a hint as to where to search:
|
||||
# MYSQL_ROOT
|
||||
|
||||
IF (MySQL_INCLUDE_DIR AND MySQL_LIBRARIES)
|
||||
# Already in cache, be silent
|
||||
SET(MySQL_FIND_QUIETLY TRUE)
|
||||
ENDIF (MySQL_INCLUDE_DIR AND MySQL_LIBRARIES)
|
||||
|
||||
# Include dir
|
||||
IF(MYSQL_ROOT)
|
||||
FIND_PATH(MySQL_INCLUDE_DIR
|
||||
NAMES mysql.h
|
||||
PATHS ${MYSQL_ROOT}/include
|
||||
PATH_SUFFIXES mysql
|
||||
NO_DEFAULT_PATH
|
||||
NO_SYSTEM_ENVIRONMENT_PATH
|
||||
)
|
||||
FIND_PATH(MySQL_INCLUDE_DIR
|
||||
NAMES mysql.h
|
||||
PATH_SUFFIXES mysql
|
||||
)
|
||||
ELSE(MYSQL_ROOT)
|
||||
FIND_PATH(MySQL_INCLUDE_DIR
|
||||
NAMES mysql.h
|
||||
PATH_SUFFIXES mysql
|
||||
)
|
||||
ENDIF(MYSQL_ROOT)
|
||||
|
||||
# Library
|
||||
SET(MySQL_NAMES libmysql)
|
||||
IF(MYSQL_ROOT)
|
||||
FIND_LIBRARY(MySQL_LIBRARY
|
||||
NAMES ${MySQL_NAMES}
|
||||
PATHS ${MYSQL_ROOT}/lib
|
||||
PATH_SUFFIXES mysql
|
||||
NO_DEFAULT_PATH
|
||||
NO_SYSTEM_ENVIRONMENT_PATH
|
||||
)
|
||||
|
||||
FIND_LIBRARY(MySQL_LIBRARY
|
||||
NAMES ${MySQL_NAMES}
|
||||
PATH_SUFFIXES mysql
|
||||
)
|
||||
ELSE(MYSQL_ROOT)
|
||||
FIND_LIBRARY(MySQL_LIBRARY
|
||||
NAMES ${MySQL_NAMES} mysqlclient_r mysqlclient
|
||||
PATHS /usr/lib /usr/local/lib /usr/lib64 /usr/local/lib64
|
||||
PATH_SUFFIXES mysql
|
||||
)
|
||||
ENDIF(MYSQL_ROOT)
|
||||
|
||||
IF (MySQL_INCLUDE_DIR AND MySQL_LIBRARY)
|
||||
SET(MySQL_FOUND TRUE)
|
||||
SET( MySQL_LIBRARIES ${MySQL_LIBRARY} )
|
||||
ELSE (MySQL_INCLUDE_DIR AND MySQL_LIBRARY)
|
||||
SET(MySQL_FOUND FALSE)
|
||||
SET( MySQL_LIBRARIES )
|
||||
ENDIF (MySQL_INCLUDE_DIR AND MySQL_LIBRARY)
|
||||
|
||||
|
||||
# handle the QUIETLY and REQUIRED arguments and set MySQL_FOUND to TRUE if
|
||||
# all listed variables are TRUE
|
||||
INCLUDE(FindPackageHandleStandardArgs)
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(MySQL DEFAULT_MSG MySQL_LIBRARY MySQL_INCLUDE_DIR)
|
||||
|
||||
IF(MySQL_FOUND)
|
||||
SET( MySQL_LIBRARY_RELEASE ${MySQL_LIBRARY} )
|
||||
SET( MySQL_LIBRARY_DEBUG ${MySQL_LIBRARY} )
|
||||
SET( MySQL_LIBRARIES ${MySQL_LIBRARY_RELEASE} ${MySQL_LIBRARY_DEBUG} )
|
||||
ELSE(MySQL_FOUND)
|
||||
SET( MySQL_LIBRARIES )
|
||||
ENDIF(MySQL_FOUND)
|
||||
|
||||
MARK_AS_ADVANCED(
|
||||
MySQL_LIBRARY_DEBUG
|
||||
MySQL_LIBRARY_RELEASE
|
||||
MySQL_INCLUDE_DIR
|
||||
)
|
||||
@@ -0,0 +1,386 @@
|
||||
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
|
||||
# file Copyright.txt or https://cmake.org/licensing for details.
|
||||
|
||||
#[=======================================================================[.rst:
|
||||
FindPackageHandleStandardArgs
|
||||
-----------------------------
|
||||
|
||||
This module provides a function intended to be used in :ref:`Find Modules`
|
||||
implementing :command:`find_package(<PackageName>)` calls. It handles the
|
||||
``REQUIRED``, ``QUIET`` and version-related arguments of ``find_package``.
|
||||
It also sets the ``<PackageName>_FOUND`` variable. The package is
|
||||
considered found if all variables listed contain valid results, e.g.
|
||||
valid filepaths.
|
||||
|
||||
.. command:: find_package_handle_standard_args
|
||||
|
||||
There are two signatures::
|
||||
|
||||
find_package_handle_standard_args(<PackageName>
|
||||
(DEFAULT_MSG|<custom-failure-message>)
|
||||
<required-var>...
|
||||
)
|
||||
|
||||
find_package_handle_standard_args(<PackageName>
|
||||
[FOUND_VAR <result-var>]
|
||||
[REQUIRED_VARS <required-var>...]
|
||||
[VERSION_VAR <version-var>]
|
||||
[HANDLE_COMPONENTS]
|
||||
[CONFIG_MODE]
|
||||
[FAIL_MESSAGE <custom-failure-message>]
|
||||
)
|
||||
|
||||
The ``<PackageName>_FOUND`` variable will be set to ``TRUE`` if all
|
||||
the variables ``<required-var>...`` are valid and any optional
|
||||
constraints are satisfied, and ``FALSE`` otherwise. A success or
|
||||
failure message may be displayed based on the results and on
|
||||
whether the ``REQUIRED`` and/or ``QUIET`` option was given to
|
||||
the :command:`find_package` call.
|
||||
|
||||
The options are:
|
||||
|
||||
``(DEFAULT_MSG|<custom-failure-message>)``
|
||||
In the simple signature this specifies the failure message.
|
||||
Use ``DEFAULT_MSG`` to ask for a default message to be computed
|
||||
(recommended). Not valid in the full signature.
|
||||
|
||||
``FOUND_VAR <result-var>``
|
||||
Obsolete. Specifies either ``<PackageName>_FOUND`` or
|
||||
``<PACKAGENAME>_FOUND`` as the result variable. This exists only
|
||||
for compatibility with older versions of CMake and is now ignored.
|
||||
Result variables of both names are always set for compatibility.
|
||||
|
||||
``REQUIRED_VARS <required-var>...``
|
||||
Specify the variables which are required for this package.
|
||||
These may be named in the generated failure message asking the
|
||||
user to set the missing variable values. Therefore these should
|
||||
typically be cache entries such as ``FOO_LIBRARY`` and not output
|
||||
variables like ``FOO_LIBRARIES``.
|
||||
|
||||
``VERSION_VAR <version-var>``
|
||||
Specify the name of a variable that holds the version of the package
|
||||
that has been found. This version will be checked against the
|
||||
(potentially) specified required version given to the
|
||||
:command:`find_package` call, including its ``EXACT`` option.
|
||||
The default messages include information about the required
|
||||
version and the version which has been actually found, both
|
||||
if the version is ok or not.
|
||||
|
||||
``HANDLE_COMPONENTS``
|
||||
Enable handling of package components. In this case, the command
|
||||
will report which components have been found and which are missing,
|
||||
and the ``<PackageName>_FOUND`` variable will be set to ``FALSE``
|
||||
if any of the required components (i.e. not the ones listed after
|
||||
the ``OPTIONAL_COMPONENTS`` option of :command:`find_package`) are
|
||||
missing.
|
||||
|
||||
``CONFIG_MODE``
|
||||
Specify that the calling find module is a wrapper around a
|
||||
call to ``find_package(<PackageName> NO_MODULE)``. This implies
|
||||
a ``VERSION_VAR`` value of ``<PackageName>_VERSION``. The command
|
||||
will automatically check whether the package configuration file
|
||||
was found.
|
||||
|
||||
``FAIL_MESSAGE <custom-failure-message>``
|
||||
Specify a custom failure message instead of using the default
|
||||
generated message. Not recommended.
|
||||
|
||||
Example for the simple signature:
|
||||
|
||||
.. code-block:: cmake
|
||||
|
||||
find_package_handle_standard_args(LibXml2 DEFAULT_MSG
|
||||
LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
|
||||
|
||||
The ``LibXml2`` package is considered to be found if both
|
||||
``LIBXML2_LIBRARY`` and ``LIBXML2_INCLUDE_DIR`` are valid.
|
||||
Then also ``LibXml2_FOUND`` is set to ``TRUE``. If it is not found
|
||||
and ``REQUIRED`` was used, it fails with a
|
||||
:command:`message(FATAL_ERROR)`, independent whether ``QUIET`` was
|
||||
used or not. If it is found, success will be reported, including
|
||||
the content of the first ``<required-var>``. On repeated CMake runs,
|
||||
the same message will not be printed again.
|
||||
|
||||
Example for the full signature:
|
||||
|
||||
.. code-block:: cmake
|
||||
|
||||
find_package_handle_standard_args(LibArchive
|
||||
REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
|
||||
VERSION_VAR LibArchive_VERSION)
|
||||
|
||||
In this case, the ``LibArchive`` package is considered to be found if
|
||||
both ``LibArchive_LIBRARY`` and ``LibArchive_INCLUDE_DIR`` are valid.
|
||||
Also the version of ``LibArchive`` will be checked by using the version
|
||||
contained in ``LibArchive_VERSION``. Since no ``FAIL_MESSAGE`` is given,
|
||||
the default messages will be printed.
|
||||
|
||||
Another example for the full signature:
|
||||
|
||||
.. code-block:: cmake
|
||||
|
||||
find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
|
||||
find_package_handle_standard_args(Automoc4 CONFIG_MODE)
|
||||
|
||||
In this case, a ``FindAutmoc4.cmake`` module wraps a call to
|
||||
``find_package(Automoc4 NO_MODULE)`` and adds an additional search
|
||||
directory for ``automoc4``. Then the call to
|
||||
``find_package_handle_standard_args`` produces a proper success/failure
|
||||
message.
|
||||
#]=======================================================================]
|
||||
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake)
|
||||
|
||||
# internal helper macro
|
||||
macro(_FPHSA_FAILURE_MESSAGE _msg)
|
||||
if (${_NAME}_FIND_REQUIRED)
|
||||
message(FATAL_ERROR "${_msg}")
|
||||
else ()
|
||||
if (NOT ${_NAME}_FIND_QUIETLY)
|
||||
message(STATUS "${_msg}")
|
||||
endif ()
|
||||
endif ()
|
||||
endmacro()
|
||||
|
||||
|
||||
# internal helper macro to generate the failure message when used in CONFIG_MODE:
|
||||
macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE)
|
||||
# <name>_CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found:
|
||||
if(${_NAME}_CONFIG)
|
||||
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing:${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})")
|
||||
else()
|
||||
# If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version.
|
||||
# List them all in the error message:
|
||||
if(${_NAME}_CONSIDERED_CONFIGS)
|
||||
set(configsText "")
|
||||
list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount)
|
||||
math(EXPR configsCount "${configsCount} - 1")
|
||||
foreach(currentConfigIndex RANGE ${configsCount})
|
||||
list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename)
|
||||
list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version)
|
||||
string(APPEND configsText " ${filename} (version ${version})\n")
|
||||
endforeach()
|
||||
if (${_NAME}_NOT_FOUND_MESSAGE)
|
||||
string(APPEND configsText " Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n")
|
||||
endif()
|
||||
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}")
|
||||
|
||||
else()
|
||||
# Simple case: No Config-file was found at all:
|
||||
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}")
|
||||
endif()
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
|
||||
function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
|
||||
|
||||
# Set up the arguments for `cmake_parse_arguments`.
|
||||
set(options CONFIG_MODE HANDLE_COMPONENTS)
|
||||
set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR)
|
||||
set(multiValueArgs REQUIRED_VARS)
|
||||
|
||||
# Check whether we are in 'simple' or 'extended' mode:
|
||||
set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} )
|
||||
list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX)
|
||||
|
||||
if(${INDEX} EQUAL -1)
|
||||
set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG})
|
||||
set(FPHSA_REQUIRED_VARS ${ARGN})
|
||||
set(FPHSA_VERSION_VAR)
|
||||
else()
|
||||
cmake_parse_arguments(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN})
|
||||
|
||||
if(FPHSA_UNPARSED_ARGUMENTS)
|
||||
message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"")
|
||||
endif()
|
||||
|
||||
if(NOT FPHSA_FAIL_MESSAGE)
|
||||
set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG")
|
||||
endif()
|
||||
|
||||
# In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package()
|
||||
# when it successfully found the config-file, including version checking:
|
||||
if(FPHSA_CONFIG_MODE)
|
||||
list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG)
|
||||
list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS)
|
||||
set(FPHSA_VERSION_VAR ${_NAME}_VERSION)
|
||||
endif()
|
||||
|
||||
if(NOT FPHSA_REQUIRED_VARS)
|
||||
message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# now that we collected all arguments, process them
|
||||
|
||||
if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG")
|
||||
set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}")
|
||||
endif()
|
||||
|
||||
list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR)
|
||||
|
||||
string(TOUPPER ${_NAME} _NAME_UPPER)
|
||||
string(TOLOWER ${_NAME} _NAME_LOWER)
|
||||
|
||||
if(FPHSA_FOUND_VAR)
|
||||
if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$")
|
||||
set(_FOUND_VAR ${FPHSA_FOUND_VAR})
|
||||
else()
|
||||
message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.")
|
||||
endif()
|
||||
else()
|
||||
set(_FOUND_VAR ${_NAME_UPPER}_FOUND)
|
||||
endif()
|
||||
|
||||
# collect all variables which were not found, so they can be printed, so the
|
||||
# user knows better what went wrong (#6375)
|
||||
set(MISSING_VARS "")
|
||||
set(DETAILS "")
|
||||
# check if all passed variables are valid
|
||||
set(FPHSA_FOUND_${_NAME} TRUE)
|
||||
foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS})
|
||||
if(NOT ${_CURRENT_VAR})
|
||||
set(FPHSA_FOUND_${_NAME} FALSE)
|
||||
string(APPEND MISSING_VARS " ${_CURRENT_VAR}")
|
||||
else()
|
||||
string(APPEND DETAILS "[${${_CURRENT_VAR}}]")
|
||||
endif()
|
||||
endforeach()
|
||||
if(FPHSA_FOUND_${_NAME})
|
||||
set(${_NAME}_FOUND TRUE)
|
||||
set(${_NAME_UPPER}_FOUND TRUE)
|
||||
else()
|
||||
set(${_NAME}_FOUND FALSE)
|
||||
set(${_NAME_UPPER}_FOUND FALSE)
|
||||
endif()
|
||||
|
||||
# component handling
|
||||
unset(FOUND_COMPONENTS_MSG)
|
||||
unset(MISSING_COMPONENTS_MSG)
|
||||
|
||||
if(FPHSA_HANDLE_COMPONENTS)
|
||||
foreach(comp ${${_NAME}_FIND_COMPONENTS})
|
||||
if(${_NAME}_${comp}_FOUND)
|
||||
|
||||
if(NOT DEFINED FOUND_COMPONENTS_MSG)
|
||||
set(FOUND_COMPONENTS_MSG "found components: ")
|
||||
endif()
|
||||
string(APPEND FOUND_COMPONENTS_MSG " ${comp}")
|
||||
|
||||
else()
|
||||
|
||||
if(NOT DEFINED MISSING_COMPONENTS_MSG)
|
||||
set(MISSING_COMPONENTS_MSG "missing components: ")
|
||||
endif()
|
||||
string(APPEND MISSING_COMPONENTS_MSG " ${comp}")
|
||||
|
||||
if(${_NAME}_FIND_REQUIRED_${comp})
|
||||
set(${_NAME}_FOUND FALSE)
|
||||
string(APPEND MISSING_VARS " ${comp}")
|
||||
endif()
|
||||
|
||||
endif()
|
||||
endforeach()
|
||||
set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}")
|
||||
string(APPEND DETAILS "[c${COMPONENT_MSG}]")
|
||||
endif()
|
||||
|
||||
# version handling:
|
||||
set(VERSION_MSG "")
|
||||
set(VERSION_OK TRUE)
|
||||
|
||||
# check with DEFINED here as the requested or found version may be "0"
|
||||
if (DEFINED ${_NAME}_FIND_VERSION)
|
||||
if(DEFINED ${FPHSA_VERSION_VAR})
|
||||
set(_FOUND_VERSION ${${FPHSA_VERSION_VAR}})
|
||||
|
||||
if(${_NAME}_FIND_VERSION_EXACT) # exact version required
|
||||
# count the dots in the version string
|
||||
string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${_FOUND_VERSION}")
|
||||
# add one dot because there is one dot more than there are components
|
||||
string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS)
|
||||
if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT)
|
||||
# Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT
|
||||
# is at most 4 here. Therefore a simple lookup table is used.
|
||||
if (${_NAME}_FIND_VERSION_COUNT EQUAL 1)
|
||||
set(_VERSION_REGEX "[^.]*")
|
||||
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2)
|
||||
set(_VERSION_REGEX "[^.]*\\.[^.]*")
|
||||
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3)
|
||||
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*")
|
||||
else ()
|
||||
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*")
|
||||
endif ()
|
||||
string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${_FOUND_VERSION}")
|
||||
unset(_VERSION_REGEX)
|
||||
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD)
|
||||
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
|
||||
set(VERSION_OK FALSE)
|
||||
else ()
|
||||
set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
|
||||
endif ()
|
||||
unset(_VERSION_HEAD)
|
||||
else ()
|
||||
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _FOUND_VERSION)
|
||||
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
|
||||
set(VERSION_OK FALSE)
|
||||
else ()
|
||||
set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
|
||||
endif ()
|
||||
endif ()
|
||||
unset(_VERSION_DOTS)
|
||||
|
||||
else() # minimum version specified:
|
||||
if (${_NAME}_FIND_VERSION VERSION_GREATER _FOUND_VERSION)
|
||||
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"")
|
||||
set(VERSION_OK FALSE)
|
||||
else ()
|
||||
set(VERSION_MSG "(found suitable version \"${_FOUND_VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")")
|
||||
endif ()
|
||||
endif()
|
||||
|
||||
else()
|
||||
|
||||
# if the package was not found, but a version was given, add that to the output:
|
||||
if(${_NAME}_FIND_VERSION_EXACT)
|
||||
set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")")
|
||||
else()
|
||||
set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")")
|
||||
endif()
|
||||
|
||||
endif()
|
||||
else ()
|
||||
# Check with DEFINED as the found version may be 0.
|
||||
if(DEFINED ${FPHSA_VERSION_VAR})
|
||||
set(VERSION_MSG "(found version \"${${FPHSA_VERSION_VAR}}\")")
|
||||
endif()
|
||||
endif ()
|
||||
|
||||
if(VERSION_OK)
|
||||
string(APPEND DETAILS "[v${${FPHSA_VERSION_VAR}}(${${_NAME}_FIND_VERSION})]")
|
||||
else()
|
||||
set(${_NAME}_FOUND FALSE)
|
||||
endif()
|
||||
|
||||
|
||||
# print the result:
|
||||
if (${_NAME}_FOUND)
|
||||
FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}")
|
||||
else ()
|
||||
|
||||
if(FPHSA_CONFIG_MODE)
|
||||
_FPHSA_HANDLE_FAILURE_CONFIG_MODE()
|
||||
else()
|
||||
if(NOT VERSION_OK)
|
||||
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})")
|
||||
else()
|
||||
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing:${MISSING_VARS}) ${VERSION_MSG}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
endif ()
|
||||
|
||||
set(${_NAME}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE)
|
||||
set(${_NAME_UPPER}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE)
|
||||
endfunction()
|
||||
@@ -0,0 +1,47 @@
|
||||
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
|
||||
# file Copyright.txt or https://cmake.org/licensing for details.
|
||||
|
||||
#.rst:
|
||||
# FindPackageMessage
|
||||
# ------------------
|
||||
#
|
||||
#
|
||||
#
|
||||
# FIND_PACKAGE_MESSAGE(<name> "message for user" "find result details")
|
||||
#
|
||||
# This macro is intended to be used in FindXXX.cmake modules files. It
|
||||
# will print a message once for each unique find result. This is useful
|
||||
# for telling the user where a package was found. The first argument
|
||||
# specifies the name (XXX) of the package. The second argument
|
||||
# specifies the message to display. The third argument lists details
|
||||
# about the find result so that if they change the message will be
|
||||
# displayed again. The macro also obeys the QUIET argument to the
|
||||
# find_package command.
|
||||
#
|
||||
# Example:
|
||||
#
|
||||
# ::
|
||||
#
|
||||
# if(X11_FOUND)
|
||||
# FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}"
|
||||
# "[${X11_X11_LIB}][${X11_INCLUDE_DIR}]")
|
||||
# else()
|
||||
# ...
|
||||
# endif()
|
||||
|
||||
function(FIND_PACKAGE_MESSAGE pkg msg details)
|
||||
# Avoid printing a message repeatedly for the same find result.
|
||||
if(NOT ${pkg}_FIND_QUIETLY)
|
||||
string(REPLACE "\n" "" details "${details}")
|
||||
set(DETAILS_VAR FIND_PACKAGE_MESSAGE_DETAILS_${pkg})
|
||||
if(NOT "${details}" STREQUAL "${${DETAILS_VAR}}")
|
||||
# The message has not yet been printed.
|
||||
message(STATUS "${msg}")
|
||||
|
||||
# Save the find details in the cache to avoid printing the same
|
||||
# message again.
|
||||
set("${DETAILS_VAR}" "${details}"
|
||||
CACHE INTERNAL "Details about finding ${pkg}")
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
@@ -0,0 +1,579 @@
|
||||
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
|
||||
# file Copyright.txt or https://cmake.org/licensing for details.
|
||||
|
||||
#.rst:
|
||||
# FindProtobuf
|
||||
# ------------
|
||||
#
|
||||
# Locate and configure the Google Protocol Buffers library.
|
||||
#
|
||||
# The following variables can be set and are optional:
|
||||
#
|
||||
# ``Protobuf_SRC_ROOT_FOLDER``
|
||||
# When compiling with MSVC, if this cache variable is set
|
||||
# the protobuf-default VS project build locations
|
||||
# (vsprojects/Debug and vsprojects/Release
|
||||
# or vsprojects/x64/Debug and vsprojects/x64/Release)
|
||||
# will be searched for libraries and binaries.
|
||||
# ``Protobuf_IMPORT_DIRS``
|
||||
# List of additional directories to be searched for
|
||||
# imported .proto files.
|
||||
# ``Protobuf_DEBUG``
|
||||
# Show debug messages.
|
||||
# ``Protobuf_USE_STATIC_LIBS``
|
||||
# Set to ON to force the use of the static libraries.
|
||||
# Default is OFF.
|
||||
#
|
||||
# Defines the following variables:
|
||||
#
|
||||
# ``Protobuf_FOUND``
|
||||
# Found the Google Protocol Buffers library
|
||||
# (libprotobuf & header files)
|
||||
# ``Protobuf_VERSION``
|
||||
# Version of package found.
|
||||
# ``Protobuf_INCLUDE_DIRS``
|
||||
# Include directories for Google Protocol Buffers
|
||||
# ``Protobuf_LIBRARIES``
|
||||
# The protobuf libraries
|
||||
# ``Protobuf_PROTOC_LIBRARIES``
|
||||
# The protoc libraries
|
||||
# ``Protobuf_LITE_LIBRARIES``
|
||||
# The protobuf-lite libraries
|
||||
#
|
||||
# The following :prop_tgt:`IMPORTED` targets are also defined:
|
||||
#
|
||||
# ``protobuf::libprotobuf``
|
||||
# The protobuf library.
|
||||
# ``protobuf::libprotobuf-lite``
|
||||
# The protobuf lite library.
|
||||
# ``protobuf::libprotoc``
|
||||
# The protoc library.
|
||||
# ``protobuf::protoc``
|
||||
# The protoc compiler.
|
||||
#
|
||||
# The following cache variables are also available to set or use:
|
||||
#
|
||||
# ``Protobuf_LIBRARY``
|
||||
# The protobuf library
|
||||
# ``Protobuf_PROTOC_LIBRARY``
|
||||
# The protoc library
|
||||
# ``Protobuf_INCLUDE_DIR``
|
||||
# The include directory for protocol buffers
|
||||
# ``Protobuf_PROTOC_EXECUTABLE``
|
||||
# The protoc compiler
|
||||
# ``Protobuf_LIBRARY_DEBUG``
|
||||
# The protobuf library (debug)
|
||||
# ``Protobuf_PROTOC_LIBRARY_DEBUG``
|
||||
# The protoc library (debug)
|
||||
# ``Protobuf_LITE_LIBRARY``
|
||||
# The protobuf lite library
|
||||
# ``Protobuf_LITE_LIBRARY_DEBUG``
|
||||
# The protobuf lite library (debug)
|
||||
#
|
||||
# Example:
|
||||
#
|
||||
# .. code-block:: cmake
|
||||
#
|
||||
# find_package(Protobuf REQUIRED)
|
||||
# include_directories(${Protobuf_INCLUDE_DIRS})
|
||||
# include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||
# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS foo.proto)
|
||||
# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS EXPORT_MACRO DLL_EXPORT foo.proto)
|
||||
# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS DESCRIPTORS PROTO_DESCS foo.proto)
|
||||
# protobuf_generate_python(PROTO_PY foo.proto)
|
||||
# add_executable(bar bar.cc ${PROTO_SRCS} ${PROTO_HDRS})
|
||||
# target_link_libraries(bar ${Protobuf_LIBRARIES})
|
||||
#
|
||||
# .. note::
|
||||
# The ``protobuf_generate_cpp`` and ``protobuf_generate_python``
|
||||
# functions and :command:`add_executable` or :command:`add_library`
|
||||
# calls only work properly within the same directory.
|
||||
#
|
||||
# .. command:: protobuf_generate_cpp
|
||||
#
|
||||
# Add custom commands to process ``.proto`` files to C++::
|
||||
#
|
||||
# protobuf_generate_cpp (<SRCS> <HDRS>
|
||||
# [DESCRIPTORS <DESC>] [EXPORT_MACRO <MACRO>] [<ARGN>...])
|
||||
#
|
||||
# ``SRCS``
|
||||
# Variable to define with autogenerated source files
|
||||
# ``HDRS``
|
||||
# Variable to define with autogenerated header files
|
||||
# ``DESCRIPTORS``
|
||||
# Variable to define with autogenerated descriptor files, if requested.
|
||||
# ``EXPORT_MACRO``
|
||||
# is a macro which should expand to ``__declspec(dllexport)`` or
|
||||
# ``__declspec(dllimport)`` depending on what is being compiled.
|
||||
# ``ARGN``
|
||||
# ``.proto`` files
|
||||
#
|
||||
# .. command:: protobuf_generate_python
|
||||
#
|
||||
# Add custom commands to process ``.proto`` files to Python::
|
||||
#
|
||||
# protobuf_generate_python (<PY> [<ARGN>...])
|
||||
#
|
||||
# ``PY``
|
||||
# Variable to define with autogenerated Python files
|
||||
# ``ARGN``
|
||||
# ``.proto`` filess
|
||||
|
||||
function(PROTOBUF_GENERATE_CPP SRCS HDRS)
|
||||
cmake_parse_arguments(protobuf "" "EXPORT_MACRO;DESCRIPTORS" "" ${ARGN})
|
||||
|
||||
set(PROTO_FILES "${protobuf_UNPARSED_ARGUMENTS}")
|
||||
if(NOT PROTO_FILES)
|
||||
message(SEND_ERROR "Error: PROTOBUF_GENERATE_CPP() called without any proto files")
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(protobuf_EXPORT_MACRO)
|
||||
set(DLL_EXPORT_DECL "dllexport_decl=${protobuf_EXPORT_MACRO}:")
|
||||
endif()
|
||||
|
||||
if(PROTOBUF_GENERATE_CPP_APPEND_PATH)
|
||||
# Create an include path for each file specified
|
||||
foreach(FIL ${PROTO_FILES})
|
||||
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
|
||||
get_filename_component(ABS_PATH ${ABS_FIL} PATH)
|
||||
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
|
||||
if(${_contains_already} EQUAL -1)
|
||||
list(APPEND _protobuf_include_path -I ${ABS_PATH})
|
||||
endif()
|
||||
endforeach()
|
||||
else()
|
||||
set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
endif()
|
||||
|
||||
if(DEFINED PROTOBUF_IMPORT_DIRS AND NOT DEFINED Protobuf_IMPORT_DIRS)
|
||||
set(Protobuf_IMPORT_DIRS "${PROTOBUF_IMPORT_DIRS}")
|
||||
endif()
|
||||
|
||||
if(DEFINED Protobuf_IMPORT_DIRS)
|
||||
foreach(DIR ${Protobuf_IMPORT_DIRS})
|
||||
get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
|
||||
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
|
||||
if(${_contains_already} EQUAL -1)
|
||||
list(APPEND _protobuf_include_path -I ${ABS_PATH})
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
set(${SRCS})
|
||||
set(${HDRS})
|
||||
if (protobuf_DESCRIPTORS)
|
||||
set(${protobuf_DESCRIPTORS})
|
||||
endif()
|
||||
|
||||
foreach(FIL ${PROTO_FILES})
|
||||
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
|
||||
get_filename_component(FIL_WE ${FIL} NAME_WE)
|
||||
if(NOT PROTOBUF_GENERATE_CPP_APPEND_PATH)
|
||||
get_filename_component(FIL_DIR ${FIL} DIRECTORY)
|
||||
if(FIL_DIR)
|
||||
set(FIL_WE "${FIL_DIR}/${FIL_WE}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(_protobuf_protoc_src "${CMAKE_CURRENT_SOURCE_DIR}/${FIL_WE}.pb.cc")
|
||||
set(_protobuf_protoc_hdr "${CMAKE_CURRENT_SOURCE_DIR}/${FIL_WE}.pb.h")
|
||||
list(APPEND ${SRCS} "${_protobuf_protoc_src}")
|
||||
list(APPEND ${HDRS} "${_protobuf_protoc_hdr}")
|
||||
|
||||
if(protobuf_DESCRIPTORS)
|
||||
set(_protobuf_protoc_desc "${CMAKE_CURRENT_SOURCE_DIR}/${FIL_WE}.desc")
|
||||
set(_protobuf_protoc_flags "--descriptor_set_out=${_protobuf_protoc_desc}")
|
||||
list(APPEND ${protobuf_DESCRIPTORS} "${_protobuf_protoc_desc}")
|
||||
else()
|
||||
set(_protobuf_protoc_desc "")
|
||||
set(_protobuf_protoc_flags "")
|
||||
endif()
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${_protobuf_protoc_src}"
|
||||
"${_protobuf_protoc_hdr}"
|
||||
${_protobuf_protoc_desc}
|
||||
COMMAND protobuf::protoc
|
||||
"--cpp_out=${DLL_EXPORT_DECL}${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
${_protobuf_protoc_flags}
|
||||
${_protobuf_include_path} ${ABS_FIL}
|
||||
DEPENDS ${ABS_FIL} protobuf::protoc
|
||||
COMMENT "Running C++ protocol buffer compiler on ${FIL}"
|
||||
VERBATIM )
|
||||
endforeach()
|
||||
|
||||
set(${SRCS} "${${SRCS}}" PARENT_SCOPE)
|
||||
set(${HDRS} "${${HDRS}}" PARENT_SCOPE)
|
||||
if(protobuf_DESCRIPTORS)
|
||||
set(${protobuf_DESCRIPTORS} "${${protobuf_DESCRIPTORS}}" PARENT_SCOPE)
|
||||
endif()
|
||||
|
||||
endfunction()
|
||||
|
||||
function(PROTOBUF_GENERATE_PYTHON SRCS)
|
||||
if(NOT ARGN)
|
||||
message(SEND_ERROR "Error: PROTOBUF_GENERATE_PYTHON() called without any proto files")
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(PROTOBUF_GENERATE_CPP_APPEND_PATH)
|
||||
# Create an include path for each file specified
|
||||
foreach(FIL ${ARGN})
|
||||
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
|
||||
get_filename_component(ABS_PATH ${ABS_FIL} PATH)
|
||||
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
|
||||
if(${_contains_already} EQUAL -1)
|
||||
list(APPEND _protobuf_include_path -I ${ABS_PATH})
|
||||
endif()
|
||||
endforeach()
|
||||
else()
|
||||
set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
endif()
|
||||
|
||||
if(DEFINED PROTOBUF_IMPORT_DIRS AND NOT DEFINED Protobuf_IMPORT_DIRS)
|
||||
set(Protobuf_IMPORT_DIRS "${PROTOBUF_IMPORT_DIRS}")
|
||||
endif()
|
||||
|
||||
if(DEFINED Protobuf_IMPORT_DIRS)
|
||||
foreach(DIR ${Protobuf_IMPORT_DIRS})
|
||||
get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
|
||||
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
|
||||
if(${_contains_already} EQUAL -1)
|
||||
list(APPEND _protobuf_include_path -I ${ABS_PATH})
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
set(${SRCS})
|
||||
foreach(FIL ${ARGN})
|
||||
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
|
||||
get_filename_component(FIL_WE ${FIL} NAME_WE)
|
||||
if(NOT PROTOBUF_GENERATE_CPP_APPEND_PATH)
|
||||
get_filename_component(FIL_DIR ${FIL} DIRECTORY)
|
||||
if(FIL_DIR)
|
||||
set(FIL_WE "${FIL_DIR}/${FIL_WE}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py")
|
||||
add_custom_command(
|
||||
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py"
|
||||
COMMAND protobuf::protoc --python_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
|
||||
DEPENDS ${ABS_FIL} protobuf::protoc
|
||||
COMMENT "Running Python protocol buffer compiler on ${FIL}"
|
||||
VERBATIM )
|
||||
endforeach()
|
||||
|
||||
set(${SRCS} ${${SRCS}} PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
|
||||
if(Protobuf_DEBUG)
|
||||
# Output some of their choices
|
||||
message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
|
||||
"Protobuf_USE_STATIC_LIBS = ${Protobuf_USE_STATIC_LIBS}")
|
||||
endif()
|
||||
|
||||
|
||||
# Backwards compatibility
|
||||
# Define camel case versions of input variables
|
||||
foreach(UPPER
|
||||
PROTOBUF_SRC_ROOT_FOLDER
|
||||
PROTOBUF_IMPORT_DIRS
|
||||
PROTOBUF_DEBUG
|
||||
PROTOBUF_LIBRARY
|
||||
PROTOBUF_PROTOC_LIBRARY
|
||||
PROTOBUF_INCLUDE_DIR
|
||||
PROTOBUF_PROTOC_EXECUTABLE
|
||||
PROTOBUF_LIBRARY_DEBUG
|
||||
PROTOBUF_PROTOC_LIBRARY_DEBUG
|
||||
PROTOBUF_LITE_LIBRARY
|
||||
PROTOBUF_LITE_LIBRARY_DEBUG
|
||||
)
|
||||
if (DEFINED ${UPPER})
|
||||
string(REPLACE "PROTOBUF_" "Protobuf_" Camel ${UPPER})
|
||||
if (NOT DEFINED ${Camel})
|
||||
set(${Camel} ${${UPPER}})
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
set(_PROTOBUF_ARCH_DIR x64/)
|
||||
endif()
|
||||
|
||||
|
||||
# Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES
|
||||
if( Protobuf_USE_STATIC_LIBS )
|
||||
set( _protobuf_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
|
||||
if(WIN32)
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
|
||||
else()
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES .a )
|
||||
endif()
|
||||
endif()
|
||||
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
|
||||
|
||||
# Internal function: search for normal library as well as a debug one
|
||||
# if the debug one is specified also include debug/optimized keywords
|
||||
# in *_LIBRARIES variable
|
||||
function(_protobuf_find_libraries name filename)
|
||||
if(${name}_LIBRARIES)
|
||||
# Use result recorded by a previous call.
|
||||
return()
|
||||
elseif(${name}_LIBRARY)
|
||||
# Honor cache entry used by CMake 3.5 and lower.
|
||||
set(${name}_LIBRARIES "${${name}_LIBRARY}" PARENT_SCOPE)
|
||||
else()
|
||||
find_library(${name}_LIBRARY_RELEASE
|
||||
NAMES ${filename}
|
||||
PATHS ${Protobuf_SRC_ROOT_FOLDER}/vsprojects/${_PROTOBUF_ARCH_DIR}Release)
|
||||
mark_as_advanced(${name}_LIBRARY_RELEASE)
|
||||
|
||||
find_library(${name}_LIBRARY_DEBUG
|
||||
NAMES ${filename}d ${filename}
|
||||
PATHS ${Protobuf_SRC_ROOT_FOLDER}/vsprojects/${_PROTOBUF_ARCH_DIR}Debug)
|
||||
mark_as_advanced(${name}_LIBRARY_DEBUG)
|
||||
|
||||
select_library_configurations(${name})
|
||||
set(${name}_LIBRARY "${${name}_LIBRARY}" PARENT_SCOPE)
|
||||
set(${name}_LIBRARIES "${${name}_LIBRARIES}" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Internal function: find threads library
|
||||
function(_protobuf_find_threads)
|
||||
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
|
||||
find_package(Threads)
|
||||
if(Threads_FOUND)
|
||||
list(APPEND Protobuf_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
|
||||
set(Protobuf_LIBRARIES "${Protobuf_LIBRARIES}" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
#
|
||||
# Main.
|
||||
#
|
||||
|
||||
# By default have PROTOBUF_GENERATE_CPP macro pass -I to protoc
|
||||
# for each directory where a proto file is referenced.
|
||||
if(NOT DEFINED PROTOBUF_GENERATE_CPP_APPEND_PATH)
|
||||
set(PROTOBUF_GENERATE_CPP_APPEND_PATH TRUE)
|
||||
endif()
|
||||
|
||||
|
||||
# Google's provided vcproj files generate libraries with a "lib"
|
||||
# prefix on Windows
|
||||
if(MSVC)
|
||||
set(Protobuf_ORIG_FIND_LIBRARY_PREFIXES "${CMAKE_FIND_LIBRARY_PREFIXES}")
|
||||
set(CMAKE_FIND_LIBRARY_PREFIXES "lib" "")
|
||||
|
||||
find_path(Protobuf_SRC_ROOT_FOLDER protobuf.pc.in)
|
||||
endif()
|
||||
|
||||
# The Protobuf library
|
||||
_protobuf_find_libraries(Protobuf protobuf)
|
||||
#DOC "The Google Protocol Buffers RELEASE Library"
|
||||
|
||||
_protobuf_find_libraries(Protobuf_LITE protobuf-lite)
|
||||
|
||||
# The Protobuf Protoc Library
|
||||
_protobuf_find_libraries(Protobuf_PROTOC protoc)
|
||||
|
||||
# Restore original find library prefixes
|
||||
if(MSVC)
|
||||
set(CMAKE_FIND_LIBRARY_PREFIXES "${Protobuf_ORIG_FIND_LIBRARY_PREFIXES}")
|
||||
endif()
|
||||
|
||||
if(UNIX)
|
||||
_protobuf_find_threads()
|
||||
endif()
|
||||
|
||||
# Find the include directory
|
||||
find_path(Protobuf_INCLUDE_DIR
|
||||
google/protobuf/service.h
|
||||
PATHS ${Protobuf_SRC_ROOT_FOLDER}/src
|
||||
)
|
||||
mark_as_advanced(Protobuf_INCLUDE_DIR)
|
||||
|
||||
# Find the protoc Executable
|
||||
find_program(Protobuf_PROTOC_EXECUTABLE
|
||||
NAMES protoc
|
||||
DOC "The Google Protocol Buffers Compiler"
|
||||
PATHS /usr/bin
|
||||
${Protobuf_SRC_ROOT_FOLDER}/vsprojects/${_PROTOBUF_ARCH_DIR}Release
|
||||
${Protobuf_SRC_ROOT_FOLDER}/vsprojects/${_PROTOBUF_ARCH_DIR}Debug
|
||||
)
|
||||
mark_as_advanced(Protobuf_PROTOC_EXECUTABLE)
|
||||
|
||||
if(Protobuf_DEBUG)
|
||||
message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
|
||||
"requested version of Google Protobuf is ${Protobuf_FIND_VERSION}")
|
||||
endif()
|
||||
|
||||
if(Protobuf_INCLUDE_DIR)
|
||||
set(_PROTOBUF_COMMON_HEADER ${Protobuf_INCLUDE_DIR}/google/protobuf/stubs/common.h)
|
||||
|
||||
if(Protobuf_DEBUG)
|
||||
message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
|
||||
"location of common.h: ${_PROTOBUF_COMMON_HEADER}")
|
||||
endif()
|
||||
|
||||
set(Protobuf_VERSION "")
|
||||
set(Protobuf_LIB_VERSION "")
|
||||
file(STRINGS ${_PROTOBUF_COMMON_HEADER} _PROTOBUF_COMMON_H_CONTENTS REGEX "#define[ \t]+GOOGLE_PROTOBUF_VERSION[ \t]+")
|
||||
if(_PROTOBUF_COMMON_H_CONTENTS MATCHES "#define[ \t]+GOOGLE_PROTOBUF_VERSION[ \t]+([0-9]+)")
|
||||
set(Protobuf_LIB_VERSION "${CMAKE_MATCH_1}")
|
||||
endif()
|
||||
unset(_PROTOBUF_COMMON_H_CONTENTS)
|
||||
|
||||
math(EXPR _PROTOBUF_MAJOR_VERSION "${Protobuf_LIB_VERSION} / 1000000")
|
||||
math(EXPR _PROTOBUF_MINOR_VERSION "${Protobuf_LIB_VERSION} / 1000 % 1000")
|
||||
math(EXPR _PROTOBUF_SUBMINOR_VERSION "${Protobuf_LIB_VERSION} % 1000")
|
||||
set(Protobuf_VERSION "${_PROTOBUF_MAJOR_VERSION}.${_PROTOBUF_MINOR_VERSION}.${_PROTOBUF_SUBMINOR_VERSION}")
|
||||
|
||||
if(Protobuf_DEBUG)
|
||||
message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
|
||||
"${_PROTOBUF_COMMON_HEADER} reveals protobuf ${Protobuf_VERSION}")
|
||||
endif()
|
||||
|
||||
# Check Protobuf compiler version to be aligned with libraries version
|
||||
execute_process(COMMAND ${Protobuf_PROTOC_EXECUTABLE} --version
|
||||
OUTPUT_VARIABLE _PROTOBUF_PROTOC_EXECUTABLE_VERSION)
|
||||
|
||||
if("${_PROTOBUF_PROTOC_EXECUTABLE_VERSION}" MATCHES "libprotoc ([0-9.]+)")
|
||||
set(_PROTOBUF_PROTOC_EXECUTABLE_VERSION "${CMAKE_MATCH_1}")
|
||||
endif()
|
||||
|
||||
if(Protobuf_DEBUG)
|
||||
message(STATUS "[ ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE} ] "
|
||||
"${Protobuf_PROTOC_EXECUTABLE} reveals version ${_PROTOBUF_PROTOC_EXECUTABLE_VERSION}")
|
||||
endif()
|
||||
|
||||
if(NOT "${_PROTOBUF_PROTOC_EXECUTABLE_VERSION}" VERSION_EQUAL "${Protobuf_VERSION}")
|
||||
message(WARNING "Protobuf compiler version ${_PROTOBUF_PROTOC_EXECUTABLE_VERSION}"
|
||||
" doesn't match library version ${Protobuf_VERSION}")
|
||||
endif()
|
||||
|
||||
if(Protobuf_LIBRARY)
|
||||
if(NOT TARGET protobuf::libprotobuf)
|
||||
add_library(protobuf::libprotobuf UNKNOWN IMPORTED)
|
||||
set_target_properties(protobuf::libprotobuf PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${Protobuf_INCLUDE_DIR}")
|
||||
if(EXISTS "${Protobuf_LIBRARY}")
|
||||
set_target_properties(protobuf::libprotobuf PROPERTIES
|
||||
IMPORTED_LOCATION "${Protobuf_LIBRARY}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_LIBRARY_RELEASE}")
|
||||
set_property(TARGET protobuf::libprotobuf APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS RELEASE)
|
||||
set_target_properties(protobuf::libprotobuf PROPERTIES
|
||||
IMPORTED_LOCATION_RELEASE "${Protobuf_LIBRARY_RELEASE}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_LIBRARY_DEBUG}")
|
||||
set_property(TARGET protobuf::libprotobuf APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS DEBUG)
|
||||
set_target_properties(protobuf::libprotobuf PROPERTIES
|
||||
IMPORTED_LOCATION_DEBUG "${Protobuf_LIBRARY_DEBUG}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(Protobuf_LITE_LIBRARY)
|
||||
if(NOT TARGET protobuf::libprotobuf-lite)
|
||||
add_library(protobuf::libprotobuf-lite UNKNOWN IMPORTED)
|
||||
set_target_properties(protobuf::libprotobuf-lite PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${Protobuf_INCLUDE_DIR}")
|
||||
if(EXISTS "${Protobuf_LITE_LIBRARY}")
|
||||
set_target_properties(protobuf::libprotobuf-lite PROPERTIES
|
||||
IMPORTED_LOCATION "${Protobuf_LITE_LIBRARY}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_LITE_LIBRARY_RELEASE}")
|
||||
set_property(TARGET protobuf::libprotobuf-lite APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS RELEASE)
|
||||
set_target_properties(protobuf::libprotobuf-lite PROPERTIES
|
||||
IMPORTED_LOCATION_RELEASE "${Protobuf_LITE_LIBRARY_RELEASE}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_LITE_LIBRARY_DEBUG}")
|
||||
set_property(TARGET protobuf::libprotobuf-lite APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS DEBUG)
|
||||
set_target_properties(protobuf::libprotobuf-lite PROPERTIES
|
||||
IMPORTED_LOCATION_DEBUG "${Protobuf_LITE_LIBRARY_DEBUG}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(Protobuf_PROTOC_LIBRARY)
|
||||
if(NOT TARGET protobuf::libprotoc)
|
||||
add_library(protobuf::libprotoc UNKNOWN IMPORTED)
|
||||
set_target_properties(protobuf::libprotoc PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${Protobuf_INCLUDE_DIR}")
|
||||
if(EXISTS "${Protobuf_PROTOC_LIBRARY}")
|
||||
set_target_properties(protobuf::libprotoc PROPERTIES
|
||||
IMPORTED_LOCATION "${Protobuf_PROTOC_LIBRARY}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_PROTOC_LIBRARY_RELEASE}")
|
||||
set_property(TARGET protobuf::libprotoc APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS RELEASE)
|
||||
set_target_properties(protobuf::libprotoc PROPERTIES
|
||||
IMPORTED_LOCATION_RELEASE "${Protobuf_PROTOC_LIBRARY_RELEASE}")
|
||||
endif()
|
||||
if(EXISTS "${Protobuf_PROTOC_LIBRARY_DEBUG}")
|
||||
set_property(TARGET protobuf::libprotoc APPEND PROPERTY
|
||||
IMPORTED_CONFIGURATIONS DEBUG)
|
||||
set_target_properties(protobuf::libprotoc PROPERTIES
|
||||
IMPORTED_LOCATION_DEBUG "${Protobuf_PROTOC_LIBRARY_DEBUG}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(Protobuf_PROTOC_EXECUTABLE)
|
||||
if(NOT TARGET protobuf::protoc)
|
||||
add_executable(protobuf::protoc IMPORTED)
|
||||
if(EXISTS "${Protobuf_PROTOC_EXECUTABLE}")
|
||||
set_target_properties(protobuf::protoc PROPERTIES
|
||||
IMPORTED_LOCATION "${Protobuf_PROTOC_EXECUTABLE}")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Protobuf
|
||||
REQUIRED_VARS Protobuf_LIBRARIES Protobuf_INCLUDE_DIR
|
||||
VERSION_VAR Protobuf_VERSION
|
||||
)
|
||||
|
||||
if(Protobuf_FOUND)
|
||||
set(Protobuf_INCLUDE_DIRS ${Protobuf_INCLUDE_DIR})
|
||||
endif()
|
||||
|
||||
# Restore the original find library ordering
|
||||
if( Protobuf_USE_STATIC_LIBS )
|
||||
set(CMAKE_FIND_LIBRARY_SUFFIXES ${_protobuf_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
|
||||
endif()
|
||||
|
||||
# Backwards compatibility
|
||||
# Define upper case versions of output variables
|
||||
foreach(Camel
|
||||
Protobuf_SRC_ROOT_FOLDER
|
||||
Protobuf_IMPORT_DIRS
|
||||
Protobuf_DEBUG
|
||||
Protobuf_INCLUDE_DIRS
|
||||
Protobuf_LIBRARIES
|
||||
Protobuf_PROTOC_LIBRARIES
|
||||
Protobuf_LITE_LIBRARIES
|
||||
Protobuf_LIBRARY
|
||||
Protobuf_PROTOC_LIBRARY
|
||||
Protobuf_INCLUDE_DIR
|
||||
Protobuf_PROTOC_EXECUTABLE
|
||||
Protobuf_LIBRARY_DEBUG
|
||||
Protobuf_PROTOC_LIBRARY_DEBUG
|
||||
Protobuf_LITE_LIBRARY
|
||||
Protobuf_LITE_LIBRARY_DEBUG
|
||||
)
|
||||
string(TOUPPER ${Camel} UPPER)
|
||||
set(${UPPER} ${${Camel}})
|
||||
endforeach()
|
||||
@@ -0,0 +1,30 @@
|
||||
if (NOT MSVC)
|
||||
include(FindPkgConfig)
|
||||
pkg_check_modules(PC_SODIUM "libsodium")
|
||||
if (NOT PC_SODIUM_FOUND)
|
||||
pkg_check_modules(PC_SODIUM "sodium")
|
||||
endif (NOT PC_SODIUM_FOUND)
|
||||
if (PC_SODIUM_FOUND)
|
||||
set(SODIUM_INCLUDE_HINTS ${PC_SODIUM_INCLUDE_DIRS} ${PC_SODIUM_INCLUDE_DIRS}/*)
|
||||
set(SODIUM_LIBRARY_HINTS ${PC_SODIUM_LIBRARY_DIRS} ${PC_SODIUM_LIBRARY_DIRS}/*)
|
||||
endif()
|
||||
endif (NOT MSVC)
|
||||
|
||||
# some libraries install the headers is a subdirectory of the include dir
|
||||
# returned by pkg-config, so use a wildcard match to improve chances of finding
|
||||
# headers and libraries.
|
||||
find_path(
|
||||
SODIUM_INCLUDE_DIRS
|
||||
NAMES sodium.h
|
||||
HINTS ${SODIUM_INCLUDE_HINTS}
|
||||
)
|
||||
|
||||
find_library(
|
||||
SODIUM_LIBRARIES
|
||||
NAMES libsodium sodium
|
||||
HINTS ${SODIUM_LIBRARY_HINTS}
|
||||
)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(SODIUM DEFAULT_MSG SODIUM_LIBRARIES SODIUM_INCLUDE_DIRS)
|
||||
mark_as_advanced(SODIUM_FOUND SODIUM_LIBRARIES SODIUM_INCLUDE_DIRS)
|
||||
@@ -0,0 +1,71 @@
|
||||
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
|
||||
# file Copyright.txt or https://cmake.org/licensing for details.
|
||||
|
||||
#.rst:
|
||||
# SelectLibraryConfigurations
|
||||
# ---------------------------
|
||||
#
|
||||
#
|
||||
#
|
||||
# select_library_configurations( basename )
|
||||
#
|
||||
# This macro takes a library base name as an argument, and will choose
|
||||
# good values for basename_LIBRARY, basename_LIBRARIES,
|
||||
# basename_LIBRARY_DEBUG, and basename_LIBRARY_RELEASE depending on what
|
||||
# has been found and set. If only basename_LIBRARY_RELEASE is defined,
|
||||
# basename_LIBRARY will be set to the release value, and
|
||||
# basename_LIBRARY_DEBUG will be set to basename_LIBRARY_DEBUG-NOTFOUND.
|
||||
# If only basename_LIBRARY_DEBUG is defined, then basename_LIBRARY will
|
||||
# take the debug value, and basename_LIBRARY_RELEASE will be set to
|
||||
# basename_LIBRARY_RELEASE-NOTFOUND.
|
||||
#
|
||||
# If the generator supports configuration types, then basename_LIBRARY
|
||||
# and basename_LIBRARIES will be set with debug and optimized flags
|
||||
# specifying the library to be used for the given configuration. If no
|
||||
# build type has been set or the generator in use does not support
|
||||
# configuration types, then basename_LIBRARY and basename_LIBRARIES will
|
||||
# take only the release value, or the debug value if the release one is
|
||||
# not set.
|
||||
|
||||
# This macro was adapted from the FindQt4 CMake module and is maintained by Will
|
||||
# Dicharry <wdicharry@stellarscience.com>.
|
||||
|
||||
macro( select_library_configurations basename )
|
||||
if(NOT ${basename}_LIBRARY_RELEASE)
|
||||
set(${basename}_LIBRARY_RELEASE "${basename}_LIBRARY_RELEASE-NOTFOUND" CACHE FILEPATH "Path to a library.")
|
||||
endif()
|
||||
if(NOT ${basename}_LIBRARY_DEBUG)
|
||||
set(${basename}_LIBRARY_DEBUG "${basename}_LIBRARY_DEBUG-NOTFOUND" CACHE FILEPATH "Path to a library.")
|
||||
endif()
|
||||
|
||||
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||
if( ${basename}_LIBRARY_DEBUG AND ${basename}_LIBRARY_RELEASE AND
|
||||
NOT ${basename}_LIBRARY_DEBUG STREQUAL ${basename}_LIBRARY_RELEASE AND
|
||||
( _isMultiConfig OR CMAKE_BUILD_TYPE ) )
|
||||
# if the generator is multi-config or if CMAKE_BUILD_TYPE is set for
|
||||
# single-config generators, set optimized and debug libraries
|
||||
set( ${basename}_LIBRARY "" )
|
||||
foreach( _libname IN LISTS ${basename}_LIBRARY_RELEASE )
|
||||
list( APPEND ${basename}_LIBRARY optimized "${_libname}" )
|
||||
endforeach()
|
||||
foreach( _libname IN LISTS ${basename}_LIBRARY_DEBUG )
|
||||
list( APPEND ${basename}_LIBRARY debug "${_libname}" )
|
||||
endforeach()
|
||||
elseif( ${basename}_LIBRARY_RELEASE )
|
||||
set( ${basename}_LIBRARY ${${basename}_LIBRARY_RELEASE} )
|
||||
elseif( ${basename}_LIBRARY_DEBUG )
|
||||
set( ${basename}_LIBRARY ${${basename}_LIBRARY_DEBUG} )
|
||||
else()
|
||||
set( ${basename}_LIBRARY "${basename}_LIBRARY-NOTFOUND")
|
||||
endif()
|
||||
|
||||
set( ${basename}_LIBRARIES "${${basename}_LIBRARY}" )
|
||||
|
||||
if( ${basename}_LIBRARY )
|
||||
set( ${basename}_FOUND TRUE )
|
||||
endif()
|
||||
|
||||
mark_as_advanced( ${basename}_LIBRARY_RELEASE
|
||||
${basename}_LIBRARY_DEBUG
|
||||
)
|
||||
endmacro()
|
||||
+248
-672
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,266 @@
|
||||
/** \file Base64.cpp
|
||||
** \date 2004-02-13
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#include "Base64.h"
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
const char *Base64::bstr =
|
||||
"ABCDEFGHIJKLMNOPQ"
|
||||
"RSTUVWXYZabcdefgh"
|
||||
"ijklmnopqrstuvwxy"
|
||||
"z0123456789+/";
|
||||
|
||||
const char Base64::rstr[] = {
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
|
||||
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0,
|
||||
0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
|
||||
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0};
|
||||
|
||||
|
||||
void Base64::encode(FILE *fil, std::string& output, bool add_crlf)
|
||||
{
|
||||
size_t remain;
|
||||
size_t i = 0;
|
||||
size_t o = 0;
|
||||
char input[4];
|
||||
|
||||
output = "";
|
||||
remain = fread(input,1,3,fil);
|
||||
while (remain > 0)
|
||||
{
|
||||
if (add_crlf && o && o % 76 == 0)
|
||||
output += "\n";
|
||||
switch (remain)
|
||||
{
|
||||
case 1:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) ];
|
||||
output += "==";
|
||||
break;
|
||||
case 2:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
|
||||
output += "=";
|
||||
break;
|
||||
default:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
|
||||
output += bstr[ (input[i + 2] & 0x3f) ];
|
||||
}
|
||||
o += 4;
|
||||
//
|
||||
remain = fread(input,1,3,fil);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Base64::encode(const std::string& str_in, std::string& str_out, bool add_crlf)
|
||||
{
|
||||
encode(str_in.c_str(), str_in.size(), str_out, add_crlf);
|
||||
}
|
||||
|
||||
|
||||
void Base64::encode(const char* input,size_t l,std::string& output, bool add_crlf)
|
||||
{
|
||||
size_t i = 0;
|
||||
size_t o = 0;
|
||||
|
||||
output = "";
|
||||
while (i < l)
|
||||
{
|
||||
size_t remain = l - i;
|
||||
if (add_crlf && o && o % 76 == 0)
|
||||
output += "\n";
|
||||
switch (remain)
|
||||
{
|
||||
case 1:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) ];
|
||||
output += "==";
|
||||
break;
|
||||
case 2:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
|
||||
output += "=";
|
||||
break;
|
||||
default:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
|
||||
output += bstr[ (input[i + 2] & 0x3f) ];
|
||||
}
|
||||
o += 4;
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Base64::encode(unsigned char* input,size_t l,std::string& output,bool add_crlf)
|
||||
{
|
||||
size_t i = 0;
|
||||
size_t o = 0;
|
||||
|
||||
output = "";
|
||||
while (i < l)
|
||||
{
|
||||
size_t remain = l - i;
|
||||
if (add_crlf && o && o % 76 == 0)
|
||||
output += "\n";
|
||||
switch (remain)
|
||||
{
|
||||
case 1:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) ];
|
||||
output += "==";
|
||||
break;
|
||||
case 2:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) ];
|
||||
output += "=";
|
||||
break;
|
||||
default:
|
||||
output += bstr[ ((input[i] >> 2) & 0x3f) ];
|
||||
output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ];
|
||||
output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ];
|
||||
output += bstr[ (input[i + 2] & 0x3f) ];
|
||||
}
|
||||
o += 4;
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Base64::decode(const std::string& input,std::string& output)
|
||||
{
|
||||
size_t i = 0;
|
||||
size_t l = input.size();
|
||||
|
||||
output = "";
|
||||
while (i < l)
|
||||
{
|
||||
while (i < l && (input[i] == 13 || input[i] == 10))
|
||||
i++;
|
||||
if (i < l)
|
||||
{
|
||||
char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) +
|
||||
(rstr[(int)input[i + 1]] >> 4 & 0x03));
|
||||
output += b1;
|
||||
if (input[i + 2] != '=')
|
||||
{
|
||||
char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
|
||||
(rstr[(int)input[i + 2]] >> 2 & 0x0f));
|
||||
output += b2;
|
||||
}
|
||||
if (input[i + 3] != '=')
|
||||
{
|
||||
char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
|
||||
rstr[(int)input[i + 3]]);
|
||||
output += b3;
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Base64::decode(const std::string& input, unsigned char *output, size_t& sz)
|
||||
{
|
||||
size_t i = 0;
|
||||
size_t l = input.size();
|
||||
size_t j = 0;
|
||||
|
||||
while (i < l)
|
||||
{
|
||||
while (i < l && (input[i] == 13 || input[i] == 10))
|
||||
i++;
|
||||
if (i < l)
|
||||
{
|
||||
unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) +
|
||||
(rstr[(int)input[i + 1]] >> 4 & 0x03));
|
||||
if (output)
|
||||
{
|
||||
output[j] = b1;
|
||||
}
|
||||
j++;
|
||||
if (input[i + 2] != '=')
|
||||
{
|
||||
unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) +
|
||||
(rstr[(int)input[i + 2]] >> 2 & 0x0f));
|
||||
if (output)
|
||||
{
|
||||
output[j] = b2;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
if (input[i + 3] != '=')
|
||||
{
|
||||
unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) +
|
||||
rstr[(int)input[i + 3]]);
|
||||
if (output)
|
||||
{
|
||||
output[j] = b3;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
sz = j;
|
||||
}
|
||||
|
||||
|
||||
size_t Base64::decode_length(const std::string& str64)
|
||||
{
|
||||
if (!str64.size() || str64.size() % 4)
|
||||
return 0;
|
||||
size_t l = 3 * (str64.size() / 4 - 1) + 1;
|
||||
if (str64[str64.size() - 2] != '=')
|
||||
l++;
|
||||
if (str64[str64.size() - 1] != '=')
|
||||
l++;
|
||||
return l;
|
||||
}
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/** \file Base64.h
|
||||
** \date 2004-02-13
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _BASE64_H
|
||||
#define _BASE64_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
/** \defgroup util Utilities */
|
||||
|
||||
/** Base64 encode/decode.
|
||||
\ingroup util */
|
||||
class Base64 {
|
||||
public:
|
||||
|
||||
static void encode(FILE *, std::string& , bool add_crlf = true);
|
||||
static void encode(const std::string&, std::string& , bool add_crlf = true);
|
||||
static void encode(const char *, size_t, std::string& , bool add_crlf = true);
|
||||
static void encode(unsigned char *, size_t, std::string& , bool add_crlf = true);
|
||||
|
||||
static void decode(const std::string&, std::string& );
|
||||
static void decode(const std::string& in, unsigned char *out, size_t&);
|
||||
|
||||
static size_t decode_length(const std::string& );
|
||||
|
||||
private:
|
||||
static const char *bstr;
|
||||
static const char rstr[128];
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _BASE64_H
|
||||
@@ -0,0 +1,126 @@
|
||||
/** \file File.cpp
|
||||
** \date 2005-04-25
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include "File.h"
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
File::File()
|
||||
:m_fil(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
File::~File()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
bool File::fopen(const std::string& path, const std::string& mode)
|
||||
{
|
||||
m_path = path;
|
||||
m_mode = mode;
|
||||
m_fil = ::fopen(path.c_str(), mode.c_str());
|
||||
return m_fil ? true : false;
|
||||
}
|
||||
|
||||
|
||||
void File::fclose()
|
||||
{
|
||||
if (m_fil)
|
||||
::fclose(m_fil);
|
||||
}
|
||||
|
||||
|
||||
|
||||
size_t File::fread(char *ptr, size_t size, size_t nmemb)
|
||||
{
|
||||
return m_fil ? ::fread(ptr, size, nmemb, m_fil) : 0;
|
||||
}
|
||||
|
||||
|
||||
size_t File::fwrite(const char *ptr, size_t size, size_t nmemb)
|
||||
{
|
||||
return m_fil ? ::fwrite(ptr, size, nmemb, m_fil) : 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
char *File::fgets(char *s, int size)
|
||||
{
|
||||
return m_fil ? ::fgets(s, size, m_fil) : nullptr;
|
||||
}
|
||||
|
||||
|
||||
void File::fprintf(char *format, ...)
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
vfprintf(m_fil, format, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
|
||||
off_t File::size()
|
||||
{
|
||||
struct stat st;
|
||||
if (stat(m_path.c_str(), &st) == -1)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return st.st_size;
|
||||
}
|
||||
|
||||
|
||||
bool File::eof()
|
||||
{
|
||||
if (m_fil)
|
||||
{
|
||||
if (feof(m_fil))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/** \file File.h
|
||||
** \date 2005-04-25
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _FILE_H
|
||||
#define _FILE_H
|
||||
|
||||
#include "IFile.h"
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
/** IFile implementation of a disk file.
|
||||
\ingroup file */
|
||||
class File : public IFile
|
||||
{
|
||||
public:
|
||||
File();
|
||||
~File();
|
||||
|
||||
bool fopen(const std::string&, const std::string&);
|
||||
void fclose();
|
||||
|
||||
size_t fread(char *, size_t, size_t);
|
||||
size_t fwrite(const char *, size_t, size_t);
|
||||
|
||||
char *fgets(char *, int);
|
||||
void fprintf(char *format, ...);
|
||||
|
||||
off_t size();
|
||||
bool eof();
|
||||
|
||||
private:
|
||||
File(const File& ) {} // copy constructor
|
||||
File& operator=(const File& ) { return *this; } // assignment operator
|
||||
|
||||
std::string m_path;
|
||||
std::string m_mode;
|
||||
FILE *m_fil;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _FILE_H
|
||||
@@ -0,0 +1,366 @@
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
*
|
||||
* This code originated from `C++ Sockets Library` referenced below.
|
||||
* Taken and stripped/modified to remove dependancies on parts of
|
||||
* the library which we are not using, and to suit other needs.
|
||||
* 2006 - EQEMu Development Team (http://eqemulator.net)
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
/** \file HTTPSocket.cpp
|
||||
** \date 2004-04-06
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
#include "../global_define.h"
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
#include <stdarg.h>
|
||||
#include "Parse.h"
|
||||
#include "HTTPSocket.h"
|
||||
#include "../tcp_connection.h"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
HTTPSocket::HTTPSocket(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort)
|
||||
:TCPConnection(ID,in_socket,irIP,irPort)
|
||||
,m_first(true)
|
||||
,m_header(true)
|
||||
,m_http_version("HTTP/1.0")
|
||||
,m_request(false)
|
||||
,m_response(false)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
HTTPSocket::~HTTPSocket()
|
||||
{
|
||||
}
|
||||
|
||||
/*
|
||||
* eqemu stuff
|
||||
*/
|
||||
|
||||
bool HTTPSocket::ProcessReceivedData(char *errbuf)
|
||||
{
|
||||
if (errbuf)
|
||||
errbuf[0] = 0;
|
||||
if (!recvbuf)
|
||||
return true;
|
||||
|
||||
char *buff=(char *)recvbuf;
|
||||
unsigned long bufflen=recvbuf_used;
|
||||
|
||||
while(1) {
|
||||
if (m_header) {
|
||||
char *ptr=(char *)memchr(buff,'\n',bufflen);
|
||||
if (!ptr)
|
||||
break;
|
||||
int length=(ptr-buff)+1;
|
||||
std::string line;
|
||||
line.append(buff,length-2);
|
||||
OnLine(line);
|
||||
|
||||
buff+=length;
|
||||
bufflen-=length;
|
||||
} else {
|
||||
OnData(buff,bufflen);
|
||||
buff+=bufflen;
|
||||
bufflen=0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (bufflen) {
|
||||
memmove(recvbuf,buff,bufflen);
|
||||
recvbuf_used=bufflen;
|
||||
} else {
|
||||
safe_delete_array(recvbuf);
|
||||
}
|
||||
}
|
||||
|
||||
bool HTTPSocket::SendString(const char *str) {
|
||||
return(TCPConnection::Send((const uchar *) str, strlen(str)));
|
||||
}
|
||||
|
||||
bool HTTPSocket::SendBuf(const char *dat, unsigned int len) {
|
||||
return(TCPConnection::Send((const uchar *) dat, len));
|
||||
}
|
||||
|
||||
/*
|
||||
* /eqemu stuff
|
||||
*/
|
||||
|
||||
void HTTPSocket::OnLine(const std::string& line)
|
||||
{
|
||||
if (m_first)
|
||||
{
|
||||
Parse pa(line);
|
||||
std::string str = pa.getword();
|
||||
if (str.substr(0,4) == "HTTP") // response
|
||||
{
|
||||
m_http_version = str;
|
||||
m_status = pa.getword();
|
||||
m_status_text = pa.getrest();
|
||||
m_response = true;
|
||||
}
|
||||
else // request
|
||||
{
|
||||
m_method = str;
|
||||
m_url = pa.getword();
|
||||
size_t spl = m_url.find("?");
|
||||
if (spl != std::string::npos)
|
||||
{
|
||||
m_uri = m_url.substr(0,spl);
|
||||
m_query_string = m_url.substr(spl + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_uri = m_url;
|
||||
}
|
||||
m_http_version = pa.getword();
|
||||
m_request = true;
|
||||
}
|
||||
m_first = false;
|
||||
OnFirst();
|
||||
return;
|
||||
}
|
||||
if (!line.size())
|
||||
{
|
||||
// SetLineProtocol(false);
|
||||
m_header = false;
|
||||
OnHeaderComplete();
|
||||
return;
|
||||
}
|
||||
Parse pa(line,":");
|
||||
std::string key = pa.getword();
|
||||
std::string value = pa.getrest();
|
||||
OnHeader(key,value);
|
||||
/* If remote end tells us to keep connection alive, and we're operating
|
||||
in http/1.1 mode (not http/1.0 mode), then we mark the socket to be
|
||||
retained. */
|
||||
/* if (!strcasecmp(key.c_str(), "connection") &&
|
||||
!strcasecmp(value.c_str(), "keep-alive") )
|
||||
{
|
||||
SetRetain();
|
||||
}*/
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SendResponse()
|
||||
{
|
||||
std::string msg;
|
||||
msg = m_http_version + " " + m_status + " " + m_status_text + "\r\n";
|
||||
for (string_m::iterator it = m_response_header.begin(); it != m_response_header.end(); it++)
|
||||
{
|
||||
std::string key = (*it).first;
|
||||
std::string val = (*it).second;
|
||||
msg += key + ": " + val + "\r\n";
|
||||
}
|
||||
msg += "\r\n";
|
||||
SendString( msg.c_str() );
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::AddResponseHeader(const std::string& header, const char *format, ...)
|
||||
{
|
||||
static char slask[5000];
|
||||
va_list ap;
|
||||
|
||||
va_start(ap, format);
|
||||
#ifdef _WIN32
|
||||
vsprintf(slask, format, ap);
|
||||
#else
|
||||
vsnprintf(slask, 5000, format, ap);
|
||||
#endif
|
||||
va_end(ap);
|
||||
|
||||
m_response_header[header] = slask;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SendRequest()
|
||||
{
|
||||
std::string msg;
|
||||
msg = m_method + " " + m_url + " " + m_http_version + "\r\n";
|
||||
for (string_m::iterator it = m_response_header.begin(); it != m_response_header.end(); it++)
|
||||
{
|
||||
std::string key = (*it).first;
|
||||
std::string val = (*it).second;
|
||||
msg += key + ": " + val + "\r\n";
|
||||
}
|
||||
msg += "\r\n";
|
||||
SendString( msg.c_str() );
|
||||
}
|
||||
|
||||
|
||||
std::string HTTPSocket::MyUseragent()
|
||||
{
|
||||
std::string version = "C++Sockets/";
|
||||
#ifdef _VERSION
|
||||
version += _VERSION;
|
||||
#endif
|
||||
return version;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::Reset()
|
||||
{
|
||||
m_first = true;
|
||||
m_header = true;
|
||||
m_request = false;
|
||||
m_response = false;
|
||||
// SetLineProtocol(true);
|
||||
while (m_response_header.size())
|
||||
{
|
||||
string_m::iterator it = m_response_header.begin();
|
||||
m_response_header.erase(it);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetMethod()
|
||||
{
|
||||
return m_method;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetMethod(const std::string& x)
|
||||
{
|
||||
m_method = x;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetUrl()
|
||||
{
|
||||
return m_url;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetUrl(const std::string& x)
|
||||
{
|
||||
m_url = x;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetUri()
|
||||
{
|
||||
return m_uri;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetQueryString()
|
||||
{
|
||||
return m_query_string;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetHttpVersion()
|
||||
{
|
||||
return m_http_version;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetStatus()
|
||||
{
|
||||
return m_status;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HTTPSocket::GetStatusText()
|
||||
{
|
||||
return m_status_text;
|
||||
}
|
||||
|
||||
|
||||
bool HTTPSocket::IsRequest()
|
||||
{
|
||||
return m_request;
|
||||
}
|
||||
|
||||
|
||||
bool HTTPSocket::IsResponse()
|
||||
{
|
||||
return m_response;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetHttpVersion(const std::string& x)
|
||||
{
|
||||
m_http_version = x;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetStatus(const std::string& num, const std::string& text) {
|
||||
m_status = num;
|
||||
m_status_text = text;
|
||||
}
|
||||
|
||||
void HTTPSocket::SetStatus(const std::string& x)
|
||||
{
|
||||
m_status = x;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetStatusText(const std::string& x)
|
||||
{
|
||||
m_status_text = x;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::AddResponseHeader(const std::string& x,const std::string& y)
|
||||
{
|
||||
m_response_header[x] = y;
|
||||
}
|
||||
|
||||
|
||||
void HTTPSocket::SetUri(const std::string& x)
|
||||
{
|
||||
m_uri = x;
|
||||
}
|
||||
|
||||
void HTTPSocket::SendResponse(const std::string& status_num, const std::string& status_text) {
|
||||
SetStatus(status_num, status_text);
|
||||
SendResponse();
|
||||
}
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
*
|
||||
* This code originated from `C++ Sockets Library` referenced below.
|
||||
* Taken and stripped/modified to remove dependancies on parts of
|
||||
* the library which we are not using, and to suit other needs.
|
||||
* 2006 - EQEMu Development Team (http://eqemulator.net)
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
/** \file HTTPSocket.h Class HTTPSocket definition.
|
||||
** \date 2004-04-06
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _HTTPSOCKET_H
|
||||
#define _HTTPSOCKET_H
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include "../tcp_connection.h"
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
/** \defgroup http HTTP Sockets */
|
||||
/** HTTP request/response base class.
|
||||
\ingroup http */
|
||||
class HTTPSocket : public TCPConnection
|
||||
{
|
||||
/** map to hold http header values. */
|
||||
typedef std::map<std::string,std::string> string_m;
|
||||
public:
|
||||
HTTPSocket(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort);
|
||||
virtual ~HTTPSocket();
|
||||
|
||||
void OnLine(const std::string& line);
|
||||
|
||||
/** Callback executes when first line has been received.
|
||||
GetMethod, GetUrl/GetUri, and GetHttpVersion are valid when this callback is executed. */
|
||||
virtual void OnFirst() = 0;
|
||||
/** For each header line this callback is executed.
|
||||
\param key Http header name
|
||||
\param value Http header value */
|
||||
virtual void OnHeader(const std::string& key,const std::string& value) = 0;
|
||||
/** Callback fires when all http headers have been received. */
|
||||
virtual void OnHeaderComplete() = 0;
|
||||
/** Chunk of http body data recevied. */
|
||||
virtual void OnData(const char *,size_t) = 0;
|
||||
|
||||
const std::string& GetMethod();
|
||||
void SetMethod(const std::string& x);
|
||||
const std::string& GetUrl();
|
||||
void SetUrl(const std::string& x);
|
||||
const std::string& GetUri();
|
||||
void SetUri(const std::string& x);
|
||||
const std::string& GetQueryString();
|
||||
const std::string& GetHttpVersion();
|
||||
const std::string& GetStatus();
|
||||
const std::string& GetStatusText();
|
||||
bool IsRequest();
|
||||
bool IsResponse();
|
||||
|
||||
void SetHttpVersion(const std::string& x);
|
||||
void SetStatus(const std::string& x);
|
||||
void SetStatus(const std::string& num, const std::string& text);
|
||||
void SetStatusText(const std::string& x);
|
||||
void AddResponseHeader(const std::string& x,const std::string& y);
|
||||
void AddResponseHeader(const std::string& x,const char *format, ...);
|
||||
void SendResponse();
|
||||
void SendResponse(const std::string& status_num, const std::string& status_text);
|
||||
void SendRequest();
|
||||
|
||||
/** Implement this to return your own User-agent string. */
|
||||
virtual std::string MyUseragent();
|
||||
|
||||
protected:
|
||||
/** Reset state of socket to sucessfully implement keep-alive. */
|
||||
virtual void Reset();
|
||||
|
||||
//stubs for crap which used to be in our parent class (TcpSocket)
|
||||
bool SendString(const char *str);
|
||||
bool SendBuf(const char *dat, unsigned int len);
|
||||
|
||||
virtual bool ProcessReceivedData(char* errbuf = 0);
|
||||
|
||||
private:
|
||||
// HTTPSocket& operator=(const HTTPSocket& ) { return *this; }
|
||||
bool m_first;
|
||||
bool m_header;
|
||||
std::string m_line;
|
||||
std::string m_method;
|
||||
std::string m_url;
|
||||
std::string m_uri;
|
||||
std::string m_query_string;
|
||||
std::string m_http_version;
|
||||
std::string m_status;
|
||||
std::string m_status_text;
|
||||
bool m_request;
|
||||
bool m_response;
|
||||
string_m m_response_header;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _HTTPSOCKET_H
|
||||
@@ -0,0 +1,250 @@
|
||||
/** \file HttpdCookies.cpp
|
||||
*/
|
||||
/*
|
||||
Copyright (C) 2003-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#include "../global_define.h"
|
||||
#ifdef _WIN32
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
#include "Parse.h"
|
||||
#include "Utility.h"
|
||||
#include "HTTPSocket.h"
|
||||
#include "HttpdCookies.h"
|
||||
#include "../types.h"
|
||||
#include <time.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
HttpdCookies::HttpdCookies()
|
||||
{
|
||||
}
|
||||
|
||||
HttpdCookies::HttpdCookies(const std::string& s)
|
||||
{
|
||||
Parse *pa = new Parse(s,";");
|
||||
|
||||
std::string slask = pa -> getword();
|
||||
while (slask.size())
|
||||
{
|
||||
Parse *pa2 = new Parse(slask,"=");
|
||||
std::string name = pa2 -> getword();
|
||||
std::string value = pa2 -> getword();
|
||||
delete pa2;
|
||||
COOKIE *c = new COOKIE(name,value);
|
||||
m_cookies.push_back(c);
|
||||
//
|
||||
slask = pa -> getword();
|
||||
}
|
||||
delete pa;
|
||||
}
|
||||
|
||||
HttpdCookies::~HttpdCookies()
|
||||
{
|
||||
for (cookie_v::iterator it = m_cookies.begin(); it != m_cookies.end(); it++)
|
||||
{
|
||||
COOKIE *c = *it;
|
||||
delete c;
|
||||
}
|
||||
}
|
||||
|
||||
bool HttpdCookies::getvalue(const std::string& name,std::string& buffer) //char *buffer,size_t length)
|
||||
{
|
||||
for (cookie_v::iterator it = m_cookies.begin(); it != m_cookies.end(); it++)
|
||||
{
|
||||
COOKIE *c = *it;
|
||||
if (!strcasecmp(c -> name.c_str(),name.c_str()))
|
||||
{
|
||||
buffer = c -> value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
buffer = "";
|
||||
return false;
|
||||
}
|
||||
|
||||
void HttpdCookies::replacevalue(const std::string& name,const std::string& value)
|
||||
{
|
||||
COOKIE *c = nullptr;
|
||||
|
||||
for (cookie_v::iterator it = m_cookies.begin(); it != m_cookies.end(); it++)
|
||||
{
|
||||
c = *it;
|
||||
if (!strcasecmp(c -> name.c_str(),name.c_str()))
|
||||
break;
|
||||
c = nullptr;
|
||||
}
|
||||
|
||||
if (c)
|
||||
{
|
||||
c -> value = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
c = new COOKIE(name,value);
|
||||
m_cookies.push_back(c);
|
||||
}
|
||||
}
|
||||
|
||||
void HttpdCookies::replacevalue(const std::string& name,long l)
|
||||
{
|
||||
replacevalue(name, Utility::l2string(l));
|
||||
}
|
||||
|
||||
void HttpdCookies::replacevalue(const std::string& name,int i)
|
||||
{
|
||||
replacevalue(name, Utility::l2string(i));
|
||||
}
|
||||
|
||||
size_t HttpdCookies::getlength(const std::string& name)
|
||||
{
|
||||
COOKIE *c = nullptr;
|
||||
|
||||
for (cookie_v::iterator it = m_cookies.begin(); it != m_cookies.end(); it++)
|
||||
{
|
||||
c = *it;
|
||||
if (!strcasecmp(c -> name.c_str(),name.c_str()))
|
||||
break;
|
||||
c = nullptr;
|
||||
}
|
||||
return c ? c -> value.size() : 0;
|
||||
}
|
||||
|
||||
void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, const std::string& value)
|
||||
{
|
||||
char *str = new char[name.size() + value.size() + domain.size() + path.size() + 100];
|
||||
|
||||
// set-cookie response
|
||||
if (domain.size())
|
||||
{
|
||||
sprintf(str, "%s=%s; domain=%s; path=%s; expires=%s",
|
||||
name.c_str(), value.c_str(),
|
||||
domain.c_str(),
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf(str, "%s=%s; path=%s; expires=%s",
|
||||
name.c_str(), value.c_str(),
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
sock -> AddResponseHeader("Set-cookie", str);
|
||||
delete[] str;
|
||||
|
||||
replacevalue(name, value);
|
||||
}
|
||||
|
||||
void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, long value)
|
||||
{
|
||||
char *str = new char[name.size() + domain.size() + path.size() + 100];
|
||||
char dt[80];
|
||||
|
||||
// set-cookie response
|
||||
if (domain.size())
|
||||
{
|
||||
sprintf(str, "%s=%ld; domain=%s; path=%s; expires=%s",
|
||||
name.c_str(), value,
|
||||
domain.c_str(),
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf(str, "%s=%ld; path=%s; expires=%s",
|
||||
name.c_str(), value,
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
sock -> AddResponseHeader("Set-cookie", str);
|
||||
delete[] str;
|
||||
|
||||
sprintf(dt, "%ld", value);
|
||||
replacevalue(name, dt);
|
||||
}
|
||||
|
||||
void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, int value)
|
||||
{
|
||||
char *str = new char[name.size() + domain.size() + path.size() + 100];
|
||||
char dt[80];
|
||||
|
||||
// set-cookie response
|
||||
if (domain.size())
|
||||
{
|
||||
sprintf(str, "%s=%d; domain=%s; path=%s; expires=%s",
|
||||
name.c_str(), value,
|
||||
domain.c_str(),
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf(str, "%s=%d; path=%s; expires=%s",
|
||||
name.c_str(), value,
|
||||
path.c_str(),
|
||||
expiredatetime().c_str());
|
||||
}
|
||||
sock -> AddResponseHeader("Set-cookie", str);
|
||||
delete[] str;
|
||||
|
||||
sprintf(dt, "%d", value);
|
||||
replacevalue(name, dt);
|
||||
}
|
||||
|
||||
|
||||
const std::string& HttpdCookies::expiredatetime()
|
||||
{
|
||||
time_t t = time(nullptr);
|
||||
struct tm * tp = gmtime(&t);
|
||||
const char *days[7] = {"Sunday", "Monday",
|
||||
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
|
||||
const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May",
|
||||
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
|
||||
char dt[100];
|
||||
|
||||
sprintf(dt, "%s, %02d-%s-%04d %02d:%02d:%02d GMT",
|
||||
days[tp -> tm_wday],
|
||||
tp -> tm_mday,
|
||||
months[tp -> tm_mon],
|
||||
tp -> tm_year + 1910,
|
||||
tp -> tm_hour,
|
||||
tp -> tm_min,
|
||||
tp -> tm_sec);
|
||||
m_date = dt;
|
||||
return m_date;
|
||||
}
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/** \file HttpdCookies.h
|
||||
*/
|
||||
/*
|
||||
Copyright (C) 2003-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#ifndef _COOKIES_H
|
||||
#define _COOKIES_H
|
||||
|
||||
#include <list>
|
||||
#include <string>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
//! Store the cookies name/value pairs.
|
||||
|
||||
|
||||
|
||||
//! Retrieve and manage cookies during a cgi call.
|
||||
class HTTPSocket;
|
||||
|
||||
/** HTTP Cookie parse/container class.
|
||||
\sa HttpdSocket
|
||||
\sa HttpdForm
|
||||
\ingroup webserver */
|
||||
class HttpdCookies
|
||||
{
|
||||
/** Name/value pair store struct.
|
||||
\ingroup webserver */
|
||||
struct COOKIE
|
||||
{
|
||||
COOKIE(const std::string& n,const std::string& v) : name(n),value(v) {}
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
/** list of key/value structs. */
|
||||
typedef std::list<COOKIE *> cookie_v;
|
||||
public:
|
||||
HttpdCookies();
|
||||
HttpdCookies(const std::string& query_string);
|
||||
~HttpdCookies();
|
||||
|
||||
// int getvalue(const std::string& ,char *,size_t); // (name, buffer, length)
|
||||
bool getvalue(const std::string&,std::string&);
|
||||
void replacevalue(const std::string& ,const std::string& );
|
||||
void replacevalue(const std::string& ,long);
|
||||
void replacevalue(const std::string& ,int);
|
||||
size_t getlength(const std::string& );
|
||||
void setcookie(HTTPSocket *,const std::string& d,const std::string& p,const std::string& c,const std::string& v);
|
||||
void setcookie(HTTPSocket *,const std::string& d,const std::string& p,const std::string& c,long v);
|
||||
void setcookie(HTTPSocket *,const std::string& d,const std::string& p,const std::string& c,int v);
|
||||
const std::string& expiredatetime();
|
||||
|
||||
cookie_v& GetHttpdCookies() { return m_cookies; }
|
||||
|
||||
private:
|
||||
cookie_v m_cookies;
|
||||
std::string m_date;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _COOKIES_H
|
||||
@@ -0,0 +1,621 @@
|
||||
/** \file HttpdForm.cpp - read stdin, parse cgi input
|
||||
**
|
||||
** Written: 1999-Feb-10 grymse@alhem.net
|
||||
**/
|
||||
|
||||
/*
|
||||
Copyright (C) 1999-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#ifdef _WIN32
|
||||
#pragma warning(disable:4786)
|
||||
#include <windows.h>
|
||||
#endif
|
||||
#include "socket_include.h"
|
||||
#include "Parse.h"
|
||||
#include "IFile.h"
|
||||
#include "HttpdForm.h"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
HttpdForm::HttpdForm(IFile *infil) : raw(false)
|
||||
{
|
||||
CGI *cgi = nullptr;
|
||||
char *c_t = getenv("CONTENT_TYPE");
|
||||
char *c_l = getenv("CONTENT_LENGTH");
|
||||
size_t extra = 2;
|
||||
char name[200];
|
||||
|
||||
m_current = m_cgi.end();
|
||||
*name = 0;
|
||||
|
||||
if (c_t && !strncmp(c_t, "multipart/form-data",19))
|
||||
{
|
||||
Parse pa(c_t,";=");
|
||||
char *tempcmp = nullptr;
|
||||
size_t tc = 0;
|
||||
size_t l = 0;
|
||||
std::string str = pa.getword();
|
||||
m_strBoundary = "";
|
||||
while (str.size())
|
||||
{
|
||||
if (!strcmp(str.c_str(),"boundary"))
|
||||
{
|
||||
m_strBoundary = pa.getword();
|
||||
l = m_strBoundary.size();
|
||||
tempcmp = new char[l + extra];
|
||||
}
|
||||
//
|
||||
str = pa.getword();
|
||||
}
|
||||
if (m_strBoundary.size())
|
||||
{
|
||||
std::string content_type;
|
||||
std::string current_name;
|
||||
std::string current_filename;
|
||||
char slask[2000];
|
||||
infil -> fgets(slask, 200);
|
||||
while (!infil -> eof())
|
||||
{
|
||||
while (strlen(slask) && (slask[strlen(slask) - 1] == 13 || slask[strlen(slask) - 1] == 10))
|
||||
{
|
||||
slask[strlen(slask) - 1] = 0;
|
||||
}
|
||||
content_type = "";
|
||||
current_name = "";
|
||||
current_filename = "";
|
||||
if ((strstr(slask,m_strBoundary.c_str()) || strstr(m_strBoundary.c_str(),slask)) && strcmp(slask, m_strBoundary.c_str()))
|
||||
{
|
||||
m_strBoundary = slask;
|
||||
l = m_strBoundary.size();
|
||||
delete[] tempcmp;
|
||||
tempcmp = new char[l + extra];
|
||||
}
|
||||
if (!strcmp(slask, m_strBoundary.c_str()))
|
||||
{
|
||||
// Get headers until empty line
|
||||
infil -> fgets(slask, 200);
|
||||
while (strlen(slask) && (slask[strlen(slask) - 1] == 13 || slask[strlen(slask) - 1] == 10))
|
||||
{
|
||||
slask[strlen(slask) - 1] = 0;
|
||||
}
|
||||
while (!infil -> eof() && *slask)
|
||||
{
|
||||
Parse pa(slask,";");
|
||||
std::string h = pa.getword();
|
||||
if (!strcasecmp(h.c_str(),"Content-type:"))
|
||||
{
|
||||
content_type = pa.getword();
|
||||
}
|
||||
else
|
||||
if (!strcasecmp(h.c_str(),"Content-Disposition:"))
|
||||
{
|
||||
h = pa.getword();
|
||||
if (!strcmp(h.c_str(),"form-data"))
|
||||
{
|
||||
pa.EnableQuote(true);
|
||||
h = pa.getword();
|
||||
while (h.size())
|
||||
{
|
||||
Parse pa2(slask,"=");
|
||||
std::string name = pa2.getword();
|
||||
std::string h = pa2.getrest();
|
||||
if (!strcmp(name.c_str(),"name"))
|
||||
{
|
||||
if (h.size() && h[0] == '"')
|
||||
{
|
||||
current_name = h.substr(1, h.size() - 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
current_name = h;
|
||||
}
|
||||
}
|
||||
else
|
||||
if (!strcmp(name.c_str(),"filename"))
|
||||
{
|
||||
if (h.size() && h[0] == '"')
|
||||
{
|
||||
current_filename = h.substr(1, h.size() - 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
current_filename = h;
|
||||
}
|
||||
size_t x = 0;
|
||||
for (size_t i = 0; i < current_filename.size(); i++)
|
||||
{
|
||||
if (current_filename[i] == '/' || current_filename[i] == '\\')
|
||||
x = i + 1;
|
||||
}
|
||||
if (x)
|
||||
{
|
||||
current_filename = current_filename.substr(x);
|
||||
}
|
||||
}
|
||||
h = pa.getword();
|
||||
}
|
||||
}
|
||||
}
|
||||
// get next header value
|
||||
infil -> fgets(slask, 200);
|
||||
while (strlen(slask) && (slask[strlen(slask) - 1] == 13 || slask[strlen(slask) - 1] == 10))
|
||||
{
|
||||
slask[strlen(slask) - 1] = 0;
|
||||
}
|
||||
}
|
||||
// Read content, save...?
|
||||
if (!current_filename.size()) // not a file
|
||||
{
|
||||
std::string val;
|
||||
infil -> fgets(slask,1000);
|
||||
while (!infil -> eof() && strncmp(slask,m_strBoundary.c_str(),m_strBoundary.size() ))
|
||||
{
|
||||
val += slask;
|
||||
infil -> fgets(slask,1000);
|
||||
}
|
||||
// remove trailing cr/linefeed
|
||||
while (val.size() && (val[val.size() - 1] == 13 || val[val.size() - 1] == 10))
|
||||
{
|
||||
val = val.substr(0,val.size() - 1);
|
||||
}
|
||||
cgi = new CGI(current_name, val);
|
||||
m_cgi.push_back(cgi);
|
||||
}
|
||||
else // current_filename.size() > 0
|
||||
{
|
||||
// read until m_strBoundary...
|
||||
FILE *fil;
|
||||
int out = 0;
|
||||
char c;
|
||||
char fn[1000]; // where post'd file will be saved
|
||||
#ifdef _WIN32
|
||||
{
|
||||
char tmp_path[1000];
|
||||
::GetTempPath(1000, tmp_path);
|
||||
if (tmp_path[strlen(tmp_path) - 1] != '\\')
|
||||
{
|
||||
strcat(tmp_path, "\\");
|
||||
}
|
||||
sprintf(fn,"%s%s",tmp_path,current_filename.c_str());
|
||||
}
|
||||
#else
|
||||
sprintf(fn,"/tmp/%s",current_filename.c_str());
|
||||
#endif
|
||||
if ((fil = fopen(fn, "wb")) != nullptr)
|
||||
{
|
||||
infil -> fread(&c,1,1);
|
||||
while (!infil -> eof())
|
||||
{
|
||||
if (out)
|
||||
{
|
||||
fwrite(&tempcmp[tc],1,1,fil);
|
||||
}
|
||||
tempcmp[tc] = c;
|
||||
tc++;
|
||||
if (tc >= l + extra)
|
||||
{
|
||||
tc = 0;
|
||||
out = 1;
|
||||
}
|
||||
if (tc)
|
||||
{
|
||||
if (!strncmp(tempcmp + tc + extra, m_strBoundary.c_str(), l - tc) &&
|
||||
!strncmp(tempcmp, m_strBoundary.c_str() + l - tc, tc))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!strncmp(tempcmp + extra, m_strBoundary.c_str(), l))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
infil -> fread(&c,1,1);
|
||||
}
|
||||
fclose(fil);
|
||||
|
||||
cgi = new CGI(current_name,fn,fn);
|
||||
m_cgi.push_back(cgi);
|
||||
|
||||
strcpy(slask, m_strBoundary.c_str());
|
||||
infil -> fgets(slask + strlen(slask), 200); // next line
|
||||
}
|
||||
else
|
||||
{
|
||||
// couldn't open file
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Probably '<m_strBoundary>--'
|
||||
break;
|
||||
}
|
||||
} // while (!infil -> eof())
|
||||
} // if (m_strBoundary)
|
||||
if (tempcmp)
|
||||
{
|
||||
delete[] tempcmp;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int i = 0;
|
||||
int cl = c_l ? atoi(c_l) : -1;
|
||||
char c,chigh,clow;
|
||||
char *slask = new char[8888];
|
||||
bool got_name = false;
|
||||
m_current = m_cgi.end();
|
||||
|
||||
*name = 0;
|
||||
|
||||
infil -> fread(&c,1,1);
|
||||
cl--;
|
||||
while (cl >= 0)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '=': /* end of name */
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
strcpy(name,slask);
|
||||
got_name = true;
|
||||
break;
|
||||
case '&': /* end of value */
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
if(got_name) {
|
||||
got_name = false;
|
||||
cgi = new CGI(name,slask);
|
||||
m_cgi.push_back(cgi);
|
||||
} else {
|
||||
cgi = new CGI(slask,"");
|
||||
m_cgi.push_back(cgi);
|
||||
}
|
||||
break;
|
||||
case '+': /* space */
|
||||
slask[i++] = ' ';
|
||||
break;
|
||||
case '%': /* hex value */
|
||||
infil -> fread(&chigh,1,1);
|
||||
cl--;
|
||||
chigh -= 48;
|
||||
chigh &= 0xff - 32;
|
||||
if (chigh > 9)
|
||||
chigh -= 7;
|
||||
infil -> fread(&clow,1,1);
|
||||
cl--;
|
||||
clow -= 48;
|
||||
clow &= 0xff - 32;
|
||||
if (clow > 9)
|
||||
clow -= 7;
|
||||
slask[i++] = (char)(chigh * 16 + clow);
|
||||
break;
|
||||
default: /* just another char */
|
||||
slask[i++] = c;
|
||||
break;
|
||||
}
|
||||
if(infil -> eof())
|
||||
break;
|
||||
//
|
||||
if (cl > 0)
|
||||
{
|
||||
infil -> fread(&c,1,1);
|
||||
}
|
||||
cl--;
|
||||
}
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
if(got_name) {
|
||||
cgi = new CGI(name,slask);
|
||||
m_cgi.push_back(cgi);
|
||||
} else {
|
||||
cgi = new CGI(slask,"");
|
||||
m_cgi.push_back(cgi);
|
||||
}
|
||||
delete[] slask;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// HttpdForm(buffer,l) -- request_method GET
|
||||
|
||||
HttpdForm::HttpdForm(const std::string& buffer,size_t l) : raw(false)
|
||||
{
|
||||
CGI *cgi = nullptr;
|
||||
char slask[8888];
|
||||
char name[200];
|
||||
int i = 0;
|
||||
char c,chigh,clow;
|
||||
bool got_name = false;
|
||||
size_t ptr = 0;
|
||||
|
||||
m_current = m_cgi.end();
|
||||
|
||||
*name = 0;
|
||||
|
||||
ptr = 0;
|
||||
while (ptr < l)
|
||||
{
|
||||
c = buffer[ptr++];
|
||||
switch (c)
|
||||
{
|
||||
case '=': /* end of name */
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
got_name = true;
|
||||
strcpy(name,slask);
|
||||
break;
|
||||
case '&': /* end of value */
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
if(got_name) {
|
||||
got_name = false;
|
||||
cgi = new CGI(name,slask);
|
||||
m_cgi.push_back(cgi);
|
||||
} else {
|
||||
cgi = new CGI(slask, "");
|
||||
m_cgi.push_back(cgi);
|
||||
}
|
||||
break;
|
||||
case '+': /* space */
|
||||
slask[i++] = ' ';
|
||||
break;
|
||||
case '%': /* hex value */
|
||||
chigh = buffer[ptr++];
|
||||
chigh -= 48;
|
||||
chigh &= 0xff - 32;
|
||||
if (chigh > 9)
|
||||
chigh -= 7;
|
||||
clow = buffer[ptr++];
|
||||
clow -= 48;
|
||||
clow &= 0xff - 32;
|
||||
if (clow > 9)
|
||||
clow -= 7;
|
||||
slask[i++] = (char)(chigh * 16 + clow);
|
||||
break;
|
||||
default: /* just another char */
|
||||
slask[i++] = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
slask[i] = 0;
|
||||
i = 0;
|
||||
if(got_name) {
|
||||
cgi = new CGI(name,slask);
|
||||
m_cgi.push_back(cgi);
|
||||
} else {
|
||||
cgi = new CGI(slask, "");
|
||||
m_cgi.push_back(cgi);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
HttpdForm::~HttpdForm()
|
||||
{
|
||||
CGI *cgi = nullptr; //,*tmp;
|
||||
|
||||
for (cgi_v::iterator it = m_cgi.begin(); it != m_cgi.end(); it++)
|
||||
{
|
||||
cgi = *it;
|
||||
delete cgi;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void HttpdForm::EnableRaw(bool b)
|
||||
{
|
||||
raw = b;
|
||||
}
|
||||
|
||||
|
||||
void HttpdForm::strcpyval(std::string& v,const char *value) //,size_t len)
|
||||
{
|
||||
v = "";
|
||||
for (size_t i = 0; i < strlen(value); i++)
|
||||
{
|
||||
if (value[i] == '<')
|
||||
{
|
||||
v += "<";
|
||||
}
|
||||
else
|
||||
if (value[i] == '>')
|
||||
{
|
||||
v += ">";
|
||||
}
|
||||
else
|
||||
if (value[i] == '&')
|
||||
{
|
||||
v += "&";
|
||||
}
|
||||
else
|
||||
{
|
||||
v += value[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool HttpdForm::getfirst(std::string& n) //char *n,size_t len)
|
||||
{
|
||||
m_current = m_cgi.begin();
|
||||
return getnext(n);
|
||||
}
|
||||
|
||||
|
||||
bool HttpdForm::getnext(std::string& n) //char *n,size_t len)
|
||||
{
|
||||
if (m_current != m_cgi.end() )
|
||||
{
|
||||
CGI *current = *m_current;
|
||||
n = current -> name;
|
||||
m_current++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
n = "";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
bool HttpdForm::getfirst(std::string& n,std::string& v) //char *n,size_t len,char *v,size_t vlen)
|
||||
{
|
||||
m_current = m_cgi.begin();
|
||||
return getnext(n,v);
|
||||
}
|
||||
|
||||
|
||||
bool HttpdForm::getnext(std::string& n,std::string& v) //char *n,size_t len,char *v,size_t vlen)
|
||||
{
|
||||
if (m_current != m_cgi.end() )
|
||||
{
|
||||
CGI *current = *m_current;
|
||||
n = current -> name;
|
||||
if (raw)
|
||||
{
|
||||
v = current -> value;
|
||||
}
|
||||
else
|
||||
{
|
||||
strcpyval(v,current -> value.c_str());
|
||||
}
|
||||
m_current++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
n = "";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
int HttpdForm::getvalue(const std::string& n,std::string& v) //char *v,size_t len)
|
||||
{
|
||||
CGI *cgi = nullptr;
|
||||
int r = 0;
|
||||
|
||||
for (cgi_v::iterator it = m_cgi.begin(); it != m_cgi.end(); it++)
|
||||
{
|
||||
cgi = *it;
|
||||
if (cgi -> name == n)
|
||||
break;
|
||||
cgi = nullptr;
|
||||
}
|
||||
if (cgi)
|
||||
{
|
||||
if (raw)
|
||||
{
|
||||
v = cgi -> value;
|
||||
}
|
||||
else
|
||||
{
|
||||
strcpyval(v,cgi -> value.c_str());
|
||||
}
|
||||
r++;
|
||||
}
|
||||
else
|
||||
{
|
||||
v = "";
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
std::string HttpdForm::getvalue(const std::string& n)
|
||||
{
|
||||
for (cgi_v::iterator it = m_cgi.begin(); it != m_cgi.end(); it++)
|
||||
{
|
||||
CGI *cgi = *it;
|
||||
if (cgi -> name == n)
|
||||
{
|
||||
return cgi -> value;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
size_t HttpdForm::getlength(const std::string& n)
|
||||
{
|
||||
CGI *cgi = nullptr;
|
||||
size_t l;
|
||||
|
||||
for (cgi_v::iterator it = m_cgi.begin(); it != m_cgi.end(); it++)
|
||||
{
|
||||
cgi = *it;
|
||||
if (cgi -> name == n)
|
||||
break;
|
||||
cgi = nullptr;
|
||||
}
|
||||
l = cgi ? cgi -> value.size() : 0;
|
||||
if (cgi && !raw)
|
||||
{
|
||||
for (size_t i = 0; i < cgi -> value.size(); i++)
|
||||
{
|
||||
switch (cgi -> value[i])
|
||||
{
|
||||
case '<': // <
|
||||
case '>': // >
|
||||
l += 4;
|
||||
break;
|
||||
case '&': // &
|
||||
l += 5;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
|
||||
HttpdForm::cgi_v& HttpdForm::getbase()
|
||||
{
|
||||
return m_cgi;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HttpdForm::GetBoundary()
|
||||
{
|
||||
return m_strBoundary;
|
||||
}
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/** \file HttpdForm.h - read stdin, parse cgi input
|
||||
**
|
||||
** Written: 1999-Feb-10 grymse@alhem.net
|
||||
**/
|
||||
|
||||
/*
|
||||
Copyright (C) 1999-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#ifndef _FORM_H
|
||||
#define _FORM_H
|
||||
|
||||
#include <string>
|
||||
#include <list>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
class IFile;
|
||||
|
||||
/** Parse/store a http query_string/form-data body.
|
||||
\ingroup webserver */
|
||||
class HttpdForm
|
||||
{
|
||||
/**
|
||||
* Store the name/value pairs from a GET/POST operation.
|
||||
* "name" does not have to be unique.
|
||||
\ingroup webserver
|
||||
*/
|
||||
struct CGI
|
||||
{
|
||||
CGI(const std::string& n,const std::string& v) : name(n),value(v) {}
|
||||
CGI(const std::string& n,const std::string& v,const std::string& p) : name(n),value(v),path(p) {}
|
||||
std::string name;
|
||||
std::string value;
|
||||
std::string path;
|
||||
};
|
||||
/** list of key/value pairs. */
|
||||
typedef std::list<CGI *> cgi_v;
|
||||
|
||||
public:
|
||||
/**
|
||||
* Default constructor (used in POST operations).
|
||||
* Input is read from stdin. Number of characters to read
|
||||
* can be found in the environment variable CONTENT_LENGTH.
|
||||
*/
|
||||
HttpdForm(IFile *);
|
||||
/**
|
||||
* Another constructor (used in GET operations).
|
||||
* Input is read from the environment variable QUERY_STRING.
|
||||
* @param query_string The httpd server provided QUERY_STRING
|
||||
* @param length Query string length.
|
||||
*/
|
||||
HttpdForm(const std::string& query_string,size_t length);
|
||||
~HttpdForm();
|
||||
|
||||
void EnableRaw(bool);
|
||||
|
||||
void strcpyval(std::string&,const char *); //,size_t);
|
||||
|
||||
/* get names */
|
||||
bool getfirst(std::string& n); //char *,size_t);
|
||||
bool getnext(std::string& n); //char *,size_t);
|
||||
|
||||
/* get names and values */
|
||||
bool getfirst(std::string& n,std::string& v); //char *,size_t,char *,size_t);
|
||||
bool getnext(std::string& n,std::string& v); //char *,size_t,char *,size_t);
|
||||
|
||||
/* get value */
|
||||
int getvalue(const std::string& ,std::string& ); //char *,size_t);
|
||||
std::string getvalue(const std::string& );
|
||||
size_t getlength(const std::string& );
|
||||
cgi_v& getbase();
|
||||
|
||||
const std::string& GetBoundary();
|
||||
|
||||
private:
|
||||
HttpdForm(const HttpdForm& ) {}
|
||||
HttpdForm& operator=(const HttpdForm& ) { return *this; }
|
||||
cgi_v m_cgi;
|
||||
cgi_v::iterator m_current;
|
||||
std::string m_strBoundary;
|
||||
bool raw;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _FORM_H
|
||||
@@ -0,0 +1,352 @@
|
||||
/** \file HttpdSocket.cpp
|
||||
*/
|
||||
/*
|
||||
Copyright (C) 2001-2004,2005 Anders Hedstrom (grymse@alhem.net)
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
#include "../global_define.h"
|
||||
#include "Utility.h"
|
||||
#include "HttpdCookies.h"
|
||||
#include "HttpdForm.h"
|
||||
#include "MemFile.h"
|
||||
#include "HttpdSocket.h"
|
||||
#include "../types.h"
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#define DEB(x)
|
||||
/*
|
||||
#define DEB(x) { \
|
||||
FILE *fil = fopen("httpdlog","at"); \
|
||||
if (!fil) \
|
||||
fil = fopen("httpdlog","wt"); \
|
||||
if (fil) { x; fclose(fil); } \
|
||||
}
|
||||
*/
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
// statics
|
||||
int HttpdSocket::m_request_count = 0;
|
||||
std::string HttpdSocket::m_start = "";
|
||||
|
||||
|
||||
HttpdSocket::HttpdSocket(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort)
|
||||
: HTTPSocket(ID,in_socket,irIP,irPort)
|
||||
,m_content_length(0)
|
||||
,m_file(nullptr)
|
||||
,m_received(0)
|
||||
,m_request_id(++m_request_count)
|
||||
,m_cookies(nullptr)
|
||||
,m_form(nullptr)
|
||||
{
|
||||
m_http_date = datetime2httpdate(GetDate());
|
||||
if (!m_start.size())
|
||||
m_start = m_http_date;
|
||||
}
|
||||
|
||||
|
||||
HttpdSocket::~HttpdSocket()
|
||||
{
|
||||
if (m_file)
|
||||
{
|
||||
delete m_file;
|
||||
}
|
||||
if (m_cookies)
|
||||
delete m_cookies;
|
||||
if (m_form)
|
||||
delete m_form;
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::OnFirst()
|
||||
{
|
||||
// printf("Request: %s %s %s\n",GetMethod().c_str(),GetUrl().c_str(),GetHttpVersion().c_str());
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::OnHeader(const std::string& key,const std::string& value)
|
||||
{
|
||||
if (!strcasecmp(key.c_str(),"content-length"))
|
||||
{
|
||||
m_content_length = atoi(value.c_str());
|
||||
m_content_length_str = value;
|
||||
}
|
||||
else
|
||||
if (!strcasecmp(key.c_str(),"cookie"))
|
||||
{
|
||||
m_http_cookie = value;
|
||||
}
|
||||
else
|
||||
if (!strcasecmp(key.c_str(),"content-type"))
|
||||
{
|
||||
m_content_type = value;
|
||||
}
|
||||
else
|
||||
if (!strcasecmp(key.c_str(),"if-modified-since"))
|
||||
{
|
||||
m_if_modified_since = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::OnHeaderComplete()
|
||||
{
|
||||
m_cookies = new HttpdCookies(m_http_cookie);
|
||||
|
||||
#if (defined(SOLARIS8) || defined(SOLARIS))
|
||||
{
|
||||
char slask[1000];
|
||||
if (GetMethod() == "GET")
|
||||
{
|
||||
sprintf(slask,"QUERY_STRING=%s", GetQueryString().c_str());
|
||||
putenv(slask);
|
||||
}
|
||||
sprintf(slask,"REQUEST_METHOD=%s", GetMethod().c_str());
|
||||
putenv(slask);
|
||||
sprintf(slask,"HTTP_COOKIE=%s", m_http_cookie.c_str());
|
||||
putenv(slask);
|
||||
sprintf(slask,"CONTENT_TYPE=%s", m_content_type.c_str());
|
||||
putenv(slask);
|
||||
sprintf(slask,"CONTENT_LENGTH=%s", m_content_length_str.c_str());
|
||||
putenv(slask);
|
||||
}
|
||||
#elif defined _WIN32
|
||||
{
|
||||
char slask[1000];
|
||||
if (GetMethod() == "GET")
|
||||
{
|
||||
sprintf(slask,"QUERY_STRING=%s", GetQueryString().c_str());
|
||||
_putenv(slask);
|
||||
}
|
||||
sprintf(slask,"REQUEST_METHOD=%s", GetMethod().c_str());
|
||||
_putenv(slask);
|
||||
sprintf(slask,"HTTP_COOKIE=%s", m_http_cookie.c_str());
|
||||
_putenv(slask);
|
||||
sprintf(slask,"CONTENT_TYPE=%s", m_content_type.c_str());
|
||||
_putenv(slask);
|
||||
sprintf(slask,"CONTENT_LENGTH=%s", m_content_length_str.c_str());
|
||||
_putenv(slask);
|
||||
}
|
||||
#else
|
||||
if (GetMethod() == "GET")
|
||||
{
|
||||
setenv("QUERY_STRING", GetQueryString().c_str(), 1);
|
||||
}
|
||||
setenv("REQUEST_METHOD", GetMethod().c_str(), 1);
|
||||
setenv("HTTP_COOKIE", m_http_cookie.c_str(), 1);
|
||||
setenv("CONTENT_TYPE", m_content_type.c_str(), 1);
|
||||
setenv("CONTENT_LENGTH", m_content_length_str.c_str(), 1);
|
||||
#endif
|
||||
|
||||
if (GetMethod() == "POST")
|
||||
{
|
||||
m_file = new MemFile;
|
||||
}
|
||||
else
|
||||
if (GetMethod() == "GET")
|
||||
{
|
||||
m_form = new HttpdForm(GetQueryString(), GetQueryString().size() );
|
||||
AddResponseHeader("Date", datetime2httpdate(GetDate()) );
|
||||
Exec();
|
||||
Reset(); // prepare for next request
|
||||
}
|
||||
else
|
||||
{
|
||||
AddResponseHeader("Date", GetHttpDate());
|
||||
AddResponseHeader("Connection", "close");
|
||||
SetStatus("405");
|
||||
SetStatusText("Method not allowed");
|
||||
SendResponse();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::OnData(const char *p,size_t l)
|
||||
{
|
||||
if (m_file)
|
||||
{
|
||||
m_file -> fwrite(p,1,l);
|
||||
}
|
||||
m_received += l;
|
||||
if (m_received >= m_content_length && m_content_length)
|
||||
{
|
||||
// all done
|
||||
if (m_file && !m_form)
|
||||
{
|
||||
m_form = new HttpdForm(m_file);
|
||||
AddResponseHeader("Date", datetime2httpdate(GetDate()) );
|
||||
Exec();
|
||||
Reset(); // prepare for next request
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::Send64(const std::string& str64, const std::string& type)
|
||||
{
|
||||
if (!strcasecmp(m_start.c_str(), m_if_modified_since.c_str()))
|
||||
{
|
||||
SetStatus("304");
|
||||
SetStatusText("Not Modified");
|
||||
SendResponse();
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t len = Base64::decode_length(str64);
|
||||
unsigned char *buf = new unsigned char[len];
|
||||
|
||||
SetStatus("200");
|
||||
SetStatusText("OK");
|
||||
|
||||
AddResponseHeader("Content-length", Utility::l2string( (long)len) );
|
||||
AddResponseHeader("Content-type", type );
|
||||
AddResponseHeader("Last-modified", m_start);
|
||||
SendResponse();
|
||||
|
||||
Base64::decode(str64, buf, len);
|
||||
SendBuf( (char *)buf, len);
|
||||
delete[] buf;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::string HttpdSocket::datetime2httpdate(const std::string& dt)
|
||||
{
|
||||
struct tm tp;
|
||||
time_t t;
|
||||
const char *days[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
|
||||
const char *months[] = { "Jan","Feb","Mar","Apr","May","Jun",
|
||||
"Jul","Aug","Sep","Oct","Nov","Dec" };
|
||||
int i;
|
||||
char s[40];
|
||||
|
||||
/* 1997-12-16 09:50:40 */
|
||||
|
||||
if (dt.size() == 19)
|
||||
{
|
||||
tp.tm_year = atoi(dt.substr(0,4).c_str()) - 1900;
|
||||
i = atoi(dt.substr(5,2).c_str()) - 1;
|
||||
tp.tm_mon = i >= 0 ? i : 0;
|
||||
tp.tm_mday = atoi(dt.substr(8,2).c_str());
|
||||
tp.tm_hour = atoi(dt.substr(11,2).c_str());
|
||||
tp.tm_min = atoi(dt.substr(14,2).c_str());
|
||||
tp.tm_sec = atoi(dt.substr(17,2).c_str());
|
||||
tp.tm_wday = 0;
|
||||
tp.tm_yday = 0;
|
||||
tp.tm_isdst = 0;
|
||||
t = mktime(&tp);
|
||||
/*if (t == -1)
|
||||
{
|
||||
Handler().LogError(this, "datetime2httpdate", 0, "mktime() failed");
|
||||
}*/
|
||||
|
||||
sprintf(s,"%s, %02d %s %d %02d:%02d:%02d GMT",
|
||||
days[tp.tm_wday],
|
||||
tp.tm_mday,
|
||||
months[tp.tm_mon],
|
||||
tp.tm_year + 1900,
|
||||
tp.tm_hour,tp.tm_min,tp.tm_sec);
|
||||
}
|
||||
else
|
||||
{
|
||||
*s = 0;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
std::string HttpdSocket::GetDate()
|
||||
{
|
||||
time_t t = time(nullptr);
|
||||
struct tm* tp = localtime(&t);
|
||||
char slask[40];
|
||||
if (tp)
|
||||
{
|
||||
sprintf(slask,"%d-%02d-%02d %02d:%02d:%02d",
|
||||
tp -> tm_year + 1900,
|
||||
tp -> tm_mon + 1,
|
||||
tp -> tm_mday,
|
||||
tp -> tm_hour,tp -> tm_min,tp -> tm_sec);
|
||||
}
|
||||
else
|
||||
{
|
||||
*slask = 0;
|
||||
}
|
||||
return slask;
|
||||
}
|
||||
|
||||
|
||||
void HttpdSocket::Reset()
|
||||
{
|
||||
HTTPSocket::Reset();
|
||||
m_content_length = 0;
|
||||
if (m_file)
|
||||
{
|
||||
delete m_file;
|
||||
m_file = nullptr;
|
||||
}
|
||||
m_received = 0;
|
||||
m_request_id = ++m_request_count;
|
||||
if (m_cookies)
|
||||
delete m_cookies;
|
||||
m_cookies = nullptr;
|
||||
if (m_form)
|
||||
delete m_form;
|
||||
m_form = nullptr;
|
||||
}
|
||||
|
||||
|
||||
const std::string& HttpdSocket::GetHttpDate()
|
||||
{
|
||||
return m_http_date;
|
||||
}
|
||||
|
||||
|
||||
HttpdCookies *HttpdSocket::GetCookies()
|
||||
{
|
||||
return m_cookies;
|
||||
}
|
||||
|
||||
|
||||
HttpdForm *HttpdSocket::GetHttpForm()
|
||||
{
|
||||
return m_form;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/** \file HttpdSocket.h
|
||||
*/
|
||||
/*
|
||||
Copyright (C) 2001-2004,2005 Anders Hedstrom (grymse@alhem.net)
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _HTTPDSOCKET_H
|
||||
#define _HTTPDSOCKET_H
|
||||
|
||||
#include "HTTPSocket.h"
|
||||
|
||||
class TCPConnection;
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
class HttpdCookies;
|
||||
class HttpdForm;
|
||||
class IFile;
|
||||
|
||||
/** \defgroup webserver Webserver framework */
|
||||
/** Web server socket framework.
|
||||
\ingroup webserver */
|
||||
class HttpdSocket : public HTTPSocket
|
||||
{
|
||||
public:
|
||||
HttpdSocket(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort);
|
||||
~HttpdSocket();
|
||||
|
||||
void OnFirst();
|
||||
void OnHeader(const std::string& key,const std::string& value);
|
||||
void OnHeaderComplete();
|
||||
void OnData(const char *,size_t);
|
||||
|
||||
/** This method needs to be implemented with logic to produce
|
||||
a response to an incoming request. */
|
||||
virtual void Exec() = 0;
|
||||
/** Get current date in http rfc format. */
|
||||
const std::string& GetHttpDate();
|
||||
/** Get pointer to cookie class. */
|
||||
HttpdCookies *GetCookies();
|
||||
/** Get pointer to query string/form data class. */
|
||||
HttpdForm *GetHttpForm();
|
||||
|
||||
protected:
|
||||
/** Decode and send a base64-encoded string.
|
||||
\param str64 Base64-encoded string
|
||||
\param type Mime type of content (content-type header) */
|
||||
void Send64(const std::string& str64, const std::string& type);
|
||||
std::string datetime2httpdate(const std::string& dt);
|
||||
std::string GetDate();
|
||||
void Reset();
|
||||
// headers
|
||||
std::string m_http_cookie;
|
||||
std::string m_content_type;
|
||||
std::string m_content_length_str;
|
||||
std::string m_if_modified_since;
|
||||
|
||||
private:
|
||||
static int m_request_count;
|
||||
static std::string m_start;
|
||||
size_t m_content_length;
|
||||
IFile *m_file;
|
||||
size_t m_received;
|
||||
int m_request_id;
|
||||
std::string m_http_date;
|
||||
HttpdCookies *m_cookies;
|
||||
HttpdForm *m_form;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _HTTPDSOCKET_H
|
||||
@@ -0,0 +1,65 @@
|
||||
/** \file IFile.h
|
||||
** \date 2005-04-25
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _IFILE_H
|
||||
#define _IFILE_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
/** \defgroup file File handling */
|
||||
/** Pure virtual file I/O interface.
|
||||
\ingroup file */
|
||||
class IFile
|
||||
{
|
||||
public:
|
||||
virtual ~IFile() {}
|
||||
|
||||
virtual bool fopen(const std::string&, const std::string&) = 0;
|
||||
virtual void fclose() = 0;
|
||||
|
||||
virtual size_t fread(char *, size_t, size_t) = 0;
|
||||
virtual size_t fwrite(const char *, size_t, size_t) = 0;
|
||||
|
||||
virtual char *fgets(char *, int) = 0;
|
||||
virtual void fprintf(char *format, ...) = 0;
|
||||
|
||||
virtual off_t size() = 0;
|
||||
virtual bool eof() = 0;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _IFILE_H
|
||||
@@ -0,0 +1,212 @@
|
||||
/** \file MemFile.cpp
|
||||
** \date 2005-04-25
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#include "MemFile.h"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define DEB(x) x
|
||||
#else
|
||||
#define DEB(x)
|
||||
#endif
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
std::map<std::string,MemFile::block_t *> MemFile::m_files;
|
||||
|
||||
|
||||
MemFile::MemFile()
|
||||
:m_temporary(true)
|
||||
,m_base(new block_t)
|
||||
,m_current_read(m_base)
|
||||
,m_current_write(m_base)
|
||||
,m_read_ptr(0)
|
||||
,m_write_ptr(0)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
MemFile::MemFile(const std::string& path)
|
||||
:m_path(path)
|
||||
,m_temporary(false)
|
||||
,m_base(m_files[path])
|
||||
,m_current_read(nullptr)
|
||||
,m_current_write(nullptr)
|
||||
,m_read_ptr(0)
|
||||
,m_write_ptr(0)
|
||||
{
|
||||
if (!m_base)
|
||||
{
|
||||
m_base = new block_t;
|
||||
m_files[path] = m_base;
|
||||
}
|
||||
m_current_read = m_base;
|
||||
m_current_write = m_base;
|
||||
}
|
||||
|
||||
|
||||
MemFile::~MemFile()
|
||||
{
|
||||
while (m_base && m_temporary)
|
||||
{
|
||||
block_t *p = m_base;
|
||||
m_base = p -> next;
|
||||
delete p;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool MemFile::fopen(const std::string& path, const std::string& mode)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void MemFile::fclose()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
size_t MemFile::fread(char *ptr, size_t size, size_t nmemb)
|
||||
{
|
||||
size_t p = m_read_ptr % BLOCKSIZE;
|
||||
size_t sz = size * nmemb;
|
||||
if (p + sz < BLOCKSIZE)
|
||||
{
|
||||
memcpy(ptr, m_current_read -> data + p, sz);
|
||||
m_read_ptr += sz;
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t sz1 = BLOCKSIZE - p;
|
||||
size_t sz2 = size - sz1;
|
||||
memcpy(ptr, m_current_read -> data + p, sz1);
|
||||
m_read_ptr += sz1;
|
||||
if (m_current_read -> next)
|
||||
{
|
||||
m_current_read = m_current_read -> next;
|
||||
memcpy(ptr + sz1, m_current_read -> data, sz2);
|
||||
m_read_ptr += sz2;
|
||||
}
|
||||
else
|
||||
{
|
||||
DEB(printf("Read beyond available data\n");)
|
||||
return sz1;
|
||||
}
|
||||
}
|
||||
return sz;
|
||||
}
|
||||
|
||||
|
||||
size_t MemFile::fwrite(const char *ptr, size_t size, size_t nmemb)
|
||||
{
|
||||
size_t p = m_write_ptr % BLOCKSIZE;
|
||||
size_t sz = size * nmemb;
|
||||
if (p + sz < BLOCKSIZE)
|
||||
{
|
||||
memcpy(m_current_write -> data + p, ptr, sz);
|
||||
m_write_ptr += sz;
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t sz1 = BLOCKSIZE - p;
|
||||
size_t sz2 = size - sz1;
|
||||
memcpy(m_current_write -> data + p, ptr, sz1);
|
||||
block_t *next = new block_t;
|
||||
m_current_write -> next = next;
|
||||
m_current_write = next;
|
||||
memcpy(m_current_write -> data, ptr + sz1, sz2);
|
||||
m_write_ptr += sz;
|
||||
}
|
||||
return sz;
|
||||
}
|
||||
|
||||
|
||||
|
||||
char *MemFile::fgets(char *s, int size)
|
||||
{
|
||||
int n = 0;
|
||||
while (n < size - 1 && !eof())
|
||||
{
|
||||
char c;
|
||||
fread(&c, 1, 1);
|
||||
if (c == 10)
|
||||
{
|
||||
s[n] = 0;
|
||||
return s;
|
||||
}
|
||||
s[n++] = c;
|
||||
}
|
||||
s[n] = 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
void MemFile::fprintf(char *format, ...)
|
||||
{
|
||||
va_list ap;
|
||||
char tmp[BLOCKSIZE];
|
||||
va_start(ap, format);
|
||||
#ifdef _WIN32
|
||||
vsprintf(tmp, format, ap);
|
||||
#else
|
||||
vsnprintf(tmp, BLOCKSIZE - 1, format, ap);
|
||||
#endif
|
||||
va_end(ap);
|
||||
fwrite(tmp, 1, strlen(tmp));
|
||||
}
|
||||
|
||||
|
||||
off_t MemFile::size()
|
||||
{
|
||||
return (off_t)m_write_ptr;
|
||||
}
|
||||
|
||||
|
||||
bool MemFile::eof()
|
||||
{
|
||||
return (m_read_ptr < m_write_ptr) ? false : true;
|
||||
}
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/** \file MemFile.h
|
||||
** \date 2005-04-25
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _MEMFILE_H
|
||||
#define _MEMFILE_H
|
||||
|
||||
#include <map>
|
||||
#include "IFile.h"
|
||||
|
||||
#define BLOCKSIZE 32768
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
/** Implements a memory file.
|
||||
\ingroup file */
|
||||
class MemFile : public IFile
|
||||
{
|
||||
public:
|
||||
/** File block structure.
|
||||
\ingroup file */
|
||||
struct block_t {
|
||||
block_t() : next(nullptr) {}
|
||||
struct block_t *next;
|
||||
char data[BLOCKSIZE];
|
||||
};
|
||||
public:
|
||||
MemFile();
|
||||
MemFile(const std::string& path);
|
||||
~MemFile();
|
||||
|
||||
bool fopen(const std::string& path, const std::string& mode);
|
||||
void fclose();
|
||||
|
||||
size_t fread(char *ptr, size_t size, size_t nmemb);
|
||||
size_t fwrite(const char *ptr, size_t size, size_t nmemb);
|
||||
|
||||
char *fgets(char *s, int size);
|
||||
void fprintf(char *format, ...);
|
||||
|
||||
off_t size();
|
||||
bool eof();
|
||||
|
||||
private:
|
||||
MemFile(const MemFile& ) {} // copy constructor
|
||||
MemFile& operator=(const MemFile& ) { return *this; } // assignment operator
|
||||
|
||||
static std::map<std::string,block_t *> m_files;
|
||||
std::string m_path;
|
||||
bool m_temporary;
|
||||
block_t *m_base;
|
||||
block_t *m_current_read;
|
||||
block_t *m_current_write;
|
||||
size_t m_read_ptr;
|
||||
size_t m_write_ptr;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _MEMFILE_H
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
** File ......... Mime.cpp
|
||||
** Published .... 2004-07-13
|
||||
** Author ....... grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004 Anders Hedstrom
|
||||
|
||||
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.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
|
||||
#include "Parse.h"
|
||||
#include "Mime.h"
|
||||
#include <cstring>
|
||||
|
||||
|
||||
|
||||
Mime::Mime() {
|
||||
}
|
||||
|
||||
Mime::Mime(const std::string& filename) {
|
||||
LoadMimeFile(filename);
|
||||
}
|
||||
|
||||
bool Mime::LoadMimeFile(const std::string& filename) {
|
||||
FILE *fil;
|
||||
if ((fil = fopen(filename.c_str(),"rt")) != nullptr) {
|
||||
char * slask = new char[1000];
|
||||
fgets(slask,1000,fil);
|
||||
while (!feof(fil))
|
||||
{
|
||||
while (strlen(slask) && (slask[strlen(slask) - 1] == 13 || slask[strlen(slask) - 1] == 10))
|
||||
{
|
||||
slask[strlen(slask) - 1] = 0;
|
||||
}
|
||||
Parse pa(slask);
|
||||
std::string mime_type = pa.getword();
|
||||
std::string ext = pa.getword();
|
||||
while (ext.size())
|
||||
{
|
||||
m_mime[ext] = mime_type;
|
||||
ext = pa.getword();
|
||||
}
|
||||
//
|
||||
fgets(slask,1000,fil);
|
||||
}
|
||||
delete[] slask;
|
||||
fclose(fil);
|
||||
return(true);
|
||||
}
|
||||
return(false);
|
||||
}
|
||||
|
||||
|
||||
Mime::~Mime()
|
||||
{
|
||||
}
|
||||
|
||||
void Mime::Clear() {
|
||||
m_mime.clear();
|
||||
}
|
||||
|
||||
std::string Mime::GetMimeFromFilename(const std::string &filename) const {
|
||||
std::string::size_type pos = filename.find_last_of('.');
|
||||
if(pos == std::string::npos)
|
||||
return(std::string("text/plain"));
|
||||
return(GetMimeFromExtension(filename.substr(pos+1)));
|
||||
}
|
||||
|
||||
std::string Mime::GetMimeFromExtension(const std::string& ext) const {
|
||||
mime_m::const_iterator res;
|
||||
res = m_mime.find(ext);
|
||||
if(res == m_mime.end())
|
||||
return(std::string("text/plain"));
|
||||
|
||||
return res->second;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
** File ......... Mime.h
|
||||
** Published .... 2004-07-13
|
||||
** Author ....... grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004 Anders Hedstrom
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _MIME_H
|
||||
#define _MIME_H
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
class Mime {
|
||||
typedef std::map<std::string,std::string> mime_m;
|
||||
public:
|
||||
Mime();
|
||||
Mime(const std::string& mime_file);
|
||||
~Mime();
|
||||
|
||||
void Clear();
|
||||
bool LoadMimeFile(const std::string& mime_file);
|
||||
|
||||
std::string GetMimeFromFilename(const std::string &filename) const;
|
||||
std::string GetMimeFromExtension(const std::string &ext) const;
|
||||
|
||||
private:
|
||||
mime_m m_mime;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _MIME_H
|
||||
@@ -0,0 +1,327 @@
|
||||
/** \file Parse.cpp - parse a string
|
||||
**
|
||||
** Written: 1999-Feb-10 grymse@alhem.net
|
||||
**/
|
||||
|
||||
/*
|
||||
Copyright (C) 1999-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "Parse.h"
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define DEB(x)
|
||||
#else
|
||||
#define DEB(x)
|
||||
#endif
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
/* implementation of class Parse */
|
||||
|
||||
Parse::Parse()
|
||||
:pa_the_str("")
|
||||
,pa_splits("")
|
||||
,pa_ord("")
|
||||
,pa_the_ptr(0)
|
||||
,pa_breakchar(0)
|
||||
,pa_enable(0)
|
||||
,pa_disable(0)
|
||||
,pa_nospace(0)
|
||||
,pa_quote(false)
|
||||
{
|
||||
}
|
||||
|
||||
Parse::Parse(const std::string&s)
|
||||
:pa_the_str(s)
|
||||
,pa_splits("")
|
||||
,pa_ord("")
|
||||
,pa_the_ptr(0)
|
||||
,pa_breakchar(0)
|
||||
,pa_enable(0)
|
||||
,pa_disable(0)
|
||||
,pa_nospace(0)
|
||||
,pa_quote(false)
|
||||
{
|
||||
}
|
||||
|
||||
Parse::Parse(const std::string&s,const std::string&sp)
|
||||
:pa_the_str(s)
|
||||
,pa_splits(sp)
|
||||
,pa_ord("")
|
||||
,pa_the_ptr(0)
|
||||
,pa_breakchar(0)
|
||||
,pa_enable(0)
|
||||
,pa_disable(0)
|
||||
,pa_nospace(0)
|
||||
,pa_quote(false)
|
||||
{
|
||||
}
|
||||
|
||||
Parse::Parse(const std::string&s,const std::string&sp,short nospace)
|
||||
:pa_the_str(s)
|
||||
,pa_splits(sp)
|
||||
,pa_ord("")
|
||||
,pa_the_ptr(0)
|
||||
,pa_breakchar(0)
|
||||
,pa_enable(0)
|
||||
,pa_disable(0)
|
||||
,pa_nospace(1)
|
||||
,pa_quote(false)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
Parse::~Parse()
|
||||
{
|
||||
}
|
||||
|
||||
#define C ((pa_the_ptr<pa_the_str.size()) ? pa_the_str[pa_the_ptr] : 0)
|
||||
|
||||
short Parse::issplit(char c)
|
||||
{
|
||||
for (size_t i = 0; i < pa_splits.size(); i++)
|
||||
if (pa_splits[i] == c)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Parse::getsplit(void)
|
||||
{
|
||||
size_t x;
|
||||
|
||||
if (C == '=')
|
||||
{
|
||||
x = pa_the_ptr++;
|
||||
} else
|
||||
{
|
||||
while (C && (issplit(C)))
|
||||
pa_the_ptr++;
|
||||
x = pa_the_ptr;
|
||||
while (C && !issplit(C) && C != '=')
|
||||
pa_the_ptr++;
|
||||
}
|
||||
if (x == pa_the_ptr && C == '=')
|
||||
pa_the_ptr++;
|
||||
pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
|
||||
}
|
||||
|
||||
std::string Parse::getword(void)
|
||||
{
|
||||
size_t x;
|
||||
int disabled = 0;
|
||||
int quote = 0;
|
||||
int rem = 0;
|
||||
|
||||
if (pa_nospace)
|
||||
{
|
||||
while (C && issplit(C))
|
||||
pa_the_ptr++;
|
||||
x = pa_the_ptr;
|
||||
while (C && !issplit(C) && (C != pa_breakchar || !pa_breakchar || disabled))
|
||||
{
|
||||
if (pa_breakchar && C == pa_disable)
|
||||
disabled = 1;
|
||||
if (pa_breakchar && C == pa_enable)
|
||||
disabled = 0;
|
||||
if (pa_quote && C == '"')
|
||||
quote = 1;
|
||||
pa_the_ptr++;
|
||||
while (quote && C && C != '"')
|
||||
{
|
||||
pa_the_ptr++;
|
||||
}
|
||||
if (pa_quote && C == '"')
|
||||
{
|
||||
pa_the_ptr++;
|
||||
}
|
||||
quote = 0;
|
||||
}
|
||||
} else
|
||||
{
|
||||
if (C == pa_breakchar && pa_breakchar)
|
||||
{
|
||||
x = pa_the_ptr++;
|
||||
rem = 1;
|
||||
} else
|
||||
{
|
||||
while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
|
||||
pa_the_ptr++;
|
||||
x = pa_the_ptr;
|
||||
while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) &&
|
||||
(C != pa_breakchar || !pa_breakchar || disabled))
|
||||
{
|
||||
if (pa_breakchar && C == pa_disable)
|
||||
disabled = 1;
|
||||
if (pa_breakchar && C == pa_enable)
|
||||
disabled = 0;
|
||||
if (pa_quote && C == '"')
|
||||
{
|
||||
quote = 1;
|
||||
pa_the_ptr++;
|
||||
while (quote && C && C != '"')
|
||||
{
|
||||
pa_the_ptr++;
|
||||
}
|
||||
if (pa_quote && C == '"')
|
||||
{
|
||||
pa_the_ptr++;
|
||||
}
|
||||
}
|
||||
else
|
||||
pa_the_ptr++;
|
||||
quote = 0;
|
||||
}
|
||||
pa_the_ptr++;
|
||||
rem = 1;
|
||||
}
|
||||
if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
|
||||
pa_the_ptr++;
|
||||
}
|
||||
if (x < pa_the_str.size())
|
||||
{
|
||||
pa_ord = pa_the_str.substr(x,pa_the_ptr - x - rem);
|
||||
}
|
||||
else
|
||||
{
|
||||
pa_ord = "";
|
||||
}
|
||||
return pa_ord;
|
||||
}
|
||||
|
||||
void Parse::getword(std::string&s)
|
||||
{
|
||||
s = Parse::getword();
|
||||
}
|
||||
|
||||
void Parse::getsplit(std::string&s)
|
||||
{
|
||||
Parse::getsplit();
|
||||
s = pa_ord;
|
||||
}
|
||||
|
||||
void Parse::getword(std::string&s,std::string&fill,int l)
|
||||
{
|
||||
Parse::getword();
|
||||
s = "";
|
||||
while (s.size() + pa_ord.size() < (size_t)l)
|
||||
s += fill;
|
||||
s += pa_ord;
|
||||
}
|
||||
|
||||
std::string Parse::getrest()
|
||||
{
|
||||
std::string s;
|
||||
while (C && (C == ' ' || C == 9 || issplit(C)))
|
||||
pa_the_ptr++;
|
||||
s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
|
||||
return s;
|
||||
}
|
||||
|
||||
void Parse::getrest(std::string&s)
|
||||
{
|
||||
while (C && (C == ' ' || C == 9 || issplit(C)))
|
||||
pa_the_ptr++;
|
||||
s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : "";
|
||||
}
|
||||
|
||||
long Parse::getvalue(void)
|
||||
{
|
||||
Parse::getword();
|
||||
return atol(pa_ord.c_str());
|
||||
}
|
||||
|
||||
void Parse::setbreak(char c)
|
||||
{
|
||||
pa_breakchar = c;
|
||||
}
|
||||
|
||||
int Parse::getwordlen(void)
|
||||
{
|
||||
size_t x,y = pa_the_ptr,len;
|
||||
|
||||
if (C == pa_breakchar && pa_breakchar)
|
||||
{
|
||||
x = pa_the_ptr++;
|
||||
} else
|
||||
{
|
||||
while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C)))
|
||||
pa_the_ptr++;
|
||||
x = pa_the_ptr;
|
||||
while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) && (C != pa_breakchar || !pa_breakchar))
|
||||
pa_the_ptr++;
|
||||
}
|
||||
if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar)
|
||||
pa_the_ptr++;
|
||||
len = pa_the_ptr - x;
|
||||
pa_the_ptr = y;
|
||||
return (int)len;
|
||||
}
|
||||
|
||||
int Parse::getrestlen(void)
|
||||
{
|
||||
size_t y = pa_the_ptr;
|
||||
size_t len;
|
||||
|
||||
while (C && (C == ' ' || C == 9 || issplit(C)))
|
||||
pa_the_ptr++;
|
||||
len = strlen(pa_the_str.c_str() + pa_the_ptr);
|
||||
pa_the_ptr = y;
|
||||
return (int)len;
|
||||
}
|
||||
|
||||
void Parse::getline(void)
|
||||
{
|
||||
size_t x;
|
||||
|
||||
x = pa_the_ptr;
|
||||
while (C && C != 13 && C != 10)
|
||||
pa_the_ptr++;
|
||||
pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : "";
|
||||
if (C == 13)
|
||||
pa_the_ptr++;
|
||||
if (C == 10)
|
||||
pa_the_ptr++;
|
||||
}
|
||||
|
||||
void Parse::getline(std::string&s)
|
||||
{
|
||||
getline();
|
||||
s = pa_ord;
|
||||
}
|
||||
|
||||
/* end of implementation of class Parse */
|
||||
/***************************************************/
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/** \file Parse.h - parse a string
|
||||
**
|
||||
** Written: 1999-Feb-10 grymse@alhem.net
|
||||
**/
|
||||
|
||||
/*
|
||||
Copyright (C) 1999-2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
#ifndef _PARSE_H
|
||||
#define _PARSE_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
/***************************************************/
|
||||
/* interface of class Parse */
|
||||
|
||||
/** Splits a string whatever way you want.
|
||||
\ingroup util */
|
||||
class Parse
|
||||
{
|
||||
public:
|
||||
Parse();
|
||||
Parse(const std::string&);
|
||||
Parse(const std::string&,const std::string&);
|
||||
Parse(const std::string&,const std::string&,short);
|
||||
~Parse();
|
||||
short issplit(char);
|
||||
void getsplit(void);
|
||||
void getsplit(std::string&);
|
||||
std::string getword(void);
|
||||
void getword(std::string&);
|
||||
void getword(std::string&,std::string&,int);
|
||||
std::string getrest();
|
||||
void getrest(std::string&);
|
||||
long getvalue(void);
|
||||
void setbreak(char);
|
||||
int getwordlen(void);
|
||||
int getrestlen(void);
|
||||
void enablebreak(char c) {
|
||||
pa_enable = c;
|
||||
}
|
||||
void disablebreak(char c) {
|
||||
pa_disable = c;
|
||||
}
|
||||
void getline(void);
|
||||
void getline(std::string&);
|
||||
size_t getptr(void) { return pa_the_ptr; }
|
||||
void EnableQuote(bool b) { pa_quote = b; }
|
||||
|
||||
private:
|
||||
std::string pa_the_str;
|
||||
std::string pa_splits;
|
||||
std::string pa_ord;
|
||||
size_t pa_the_ptr;
|
||||
char pa_breakchar;
|
||||
char pa_enable;
|
||||
char pa_disable;
|
||||
short pa_nospace;
|
||||
bool pa_quote;
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _PARSE_H
|
||||
@@ -0,0 +1,5 @@
|
||||
EQEmu took this code from `C++ Sockets Library`
|
||||
http://www.alhem.net/Sockets/
|
||||
and integrated it into our world server. We did not care for the actual
|
||||
socket code (didnt work on windows) so we scrapped all of it, and just
|
||||
used the HTTP framework code.
|
||||
@@ -0,0 +1,5 @@
|
||||
Find uuid.h here
|
||||
http://www.die.net/doc/linux/include/uuid/uuid.h
|
||||
or here
|
||||
http://www.thedna.net/uuid.h
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/** \file Utility.cpp
|
||||
** \date 2004-02-13
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#include "Utility.h"
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
|
||||
std::string Utility::base64(const std::string& str_in)
|
||||
{
|
||||
std::string str;
|
||||
Base64::encode(str_in, str, false); // , false == do not add cr/lf
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
std::string Utility::base64d(const std::string& str_in)
|
||||
{
|
||||
std::string str;
|
||||
Base64::decode(str_in, str);
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
std::string Utility::l2string(long l)
|
||||
{
|
||||
std::string str;
|
||||
char tmp[100];
|
||||
sprintf(tmp,"%ld",l);
|
||||
str = tmp;
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
std::string Utility::bigint2string(uint64_t l)
|
||||
{
|
||||
std::string str;
|
||||
uint64_t tmp = l;
|
||||
while (tmp)
|
||||
{
|
||||
uint64_t a = tmp % 10;
|
||||
str = (char)(a + 48) + str;
|
||||
tmp /= 10;
|
||||
}
|
||||
if (!str.size())
|
||||
{
|
||||
str = "0";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
uint64_t Utility::atoi64(const std::string& str)
|
||||
{
|
||||
uint64_t l = 0;
|
||||
for (size_t i = 0; i < str.size(); i++)
|
||||
{
|
||||
l = l * 10 + str[i] - 48;
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
|
||||
unsigned int Utility::hex2unsigned(const std::string& str)
|
||||
{
|
||||
unsigned int r = 0;
|
||||
for (size_t i = 0; i < str.size(); i++)
|
||||
{
|
||||
r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Encode string per RFC1738 URL encoding rules
|
||||
* tnx rstaveley
|
||||
*/
|
||||
std::string Utility::rfc1738_encode(const std::string& src)
|
||||
{
|
||||
static char hex[] = "0123456789ABCDEF";
|
||||
std::string dst;
|
||||
for (size_t i = 0; i < src.size(); i++)
|
||||
{
|
||||
if (isalnum(src[i]))
|
||||
{
|
||||
dst += src[i];
|
||||
}
|
||||
else
|
||||
if (src[i] == ' ')
|
||||
{
|
||||
dst += '+';
|
||||
}
|
||||
else
|
||||
{
|
||||
dst += '%';
|
||||
dst += hex[src[i] / 16];
|
||||
dst += hex[src[i] % 16];
|
||||
}
|
||||
}
|
||||
return dst;
|
||||
} // rfc1738_encode
|
||||
|
||||
|
||||
/*
|
||||
* Decode string per RFC1738 URL encoding rules
|
||||
* tnx rstaveley
|
||||
*/
|
||||
std::string Utility::rfc1738_decode(const std::string& src)
|
||||
{
|
||||
std::string dst;
|
||||
for (size_t i = 0; i < src.size(); i++)
|
||||
{
|
||||
if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2]))
|
||||
{
|
||||
char c1 = src[++i];
|
||||
char c2 = src[++i];
|
||||
c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
|
||||
c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
|
||||
dst += (char)(c1 * 16 + c2);
|
||||
}
|
||||
else
|
||||
if (src[i] == '+')
|
||||
{
|
||||
dst += ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
dst += src[i];
|
||||
}
|
||||
}
|
||||
return dst;
|
||||
} // rfc1738_decode
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/** \file Utility.h
|
||||
** \date 2004-02-13
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _UTILITY_H
|
||||
#define _UTILITY_H
|
||||
|
||||
#include <ctype.h>
|
||||
#ifdef _WIN32
|
||||
typedef unsigned __int64 uint64_t;
|
||||
#else
|
||||
#include <stdlib.h>
|
||||
#ifdef SOLARIS
|
||||
# include <sys/types.h>
|
||||
#else
|
||||
# include <stdint.h>
|
||||
#endif
|
||||
#endif
|
||||
#include "Base64.h"
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
/** Conversion utilities.
|
||||
\ingroup util */
|
||||
class Utility
|
||||
{
|
||||
public:
|
||||
static std::string base64(const std::string& str_in);
|
||||
static std::string base64d(const std::string& str_in);
|
||||
static std::string l2string(long l);
|
||||
static std::string bigint2string(uint64_t l);
|
||||
static uint64_t atoi64(const std::string& str);
|
||||
static unsigned int hex2unsigned(const std::string& str);
|
||||
static std::string rfc1738_encode(const std::string& src);
|
||||
static std::string rfc1738_decode(const std::string& src);
|
||||
};
|
||||
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // _UTILITY_H
|
||||
@@ -0,0 +1,340 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,87 @@
|
||||
/** \file socket_include.cpp
|
||||
** \date 2004-11-28
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
|
||||
// only to be included in win32 projects
|
||||
const char *StrError(int x)
|
||||
{
|
||||
static char tmp[100];
|
||||
switch (x)
|
||||
{
|
||||
case 10004: return "Interrupted function call.";
|
||||
case 10013: return "Permission denied.";
|
||||
case 10014: return "Bad address.";
|
||||
case 10022: return "Invalid argument.";
|
||||
case 10024: return "Too many open files.";
|
||||
case 10035: return "Resource temporarily unavailable.";
|
||||
case 10036: return "Operation now in progress.";
|
||||
case 10037: return "Operation already in progress.";
|
||||
case 10038: return "Socket operation on nonsocket.";
|
||||
case 10039: return "Destination address required.";
|
||||
case 10040: return "Message too long.";
|
||||
case 10041: return "Protocol wrong type for socket.";
|
||||
case 10042: return "Bad protocol option.";
|
||||
case 10043: return "Protocol not supported.";
|
||||
case 10044: return "Socket type not supported.";
|
||||
case 10045: return "Operation not supported.";
|
||||
case 10046: return "Protocol family not supported.";
|
||||
case 10047: return "Address family not supported by protocol family.";
|
||||
case 10048: return "Address already in use.";
|
||||
case 10049: return "Cannot assign requested address.";
|
||||
case 10050: return "Network is down.";
|
||||
case 10051: return "Network is unreachable.";
|
||||
case 10052: return "Network dropped connection on reset.";
|
||||
case 10053: return "Software caused connection abort.";
|
||||
case 10054: return "Connection reset by peer.";
|
||||
case 10055: return "No buffer space available.";
|
||||
case 10056: return "Socket is already connected.";
|
||||
case 10057: return "Socket is not connected.";
|
||||
case 10058: return "Cannot send after socket shutdown.";
|
||||
case 10060: return "Connection timed out.";
|
||||
case 10061: return "Connection refused.";
|
||||
case 10064: return "Host is down.";
|
||||
case 10065: return "No route to host.";
|
||||
case 10067: return "Too many processes.";
|
||||
case 10091: return "Network subsystem is unavailable.";
|
||||
case 10092: return "Winsock.dll version out of range.";
|
||||
case 10093: return "Successful WSAStartup not yet performed.";
|
||||
case 10101: return "Graceful shutdown in progress.";
|
||||
case 10109: return "Class type not found.";
|
||||
case 11001: return "Host not found.";
|
||||
case 11002: return "Nonauthoritative host not found.";
|
||||
case 11003: return "This is a nonrecoverable error.";
|
||||
case 11004: return "Valid name, no data record of requested type.";
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
sprintf(tmp, "Winsock error code: %d", x);
|
||||
return tmp;
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
/** \file socket_include.h
|
||||
** \date 2005-04-12
|
||||
** \author grymse@alhem.net
|
||||
**/
|
||||
/*
|
||||
Copyright (C) 2004,2005 Anders Hedstrom
|
||||
|
||||
This library is made available under the terms of the GNU GPL.
|
||||
|
||||
If you would like to use this library in a closed-source application,
|
||||
a separate license agreement is available. For information about
|
||||
the closed-source license agreement for the C++ sockets library,
|
||||
please visit http://www.alhem.net/Sockets/license.html and/or
|
||||
email license@alhem.net.
|
||||
|
||||
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.
|
||||
*/
|
||||
#ifndef _SOCKET_INCLUDE_H
|
||||
#define _SOCKET_INCLUDE_H
|
||||
|
||||
#if (defined(__unix__) || defined(unix)) && !defined(USG)
|
||||
#include <sys/param.h>
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef _WIN32
|
||||
// ----------------------------------------
|
||||
// common unix includes / defines
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
#define Errno errno
|
||||
#define StrError strerror
|
||||
|
||||
// WIN32 adapt
|
||||
#define closesocket close
|
||||
#define INVALID_SOCKET -1
|
||||
#define SOCKET_ERROR -1
|
||||
typedef int SOCKET;
|
||||
|
||||
#ifndef INADDR_NONE
|
||||
#define INADDR_NONE ((unsigned long) -1)
|
||||
#endif // INADDR_NONE
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // !_WIN32
|
||||
|
||||
|
||||
// ----------------------------------------
|
||||
// Generic
|
||||
#ifndef SOL_IP
|
||||
#define SOL_IP IPPROTO_IP
|
||||
#endif
|
||||
|
||||
|
||||
// ----------------------------------------
|
||||
// OS specific adaptions
|
||||
|
||||
#ifdef SOLARIS
|
||||
// ----------------------------------------
|
||||
// Solaris
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
typedef unsigned short port_t;
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#define s6_addr16 _S6_un._S6_u8
|
||||
#define MSG_NOSIGNAL 0
|
||||
|
||||
#elif defined __FreeBSD__
|
||||
// ----------------------------------------
|
||||
// FreeBSD
|
||||
# if __FreeBSD_version >= 400014
|
||||
# define s6_addr16 __u6_addr.__u6_addr16
|
||||
# if !defined(MSG_NOSIGNAL)
|
||||
# define MSG_NOSIGNAL 0
|
||||
# endif
|
||||
# include <netinet/in.h>
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
typedef in_addr_t ipaddr_t;
|
||||
typedef in_port_t port_t;
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
|
||||
# define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
|
||||
# else
|
||||
# error FreeBSD versions prior to 400014 does not support ipv6
|
||||
# endif
|
||||
|
||||
#elif defined MACOSX
|
||||
// ----------------------------------------
|
||||
// Mac OS X
|
||||
#include <string.h>
|
||||
#include <mach/port.h>
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
typedef unsigned long ipaddr_t;
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#define s6_addr16 __u6_addr.__u6_addr16
|
||||
#define MSG_NOSIGNAL 0 // oops - thanks Derek
|
||||
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
|
||||
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
|
||||
|
||||
#elif defined _WIN32
|
||||
// ----------------------------------------
|
||||
// Win32
|
||||
#pragma comment(lib, "wsock32.lib")
|
||||
#define strcasecmp _stricmp
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
typedef unsigned long ipaddr_t;
|
||||
typedef unsigned short port_t;
|
||||
typedef int socklen_t;
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#define MSG_NOSIGNAL 0
|
||||
#define SHUT_RDWR 2
|
||||
|
||||
// 1.8.6: define FD_SETSIZE to something bigger than 64 if there are a lot of
|
||||
// simultaneous connections (must be done before including winsock.h)
|
||||
//#define FD_SETSIZE 1024
|
||||
#include <winsock.h>
|
||||
|
||||
#define Errno WSAGetLastError()
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
const char *StrError(int x);
|
||||
|
||||
// class WSAInitializer is a part of the Socket class (on win32)
|
||||
// as a static instance - so whenever an application uses a Socket,
|
||||
// winsock is initialized
|
||||
class WSAInitializer // Winsock Initializer
|
||||
{
|
||||
public:
|
||||
WSAInitializer() {
|
||||
if (WSAStartup(0x101,&m_wsadata))
|
||||
{
|
||||
exit(-1);
|
||||
}
|
||||
}
|
||||
~WSAInitializer() {
|
||||
WSACleanup();
|
||||
}
|
||||
private:
|
||||
WSADATA m_wsadata;
|
||||
};
|
||||
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// ----------------------------------------
|
||||
// LINUX
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
namespace SOCKETS_NAMESPACE {
|
||||
#endif
|
||||
|
||||
typedef unsigned long ipaddr_t;
|
||||
typedef unsigned short port_t;
|
||||
#ifdef SOCKETS_NAMESPACE
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef _THREADSAFE_SOCKETS
|
||||
#include "mutex.h"
|
||||
#include "Lock.h"
|
||||
#endif
|
||||
|
||||
#endif // _SOCKET_INCLUDE_H
|
||||
@@ -1,20 +1,3 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**********************************************************************
|
||||
*
|
||||
* StackWalker.cpp
|
||||
@@ -359,7 +342,7 @@ public:
|
||||
BOOL Publics; // contains public symbols
|
||||
};
|
||||
*/
|
||||
struct IMAGEHLP_MODULE64_V2 {
|
||||
typedef struct IMAGEHLP_MODULE64_V2 {
|
||||
DWORD SizeOfStruct; // set to sizeof(IMAGEHLP_MODULE64)
|
||||
DWORD64 BaseOfImage; // base load address of module
|
||||
DWORD ImageSize; // virtual size of the loaded module
|
||||
|
||||
@@ -1,20 +1,3 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**********************************************************************
|
||||
*
|
||||
* StackWalker.h
|
||||
@@ -31,7 +14,7 @@
|
||||
// so we need not to check the version (because we only support _MSC_VER >= 1100)!
|
||||
#pragma once
|
||||
|
||||
#include "common/platform/win/include_windows.h"
|
||||
#include <windows.h>
|
||||
|
||||
// special defines for VC5/6 (if no actual PSDK is installed):
|
||||
#if _MSC_VER < 1300
|
||||
@@ -134,7 +117,7 @@ protected:
|
||||
CHAR loadedImageName[STACKWALK_MAX_NAMELEN];
|
||||
} CallstackEntry;
|
||||
|
||||
enum CallstackEntryType {firstEntry, nextEntry, lastEntry};
|
||||
typedef enum CallstackEntryType {firstEntry, nextEntry, lastEntry};
|
||||
|
||||
virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName);
|
||||
virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion);
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
|
||||
/*
|
||||
* This is an additive lagged fibonacci generator as seen in The Art of Computer Programming, Vol. 2
|
||||
* This should roughly match the implementation that EQ's client uses and be compatible with our Random class
|
||||
*
|
||||
* EQ's rand looks like it was from an example implementation that as posted on pscode.com
|
||||
*
|
||||
* You might also want to consider defining BIASED_INT_DIST as well to more closely match EQ
|
||||
*/
|
||||
|
||||
namespace EQ {
|
||||
template<typename UIntType, size_t w, size_t j, size_t k>
|
||||
class additive_lagged_fibonacci_engine {
|
||||
static_assert(std::is_unsigned<UIntType>::value, "result_type must be an unsigned integral type");
|
||||
static_assert(0u < j && j < k, "0 < j < k");
|
||||
static_assert(0u < w && w <= std::numeric_limits<UIntType>::digits,
|
||||
"template argument substituting w out of bounds");
|
||||
|
||||
public:
|
||||
using result_type = UIntType;
|
||||
static constexpr size_t word_size = w;
|
||||
static constexpr size_t short_lag = j;
|
||||
static constexpr size_t long_lag = k;
|
||||
static constexpr result_type default_seed = 19780503u; // default for subtract_with_carry_engine
|
||||
|
||||
additive_lagged_fibonacci_engine() : additive_lagged_fibonacci_engine(default_seed) {}
|
||||
|
||||
explicit additive_lagged_fibonacci_engine(result_type sd) { seed(sd); }
|
||||
|
||||
void seed(result_type seed = default_seed)
|
||||
{
|
||||
state1 = long_lag - long_lag;
|
||||
state2 = long_lag - short_lag;
|
||||
state[0] = static_cast<int>(seed) & ((1u << word_size) - 1);
|
||||
state[1] = 1;
|
||||
for (int i = 2; i < long_lag; ++i)
|
||||
state[i] = (state[i - 1] + state[i - 2]) & ((1u << word_size) - 1);
|
||||
return;
|
||||
}
|
||||
// TODO: seed via seed_seq
|
||||
|
||||
static constexpr result_type min() { return 0; }
|
||||
static constexpr result_type max() { return ((1u << word_size) - 1) >> 6; }
|
||||
|
||||
void discard(unsigned long long z) {
|
||||
for (; z != 0ULL; --z)
|
||||
(*this)();
|
||||
}
|
||||
|
||||
result_type operator()() {
|
||||
result_type rand = (state[state1] + state[state2]) & ((1u << word_size) - 1);
|
||||
state[state1] = rand;
|
||||
if (++state1 == long_lag)
|
||||
state1 = 0;
|
||||
if (++state2 == long_lag)
|
||||
state2 = 0;
|
||||
|
||||
return rand >> 6;
|
||||
}
|
||||
|
||||
private:
|
||||
result_type state1;
|
||||
result_type state2;
|
||||
result_type state[long_lag];
|
||||
|
||||
public:
|
||||
template<typename UInt, size_t W, size_t J, size_t K>
|
||||
friend bool operator==(const additive_lagged_fibonacci_engine<UInt, W, J, K> &x,
|
||||
const additive_lagged_fibonacci_engine<UInt, W, J, K> &y)
|
||||
{
|
||||
return std::equal(x.state, x.state + long_lag, y.state) && x.state1 == y.state1 &&
|
||||
x.state2 == y.state2;
|
||||
}
|
||||
|
||||
template<typename UInt, size_t W, size_t J, size_t K>
|
||||
friend bool operator!=(const additive_lagged_fibonacci_engine<UInt, W, J, K> &x,
|
||||
const additive_lagged_fibonacci_engine<UInt, W, J, K> &y)
|
||||
{ return !(x == y); }
|
||||
|
||||
template<typename UInt, size_t W, size_t J, size_t K, typename CharT, typename Traits>
|
||||
friend std::basic_ostream<CharT, Traits> &
|
||||
operator<<(std::basic_istream<CharT, Traits> &os, additive_lagged_fibonacci_engine<UInt, W, J, K> &x)
|
||||
{
|
||||
using ios_base = typename std::basic_istream<CharT, Traits>::ios_base;
|
||||
|
||||
const typename ios_base::fmtflags flags = os.flags();
|
||||
const CharT fill = os.fill();
|
||||
const CharT space = os.widen(' ');
|
||||
os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
|
||||
os.fill(space);
|
||||
|
||||
for (size_t i = 0; i < long_lag; ++i)
|
||||
os << x.state[i] << space;
|
||||
os << x.state1 << space << x.state2;
|
||||
|
||||
os.flags(flags);
|
||||
os.fill(fill);
|
||||
return os;
|
||||
}
|
||||
|
||||
template<typename UInt, size_t W, size_t J, size_t K, typename CharT, typename Traits>
|
||||
friend std::basic_istream<CharT, Traits> &
|
||||
operator>>(std::basic_istream<CharT, Traits> &is, additive_lagged_fibonacci_engine<UInt, W, J, K> &x)
|
||||
{
|
||||
using ios_base = typename std::basic_istream<CharT, Traits>::ios_base;
|
||||
|
||||
const typename ios_base::fmtflags flags = is.flags();
|
||||
is.flags(ios_base::dec | ios_base::skipws);
|
||||
|
||||
for (size_t i = 0; i < long_lag; ++i)
|
||||
is >> x.state[i];
|
||||
is >> x.state1;
|
||||
is >> x.state2;
|
||||
|
||||
is.flags(flags);
|
||||
return is;
|
||||
}
|
||||
};
|
||||
|
||||
using EQRand = additive_lagged_fibonacci_engine<uint32_t, 30, 24, 55>;
|
||||
};
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
* Boost Software License - Version 1.0 - August 17th, 2003
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person or organization
|
||||
* obtaining a copy of the software and accompanying documentation covered by
|
||||
* this license (the "Software") to use, reproduce, display, distribute,
|
||||
* execute, and transmit the Software, and to prepare derivative works of the
|
||||
* Software, and to permit third-parties to whom the Software is furnished to
|
||||
* do so, all subject to the following:
|
||||
*
|
||||
* The copyright notices in the Software and this entire statement, including
|
||||
* the above license grant, this restriction and the following disclaimer,
|
||||
* must be included in all copies of the Software, in whole or in part, and
|
||||
* all derivative works of the Software, unless such copies or derivative
|
||||
* works are solely in the form of machine-executable object code generated by
|
||||
* a source language processor.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
||||
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
||||
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// EQEmu::Any is a modified version of Boost::Any and as such retains the Boost licensing.
|
||||
|
||||
#ifndef EQEMU_COMMON_ANY_H
|
||||
#define EQEMU_COMMON_ANY_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <typeinfo>
|
||||
|
||||
namespace EQEmu
|
||||
{
|
||||
class Any
|
||||
{
|
||||
public:
|
||||
Any()
|
||||
: content(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
Any(const ValueType &value)
|
||||
: content(new Holder<ValueType>(value))
|
||||
{
|
||||
}
|
||||
|
||||
Any(const Any &other)
|
||||
: content(other.content ? other.content->clone() : 0)
|
||||
{
|
||||
}
|
||||
|
||||
~Any()
|
||||
{
|
||||
if(content)
|
||||
delete content;
|
||||
}
|
||||
|
||||
Any& swap(Any &rhs)
|
||||
{
|
||||
std::swap(content, rhs.content);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
Any& operator=(const ValueType &rhs)
|
||||
{
|
||||
Any(rhs).swap(*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Any& operator=(Any rhs)
|
||||
{
|
||||
rhs.swap(*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return !content;
|
||||
}
|
||||
|
||||
const std::type_info& type() const
|
||||
{
|
||||
return content ? content->type() : typeid(void);
|
||||
}
|
||||
|
||||
class Placeholder
|
||||
{
|
||||
public:
|
||||
virtual ~Placeholder()
|
||||
{
|
||||
}
|
||||
|
||||
virtual const std::type_info& type() const = 0;
|
||||
virtual Placeholder* clone() const = 0;
|
||||
};
|
||||
|
||||
|
||||
template<typename ValueType>
|
||||
class Holder : public Placeholder
|
||||
{
|
||||
public:
|
||||
Holder(const ValueType &value)
|
||||
: held(value)
|
||||
{
|
||||
}
|
||||
|
||||
virtual const std::type_info& type() const
|
||||
{
|
||||
return typeid(ValueType);
|
||||
}
|
||||
|
||||
virtual Placeholder* clone() const
|
||||
{
|
||||
return new Holder(held);
|
||||
}
|
||||
|
||||
ValueType held;
|
||||
|
||||
private:
|
||||
Holder& operator=(const Holder&);
|
||||
};
|
||||
|
||||
private:
|
||||
template<typename ValueType>
|
||||
friend ValueType* any_cast(Any*);
|
||||
|
||||
template<typename ValueType>
|
||||
friend ValueType* unsafe_any_cast(Any*);
|
||||
|
||||
Placeholder* content;
|
||||
};
|
||||
|
||||
class bad_any_cast : public std::bad_cast
|
||||
{
|
||||
public:
|
||||
virtual const char * what() const throw()
|
||||
{
|
||||
return "DBI::bad_any_cast: failed conversion using DBI::any_cast";
|
||||
}
|
||||
};
|
||||
|
||||
template<typename ValueType>
|
||||
ValueType* any_cast(Any* operand)
|
||||
{
|
||||
return operand &&
|
||||
operand->type() == typeid(ValueType) ? &static_cast<Any::Holder<ValueType>*>(operand->content)->held : nullptr;
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
inline const ValueType* any_cast(const Any* operand)
|
||||
{
|
||||
return any_cast<ValueType>(const_cast<Any*>(operand));
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
ValueType any_cast(Any& operand)
|
||||
{
|
||||
typedef typename std::remove_reference<ValueType>::type nonref;
|
||||
nonref* result = any_cast<nonref>(&operand);
|
||||
if(!result)
|
||||
throw bad_any_cast();
|
||||
return *result;
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
inline ValueType any_cast(const Any& operand)
|
||||
{
|
||||
typedef typename std::remove_reference<ValueType>::type nonref;
|
||||
return any_cast<const nonref&>(const_cast<Any&>(operand));
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
inline ValueType* unsafe_any_cast(Any* operand)
|
||||
{
|
||||
return &static_cast<Any::Holder<ValueType>*>(operand->content)->held;
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
inline const ValueType* unsafe_any_cast(const Any* operand)
|
||||
{
|
||||
return unsafe_any_cast<ValueType>(const_cast<Any*>(operand));
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,34 @@
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2013 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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; version 2 of the License.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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
|
||||
*/
|
||||
|
||||
#ifndef __EQEMU_COMMON_BASE_DATA_H
|
||||
#define __EQEMU_COMMON_BASE_DATA_H
|
||||
|
||||
struct BaseDataStruct
|
||||
{
|
||||
double base_hp;
|
||||
double base_mana;
|
||||
double base_end;
|
||||
double hp_regen;
|
||||
double end_regen;
|
||||
double hp_factor;
|
||||
double mana_factor;
|
||||
double endurance_factor;
|
||||
};
|
||||
|
||||
#endif
|
||||
+30
-30
@@ -1,52 +1,52 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2006 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#include "common/base_packet.h"
|
||||
#include "common/misc.h"
|
||||
#include "common/packet_dump.h"
|
||||
|
||||
BasePacket::BasePacket(const unsigned char* buf, size_t len)
|
||||
#include "global_define.h"
|
||||
#include "base_packet.h"
|
||||
#include "misc.h"
|
||||
#include "packet_dump.h"
|
||||
|
||||
BasePacket::BasePacket(const unsigned char *buf, uint32 len)
|
||||
{
|
||||
if (len > 0) {
|
||||
size = static_cast<uint32>(len);
|
||||
pBuffer = new unsigned char[len];
|
||||
this->pBuffer=nullptr;
|
||||
this->size=0;
|
||||
this->_wpos = 0;
|
||||
this->_rpos = 0;
|
||||
this->timestamp.tv_sec = 0;
|
||||
if (len>0) {
|
||||
this->size=len;
|
||||
pBuffer= new unsigned char[len];
|
||||
if (buf) {
|
||||
memcpy(pBuffer, buf, len);
|
||||
}
|
||||
else {
|
||||
memset(pBuffer, 0, len);
|
||||
memcpy(this->pBuffer,buf,len);
|
||||
} else {
|
||||
memset(this->pBuffer,0,len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BasePacket::BasePacket(SerializeBuffer&& buf)
|
||||
: pBuffer(std::exchange(buf.m_buffer, nullptr))
|
||||
{
|
||||
// We are essentially taking ownership of this serialize buffer.
|
||||
size = static_cast<uint32>(std::exchange(buf.m_pos, 0));
|
||||
buf.m_capacity = 0;
|
||||
}
|
||||
|
||||
BasePacket::~BasePacket()
|
||||
{
|
||||
delete[] pBuffer;
|
||||
pBuffer = nullptr;
|
||||
if (pBuffer)
|
||||
delete[] pBuffer;
|
||||
pBuffer=nullptr;
|
||||
}
|
||||
|
||||
|
||||
void BasePacket::build_raw_header_dump(char *buffer, uint16 seq) const
|
||||
{
|
||||
if (timestamp.tv_sec) {
|
||||
|
||||
+39
-40
@@ -1,48 +1,44 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2006 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef BASEPACKET_H_
|
||||
#define BASEPACKET_H_
|
||||
|
||||
#include "common/platform/inet.h"
|
||||
#include "common/serialize_buffer.h"
|
||||
#include "common/types.h"
|
||||
#include "types.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
class BasePacket
|
||||
{
|
||||
protected:
|
||||
BasePacket() = default;
|
||||
BasePacket(const unsigned char* buf, size_t len);
|
||||
BasePacket(SerializeBuffer&& buf);
|
||||
|
||||
virtual ~BasePacket();
|
||||
#ifdef _WINDOWS
|
||||
#include <time.h>
|
||||
#include <winsock2.h>
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <sys/time.h>
|
||||
#include <netinet/in.h>
|
||||
#endif
|
||||
|
||||
class BasePacket {
|
||||
public:
|
||||
unsigned char* pBuffer = nullptr;
|
||||
uint32 size = 0;
|
||||
uint32 _wpos = 0;
|
||||
uint32 _rpos = 0;
|
||||
uint32 src_ip = 0;
|
||||
uint32 dst_ip = 0;
|
||||
uint16 src_port = 0;
|
||||
uint16 dst_port = 0;
|
||||
uint32 priority = 0;
|
||||
timeval timestamp{};
|
||||
unsigned char *pBuffer;
|
||||
uint32 size, _wpos, _rpos;
|
||||
uint32 src_ip,dst_ip;
|
||||
uint16 src_port,dst_port;
|
||||
uint32 priority;
|
||||
timeval timestamp;
|
||||
|
||||
virtual void build_raw_header_dump(char *buffer, uint16 seq=0xffff) const;
|
||||
virtual void build_header_dump(char *buffer) const;
|
||||
@@ -52,24 +48,21 @@ public:
|
||||
|
||||
void setSrcInfo(uint32 sip, uint16 sport) { src_ip=sip; src_port=sport; }
|
||||
void setDstInfo(uint32 dip, uint16 dport) { dst_ip=dip; dst_port=dport; }
|
||||
void setTimeInfo(uint32 ts_sec, uint32 ts_usec) { timestamp.tv_sec = ts_sec; timestamp.tv_usec = ts_usec; }
|
||||
void setTimeInfo(uint32 ts_sec, uint32 ts_usec) { timestamp.tv_sec=ts_sec; timestamp.tv_usec=ts_usec; }
|
||||
void copyInfo(const BasePacket *p) { src_ip=p->src_ip; src_port=p->src_port; dst_ip=p->dst_ip; dst_port=p->dst_port; timestamp.tv_sec=p->timestamp.tv_sec; timestamp.tv_usec=p->timestamp.tv_usec; }
|
||||
|
||||
inline bool operator<(const BasePacket &rhs) {
|
||||
return (timestamp.tv_sec < rhs.timestamp.tv_sec || (timestamp.tv_sec == rhs.timestamp.tv_sec && timestamp.tv_usec < rhs.timestamp.tv_usec));
|
||||
return (timestamp.tv_sec < rhs.timestamp.tv_sec || (timestamp.tv_sec==rhs.timestamp.tv_sec && timestamp.tv_usec < rhs.timestamp.tv_usec));
|
||||
}
|
||||
|
||||
void WriteUInt8(uint8 value) { *(uint8 *)(pBuffer + _wpos) = value; _wpos += sizeof(uint8); }
|
||||
void WriteUInt32(uint32 value) { *(uint32 *)(pBuffer + _wpos) = value; _wpos += sizeof(uint32); }
|
||||
void WriteUInt64(uint64 value) { *(uint64 *)(pBuffer + _wpos) = value; _wpos += sizeof(uint64); }
|
||||
void WriteSInt16(int32 value) { *(int16*)(pBuffer + _wpos) = value; _wpos += sizeof(int16); }
|
||||
void WriteUInt16(uint32 value) { *(uint16 *)(pBuffer + _wpos) = value; _wpos += sizeof(uint16); }
|
||||
void WriteSInt32(int32 value) { *(int32 *)(pBuffer + _wpos) = value; _wpos += sizeof(int32); }
|
||||
void WriteFloat(float value) { *(float *)(pBuffer + _wpos) = value; _wpos += sizeof(float); }
|
||||
void WriteDouble(double value) { *(double *)(pBuffer + _wpos) = value; _wpos += sizeof(double); }
|
||||
void WriteString(const char * str) { uint32 len = static_cast<uint32>(strlen(str)) + 1; memcpy(pBuffer + _wpos, str, len); _wpos += len; }
|
||||
// this is used in task system a lot, it is NOT null-termed
|
||||
void WriteLengthString(uint32 len, const char *str) { *(uint32 *)(pBuffer + _wpos) = len; _wpos += sizeof(uint32); memcpy(pBuffer + _wpos, str, len); _wpos += len; }
|
||||
void WriteData(const void *ptr, size_t n) { memcpy(pBuffer + _wpos, ptr, n); _wpos += n; }
|
||||
|
||||
uint8 ReadUInt8() { uint8 value = *(uint8 *)(pBuffer + _rpos); _rpos += sizeof(uint8); return value; }
|
||||
@@ -79,16 +72,22 @@ public:
|
||||
uint32 ReadUInt32() { uint32 value = *(uint32 *)(pBuffer + _rpos); _rpos += sizeof(uint32); return value; }
|
||||
uint32 ReadUInt32(uint32 Offset) const { uint32 value = *(uint32 *)(pBuffer + Offset); return value; }
|
||||
void ReadString(char *str) { uint32 len = static_cast<uint32>(strlen((char *)(pBuffer + _rpos))) + 1; memcpy(str, pBuffer + _rpos, len); _rpos += len; }
|
||||
void ReadString(std::string &str) { str = reinterpret_cast<char *>(pBuffer + _rpos); _rpos += str.length() + 1; }
|
||||
void ReadString(char *str, uint32 Offset, uint32 MaxLength) const;
|
||||
void ReadLengthString(std::string& str) { uint32 len = *(uint32*)(pBuffer + _rpos); _rpos += sizeof(uint32); str.resize(len); memcpy(&str[0], pBuffer + _rpos, len); _rpos += len; }
|
||||
|
||||
uint32 GetWritePosition() { return _wpos; }
|
||||
uint32 GetReadPosition() { return _rpos; }
|
||||
void SetWritePosition(uint32 Newwpos) { _wpos = Newwpos; }
|
||||
void SetReadPosition(uint32 Newrpos) { _rpos = Newrpos; }
|
||||
|
||||
protected:
|
||||
virtual ~BasePacket();
|
||||
BasePacket() { pBuffer=nullptr; size=0; _wpos = 0; _rpos = 0; }
|
||||
BasePacket(const unsigned char *buf, const uint32 len);
|
||||
};
|
||||
|
||||
extern void DumpPacketHex(const BasePacket* app);
|
||||
extern void DumpPacketAscii(const BasePacket* app);
|
||||
extern void DumpPacketBin(const BasePacket* app);
|
||||
|
||||
#endif /*BASEPACKET_H_*/
|
||||
|
||||
|
||||
@@ -1,352 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "bazaar.h"
|
||||
|
||||
#include "common/item_instance.h"
|
||||
#include "common/repositories/trader_repository.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
std::vector<BazaarSearchResultsFromDB_Struct>
|
||||
Bazaar::GetSearchResults(
|
||||
Database &db,
|
||||
Database &content_db,
|
||||
BazaarSearchCriteria_Struct search,
|
||||
uint32 char_zone_id,
|
||||
int32 char_zone_instance_id
|
||||
)
|
||||
{
|
||||
LogTrading(
|
||||
"Searching for items with search criteria - item_name [{}] min_cost [{}] max_cost [{}] min_level [{}] "
|
||||
"max_level [{}] max_results [{}] prestige [{}] augment [{}] trader_entity_id [{}] trader_id [{}] "
|
||||
"search_scope [{}] char_zone_id [{}], char_zone_instance_id [{}]",
|
||||
search.item_name,
|
||||
search.min_cost,
|
||||
search.max_cost,
|
||||
search.min_level,
|
||||
search.max_level,
|
||||
search.max_results,
|
||||
search.prestige,
|
||||
search.augment,
|
||||
search.trader_entity_id,
|
||||
search.trader_id,
|
||||
search.search_scope,
|
||||
char_zone_id,
|
||||
char_zone_instance_id
|
||||
);
|
||||
|
||||
static std::map<uint8, uint32> item_slot_searches_new = {
|
||||
{EQ::invslot::slotCharm, 1},
|
||||
{EQ::invslot::slotEar1, 2},
|
||||
{EQ::invslot::slotHead, 4},
|
||||
{EQ::invslot::slotFace, 8},
|
||||
{EQ::invslot::slotEar2, 16},
|
||||
{EQ::invslot::slotNeck, 32},
|
||||
{EQ::invslot::slotShoulders, 64},
|
||||
{EQ::invslot::slotArms, 128},
|
||||
{EQ::invslot::slotBack, 256},
|
||||
{EQ::invslot::slotWrist1, 512},
|
||||
{EQ::invslot::slotWrist2, 1024},
|
||||
{EQ::invslot::slotRange, 2048},
|
||||
{EQ::invslot::slotHands, 4096},
|
||||
{EQ::invslot::slotPrimary, 8192},
|
||||
{EQ::invslot::slotSecondary, 16384},
|
||||
{EQ::invslot::slotFinger1, 32768},
|
||||
{EQ::invslot::slotFinger2, 65536},
|
||||
{EQ::invslot::slotChest, 131072},
|
||||
{EQ::invslot::slotLegs, 262144},
|
||||
{EQ::invslot::slotFeet, 524288},
|
||||
{EQ::invslot::slotWaist, 1048576},
|
||||
{EQ::invslot::slotPowerSource, 2097152},
|
||||
{EQ::invslot::slotAmmo, 4194304},
|
||||
};
|
||||
|
||||
struct ItemSearchType {
|
||||
EQ::item::ItemType type;
|
||||
std::string condition;
|
||||
};
|
||||
|
||||
std::vector<ItemSearchType> item_search_types_new = {
|
||||
{EQ::item::ItemType::ItemTypeBook, " AND (items.itemclass = 2 or items.itemclass = 31)"},
|
||||
{EQ::item::ItemType::ItemTypeContainer, " AND (items.itemclass = 1 or items.itemclass = 67)"},
|
||||
{EQ::item::ItemType::ItemTypeAllEffects, " AND (items.scrolleffect > 0 && items.scrolleffect < 65000)"},
|
||||
{EQ::item::ItemType::ItemTypeUnknown9, " AND items.worneffect = 998"},
|
||||
{EQ::item::ItemType::ItemTypeUnknown10, " AND (items.worneffect >= 1298 && items.worneffect <= 1307)"},
|
||||
{EQ::item::ItemType::ItemTypeFocusEffect, " AND items.focuseffect > 0"},
|
||||
{EQ::item::ItemType::ItemTypeArmor, " AND items.itemtype = 10"},
|
||||
{EQ::item::ItemType::ItemType1HBlunt, " AND items.itemtype = 3"},
|
||||
{EQ::item::ItemType::ItemType1HPiercing, " AND items.itemtype = 2"},
|
||||
{EQ::item::ItemType::ItemType1HSlash, " AND items.itemtype = 0"},
|
||||
{EQ::item::ItemType::ItemType2HBlunt, " AND items.itemtype = 4"},
|
||||
{EQ::item::ItemType::ItemType2HSlash, " AND items.itemtype = 1"},
|
||||
{EQ::item::ItemType::ItemTypeBow, " AND items.itemtype = 5"},
|
||||
{EQ::item::ItemType::ItemTypeShield, " AND items.itemtype = 8"},
|
||||
{EQ::item::ItemType::ItemTypeMisc, " AND items.itemtype = 11"},
|
||||
{EQ::item::ItemType::ItemTypeFood, " AND items.itemtype = 14"},
|
||||
{EQ::item::ItemType::ItemTypeDrink, " AND items.itemtype = 15"},
|
||||
{EQ::item::ItemType::ItemTypeLight, " AND items.itemtype = 16"},
|
||||
{EQ::item::ItemType::ItemTypeCombinable, " AND items.itemtype = 17"},
|
||||
{EQ::item::ItemType::ItemTypeBandage, " AND items.itemtype = 18"},
|
||||
{EQ::item::ItemType::ItemTypeSmallThrowing, " AND (items.itemtype = 19 OR items.itemtype = 7)"},
|
||||
{EQ::item::ItemType::ItemTypeSpell, " AND items.itemtype = 20"},
|
||||
{EQ::item::ItemType::ItemTypePotion, " AND items.itemtype = 21"},
|
||||
{EQ::item::ItemType::ItemTypeBrassInstrument, " AND items.itemtype = 25"},
|
||||
{EQ::item::ItemType::ItemTypeWindInstrument, " AND items.itemtype = 23"},
|
||||
{EQ::item::ItemType::ItemTypeStringedInstrument, " AND items.itemtype = 24"},
|
||||
{EQ::item::ItemType::ItemTypePercussionInstrument, " AND items.itemtype = 26"},
|
||||
{EQ::item::ItemType::ItemTypeArrow, " AND items.itemtype = 27"},
|
||||
{EQ::item::ItemType::ItemTypeJewelry, " AND items.itemtype = 29"},
|
||||
{EQ::item::ItemType::ItemTypeNote, " AND items.itemtype = 32"},
|
||||
{EQ::item::ItemType::ItemTypeKey, " AND items.itemtype = 33"},
|
||||
{EQ::item::ItemType::ItemType2HPiercing, " AND items.itemtype = 35"},
|
||||
{EQ::item::ItemType::ItemTypeAlcohol, " AND items.itemtype = 38"},
|
||||
{EQ::item::ItemType::ItemTypeMartial, " AND items.itemtype = 45"},
|
||||
{EQ::item::ItemType::ItemTypeAugmentation, " AND items.itemtype = 54"},
|
||||
{EQ::item::ItemType::ItemTypeAlternateAbility, " AND items.itemtype = 57"},
|
||||
{EQ::item::ItemType::ItemTypeCount, " AND items.itemtype = 65"},
|
||||
{EQ::item::ItemType::ItemTypeCollectible, " AND items.itemtype = 66"}
|
||||
};
|
||||
|
||||
// item stat searches
|
||||
struct ItemStatSearch {
|
||||
std::string query_string;
|
||||
EQ::skills::SkillType skill_type;
|
||||
};
|
||||
|
||||
std::map<uint32, ItemStatSearch> item_stat_searches_new = {
|
||||
{STAT_AC, {" items.ac" , static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_AGI, {" items.aagi", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_CHA, {" items.acha", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_DEX, {" items.adex", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_INT, {" items.aint", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_STA, {" items.asta", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_STR, {" items.astr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_WIS, {" items.awis", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_COLD, {" items.cr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_DISEASE, {" items.dr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_FIRE, {" items.fr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_MAGIC, {" items.mr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_POISON, {" items.pr", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HP, {" items.hp", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_MANA, {" items.mana", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_ENDURANCE, {" items.endur", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_ATTACK, {" items.attack", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HP_REGEN, {" items.regen", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_MANA_REGEN, {" items.manaregen", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HASTE, {" items.haste", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_DAMAGE_SHIELD, {" items.damageshield", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_DS_MITIGATION, {" items.dsmitigation", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEAL_AMOUNT, {" items.healamt", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_SPELL_DAMAGE, {" items.spelldmg", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_CLAIRVOYANCE, {" items.clairvoyance", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_AGILITY, {" items.heroic_agi", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_CHARISMA, {" items.heroic_cha", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_DEXTERITY, {" items.heroic_dex", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_INTELLIGENCE, {" items.heroic_int", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_STAMINA, {" items.heroic_sta", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_STRENGTH, {" items.heroic_str", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_HEROIC_WISDOM, {" items.heroic_wis", static_cast<EQ::skills::SkillType>(0)} },
|
||||
{STAT_BASH, {" items.skillmodvalue", EQ::skills::SkillBash} },
|
||||
{STAT_BACKSTAB, {" items.backstabdmg", EQ::skills::SkillBackstab} },
|
||||
{STAT_DRAGON_PUNCH, {" items.skillmodvalue", EQ::skills::SkillDragonPunch} },
|
||||
{STAT_EAGLE_STRIKE, {" items.skillmodvalue", EQ::skills::SkillEagleStrike} },
|
||||
{STAT_FLYING_KICK, {" items.skillmodvalue", EQ::skills::SkillFlyingKick} },
|
||||
{STAT_KICK, {" items.skillmodvalue", EQ::skills::SkillKick} },
|
||||
{STAT_ROUND_KICK, {" items.skillmodvalue", EQ::skills::SkillRoundKick} },
|
||||
{STAT_TIGER_CLAW, {" items.skillmodvalue", EQ::skills::SkillTigerClaw} },
|
||||
{STAT_FRENZY, {" items.skillmodvalue", EQ::skills::SkillFrenzy} },
|
||||
};
|
||||
|
||||
bool convert = false;
|
||||
std::string search_criteria_trader("TRUE");
|
||||
std::string field_criteria_items("FALSE");
|
||||
std::string where_criteria_items(" TRUE ");
|
||||
|
||||
if (search.search_scope == NonRoFBazaarSearchScope) {
|
||||
search_criteria_trader.append(
|
||||
fmt::format(
|
||||
" AND trader.char_entity_id = {} AND trader.char_zone_id = {} AND trader.char_zone_instance_id = {}",
|
||||
search.trader_entity_id,
|
||||
Zones::BAZAAR,
|
||||
char_zone_instance_id
|
||||
)
|
||||
);
|
||||
}
|
||||
else if (search.search_scope == Local_Scope) {
|
||||
search_criteria_trader.append(fmt::format(
|
||||
" AND trader.char_zone_id = {} AND trader.char_zone_instance_id = {}",
|
||||
char_zone_id,
|
||||
char_zone_instance_id)
|
||||
);
|
||||
}
|
||||
else if (search.trader_id > 0) {
|
||||
if (RuleB(Bazaar, UseAlternateBazaarSearch)) {
|
||||
if (search.trader_id >= TraderRepository::TRADER_CONVERT_ID) {
|
||||
convert = true;
|
||||
search_criteria_trader.append(fmt::format(
|
||||
" AND trader.char_zone_id = {} AND trader.char_zone_instance_id = {}",
|
||||
Zones::BAZAAR,
|
||||
search.trader_id - TraderRepository::TRADER_CONVERT_ID)
|
||||
);
|
||||
}
|
||||
else {
|
||||
search_criteria_trader.append(fmt::format(" AND trader.char_id = {}", search.trader_id));
|
||||
}
|
||||
}
|
||||
else {
|
||||
search_criteria_trader.append(fmt::format(" AND trader.char_id = {}", search.trader_id));
|
||||
}
|
||||
}
|
||||
|
||||
if (search.min_cost != 0) {
|
||||
search_criteria_trader.append(fmt::format(" AND trader.item_cost >= {}", search.min_cost * 1000));
|
||||
}
|
||||
if (search.max_cost != 0) {
|
||||
search_criteria_trader.append(fmt::format(" AND trader.item_cost <= {}", (uint64) search.max_cost * 1000));
|
||||
}
|
||||
|
||||
if (search.slot != std::numeric_limits<uint32>::max()) {
|
||||
if (item_slot_searches_new.contains(search.slot)) {
|
||||
where_criteria_items.append(
|
||||
fmt::format(" AND items.slots & {0} = {0}", item_slot_searches_new[search.slot]));
|
||||
}
|
||||
}
|
||||
|
||||
if (search.type != std::numeric_limits<uint32>::max()) {
|
||||
for (auto const &[type, condition]: item_search_types_new) {
|
||||
if (type == search.type) {
|
||||
where_criteria_items.append(condition);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (search.race != std::numeric_limits<uint32>::max()) {
|
||||
where_criteria_items.append(
|
||||
fmt::format(" AND items.races & {0} = {0}", GetPlayerRaceBit(GetRaceIDFromPlayerRaceValue(search.race))));
|
||||
}
|
||||
|
||||
if (search._class != std::numeric_limits<uint32>::max()) {
|
||||
where_criteria_items.append(fmt::format(" AND items.classes & {0} = {0}", GetPlayerClassBit(search._class)));
|
||||
}
|
||||
|
||||
if (search.item_stat != std::numeric_limits<uint32>::max()) {
|
||||
if (item_stat_searches_new.contains(search.item_stat)) {
|
||||
field_criteria_items = fmt::format("{}", item_stat_searches_new[search.item_stat].query_string);
|
||||
if (item_stat_searches_new[search.item_stat].skill_type) {
|
||||
where_criteria_items.append(
|
||||
fmt::format(" AND items.skillmodtype = {} ", item_stat_searches_new[search.item_stat].skill_type));
|
||||
}
|
||||
else {
|
||||
where_criteria_items.append(
|
||||
fmt::format(" AND {} > 0 ", item_stat_searches_new[search.item_stat].query_string));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (search.augment) {
|
||||
where_criteria_items.append(fmt::format(
|
||||
" AND (items.augslot1type = {0} OR "
|
||||
"items.augslot2type = {0} OR "
|
||||
"items.augslot3type = {0} OR "
|
||||
"items.augslot4type = {0} OR "
|
||||
"items.augslot5type = {0} OR "
|
||||
"items.augslot6type = {0})",
|
||||
search.augment)
|
||||
);
|
||||
}
|
||||
|
||||
if (search.min_level != 1) {
|
||||
where_criteria_items.append(fmt::format(" AND items.reclevel >= {}", search.min_level));
|
||||
}
|
||||
|
||||
if (search.max_level != 100) {
|
||||
where_criteria_items.append(fmt::format(" AND items.reclevel <= {}", search.max_level));
|
||||
}
|
||||
|
||||
std::vector<BazaarSearchResultsFromDB_Struct> all_entries;
|
||||
std::vector<std::string> trader_items_ids{};
|
||||
|
||||
auto const trader_results = TraderRepository::GetBazaarTraderDetails(db, search_criteria_trader);
|
||||
if (trader_results.empty()) {
|
||||
LogTradingDetail("Bazaar - No traders found in bazaar search.");
|
||||
return all_entries;
|
||||
}
|
||||
|
||||
for (auto const &i: trader_results) {
|
||||
trader_items_ids.push_back(std::to_string(i.trader.item_id));
|
||||
}
|
||||
|
||||
auto const item_results = ItemsRepository::GetItemsForBazaarSearch(
|
||||
content_db,
|
||||
trader_items_ids,
|
||||
std::string(search.item_name),
|
||||
field_criteria_items,
|
||||
where_criteria_items,
|
||||
search.max_results
|
||||
);
|
||||
|
||||
if (item_results.empty()) {
|
||||
LogTradingDetail("Bazaar - No items found in bazaar search.");
|
||||
return all_entries;
|
||||
}
|
||||
|
||||
all_entries.reserve(trader_results.size());
|
||||
|
||||
for (auto const& t:trader_results) {
|
||||
if (!item_results.contains(t.trader.item_id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BazaarSearchResultsFromDB_Struct r{};
|
||||
r.count = 1;
|
||||
r.trader_id = t.trader.char_id;
|
||||
r.serial_number = t.trader.item_sn;
|
||||
r.cost = t.trader.item_cost;
|
||||
r.slot_id = t.trader.slot_id;
|
||||
r.charges = t.trader.item_charges;
|
||||
r.stackable = item_results.at(t.trader.item_id).stackable;
|
||||
r.icon_id = item_results.at(t.trader.item_id).icon;
|
||||
r.trader_zone_id = t.trader.char_zone_id;
|
||||
r.trader_zone_instance_id = t.trader.char_zone_instance_id;
|
||||
r.trader_entity_id = t.trader.char_entity_id;
|
||||
r.serial_number_RoF = fmt::format("{:016}\0", t.trader.item_sn);
|
||||
r.item_name = fmt::format("{:.63}\0", item_results.at(t.trader.item_id).name);
|
||||
r.trader_name = fmt::format("{:.63}\0", t.trader_name);
|
||||
r.item_stat = item_results.at(t.trader.item_id).stats;
|
||||
|
||||
if (RuleB(Bazaar, UseAlternateBazaarSearch)) {
|
||||
if (convert ||
|
||||
char_zone_id != Zones::BAZAAR ||
|
||||
(char_zone_id == Zones::BAZAAR && r.trader_zone_instance_id != char_zone_instance_id)
|
||||
) {
|
||||
r.trader_id = TraderRepository::TRADER_CONVERT_ID + r.trader_zone_instance_id;
|
||||
}
|
||||
}
|
||||
|
||||
all_entries.push_back(r);
|
||||
}
|
||||
|
||||
if (all_entries.size() > search.max_results) {
|
||||
all_entries.resize(search.max_results);
|
||||
}
|
||||
|
||||
LogTrading("Returning [{}] items from search results", all_entries.size());
|
||||
|
||||
return all_entries;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/item_instance.h"
|
||||
#include "common/shareddb.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
class Bazaar {
|
||||
public:
|
||||
static std::vector<BazaarSearchResultsFromDB_Struct>
|
||||
GetSearchResults(Database &content_db, Database &db, BazaarSearchCriteria_Struct search, unsigned int char_zone_id, int char_zone_instance_id);
|
||||
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "bodytypes.h"
|
||||
|
||||
std::string BodyType::GetName(uint8 body_type_id)
|
||||
{
|
||||
return IsValid(body_type_id) ? body_type_names[body_type_id] : "UNKNOWN BODY TYPE";
|
||||
}
|
||||
|
||||
bool BodyType::IsValid(uint8 body_type_id)
|
||||
{
|
||||
return body_type_names.find(body_type_id) != body_type_names.end();
|
||||
}
|
||||
+55
-101
@@ -1,111 +1,65 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2002 EQEMu Development Team (http://eqemu.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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef BODYTYPES_H
|
||||
#define BODYTYPES_H
|
||||
|
||||
#include "common/types.h"
|
||||
typedef enum {
|
||||
BT_Humanoid = 1,
|
||||
BT_Lycanthrope = 2,
|
||||
BT_Undead = 3,
|
||||
BT_Giant = 4,
|
||||
BT_Construct = 5,
|
||||
BT_Extraplanar = 6,
|
||||
BT_Magical = 7, //this name might be a bit off,
|
||||
BT_SummonedUndead = 8,
|
||||
BT_RaidGiant = 9,
|
||||
// ...
|
||||
BT_NoTarget = 11, //no name, can't target this bodytype
|
||||
BT_Vampire = 12,
|
||||
BT_Atenha_Ra = 13,
|
||||
BT_Greater_Akheva = 14,
|
||||
BT_Khati_Sha = 15,
|
||||
BT_Seru = 16, //not confirmed....
|
||||
BT_Draz_Nurakk = 18,
|
||||
BT_Zek = 19,
|
||||
BT_Luggald = 20,
|
||||
BT_Animal = 21,
|
||||
BT_Insect = 22,
|
||||
BT_Monster = 23,
|
||||
BT_Summoned = 24, //Elemental?
|
||||
BT_Plant = 25,
|
||||
BT_Dragon = 26,
|
||||
BT_Summoned2 = 27,
|
||||
BT_Summoned3 = 28,
|
||||
//29
|
||||
BT_VeliousDragon = 30, //might not be a tight set
|
||||
// ...
|
||||
BT_Dragon3 = 32,
|
||||
BT_Boxes = 33,
|
||||
BT_Muramite = 34, //tribal dudes
|
||||
// ...
|
||||
BT_NoTarget2 = 60,
|
||||
// ...
|
||||
BT_SwarmPet = 63, //is this valid, or made up?
|
||||
// ...
|
||||
BT_InvisMan = 66, //no name, seen on 'InvisMan', can be /targeted
|
||||
BT_Special = 67
|
||||
} bodyType;
|
||||
/* bodytypes above 64 make the mob not show up */
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
// body types above 64 make the mob invisible
|
||||
namespace BodyType {
|
||||
constexpr uint8 Humanoid = 1;
|
||||
constexpr uint8 Lycanthrope = 2;
|
||||
constexpr uint8 Undead = 3;
|
||||
constexpr uint8 Giant = 4;
|
||||
constexpr uint8 Construct = 5;
|
||||
constexpr uint8 Extraplanar = 6;
|
||||
constexpr uint8 Magical = 7; // this name might be a bit off,
|
||||
constexpr uint8 SummonedUndead = 8;
|
||||
constexpr uint8 RaidGiant = 9; // Velious era Raid Giant
|
||||
constexpr uint8 RaidColdain = 10; // Velious era Raid Coldain
|
||||
constexpr uint8 NoTarget = 11; // no name, can't target this bodytype
|
||||
constexpr uint8 Vampire = 12;
|
||||
constexpr uint8 AtenHaRa = 13;
|
||||
constexpr uint8 GreaterAkheva = 14;
|
||||
constexpr uint8 KhatiSha = 15;
|
||||
constexpr uint8 Seru = 16;
|
||||
constexpr uint8 GriegVeneficus = 17;
|
||||
constexpr uint8 DrazNurakk = 18;
|
||||
constexpr uint8 Zek = 19; //"creatures from the Plane of War."
|
||||
constexpr uint8 Luggald = 20;
|
||||
constexpr uint8 Animal = 21;
|
||||
constexpr uint8 Insect = 22;
|
||||
constexpr uint8 Monster = 23;
|
||||
constexpr uint8 Summoned = 24; // Elemental?
|
||||
constexpr uint8 Plant = 25;
|
||||
constexpr uint8 Dragon = 26;
|
||||
constexpr uint8 Summoned2 = 27;
|
||||
constexpr uint8 Summoned3 = 28;
|
||||
constexpr uint8 Dragon2 = 29; // database data indicates this is a dragon type (Kunark and DoN?)
|
||||
constexpr uint8 VeliousDragon = 30; // might not be a tight set
|
||||
constexpr uint8 Familiar = 31;
|
||||
constexpr uint8 Dragon3 = 32;
|
||||
constexpr uint8 Boxes = 33;
|
||||
constexpr uint8 Muramite = 34; // tribal dudes
|
||||
constexpr uint8 NoTarget2 = 60;
|
||||
constexpr uint8 SwarmPet = 63; // Looks like weapon proc related temp pets and few misc pets, should not be used for checking swarm pets in general.
|
||||
constexpr uint8 MonsterSummon = 64;
|
||||
constexpr uint8 InvisibleMan = 66; // no name, seen on 'InvisMan', can be /targeted
|
||||
constexpr uint8 Special = 67;
|
||||
|
||||
std::string GetName(uint8 body_type_id);
|
||||
bool IsValid(uint8 body_type_id);
|
||||
}
|
||||
|
||||
static std::map<uint8, std::string> body_type_names = {
|
||||
{ BodyType::Humanoid, "Humanoid" },
|
||||
{ BodyType::Lycanthrope, "Lycanthrope" },
|
||||
{ BodyType::Undead, "Undead" },
|
||||
{ BodyType::Giant, "Giant" },
|
||||
{ BodyType::Construct, "Construct" },
|
||||
{ BodyType::Extraplanar, "Extraplanar" },
|
||||
{ BodyType::Magical, "Magical" },
|
||||
{ BodyType::SummonedUndead, "Summoned Undead" },
|
||||
{ BodyType::RaidGiant, "Raid Giant" },
|
||||
{ BodyType::RaidColdain, "Raid Coldain" },
|
||||
{ BodyType::NoTarget, "Untargetable" },
|
||||
{ BodyType::Vampire, "Vampire" },
|
||||
{ BodyType::AtenHaRa, "Aten Ha Ra" },
|
||||
{ BodyType::GreaterAkheva, "Greater Akheva" },
|
||||
{ BodyType::KhatiSha, "Khati Sha" },
|
||||
{ BodyType::Seru, "Seru" },
|
||||
{ BodyType::GriegVeneficus, "Grieg Veneficus" },
|
||||
{ BodyType::DrazNurakk, "Draz Nurakk" },
|
||||
{ BodyType::Zek, "Zek" },
|
||||
{ BodyType::Luggald, "Luggald" },
|
||||
{ BodyType::Animal, "Animal" },
|
||||
{ BodyType::Insect, "Insect" },
|
||||
{ BodyType::Monster, "Monster" },
|
||||
{ BodyType::Summoned, "Summoned" },
|
||||
{ BodyType::Plant, "Plant" },
|
||||
{ BodyType::Dragon, "Dragon" },
|
||||
{ BodyType::Summoned2, "Summoned 2" },
|
||||
{ BodyType::Summoned3, "Summoned 3" },
|
||||
{ BodyType::Dragon2, "Dragon 2" },
|
||||
{ BodyType::VeliousDragon, "Velious Dragon" },
|
||||
{ BodyType::Familiar, "Familiar" },
|
||||
{ BodyType::Dragon3, "Dragon 3" },
|
||||
{ BodyType::Boxes, "Boxes" },
|
||||
{ BodyType::Muramite, "Muramite" },
|
||||
{ BodyType::NoTarget2, "Untargetable 2" },
|
||||
{ BodyType::SwarmPet, "Swarm Pet" },
|
||||
{ BodyType::MonsterSummon, "Monster Summon" },
|
||||
{ BodyType::InvisibleMan, "Invisible Man" },
|
||||
{ BodyType::Special, "Special" },
|
||||
};
|
||||
#endif
|
||||
|
||||
+503
-535
File diff suppressed because it is too large
Load Diff
+105
-118
@@ -1,127 +1,115 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2016 EQEMu Development Team (http://eqemu.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 3 of the License, or
|
||||
(at your option) any later version.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef CLASSES_CH
|
||||
#define CLASSES_CH
|
||||
|
||||
#include "common/rulesys.h"
|
||||
#include "common/types.h"
|
||||
#include "../common/types.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#define WARRIOR 1
|
||||
#define CLERIC 2
|
||||
#define PALADIN 3
|
||||
#define RANGER 4
|
||||
#define SHADOWKNIGHT 5
|
||||
#define DRUID 6
|
||||
#define MONK 7
|
||||
#define BARD 8
|
||||
#define ROGUE 9
|
||||
#define SHAMAN 10
|
||||
#define NECROMANCER 11
|
||||
#define WIZARD 12
|
||||
#define MAGICIAN 13
|
||||
#define ENCHANTER 14
|
||||
#define BEASTLORD 15
|
||||
#define BERSERKER 16
|
||||
#define WARRIORGM 20
|
||||
#define CLERICGM 21
|
||||
#define PALADINGM 22
|
||||
#define RANGERGM 23
|
||||
#define SHADOWKNIGHTGM 24
|
||||
#define DRUIDGM 25
|
||||
#define MONKGM 26
|
||||
#define BARDGM 27
|
||||
#define ROGUEGM 28
|
||||
#define SHAMANGM 29
|
||||
#define NECROMANCERGM 30
|
||||
#define WIZARDGM 31
|
||||
#define MAGICIANGM 32
|
||||
#define ENCHANTERGM 33
|
||||
#define BEASTLORDGM 34
|
||||
#define BERSERKERGM 35
|
||||
#define BANKER 40
|
||||
#define MERCHANT 41
|
||||
#define DISCORD_MERCHANT 59
|
||||
#define ADVENTURERECRUITER 60
|
||||
#define ADVENTUREMERCHANT 61
|
||||
#define LDON_TREASURE 62 // objects you can use /open on first seen in LDONs
|
||||
#define CORPSE_CLASS 62 // only seen on Danvi's Corpse in Akheva so far..
|
||||
#define TRIBUTE_MASTER 63
|
||||
#define GUILD_TRIBUTE_MASTER 64 // not sure
|
||||
#define NORRATHS_KEEPERS_MERCHANT 67
|
||||
#define DARK_REIGN_MERCHANT 68
|
||||
#define FELLOWSHIP_MASTER 69
|
||||
#define ALT_CURRENCY_MERCHANT 70
|
||||
#define MERCERNARY_MASTER 71
|
||||
|
||||
namespace Class {
|
||||
constexpr uint8 None = 0;
|
||||
constexpr uint8 Warrior = 1;
|
||||
constexpr uint8 Cleric = 2;
|
||||
constexpr uint8 Paladin = 3;
|
||||
constexpr uint8 Ranger = 4;
|
||||
constexpr uint8 ShadowKnight = 5;
|
||||
constexpr uint8 Druid = 6;
|
||||
constexpr uint8 Monk = 7;
|
||||
constexpr uint8 Bard = 8;
|
||||
constexpr uint8 Rogue = 9;
|
||||
constexpr uint8 Shaman = 10;
|
||||
constexpr uint8 Necromancer = 11;
|
||||
constexpr uint8 Wizard = 12;
|
||||
constexpr uint8 Magician = 13;
|
||||
constexpr uint8 Enchanter = 14;
|
||||
constexpr uint8 Beastlord = 15;
|
||||
constexpr uint8 Berserker = 16;
|
||||
constexpr uint8 WarriorGM = 20;
|
||||
constexpr uint8 ClericGM = 21;
|
||||
constexpr uint8 PaladinGM = 22;
|
||||
constexpr uint8 RangerGM = 23;
|
||||
constexpr uint8 ShadowKnightGM = 24;
|
||||
constexpr uint8 DruidGM = 25;
|
||||
constexpr uint8 MonkGM = 26;
|
||||
constexpr uint8 BardGM = 27;
|
||||
constexpr uint8 RogueGM = 28;
|
||||
constexpr uint8 ShamanGM = 29;
|
||||
constexpr uint8 NecromancerGM = 30;
|
||||
constexpr uint8 WizardGM = 31;
|
||||
constexpr uint8 MagicianGM = 32;
|
||||
constexpr uint8 EnchanterGM = 33;
|
||||
constexpr uint8 BeastlordGM = 34;
|
||||
constexpr uint8 BerserkerGM = 35;
|
||||
constexpr uint8 Banker = 40;
|
||||
constexpr uint8 Merchant = 41;
|
||||
constexpr uint8 DiscordMerchant = 59;
|
||||
constexpr uint8 AdventureRecruiter = 60;
|
||||
constexpr uint8 AdventureMerchant = 61;
|
||||
constexpr uint8 LDoNTreasure = 62;
|
||||
constexpr uint8 TributeMaster = 63;
|
||||
constexpr uint8 GuildTributeMaster = 64;
|
||||
constexpr uint8 GuildBanker = 66;
|
||||
constexpr uint8 NorrathsKeepersMerchant = 67;
|
||||
constexpr uint8 DarkReignMerchant = 68;
|
||||
constexpr uint8 FellowshipMaster = 69;
|
||||
constexpr uint8 AlternateCurrencyMerchant = 70;
|
||||
constexpr uint8 MercenaryLiaison = 71;
|
||||
constexpr uint8 RealEstateMerchant = 72;
|
||||
constexpr uint8 LoyaltyMerchant = 73;
|
||||
constexpr uint8 TributeMaster2 = 74;
|
||||
|
||||
constexpr uint8 PLAYER_CLASS_COUNT = 16;
|
||||
constexpr uint16 ALL_CLASSES_BITMASK = 65535;
|
||||
};
|
||||
// player class values
|
||||
#define PLAYER_CLASS_UNKNOWN 0
|
||||
#define PLAYER_CLASS_WARRIOR 1
|
||||
#define PLAYER_CLASS_CLERIC 2
|
||||
#define PLAYER_CLASS_PALADIN 3
|
||||
#define PLAYER_CLASS_RANGER 4
|
||||
#define PLAYER_CLASS_SHADOWKNIGHT 5
|
||||
#define PLAYER_CLASS_DRUID 6
|
||||
#define PLAYER_CLASS_MONK 7
|
||||
#define PLAYER_CLASS_BARD 8
|
||||
#define PLAYER_CLASS_ROGUE 9
|
||||
#define PLAYER_CLASS_SHAMAN 10
|
||||
#define PLAYER_CLASS_NECROMANCER 11
|
||||
#define PLAYER_CLASS_WIZARD 12
|
||||
#define PLAYER_CLASS_MAGICIAN 13
|
||||
#define PLAYER_CLASS_ENCHANTER 14
|
||||
#define PLAYER_CLASS_BEASTLORD 15
|
||||
#define PLAYER_CLASS_BERSERKER 16
|
||||
|
||||
static std::map<uint8, uint16> player_class_bitmasks = {
|
||||
{Class::Warrior, 1},
|
||||
{Class::Cleric, 2},
|
||||
{Class::Paladin, 4},
|
||||
{Class::Ranger, 8},
|
||||
{Class::ShadowKnight, 16},
|
||||
{Class::Druid, 32},
|
||||
{Class::Monk, 64},
|
||||
{Class::Bard, 128},
|
||||
{Class::Rogue, 256},
|
||||
{Class::Shaman, 512},
|
||||
{Class::Necromancer, 1024},
|
||||
{Class::Wizard, 2048},
|
||||
{Class::Magician, 4096},
|
||||
{Class::Enchanter, 8192},
|
||||
{Class::Beastlord, 16384},
|
||||
{Class::Berserker, 32768},
|
||||
};
|
||||
#define PLAYER_CLASS_COUNT 16
|
||||
|
||||
static std::string shadow_knight_class_name = (
|
||||
RuleB(World, UseOldShadowKnightClassExport) ?
|
||||
"Shadowknight" :
|
||||
"Shadow Knight"
|
||||
);
|
||||
|
||||
static std::map<uint8, std::string> class_names = {
|
||||
{Class::Warrior, "Warrior"},
|
||||
{Class::Cleric, "Cleric"},
|
||||
{Class::Paladin, "Paladin"},
|
||||
{Class::Ranger, "Ranger"},
|
||||
{Class::ShadowKnight, shadow_knight_class_name},
|
||||
{Class::Druid, "Druid"},
|
||||
{Class::Monk, "Monk"},
|
||||
{Class::Bard, "Bard"},
|
||||
{Class::Rogue, "Rogue"},
|
||||
{Class::Shaman, "Shaman"},
|
||||
{Class::Necromancer, "Necromancer"},
|
||||
{Class::Wizard, "Wizard"},
|
||||
{Class::Magician, "Magician"},
|
||||
{Class::Enchanter, "Enchanter"},
|
||||
{Class::Beastlord, "Beastlord"},
|
||||
{Class::Berserker, "Berserker"},
|
||||
};
|
||||
// player class bits
|
||||
#define PLAYER_CLASS_UNKNOWN_BIT 0
|
||||
#define PLAYER_CLASS_WARRIOR_BIT 1
|
||||
#define PLAYER_CLASS_CLERIC_BIT 2
|
||||
#define PLAYER_CLASS_PALADIN_BIT 4
|
||||
#define PLAYER_CLASS_RANGER_BIT 8
|
||||
#define PLAYER_CLASS_SHADOWKNIGHT_BIT 16
|
||||
#define PLAYER_CLASS_DRUID_BIT 32
|
||||
#define PLAYER_CLASS_MONK_BIT 64
|
||||
#define PLAYER_CLASS_BARD_BIT 128
|
||||
#define PLAYER_CLASS_ROGUE_BIT 256
|
||||
#define PLAYER_CLASS_SHAMAN_BIT 512
|
||||
#define PLAYER_CLASS_NECROMANCER_BIT 1024
|
||||
#define PLAYER_CLASS_WIZARD_BIT 2048
|
||||
#define PLAYER_CLASS_MAGICIAN_BIT 4096
|
||||
#define PLAYER_CLASS_ENCHANTER_BIT 8192
|
||||
#define PLAYER_CLASS_BEASTLORD_BIT 16384
|
||||
#define PLAYER_CLASS_BERSERKER_BIT 32768
|
||||
|
||||
#define PLAYER_CLASS_ALL_MASK 65535 // was 65536
|
||||
|
||||
|
||||
#define ARMOR_TYPE_UNKNOWN 0
|
||||
@@ -134,28 +122,27 @@ static std::map<uint8, std::string> class_names = {
|
||||
#define ARMOR_TYPE_LAST ARMOR_TYPE_PLATE
|
||||
#define ARMOR_TYPE_COUNT 5
|
||||
|
||||
#define BOT_CLASS_BASE_ID_PREFIX 3000
|
||||
|
||||
|
||||
const char* GetClassIDName(uint8 class_id, uint8 level = 0);
|
||||
const char* GetPlayerClassName(uint32 player_class_value, uint8 level = 0);
|
||||
|
||||
bool IsPlayerClass(uint8 class_id);
|
||||
const std::string GetPlayerClassAbbreviation(uint8 class_id);
|
||||
uint32 GetPlayerClassValue(uint8 class_id);
|
||||
uint32 GetPlayerClassBit(uint8 class_id);
|
||||
|
||||
uint8 GetPlayerClassValue(uint8 class_id);
|
||||
uint16 GetPlayerClassBit(uint8 class_id);
|
||||
uint8 GetClassIDFromPlayerClassValue(uint32 player_class_value);
|
||||
uint8 GetClassIDFromPlayerClassBit(uint32 player_class_bit);
|
||||
|
||||
bool IsFighterClass(uint8 class_id);
|
||||
bool IsSpellFighterClass(uint8 class_id);
|
||||
bool IsNonSpellFighterClass(uint8 class_id);
|
||||
bool IsHybridClass(uint8 class_id);
|
||||
bool IsCasterClass(uint8 class_id);
|
||||
bool IsINTCasterClass(uint8 class_id);
|
||||
bool IsWISCasterClass(uint8 class_id);
|
||||
bool IsHeroicINTCasterClass(uint8 class_id);
|
||||
bool IsHeroicWISCasterClass(uint8 class_id);
|
||||
|
||||
bool IsPlateClass(uint8 class_id);
|
||||
bool IsChainClass(uint8 class_id);
|
||||
bool IsLeatherClass(uint8 class_id);
|
||||
bool IsClothClass(uint8 class_id);
|
||||
uint8 ClassArmorType(uint8 class_id);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,451 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <map>
|
||||
#include <cassert>
|
||||
|
||||
namespace argh
|
||||
{
|
||||
// Terminology:
|
||||
// A command line is composed of 2 types of args:
|
||||
// 1. Positional args, i.e. free standing values
|
||||
// 2. Options: args beginning with '-'. We identify two kinds:
|
||||
// 2.1: Flags: boolean options => (exist ? true : false)
|
||||
// 2.2: Parameters: a name followed by a non-option value
|
||||
|
||||
#if !defined(__GNUC__) || (__GNUC__ >= 5)
|
||||
using string_stream = std::istringstream;
|
||||
#else
|
||||
// Until GCC 5, istringstream did not have a move constructor.
|
||||
// stringstream_proxy is used instead, as a workaround.
|
||||
class stringstream_proxy
|
||||
{
|
||||
public:
|
||||
stringstream_proxy() = default;
|
||||
|
||||
// Construct with a value.
|
||||
stringstream_proxy(std::string const& value) :
|
||||
stream_(value)
|
||||
{}
|
||||
|
||||
// Copy constructor.
|
||||
stringstream_proxy(const stringstream_proxy& other) :
|
||||
stream_(other.stream_.str())
|
||||
{
|
||||
stream_.setstate(other.stream_.rdstate());
|
||||
}
|
||||
|
||||
void setstate(std::ios_base::iostate state) { stream_.setstate(state); }
|
||||
|
||||
// Stream out the value of the parameter.
|
||||
// If the conversion was not possible, the stream will enter the fail state,
|
||||
// and operator bool will return false.
|
||||
template<typename T>
|
||||
stringstream_proxy& operator >> (T& thing)
|
||||
{
|
||||
stream_ >> thing;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
// Get the string value.
|
||||
std::string str() const { return stream_.str(); }
|
||||
|
||||
std::stringbuf* rdbuf() const { return stream_.rdbuf(); }
|
||||
|
||||
// Check the state of the stream.
|
||||
// False when the most recent stream operation failed
|
||||
operator bool() const { return !!stream_; }
|
||||
|
||||
~stringstream_proxy() = default;
|
||||
private:
|
||||
std::istringstream stream_;
|
||||
};
|
||||
using string_stream = stringstream_proxy;
|
||||
#endif
|
||||
|
||||
class parser
|
||||
{
|
||||
public:
|
||||
enum Mode { PREFER_FLAG_FOR_UNREG_OPTION = 1 << 0,
|
||||
PREFER_PARAM_FOR_UNREG_OPTION = 1 << 1,
|
||||
NO_SPLIT_ON_EQUALSIGN = 1 << 2,
|
||||
SINGLE_DASH_IS_MULTIFLAG = 1 << 3,
|
||||
};
|
||||
|
||||
parser() = default;
|
||||
|
||||
parser(std::initializer_list<char const* const> pre_reg_names)
|
||||
{ add_params(pre_reg_names); }
|
||||
|
||||
parser(const char* const argv[], int mode = PREFER_FLAG_FOR_UNREG_OPTION)
|
||||
{ parse(argv, mode); }
|
||||
|
||||
parser(int argc, const char* const argv[], int mode = PREFER_FLAG_FOR_UNREG_OPTION)
|
||||
{ parse(argc, argv, mode); }
|
||||
|
||||
void add_param(std::string const& name);
|
||||
void add_params(std::initializer_list<char const* const> init_list);
|
||||
|
||||
void parse(const char* const argv[], int mode = PREFER_FLAG_FOR_UNREG_OPTION);
|
||||
void parse(int argc, const char* const argv[], int mode = PREFER_FLAG_FOR_UNREG_OPTION);
|
||||
|
||||
std::multiset<std::string> const& flags() const { return flags_; }
|
||||
std::map<std::string, std::string> const& params() const { return params_; }
|
||||
std::vector<std::string> const& pos_args() const { return pos_args_; }
|
||||
|
||||
// begin() and end() for using range-for over positional args.
|
||||
std::vector<std::string>::const_iterator begin() const { return pos_args_.cbegin(); }
|
||||
std::vector<std::string>::const_iterator end() const { return pos_args_.cend(); }
|
||||
size_t size() const { return pos_args_.size(); }
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Accessors
|
||||
|
||||
// flag (boolean) accessors: return true if the flag appeared, otherwise false.
|
||||
bool operator[](std::string const& name) const;
|
||||
|
||||
// multiple flag (boolean) accessors: return true if at least one of the flag appeared, otherwise false.
|
||||
bool operator[](std::initializer_list<char const* const> init_list) const;
|
||||
|
||||
// returns positional arg string by order. Like argv[] but without the options
|
||||
std::string const& operator[](size_t ind) const;
|
||||
|
||||
// returns a std::istream that can be used to convert a positional arg to a typed value.
|
||||
string_stream operator()(size_t ind) const;
|
||||
|
||||
// same as above, but with a default value in case the arg is missing (index out of range).
|
||||
template<typename T>
|
||||
string_stream operator()(size_t ind, T&& def_val) const;
|
||||
|
||||
// parameter accessors, give a name get an std::istream that can be used to convert to a typed value.
|
||||
// call .str() on result to get as string
|
||||
string_stream operator()(std::string const& name) const;
|
||||
|
||||
// accessor for a parameter with multiple names, give a list of names, get an std::istream that can be used to convert to a typed value.
|
||||
// call .str() on result to get as string
|
||||
// returns the first value in the list to be found.
|
||||
string_stream operator()(std::initializer_list<char const* const> init_list) const;
|
||||
|
||||
// same as above, but with a default value in case the param was missing.
|
||||
// Non-string def_val types must have an operator<<() (output stream operator)
|
||||
// If T only has an input stream operator, pass the string version of the type as in "3" instead of 3.
|
||||
template<typename T>
|
||||
string_stream operator()(std::string const& name, T&& def_val) const;
|
||||
|
||||
// same as above but for a list of names. returns the first value to be found.
|
||||
template<typename T>
|
||||
string_stream operator()(std::initializer_list<char const* const> init_list, T&& def_val) const;
|
||||
|
||||
private:
|
||||
string_stream bad_stream() const;
|
||||
std::string trim_leading_dashes(std::string const& name) const;
|
||||
bool is_number(std::string const& arg) const;
|
||||
bool is_option(std::string const& arg) const;
|
||||
bool got_flag(std::string const& name) const;
|
||||
bool is_param(std::string const& name) const;
|
||||
|
||||
private:
|
||||
std::vector<std::string> args_;
|
||||
std::map<std::string, std::string> params_;
|
||||
std::vector<std::string> pos_args_;
|
||||
std::multiset<std::string> flags_;
|
||||
std::set<std::string> registeredParams_;
|
||||
std::string empty_;
|
||||
};
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline void parser::parse(const char * const argv[], int mode)
|
||||
{
|
||||
int argc = 0;
|
||||
for (auto argvp = argv; *argvp; ++argc, ++argvp);
|
||||
parse(argc, argv, mode);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline void parser::parse(int argc, const char* const argv[], int mode /*= PREFER_FLAG_FOR_UNREG_OPTION*/)
|
||||
{
|
||||
// convert to strings
|
||||
args_.resize(argc);
|
||||
std::transform(argv, argv + argc, args_.begin(), [](const char* const arg) { return arg; });
|
||||
|
||||
// parse line
|
||||
for (auto i = 0u; i < args_.size(); ++i)
|
||||
{
|
||||
if (!is_option(args_[i]))
|
||||
{
|
||||
pos_args_.emplace_back(args_[i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto name = trim_leading_dashes(args_[i]);
|
||||
|
||||
if (!(mode & NO_SPLIT_ON_EQUALSIGN))
|
||||
{
|
||||
auto equalPos = name.find('=');
|
||||
if (equalPos != std::string::npos)
|
||||
{
|
||||
params_.insert({ name.substr(0, equalPos), name.substr(equalPos + 1) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// if the option is unregistered and should be a multi-flag
|
||||
if (1 == (args_[i].size() - name.size()) && // single dash
|
||||
argh::parser::SINGLE_DASH_IS_MULTIFLAG & mode && // multi-flag mode
|
||||
!is_param(name)) // unregistered
|
||||
{
|
||||
std::string keep_param;
|
||||
|
||||
if (!name.empty() && is_param(std::string(1ul, name.back()))) // last char is param
|
||||
{
|
||||
keep_param += name.back();
|
||||
name.resize(name.size() - 1);
|
||||
}
|
||||
|
||||
for (auto const& c : name)
|
||||
{
|
||||
flags_.emplace(std::string{ c });
|
||||
}
|
||||
|
||||
if (!keep_param.empty())
|
||||
{
|
||||
name = keep_param;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue; // do not consider other options for this arg
|
||||
}
|
||||
}
|
||||
|
||||
// any potential option will get as its value the next arg, unless that arg is an option too
|
||||
// in that case it will be determined a flag.
|
||||
if (i == args_.size() - 1 || is_option(args_[i + 1]))
|
||||
{
|
||||
flags_.emplace(name);
|
||||
continue;
|
||||
}
|
||||
|
||||
// if 'name' is a pre-registered option, then the next arg cannot be a free parameter to it is skipped
|
||||
// otherwise we have 2 modes:
|
||||
// PREFER_FLAG_FOR_UNREG_OPTION: a non-registered 'name' is determined a flag.
|
||||
// The following value (the next arg) will be a free parameter.
|
||||
//
|
||||
// PREFER_PARAM_FOR_UNREG_OPTION: a non-registered 'name' is determined a parameter, the next arg
|
||||
// will be the value of that option.
|
||||
|
||||
assert(!(mode & argh::parser::PREFER_FLAG_FOR_UNREG_OPTION)
|
||||
|| !(mode & argh::parser::PREFER_PARAM_FOR_UNREG_OPTION));
|
||||
|
||||
bool preferParam = mode & argh::parser::PREFER_PARAM_FOR_UNREG_OPTION;
|
||||
|
||||
if (is_param(name) || preferParam)
|
||||
{
|
||||
params_.insert({ name, args_[i + 1] });
|
||||
++i; // skip next value, it is not a free parameter
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
flags_.emplace(name);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline string_stream parser::bad_stream() const
|
||||
{
|
||||
string_stream bad;
|
||||
bad.setstate(std::ios_base::failbit);
|
||||
return bad;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool parser::is_number(std::string const& arg) const
|
||||
{
|
||||
// inefficient but simple way to determine if a string is a number (which can start with a '-')
|
||||
std::istringstream istr(arg);
|
||||
double number;
|
||||
istr >> number;
|
||||
return !(istr.fail() || istr.bad());
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool parser::is_option(std::string const& arg) const
|
||||
{
|
||||
assert(0 != arg.size());
|
||||
if (is_number(arg))
|
||||
return false;
|
||||
return '-' == arg[0];
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline std::string parser::trim_leading_dashes(std::string const& name) const
|
||||
{
|
||||
auto pos = name.find_first_not_of('-');
|
||||
return std::string::npos != pos ? name.substr(pos) : name;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool argh::parser::got_flag(std::string const& name) const
|
||||
{
|
||||
return flags_.end() != flags_.find(trim_leading_dashes(name));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool argh::parser::is_param(std::string const& name) const
|
||||
{
|
||||
return registeredParams_.count(name);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool parser::operator[](std::string const& name) const
|
||||
{
|
||||
return got_flag(name);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline bool parser::operator[](std::initializer_list<char const* const> init_list) const
|
||||
{
|
||||
return std::any_of(init_list.begin(), init_list.end(), [&](char const* const name) { return got_flag(name); });
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline std::string const& parser::operator[](size_t ind) const
|
||||
{
|
||||
if (ind < pos_args_.size())
|
||||
return pos_args_[ind];
|
||||
return empty_;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline string_stream parser::operator()(std::string const& name) const
|
||||
{
|
||||
auto optIt = params_.find(trim_leading_dashes(name));
|
||||
if (params_.end() != optIt)
|
||||
return string_stream(optIt->second);
|
||||
return bad_stream();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline string_stream parser::operator()(std::initializer_list<char const* const> init_list) const
|
||||
{
|
||||
for (auto& name : init_list)
|
||||
{
|
||||
auto optIt = params_.find(trim_leading_dashes(name));
|
||||
if (params_.end() != optIt)
|
||||
return string_stream(optIt->second);
|
||||
}
|
||||
return bad_stream();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
template<typename T>
|
||||
string_stream parser::operator()(std::string const& name, T&& def_val) const
|
||||
{
|
||||
auto optIt = params_.find(trim_leading_dashes(name));
|
||||
if (params_.end() != optIt)
|
||||
return string_stream(optIt->second);
|
||||
|
||||
std::ostringstream ostr;
|
||||
ostr.precision(std::numeric_limits<long double>::max_digits10);
|
||||
ostr << def_val;
|
||||
return string_stream(ostr.str()); // use default
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// same as above but for a list of names. returns the first value to be found.
|
||||
template<typename T>
|
||||
string_stream parser::operator()(std::initializer_list<char const* const> init_list, T&& def_val) const
|
||||
{
|
||||
for (auto& name : init_list)
|
||||
{
|
||||
auto optIt = params_.find(trim_leading_dashes(name));
|
||||
if (params_.end() != optIt)
|
||||
return string_stream(optIt->second);
|
||||
}
|
||||
std::ostringstream ostr;
|
||||
ostr.precision(std::numeric_limits<long double>::max_digits10);
|
||||
ostr << def_val;
|
||||
return string_stream(ostr.str()); // use default
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline string_stream parser::operator()(size_t ind) const
|
||||
{
|
||||
if (pos_args_.size() <= ind)
|
||||
return bad_stream();
|
||||
|
||||
return string_stream(pos_args_[ind]);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
template<typename T>
|
||||
string_stream parser::operator()(size_t ind, T&& def_val) const
|
||||
{
|
||||
if (pos_args_.size() <= ind)
|
||||
{
|
||||
std::ostringstream ostr;
|
||||
ostr.precision(std::numeric_limits<long double>::max_digits10);
|
||||
ostr << def_val;
|
||||
return string_stream(ostr.str());
|
||||
}
|
||||
|
||||
return string_stream(pos_args_[ind]);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline void parser::add_param(std::string const& name)
|
||||
{
|
||||
registeredParams_.insert(trim_leading_dashes(name));
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
inline void parser::add_params(std::initializer_list<char const* const> init_list)
|
||||
{
|
||||
for (auto& name : init_list)
|
||||
registeredParams_.insert(trim_leading_dashes(name));
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "common/cli/eqemu_command_handler.h"
|
||||
#include "common/cli/terminal_color.hpp"
|
||||
#include "common/platform.h"
|
||||
|
||||
#include "fmt/format.h"
|
||||
|
||||
namespace EQEmuCommand {
|
||||
|
||||
using CommandFunction = void(*)(int argc, char** argv, argh::parser& cmd, std::string& description);
|
||||
|
||||
std::map<std::string, CommandFunction> function_map;
|
||||
|
||||
/**
|
||||
* @param cmd
|
||||
*/
|
||||
void DisplayDebug(argh::parser &cmd)
|
||||
{
|
||||
if (cmd[{"-d", "--debug"}]) {
|
||||
std::cout << "Positional args:\n";
|
||||
for (auto &pos_arg: cmd.pos_args())
|
||||
std::cout << '\t' << pos_arg << std::endl;
|
||||
|
||||
std::cout << "\nFlags:\n";
|
||||
for (auto &flag: cmd.flags())
|
||||
std::cout << '\t' << flag << std::endl;
|
||||
|
||||
std::cout << "\nParameters:\n";
|
||||
for (auto ¶m: cmd.params())
|
||||
std::cout << '\t' << param.first << " : " << param.second << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param arguments
|
||||
* @param options
|
||||
* @param cmd
|
||||
* @param argc
|
||||
* @param argv
|
||||
*/
|
||||
void ValidateCmdInput(
|
||||
std::vector<std::string> &arguments,
|
||||
std::vector<std::string> &options,
|
||||
argh::parser &cmd,
|
||||
int argc,
|
||||
char **argv
|
||||
)
|
||||
{
|
||||
bool arguments_filled = true;
|
||||
|
||||
int index = 2;
|
||||
for (auto &arg: arguments) {
|
||||
if (cmd(arg).str().empty() && cmd(index).str().empty()) {
|
||||
arguments_filled = false;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
if (!arguments_filled || (argc == 2 && !cmd[{"-h", "--help"}]) || (argc == 3 && cmd[{"-h", "--help"}])) {
|
||||
std::string arguments_string;
|
||||
for (auto &arg: arguments) {
|
||||
arguments_string += " " + arg;
|
||||
}
|
||||
|
||||
std::string options_string;
|
||||
for (auto &opt: options) {
|
||||
options_string += " " + opt + "\n";
|
||||
}
|
||||
|
||||
std::stringstream command_string;
|
||||
|
||||
command_string <<
|
||||
termcolor::colorize <<
|
||||
termcolor::yellow <<
|
||||
"\nCommand" <<
|
||||
termcolor::reset << "\n\n" <<
|
||||
termcolor::green << argv[1] << arguments_string << termcolor::reset << "\n" <<
|
||||
termcolor::yellow << (!options_string.empty() ? "\nOptions\n\n" : "") <<
|
||||
termcolor::reset << termcolor::cyan << options_string << termcolor::reset;
|
||||
|
||||
std::cout << command_string.str() << std::endl;
|
||||
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param in_function_map
|
||||
* @param cmd
|
||||
* @param argc
|
||||
* @param argv
|
||||
*/
|
||||
void HandleMenu(
|
||||
std::map<std::string, void (*)(
|
||||
int argc,
|
||||
char **argv,
|
||||
argh::parser &cmd,
|
||||
std::string &description
|
||||
)> &in_function_map,
|
||||
argh::parser &cmd,
|
||||
int argc,
|
||||
char **argv
|
||||
)
|
||||
{
|
||||
std::string description;
|
||||
if (cmd[{"-h", "--help"}]) {
|
||||
std::cout << std::endl;
|
||||
std::cout <<
|
||||
"> " <<
|
||||
termcolor::yellow <<
|
||||
"EQEmulator [" + GetPlatformName() + "] CLI Menu" <<
|
||||
termcolor::reset
|
||||
<< std::endl
|
||||
<< std::endl;
|
||||
|
||||
// Get max command length for padding length
|
||||
int max_command_length = 0;
|
||||
|
||||
for (auto &it: in_function_map) {
|
||||
std::stringstream command;
|
||||
command << termcolor::colorize << termcolor::yellow << it.first << termcolor::reset;
|
||||
if (command.str().length() > max_command_length) {
|
||||
max_command_length = command.str().length() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Display command menu
|
||||
std::string command_section;
|
||||
for (auto &it: in_function_map) {
|
||||
description.clear();
|
||||
|
||||
(it.second)(argc, argv, cmd, description);
|
||||
|
||||
// Print section header
|
||||
std::string command_prefix = it.first.substr(0, it.first.find(":"));
|
||||
|
||||
if (command_prefix.find("test") != std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (command_section != command_prefix) {
|
||||
command_section = command_prefix;
|
||||
std::cout << termcolor::reset << command_prefix << std::endl;
|
||||
}
|
||||
|
||||
// Print commands
|
||||
std::stringstream command;
|
||||
command << termcolor::colorize << termcolor::yellow << it.first << termcolor::reset;
|
||||
printf(" %-*s %s\n", max_command_length, command.str().c_str(), description.c_str());
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
std::exit(0);
|
||||
}
|
||||
|
||||
bool ran_command = false;
|
||||
|
||||
for (auto &it: in_function_map) {
|
||||
if (it.first == argv[1]) {
|
||||
(it.second)(argc, argv, cmd, description);
|
||||
ran_command = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (ran_command) {
|
||||
std::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/cli/argh.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace EQEmuCommand {
|
||||
|
||||
extern std::map<std::string, void (*)(
|
||||
int argc,
|
||||
char **argv,
|
||||
argh::parser &cmd,
|
||||
std::string &description
|
||||
)> function_map;
|
||||
|
||||
/**
|
||||
* @param arguments
|
||||
* @param options
|
||||
* @param cmd
|
||||
* @param argc
|
||||
* @param argv
|
||||
*/
|
||||
void ValidateCmdInput(
|
||||
std::vector<std::string> &arguments,
|
||||
std::vector<std::string> &options,
|
||||
argh::parser &cmd,
|
||||
int argc,
|
||||
char **argv
|
||||
);
|
||||
|
||||
/**
|
||||
* @param cmd
|
||||
*/
|
||||
void DisplayDebug(argh::parser &cmd);
|
||||
|
||||
/**
|
||||
* @param in_function_map
|
||||
* @param cmd
|
||||
* @param argc
|
||||
* @param argv
|
||||
*/
|
||||
void HandleMenu(
|
||||
std::map<std::string, void (*)(
|
||||
int argc,
|
||||
char **argv,
|
||||
argh::parser &cmd,
|
||||
std::string &description
|
||||
)> &in_function_map,
|
||||
argh::parser &cmd,
|
||||
int argc,
|
||||
char **argv
|
||||
);
|
||||
};
|
||||
@@ -1,574 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
//!
|
||||
//! termcolor
|
||||
//! ~~~~~~~~~
|
||||
//!
|
||||
//! termcolor is a header-only c++ library for printing colored messages
|
||||
//! to the terminal. Written just for fun with a help of the Force.
|
||||
//!
|
||||
//! :copyright: (c) 2013 by Ihor Kalnytskyi
|
||||
//! :license: BSD, see LICENSE for details
|
||||
//!
|
||||
|
||||
#ifndef TERMCOLOR_HPP_
|
||||
#define TERMCOLOR_HPP_
|
||||
|
||||
// the following snippet of code detects the current OS and
|
||||
// defines the appropriate macro that is used to wrap some
|
||||
// platform specific things
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
# define TERMCOLOR_OS_WINDOWS
|
||||
#elif defined(__APPLE__)
|
||||
# define TERMCOLOR_OS_MACOS
|
||||
#elif defined(__unix__) || defined(__unix)
|
||||
# define TERMCOLOR_OS_LINUX
|
||||
#else
|
||||
# error unsupported platform
|
||||
#endif
|
||||
|
||||
|
||||
// This headers provides the `isatty()`/`fileno()` functions,
|
||||
// which are used for testing whether a standart stream refers
|
||||
// to the terminal. As for Windows, we also need WinApi funcs
|
||||
// for changing colors attributes of the terminal.
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
# include <unistd.h>
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
# include <io.h>
|
||||
# include "common/platform/win/include_windows.h"
|
||||
#endif
|
||||
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdio>
|
||||
|
||||
|
||||
|
||||
namespace termcolor
|
||||
{
|
||||
// Forward declaration of the `_internal` namespace.
|
||||
// All comments are below.
|
||||
namespace _internal
|
||||
{
|
||||
// An index to be used to access a private storage of I/O streams. See
|
||||
// colorize / nocolorize I/O manipulators for details.
|
||||
static int colorize_index = std::ios_base::xalloc();
|
||||
|
||||
inline FILE* get_standard_stream(const std::ostream& stream);
|
||||
inline bool is_colorized(std::ostream& stream);
|
||||
inline bool is_atty(const std::ostream& stream);
|
||||
|
||||
#if defined(TERMCOLOR_OS_WINDOWS)
|
||||
inline void win_change_attributes(std::ostream& stream, int foreground, int background=-1);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& colorize(std::ostream& stream)
|
||||
{
|
||||
stream.iword(_internal::colorize_index) = 1L;
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& nocolorize(std::ostream& stream)
|
||||
{
|
||||
stream.iword(_internal::colorize_index) = 0L;
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& reset(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;00m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1, -1);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& bold(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;1m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& dark(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;2m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& underline(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;4m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& blink(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;5m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& reverse(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;7m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& concealed(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;8m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& grey(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;30m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
0 // grey (black)
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& red(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;31m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& green(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;32m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_GREEN
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& yellow(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;33m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_GREEN | FOREGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& blue(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;34m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_BLUE
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& magenta(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;35m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_BLUE | FOREGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& cyan(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;36m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_BLUE | FOREGROUND_GREEN
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& white(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;37m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream,
|
||||
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
|
||||
inline
|
||||
std::ostream& on_grey(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;40m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
0 // grey (black)
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_red(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;41m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_green(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;42m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_GREEN
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_yellow(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;43m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_GREEN | BACKGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_blue(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;44m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_BLUE
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_magenta(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;45m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_BLUE | BACKGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_cyan(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;46m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_GREEN | BACKGROUND_BLUE
|
||||
);
|
||||
#endif
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline
|
||||
std::ostream& on_white(std::ostream& stream)
|
||||
{
|
||||
if (_internal::is_colorized(stream))
|
||||
{
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
stream << "\e[1;47m";
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
_internal::win_change_attributes(stream, -1,
|
||||
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED
|
||||
);
|
||||
#endif
|
||||
}
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//! Since C++ hasn't a way to hide something in the header from
|
||||
//! the outer access, I have to introduce this namespace which
|
||||
//! is used for internal purpose and should't be access from
|
||||
//! the user code.
|
||||
namespace _internal
|
||||
{
|
||||
//! Since C++ hasn't a true way to extract stream handler
|
||||
//! from the a given `std::ostream` object, I have to write
|
||||
//! this kind of hack.
|
||||
inline
|
||||
FILE* get_standard_stream(const std::ostream& stream)
|
||||
{
|
||||
if (&stream == &std::cout)
|
||||
return stdout;
|
||||
else if ((&stream == &std::cerr) || (&stream == &std::clog))
|
||||
return stderr;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Say whether a given stream should be colorized or not. It's always
|
||||
// true for ATTY streams and may be true for streams marked with
|
||||
// colorize flag.
|
||||
inline
|
||||
bool is_colorized(std::ostream& stream)
|
||||
{
|
||||
return is_atty(stream) || static_cast<bool>(stream.iword(colorize_index));
|
||||
}
|
||||
|
||||
//! Test whether a given `std::ostream` object refers to
|
||||
//! a terminal.
|
||||
inline
|
||||
bool is_atty(const std::ostream& stream)
|
||||
{
|
||||
FILE* std_stream = get_standard_stream(stream);
|
||||
|
||||
// Unfortunately, fileno() ends with segmentation fault
|
||||
// if invalid file descriptor is passed. So we need to
|
||||
// handle this case gracefully and assume it's not a tty
|
||||
// if standard stream is not detected, and 0 is returned.
|
||||
if (!std_stream)
|
||||
return false;
|
||||
|
||||
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
|
||||
return ::isatty(fileno(std_stream));
|
||||
#elif defined(TERMCOLOR_OS_WINDOWS)
|
||||
return ::_isatty(_fileno(std_stream));
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(TERMCOLOR_OS_WINDOWS)
|
||||
//! Change Windows Terminal colors attribute. If some
|
||||
//! parameter is `-1` then attribute won't changed.
|
||||
inline void win_change_attributes(std::ostream& stream, int foreground, int background)
|
||||
{
|
||||
// yeah, i know.. it's ugly, it's windows.
|
||||
static WORD defaultAttributes = 0;
|
||||
|
||||
// Windows doesn't have ANSI escape sequences and so we use special
|
||||
// API to change Terminal output color. That means we can't
|
||||
// manipulate colors by means of "std::stringstream" and hence
|
||||
// should do nothing in this case.
|
||||
if (!_internal::is_atty(stream))
|
||||
return;
|
||||
|
||||
// get terminal handle
|
||||
HANDLE hTerminal = INVALID_HANDLE_VALUE;
|
||||
if (&stream == &std::cout)
|
||||
hTerminal = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
else if (&stream == &std::cerr)
|
||||
hTerminal = GetStdHandle(STD_ERROR_HANDLE);
|
||||
|
||||
// save default terminal attributes if it unsaved
|
||||
if (!defaultAttributes)
|
||||
{
|
||||
CONSOLE_SCREEN_BUFFER_INFO info;
|
||||
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
|
||||
return;
|
||||
defaultAttributes = info.wAttributes;
|
||||
}
|
||||
|
||||
// restore all default settings
|
||||
if (foreground == -1 && background == -1)
|
||||
{
|
||||
SetConsoleTextAttribute(hTerminal, defaultAttributes);
|
||||
return;
|
||||
}
|
||||
|
||||
// get current settings
|
||||
CONSOLE_SCREEN_BUFFER_INFO info;
|
||||
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
|
||||
return;
|
||||
|
||||
if (foreground != -1)
|
||||
{
|
||||
info.wAttributes &= ~(info.wAttributes & 0x0F);
|
||||
info.wAttributes |= static_cast<WORD>(foreground);
|
||||
}
|
||||
|
||||
if (background != -1)
|
||||
{
|
||||
info.wAttributes &= ~(info.wAttributes & 0xF0);
|
||||
info.wAttributes |= static_cast<WORD>(background);
|
||||
}
|
||||
|
||||
SetConsoleTextAttribute(hTerminal, info.wAttributes);
|
||||
}
|
||||
#endif // TERMCOLOR_OS_WINDOWS
|
||||
|
||||
} // namespace _internal
|
||||
|
||||
} // namespace termcolor
|
||||
|
||||
|
||||
#undef TERMCOLOR_OS_WINDOWS
|
||||
#undef TERMCOLOR_OS_MACOS
|
||||
#undef TERMCOLOR_OS_LINUX
|
||||
|
||||
#endif // TERMCOLOR_HPP_
|
||||
@@ -1,20 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#define PUSH_DISABLE_DEPRECATED_WARNINGS() __pragma(warning(push)) \
|
||||
__pragma(warning(disable:4996))
|
||||
#define POP_DISABLE_DEPRECATED_WARNINGS() __pragma(warning(pop))
|
||||
#elif defined(__GNUC__) || defined(__clang__)
|
||||
#define PUSH_DISABLE_DEPRECATED_WARNINGS() _Pragma("GCC diagnostic push") \
|
||||
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
|
||||
#define POP_DISABLE_DEPRECATED_WARNINGS() _Pragma("GCC diagnostic pop")
|
||||
#else
|
||||
#define PUSH_DISABLE_DEPRECATED_WARNINGS()
|
||||
#define POP_DISABLE_DEPRECATED_WARNINGS()
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
#define UNREACHABLE() __assume(0)
|
||||
#else
|
||||
#define UNREACHABLE() __builtin_unreachable()
|
||||
#endif
|
||||
@@ -1,101 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "compression.h"
|
||||
|
||||
#include "common/types.h"
|
||||
|
||||
#include "zlib.h"
|
||||
#include <cstring>
|
||||
|
||||
namespace EQ
|
||||
{
|
||||
uint32 EstimateDeflateBuffer(uint32 len) {
|
||||
z_stream zstream;
|
||||
memset(&zstream, 0, sizeof(zstream));
|
||||
|
||||
zstream.zalloc = Z_NULL;
|
||||
zstream.zfree = Z_NULL;
|
||||
zstream.opaque = Z_NULL;
|
||||
if (deflateInit(&zstream, Z_FINISH) != Z_OK)
|
||||
return 0;
|
||||
|
||||
return deflateBound(&zstream, len);
|
||||
}
|
||||
|
||||
uint32 DeflateData(const char *buffer, uint32 len, char *out_buffer, uint32 out_len_max) {
|
||||
z_stream zstream;
|
||||
memset(&zstream, 0, sizeof(zstream));
|
||||
int zerror;
|
||||
|
||||
zstream.next_in = const_cast<unsigned char*>(reinterpret_cast<const unsigned char*>(buffer));
|
||||
zstream.avail_in = len;
|
||||
zstream.zalloc = Z_NULL;
|
||||
zstream.zfree = Z_NULL;
|
||||
zstream.opaque = Z_NULL;
|
||||
deflateInit(&zstream, Z_FINISH);
|
||||
|
||||
zstream.next_out = reinterpret_cast<unsigned char*>(out_buffer);
|
||||
zstream.avail_out = out_len_max;
|
||||
zerror = deflate(&zstream, Z_FINISH);
|
||||
|
||||
if (zerror == Z_STREAM_END)
|
||||
{
|
||||
deflateEnd(&zstream);
|
||||
return (uint32)zstream.total_out;
|
||||
}
|
||||
else
|
||||
{
|
||||
zerror = deflateEnd(&zstream);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
uint32 InflateData(const char* buffer, uint32 len, char* out_buffer, uint32 out_len_max) {
|
||||
z_stream zstream;
|
||||
int zerror = 0;
|
||||
int i;
|
||||
|
||||
zstream.next_in = const_cast<unsigned char*>(reinterpret_cast<const unsigned char*>(buffer));
|
||||
zstream.avail_in = len;
|
||||
zstream.next_out = reinterpret_cast<unsigned char*>(out_buffer);;
|
||||
zstream.avail_out = out_len_max;
|
||||
zstream.zalloc = Z_NULL;
|
||||
zstream.zfree = Z_NULL;
|
||||
zstream.opaque = Z_NULL;
|
||||
|
||||
i = inflateInit2(&zstream, 15);
|
||||
if (i != Z_OK) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
zerror = inflate(&zstream, Z_FINISH);
|
||||
if (zerror == Z_STREAM_END) {
|
||||
inflateEnd(&zstream);
|
||||
return zstream.total_out;
|
||||
}
|
||||
else {
|
||||
if (zerror == -4 && zstream.msg == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
zerror = inflateEnd(&zstream);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/types.h"
|
||||
|
||||
namespace EQ
|
||||
{
|
||||
uint32 EstimateDeflateBuffer(uint32 len);
|
||||
uint32 DeflateData(const char *buffer, uint32 len, char *out_buffer, uint32 out_len_max);
|
||||
uint32 InflateData(const char* buffer, uint32 len, char* out_buffer, uint32 out_len_max);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2006 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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; version 2 of the License.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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
|
||||
*/
|
||||
|
||||
#include "condition.h"
|
||||
|
||||
#ifdef _WINDOWS
|
||||
|
||||
Condition::Condition()
|
||||
{
|
||||
m_events[SignalEvent] = CreateEvent (nullptr, // security
|
||||
FALSE, // is auto-reset event?
|
||||
FALSE, // is signaled initially?
|
||||
nullptr); // name
|
||||
m_events[BroadcastEvent] = CreateEvent (nullptr, // security
|
||||
TRUE, // is auto-reset event?
|
||||
FALSE, // is signaled initially?
|
||||
nullptr); // name
|
||||
m_waiters = 0;
|
||||
InitializeCriticalSection(&CSMutex);
|
||||
}
|
||||
|
||||
Condition::~Condition()
|
||||
{
|
||||
DeleteCriticalSection(&CSMutex);
|
||||
CloseHandle(m_events[SignalEvent]);
|
||||
CloseHandle(m_events[BroadcastEvent]);
|
||||
}
|
||||
|
||||
void Condition::Signal()
|
||||
{
|
||||
EnterCriticalSection(&CSMutex);
|
||||
if(m_waiters > 0)
|
||||
SetEvent(m_events[SignalEvent]);
|
||||
LeaveCriticalSection(&CSMutex);
|
||||
}
|
||||
|
||||
void Condition::SignalAll()
|
||||
{
|
||||
EnterCriticalSection(&CSMutex);
|
||||
if(m_waiters > 0)
|
||||
SetEvent(m_events[BroadcastEvent]);
|
||||
LeaveCriticalSection(&CSMutex);
|
||||
}
|
||||
|
||||
void Condition::Wait()
|
||||
{
|
||||
EnterCriticalSection(&CSMutex);
|
||||
|
||||
m_waiters++;
|
||||
|
||||
|
||||
LeaveCriticalSection(&CSMutex);
|
||||
int result = WaitForMultipleObjects (_eventCount, m_events, FALSE, INFINITE);
|
||||
EnterCriticalSection(&CSMutex);
|
||||
|
||||
m_waiters--;
|
||||
|
||||
//see if we are the last person waiting on the condition, and there was a broadcast
|
||||
//if so, we need to reset the broadcast event.
|
||||
if(m_waiters == 0 && result == (WAIT_OBJECT_0+BroadcastEvent))
|
||||
ResetEvent(m_events[BroadcastEvent]);
|
||||
|
||||
LeaveCriticalSection(&CSMutex);
|
||||
}
|
||||
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <sys/time.h>
|
||||
#include <errno.h>
|
||||
|
||||
Condition::Condition()
|
||||
{
|
||||
pthread_cond_init(&cond,nullptr);
|
||||
pthread_mutex_init(&mutex,nullptr);
|
||||
}
|
||||
|
||||
void Condition::Signal()
|
||||
{
|
||||
pthread_mutex_lock(&mutex);
|
||||
pthread_cond_signal(&cond);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
|
||||
void Condition::SignalAll()
|
||||
{
|
||||
pthread_mutex_lock(&mutex);
|
||||
pthread_cond_broadcast(&cond);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
|
||||
void Condition::Wait()
|
||||
{
|
||||
pthread_mutex_lock(&mutex);
|
||||
pthread_cond_wait(&cond,&mutex);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
|
||||
/*
|
||||
I commented this specifically because I think it might be very
|
||||
difficult to write a windows counterpart to it, so I would like
|
||||
to discourage its use until we can confirm that it can be reasonably
|
||||
implemented on windows.
|
||||
|
||||
bool Condition::TimedWait(unsigned long usec)
|
||||
{
|
||||
struct timeval now;
|
||||
struct timespec timeout;
|
||||
int retcode=0;
|
||||
pthread_mutex_lock(&mutex);
|
||||
gettimeofday(&now,nullptr);
|
||||
now.tv_usec+=usec;
|
||||
timeout.tv_sec = now.tv_sec + (now.tv_usec/1000000);
|
||||
timeout.tv_nsec = (now.tv_usec%1000000) *1000;
|
||||
//cout << "now=" << now.tv_sec << "."<<now.tv_usec << endl;
|
||||
//cout << "timeout=" << timeout.tv_sec << "."<<timeout.tv_nsec << endl;
|
||||
retcode=pthread_cond_timedwait(&cond,&mutex,&timeout);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
|
||||
return retcode!=ETIMEDOUT;
|
||||
}
|
||||
*/
|
||||
|
||||
Condition::~Condition()
|
||||
{
|
||||
pthread_mutex_lock(&mutex);
|
||||
pthread_cond_destroy(&cond);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
pthread_mutex_destroy(&mutex);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
Copyright (C) 2001-2006 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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; version 2 of the License.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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
|
||||
*/
|
||||
#ifndef __CONDITION_H
|
||||
#define __CONDITION_H
|
||||
|
||||
#include "global_define.h"
|
||||
#include "mutex.h"
|
||||
#ifndef WIN32
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
|
||||
//Sombody, someday needs to figure out how to implement a condition
|
||||
//system on windows...
|
||||
|
||||
|
||||
class Condition {
|
||||
private:
|
||||
#ifdef WIN32
|
||||
enum {
|
||||
SignalEvent = 0,
|
||||
BroadcastEvent,
|
||||
_eventCount
|
||||
};
|
||||
|
||||
HANDLE m_events[_eventCount];
|
||||
uint32 m_waiters;
|
||||
CRITICAL_SECTION CSMutex;
|
||||
#else
|
||||
pthread_cond_t cond;
|
||||
pthread_mutex_t mutex;
|
||||
#endif
|
||||
public:
|
||||
Condition();
|
||||
void Signal();
|
||||
void SignalAll();
|
||||
void Wait();
|
||||
// bool TimedWait(unsigned long usec);
|
||||
~Condition();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,366 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "world_content_service.h"
|
||||
|
||||
#include "common/database.h"
|
||||
#include "common/eqemu_logsys.h"
|
||||
#include "common/repositories/instance_list_repository.h"
|
||||
#include "common/rulesys.h"
|
||||
#include "common/zone_store.h"
|
||||
|
||||
#include "glm/vec3.hpp"
|
||||
#include <utility>
|
||||
|
||||
WorldContentService::WorldContentService()
|
||||
{
|
||||
SetCurrentExpansion(Expansion::EXPANSION_ALL);
|
||||
}
|
||||
|
||||
int WorldContentService::GetCurrentExpansion() const
|
||||
{
|
||||
return current_expansion;
|
||||
}
|
||||
|
||||
WorldContentService *WorldContentService::SetExpansionContext()
|
||||
{
|
||||
// do a rule manager reload until where we store expansion is changed to somewhere else
|
||||
RuleManager::Instance()->LoadRules(GetDatabase(), "default", true);
|
||||
|
||||
// pull expansion from rules
|
||||
int expansion = RuleI(Expansion, CurrentExpansion);
|
||||
if (expansion >= Expansion::Classic && expansion <= Expansion::MaxId) {
|
||||
WorldContentService::Instance()->SetCurrentExpansion(expansion);
|
||||
}
|
||||
|
||||
LogInfo(
|
||||
"Current expansion is [{}] ({})",
|
||||
GetCurrentExpansion(),
|
||||
GetCurrentExpansionName()
|
||||
);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
std::string WorldContentService::GetCurrentExpansionName()
|
||||
{
|
||||
if (WorldContentService::Instance()->GetCurrentExpansion() == Expansion::EXPANSION_ALL) {
|
||||
return "All Expansions";
|
||||
}
|
||||
|
||||
if (current_expansion >= Expansion::Classic && current_expansion <= Expansion::MaxId) {
|
||||
return Expansion::ExpansionName[WorldContentService::Instance()->GetCurrentExpansion()];
|
||||
}
|
||||
|
||||
return "Unknown Expansion";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param current_expansion
|
||||
*/
|
||||
void WorldContentService::SetCurrentExpansion(int current_expansion)
|
||||
{
|
||||
WorldContentService::current_expansion = current_expansion;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
const std::vector<ContentFlagsRepository::ContentFlags> &WorldContentService::GetContentFlags() const
|
||||
{
|
||||
return content_flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
std::vector<std::string> WorldContentService::GetContentFlagsEnabled()
|
||||
{
|
||||
std::vector<std::string> enabled_flags;
|
||||
|
||||
for (auto &f: GetContentFlags()) {
|
||||
if (f.enabled) {
|
||||
enabled_flags.emplace_back(f.flag_name);
|
||||
}
|
||||
}
|
||||
|
||||
return enabled_flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
std::vector<std::string> WorldContentService::GetContentFlagsDisabled()
|
||||
{
|
||||
std::vector<std::string> disabled_flags;
|
||||
|
||||
for (auto &f: GetContentFlags()) {
|
||||
if (!f.enabled) {
|
||||
disabled_flags.emplace_back(f.flag_name);
|
||||
}
|
||||
}
|
||||
|
||||
return disabled_flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param content_flags
|
||||
*/
|
||||
void WorldContentService::SetContentFlags(const std::vector<ContentFlagsRepository::ContentFlags> &content_flags)
|
||||
{
|
||||
WorldContentService::content_flags = content_flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param content_flag
|
||||
* @return
|
||||
*/
|
||||
bool WorldContentService::IsContentFlagEnabled(const std::string &content_flag)
|
||||
{
|
||||
for (auto &f: GetContentFlags()) {
|
||||
if (f.flag_name == content_flag && f.enabled == 1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param content_flag
|
||||
* @return
|
||||
*/
|
||||
bool WorldContentService::IsContentFlagDisabled(const std::string &content_flag)
|
||||
{
|
||||
for (auto &f: GetContentFlags()) {
|
||||
if (f.flag_name == content_flag && f.enabled == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WorldContentService::DoesPassContentFiltering(const ContentFlags &f)
|
||||
{
|
||||
// if we're not set to (-1 All) then fail when we aren't within minimum expansion
|
||||
if (f.min_expansion > Expansion::EXPANSION_ALL && current_expansion < f.min_expansion && current_expansion != -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if we're not set to (-1 All) then fail when we aren't within max expansion
|
||||
if (f.max_expansion > Expansion::EXPANSION_ALL && current_expansion > f.max_expansion && current_expansion != -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if we don't have any enabled flag in enabled flags, we fail
|
||||
for (const auto &flag: Strings::Split(f.content_flags)) {
|
||||
if (!Strings::Contains(GetContentFlagsEnabled(), flag)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// if we don't have any disabled flag in disabled flags, we fail
|
||||
for (const auto &flag: Strings::Split(f.content_flags_disabled)) {
|
||||
if (!Strings::Contains(GetContentFlagsDisabled(), flag)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void WorldContentService::ReloadContentFlags()
|
||||
{
|
||||
std::vector<ContentFlagsRepository::ContentFlags> set_content_flags;
|
||||
auto flags = ContentFlagsRepository::All(*GetDatabase());
|
||||
|
||||
set_content_flags.reserve(flags.size());
|
||||
for (auto &f: flags) {
|
||||
set_content_flags.push_back(f);
|
||||
|
||||
LogInfo(
|
||||
"Loaded content flag [{}] [{}]",
|
||||
f.flag_name,
|
||||
(f.enabled ? "enabled" : "disabled")
|
||||
);
|
||||
}
|
||||
|
||||
SetContentFlags(set_content_flags);
|
||||
LoadStaticGlobalZoneInstances();
|
||||
ZoneStore::Instance()->LoadZones(*m_content_database);
|
||||
}
|
||||
|
||||
Database *WorldContentService::GetDatabase() const
|
||||
{
|
||||
return m_database;
|
||||
}
|
||||
|
||||
WorldContentService *WorldContentService::SetDatabase(Database *database)
|
||||
{
|
||||
WorldContentService::m_database = database;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
Database *WorldContentService::GetContentDatabase() const
|
||||
{
|
||||
return m_content_database;
|
||||
}
|
||||
|
||||
WorldContentService *WorldContentService::SetContentDatabase(Database *database)
|
||||
{
|
||||
WorldContentService::m_content_database = database;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
void WorldContentService::SetContentFlag(const std::string &content_flag_name, bool enabled)
|
||||
{
|
||||
auto flags = ContentFlagsRepository::GetWhere(
|
||||
*GetDatabase(),
|
||||
fmt::format("flag_name = '{}'", content_flag_name)
|
||||
);
|
||||
|
||||
auto f = ContentFlagsRepository::NewEntity();
|
||||
if (!flags.empty()) {
|
||||
f = flags.front();
|
||||
}
|
||||
|
||||
f.enabled = enabled ? 1 : 0;
|
||||
f.flag_name = content_flag_name;
|
||||
|
||||
if (!flags.empty()) {
|
||||
ContentFlagsRepository::UpdateOne(*GetDatabase(), f);
|
||||
}
|
||||
else {
|
||||
ContentFlagsRepository::InsertOne(*GetDatabase(), f);
|
||||
}
|
||||
|
||||
ReloadContentFlags();
|
||||
}
|
||||
|
||||
void WorldContentService::HandleZoneRoutingMiddleware(ZoneChange_Struct *zc)
|
||||
{
|
||||
auto r = FindZone(zc->zoneID, zc->instanceID);
|
||||
if (r.zone_id == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
zc->instanceID = r.instance.id;
|
||||
}
|
||||
|
||||
// LoadStaticGlobalZoneInstances loads all static global zone instances
|
||||
// these are zones that are never set to expire and are global
|
||||
// these are used commonly in v1/v2/v3 versions of the same zone for expansion routing
|
||||
WorldContentService *WorldContentService::LoadStaticGlobalZoneInstances()
|
||||
{
|
||||
m_zone_static_instances = InstanceListRepository::GetWhere(
|
||||
*GetDatabase(),
|
||||
fmt::format("never_expires = 1 AND is_global = 1")
|
||||
);
|
||||
|
||||
LogInfo("Loaded [{}] zone_instances", m_zone_static_instances.size());
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// FindZone handles content and context aware zone routing (middleware)
|
||||
//
|
||||
// this is a middleware function that is meant to be used in the zone change process
|
||||
// this hooks all core zone changes within the server and routes the player to the correct zone
|
||||
// returning a zone_id of non-zero means the middleware will route the player
|
||||
// returning a zone_id of 0 means the middleware will not route the player
|
||||
// this is useful for handling multiple versions of the same zone
|
||||
//
|
||||
// implementation >
|
||||
// the zoning and process spawning logic already is handled by two keys "zone_id" and "instance_id"
|
||||
// we leverage static, never expires instances to handle this and client still sees it as a normal zone
|
||||
//
|
||||
// content awareness >
|
||||
// simply use the zone_id, server content settings and the middleware will handle the rest
|
||||
// you don't have to think about instances in any data tables (use instance_id 0)
|
||||
// you don't have to keep track of instance ids in scripts (use instance_id 0)
|
||||
// the versions of zones are represented by two zone entries that have potentially different min/max expansion and/or different content flags
|
||||
// we decide to route the client to the correct version of the zone based on the current server side expansion
|
||||
//
|
||||
// example >
|
||||
// we want to route players to the correct version of lavastorm based on the current server side expansion (DoesZonePassContentFiltering)
|
||||
// lavastorm (pre-don) version 0 (classic)
|
||||
// zone table entry for version = 0, min_expansion = 0, max_expansion = 8
|
||||
// instance_list table entry for lavastorm has version = 0, is_global = 1, never_expires = 1
|
||||
// lavastorm (don) version 1
|
||||
// zone table entry for version = 1, min_expansion = 9, max_expansion = 99
|
||||
// instance_list table entry for lavastorm has version = 1, is_global = 1, never_expires = 1
|
||||
WorldContentService::FindZoneResult WorldContentService::FindZone(uint32 zone_id, uint32 instance_id)
|
||||
{
|
||||
for (const auto &z: ZoneStore::Instance()->GetZones()) {
|
||||
for (auto &i: m_zone_static_instances) {
|
||||
if (
|
||||
z.zoneidnumber == zone_id &&
|
||||
DoesZonePassContentFiltering(z) &&
|
||||
i.zone == zone_id &&
|
||||
i.version == z.version) {
|
||||
|
||||
if (instance_id > 0 && i.id != instance_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
LogInfo(
|
||||
"Routed player to public static instance [{}] of zone [{}] ({}) version [{}] long_name [{}] notes [{}]",
|
||||
i.id,
|
||||
z.short_name,
|
||||
z.zoneidnumber,
|
||||
z.version,
|
||||
z.long_name,
|
||||
i.notes
|
||||
);
|
||||
|
||||
return WorldContentService::FindZoneResult{
|
||||
.zone_id = static_cast<uint32>(z.zoneidnumber),
|
||||
.instance = i,
|
||||
.zone = z
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return WorldContentService::FindZoneResult{.zone_id = 0};
|
||||
}
|
||||
|
||||
bool WorldContentService::IsInPublicStaticInstance(uint32 instance_id)
|
||||
{
|
||||
for (auto &i: m_zone_static_instances) {
|
||||
if (i.id == instance_id) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WorldContentService::DoesZonePassContentFiltering(const ZoneRepository::Zone &z)
|
||||
{
|
||||
auto f = ContentFlags{
|
||||
.min_expansion = z.min_expansion,
|
||||
.max_expansion = z.max_expansion,
|
||||
.content_flags = z.content_flags,
|
||||
.content_flags_disabled = z.content_flags_disabled
|
||||
};
|
||||
|
||||
return DoesPassContentFiltering(f);
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common/repositories/content_flags_repository.h"
|
||||
#include "common/repositories/instance_list_repository.h"
|
||||
#include "common/repositories/zone_repository.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Database;
|
||||
|
||||
struct ContentFlags {
|
||||
int16 min_expansion;
|
||||
int16 max_expansion;
|
||||
std::string content_flags;
|
||||
std::string content_flags_disabled;
|
||||
};
|
||||
|
||||
namespace Expansion {
|
||||
static const int EXPANSION_ALL = -1;
|
||||
static const int EXPANSION_FILTER_MAX = 99;
|
||||
|
||||
enum ExpansionNumber {
|
||||
Classic = 0,
|
||||
TheRuinsOfKunark,
|
||||
TheScarsOfVelious,
|
||||
TheShadowsOfLuclin,
|
||||
ThePlanesOfPower,
|
||||
TheLegacyOfYkesha,
|
||||
LostDungeonsOfNorrath,
|
||||
GatesOfDiscord,
|
||||
OmensOfWar,
|
||||
DragonsOfNorrath,
|
||||
DepthsOfDarkhollow,
|
||||
ProphecyOfRo,
|
||||
TheSerpentsSpine,
|
||||
TheBuriedSea,
|
||||
SecretsOfFaydwer,
|
||||
SeedsOfDestruction,
|
||||
Underfoot,
|
||||
HouseOfThule,
|
||||
VeilOfAlaris,
|
||||
RainOfFear,
|
||||
CallOfTheForsaken,
|
||||
TheDarkenedSea,
|
||||
TheBrokenMirror,
|
||||
EmpiresOfKunark,
|
||||
RingOfScale,
|
||||
TheBurningLands,
|
||||
TormentOfVelious,
|
||||
MaxId
|
||||
};
|
||||
|
||||
/**
|
||||
* If you add to this, make sure you update LogCategory
|
||||
*/
|
||||
static const char *ExpansionName[ExpansionNumber::MaxId] = {
|
||||
"Classic",
|
||||
"The Ruins of Kunark",
|
||||
"The Scars of Velious",
|
||||
"The Shadows of Luclin",
|
||||
"The Planes of Power",
|
||||
"The Legacy of Ykesha",
|
||||
"Lost Dungeons of Norrath",
|
||||
"Gates of Discord",
|
||||
"Omens of War",
|
||||
"Dragons of Norrath",
|
||||
"Depths of Darkhollow",
|
||||
"Prophecy of Ro",
|
||||
"The Serpent's Spine",
|
||||
"The Buried Sea",
|
||||
"Secrets of Faydwer",
|
||||
"Seeds of Destruction",
|
||||
"Underfoot",
|
||||
"House of Thule",
|
||||
"Veil of Alaris",
|
||||
"Rain of Fear",
|
||||
"Call of the Forsaken",
|
||||
"The Darkened Sea",
|
||||
"The Broken Mirror",
|
||||
"Empires of Kunark",
|
||||
"Ring of Scale",
|
||||
"The Burning Lands",
|
||||
"Torment of Velious",
|
||||
};
|
||||
}
|
||||
|
||||
class WorldContentService {
|
||||
public:
|
||||
|
||||
WorldContentService();
|
||||
|
||||
std::string GetCurrentExpansionName();
|
||||
int GetCurrentExpansion() const;
|
||||
void SetCurrentExpansion(int current_expansion);
|
||||
|
||||
bool IsClassicEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::Classic || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheRuinsOfKunarkEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheRuinsOfKunark || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheScarsOfVeliousEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheScarsOfVelious || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheShadowsOfLuclinEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheShadowsOfLuclin || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsThePlanesOfPowerEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::ThePlanesOfPower || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheLegacyOfYkeshaEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheLegacyOfYkesha || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsLostDungeonsOfNorrathEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::LostDungeonsOfNorrath || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsGatesOfDiscordEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::GatesOfDiscord || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsOmensOfWarEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::OmensOfWar || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsDragonsOfNorrathEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::DragonsOfNorrath || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsDepthsOfDarkhollowEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::DepthsOfDarkhollow || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsProphecyOfRoEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::ProphecyOfRo || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheSerpentsSpineEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheSerpentsSpine || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheBuriedSeaEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheBuriedSea || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsSecretsOfFaydwerEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::SecretsOfFaydwer || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsSeedsOfDestructionEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::SeedsOfDestruction || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsUnderfootEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::Underfoot || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsHouseOfThuleEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::HouseOfThule || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsVeilOfAlarisEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::VeilOfAlaris || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsRainOfFearEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::RainOfFear || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsCallOfTheForsakenEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::CallOfTheForsaken || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheDarkenedSeaEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheDarkenedSea || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheBrokenMirrorEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheBrokenMirror || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsEmpiresOfKunarkEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::EmpiresOfKunark || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsRingOfScaleEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::RingOfScale || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTheBurningLandsEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TheBurningLands || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
bool IsTormentOfVeliousEnabled() { return GetCurrentExpansion() >= Expansion::ExpansionNumber::TormentOfVelious || GetCurrentExpansion() == Expansion::EXPANSION_ALL; }
|
||||
|
||||
bool IsCurrentExpansionClassic() { return current_expansion == Expansion::ExpansionNumber::Classic; }
|
||||
bool IsCurrentExpansionTheRuinsOfKunark() { return current_expansion == Expansion::ExpansionNumber::TheRuinsOfKunark; }
|
||||
bool IsCurrentExpansionTheScarsOfVelious() { return current_expansion == Expansion::ExpansionNumber::TheScarsOfVelious; }
|
||||
bool IsCurrentExpansionTheShadowsOfLuclin() { return current_expansion == Expansion::ExpansionNumber::TheShadowsOfLuclin; }
|
||||
bool IsCurrentExpansionThePlanesOfPower() { return current_expansion == Expansion::ExpansionNumber::ThePlanesOfPower; }
|
||||
bool IsCurrentExpansionTheLegacyOfYkesha() { return current_expansion == Expansion::ExpansionNumber::TheLegacyOfYkesha; }
|
||||
bool IsCurrentExpansionLostDungeonsOfNorrath() { return current_expansion == Expansion::ExpansionNumber::LostDungeonsOfNorrath; }
|
||||
bool IsCurrentExpansionGatesOfDiscord() { return current_expansion == Expansion::ExpansionNumber::GatesOfDiscord; }
|
||||
bool IsCurrentExpansionOmensOfWar() { return current_expansion == Expansion::ExpansionNumber::OmensOfWar; }
|
||||
bool IsCurrentExpansionDragonsOfNorrath() { return current_expansion == Expansion::ExpansionNumber::DragonsOfNorrath; }
|
||||
bool IsCurrentExpansionDepthsOfDarkhollow() { return current_expansion == Expansion::ExpansionNumber::DepthsOfDarkhollow; }
|
||||
bool IsCurrentExpansionProphecyOfRo() { return current_expansion == Expansion::ExpansionNumber::ProphecyOfRo; }
|
||||
bool IsCurrentExpansionTheSerpentsSpine() { return current_expansion == Expansion::ExpansionNumber::TheSerpentsSpine; }
|
||||
bool IsCurrentExpansionTheBuriedSea() { return current_expansion == Expansion::ExpansionNumber::TheBuriedSea; }
|
||||
bool IsCurrentExpansionSecretsOfFaydwer() { return current_expansion == Expansion::ExpansionNumber::SecretsOfFaydwer; }
|
||||
bool IsCurrentExpansionSeedsOfDestruction() { return current_expansion == Expansion::ExpansionNumber::SeedsOfDestruction; }
|
||||
bool IsCurrentExpansionUnderfoot() { return current_expansion == Expansion::ExpansionNumber::Underfoot; }
|
||||
bool IsCurrentExpansionHouseOfThule() { return current_expansion == Expansion::ExpansionNumber::HouseOfThule; }
|
||||
bool IsCurrentExpansionVeilOfAlaris() { return current_expansion == Expansion::ExpansionNumber::VeilOfAlaris; }
|
||||
bool IsCurrentExpansionRainOfFear() { return current_expansion == Expansion::ExpansionNumber::RainOfFear; }
|
||||
bool IsCurrentExpansionCallOfTheForsaken() { return current_expansion == Expansion::ExpansionNumber::CallOfTheForsaken; }
|
||||
bool IsCurrentExpansionTheDarkenedSea() { return current_expansion == Expansion::ExpansionNumber::TheDarkenedSea; }
|
||||
bool IsCurrentExpansionTheBrokenMirror() { return current_expansion == Expansion::ExpansionNumber::TheBrokenMirror; }
|
||||
bool IsCurrentExpansionEmpiresOfKunark() { return current_expansion == Expansion::ExpansionNumber::EmpiresOfKunark; }
|
||||
bool IsCurrentExpansionRingOfScale() { return current_expansion == Expansion::ExpansionNumber::RingOfScale; }
|
||||
bool IsCurrentExpansionTheBurningLands() { return current_expansion == Expansion::ExpansionNumber::TheBurningLands; }
|
||||
bool IsCurrentExpansionTormentOfVelious() { return current_expansion == Expansion::ExpansionNumber::TormentOfVelious; }
|
||||
|
||||
const std::vector<ContentFlagsRepository::ContentFlags> &GetContentFlags() const;
|
||||
std::vector<std::string> GetContentFlagsEnabled();
|
||||
std::vector<std::string> GetContentFlagsDisabled();
|
||||
bool IsContentFlagEnabled(const std::string& content_flag);
|
||||
bool IsContentFlagDisabled(const std::string& content_flag);
|
||||
void SetContentFlags(const std::vector<ContentFlagsRepository::ContentFlags>& content_flags);
|
||||
void ReloadContentFlags();
|
||||
WorldContentService * SetExpansionContext();
|
||||
|
||||
bool DoesPassContentFiltering(const ContentFlags& f);
|
||||
bool DoesZonePassContentFiltering(const ZoneRepository::Zone& z);
|
||||
|
||||
WorldContentService * SetDatabase(Database *database);
|
||||
Database *GetDatabase() const;
|
||||
|
||||
WorldContentService * SetContentDatabase(Database *database);
|
||||
Database *GetContentDatabase() const;
|
||||
|
||||
void SetContentFlag(const std::string &content_flag_name, bool enabled);
|
||||
|
||||
void HandleZoneRoutingMiddleware(ZoneChange_Struct *zc);
|
||||
|
||||
struct FindZoneResult {
|
||||
uint32 zone_id = 0;
|
||||
InstanceListRepository::InstanceList instance;
|
||||
ZoneRepository::Zone zone;
|
||||
};
|
||||
|
||||
FindZoneResult FindZone(uint32 zone_id, uint32 instance_id);
|
||||
bool IsInPublicStaticInstance(uint32 instance_id);
|
||||
|
||||
static WorldContentService* Instance()
|
||||
{
|
||||
static WorldContentService instance;
|
||||
return &instance;
|
||||
}
|
||||
|
||||
private:
|
||||
int current_expansion{};
|
||||
std::vector<ContentFlagsRepository::ContentFlags> content_flags;
|
||||
|
||||
// reference to database
|
||||
Database *m_database;
|
||||
Database *m_content_database;
|
||||
|
||||
// holds a record of the zone table from the database
|
||||
WorldContentService *LoadStaticGlobalZoneInstances();
|
||||
std::vector<InstanceListRepository::InstanceList> m_zone_static_instances;
|
||||
};
|
||||
+8
-216
@@ -1,111 +1,7 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "global_define.h"
|
||||
#include "eqemu_logsys.h"
|
||||
#include "crash.h"
|
||||
|
||||
#include "common/eqemu_config.h"
|
||||
#include "common/eqemu_logsys.h"
|
||||
#include "common/http/httplib.h"
|
||||
#include "common/http/uri.h"
|
||||
#include "common/json/json.h"
|
||||
#include "common/platform.h"
|
||||
#include "common/process/process.h"
|
||||
#include "common/rulesys.h"
|
||||
#include "common/serverinfo.h"
|
||||
#include "common/strings.h"
|
||||
#include "common/version.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
void SendCrashReport(const std::string &crash_report)
|
||||
{
|
||||
// can configure multiple endpoints if need be
|
||||
std::vector<std::string> endpoints = {
|
||||
"https://spire.eqemu.dev/api/v1/analytics/server-crash-report",
|
||||
// "http://localhost:3010/api/v1/analytics/server-crash-report", // development
|
||||
};
|
||||
|
||||
EQEmuLogSys* log = EQEmuLogSys::Instance();
|
||||
|
||||
auto config = EQEmuConfig::get();
|
||||
for (auto &e: endpoints) {
|
||||
uri u(e);
|
||||
|
||||
std::string base_url = fmt::format("{}://{}", u.get_scheme(), u.get_host());
|
||||
if (u.get_port()) {
|
||||
base_url += fmt::format(":{}", u.get_port());
|
||||
}
|
||||
|
||||
// client
|
||||
httplib::Client r(base_url);
|
||||
r.set_connection_timeout(1, 0);
|
||||
r.set_read_timeout(1, 0);
|
||||
r.set_write_timeout(1, 0);
|
||||
|
||||
// os info
|
||||
auto os = EQ::GetOS();
|
||||
auto cpus = EQ::GetCPUs();
|
||||
auto process_id = EQ::GetPID();
|
||||
auto rss = EQ::GetRSS() / 1048576.0;
|
||||
auto uptime = static_cast<uint32>(EQ::GetUptime());
|
||||
|
||||
// payload
|
||||
Json::Value p;
|
||||
p["platform_name"] = GetPlatformName();
|
||||
p["crash_report"] = crash_report;
|
||||
p["server_version"] = CURRENT_VERSION;
|
||||
p["compile_date"] = COMPILE_DATE;
|
||||
p["compile_time"] = COMPILE_TIME;
|
||||
p["server_name"] = config->LongName;
|
||||
p["server_short_name"] = config->ShortName;
|
||||
p["uptime"] = uptime;
|
||||
p["os_machine"] = os.machine;
|
||||
p["os_release"] = os.release;
|
||||
p["os_version"] = os.version;
|
||||
p["os_sysname"] = os.sysname;
|
||||
p["process_id"] = process_id;
|
||||
p["rss_memory"] = rss;
|
||||
p["cpus"] = cpus.size();
|
||||
p["origination_info"] = "";
|
||||
|
||||
if (!log->origination_info.zone_short_name.empty()) {
|
||||
p["origination_info"] = fmt::format(
|
||||
"{} ({}) instance_id [{}]",
|
||||
log->origination_info.zone_short_name,
|
||||
log->origination_info.zone_long_name,
|
||||
log->origination_info.instance_id
|
||||
);
|
||||
}
|
||||
|
||||
std::stringstream payload;
|
||||
payload << p;
|
||||
|
||||
if (auto res = r.Post(e, payload.str(), "application/json")) {
|
||||
if (res->status == 200) {
|
||||
LogInfo("Sent crash report");
|
||||
}
|
||||
else {
|
||||
LogError("Failed to send crash report to [{}]", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(_WINDOWS) && defined(CRASH_LOGGING)
|
||||
#include "StackWalker.h"
|
||||
|
||||
@@ -116,30 +12,22 @@ public:
|
||||
EQEmuStackWalker(DWORD dwProcessId, HANDLE hProcess) : StackWalker(dwProcessId, hProcess) { }
|
||||
virtual void OnOutput(LPCSTR szText) {
|
||||
char buffer[4096];
|
||||
for (int i = 0; i < 4096; ++i) {
|
||||
if (szText[i] == 0) {
|
||||
for(int i = 0; i < 4096; ++i) {
|
||||
if(szText[i] == 0) {
|
||||
buffer[i] = '\0';
|
||||
break;
|
||||
}
|
||||
|
||||
if (szText[i] == '\n' || szText[i] == '\r') {
|
||||
if(szText[i] == '\n' || szText[i] == '\r') {
|
||||
buffer[i] = ' ';
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
buffer[i] = szText[i];
|
||||
}
|
||||
}
|
||||
|
||||
std::string line = buffer;
|
||||
_lines.push_back(line);
|
||||
|
||||
Log(Logs::General, Logs::Crash, buffer);
|
||||
StackWalker::OnOutput(szText);
|
||||
}
|
||||
|
||||
const std::vector<std::string>& GetLines() { return _lines; }
|
||||
private:
|
||||
std::vector<std::string> _lines;
|
||||
};
|
||||
|
||||
LONG WINAPI windows_exception_handler(EXCEPTION_POINTERS *ExceptionInfo)
|
||||
@@ -213,20 +101,7 @@ LONG WINAPI windows_exception_handler(EXCEPTION_POINTERS *ExceptionInfo)
|
||||
|
||||
if(EXCEPTION_STACK_OVERFLOW != ExceptionInfo->ExceptionRecord->ExceptionCode)
|
||||
{
|
||||
EQEmuStackWalker sw;
|
||||
sw.ShowCallstack(GetCurrentThread(), ExceptionInfo->ContextRecord);
|
||||
|
||||
if (RuleB(Analytics, CrashReporting)) {
|
||||
std::string crash_report;
|
||||
auto& lines = sw.GetLines();
|
||||
|
||||
for (auto& line : lines) {
|
||||
crash_report += line;
|
||||
crash_report += "\n";
|
||||
}
|
||||
|
||||
SendCrashReport(crash_report);
|
||||
}
|
||||
EQEmuStackWalker sw; sw.ShowCallstack(GetCurrentThread(), ExceptionInfo->ContextRecord);
|
||||
}
|
||||
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
@@ -236,90 +111,7 @@ void set_exception_handler() {
|
||||
SetUnhandledExceptionFilter(windows_exception_handler);
|
||||
}
|
||||
#else
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/fcntl.h>
|
||||
|
||||
#ifdef __FreeBSD__
|
||||
#include <signal.h>
|
||||
#include <sys/stat.h>
|
||||
#endif
|
||||
|
||||
void print_trace()
|
||||
{
|
||||
bool does_gdb_exist = Strings::Contains(Process::execute("gdb -v"), "GNU");
|
||||
if (!does_gdb_exist) {
|
||||
LogCrash(
|
||||
"[Error] GDB is not installed, if you want crash dumps on Linux to work properly you will need GDB installed"
|
||||
);
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
auto uid = geteuid();
|
||||
std::string temp_output_file = fmt::format("/tmp/dump-output-{}", Strings::Random(10));
|
||||
|
||||
// check for passwordless sudo if not root
|
||||
if (uid != 0) {
|
||||
bool sudo_password_required = Strings::Contains(Process::execute("sudo -n true"), "a password is required");
|
||||
if (sudo_password_required) {
|
||||
LogCrash(
|
||||
"[Error] Current user does not have passwordless sudo installed. It is required to automatically process crash dumps with GDB as non-root."
|
||||
);
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
char pid_buf[30];
|
||||
sprintf(pid_buf, "%d", getpid());
|
||||
char name_buf[512];
|
||||
name_buf[readlink("/proc/self/exe", name_buf, 511)] = 0;
|
||||
int child_pid = fork();
|
||||
if (!child_pid) {
|
||||
int fd = open(temp_output_file.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
|
||||
dup2(fd, 1); // redirect output to stderr
|
||||
fprintf(stdout, "stack trace for %s pid=%s\n", name_buf, pid_buf);
|
||||
if (uid == 0) {
|
||||
execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
|
||||
}
|
||||
else {
|
||||
execlp("sudo", "gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
abort(); /* If gdb failed to start */
|
||||
}
|
||||
else {
|
||||
waitpid(child_pid, nullptr, 0);
|
||||
}
|
||||
|
||||
std::ifstream input(temp_output_file);
|
||||
std::string crash_report;
|
||||
for (std::string line; getline(input, line);) {
|
||||
LogCrash("{}", line);
|
||||
crash_report += fmt::format("{}\n", line);
|
||||
}
|
||||
|
||||
std::remove(temp_output_file.c_str());
|
||||
|
||||
if (RuleB(Analytics, CrashReporting)) {
|
||||
SendCrashReport(crash_report);
|
||||
}
|
||||
|
||||
EQEmuLogSys::Instance()->CloseFileLogs();
|
||||
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// crash is off or an unhandled platform
|
||||
void set_exception_handler()
|
||||
{
|
||||
signal(SIGABRT, reinterpret_cast<void (*)(int)>(print_trace));
|
||||
signal(SIGFPE, reinterpret_cast<void (*)(int)>(print_trace));
|
||||
signal(SIGFPE, reinterpret_cast<void (*)(int)>(print_trace));
|
||||
signal(SIGSEGV, reinterpret_cast<void (*)(int)>(print_trace));
|
||||
void set_exception_handler() {
|
||||
}
|
||||
#endif
|
||||
|
||||
+4
-18
@@ -1,20 +1,6 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef __EQEMU_CRASH_H
|
||||
#define __EQEMU_CRASH_H
|
||||
|
||||
void set_exception_handler();
|
||||
|
||||
#endif
|
||||
|
||||
+2
-20
@@ -1,23 +1,4 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "crc16.h"
|
||||
|
||||
#include "common/crc32.h"
|
||||
#include "crc32.h"
|
||||
|
||||
uint16 CRC16(const unsigned char *buf, int size, int key)
|
||||
{
|
||||
@@ -31,3 +12,4 @@ uint16 CRC16(const unsigned char *buf, int size, int key)
|
||||
crc = CRC32::Update(buf, size, crc);
|
||||
return CRC32::Finish(crc) & 0xffff;
|
||||
}
|
||||
|
||||
|
||||
+5
-20
@@ -1,22 +1,7 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/types.h"
|
||||
#ifndef _CRC16_H
|
||||
#define _CRC16_H
|
||||
#include "types.h"
|
||||
|
||||
uint16 CRC16(const unsigned char *buf, int size, int key);
|
||||
|
||||
#endif
|
||||
|
||||
+2
-38
@@ -1,23 +1,5 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "crc32.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <assert.h>
|
||||
#include <memory.h>
|
||||
|
||||
uint32 CRC32Table[256] =
|
||||
@@ -99,24 +81,6 @@ uint32 CRC32::GenerateNoFlip(const uint8* buf, uint32 bufsize) {
|
||||
return Update(buf, bufsize);
|
||||
}
|
||||
|
||||
unsigned long CRC32::GetEQChecksum(uchar* in_data, uint32 in_length, uint32 start_at)
|
||||
{
|
||||
unsigned long data;
|
||||
unsigned long check = 0xffffffff;
|
||||
|
||||
for (uint32 i = start_at; i < in_length; i++)
|
||||
{
|
||||
data = in_data[i];
|
||||
data = data ^ (check);
|
||||
data = data & 0x000000ff;
|
||||
check = check >> 8;
|
||||
data = CRC32Table[data];
|
||||
check = check ^ data;
|
||||
}
|
||||
|
||||
return check;
|
||||
}
|
||||
|
||||
void CRC32::SetEQChecksum(uchar* in_data, uint32 in_length, uint32 start_at)
|
||||
{
|
||||
unsigned long data;
|
||||
@@ -143,6 +107,6 @@ uint32 CRC32::Update(const uint8* buf, uint32 bufsize, uint32 crc32var) {
|
||||
return crc32var;
|
||||
}
|
||||
|
||||
void CRC32::Calc(const uint8 byte, uint32& crc32var) {
|
||||
inline void CRC32::Calc(const uint8 byte, uint32& crc32var) {
|
||||
crc32var = ((crc32var) >> 8) ^ CRC32Table[(byte) ^ ((crc32var) & 0x000000FF)];
|
||||
}
|
||||
|
||||
+4
-21
@@ -1,23 +1,6 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/types.h"
|
||||
#ifndef CRC32_H
|
||||
#define CRC32_H
|
||||
#include "types.h"
|
||||
|
||||
class CRC32 {
|
||||
public:
|
||||
@@ -25,7 +8,6 @@ public:
|
||||
static uint32 Generate(const uint8* buf, uint32 bufsize);
|
||||
static uint32 GenerateNoFlip(const uint8* buf, uint32 bufsize); // Same as Generate(), but without the ~
|
||||
static void SetEQChecksum(uchar* in_data, uint32 in_length, uint32 start_at=4);
|
||||
static unsigned long GetEQChecksum(uchar* in_data, uint32 in_length, uint32 start_at = 4);
|
||||
|
||||
// Multiple buffer CRC32
|
||||
static uint32 Update(const uint8* buf, uint32 bufsize, uint32 crc32 = 0xFFFFFFFF);
|
||||
@@ -35,3 +17,4 @@ public:
|
||||
private:
|
||||
static inline void Calc(const uint8 byte, uint32& crc32);
|
||||
};
|
||||
#endif
|
||||
|
||||
@@ -1,893 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <bitset>
|
||||
#include <cctype>
|
||||
#include <ctime>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if __cplusplus > 201402L
|
||||
#include <string_view>
|
||||
#define CRONCPP_IS_CPP17
|
||||
#endif
|
||||
|
||||
namespace cron
|
||||
{
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
#define HAS_STRING_VIEW
|
||||
#define STRING_VIEW std::string_view
|
||||
#define STRING_VIEW_NPOS std::string_view::npos
|
||||
#define CONSTEXPTR constexpr
|
||||
#else
|
||||
#define STRING_VIEW std::string const &
|
||||
#define STRING_VIEW_NPOS std::string::npos
|
||||
#define CONSTEXPTR
|
||||
#endif
|
||||
|
||||
using cron_int = uint8_t;
|
||||
|
||||
constexpr std::time_t INVALID_TIME = static_cast<std::time_t>(-1);
|
||||
|
||||
constexpr size_t INVALID_CRON_INDEX = static_cast<size_t>(-1);
|
||||
|
||||
class cronexpr;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
enum class cron_field
|
||||
{
|
||||
second,
|
||||
minute,
|
||||
hour_of_day,
|
||||
day_of_week,
|
||||
day_of_month,
|
||||
month,
|
||||
year
|
||||
};
|
||||
|
||||
template <typename Traits>
|
||||
static bool find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot);
|
||||
}
|
||||
|
||||
struct bad_cronexpr : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
explicit bad_cronexpr(STRING_VIEW message) :
|
||||
std::runtime_error(message.data())
|
||||
{}
|
||||
};
|
||||
|
||||
|
||||
struct cron_standard_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 0;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 6;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 1;
|
||||
static const cron_int CRON_MAX_MONTHS = 12;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
struct cron_oracle_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 0;
|
||||
static const cron_int CRON_MAX_MONTHS = 11;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
struct cron_quartz_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 1;
|
||||
static const cron_int CRON_MAX_MONTHS = 12;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
class cronexpr;
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static cronexpr make_cron(STRING_VIEW expr);
|
||||
|
||||
class cronexpr
|
||||
{
|
||||
std::bitset<60> seconds;
|
||||
std::bitset<60> minutes;
|
||||
std::bitset<24> hours;
|
||||
std::bitset<7> days_of_week;
|
||||
std::bitset<31> days_of_month;
|
||||
std::bitset<12> months;
|
||||
|
||||
friend bool operator==(cronexpr const & e1, cronexpr const & e2);
|
||||
friend bool operator!=(cronexpr const & e1, cronexpr const & e2);
|
||||
|
||||
template <typename Traits>
|
||||
friend bool detail::find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot);
|
||||
|
||||
friend std::string to_string(cronexpr const & cex);
|
||||
|
||||
template <typename Traits>
|
||||
friend cronexpr make_cron(STRING_VIEW expr);
|
||||
};
|
||||
|
||||
inline bool operator==(cronexpr const & e1, cronexpr const & e2)
|
||||
{
|
||||
return
|
||||
e1.seconds == e2.seconds &&
|
||||
e1.minutes == e2.minutes &&
|
||||
e1.hours == e2.hours &&
|
||||
e1.days_of_week == e2.days_of_week &&
|
||||
e1.days_of_month == e2.days_of_month &&
|
||||
e1.months == e2.months;
|
||||
}
|
||||
|
||||
inline bool operator!=(cronexpr const & e1, cronexpr const & e2)
|
||||
{
|
||||
return !(e1 == e2);
|
||||
}
|
||||
|
||||
inline std::string to_string(cronexpr const & cex)
|
||||
{
|
||||
return
|
||||
cex.seconds.to_string() + " " +
|
||||
cex.minutes.to_string() + " " +
|
||||
cex.hours.to_string() + " " +
|
||||
cex.days_of_month.to_string() + " " +
|
||||
cex.months.to_string() + " " +
|
||||
cex.days_of_week.to_string();
|
||||
}
|
||||
|
||||
namespace utils
|
||||
{
|
||||
inline std::time_t tm_to_time(std::tm& date)
|
||||
{
|
||||
return std::mktime(&date);
|
||||
}
|
||||
|
||||
inline std::tm* time_to_tm(std::time_t const * date, std::tm* const out)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
errno_t err = localtime_s(out, date);
|
||||
return 0 == err ? out : nullptr;
|
||||
#else
|
||||
return localtime_r(date, out);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline std::tm to_tm(STRING_VIEW time)
|
||||
{
|
||||
std::istringstream str(time.data());
|
||||
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||
|
||||
std::tm result;
|
||||
str >> std::get_time(&result, "%Y-%m-%d %H:%M:%S");
|
||||
if (str.fail()) throw std::runtime_error("Parsing date failed!");
|
||||
|
||||
result.tm_isdst = -1; // DST info not available
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::string to_string(std::tm const & tm)
|
||||
{
|
||||
std::ostringstream str;
|
||||
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||
str << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
|
||||
if (str.fail()) throw std::runtime_error("Writing date failed!");
|
||||
|
||||
return str.str();
|
||||
}
|
||||
|
||||
inline std::string to_upper(std::string text)
|
||||
{
|
||||
std::transform(std::begin(text), std::end(text),
|
||||
std::begin(text), static_cast<int(*)(int)>(std::toupper));
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
static std::vector<std::string> split(STRING_VIEW text, char const delimiter)
|
||||
{
|
||||
std::vector<std::string> tokens;
|
||||
std::string token;
|
||||
std::istringstream tokenStream(text.data());
|
||||
while (std::getline(tokenStream, token, delimiter))
|
||||
{
|
||||
tokens.push_back(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
CONSTEXPTR inline bool contains(STRING_VIEW text, char const ch) noexcept
|
||||
{
|
||||
return STRING_VIEW_NPOS != text.find_first_of(ch);
|
||||
}
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
inline cron_int to_cron_int(STRING_VIEW text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return static_cast<cron_int>(Strings::ToUnsignedInt(text.data()));
|
||||
}
|
||||
catch (std::exception const & ex)
|
||||
{
|
||||
throw bad_cronexpr(ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
static std::string replace_ordinals(
|
||||
std::string text,
|
||||
std::vector<std::string> const & replacement)
|
||||
{
|
||||
for (size_t i = 0; i < replacement.size(); ++i)
|
||||
{
|
||||
auto pos = text.find(replacement[i]);
|
||||
if (std::string::npos != pos)
|
||||
text.replace(pos, 3 ,std::to_string(i));
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
static std::pair<cron_int, cron_int> make_range(
|
||||
STRING_VIEW field,
|
||||
cron_int const minval,
|
||||
cron_int const maxval)
|
||||
{
|
||||
cron_int first = 0;
|
||||
cron_int last = 0;
|
||||
if (field.size() == 1 && field[0] == '*')
|
||||
{
|
||||
first = minval;
|
||||
last = maxval;
|
||||
}
|
||||
else if (!utils::contains(field, '-'))
|
||||
{
|
||||
first = to_cron_int(field);
|
||||
last = first;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto parts = utils::split(field, '-');
|
||||
if (parts.size() != 2)
|
||||
throw bad_cronexpr("Specified range requires two fields");
|
||||
|
||||
first = to_cron_int(parts[0]);
|
||||
last = to_cron_int(parts[1]);
|
||||
}
|
||||
|
||||
if (first > maxval || last > maxval)
|
||||
{
|
||||
throw bad_cronexpr("Specified range exceeds maximum");
|
||||
}
|
||||
if (first < minval || last < minval)
|
||||
{
|
||||
throw bad_cronexpr("Specified range is less than minimum");
|
||||
}
|
||||
if (first > last)
|
||||
{
|
||||
throw bad_cronexpr("Specified range start exceeds range end");
|
||||
}
|
||||
|
||||
return { first, last };
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
static void set_cron_field(
|
||||
STRING_VIEW value,
|
||||
std::bitset<N>& target,
|
||||
cron_int const minval,
|
||||
cron_int const maxval)
|
||||
{
|
||||
if(value.length() > 0 && value[value.length()-1] == ',')
|
||||
throw bad_cronexpr("Value cannot end with comma");
|
||||
|
||||
auto fields = utils::split(value, ',');
|
||||
if (fields.empty())
|
||||
throw bad_cronexpr("Expression parsing error");
|
||||
|
||||
for (auto const & field : fields)
|
||||
{
|
||||
if (!utils::contains(field, '/'))
|
||||
{
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
auto[first, last] = detail::make_range(field, minval, maxval);
|
||||
#else
|
||||
auto range = detail::make_range(field, minval, maxval);
|
||||
auto first = range.first;
|
||||
auto last = range.second;
|
||||
#endif
|
||||
for (cron_int i = first - minval; i <= last - minval; ++i)
|
||||
{
|
||||
target.set(i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
auto parts = utils::split(field, '/');
|
||||
if (parts.size() != 2)
|
||||
throw bad_cronexpr("Incrementer must have two fields");
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
auto[first, last] = detail::make_range(parts[0], minval, maxval);
|
||||
#else
|
||||
auto range = detail::make_range(parts[0], minval, maxval);
|
||||
auto first = range.first;
|
||||
auto last = range.second;
|
||||
#endif
|
||||
|
||||
if (!utils::contains(parts[0], '-'))
|
||||
{
|
||||
last = maxval;
|
||||
}
|
||||
|
||||
auto delta = detail::to_cron_int(parts[1]);
|
||||
if(delta <= 0)
|
||||
throw bad_cronexpr("Incrementer must be a positive value");
|
||||
|
||||
for (cron_int i = first - minval; i <= last - minval; i += delta)
|
||||
{
|
||||
target.set(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_days_of_week(
|
||||
std::string value,
|
||||
std::bitset<7>& target)
|
||||
{
|
||||
auto days = utils::to_upper(value);
|
||||
auto days_replaced = detail::replace_ordinals(
|
||||
days,
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
Traits::DAYS
|
||||
#else
|
||||
Traits::DAYS()
|
||||
#endif
|
||||
);
|
||||
|
||||
if (days_replaced.size() == 1 && days_replaced[0] == '?')
|
||||
days_replaced[0] = '*';
|
||||
|
||||
set_cron_field(
|
||||
days_replaced,
|
||||
target,
|
||||
Traits::CRON_MIN_DAYS_OF_WEEK,
|
||||
Traits::CRON_MAX_DAYS_OF_WEEK);
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_days_of_month(
|
||||
std::string value,
|
||||
std::bitset<31>& target)
|
||||
{
|
||||
if (value.size() == 1 && value[0] == '?')
|
||||
value[0] = '*';
|
||||
|
||||
set_cron_field(
|
||||
value,
|
||||
target,
|
||||
Traits::CRON_MIN_DAYS_OF_MONTH,
|
||||
Traits::CRON_MAX_DAYS_OF_MONTH);
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_month(
|
||||
std::string value,
|
||||
std::bitset<12>& target)
|
||||
{
|
||||
auto month = utils::to_upper(value);
|
||||
auto month_replaced = replace_ordinals(
|
||||
month,
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
Traits::MONTHS
|
||||
#else
|
||||
Traits::MONTHS()
|
||||
#endif
|
||||
);
|
||||
|
||||
set_cron_field(
|
||||
month_replaced,
|
||||
target,
|
||||
Traits::CRON_MIN_MONTHS,
|
||||
Traits::CRON_MAX_MONTHS);
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
inline size_t next_set_bit(
|
||||
std::bitset<N> const & target,
|
||||
size_t /*minimum*/,
|
||||
size_t /*maximum*/,
|
||||
size_t offset)
|
||||
{
|
||||
for (auto i = offset; i < N; ++i)
|
||||
{
|
||||
if (target.test(i)) return i;
|
||||
}
|
||||
|
||||
return INVALID_CRON_INDEX;
|
||||
}
|
||||
|
||||
inline void add_to_field(
|
||||
std::tm& date,
|
||||
cron_field const field,
|
||||
int const val)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec += val;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min += val;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour += val;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday += val;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon += val;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year += val;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void set_field(
|
||||
std::tm& date,
|
||||
cron_field const field,
|
||||
int const val)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec = val;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min = val;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour = val;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
date.tm_wday = val;
|
||||
break;
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday = val;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon = val;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year = val;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void reset_field(
|
||||
std::tm& date,
|
||||
cron_field const field)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec = 0;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min = 0;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour = 0;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
date.tm_wday = 0;
|
||||
break;
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday = 1;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon = 0;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void reset_all_fields(
|
||||
std::tm& date,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
for (size_t i = 0; i < marked_fields.size(); ++i)
|
||||
{
|
||||
if (marked_fields.test(i))
|
||||
reset_field(date, static_cast<cron_field>(i));
|
||||
}
|
||||
}
|
||||
|
||||
inline void mark_field(
|
||||
std::bitset<7> & orders,
|
||||
cron_field const field)
|
||||
{
|
||||
if (!orders.test(static_cast<size_t>(field)))
|
||||
orders.set(static_cast<size_t>(field));
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
static size_t find_next(
|
||||
std::bitset<N> const & target,
|
||||
std::tm& date,
|
||||
unsigned int const minimum,
|
||||
unsigned int const maximum,
|
||||
unsigned int const value,
|
||||
cron_field const field,
|
||||
cron_field const next_field,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
auto next_value = next_set_bit(target, minimum, maximum, value);
|
||||
if (INVALID_CRON_INDEX == next_value)
|
||||
{
|
||||
add_to_field(date, next_field, 1);
|
||||
reset_field(date, field);
|
||||
next_value = next_set_bit(target, minimum, maximum, 0);
|
||||
}
|
||||
|
||||
if (INVALID_CRON_INDEX == next_value || next_value != value)
|
||||
{
|
||||
set_field(date, field, static_cast<int>(next_value));
|
||||
reset_all_fields(date, marked_fields);
|
||||
}
|
||||
|
||||
return next_value;
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static size_t find_next_day(
|
||||
std::tm& date,
|
||||
std::bitset<31> const & days_of_month,
|
||||
size_t day_of_month,
|
||||
std::bitset<7> const & days_of_week,
|
||||
size_t day_of_week,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
unsigned int count = 0;
|
||||
unsigned int maximum = 366;
|
||||
while (
|
||||
(!days_of_month.test(day_of_month - Traits::CRON_MIN_DAYS_OF_MONTH) ||
|
||||
!days_of_week.test(day_of_week - Traits::CRON_MIN_DAYS_OF_WEEK))
|
||||
&& count++ < maximum)
|
||||
{
|
||||
add_to_field(date, cron_field::day_of_month, 1);
|
||||
|
||||
day_of_month = date.tm_mday;
|
||||
day_of_week = date.tm_wday;
|
||||
|
||||
reset_all_fields(date, marked_fields);
|
||||
}
|
||||
|
||||
return day_of_month;
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static bool find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot)
|
||||
{
|
||||
bool res = true;
|
||||
|
||||
std::bitset<7> marked_fields{ 0 };
|
||||
std::bitset<7> empty_list{ 0 };
|
||||
|
||||
unsigned int second = date.tm_sec;
|
||||
auto updated_second = find_next(
|
||||
cex.seconds,
|
||||
date,
|
||||
Traits::CRON_MIN_SECONDS,
|
||||
Traits::CRON_MAX_SECONDS,
|
||||
second,
|
||||
cron_field::second,
|
||||
cron_field::minute,
|
||||
empty_list);
|
||||
|
||||
if (second == updated_second)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::second);
|
||||
}
|
||||
|
||||
unsigned int minute = date.tm_min;
|
||||
auto update_minute = find_next(
|
||||
cex.minutes,
|
||||
date,
|
||||
Traits::CRON_MIN_MINUTES,
|
||||
Traits::CRON_MAX_MINUTES,
|
||||
minute,
|
||||
cron_field::minute,
|
||||
cron_field::hour_of_day,
|
||||
marked_fields);
|
||||
if (minute == update_minute)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::minute);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int hour = date.tm_hour;
|
||||
auto updated_hour = find_next(
|
||||
cex.hours,
|
||||
date,
|
||||
Traits::CRON_MIN_HOURS,
|
||||
Traits::CRON_MAX_HOURS,
|
||||
hour,
|
||||
cron_field::hour_of_day,
|
||||
cron_field::day_of_week,
|
||||
marked_fields);
|
||||
if (hour == updated_hour)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::hour_of_day);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int day_of_week = date.tm_wday;
|
||||
unsigned int day_of_month = date.tm_mday;
|
||||
auto updated_day_of_month = find_next_day<Traits>(
|
||||
date,
|
||||
cex.days_of_month,
|
||||
day_of_month,
|
||||
cex.days_of_week,
|
||||
day_of_week,
|
||||
marked_fields);
|
||||
if (day_of_month == updated_day_of_month)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::day_of_month);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int month = date.tm_mon;
|
||||
auto updated_month = find_next(
|
||||
cex.months,
|
||||
date,
|
||||
Traits::CRON_MIN_MONTHS,
|
||||
Traits::CRON_MAX_MONTHS,
|
||||
month,
|
||||
cron_field::month,
|
||||
cron_field::year,
|
||||
marked_fields);
|
||||
if (month != updated_month)
|
||||
{
|
||||
if (date.tm_year - dot > Traits::CRON_MAX_YEARS_DIFF)
|
||||
return false;
|
||||
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static cronexpr make_cron(STRING_VIEW expr)
|
||||
{
|
||||
cronexpr cex;
|
||||
|
||||
if (expr.empty())
|
||||
throw bad_cronexpr("Invalid empty cron expression");
|
||||
|
||||
auto fields = utils::split(expr, ' ');
|
||||
fields.erase(
|
||||
std::remove_if(std::begin(fields), std::end(fields),
|
||||
[](STRING_VIEW s) {return s.empty(); }),
|
||||
std::end(fields));
|
||||
if (fields.size() != 6)
|
||||
throw bad_cronexpr("cron expression must have six fields");
|
||||
|
||||
detail::set_cron_field(fields[0], cex.seconds, Traits::CRON_MIN_SECONDS, Traits::CRON_MAX_SECONDS);
|
||||
detail::set_cron_field(fields[1], cex.minutes, Traits::CRON_MIN_MINUTES, Traits::CRON_MAX_MINUTES);
|
||||
detail::set_cron_field(fields[2], cex.hours, Traits::CRON_MIN_HOURS, Traits::CRON_MAX_HOURS);
|
||||
|
||||
detail::set_cron_days_of_week<Traits>(fields[5], cex.days_of_week);
|
||||
|
||||
detail::set_cron_days_of_month<Traits>(fields[3], cex.days_of_month);
|
||||
|
||||
detail::set_cron_month<Traits>(fields[4], cex.months);
|
||||
|
||||
return cex;
|
||||
}
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static std::tm cron_next(cronexpr const & cex, std::tm date)
|
||||
{
|
||||
time_t original = utils::tm_to_time(date);
|
||||
if (INVALID_TIME == original) return {};
|
||||
|
||||
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||
return {};
|
||||
|
||||
time_t calculated = utils::tm_to_time(date);
|
||||
if (INVALID_TIME == calculated) return {};
|
||||
|
||||
if (calculated == original)
|
||||
{
|
||||
add_to_field(date, detail::cron_field::second, 1);
|
||||
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||
return {};
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static std::time_t cron_next(cronexpr const & cex, std::time_t const & date)
|
||||
{
|
||||
std::tm val;
|
||||
std::tm* dt = utils::time_to_tm(&date, &val);
|
||||
if (dt == nullptr) return INVALID_TIME;
|
||||
|
||||
time_t original = utils::tm_to_time(*dt);
|
||||
if (INVALID_TIME == original) return INVALID_TIME;
|
||||
|
||||
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||
return INVALID_TIME;
|
||||
|
||||
time_t calculated = utils::tm_to_time(*dt);
|
||||
if (INVALID_TIME == calculated) return calculated;
|
||||
|
||||
if (calculated == original)
|
||||
{
|
||||
add_to_field(*dt, detail::cron_field::second, 1);
|
||||
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||
return INVALID_TIME;
|
||||
}
|
||||
|
||||
return utils::tm_to_time(*dt);
|
||||
}
|
||||
}
|
||||
@@ -1,856 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "data_bucket.h"
|
||||
|
||||
#include "common/data_bucket.h"
|
||||
#include "common/database.h"
|
||||
#include "common/json/json.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <ctime>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
const std::string NESTED_KEY_DELIMITER = ".";
|
||||
std::vector<DataBucketsRepository::DataBuckets> g_data_bucket_cache = {};
|
||||
|
||||
void DataBucket::SetData(SharedDatabase* database, const std::string &bucket_key, const std::string &bucket_value, std::string expires_time)
|
||||
{
|
||||
auto k = DataBucketKey{
|
||||
.key = bucket_key,
|
||||
.value = bucket_value,
|
||||
.expires = expires_time,
|
||||
};
|
||||
|
||||
DataBucket::SetData(database, k);
|
||||
}
|
||||
|
||||
void DataBucket::SetData(SharedDatabase *database, const DataBucketKey &k_)
|
||||
{
|
||||
DataBucketKey k = k_; // copy the key so we can modify it
|
||||
bool is_nested = k.key.find(NESTED_KEY_DELIMITER) != std::string::npos;
|
||||
if (is_nested) {
|
||||
k.key = Strings::Split(k.key, NESTED_KEY_DELIMITER).front();
|
||||
}
|
||||
|
||||
auto b = DataBucketsRepository::NewEntity();
|
||||
auto r = GetData(database, k, true);
|
||||
// if we have an entry, use it
|
||||
if (r.id > 0) {
|
||||
b = r;
|
||||
}
|
||||
|
||||
// add scoping to bucket
|
||||
if (k.character_id > 0) {
|
||||
b.character_id = k.character_id;
|
||||
}
|
||||
else if (k.account_id > 0) {
|
||||
b.account_id = k.account_id;
|
||||
}
|
||||
else if (k.npc_id > 0) {
|
||||
b.npc_id = k.npc_id;
|
||||
}
|
||||
else if (k.bot_id > 0) {
|
||||
b.bot_id = k.bot_id;
|
||||
} else if (k.zone_id > 0) {
|
||||
b.zone_id = k.zone_id;
|
||||
b.instance_id = k.instance_id;
|
||||
}
|
||||
|
||||
const uint64 bucket_id = b.id;
|
||||
int64 expires_time_unix = 0;
|
||||
|
||||
if (!k.expires.empty()) {
|
||||
expires_time_unix = static_cast<int64>(std::time(nullptr)) + Strings::ToInt(k.expires);
|
||||
if (isalpha(k.expires[0]) || isalpha(k.expires[k.expires.length() - 1])) {
|
||||
expires_time_unix = static_cast<int64>(std::time(nullptr)) + Strings::TimeToSeconds(k.expires);
|
||||
}
|
||||
if (is_nested) {
|
||||
LogDataBuckets("Nested keys can't expire; set expiration on the parent key");
|
||||
expires_time_unix = 0;
|
||||
}
|
||||
}
|
||||
|
||||
b.expires = expires_time_unix;
|
||||
b.value = k.value;
|
||||
b.key_ = k.key;
|
||||
|
||||
// Check for nested keys (keys with dots)
|
||||
if (k_.key.find(NESTED_KEY_DELIMITER) != std::string::npos) {
|
||||
// Retrieve existing JSON or create a new one
|
||||
std::string existing_value = r.id > 0 ? r.value : "{}";
|
||||
json json_value = json::object();
|
||||
|
||||
// Check if the JSON is valid
|
||||
if (Strings::IsValidJson(existing_value)) {
|
||||
try {
|
||||
json_value = json::parse(existing_value);
|
||||
} catch (json::parse_error &e) {
|
||||
LogDataBuckets("Failed to parse JSON for key [{}] [{}]", k_.key, e.what());
|
||||
json_value = json::object(); // Reset to an empty object on error
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively merge new key-value pair into the JSON object
|
||||
auto nested_keys = Strings::Split(k_.key, NESTED_KEY_DELIMITER);
|
||||
auto top_key = nested_keys.front();
|
||||
// remove the top-level key
|
||||
nested_keys.erase(nested_keys.begin());
|
||||
|
||||
json *current = &json_value;
|
||||
|
||||
for (size_t i = 0; i < nested_keys.size(); ++i) {
|
||||
const std::string &key_part = nested_keys[i];
|
||||
|
||||
if (i == nested_keys.size() - 1) {
|
||||
|
||||
LogDataBucketsDetail("Setting key [{}] key_part [{}]", k.key, key_part);
|
||||
|
||||
// If the key already exists and is an object or array, prevent overwriting to avoid data loss
|
||||
if (current->contains(key_part) &&
|
||||
((*current)[key_part].is_object() || (*current)[key_part].is_array())) {
|
||||
LogDataBuckets("Attempted to overwrite an existing object or array at key [{}] - skipping", k_.key);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the value at the final key
|
||||
(*current)[key_part] = k_.value;
|
||||
} else {
|
||||
// Traverse or create nested objects
|
||||
if (!current->contains(key_part)) {
|
||||
(*current)[key_part] = json::object();
|
||||
LogDataBucketsDetail("Creating nested root key [{}] key_part [{}]", k.key, key_part);
|
||||
} else if (!(*current)[key_part].is_object()) {
|
||||
// If key exists but is not an object, reset to object to avoid conflicts
|
||||
(*current)[key_part] = json::object();
|
||||
}
|
||||
current = &(*current)[key_part];
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize JSON back to string
|
||||
b.value = json_value.dump();
|
||||
b.key_ = top_key; // Use the top-level key
|
||||
}
|
||||
|
||||
if (bucket_id) {
|
||||
// update the cache if it exists
|
||||
if (CanCache(k)) {
|
||||
for (auto &e: g_data_bucket_cache) {
|
||||
if (CheckBucketMatch(e, k)) {
|
||||
e = b;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DataBucketsRepository::UpdateOne(*database, b);
|
||||
}
|
||||
else {
|
||||
b = DataBucketsRepository::InsertOne(*database, b);
|
||||
|
||||
// add to cache if it doesn't exist
|
||||
if (CanCache(k) && !ExistsInCache(b)) {
|
||||
DeleteFromMissesCache(b);
|
||||
g_data_bucket_cache.emplace_back(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string DataBucket::GetData(SharedDatabase* database, const std::string &bucket_key)
|
||||
{
|
||||
return GetData(database, DataBucketKey{.key = bucket_key}).value;
|
||||
}
|
||||
|
||||
DataBucketsRepository::DataBuckets DataBucket::ExtractNestedValue(
|
||||
const DataBucketsRepository::DataBuckets &bucket,
|
||||
const std::string &full_key)
|
||||
{
|
||||
auto nested_keys = Strings::Split(full_key, NESTED_KEY_DELIMITER);
|
||||
auto top_key = nested_keys.front();
|
||||
nested_keys.erase(nested_keys.begin());
|
||||
json json_value;
|
||||
|
||||
// Check if the JSON is valid
|
||||
if (!Strings::IsValidJson(bucket.value)) {
|
||||
LogDataBuckets("Invalid JSON for key [{}]", bucket.key_);
|
||||
return DataBucketsRepository::NewEntity();
|
||||
}
|
||||
|
||||
try {
|
||||
json_value = json::parse(bucket.value); // Parse the JSON
|
||||
} catch (json::parse_error &ex) {
|
||||
LogDataBuckets("Failed to parse JSON for key [{}] [{}]", bucket.key_, ex.what());
|
||||
return DataBucketsRepository::NewEntity(); // Return empty entity on parse error
|
||||
}
|
||||
|
||||
// Start from the top-level key (e.g., "progression")
|
||||
json *current = &json_value;
|
||||
|
||||
// Traverse the JSON structure
|
||||
for (const auto &key_part: nested_keys) {
|
||||
LogDataBuckets("Looking for key part [{}] in JSON", key_part);
|
||||
|
||||
if (!current->contains(key_part)) {
|
||||
LogDataBuckets("Key part [{}] not found in JSON for [{}]", key_part, full_key);
|
||||
return DataBucketsRepository::NewEntity();
|
||||
}
|
||||
|
||||
current = &(*current)[key_part];
|
||||
}
|
||||
|
||||
// Create a new entity with the extracted value
|
||||
DataBucketsRepository::DataBuckets result = bucket; // Copy the original bucket
|
||||
result.value = current->is_string() ? current->get<std::string>() : current->dump();
|
||||
return result;
|
||||
}
|
||||
|
||||
// GetData fetches bucket data from the database or cache if it exists
|
||||
// if the bucket doesn't exist, it will be added to the cache as a miss
|
||||
// if ignore_misses_cache is true, the bucket will not be added to the cache as a miss
|
||||
// the only place we should be ignoring the misses cache is on the initial read during SetData
|
||||
DataBucketsRepository::DataBuckets DataBucket::GetData(SharedDatabase* database, const DataBucketKey &k_, bool ignore_misses_cache)
|
||||
{
|
||||
DataBucketKey k = k_; // Copy the key so we can modify it
|
||||
|
||||
bool is_nested_key = k.key.find(NESTED_KEY_DELIMITER) != std::string::npos;
|
||||
|
||||
// Extract the top-level key for nested keys
|
||||
if (is_nested_key) {
|
||||
k.key = Strings::Split(k.key, NESTED_KEY_DELIMITER).front();
|
||||
}
|
||||
|
||||
LogDataBuckets(
|
||||
"Getting bucket key [{}] bot_id [{}] account_id [{}] character_id [{}] npc_id [{}] zone_id [{}] instance_id [{}]",
|
||||
k.key,
|
||||
k.bot_id,
|
||||
k.account_id,
|
||||
k.character_id,
|
||||
k.npc_id,
|
||||
k.zone_id,
|
||||
k.instance_id
|
||||
);
|
||||
|
||||
bool can_cache = CanCache(k);
|
||||
|
||||
// Attempt to retrieve the value from the cache
|
||||
if (can_cache) {
|
||||
for (const auto &e : g_data_bucket_cache) {
|
||||
if (CheckBucketMatch(e, k)) {
|
||||
if (e.expires > 0 && e.expires < std::time(nullptr)) {
|
||||
LogDataBuckets("Attempted to read expired key [{}] removing from cache", e.key_);
|
||||
DeleteData(database, k);
|
||||
return DataBucketsRepository::NewEntity();
|
||||
}
|
||||
|
||||
LogDataBuckets("Returning key [{}] value [{}] from cache", e.key_, e.value);
|
||||
|
||||
if (is_nested_key && !k_.key.empty()) {
|
||||
return ExtractNestedValue(e, k_.key);
|
||||
}
|
||||
|
||||
return e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch the value from the database
|
||||
auto r = DataBucketsRepository::GetWhere(
|
||||
*database,
|
||||
fmt::format(
|
||||
" {} `key` = '{}' LIMIT 1",
|
||||
DataBucket::GetScopedDbFilters(k),
|
||||
k.key
|
||||
)
|
||||
);
|
||||
|
||||
if (r.empty()) {
|
||||
// Handle cache misses
|
||||
if (!ignore_misses_cache && can_cache) {
|
||||
size_t size_before = g_data_bucket_cache.size();
|
||||
|
||||
g_data_bucket_cache.emplace_back(
|
||||
DataBucketsRepository::DataBuckets{
|
||||
.id = 0,
|
||||
.key_ = k.key,
|
||||
.value = "",
|
||||
.expires = 0,
|
||||
.account_id = k.account_id,
|
||||
.character_id = k.character_id,
|
||||
.npc_id = k.npc_id,
|
||||
.bot_id = k.bot_id,
|
||||
.zone_id = k.zone_id,
|
||||
.instance_id = k.instance_id
|
||||
}
|
||||
);
|
||||
|
||||
LogDataBuckets(
|
||||
"Key [{}] not found in database, adding to cache as a miss account_id [{}] character_id [{}] npc_id [{}] bot_id [{}] zone_id [{}] instance_id [{}] cache size before [{}] after [{}]",
|
||||
k.key,
|
||||
k.account_id,
|
||||
k.character_id,
|
||||
k.npc_id,
|
||||
k.bot_id,
|
||||
k.zone_id,
|
||||
k.instance_id,
|
||||
size_before,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
return DataBucketsRepository::NewEntity();
|
||||
}
|
||||
|
||||
auto bucket = r.front();
|
||||
|
||||
// If the entry has expired, delete it
|
||||
if (bucket.expires > 0 && bucket.expires < static_cast<long long>(std::time(nullptr))) {
|
||||
DeleteData(database, k);
|
||||
return DataBucketsRepository::NewEntity();
|
||||
}
|
||||
|
||||
// Add the value to the cache if it doesn't exist
|
||||
if (can_cache) {
|
||||
bool has_cache = false;
|
||||
for (const auto &e : g_data_bucket_cache) {
|
||||
if (e.id == bucket.id) {
|
||||
has_cache = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!has_cache) {
|
||||
g_data_bucket_cache.emplace_back(bucket);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle nested key extraction
|
||||
if (is_nested_key && !k_.key.empty()) {
|
||||
return ExtractNestedValue(bucket, k_.key);
|
||||
}
|
||||
|
||||
return bucket;
|
||||
}
|
||||
|
||||
std::string DataBucket::GetDataExpires(SharedDatabase* database, const std::string &bucket_key)
|
||||
{
|
||||
return GetDataExpires(database, DataBucketKey{.key = bucket_key});
|
||||
}
|
||||
|
||||
std::string DataBucket::GetDataRemaining(SharedDatabase* database, const std::string &bucket_key)
|
||||
{
|
||||
return GetDataRemaining(database, DataBucketKey{.key = bucket_key});
|
||||
}
|
||||
|
||||
bool DataBucket::DeleteData(SharedDatabase* database, const std::string &bucket_key)
|
||||
{
|
||||
return DeleteData(database, DataBucketKey{.key = bucket_key});
|
||||
}
|
||||
|
||||
bool DataBucket::DeleteData(SharedDatabase* database, const DataBucketKey &k)
|
||||
{
|
||||
bool is_nested_key = k.key.find(NESTED_KEY_DELIMITER) != std::string::npos;
|
||||
|
||||
if (!is_nested_key) {
|
||||
// Update cache
|
||||
if (CanCache(k)) {
|
||||
// delete from cache where contents match
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &e) {
|
||||
return CheckBucketMatch(e, k);
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
}
|
||||
|
||||
// Regular key deletion, no nesting involved
|
||||
return DataBucketsRepository::DeleteWhere(
|
||||
*database,
|
||||
fmt::format("{} `key` = '{}'", DataBucket::GetScopedDbFilters(k), k.key)
|
||||
);
|
||||
}
|
||||
|
||||
// If it's a nested key, retrieve the top-level JSON object
|
||||
auto top_level_key = Strings::Split(k.key, NESTED_KEY_DELIMITER).front();
|
||||
DataBucketKey top_level_k = k;
|
||||
top_level_k.key = top_level_key;
|
||||
|
||||
auto r = GetData(database, top_level_k);
|
||||
if (r.id == 0 || r.value.empty() || !Strings::IsValidJson(r.value)) {
|
||||
LogDataBuckets("Attempted to delete nested key [{}] but parent key [{}] does not exist or is invalid JSON", k.key, top_level_key);
|
||||
return false;
|
||||
}
|
||||
|
||||
json json_value;
|
||||
try {
|
||||
json_value = json::parse(r.value);
|
||||
} catch (json::parse_error &ex) {
|
||||
LogDataBuckets("Failed to parse JSON for key [{}] [{}]", top_level_key, ex.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Recursively remove the nested key
|
||||
auto nested_keys = Strings::Split(k.key, NESTED_KEY_DELIMITER);
|
||||
auto top_key = nested_keys.front();
|
||||
nested_keys.erase(nested_keys.begin());
|
||||
json *current = &json_value;
|
||||
|
||||
for (size_t i = 0; i < nested_keys.size(); ++i) {
|
||||
const std::string &key_part = nested_keys[i];
|
||||
|
||||
if (i == nested_keys.size() - 1) {
|
||||
// Last key in the hierarchy - delete it
|
||||
if (current->contains(key_part)) {
|
||||
current->erase(key_part);
|
||||
LogDataBuckets("Deleted nested key [{}] from [{}]", key_part, k.key);
|
||||
} else {
|
||||
LogDataBuckets("Key [{}] not found in JSON - nothing to delete", k.key);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!current->contains(key_part) || !(*current)[key_part].is_object()) {
|
||||
LogDataBuckets("Parent key [{}] does not exist or is not an object", key_part);
|
||||
return false;
|
||||
}
|
||||
current = &(*current)[key_part];
|
||||
}
|
||||
}
|
||||
|
||||
// If the JSON object is now empty, delete the top-level key
|
||||
if (json_value.empty()) {
|
||||
LogDataBuckets("Top-level key [{}] is now empty, deleting entire entry", top_level_key);
|
||||
|
||||
// delete cache
|
||||
if (CanCache(k)) {
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &e) {
|
||||
return CheckBucketMatch(e, top_level_k);
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
}
|
||||
|
||||
return DataBucketsRepository::DeleteWhere(
|
||||
*database,
|
||||
fmt::format("{} `key` = '{}'", DataBucket::GetScopedDbFilters(k), top_level_key)
|
||||
);
|
||||
}
|
||||
|
||||
// Otherwise, update the existing JSON without the deleted key
|
||||
r.value = json_value.dump();
|
||||
DataBucketsRepository::UpdateOne(*database, r);
|
||||
|
||||
// Update cache
|
||||
if (CanCache(k)) {
|
||||
for (auto &e : g_data_bucket_cache) {
|
||||
if (CheckBucketMatch(e, top_level_k)) {
|
||||
e.value = r.value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string DataBucket::GetDataExpires(SharedDatabase* database, const DataBucketKey &k)
|
||||
{
|
||||
LogDataBuckets(
|
||||
"Getting bucket expiration key [{}] bot_id [{}] account_id [{}] character_id [{}] npc_id [{}]",
|
||||
k.key,
|
||||
k.bot_id,
|
||||
k.account_id,
|
||||
k.character_id,
|
||||
k.npc_id
|
||||
);
|
||||
|
||||
auto r = GetData(database, k);
|
||||
if (r.id == 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return std::to_string(r.expires);
|
||||
}
|
||||
|
||||
std::string DataBucket::GetDataRemaining(SharedDatabase* database, const DataBucketKey &k)
|
||||
{
|
||||
LogDataBuckets(
|
||||
"Getting bucket remaining key [{}] bot_id [{}] account_id [{}] character_id [{}] npc_id [{}] bot_id [{}] zone_id [{}] instance_id [{}]",
|
||||
k.key,
|
||||
k.bot_id,
|
||||
k.account_id,
|
||||
k.character_id,
|
||||
k.npc_id,
|
||||
k.bot_id,
|
||||
k.zone_id,
|
||||
k.instance_id
|
||||
);
|
||||
|
||||
auto r = GetData(database, k);
|
||||
if (r.id == 0) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return fmt::format("{}", r.expires - (long long) std::time(nullptr));
|
||||
}
|
||||
|
||||
std::string DataBucket::GetScopedDbFilters(const DataBucketKey &k)
|
||||
{
|
||||
std::vector<std::string> q = {};
|
||||
if (k.character_id > 0) {
|
||||
q.emplace_back(fmt::format("character_id = {}", k.character_id));
|
||||
}
|
||||
else {
|
||||
q.emplace_back("character_id = 0");
|
||||
}
|
||||
|
||||
if (k.account_id > 0) {
|
||||
q.emplace_back(fmt::format("account_id = {}", k.account_id));
|
||||
}
|
||||
else {
|
||||
q.emplace_back("account_id = 0");
|
||||
}
|
||||
|
||||
if (k.npc_id > 0) {
|
||||
q.emplace_back(fmt::format("npc_id = {}", k.npc_id));
|
||||
}
|
||||
else {
|
||||
q.emplace_back("npc_id = 0");
|
||||
}
|
||||
|
||||
if (k.bot_id > 0) {
|
||||
q.emplace_back(fmt::format("bot_id = {}", k.bot_id));
|
||||
}
|
||||
else {
|
||||
q.emplace_back("bot_id = 0");
|
||||
}
|
||||
|
||||
if (k.zone_id > 0) {
|
||||
q.emplace_back(fmt::format("zone_id = {} AND instance_id = {}", k.zone_id, k.instance_id));
|
||||
}
|
||||
else {
|
||||
q.emplace_back("zone_id = 0 AND instance_id = 0");
|
||||
}
|
||||
|
||||
return fmt::format(
|
||||
"{} {}",
|
||||
Strings::Join(q, " AND "),
|
||||
!q.empty() ? "AND" : ""
|
||||
);
|
||||
}
|
||||
|
||||
bool DataBucket::CheckBucketMatch(const DataBucketsRepository::DataBuckets &dbe, const DataBucketKey &k)
|
||||
{
|
||||
return (
|
||||
dbe.key_ == k.key &&
|
||||
dbe.bot_id == k.bot_id &&
|
||||
dbe.account_id == k.account_id &&
|
||||
dbe.character_id == k.character_id &&
|
||||
dbe.npc_id == k.npc_id &&
|
||||
dbe.zone_id == k.zone_id &&
|
||||
dbe.instance_id == k.instance_id
|
||||
);
|
||||
}
|
||||
|
||||
void DataBucket::LoadZoneCache(SharedDatabase* database, uint16 zone_id, uint16 instance_id)
|
||||
{
|
||||
const auto &l = DataBucketsRepository::GetWhere(
|
||||
*database,
|
||||
fmt::format(
|
||||
"zone_id = {} AND instance_id = {} AND (`expires` > {} OR `expires` = 0)",
|
||||
zone_id,
|
||||
instance_id,
|
||||
(long long) std::time(nullptr)
|
||||
)
|
||||
);
|
||||
|
||||
if (l.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
LogDataBucketsDetail("cache size before [{}] l size [{}]", g_data_bucket_cache.size(), l.size());
|
||||
|
||||
uint32 added_count = 0;
|
||||
|
||||
for (const auto &e: l) {
|
||||
if (!ExistsInCache(e)) {
|
||||
added_count++;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &e: l) {
|
||||
if (!ExistsInCache(e)) {
|
||||
LogDataBucketsDetail("bucket id [{}] bucket key [{}] bucket value [{}]", e.id, e.key_, e.value);
|
||||
|
||||
g_data_bucket_cache.emplace_back(e);
|
||||
}
|
||||
}
|
||||
|
||||
LogDataBucketsDetail("cache size after [{}]", g_data_bucket_cache.size());
|
||||
|
||||
LogDataBuckets(
|
||||
"Loaded [{}] zone keys new cache size is [{}]",
|
||||
l.size(),
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
void DataBucket::BulkLoadEntitiesToCache(SharedDatabase* database, DataBucketLoadType::Type t, std::vector<uint32> ids)
|
||||
{
|
||||
if (ids.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ids.size() == 1) {
|
||||
bool has_cache = false;
|
||||
|
||||
for (const auto &e: g_data_bucket_cache) {
|
||||
if (t == DataBucketLoadType::Bot) {
|
||||
has_cache = e.bot_id == ids[0];
|
||||
}
|
||||
else if (t == DataBucketLoadType::Account) {
|
||||
has_cache = e.account_id == ids[0];
|
||||
}
|
||||
else if (t == DataBucketLoadType::Client) {
|
||||
has_cache = e.character_id == ids[0];
|
||||
}
|
||||
}
|
||||
|
||||
if (has_cache) {
|
||||
LogDataBucketsDetail("LoadType [{}] ID [{}] has cache", DataBucketLoadType::Name[t], ids[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::string column;
|
||||
|
||||
switch (t) {
|
||||
case DataBucketLoadType::Bot:
|
||||
column = "bot_id";
|
||||
break;
|
||||
case DataBucketLoadType::Client:
|
||||
column = "character_id";
|
||||
break;
|
||||
case DataBucketLoadType::Account:
|
||||
column = "account_id";
|
||||
break;
|
||||
default:
|
||||
LogError("Incorrect LoadType [{}]", static_cast<int>(t));
|
||||
break;
|
||||
}
|
||||
|
||||
const auto &l = DataBucketsRepository::GetWhere(
|
||||
*database,
|
||||
fmt::format(
|
||||
"{} IN ({}) AND (`expires` > {} OR `expires` = 0)",
|
||||
column,
|
||||
Strings::Join(ids, ", "),
|
||||
(long long) std::time(nullptr)
|
||||
)
|
||||
);
|
||||
|
||||
if (l.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
LogDataBucketsDetail("cache size before [{}] l size [{}]", g_data_bucket_cache.size(), l.size());
|
||||
|
||||
uint32 added_count = 0;
|
||||
|
||||
for (const auto &e: l) {
|
||||
if (!ExistsInCache(e)) {
|
||||
added_count++;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &e: l) {
|
||||
if (!ExistsInCache(e)) {
|
||||
LogDataBucketsDetail("bucket id [{}] bucket key [{}] bucket value [{}]", e.id, e.key_, e.value);
|
||||
|
||||
g_data_bucket_cache.emplace_back(e);
|
||||
}
|
||||
}
|
||||
|
||||
LogDataBucketsDetail("cache size after [{}]", g_data_bucket_cache.size());
|
||||
|
||||
LogDataBuckets(
|
||||
"Bulk Loaded ids [{}] column [{}] new cache size is [{}]",
|
||||
ids.size(),
|
||||
column,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
void DataBucket::DeleteCachedBuckets(DataBucketLoadType::Type type, uint32 id, uint32 secondary_id)
|
||||
{
|
||||
size_t size_before = g_data_bucket_cache.size();
|
||||
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &e) {
|
||||
return (
|
||||
(type == DataBucketLoadType::Bot && e.bot_id == id) ||
|
||||
(type == DataBucketLoadType::Account && e.account_id == id) ||
|
||||
(type == DataBucketLoadType::Client && e.character_id == id) ||
|
||||
(type == DataBucketLoadType::Zone && e.zone_id == id && e.instance_id == secondary_id)
|
||||
);
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
|
||||
LogDataBuckets(
|
||||
"LoadType [{}] id [{}] cache size before [{}] after [{}]",
|
||||
DataBucketLoadType::Name[type],
|
||||
id,
|
||||
size_before,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
bool DataBucket::ExistsInCache(const DataBucketsRepository::DataBuckets &entry)
|
||||
{
|
||||
for (const auto &e: g_data_bucket_cache) {
|
||||
if (e.id == entry.id) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void DataBucket::DeleteFromMissesCache(DataBucketsRepository::DataBuckets e)
|
||||
{
|
||||
// delete from cache where there might have been a written bucket miss to the cache
|
||||
// this is to prevent the cache from growing too large
|
||||
size_t size_before = g_data_bucket_cache.size();
|
||||
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &ce) {
|
||||
return ce.id == 0 && ce.key_ == e.key_ &&
|
||||
ce.account_id == e.account_id &&
|
||||
ce.character_id == e.character_id &&
|
||||
ce.npc_id == e.npc_id &&
|
||||
ce.bot_id == e.bot_id &&
|
||||
ce.zone_id == e.zone_id &&
|
||||
ce.instance_id == e.instance_id;
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
LogDataBucketsDetail(
|
||||
"Deleted bucket misses from cache where key [{}] size before [{}] after [{}]",
|
||||
e.key_,
|
||||
size_before,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
void DataBucket::ClearCache()
|
||||
{
|
||||
g_data_bucket_cache.clear();
|
||||
LogInfo("Cleared data buckets cache");
|
||||
}
|
||||
|
||||
void DataBucket::DeleteFromCache(uint64 id, DataBucketLoadType::Type type)
|
||||
{
|
||||
size_t size_before = g_data_bucket_cache.size();
|
||||
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &e) {
|
||||
switch (type) {
|
||||
case DataBucketLoadType::Bot:
|
||||
return e.bot_id == id;
|
||||
case DataBucketLoadType::Client:
|
||||
return e.character_id == id;
|
||||
case DataBucketLoadType::Account:
|
||||
return e.account_id == id;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
|
||||
LogDataBuckets(
|
||||
"Deleted [{}] id [{}] from cache size before [{}] after [{}]",
|
||||
DataBucketLoadType::Name[type],
|
||||
id,
|
||||
size_before,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
void DataBucket::DeleteZoneFromCache(uint16 zone_id, uint16 instance_id, DataBucketLoadType::Type type)
|
||||
{
|
||||
size_t size_before = g_data_bucket_cache.size();
|
||||
|
||||
g_data_bucket_cache.erase(
|
||||
std::remove_if(
|
||||
g_data_bucket_cache.begin(),
|
||||
g_data_bucket_cache.end(),
|
||||
[&](DataBucketsRepository::DataBuckets &e) {
|
||||
switch (type) {
|
||||
case DataBucketLoadType::Zone:
|
||||
return e.zone_id == zone_id && e.instance_id == instance_id;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
),
|
||||
g_data_bucket_cache.end()
|
||||
);
|
||||
|
||||
LogDataBuckets(
|
||||
"Deleted zone [{}] instance [{}] from cache size before [{}] after [{}]",
|
||||
zone_id,
|
||||
instance_id,
|
||||
size_before,
|
||||
g_data_bucket_cache.size()
|
||||
);
|
||||
}
|
||||
|
||||
// CanCache returns whether a bucket can be cached or not
|
||||
// characters are only in one zone at a time so we can cache locally to the zone
|
||||
// bots (not implemented) are only in one zone at a time so we can cache locally to the zone
|
||||
// npcs (ids) can be in multiple zones so we can't cache locally to the zone
|
||||
bool DataBucket::CanCache(const DataBucketKey &key)
|
||||
{
|
||||
if (key.character_id > 0 || key.account_id > 0 || key.bot_id > 0 || key.zone_id > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/* EQEmu: EQEmulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "common/json/json_archive_single_line.h"
|
||||
#include "common/repositories/data_buckets_repository.h"
|
||||
#include "common/shareddb.h"
|
||||
#include "common/types.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
struct DataBucketKey {
|
||||
std::string key;
|
||||
std::string value;
|
||||
std::string expires;
|
||||
uint64_t account_id = 0;
|
||||
uint64_t character_id = 0;
|
||||
uint32_t npc_id = 0;
|
||||
uint32_t bot_id = 0;
|
||||
uint16_t zone_id = 0;
|
||||
uint16_t instance_id = 0;
|
||||
};
|
||||
|
||||
namespace DataBucketLoadType {
|
||||
enum Type : uint8 {
|
||||
Bot,
|
||||
Account,
|
||||
Client,
|
||||
Zone,
|
||||
MaxType
|
||||
};
|
||||
|
||||
static const std::string Name[Type::MaxType] = {
|
||||
"Bot",
|
||||
"Account",
|
||||
"Client",
|
||||
"Zone"
|
||||
};
|
||||
}
|
||||
|
||||
class DataBucket {
|
||||
public:
|
||||
// non-scoped bucket methods (for global buckets)
|
||||
static void SetData(SharedDatabase *database, const std::string &bucket_key, const std::string &bucket_value, std::string expires_time = "");
|
||||
static bool DeleteData(SharedDatabase *database, const std::string &bucket_key);
|
||||
static std::string GetData(SharedDatabase *database, const std::string &bucket_key);
|
||||
static std::string GetDataExpires(SharedDatabase *database, const std::string &bucket_key);
|
||||
static std::string GetDataRemaining(SharedDatabase *database, const std::string &bucket_key);
|
||||
|
||||
// scoped bucket methods
|
||||
static void SetData(SharedDatabase *database, const DataBucketKey &k_);
|
||||
static bool DeleteData(SharedDatabase *database, const DataBucketKey &k);
|
||||
static DataBucketsRepository::DataBuckets GetData(SharedDatabase *database, const DataBucketKey &k_, bool ignore_misses_cache = false);
|
||||
static std::string GetDataExpires(SharedDatabase *database, const DataBucketKey &k);
|
||||
static std::string GetDataRemaining(SharedDatabase *database, const DataBucketKey &k);
|
||||
static std::string GetScopedDbFilters(const DataBucketKey &k);
|
||||
|
||||
// bucket repository versus key matching
|
||||
static bool CheckBucketMatch(const DataBucketsRepository::DataBuckets &dbe, const DataBucketKey &k);
|
||||
static bool ExistsInCache(const DataBucketsRepository::DataBuckets &entry);
|
||||
|
||||
static void LoadZoneCache(SharedDatabase* database, uint16 zone_id, uint16 instance_id);
|
||||
static void BulkLoadEntitiesToCache(SharedDatabase* database, DataBucketLoadType::Type t, std::vector<uint32> ids);
|
||||
static void DeleteCachedBuckets(DataBucketLoadType::Type type, uint32 id, uint32 secondary_id = 0);
|
||||
|
||||
static void DeleteFromMissesCache(DataBucketsRepository::DataBuckets e);
|
||||
static void ClearCache();
|
||||
static void DeleteFromCache(uint64 id, DataBucketLoadType::Type type);
|
||||
static void DeleteZoneFromCache(uint16 zone_id, uint16 instance_id, DataBucketLoadType::Type type);
|
||||
static bool CanCache(const DataBucketKey &key);
|
||||
static DataBucketsRepository::DataBuckets
|
||||
ExtractNestedValue(const DataBucketsRepository::DataBuckets &bucket, const std::string &full_key);
|
||||
};
|
||||
+28
-27
@@ -1,54 +1,55 @@
|
||||
/* EQEmu: EQEmulator
|
||||
/* EQEMu: Everquest Server Emulator
|
||||
|
||||
Copyright (C) 2001-2026 EQEmu Development Team
|
||||
Copyright (C) 2001-2016 EQEMu Development Team (http://eqemulator.net)
|
||||
|
||||
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.
|
||||
the Free Software Foundation; version 2 of the License.
|
||||
|
||||
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.
|
||||
but WITHOUT ANY WARRANTY except by those people which sell it, which
|
||||
are required to give you total support for your newly bought product;
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#ifndef COMMON_DATA_VERIFICATION_H
|
||||
#define COMMON_DATA_VERIFICATION_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace EQ {
|
||||
template<typename T>
|
||||
T Clamp(const T &value, const T &lower, const T &upper)
|
||||
{
|
||||
|
||||
namespace EQEmu
|
||||
{
|
||||
template <typename T>
|
||||
T Clamp(const T& value, const T& lower, const T& upper) {
|
||||
return std::max(lower, std::min(value, upper));
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T ClampLower(const T &value, const T &lower)
|
||||
{
|
||||
template <typename T>
|
||||
T ClampLower(const T& value, const T& lower) {
|
||||
return std::max(lower, value);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T ClampUpper(const T &value, const T &upper)
|
||||
{
|
||||
template <typename T>
|
||||
T ClampUpper(const T& value, const T& upper) {
|
||||
return std::min(value, upper);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
bool ValueWithin(const T &value, const T &lower, const T &upper)
|
||||
{
|
||||
template <typename T>
|
||||
bool ValueWithin(const T& value, const T& lower, const T& upper) {
|
||||
return value >= lower && value <= upper;
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3>
|
||||
bool ValueWithin(const T1 &value, const T2 &lower, const T3 &upper)
|
||||
{
|
||||
return value >= (T1) lower && value <= (T1) upper;
|
||||
template <typename T1, typename T2, typename T3>
|
||||
bool ValueWithin(const T1& value, const T2& lower, const T3& upper) {
|
||||
return value >= (T1)lower && value <= (T1)upper;
|
||||
}
|
||||
|
||||
} /*EQEmu*/
|
||||
|
||||
#endif /*COMMON_DATA_VERIFICATION_H*/
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user