Compare commits

...

No commits in common. "ade7867fee2bb947b7dfea3247dde9a7799967bd" and "4df70576424af8da05a7544daebf8bddfe126d0a" have entirely different histories.

151 changed files with 345530 additions and 12 deletions

9
.gitattributes vendored Normal file
View file

@ -0,0 +1,9 @@
# .gitattributes
* text=auto eol=lf
*.sh eol=lf
*.ps1 text eol=ctrlf
*.bat text eol=ctrlf
# Binaries
*.png binary
*.db binary

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
# Builds
build/

47
CMakeLists.txt Normal file
View file

@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.16)
project(tibia-kaplar VERSION 0.1.0 LANGUAGES C CXX)
option(TIBIA772 "Login/Protocol RSA for Tibia 7.72 (Required for the login to work" ON)
option(BUILD_GAME "Compile game server" OFF)
option(BUILD_LOGIN "Compile login server" ON)
option(BUILD_QUERYMANAGER "Compile querymanager" ON)
option(BUILD_IPCHANGER "Compile IP Changer" OFF)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 17)
# All binaries fall into /build/bin (dockerfile copies build/ -> /opt/tibia/bin/)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
if(CMAKE_CONFIGURATION_TYPES)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/$<CONFIG>)
endif()
# Critical flag: Without TIBIA772=1 the RSA is read from the offset 7.7
# and the cypher from the login fails silently.
if(TIBIA772)
add_compile_definitions(TIBIA772=1)
endif()
message(STATUS "tibia-kaplar")
message(STATUS "TIBIA772 : ${TIBIA772}")
message(STATUS "GAME : ${BUILD_GAME}")
message(STATUS "LOGIN : ${BUILD_LOGIN}")
message(STATUS "QUERYMGR : ${BUILD_QUERYMANAGER}")
if(BUILD_GAME)
add_subdirectory(src/game)
endif()
if(BUILD_LOGIN)
add_subdirectory(src/login)
endif()
if(BUILD_QUERYMANAGER)
add_subdirectory(src/querymanager)
endif()
if(BUILD_IPCHANGER)
add_subdirectory(src/ipchanger)
endif()

View file

@ -1,9 +0,0 @@
MIT License
Copyright (c) 2026 Alan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,3 +0,0 @@
# tibia772
Tibia leaked from the cipsoft hack

15
scripts/README.md Normal file
View file

@ -0,0 +1,15 @@
# scripts/
Operación del monorepo:
- `vendor.ps1` — vendiza los repos kaplar en `src/`: guarda remote+commit en `.upstream.json` y elimina el `.git` anidado. **Ejecutar antes del primer commit del monorepo.**
- `fetch-data.sh` — descarga la data del leak desde un link compartido (OneDrive/GDrive/directo) usando `TIBIA_DATA_URL` (y opcional `TIBIA_DATA_TOKEN`). La data nunca entra al repo.
- `backup.sh` — respaldo de `data/` y `qm-db/` (snapshot consistente del SQLite)
- *(pendiente)* `new-account.sh` — INSERTs en `tibia.db` siguiendo el patrón del seed `z-999`
- *(pendiente)* `restore.sh` — restaurar desde un backup
## Flujo de data con OneDrive/GDrive
1. Empaqueta local: `tar -czf tibia-data.tar.gz data/ qm-db/`
2. Súbelo a OneDrive/GDrive y genera un link compartido (privado).
3. En cualquier máquina/VPS: `export TIBIA_DATA_URL="..."` y `./scripts/fetch-data.sh`.

32
scripts/backup.sh Normal file
View file

@ -0,0 +1,32 @@
#!/bin/sh
# Respaldo completo: data del leak + DB del QM.
# Uso: ./scripts/backup.sh [destino] (default: ./backups)
set -e
DEST="${1:-./backups}"
STAMP=$(date +%Y%m%d-%H%M%S)
echo "[backup] asegurando que el server no esté en mitad de un save..."
echo "[backup] destino: $DEST/$STAMP"
mkdir -p "$DEST/$STAMP"
# rsync copia calientemente; para respaldo consistente apaga antes:
# docker compose down
if [ -d ./data ]; then
tar -czf "$DEST/$STAMP/data.tar.gz" ./data
echo "[backup] data.tar.gz OK"
fi
if [ -d ./qm-db ]; then
# sqlite3 .backup es consistente incluso en caliente
if command -v sqlite3 >/dev/null; then
sqlite3 ./qm-db/tibia.db ".backup '$DEST/$STAMP/tibia.db'"
echo "[backup] tibia.db (consistente) OK"
else
tar -czf "$DEST/$STAMP/qm-db.tar.gz" ./qm-db
echo "[backup] qm-db.tar.gz OK (caliente, sin sqlite3)"
fi
fi
echo "[backup] listo: $DEST/$STAMP"

69
scripts/fetch-data.sh Normal file
View file

@ -0,0 +1,69 @@
#!/bin/sh
# ============================================================
# fetch-data.sh — trae la data del leak desde un link compartido
# (OneDrive / Google Drive / URL directa) usando una variable de entorno.
#
# Uso:
# export TIBIA_DATA_URL="https://..." # link compartido
# export TIBIA_DATA_TOKEN="" # opcional: token para OneDrive con password / gdrive confirm
# ./scripts/fetch-data.sh [destino] # default: ./data
#
# El destino NO se commitea: está en .gitignore (regla de oro).
# ============================================================
set -e
URL="${TIBIA_DATA_URL:?Debes exportar TIBIA_DATA_URL con el link de la data}"
TOKEN="${TIBIA_DATA_TOKEN:-}"
DEST="${1:-./data}"
# --- Detecta el tipo de link y lo convierte a descarga directa ---
case "$URL" in
*drive.google.com*drive/d/*|*drive.google.com*file/d/*)
# Google Drive: id del archivo -> descarga directa (con confirm para archivos grandes)
FILE_ID=$(printf '%s' "$URL" | sed -E 's#.*file/d/([A-Za-z0-9_-]+).*#\1#;s#.*drive/d/([A-Za-z0-9_-]+).*#\1#')
DL_URL="https://drive.google.com/uc?export=download&id=${FILE_ID}&confirm=t"
;;
*1drv.ms*|*onedrive.live.com*|*sharepoint.com*)
# OneDrive: el link corto redirige al archivo; dejar que curl siga el redirect.
# "download=1" fuerza descarga en vez de preview HTML.
case "$URL" in
*\?*) DL_URL="${URL}&download=1" ;;
*) DL_URL="${URL}?download=1" ;;
esac
;;
*)
DL_URL="$URL"
;;
esac
mkdir -p "$DEST.tmp"
echo "[fetch-data] descargando a $DEST.tmp/data.tar.gz ..."
curl -fL --retry 3 ${TOKEN:+-H "Authorization: Bearer $TOKEN"} \
-o "$DEST.tmp/data.tar.gz" "$DL_URL"
echo "[fetch-data] verificando que es un tarball válido..."
tar -tzf "$DEST.tmp/data.tar.gz" >/dev/null || {
echo "[fetch-data] ERROR: el contenido no es un tar.gz válido."
echo " Verifica que el link sea de descarga directa y no de vista previa."
exit 1
}
echo "[fetch-data] extrayendo..."
tar -xzf "$DEST.tmp/data.tar.gz" -C "$DEST.tmp"
# Si el tarball trae una carpeta raíz única, aplánala
if [ -d "$DEST.tmp/data" ]; then
mv "$DEST.tmp/data" "$DEST.new"
else
mv "$DEST.tmp" "$DEST.new"
fi
if [ -d "$DEST" ]; then
echo "[fetch-data] ya existe $DEST — moviendo el anterior a $DEST.old"
mv "$DEST" "$DEST.old"
fi
mv "$DEST.new" "$DEST"
rm -rf "$DEST.tmp" "$DEST.old"
echo "[fetch-data] listo: data en $DEST (recordar ./qm-db también)"

59
scripts/vendor.ps1 Normal file
View file

@ -0,0 +1,59 @@
# ============================================================
# vendor.ps1 — vendiza los repos kaplar dentro de src/
#
# Por cada componente: guarda su remote en .upstream.json,
# elimina su .git y lo deja listo para el commit del monorepo.
#
# Uso (PowerShell, en la raíz del monorepo):
# ./scripts/vendor.ps1 # procesa src/game, login, querymanager, web, ipchanger
# ./scripts/vendor.ps1 -WhatIf # solo muestra qué haría
# ============================================================
param([switch]$WhatIf)
$ErrorActionPreference = "Stop"
$components = @("game", "login", "querymanager", "web", "ipchanger")
foreach ($name in $components) {
$dir = Join-Path "src" $name
$gitDir = Join-Path $dir ".git"
if (-not (Test-Path $gitDir)) {
Write-Host "[vendor] $name : sin .git, se omite" -ForegroundColor DarkGray
continue
}
Push-Location $dir
$remote = git remote get-url origin 2>$null
$head = git rev-parse HEAD 2>$null
$branch = git rev-parse --abbrev-ref HEAD 2>$null
Pop-Location
$meta = @{
upstream = $remote
commit = $head
branch = $branch
vendoredAt = (Get-Date -Format "yyyy-MM-dd")
} | ConvertTo-Json
Write-Host "[vendor] $name : $remote @ $($head.Substring(0,8)) ($branch)"
if ($WhatIf) { continue }
Set-Content -Path "$dir\.upstream.json" -Value (
[pscustomobject]@{
upstream = "$remote"
commit = "$head"
branch = "$branch"
vendoredAt = (Get-Date -Format "yyyy-MM-dd")
} | ConvertTo-Json
)
# Elimina el git anidado: el contenido pasa a ser del monorepo
Remove-Item -Recurse -Force $gitDir
# Asegura que el monorepo ignore nada de estos dirs
Write-Host "[vendor] $name : vendizado OK" -ForegroundColor Green
}
Write-Host ""
Write-Host "[vendor] Listo. Ahora: git add -A; git commit -m 'vendor: kaplar sources'"

5
src/game/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
.vscode
bin
build
local
*.log

6
src/game/.upstream.json Normal file
View file

@ -0,0 +1,6 @@
{
"upstream": "https://kaplar.net/tibia/game.git",
"commit": "3fd1bdbaaffc6582943e3c9b3c28c20976fcb2ad",
"branch": "master",
"vendoredAt": "2026-11-12"
}

71
src/game/CMakeLists.txt Normal file
View file

@ -0,0 +1,71 @@
cmake_minimum_required(VERSION 3.16)
project(game LANGUAGES CXX)
# 28 objects from the original Makefile in the same order
add_executable(game
src/main.cc
src/communication.cc
src/config.cc
src/connections.cc
src/cract.cc
src/crcombat.cc
src/crmain.cc
src/crnonpl.cc
src/crplayer.cc
src/crskill.cc
src/crypto.cc
src/houses.cc
src/info.cc
src/magic.cc
src/map.cc
src/moveuse.cc
src/objects.cc
src/operate.cc
src/query.cc
src/reader.cc
src/receiving.cc
src/script.cc
src/sending.cc
src/shm.cc
src/strings.cc
src/threads.cc
src/time.cc
src/utils.cc
src/writer.cc
)
target_include_directories(game PRIVATE src)
# Flags del Makefile original (CFLAGS)
target_compile_options(game PRIVATE
-fno-strict-aliasing
-pedantic
-Wall -Wextra
-Wno-deprecated-declarations
-Wno-unused-parameter
-Wno-format-truncation
)
# Original Makefile defines: OS/arch (TIBIA722 inherits from the superbuild,
# replacing the sed over CFLAGS that was done before)
target_compile_definitions(game PRIVATE
OS_LINUX=1
ARCH_X64=1
$<$<CONFIG:Debug>:ENABLE_ASSERTIONS=1>
)
set_target_properties(game PROPERTIES
CXX_STANDARD 11
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
# LFLAGS: -lrt -lcrypto -pthread
target_link_libraries(game PRIVATE
rt
crypto
pthread
)
install(TARGETS game RUNTIME DESTINATION bin)

24
src/game/LICENSE.txt Normal file
View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>

141
src/game/Makefile Normal file
View file

@ -0,0 +1,141 @@
SRCDIR = src
BUILDDIR = build
OUTPUTEXE = game
CC = g++
CFLAGS = -m64 -fno-strict-aliasing -pedantic -Wall -Wextra -Wno-deprecated-declarations -Wno-unused-parameter -Wno-format-truncation -std=c++11 -pthread -DOS_LINUX=1 -DARCH_X64=1
LFLAGS = -Wl,-t -lrt -lcrypto
DEBUG ?= 0
ifneq ($(DEBUG), 0)
CFLAGS += -g -Og -DENABLE_ASSERTIONS=1
else
CFLAGS += -O2
endif
HEADERS = $(SRCDIR)/common.hh $(SRCDIR)/communication.hh $(SRCDIR)/config.hh $(SRCDIR)/connections.hh $(SRCDIR)/containers.hh $(SRCDIR)/cr.hh $(SRCDIR)/crypto.hh $(SRCDIR)/enums.hh $(SRCDIR)/houses.hh $(SRCDIR)/info.hh $(SRCDIR)/magic.hh $(SRCDIR)/map.hh $(SRCDIR)/moveuse.hh $(SRCDIR)/objects.hh $(SRCDIR)/operate.hh $(SRCDIR)/query.hh $(SRCDIR)/reader.hh $(SRCDIR)/script.hh $(SRCDIR)/threads.hh $(SRCDIR)/writer.hh
$(BUILDDIR)/$(OUTPUTEXE): $(BUILDDIR)/communication.obj $(BUILDDIR)/config.obj $(BUILDDIR)/connections.obj $(BUILDDIR)/cract.obj $(BUILDDIR)/crcombat.obj $(BUILDDIR)/crmain.obj $(BUILDDIR)/crnonpl.obj $(BUILDDIR)/crplayer.obj $(BUILDDIR)/crskill.obj $(BUILDDIR)/crypto.obj $(BUILDDIR)/houses.obj $(BUILDDIR)/info.obj $(BUILDDIR)/magic.obj $(BUILDDIR)/main.obj $(BUILDDIR)/map.obj $(BUILDDIR)/moveuse.obj $(BUILDDIR)/objects.obj $(BUILDDIR)/operate.obj $(BUILDDIR)/query.obj $(BUILDDIR)/reader.obj $(BUILDDIR)/receiving.obj $(BUILDDIR)/script.obj $(BUILDDIR)/sending.obj $(BUILDDIR)/shm.obj $(BUILDDIR)/strings.obj $(BUILDDIR)/threads.obj $(BUILDDIR)/time.obj $(BUILDDIR)/utils.obj $(BUILDDIR)/writer.obj
$(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)
$(BUILDDIR)/communication.obj: $(SRCDIR)/communication.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/config.obj: $(SRCDIR)/config.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/connections.obj: $(SRCDIR)/connections.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/cract.obj: $(SRCDIR)/cract.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crcombat.obj: $(SRCDIR)/crcombat.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crmain.obj: $(SRCDIR)/crmain.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crnonpl.obj: $(SRCDIR)/crnonpl.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crplayer.obj: $(SRCDIR)/crplayer.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crskill.obj: $(SRCDIR)/crskill.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/crypto.obj: $(SRCDIR)/crypto.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/houses.obj: $(SRCDIR)/houses.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/info.obj: $(SRCDIR)/info.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/magic.obj: $(SRCDIR)/magic.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/main.obj: $(SRCDIR)/main.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/map.obj: $(SRCDIR)/map.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/moveuse.obj: $(SRCDIR)/moveuse.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/objects.obj: $(SRCDIR)/objects.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/operate.obj: $(SRCDIR)/operate.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/query.obj: $(SRCDIR)/query.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/reader.obj: $(SRCDIR)/reader.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/receiving.obj: $(SRCDIR)/receiving.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/script.obj: $(SRCDIR)/script.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/sending.obj: $(SRCDIR)/sending.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/shm.obj: $(SRCDIR)/shm.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/strings.obj: $(SRCDIR)/strings.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/threads.obj: $(SRCDIR)/threads.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/time.obj: $(SRCDIR)/time.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/utils.obj: $(SRCDIR)/utils.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
$(BUILDDIR)/writer.obj: $(SRCDIR)/writer.cc $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
.PHONY: clean
clean:
@rm -rf $(BUILDDIR)

116
src/game/README.md Normal file
View file

@ -0,0 +1,116 @@
# Tibia 7.7 Game Server
This is the result of manually decompiling the leaked Tibia 7.7 server binary into a readable version of the original source code. With the exception of a few [changes](#changes), expected typos, and translation errors, everything should be as close as possible to the original. I do expect problems so any issues should be submitted to the issue tracker with the appropriate description.
## License and Legal Issues
The legal status of decompiled and rewritten code is a gray area. While the project contains no original assets or code, CipSoft may still view this as a violation of their claimed intellectual property rights, due to the original binary not being willfully released. As the author, I release this code into the public domain, relinquishing all rights and claims to it (see `LICENSE.txt`).
## Changes
- The most important change was fixing thread interactions. The original binary relied on some old Linux threading library, most likely LinuxThreads, which assigned different process ids to different threads, among other quirks. The fix is small and contained in commit d359c0a.
- Custom RSA routines were replaced with OpenSSL's libcrypto. I didn't bother to translate the decompiled routines because it would be annoying to get right and could end up with security issues. This introduces the **ONLY** dependency required to compile but is fairly simple to get it installed on most Linux distros. For example, on Debian you can use `apt install libssl-dev`.
## Future
I had a small *TODO* list with a few things to attempt after the server was up and running but I think that trying to modernize it further or get it to run on Windows wouldn't really add any value, plus it would probably require a lot of extra time. My commitment is to fix all reported bugs and perhaps string handling/building which is kind of a disaster. Exceptions are already too engraved into the codebase, to the point it would make more sense to rewrite everything without them rather than attempting to remove them.
## Compiling
The server uses a few Linux specific features so it will **ONLY** compile on Linux. It's possible to port to Windows but it would require a few design changes. Originally it would have no dependencies but with the RSA routines change it now requires OpenSSL's `libcrypto` as its **ONLY** dependency. The makefile is very simple and should work as long as libcrypto is installed. You can add the `-j N` switch to make it compile across N processes.
```
make # build in release mode
make DEBUG=1 # build in debug mode
make clean # remove `build` directory
make -B # full rebuild in release mode (recommended)
make -B DEBUG=1 # full rebuild in debug mode (recommended)
```
### Extra Features (Advanced)
There are also some extra features that can be enabled by appending the following definitions to the `CFLAGS` variable in your `Makefile`. They're completely optional but can be useful in specific scenarios.
- `-DTIBIA772=1`
- Modify the protocol to match Tibia 7.72. It's not a 1:1 relation so 7.7 clients won't be able to connect.
- `-DALLOW_LOCAL_PROXY=1`
- Allow **local** connections to send a proxy header. Ideally we'd have a list of trusted proxies to prevent clients from spoofing their addresses. In reality, it is almost always simpler to have a **local** relay. This is also the only way to get a multi-route proxy without having to drastically change the way connections are handled.
- `-DBIND_ACCEPTOR_TO_GAME_ADDRESS=1`
- Make the acceptor socket bind to the interface specified by the game address, rather than all available network interfaces. This is the same address stored in the database and may cause startup issues if no such interface exists, or connection issues if the address is not publicly reachable.
## Running
This repository contains only the source code for the game server. After the first decompilation pass, it was clear the server would need a few supporting services. They're fairly simple but each one will have a separate *README* file with a short description on how to compile and run them.
- [Query Manager](https://github.com/fusion32/tibia-querymanager)
- [Login Server](https://github.com/fusion32/tibia-login)
- [Web Server](https://github.com/fusion32/tibia-web)
The game server won't boot up if it's not able to connect to the query manager which makes it the only real hard dependency. The login server will handle character list, and the web server will handle basic account management.
It is recommended that the server is setup as a service. There is a *systemd* configuration file (`tibia-game.service`) in the repository that may be used along with the intructions below to set everything up. The steps may change depending on whether your system uses *systemd* or not.
> It is also a good idea to configure a firewall and generate a new RSA private key for **security** reasons, but those aren't covered here.
## Playing
Playing will require a copy of the original Tibia 7.7 client and some IP-Changer application. Since I can't trust anything out there, I also wrote a small [IP-Changer](https://github.com/fusion32/tibia-ipchanger) command line tool which should be very simple to use. As for the client itself, there is no way except to look around the internet for the old installer and hope that it doesn't contain viruses. It is always a good idea to check it with [Virus Total](https://www.virustotal.com).
### Stale data
The leaked tarball contains a lot of stale data that you may want to cleanup ahead of time:
- `.tibia` contains the base config and should be configured appropriately
- `dat/owners.dat` contains house owner information and will cause query manager errors the first time the server is run because there is no character data in the database
- `log` contains old log data
- `map` contains world data which is **PERSISTENT** and should probably be replaced with a fresh copy of `origmap`
- `map.bak` contains map backup data (generated from `map` by some external tool)
- `usr` contains old character data
- `usr.bak` contains character backup data (generated from `usr` by some external tool)
- `save/game.pid` is used to prevent multiple instances of the game server from running at the same time and will linger if the process doesn't exit gracefully -- should be removed whenever **needed** to allow the server to properly startup
> The server won't create sub-directories like `usr/01` which will result in saving/loading errors. You'll need to recreate them manually with `mkdir -p {00..99}`.
### Prepare game files
```
tar -xzf ./tibia-game.tarball.tar.gz ./tibia-game # extract game files
cp game ./tibia-game/bin/game # replace old game binary with newly compiled one
cp tibia.pem ./tibia-game/tibia.pem # copy RSA private key
```
### Setup service user and game files
The default service config will assume game files are in `/opt/tibia/game`.
```
useradd -r -M tibia-game # create user that will run the service
mkdir -p /opt/tibia/game # create directory that will hold game files
cp -r ./tibia-game/* /opt/tibia/game # copy game files into /opt/tibia/game
chown -R tibia-game:tibia-game /opt/tibia/game # change game files ownership to newly created user
```
### Install service
```
cp tibia-game.service /etc/systemd/system # copy service configuration into place
systemctl daemon-reload # reload configuration files
systemctl enable tibia-game.service # enable service
systemctl start tibia-game.service # start service
```
### Check service
```
systemctl status tibia-game.service # show service status
journalctl -n 100 -f -u tibia-game.service # show last 100 log lines
```
### Ownership and permission problems
Unexpected errors may arise from invalid file ownership and permissions. You should always make sure that game files have the appropriate read-write-execute permissions and that are owned by the user running the game binary. I won't discuss this topic here but you may find plenty of information either in the manual (`man chmod`, `man chown`) or the internet.
> Extra Security: Files with sensitive data like `tibia.pem` should have 0600 permissions to make sure it is only accessed by the assigned user.
## Comparison with OpenTibia
### Performance
The application is well designed and I'd expect the main thread to have comparable performance to OpenTibia distros. The problem is that each connection will spawn a communication thread, each with its own stack (hardcoded to 64KB) and a few extra system resources for bookkeeping. They should have negligible runtime due to constant I/O but if we consider a high volume, CPU performance would surely be impacted with the constant context switching, nevermind the constant instruction and data cache thrashing.
Making connection management asynchronous would probably allow a higher number of connections with better performance but would also require some design changes as the communication threads will also handle authentication which involves reaching out to the query manager which also performs I/O.
### Customizability
If we're talking about the executable itself, then the imagination is the limit. If we're talking about external files/scripts, then you'll find that changes are strictly limited to existing game mechanics. The level of customizability of OpenTibia servers are a lot higher with custom Lua scripts, etc...
Modifying original files shouldn't be too difficult with a text editor but having a specialized tool like a map editor will make a huge difference when trying to modify the map particularly.
## Why
I've been thinking about different server designs lately, and at the start of the year, I had setup a decompilation project for the leaked binary to see if would give me any insights. To my surprise it had debug symbols which made all the difference and kinda got me hooked. I knew I'd want to fully decompile it at some point but mostly for introspection.
I still visit OTLand every once in a while, and around May of this year, there was a thread advertising a server using some modified version of the 7.7 leak, which quickly turned into a shit show. It got me wondering why hadn't anyone released anything related to this leak **AT ALL**, and as the depressing as it may sound, there is only one answer: the OpenTibia **community** is pretty much dead. People gate-keeping or selling features/bug-fixes, abusing known bugs to extort server owners. Entitled users that can't get anything working without help while also extorting players with their low quality servers. A pathetic server list that requires advertisement fees to even display servers past a certain amount of players. It is a dread scenario all across.
To break out of this shitty ass trend, I knew from the beginning that I'd release it all with no strings attached. It may not be in the best possible shape but it will give an idea on how earlier Tibia servers worked and may even serve as inspiration for future server designs.

299
src/game/src/common.hh Normal file
View file

@ -0,0 +1,299 @@
#ifndef TIBIA_COMMON_HH_
#define TIBIA_COMMON_HH_ 1
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <algorithm>
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
typedef uintptr_t uintptr;
typedef size_t usize;
#define STATIC_ASSERT(expr) static_assert((expr), #expr)
#define NARRAY(arr) (int)(sizeof(arr) / sizeof(arr[0]))
#define ISPOW2(x) ((x) != 0 && ((x) & ((x) - 1)) == 0)
#define KB(x) ((usize)(x) << 10)
#define MB(x) ((usize)(x) << 20)
#define GB(x) ((usize)(x) << 30)
#if !OS_WINDOWS && !OS_LINUX
# if defined(_WIN32)
# define OS_WINDOWS 1
# elif defined(__linux__) || defined(__gnu_linux__)
# define OS_LINUX 1
# else
# error "Operating system not supported."
# endif
#endif
#if !COMPILER_MSVC && !COMPILER_GCC && !COMPILER_CLANG
# if defined(_MSC_VER)
# define COMPILER_MSVC 1
# elif defined(__GNUC__)
# define COMPILER_GCC 1
# elif defined(__clang__)
# define COMPILER_CLANG 1
# endif
#endif
#if COMPILER_GCC || COMPILER_CLANG
# define ATTR_FALLTHROUGH __attribute__((fallthrough))
# define ATTR_PRINTF(x, y) __attribute__((format(printf, x, y)))
#else
# define ATTR_FALLTHROUGH
# define ATTR_PRINTF(x, y)
#endif
#if COMPILER_MSVC
# define TRAP() __debugbreak()
#elif COMPILER_GCC || COMPILER_CLANG
# define TRAP() __builtin_trap()
#else
# define TRAP() abort()
#endif
#define ASSERT_ALWAYS(expr) if(!(expr)) { TRAP(); }
#if ENABLE_ASSERTIONS
# define ASSERT(expr) ASSERT_ALWAYS(expr)
#else
# define ASSERT(expr) ((void)(expr))
#endif
// NOTE(fusion): The server will only compile on Linux due to a few Linux specific
// features being used. Making it compile on Windows shouldn't be too difficult but
// would require a few design changes.
STATIC_ASSERT(OS_LINUX);
#include <errno.h>
#include <unistd.h>
// NOTE(fusion): This is the member name for the thread id in `struct sigevent`
// when `sigev_notify` is `SIGEV_THREAD_ID` but for whatever reason glibc doesn't
// define it.
#ifndef sigev_notify_thread_id
# define sigev_notify_thread_id _sigev_un._tid
#endif
// Constants
// =============================================================================
// TODO(fusion): There are many constants that are hardcoded as decompilation
// artifacts. We should define them here and use when appropriate. It is not
// as simple because I've been using `NARRAY` in some cases and they're used
// essentially everywhere.
//#define MAX_NAME 30 // used with most short strings (should replace MAX_IDENT_LENGTH too)
//#define MAX_IPADDRESS 16
//#define MAX_BUDDIES 100
//#define MAX_SKILLS 25
//#define MAX_SPELLS 256
//#define MAX_QUESTS 500
#define MAX_DEPOTS 9
//#define MAX_OPEN_CONTAINERS 16
#define MAX_SPELL_SYLLABLES 10
// shm.cc
// =============================================================================
void StartGame(void);
void CloseGame(void);
void EndGame(void);
bool LoginAllowed(void);
bool GameRunning(void);
bool GameStarting(void);
bool GameEnding(void);
pid_t GetGameProcessID(void);
pid_t GetGameThreadID(void);
int GetPrintlogPosition(void);
char *GetPrintlogLine(int Line);
void IncrementObjectCounter(void);
void DecrementObjectCounter(void);
uint32 GetObjectCounter(void);
void IncrementPlayersOnline(void);
void DecrementPlayersOnline(void);
int GetPlayersOnline(void);
void IncrementNewbiesOnline(void);
void DecrementNewbiesOnline(void);
int GetNewbiesOnline(void);
void SetRoundNr(uint32 RoundNr);
uint32 GetRoundNr(void);
void SetCommand(int Command, char *Text);
int GetCommand(void);
char *GetCommandBuffer(void);
void InitSHM(bool Verbose);
void ExitSHM(void);
void InitSHMExtern(bool Verbose);
void ExitSHMExtern(void);
// strings.cc
// =============================================================================
const char *AddStaticString(const char *String);
uint32 AddDynamicString(const char *String);
const char *GetDynamicString(uint32 Number);
void DeleteDynamicString(uint32 Number);
void CleanupDynamicStrings(void);
void InitStrings(void);
void ExitStrings(void);
bool IsCountable(const char *s);
const char *Plural(const char *s, int Count);
const char *SearchForWord(const char *Pattern, const char *Text);
const char *SearchForNumber(int Count, const char *Text);
bool MatchString(const char *Pattern, const char *String);
void AddSlashes(char *Destination, const char *Source);
void Trim(char *Text);
void Trim(char *Destination, const char *Source);
char *Capitals(char *Text);
// time.cc
// =============================================================================
extern uint32 RoundNr;
extern uint32 ServerMilliseconds;
struct tm GetLocalTimeTM(time_t t);
int64 GetClockMonotonicMS(void);
void GetRealTime(int *Hour, int *Minute);
void GetTime(int *Hour, int *Minute);
void GetDate(int *Year, int *Cycle, int *Day);
void GetAmbiente(int *Brightness, int *Color);
uint32 GetRoundAtTime(int Hour, int Minute);
uint32 GetRoundForNextMinute(void);
// utils.cc
// =============================================================================
typedef void TErrorFunction(const char *Text);
typedef void TPrintFunction(int Level, const char *Text);
void SetErrorFunction(TErrorFunction *Function);
void SetPrintFunction(TPrintFunction *Function);
void SilentHandler(const char *Text);
void SilentHandler(int Level, const char *Text);
void LogFileHandler(const char *Text);
void LogFileHandler(int Level, const char *Text);
void error(const char *Text, ...) ATTR_PRINTF(1, 2);
void print(int Level, const char *Text, ...) ATTR_PRINTF(2, 3);
int random(int Min, int Max);
bool FileExists(const char *FileName);
const char *GetSignalDescription(int SigNr);
const char *GetErrorDescription(int SigNr);
bool isSpace(int c);
bool isAlpha(int c);
bool isEngAlpha(int c);
bool isDigit(int c);
int toLower(int c);
int toUpper(int c);
char *strLower(char *s);
char *strUpper(char *s);
int stricmp(const char *s1, const char *s2, int Max = INT_MAX);
char *findFirst(char *s, char c);
char *findLast(char *s, char c);
bool CheckBitIndex(int BitSetBytes, int Index);
bool CheckBit(uint8 *BitSet, int Index);
void SetBit(uint8 *BitSet, int Index);
void ClearBit(uint8 *BitSet, int Index);
template<typename T>
void RandomShuffle(T *Buffer, int Size){
if(Buffer == NULL){
error("RandomShuffle: Buffer ist NULL.\n");
return;
}
int Max = Size - 1;
for(int Min = 0; Min < Max; Min += 1){
int Swap = random(Min, Max);
if(Swap != Min){
std::swap(Buffer[Min], Buffer[Swap]);
}
}
}
struct TReadStream {
// VIRTUAL FUNCTIONS
// =================
virtual bool readFlag(void); // VTABLE[0]
virtual uint8 readByte(void) = 0; // VTABLE[1]
virtual uint16 readWord(void); // VTABLE[2]
virtual uint32 readQuad(void); // VTABLE[3]
virtual void readString(char *Buffer, int MaxLength); // VTABLE[4]
virtual void readBytes(uint8 *Buffer, int Count); // VTABLE[5]
virtual bool eof(void) = 0; // VTABLE[6]
virtual void skip(int Count) = 0; // VTABLE[7]
};
struct TReadBuffer: TReadStream {
TReadBuffer(const uint8 *Data, int Size);
// VIRTUAL FUNCTIONS
// =================
uint8 readByte(void) override;
uint16 readWord(void) override;
uint32 readQuad(void) override;
void readBytes(uint8 *Buffer, int Count) override;
bool eof(void) override;
void skip(int Count) override;
// DATA
// =================
const uint8 *Data;
int Size;
int Position;
};
struct TWriteStream {
// VIRTUAL FUNCTIONS
// =================
virtual void writeFlag(bool Flag); // VTABLE[0]
virtual void writeByte(uint8 Byte) = 0; // VTABLE[1]
virtual void writeWord(uint16 Word); // VTABLE[2]
virtual void writeQuad(uint32 Quad); // VTABLE[3]
virtual void writeString(const char *String); // VTABLE[4]
virtual void writeBytes(const uint8 *Buffer, int Count); // VTABLE[5]
};
struct TWriteBuffer: TWriteStream {
TWriteBuffer(uint8 *Data, int Size);
// VIRTUAL FUNCTIONS
// =================
void writeByte(uint8 Byte) override;
void writeWord(uint16 Word) override;
void writeQuad(uint32 Quad) override;
void writeBytes(const uint8 *Buffer, int Count) override;
// DATA
// =================
uint8 *Data;
int Size;
int Position;
};
struct TDynamicWriteBuffer: TWriteBuffer {
TDynamicWriteBuffer(int InitialSize);
void resizeBuffer(void);
// VIRTUAL FUNCTIONS
// =================
void writeByte(uint8 Byte) override;
void writeWord(uint16 Word) override;
void writeQuad(uint32 Quad) override;
void writeBytes(const uint8 *Buffer, int Count) override;
// TODO(fusion): Appended virtual functions. These are not in the base class
// VTABLE which can be problematic if we intend to use polymorphism, although
// that doesn't seem to be case.
virtual ~TDynamicWriteBuffer(void); // VTABLE[6]
// Duplicate destructor that also calls operator delete. // VTABLE[7]
};
#endif //TIBIA_COMMON_HH_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,66 @@
#ifndef TIBIA_COMMUNICATION_HH_
#define TIBIA_COMMUNICATION_HH_ 1
#include "common.hh"
#include "connections.hh"
struct TPlayerData;
enum{
LOGIN_MESSAGE_ERROR = SV_CMD_LOGIN_ERROR,
LOGIN_MESSAGE_PREMIUM = SV_CMD_LOGIN_PREMIUM,
LOGIN_MESSAGE_WAITINGLIST = SV_CMD_LOGIN_WAITINGLIST,
};
struct TWaitinglistEntry {
TWaitinglistEntry *Next;
char Name[30];
uint32 NextTry;
bool FreeAccount;
bool Newbie;
bool Sleeping;
};
void GetCommunicationThreadStack(int *StackNumber, void **Stack);
void AttachCommunicationThreadStack(int StackNumber);
void ReleaseCommunicationThreadStack(int StackNumber);
void InitCommunicationThreadStacks(void);
void ExitCommunicationThreadStacks(void);
bool LagDetected(void);
void NetLoad(int Amount, bool Send);
void NetLoadSummary(void);
void NetLoadCheck(void);
void InitLoadHistory(void);
void ExitLoadHistory(void);
bool WriteToSocket(TConnection *Connection, uint8 *Buffer, int Size, int MaxSize);
bool SendLoginMessage(TConnection *Connection, int Type, const char *Message, int WaitingTime);
bool SendData(TConnection *Connection);
bool GetWaitinglistEntry(const char *Name, uint32 *NextTry, bool *FreeAccount, bool *Newbie);
void InsertWaitinglistEntry(const char *Name, uint32 NextTry, bool FreeAccount, bool Newbie);
void DeleteWaitinglistEntry(const char *Name);
int GetWaitinglistPosition(const char *Name, bool FreeAccount, bool Newbie);
int CheckWaitingTime(const char *Name, TConnection *Connection, bool FreeAccount, bool Newbie);
int ReadFromSocket(TConnection *Connection, uint8 *Buffer, int Size);
bool CallGameThread(TConnection *Connection);
bool CheckConnection(TConnection *Connection);
TPlayerData *PerformRegistration(TConnection *Connection, char *PlayerName,
uint32 AccountID, const char *PlayerPassword, bool GamemasterClient);
bool HandleLogin(TConnection *Connection);
bool ReceiveCommand(TConnection *Connection);
void IncrementActiveConnections(void);
void DecrementActiveConnections(void);
void CommunicationThread(int Socket);
int HandleConnection(void *Data);
bool OpenSocket(void);
int AcceptorThreadLoop(void *Unused);
void CheckThreadlibVersion(void);
void InitCommunication(void);
void ExitCommunication(void);
#endif //TIBIA_COMMUNICATION_HH_

280
src/game/src/config.cc Normal file
View file

@ -0,0 +1,280 @@
#include "config.hh"
#include "script.hh"
char BINPATH[4096];
char DATAPATH[4096];
char LOGPATH[4096];
char MAPPATH[4096];
char MONSTERPATH[4096];
char NPCPATH[4096];
char ORIGMAPPATH[4096];
char SAVEPATH[4096];
char USERPATH[4096];
int SHMKey;
int AdminPort;
int GamePort;
int QueryManagerPort;
char AdminAddress[16];
char GameAddress[16];
char QueryManagerAddress[16];
char QueryManagerAdminPW[9];
char QueryManagerGamePW[9];
char QueryManagerWebPW[9];
int DebugLevel;
bool PrivateWorld;
TWorldType WorldType;
char WorldName[30];
int MaxPlayers;
int MaxNewbies;
int PremiumPlayerBuffer;
int PremiumNewbieBuffer;
int Beat;
int RebootTime;
TDatabaseSettings ADMIN_DATABASE;
TDatabaseSettings VOLATILE_DATABASE;
TDatabaseSettings WEB_DATABASE;
TDatabaseSettings FORUM_DATABASE;
TDatabaseSettings MANAGER_DATABASE;
int NumberOfQueryManagers;
TQueryManagerSettings QUERY_MANAGER[10];
static char PasswordKey[9] = "Pm-,o%yD";
static void DisguisePassword(char *Password, char *Key){
if(Password == NULL){
throw "password is null";
}
if(Key == NULL){
throw "key for disguising password is null";
}
usize KeyLen = strlen(Key);
usize PasswordLen = strlen(Password);
if(KeyLen < PasswordLen){
throw "key for disguising password is too short";
}
for(usize Index = 0; Index < PasswordLen; Index += 1){
Password[Index] = (Key[Index] - Password[Index] + 0x5E) % 0x5E + 0x21;
}
}
void ReadConfig(void){
// TODO(fusion): We're not properly initializing these values, specially the
// `TDatabaseSettings` ones. It is probably not that big of a deal anyway since
// we only call this function once at startup and all this memory should be zero
// initialized.
PrivateWorld = false;
strncpy(GameAddress, "0.0.0.0", 8);
SHMKey = 0;
QueryManagerPort = 0;
strncpy(QueryManagerAddress, "0.0.0.0", 8);
AdminPort = 0;
GamePort = 0;
strncpy(AdminAddress, "0.0.0.0", 8);
MaxPlayers = 0;
DebugLevel = 1;
WorldType = NORMAL;
BINPATH[0] = 0;
DATAPATH[0] = 0;
LOGPATH[0] = 0;
MAPPATH[0] = 0;
MONSTERPATH[0] = 0;
NPCPATH[0] = 0;
ORIGMAPPATH[0] = 0;
SAVEPATH[0] = 0;
USERPATH[0] = 0;
QueryManagerAdminPW[0] = 0;
QueryManagerGamePW[0] = 0;
QueryManagerWebPW[0] = 0;
MaxNewbies = 0;
PremiumPlayerBuffer = 0;
PremiumNewbieBuffer = 0;
NumberOfQueryManagers = 0;
Beat = 200;
RebootTime = 540;
ADMIN_DATABASE.Database[0] = 0;
VOLATILE_DATABASE.Database[0] = 0;
WEB_DATABASE.Database[0] = 0;
FORUM_DATABASE.Database[0] = 0;
MANAGER_DATABASE.Database[0] = 0;
char FileName[4096];
#if 0
if(const char *Home = getenv("home")){
snprintf(FileName, sizeof(FileName), "%s/.tibia", Home);
}else if(const char *Home = getenv("HOME")){
snprintf(FileName, sizeof(FileName), "%s/.tibia", Home);
}else{
snprintf(FileName, sizeof(FileName), ".tibia");
}
#else
snprintf(FileName, sizeof(FileName), ".tibia");
#endif
if(!FileExists(FileName)){
throw "cannot find config-file";
}
TReadScriptFile Script;
Script.open(FileName);
while(true){
Script.nextToken();
if(Script.Token == ENDOFFILE){
// NOTE(fusion): This is the only graceful exit point of the function.
// Errors are transmitted back through exceptions.
Script.close();
return;
}
char Identifier[MAX_IDENT_LENGTH];
strcpy(Identifier, Script.getIdentifier());
Script.readSymbol('=');
// TODO(fusion): Ughh... Get rid of all `strcpy`s. A malicious configuration
// file could do a lot of damage.
if(strcmp(Identifier, "binpath") == 0){
strcpy(BINPATH, Script.readString());
}else if(strcmp(Identifier, "mappath") == 0){
strcpy(MAPPATH, Script.readString());
}else if(strcmp(Identifier, "origmappath") == 0){
strcpy(ORIGMAPPATH, Script.readString());
}else if(strcmp(Identifier, "datapath") == 0){
strcpy(DATAPATH, Script.readString());
}else if(strcmp(Identifier, "monsterpath") == 0){
strcpy(MONSTERPATH, Script.readString());
}else if(strcmp(Identifier, "npcpath") == 0){
strcpy(NPCPATH, Script.readString());
}else if(strcmp(Identifier, "userpath") == 0){
strcpy(USERPATH, Script.readString());
}else if(strcmp(Identifier, "logpath") == 0){
strcpy(LOGPATH, Script.readString());
}else if(strcmp(Identifier, "savepath") == 0){
strcpy(SAVEPATH, Script.readString());
}else if(strcmp(Identifier, "shm") == 0){
SHMKey = Script.readNumber();
}else if(strcmp(Identifier, "adminport") == 0){
AdminPort = Script.readNumber();
}else if(strcmp(Identifier, "adminaddress") == 0){
strcpy(AdminAddress, Script.readString());
}else if(strcmp(Identifier, "querymanagerport") == 0){
QueryManagerPort = Script.readNumber();
}else if(strcmp(Identifier, "querymanageraddress") == 0){
strcpy(QueryManagerAddress, Script.readString());
}else if(strcmp(Identifier, "querymanageradminpw") == 0){
strcpy(QueryManagerAdminPW, Script.readString());
}else if(strcmp(Identifier, "querymanagergamepw") == 0){
strcpy(QueryManagerGamePW, Script.readString());
}else if(strcmp(Identifier, "querymanagerwebpw") == 0){
strcpy(QueryManagerWebPW, Script.readString());
}else if(strcmp(Identifier, "debuglevel") == 0){
DebugLevel = Script.readNumber();
}else if(strcmp(Identifier, "state") == 0){
PrivateWorld = (strcmp(Script.readIdentifier(), "private") == 0);
}else if(strcmp(Identifier, "world") == 0){
strcpy(WorldName, Script.readString());
}else if(strcmp(Identifier, "beat") == 0){
Beat = Script.readNumber();
}else if(strcmp(Identifier, "admindatabase") == 0){
Script.readSymbol('(');
strcpy(ADMIN_DATABASE.Product, Script.readIdentifier());
Script.readSymbol(',');
strcpy(ADMIN_DATABASE.Database, Script.readString());
Script.readSymbol(',');
strcpy(ADMIN_DATABASE.Login, Script.readString());
Script.readSymbol(',');
strcpy(ADMIN_DATABASE.Password, Script.readString());
DisguisePassword(ADMIN_DATABASE.Password, PasswordKey);
Script.readSymbol(',');
strcpy(ADMIN_DATABASE.Host, Script.readString());
Script.readSymbol(',');
strcpy(ADMIN_DATABASE.Port, Script.readString());
Script.readSymbol(')');
}else if(strcmp(Identifier, "volatiledatabase") == 0){
Script.readSymbol('(');
strcpy(VOLATILE_DATABASE.Product, Script.readIdentifier());
Script.readSymbol(',');
strcpy(VOLATILE_DATABASE.Database, Script.readString());
Script.readSymbol(',');
strcpy(VOLATILE_DATABASE.Login, Script.readString());
Script.readSymbol(',');
strcpy(VOLATILE_DATABASE.Password, Script.readString());
DisguisePassword(VOLATILE_DATABASE.Password, PasswordKey);
Script.readSymbol(',');
strcpy(VOLATILE_DATABASE.Host, Script.readString());
Script.readSymbol(',');
strcpy(VOLATILE_DATABASE.Port, Script.readString());
Script.readSymbol(')');
}else if(strcmp(Identifier, "webdatabase") == 0){
Script.readSymbol('(');
strcpy(WEB_DATABASE.Product, Script.readIdentifier());
Script.readSymbol(',');
strcpy(WEB_DATABASE.Database, Script.readString());
Script.readSymbol(',');
strcpy(WEB_DATABASE.Login, Script.readString());
Script.readSymbol(',');
strcpy(WEB_DATABASE.Password, Script.readString());
DisguisePassword(WEB_DATABASE.Password, PasswordKey);
Script.readSymbol(',');
strcpy(WEB_DATABASE.Host, Script.readString());
Script.readSymbol(',');
strcpy(WEB_DATABASE.Port, Script.readString());
Script.readSymbol(')');
}else if(strcmp(Identifier, "forumdatabase") == 0){
Script.readSymbol('(');
strcpy(FORUM_DATABASE.Product, Script.readIdentifier());
Script.readSymbol(',');
strcpy(FORUM_DATABASE.Database, Script.readString());
Script.readSymbol(',');
strcpy(FORUM_DATABASE.Login, Script.readString());
Script.readSymbol(',');
strcpy(FORUM_DATABASE.Password, Script.readString());
DisguisePassword(FORUM_DATABASE.Password, PasswordKey);
Script.readSymbol(',');
strcpy(FORUM_DATABASE.Host, Script.readString());
Script.readSymbol(',');
strcpy(FORUM_DATABASE.Port, Script.readString());
Script.readSymbol(')');
}else if(strcmp(Identifier, "managerdatabase") == 0){
Script.readSymbol('(');
strcpy(MANAGER_DATABASE.Product, Script.readIdentifier());
Script.readSymbol(',');
strcpy(MANAGER_DATABASE.Database, Script.readString());
Script.readSymbol(',');
strcpy(MANAGER_DATABASE.Login, Script.readString());
Script.readSymbol(',');
strcpy(MANAGER_DATABASE.Password, Script.readString());
DisguisePassword(MANAGER_DATABASE.Password, PasswordKey);
Script.readSymbol(',');
strcpy(MANAGER_DATABASE.Host, Script.readString());
Script.readSymbol(',');
strcpy(MANAGER_DATABASE.Port, Script.readString());
Script.readSymbol(')');
}else if(strcmp(Identifier, "querymanager") == 0){
Script.readSymbol('{');
do{
if(NumberOfQueryManagers >= NARRAY(QUERY_MANAGER)){
Script.error("Cannot handle more query managers");
}
Script.readSymbol('(');
strcpy(QUERY_MANAGER[NumberOfQueryManagers].Host, Script.readString());
Script.readSymbol(',');
QUERY_MANAGER[NumberOfQueryManagers].Port = Script.readNumber();
Script.readSymbol(',');
strcpy(QUERY_MANAGER[NumberOfQueryManagers].Password, Script.readString());
DisguisePassword(QUERY_MANAGER[NumberOfQueryManagers].Password, PasswordKey);
Script.readSymbol(')');
NumberOfQueryManagers += 1;
}while(Script.readSpecial() != '}');
}else{
// TODO(fusion):
//error("Unknown configuration key \"%s\"", Identifier);
}
}
}

61
src/game/src/config.hh Normal file
View file

@ -0,0 +1,61 @@
#ifndef TIBIA_CONFIG_HH_
#define TIBIA_CONFIG_HH_ 1
#include "common.hh"
#include "enums.hh"
struct TDatabaseSettings {
char Product[30];
char Database[30];
char Login[30];
char Password[30];
char Host[30];
char Port[6];
};
struct TQueryManagerSettings {
char Host[50];
int Port;
char Password[30];
};
extern char BINPATH[4096];
extern char DATAPATH[4096];
extern char LOGPATH[4096];
extern char MAPPATH[4096];
extern char MONSTERPATH[4096];
extern char NPCPATH[4096];
extern char ORIGMAPPATH[4096];
extern char SAVEPATH[4096];
extern char USERPATH[4096];
extern int SHMKey;
extern int AdminPort;
extern int GamePort;
extern int QueryManagerPort;
extern char AdminAddress[16];
extern char GameAddress[16];
extern char QueryManagerAddress[16];
extern char QueryManagerAdminPW[9];
extern char QueryManagerGamePW[9];
extern char QueryManagerWebPW[9];
extern int DebugLevel;
extern bool PrivateWorld;
extern TWorldType WorldType;
extern char WorldName[30];
extern int MaxPlayers;
extern int MaxNewbies;
extern int PremiumPlayerBuffer;
extern int PremiumNewbieBuffer;
extern int Beat;
extern int RebootTime;
extern TDatabaseSettings ADMIN_DATABASE;
extern TDatabaseSettings VOLATILE_DATABASE;
extern TDatabaseSettings WEB_DATABASE;
extern TDatabaseSettings FORUM_DATABASE;
extern TDatabaseSettings MANAGER_DATABASE;
extern int NumberOfQueryManagers;
extern TQueryManagerSettings QUERY_MANAGER[10];
void ReadConfig(void);
#endif //TIBIA_CONFIG_HH_

557
src/game/src/connections.cc Normal file
View file

@ -0,0 +1,557 @@
#include "connections.hh"
#include "cr.hh"
#include "info.hh"
#include "threads.hh"
#include "writer.hh"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
static Semaphore ConnectionMutex(1);
static int ConnectionIterator;
static TConnection Connections[MAX_CONNECTIONS];
// TConnection
// =============================================================================
TConnection::TConnection(void){
this->State = CONNECTION_FREE;
}
void TConnection::Process(void){
if(this->InGame()){
uint32 LastCommand = (RoundNr - this->TimeStamp);
if(LastCommand == 30 || LastCommand == 60){
SendPing(this);
}
uint32 LastAction = (RoundNr - this->TimeStampAction);
if(LastAction == 900 && !CheckRight(this->CharacterID, NO_LOGOUT_BLOCK)){
SendMessage(this, TALK_ADMIN_MESSAGE,
"You have been idle for %d minutes. You will be disconnected"
" in one minute if you are still idle then.", 15);
}
if(LastAction >= 960 && !CheckRight(this->CharacterID, NO_LOGOUT_BLOCK)){
this->Logout(0, true);
}else if(!GameRunning() || !this->ConnectionIsOk || (LastCommand >= 90)){
this->Logout(0, false);
}
}else if(this->State == CONNECTION_LOGIN){
if(!GameRunning() || !this->ConnectionIsOk){
this->Disconnect();
}
}else if(this->State == CONNECTION_LOGOUT){
// NOTE(fusion): `TimeStamp` has the logout round which is set by
// `TConnection::Logout`.
if(!GameRunning() || !this->ConnectionIsOk || this->TimeStamp <= RoundNr){
this->Disconnect();
}
}
}
void TConnection::ResetTimer(int Command){
if(this->InGame()){
this->TimeStamp = RoundNr;
if(Command != CL_CMD_PING
&& Command != CL_CMD_GO_STOP
&& Command != CL_CMD_CANCEL
&& Command != CL_CMD_REFRESH_FIELD
&& Command != CL_CMD_REFRESH_CONTAINER){
this->TimeStampAction = RoundNr;
}
}
}
void TConnection::EmergencyPing(void){
if(this->InGame()){
uint32 LastCommand = (RoundNr - this->TimeStamp);
if(LastCommand < 80){
// TODO(fusion): This is only called by `NetLoadCheck`, when it detects
// lag, which can only happen after some set number of rounds, usually
// higher than 100. This is all to say this subtraction below is very
// unlikely to wrap. Nevertheless, we should also have some helper
// functions to do saturating addition or subtraction for both signed
// and unsigned integers.
this->TimeStamp = RoundNr - 100;
}
SendPing(this);
}
}
pid_t TConnection::GetThreadID(void){
if(this->State == CONNECTION_FREE){
error("TConnection::GetThreadID: Verbindung ist nicht zugewiesen.\n");
return 0;
}
return this->ThreadID;
}
bool TConnection::SetLoginTimer(int Timeout){
if(this->State == CONNECTION_FREE){
error("TConnection::SetLoginTimer: Verbindung ist nicht zugewiesen.\n");
return false;
}
if(this->LoginTimer != 0){
error("TConnection::SetLoginTimer: Timer already set.\n");
return false;
}
struct sigevent SigEvent = {};
SigEvent.sigev_notify = SIGEV_THREAD_ID;
SigEvent.sigev_signo = SIGALRM;
SigEvent.sigev_notify_thread_id = this->ThreadID;
if(timer_create(CLOCK_MONOTONIC, &SigEvent, &this->LoginTimer) == -1){
error("TConnection::SetLoginTimer: Failed to create timer: (%d) %s\n",
errno, GetErrorDescription(errno));
return false;
}
struct itimerspec TimerSpec = {};
TimerSpec.it_value.tv_sec = Timeout;
if(timer_settime(this->LoginTimer, 0, &TimerSpec, NULL) == -1){
error("TConnection::SetLoginTimer: Failed to start timer: (%d) %s\n",
errno, GetErrorDescription(errno));
return false;
}
return true;
}
void TConnection::StopLoginTimer(void){
if(this->State == CONNECTION_FREE){
error("TConnection::SetLoginTimer: Verbindung ist nicht zugewiesen.\n");
return;
}
if(this->LoginTimer == 0){
error("TConnection::StopLoginTimer: Timer not set.\n");
return;
}
if(timer_delete(this->LoginTimer) == -1){
error("TConnection::StopLoginTimer: Failed to delete timer: (%d) %s\n",
errno, GetErrorDescription(errno));
}
this->LoginTimer = 0;
}
int TConnection::GetSocket(void){
if(this->State == CONNECTION_FREE || this->State == CONNECTION_ASSIGNED){
error("TConnection::GetSocket: Verbindung ist nicht angeschlossen.\n");
return -1;
}
return this->Socket;
}
const char *TConnection::GetIPAddress(void){
if(this->State == CONNECTION_FREE || this->State == CONNECTION_ASSIGNED){
error("TConnection::GetIPAddress: Verbindung ist nicht angeschlossen.\n");
return "Unknown";
}
return this->IPAddress;
}
void TConnection::Free(void){
this->State = CONNECTION_FREE;
}
void TConnection::Assign(void){
if(this->State != CONNECTION_FREE){
error("TConnection::Assign: Verbindung ist nicht frei.\n");
}
this->State = CONNECTION_ASSIGNED;
this->ThreadID = gettid();
this->LoginTimer = 0;
}
void TConnection::Connect(int Socket){
if(this->State != CONNECTION_ASSIGNED){
error("TConnection::Connect: Verbindung ist keinem Thread zugewiesen.\n");
}
this->State = CONNECTION_CONNECTED;
this->Socket = Socket;
this->ConnectionIsOk = true;
this->ClosingIsDelayed = true;
this->RandomSeed = rand();
struct sockaddr_in RemoteAddr;
socklen_t RemoteAddrLen = sizeof(RemoteAddr);
getpeername(Socket, (struct sockaddr*)&RemoteAddr, &RemoteAddrLen);
strcpy(this->IPAddress, inet_ntoa(RemoteAddr.sin_addr));
}
void TConnection::Login(void){
if(this->State != CONNECTION_CONNECTED){
error("TConnection::Connect: Ungültiger Verbindungs-Zustand %d.\n", this->State);
}
this->State = CONNECTION_LOGIN;
}
bool TConnection::JoinGame(TReadBuffer *Buffer){
if(this->State != CONNECTION_LOGIN){
error("TConnection::JoinGame: Ungültiger Verbindungszustand %d.\n", this->State);
}
this->ClearKnownCreatureTable(false);
try{
this->TerminalType = (int)Buffer->readWord();
this->TerminalVersion = (int)Buffer->readWord();
this->CharacterID = Buffer->readQuad();
}catch(const char *str){
error("TConnection::JoinGame: Fehler beim Auslesen des Puffers (%s).\n", str);
}
if(this->TerminalType != 1 && this->TerminalType != 2){
error("TConnection::JoinGame: Unbekannter Terminal-Typ %d.\n", this->TerminalType);
return false;
}
this->TerminalOffsetX = 8;
this->TerminalOffsetY = 6;
this->TerminalWidth = 18;
this->TerminalHeight = 14;
TPlayer *Player = ::GetPlayer(this->CharacterID);
if(Player == NULL){
Player = new TPlayer(this, this->CharacterID);
if(Player->ConstructError != NOERROR){
delete Player;
return false;
}
}else{
if(Player->IsDead){
Log("game", "Spieler %s ist gerade am Sterben - Einloggen gescheitert.\n", Player->Name);
DecreasePlayerPoolSlotSticky(this->CharacterID);
return false;
}
if(Player->LoggingOut && Player->LogoutPossible() == 0){
Log("game", "Spieler %s loggt gerade aus - Einloggen gescheitert.\n", Player->Name);
DecreasePlayerPoolSlotSticky(this->CharacterID);
return false;
}
TConnection *OldConnection = Player->Connection;
Player->ClearConnection();
if(OldConnection != NULL){
OldConnection->CharacterID = 0;
OldConnection->Logout(0, true);
}
DecrementIsOnlineOrder(this->CharacterID);
Player->TakeOver(this);
}
strcpy(this->Name, Player->Name);
this->TimeStamp = RoundNr;
this->TimeStampAction = RoundNr;
return true;
}
void TConnection::EnterGame(void){
if(this->State != CONNECTION_LOGIN){
error("TConnection::EnterGame: Ungültiger Verbindungszustand %d.\n", this->State);
}
this->State = CONNECTION_GAME;
}
void TConnection::Die(void){
if(this->State == CONNECTION_GAME){
this->State = CONNECTION_DEAD;
}
}
void TConnection::Logout(int Delay, bool StopFight){
if(!this->InGame() && this->State != CONNECTION_LOGOUT){
error("TConnection::Logout: Ungültiger Verbindungszustand %d.\n", this->State);
}
this->State = CONNECTION_LOGOUT;
if(this->CharacterID != 0){
TPlayer *Player = ::GetPlayer(this->CharacterID);
if(Player != NULL){
Player->ClearConnection();
Player->StartLogout(false, StopFight);
}
}
if(Delay < 0){
Delay = 0;
}
this->CharacterID = 0;
this->TimeStamp = RoundNr + (uint32)Delay;
this->ClosingIsDelayed = false;
}
void TConnection::Close(bool Delay){
if(this->State == CONNECTION_FREE || this->State == CONNECTION_ASSIGNED){
error("TConnection::Close: Ungültiger Verbindungszustand %d.\n", this->State);
}
if(this->State == CONNECTION_CONNECTED){
this->State = CONNECTION_DISCONNECTED;
}
this->ConnectionIsOk = false;
this->ClosingIsDelayed = Delay;
}
void TConnection::Disconnect(void){
if(this->State == CONNECTION_FREE || this->State == CONNECTION_ASSIGNED){
error("TConnection::Close: Ungültiger Verbindungszustand %d.\n", this->State);
}
this->ClearKnownCreatureTable(true);
this->ConnectionIsOk = false;
this->State = CONNECTION_DISCONNECTED;
tgkill(GetGameProcessID(), this->ThreadID, SIGHUP);
}
TPlayer *TConnection::GetPlayer(void){
if(!this->Live()){
error("TConnection::GetPlayer: Ungültiger Verbindungszustand %d.\n", this->State);
return NULL;
}
TPlayer *Player = NULL;
if(this->CharacterID != 0){
Player = ::GetPlayer(this->CharacterID);
}
return Player;
}
const char *TConnection::GetName(void){
if(!this->Live()){
error("TConnection::GetName: Ungültiger Verbindungszustand %d.\n", this->State);
return "";
}
return this->Name;
}
void TConnection::GetPosition(int *x, int *y, int *z){
TPlayer *Player = this->GetPlayer();
if(Player != NULL){
*x = Player->posx;
*y = Player->posy;
*z = Player->posz;
}else{
*x = 0;
*y = 0;
*z = 0;
}
}
bool TConnection::IsVisible(int x, int y, int z){
int PlayerX, PlayerY, PlayerZ;
this->GetPosition(&PlayerX, &PlayerY, &PlayerZ);
// TODO(fusion): Have a standalone version of `TCreature::CanSeeFloor`?
if(PlayerZ <= 7){
if(z > 7){
return false;
}
}else{
if(std::abs(PlayerZ - z) > 2){
return false;
}
}
int MinX = (PlayerX - this->TerminalOffsetX) + (PlayerZ - z);
int MinY = (PlayerY - this->TerminalOffsetY) + (PlayerZ - z);
int MaxX = MinX + this->TerminalWidth - 1;
int MaxY = MinY + this->TerminalHeight - 1;
return x >= MinX && x <= MaxX
&& y >= MinY && y <= MaxY;
}
KNOWNCREATURESTATE TConnection::KnownCreature(uint32 ID, bool UpdateFollows){
int EntryIndex = -1;
for(int i = 0; i < NARRAY(this->KnownCreatureTable); i += 1){
if(this->KnownCreatureTable[i].CreatureID == ID){
EntryIndex = i;
break;
}
}
if(EntryIndex == -1){
return KNOWNCREATURE_FREE;
}
KNOWNCREATURESTATE Result = this->KnownCreatureTable[EntryIndex].State;
if(Result == KNOWNCREATURE_OUTDATED && UpdateFollows){
this->KnownCreatureTable[EntryIndex].State = KNOWNCREATURE_UPTODATE;
}
return Result;
}
uint32 TConnection::NewKnownCreature(uint32 NewID){
uint32 OldID = 0;
int EntryIndex = -1;
for(int i = 0; i < NARRAY(this->KnownCreatureTable); i += 1){
if(this->KnownCreatureTable[i].CreatureID == NewID){
OldID = NewID;
EntryIndex = i;
break;
}
}
if(EntryIndex == -1){
for(int i = 0; i < NARRAY(this->KnownCreatureTable); i += 1){
if(this->KnownCreatureTable[i].State == KNOWNCREATURE_FREE){
OldID = this->KnownCreatureTable[i].CreatureID;
EntryIndex = i;
break;
}
}
}
if(EntryIndex == -1){
for(int i = 0; i < NARRAY(this->KnownCreatureTable); i += 1){
TCreature *Creature = GetCreature(this->KnownCreatureTable[i].CreatureID);
if(Creature == NULL || !this->IsVisible(Creature->posx, Creature->posy, Creature->posz)){
OldID = this->KnownCreatureTable[i].CreatureID;
EntryIndex = i;
this->UnchainKnownCreature(OldID);
break;
}
}
}
if(EntryIndex == -1){
print(3, "KnownCreatureTable ausgelastet.\n");
return 0;
}
if(this->KnownCreatureTable[EntryIndex].State != KNOWNCREATURE_FREE){
error("TUserCom::NewKnownCreature: Slot ist nicht gelöscht.\n");
}
this->KnownCreatureTable[EntryIndex].State = KNOWNCREATURE_UPTODATE;
this->KnownCreatureTable[EntryIndex].CreatureID = NewID;
TCreature *Creature = GetCreature(NewID);
if(Creature != NULL){
this->KnownCreatureTable[EntryIndex].Next = Creature->FirstKnowingConnection;
Creature->FirstKnowingConnection = &this->KnownCreatureTable[EntryIndex];
}else{
error("TUserCom::NewKnownCreature: Kreatur %u existiert nicht.\n", NewID);
}
return OldID;
}
void TConnection::ClearKnownCreatureTable(bool Unchain){
for(int i = 0; i < NARRAY(this->KnownCreatureTable); i += 1){
if(Unchain && this->KnownCreatureTable[i].State != KNOWNCREATURE_FREE){
this->UnchainKnownCreature(this->KnownCreatureTable[i].CreatureID);
}
this->KnownCreatureTable[i].State = KNOWNCREATURE_FREE;
this->KnownCreatureTable[i].CreatureID = 0;
this->KnownCreatureTable[i].Connection = this;
}
}
void TConnection::UnchainKnownCreature(uint32 ID){
TCreature *Creature = GetCreature(ID);
if(Creature == NULL){
error("TUserCom::UnchainKnownCreature: Kreatur %u existiert nicht.\n", ID);
return;
}
if(Creature->FirstKnowingConnection == NULL){
error("TUserCom::UnchainKnownCreature: Kreatur %u kennt niemand.\n", ID);
return;
}
TKnownCreature *Prev = NULL;
TKnownCreature *Cur = Creature->FirstKnowingConnection;
while(Cur != NULL){
if(Cur->Connection == this){
break;
}
Prev = Cur;
Cur = Cur->Next;
}
if(Cur == NULL){
error("TUserCom::UnchainKnownCreature: Kreatur %u ist nicht bekannt.\n", ID);
return;
}
Cur->State = KNOWNCREATURE_FREE;
if(Prev == NULL){
Creature->FirstKnowingConnection = Cur->Next;
}else{
Prev->Next = Cur->Next;
}
}
// Connection Utility
// =============================================================================
TConnection *AssignFreeConnection(void){
TConnection *Connection = NULL;
ConnectionMutex.down();
for(int i = 0; i < MAX_CONNECTIONS; i += 1){
if(Connections[i].State == CONNECTION_FREE){
Connection = &Connections[i];
Connection->Assign();
break;
}
}
ConnectionMutex.up();
return Connection;
}
TConnection *GetFirstConnection(void){
ConnectionIterator = 0;
return GetNextConnection();
}
TConnection *GetNextConnection(void){
TConnection *NextConnection = NULL;
while(ConnectionIterator < MAX_CONNECTIONS){
TConnection *Connection = &Connections[ConnectionIterator];
ConnectionIterator += 1;
if(Connection->State != CONNECTION_FREE){
NextConnection = Connection;
break;
}
}
return NextConnection;
}
void ProcessConnections(void){
TConnection *Connection = GetFirstConnection();
while(Connection != NULL){
Connection->Process();
Connection = GetNextConnection();
}
}
void InitConnections(void){
InitSending();
InitReceiving();
ConnectionIterator = 0;
for(int i = 0; i < MAX_CONNECTIONS; i += 1){
Connections[i].State = CONNECTION_FREE;
}
}
void ExitConnections(void){
ExitSending();
ExitReceiving();
}

317
src/game/src/connections.hh Normal file
View file

@ -0,0 +1,317 @@
#ifndef TIBIA_CONNECTIONS_HH_
#define TIBIA_CONNECTIONS_HH_ 1
#include "common.hh"
#include "crypto.hh"
#include "enums.hh"
#include "map.hh"
struct TConnection;
struct TPlayer;
enum ClientCommand: int {
CL_CMD_LOGIN_REQUEST = 10,
CL_CMD_LOGIN = 11,
CL_CMD_LOGOUT = 20,
CL_CMD_PING = 30,
CL_CMD_GO_PATH = 100,
CL_CMD_GO_NORTH = 101,
CL_CMD_GO_EAST = 102,
CL_CMD_GO_SOUTH = 103,
CL_CMD_GO_WEST = 104,
CL_CMD_GO_STOP = 105,
CL_CMD_GO_NORTHEAST = 106,
CL_CMD_GO_SOUTHEAST = 107,
CL_CMD_GO_SOUTHWEST = 108,
CL_CMD_GO_NORTHWEST = 109,
CL_CMD_ROTATE_NORTH = 111,
CL_CMD_ROTATE_EAST = 112,
CL_CMD_ROTATE_SOUTH = 113,
CL_CMD_ROTATE_WEST = 114,
CL_CMD_MOVE_OBJECT = 120,
CL_CMD_TRADE_OBJECT = 125,
CL_CMD_INSPECT_TRADE = 126,
CL_CMD_ACCEPT_TRADE = 127,
CL_CMD_REJECT_TRADE = 128,
CL_CMD_USE_OBJECT = 130,
CL_CMD_USE_TWO_OBJECTS = 131,
CL_CMD_USE_ON_CREATURE = 132,
CL_CMD_TURN_OBJECT = 133,
CL_CMD_CLOSE_CONTAINER = 135,
CL_CMD_UP_CONTAINER = 136,
CL_CMD_EDIT_TEXT = 137,
CL_CMD_EDIT_LIST = 138,
CL_CMD_LOOK_AT_POINT = 140,
CL_CMD_TALK = 150,
CL_CMD_GET_CHANNELS = 151,
CL_CMD_JOIN_CHANNEL = 152,
CL_CMD_LEAVE_CHANNEL = 153,
CL_CMD_PRIVATE_CHANNEL = 154,
CL_CMD_PROCESS_REQUEST = 155,
CL_CMD_REMOVE_REQUEST = 156,
CL_CMD_CANCEL_REQUEST = 157,
CL_CMD_SET_TACTICS = 160,
CL_CMD_ATTACK = 161,
CL_CMD_FOLLOW = 162,
CL_CMD_INVITE_TO_PARTY = 163,
CL_CMD_JOIN_PARTY = 164,
CL_CMD_REVOKE_INVITATION = 165,
CL_CMD_PASS_LEADERSHIP = 166,
CL_CMD_LEAVE_PARTY = 167,
CL_CMD_OPEN_CHANNEL = 170,
CL_CMD_INVITE_TO_CHANNEL = 171,
CL_CMD_EXCLUDE_FROM_CHANNEL = 172,
CL_CMD_CANCEL = 190,
CL_CMD_REFRESH_FIELD = 201,
CL_CMD_REFRESH_CONTAINER = 202,
CL_CMD_GET_OUTFIT = 210,
CL_CMD_SET_OUTFIT = 211,
CL_CMD_ADD_BUDDY = 220,
CL_CMD_REMOVE_BUDDY = 221,
CL_CMD_BUG_REPORT = 230,
CL_CMD_RULE_VIOLATION = 231,
CL_CMD_ERROR_FILE_ENTRY = 232,
};
enum ServerCommand: int {
SV_CMD_INIT_GAME = 10,
SV_CMD_RIGHTS = 11,
SV_CMD_LOGIN_ERROR = 20,
SV_CMD_LOGIN_PREMIUM = 21,
SV_CMD_LOGIN_WAITINGLIST = 22,
SV_CMD_PING = 30,
SV_CMD_FULLSCREEN = 100,
SV_CMD_ROW_NORTH = 101,
SV_CMD_ROW_EAST = 102,
SV_CMD_ROW_SOUTH = 103,
SV_CMD_ROW_WEST = 104,
SV_CMD_FIELD_DATA = 105,
SV_CMD_ADD_FIELD = 106,
SV_CMD_CHANGE_FIELD = 107,
SV_CMD_DELETE_FIELD = 108,
SV_CMD_MOVE_CREATURE = 109,
SV_CMD_CONTAINER = 110,
SV_CMD_CLOSE_CONTAINER = 111,
SV_CMD_CREATE_IN_CONTAINER = 112,
SV_CMD_CHANGE_IN_CONTAINER = 113,
SV_CMD_DELETE_IN_CONTAINER = 114,
SV_CMD_SET_INVENTORY = 120,
SV_CMD_DELETE_INVENTORY = 121,
SV_CMD_TRADE_OFFER_OWN = 125,
SV_CMD_TRADE_OFFER_PARTNER = 126,
SV_CMD_CLOSE_TRADE = 127,
SV_CMD_AMBIENTE = 130,
SV_CMD_GRAPHICAL_EFFECT = 131,
SV_CMD_TEXTUAL_EFFECT = 132,
SV_CMD_MISSILE_EFFECT = 133,
SV_CMD_MARK_CREATURE = 134,
SV_CMD_CREATURE_HEALTH = 140,
SV_CMD_CREATURE_LIGHT = 141,
SV_CMD_CREATURE_OUTFIT = 142,
SV_CMD_CREATURE_SPEED = 143,
SV_CMD_CREATURE_SKULL = 144,
SV_CMD_CREATURE_PARTY = 145,
SV_CMD_EDIT_TEXT = 150,
SV_CMD_EDIT_LIST = 151,
SV_CMD_PLAYER_DATA = 160,
SV_CMD_PLAYER_SKILLS = 161,
SV_CMD_PLAYER_STATE = 162,
SV_CMD_CLEAR_TARGET = 163,
SV_CMD_TALK = 170,
SV_CMD_CHANNELS = 171,
SV_CMD_OPEN_CHANNEL = 172,
SV_CMD_PRIVATE_CHANNEL = 173,
SV_CMD_OPEN_REQUEST_QUEUE = 174,
SV_CMD_DELETE_REQUEST = 175,
SV_CMD_FINISH_REQUEST = 176,
SV_CMD_CLOSE_REQUEST = 177,
SV_CMD_OPEN_OWN_CHANNEL = 178,
SV_CMD_CLOSE_CHANNEL = 179,
SV_CMD_MESSAGE = 180,
SV_CMD_SNAPBACK = 181,
SV_CMD_FLOOR_UP = 190,
SV_CMD_FLOOR_DOWN = 191,
SV_CMD_OUTFIT = 200,
SV_CMD_BUDDY_DATA = 210,
SV_CMD_BUDDY_ONLINE = 211,
SV_CMD_BUDDY_OFFLINE = 212,
};
// TODO(fusion): The maximum number of connections should probably be kept in
// sync with the maximum number of communication threads, or maybe it is the
// same constant.
#define MAX_CONNECTIONS 1100
struct TKnownCreature {
KNOWNCREATURESTATE State;
uint32 CreatureID;
TKnownCreature *Next;
TConnection *Connection;
};
struct TConnection {
TConnection(void);
void Process(void);
void ResetTimer(int Command);
void EmergencyPing(void);
pid_t GetThreadID(void);
bool SetLoginTimer(int Timeout);
void StopLoginTimer(void);
int GetSocket(void);
const char *GetIPAddress(void);
void Free(void);
void Assign(void);
void Connect(int Socket);
void Login(void);
bool JoinGame(TReadBuffer *Buffer);
void EnterGame(void);
void Die(void);
void Logout(int Delay, bool StopFight);
void Close(bool Delay);
void Disconnect(void);
TPlayer *GetPlayer(void);
const char *GetName(void);
void GetPosition(int *x, int *y, int *z);
bool IsVisible(int x, int y, int z);
KNOWNCREATURESTATE KnownCreature(uint32 ID, bool UpdateFollows);
uint32 NewKnownCreature(uint32 NewID);
void ClearKnownCreatureTable(bool Unchain);
void UnchainKnownCreature(uint32 ID);
bool InGame(void) const {
return this->State == CONNECTION_GAME
|| this->State == CONNECTION_DEAD;
}
bool Live(void) const {
return this->State == CONNECTION_LOGIN
|| this->State == CONNECTION_GAME
|| this->State == CONNECTION_DEAD
|| this->State == CONNECTION_LOGOUT;
}
// DATA
// =================
uint8 InData[2048];
int InDataSize;
bool SigIOPending;
bool WaitingForACK;
uint8 OutData[16384];
int NextToSend;
int NextToCommit;
int NextToWrite;
bool Overflow;
bool WillingToSend;
TConnection *NextSendingConnection;
uint32 RandomSeed;
CONNECTIONSTATE State;
pid_t ThreadID;
timer_t LoginTimer;
int Socket;
char IPAddress[16];
TXTEASymmetricKey SymmetricKey;
bool ConnectionIsOk;
bool ClosingIsDelayed;
uint32 TimeStamp;
uint32 TimeStampAction;
int TerminalType;
int TerminalVersion;
int TerminalOffsetX;
int TerminalOffsetY;
int TerminalWidth;
int TerminalHeight;
uint32 CharacterID;
char Name[31];
TKnownCreature KnownCreatureTable[150];
};
// connections.cc
TConnection *AssignFreeConnection(void);
TConnection *GetFirstConnection(void);
TConnection *GetNextConnection(void);
void ProcessConnections(void);
void InitConnections(void);
void ExitConnections(void);
// sending.cc
void SendAll(void);
bool BeginSendData(TConnection *Connection);
void FinishSendData(TConnection *Connection);
void SkipFlush(TConnection *Connection);
void SendMapObject(TConnection *Connection, Object Obj);
void SendMapPoint(TConnection *Connection, int x, int y, int z);
void SendResult(TConnection *Connection, RESULT r);
void SendRefresh(TConnection *Connection);
void SendInitGame(TConnection *Connection, uint32 CreatureID);
void SendRights(TConnection *Connection);
void SendPing(TConnection *Connection);
void SendFullScreen(TConnection *Connection);
void SendRow(TConnection *Connection, int Direction);
void SendFloors(TConnection *Connection, bool Up);
void SendFieldData(TConnection *Connection, int x, int y, int z);
void SendAddField(TConnection *Connection, int x, int y, int z, Object Obj);
void SendChangeField(TConnection *Connection, int x, int y, int z, Object Obj);
void SendDeleteField(TConnection *Connection, int x, int y, int z, Object Obj);
void SendMoveCreature(TConnection *Connection,
uint32 CreatureID, int DestX, int DestY, int DestZ);
void SendContainer(TConnection *Connection, int ContainerNr);
void SendCloseContainer(TConnection *Connection, int ContainerNr);
void SendCreateInContainer(TConnection *Connection, int ContainerNr, Object Obj);
void SendChangeInContainer(TConnection *Connection, int ContainerNr, Object Obj);
void SendDeleteInContainer(TConnection *Connection, int ContainerNr, Object Obj);
void SendBodyInventory(TConnection *Connection, uint32 CreatureID);
void SendSetInventory(TConnection *Connection, int Position, Object Obj);
void SendDeleteInventory(TConnection *Connection, int Position);
void SendTradeOffer(TConnection *Connection, const char *Name, bool OwnOffer, Object Obj);
void SendCloseTrade(TConnection *Connection);
void SendAmbiente(TConnection *Connection);
void SendGraphicalEffect(TConnection *Connection, int x, int y, int z, int Type);
void SendTextualEffect(TConnection *Connection, int x, int y, int z, int Color, const char *Text);
void SendMissileEffect(TConnection *Connection, int OrigX, int OrigY, int OrigZ,
int DestX, int DestY, int DestZ, int Type);
void SendMarkCreature(TConnection *Connection, uint32 CreatureID, int Color);
void SendCreatureHealth(TConnection *Connection, uint32 CreatureID);
void SendCreatureLight(TConnection *Connection, uint32 CreatureID);
void SendCreatureOutfit(TConnection *Connection, uint32 CreatureID);
void SendCreatureSpeed(TConnection *Connection, uint32 CreatureID);
void SendCreatureSkull(TConnection *Connection, uint32 CreatureID);
void SendCreatureParty(TConnection *Connection, uint32 CreatureID);
void SendEditText(TConnection *Connection, Object Obj);
void SendEditList(TConnection *Connection, uint8 Type, uint32 ID, const char *Text);
void SendPlayerData(TConnection *Connection);
void SendPlayerSkills(TConnection *Connection);
void SendPlayerState(TConnection *Connection, uint8 State);
void SendClearTarget(TConnection *Connection);
void SendTalk(TConnection *Connection, uint32 StatementID,
const char *Sender, int Mode, const char *Text, int Data);
void SendTalk(TConnection *Connection, uint32 StatementID,
const char *Sender, int Mode, int Channel, const char *Text);
void SendTalk(TConnection *Connection, uint32 StatementID,
const char *Sender, int Mode, int x, int y, int z, const char *Text);
void SendChannels(TConnection *Connection);
void SendOpenChannel(TConnection *Connection, int Channel);
void SendPrivateChannel(TConnection *Connection, const char *Name);
void SendOpenRequestQueue(TConnection *Connection);
void SendDeleteRequest(TConnection *Connection, const char *Name);
void SendFinishRequest(TConnection *Connection, const char *Name);
void SendCloseRequest(TConnection *Connection);
void SendOpenOwnChannel(TConnection *Connection, int Channel);
void SendCloseChannel(TConnection *Connection, int Channel);
void SendMessage(TConnection *Connection, int Mode, const char *Text, ...) ATTR_PRINTF(3, 4);
void SendSnapback(TConnection *Connection);
void SendOutfit(TConnection *Connection);
void SendBuddyData(TConnection *Connection, uint32 CharacterID, const char *Name, bool Online);
void SendBuddyStatus(TConnection *Connection, uint32 CharacterID, bool Online);
void BroadcastMessage(int Mode, const char *Text, ...) ATTR_PRINTF(2, 3);
void CreateGamemasterRequest(const char *Name, const char *Text);
void DeleteGamemasterRequest(const char *Name);
void InitSending(void);
void ExitSending(void);
// receiving.cc
void ReceiveData(TConnection *Connection);
void ReceiveData(void);
void InitReceiving(void);
void ExitReceiving(void);
#endif // TIBIA_CONNECTIONS_HH_

593
src/game/src/containers.hh Normal file
View file

@ -0,0 +1,593 @@
#ifndef TIBIA_CONTAINERS_HH_
#define TIBIA_CONTAINERS_HH_ 1
#include "common.hh"
// NOTE(fusion): All containers are automatically managed by their constructors
// and destructors, meaning raw copies could result in memory corruption through
// double frees, use after frees, etc... To avoid that, we need to make them all
// non copyable.
#define NONCOPYABLE(Type) \
Type(const Type &Other) = delete; \
void operator=(const Type &Other) = delete;
// NOTE(fusion): What the actual fuck. This is an ever growing dynamic array
// with each access through `operator()` growing it to make sure the requested
// index is valid, even for negative indices.
template<typename T>
struct vector{
NONCOPYABLE(vector)
vector(int min, int max, int block){
int space = (max - min) + 1;
if(space < 1){
error("vector: Ungueltige Feldgroesse %d bis %d.\n", min, max);
space = 1;
}
if(block < 0){
error("vector: Ungueltige Blockgroesse %d.\n", block);
block = 0;
}
this->min = min;
this->max = max;
this->start = min;
this->space = space;
this->block = block;
this->initialized = false;
this->entry = new T[this->space];
}
vector(int min, int max, int block, T init) : vector(min, max, block) {
this->initialized = true;
this->init = init;
for(int i = 0; i < this->space; i += 1){
this->entry[i] = init;
}
}
~vector(void){
delete[] this->entry;
}
T *at(int index){
// TODO(fusion): This is probably not the best way to achieve this.
while(index < this->start){
int increment = this->block;
if(increment == 0){
increment = this->space;
}
T *entry = new T[this->space + increment];
for(int i = this->min; i <= this->max; i += 1){
int old_index = i - this->start;
int new_index = old_index + increment;
// TODO(fusion): Do we actually need to swap elements here? I'm
// assuming some non-trivial structures that would invoke their
// destructors when `this->entry` gets deleted just below.
std::swap(entry[new_index], this->entry[old_index]);
}
if(this->entry != NULL){
delete[] this->entry;
}
this->entry = entry;
this->start -= increment;
this->space += increment;
}
while(index >= (this->start + this->space)){
int increment = this->block;
if(increment == 0){
increment = this->space;
}
T *entry = new T[this->space + increment];
for(int i = this->min; i <= this->max; i += 1){
int old_index = i - this->start;
int new_index = old_index;
// TODO(fusion): Same as above.
std::swap(entry[new_index], this->entry[old_index]);
}
if(this->entry != NULL){
delete[] this->entry;
}
this->entry = entry;
this->space += increment;
}
while(index < this->min){
this->min -= 1;
if(this->initialized){
this->entry[this->min - this->start] = this->init;
}
}
while(index > this->max){
this->max += 1;
if(this->initialized){
this->entry[this->max - this->start] = this->init;
}
}
return &this->entry[index - this->start];
}
T copyAt(int index) const {
T Result = {};
if(index >= this->start && index < (this->start + this->space)){
Result = this->entry[index - this->start];
}else if(this->initialized){
Result = this->init;
}
return Result;
}
// DATA
// =================
int min;
int max;
int start;
int space;
int block;
bool initialized;
T init;
T *entry;
};
template<typename K, typename T>
struct priority_queue_entry{
K Key;
T Data;
};
template<typename K, typename T>
struct priority_queue{
NONCOPYABLE(priority_queue)
priority_queue(int capacity, int increment){
Entry = new vector<priority_queue_entry<K, T>>(1, capacity, increment);
Entries = 0;
}
~priority_queue(void){
delete Entry;
}
void insert(K Key, T Data){
this->Entries += 1;
int CurrentIndex = this->Entries;
*this->Entry->at(CurrentIndex) = {Key, Data};
while(CurrentIndex > 1){
int ParentIndex = CurrentIndex / 2;
priority_queue_entry<K, T> *Current = this->Entry->at(CurrentIndex);
priority_queue_entry<K, T> *Parent = this->Entry->at(ParentIndex);
if(Parent->Key <= Current->Key)
break;
std::swap(*Current, *Parent);
CurrentIndex = ParentIndex;
}
}
void deleteMin(void){
if(this->Entries < 1){
error("priority_queue::deleteMin: Warteschlange ist leer.\n");
return;
}
if(this->Entries > 1){
int CurrentIndex = 1;
int LastIndex = this->Entries;
std::swap(*this->Entry->at(CurrentIndex),
*this->Entry->at(LastIndex));
// TODO(fusion): This may be an oversight but the decompiled version
// checks in the loop below would INCLUDE `LastIndex`, which I assume
// is a bug? The first and last elements were just swapped and what
// was the first element in the queue is now at the end and should be
// considered "removed".
while(1){
int SmallestIndex = CurrentIndex * 2;
if(SmallestIndex >= LastIndex){
break;
}
priority_queue_entry<K, T> *Smallest = this->Entry->at(SmallestIndex);
if((SmallestIndex + 1) < LastIndex){
priority_queue_entry<K, T> *Other = this->Entry->at(SmallestIndex + 1);
if(Other->Key < Smallest->Key){
Smallest = Other;
SmallestIndex += 1;
}
}
priority_queue_entry<K, T> *Current = this->Entry->at(CurrentIndex);
if(Current->Key <= Smallest->Key){
break;
}
std::swap(*Current, *Smallest);
CurrentIndex = SmallestIndex;
}
}
this->Entries -= 1;
}
// DATA
// =================
vector<priority_queue_entry<K, T>> *Entry;
int Entries;
};
template<typename T>
struct matrix{
NONCOPYABLE(matrix)
matrix(int xmin, int xmax, int ymin, int ymax){
int dx = (xmax - xmin) + 1;
int dy = (ymax - ymin) + 1;
if(dx < 1 || dy < 1){
error("matrix: Ungueltige Feldgroesse %d..%d, %d..%d.\n", xmin, xmax, ymin, ymax);
if(dx < 1){
dx = 1;
}
if(dy < 1){
dy = 1;
}
}
this->xmin = xmin;
this->ymin = ymin;
this->dx = dx;
this->dy = dy;
this->entry = new T[dx * dy];
}
matrix(int xmin, int xmax, int ymin, int ymax, T init) : matrix(xmin, xmax, ymin, ymax) {
int count = this->dx * this->dy;
for(int i = 0; i < count; i += 1){
this->entry[i] = init;
}
}
~matrix(void){
delete[] this->entry;
}
// NOTE(fusion): Same as `at` but returns NULL on out of bounds coordinates.
T *boundedAt(int x, int y){
int xoffset = x - this->xmin;
int yoffset = y - this->ymin;
if(xoffset < 0 || xoffset >= this->dx || yoffset < 0 || yoffset >= this->dy){
return NULL;
}else{
return &this->entry[yoffset * this->dx + xoffset];
}
}
T *at(int x, int y){
int xoffset = x - this->xmin;
int yoffset = y - this->ymin;
if(xoffset < 0 || xoffset >= this->dx || yoffset < 0 || yoffset >= this->dy){
error("matrix::operator(): Ungueltiger Index %d/%d.\n", x, y);
return &this->entry[0];
}else{
// TODO(fusion): Are we really storing this in row major order?
return &this->entry[yoffset * this->dx + xoffset];
}
}
// DATA
// =================
int xmin;
int ymin;
int dx;
int dy;
T *entry;
};
template<typename T>
struct matrix3d{
NONCOPYABLE(matrix3d)
matrix3d(int xmin, int xmax, int ymin, int ymax, int zmin, int zmax){
int dx = (xmax - xmin) + 1;
int dy = (ymax - ymin) + 1;
int dz = (zmax - zmin) + 1;
if(dx < 1 || dy < 1 || dz < 1){
error("matrix3d: Ungueltige Feldgroesse %d..%d, %d..%d, %d..%d.\n",
xmin, xmax, ymin, ymax, zmin, zmax);
if(dx < 1){
dx = 1;
}
if(dy < 1){
dy = 1;
}
if(dz < 1){
dz = 1;
}
}
this->xmin = xmin;
this->ymin = ymin;
this->zmin = zmin;
this->dx = dx;
this->dy = dy;
this->dz = dz;
this->entry = new T[dx * dy * dz];
}
matrix3d(int xmin, int xmax, int ymin, int ymax, int zmin, int zmax, T init)
: matrix3d(xmin, xmax, ymin, ymax, zmin, zmax) {
int count = this->dx * this->dy * this->dz;
for(int i = 0; i < count; i += 1){
this->entry[i] = init;
}
}
~matrix3d(void){
delete[] this->entry;
}
T *at(int x, int y, int z){
int xoffset = x - this->xmin;
int yoffset = y - this->ymin;
int zoffset = z - this->zmin;
if(xoffset < 0 || xoffset >= this->dx
|| yoffset < 0 || yoffset >= this->dy
|| zoffset < 0 || zoffset >= this->dz){
error("matrix3d::operator(): Ungueltiger Index %d/%d/%d.\n", x, y, z);
return &this->entry[0];
}else{
// TODO(fusion): Same as `matrix::at` on the XY plane.
return &this->entry[zoffset * this->dx * this->dy
+ yoffset * this->dx
+ xoffset];
}
}
// DATA
// =================
int xmin;
int ymin;
int zmin;
int dx;
int dy;
int dz;
T *entry;
};
template<typename T>
struct listnode{
listnode *next;
listnode *prev;
T data;
};
template<typename T>
struct list{
NONCOPYABLE(list)
list(void){
firstNode = NULL;
lastNode = NULL;
}
~list(void){
while(this->firstNode != NULL){
this->remove(this->firstNode);
}
}
listnode<T> *append(void){
listnode<T> *node = new listnode<T>;
node->next = NULL;
node->prev = NULL;
if(this->firstNode == NULL){
ASSERT(this->lastNode == NULL);
this->firstNode = node;
}else{
ASSERT(this->lastNode != NULL);
this->lastNode->next = node;
node->prev = this->lastNode;
}
this->lastNode = node;
return node;
}
void remove(listnode<T> *node){
if(node == NULL){
error("list::remove: node ist NULL.\n");
return;
}
if(node->prev == NULL){
ASSERT(this->firstNode == node);
this->firstNode = node->next;
}else{
node->prev->next = node->next;
}
if(node->next == NULL){
ASSERT(this->lastNode == node);
this->lastNode = node->prev;
}else{
node->next->prev = node->prev;
}
delete node;
}
// DATA
// =================
listnode<T> *firstNode;
listnode<T> *lastNode;
};
template<typename T>
struct fifo{
NONCOPYABLE(fifo)
fifo(int InitialSize){
ASSERT(InitialSize > 0);
this->Entry = new T[InitialSize];
this->Size = InitialSize;
this->Head = -1;
this->Tail = 0;
}
~fifo(void){
delete[] this->Entry;
}
T *next(void){
T *Next = NULL;
if(this->Tail <= this->Head){
Next = &this->Entry[this->Tail % this->Size];
}
return Next;
}
T *append(void){
if((this->Head - this->Tail + 1) == this->Size){
int NewSize = this->Size * 2;
T *NewEntry = new T[NewSize];
// TODO(fusion): Is it even possible to have `this->Entry == NULL`?
if(this->Entry != NULL){
for(int Index = this->Tail; Index <= this->Head; Index += 1){
NewEntry[Index % NewSize] = this->Entry[Index % this->Size];
}
delete[] this->Entry;
}
this->Entry = NewEntry;
this->Size = NewSize;
}
// TODO(fusion): We don't consider integer overflow at all.
this->Head += 1;
return &this->Entry[this->Head % this->Size];
}
void remove(void){
if(this->Tail > this->Head){
error("fifo::remove: Fifo ist leer.\n");
return;
}
this->Tail += 1;
}
int iterFirst(void){
return this->Head;
}
int iterLast(void){
return this->Tail;
}
T *iterNext(int *Position){
if(*Position < this->Tail || this->Head < *Position){
return NULL;
}
T *Result = &this->Entry[*Position % this->Size];
*Position -= 1;
return Result;
}
T *iterPrev(int *Position){
if(*Position < this->Tail || this->Head < *Position){
return NULL;
}
T *Result = &this->Entry[*Position % this->Size];
*Position += 1;
return Result;
}
// TODO(fusion): There is also a `fifoIterator` used a few times and it is
// essentially iterating from `this->Head` towards `this->Tail`. All its
// functions were inlined so I'm not sure it is needed.
// DATA
// =================
T *Entry;
int Size;
int Head;
int Tail;
};
template<typename T>
union storeitem{
// IMPORTANT(fusion): This will only work properly with POD structures. We
// could also manually handle `data` construction and destruction but I don't
// think we need it.
STATIC_ASSERT(std::is_trivially_default_constructible<T>::value
&& std::is_trivially_destructible<T>::value
&& std::is_trivially_copyable<T>::value);
storeitem<T> *next;
T data;
};
template<typename T, usize N>
struct storeunit{
STATIC_ASSERT(N > 0);
storeitem<T> item[N];
};
// NOTE(fusion): The `store` container is an allocator that manages a single type.
// It is also known as a slab allocator.
template<typename T, usize N>
struct store{
NONCOPYABLE(store)
store(void){
this->Units = new list<storeunit<T, N>>;
this->firstFreeItem = NULL;
}
~store(void){
delete this->Units;
}
T *getFreeItem(void){
if(this->firstFreeItem == NULL){
storeunit<T, N> *Unit = &this->Units->append()->data;
for(usize i = 0; i < (N - 1); i += 1){
Unit->item[i].next = &Unit->item[i + 1];
}
Unit->item[N - 1].next = NULL;
this->firstFreeItem = &Unit->item[0];
}
storeitem<T> *Item = this->firstFreeItem;
this->firstFreeItem = Item->next;
return &Item->data;
}
void putFreeItem(T *Item){
// TODO(fusion): Not the safest thing to do.
ASSERT(Item != NULL);
((storeitem<T>*)Item)->next = this->firstFreeItem;
this->firstFreeItem = (storeitem<T>*)Item;
}
// DATA
// =================
list<storeunit<T, N>> *Units;
storeitem<T> *firstFreeItem;
};
#endif //TIBIA_CONTAINERS_HH_

1051
src/game/src/cr.hh Normal file

File diff suppressed because it is too large Load diff

1590
src/game/src/cract.cc Normal file

File diff suppressed because it is too large Load diff

955
src/game/src/crcombat.cc Normal file
View file

@ -0,0 +1,955 @@
#include "cr.hh"
#include "config.hh"
#include "info.hh"
#include "magic.hh"
#include "operate.hh"
TCombat::TCombat(void){
this->Master = NULL;
this->EarliestAttackTime = 0;
this->EarliestDefendTime = 0;
this->LastDefendTime = 0;
this->LatestAttackTime = 0;
this->AttackMode = ATTACK_MODE_BALANCED;
this->ChaseMode = CHASE_MODE_NONE;
this->SecureMode = SECURE_MODE_ENABLED;
this->AttackDest = 0;
this->Following = false;
this->Shield = NONE;
this->Close = NONE;
this->Missile = NONE;
this->Throw = NONE;
this->Wand = NONE;
this->Ammo = NONE;
this->Fist = false;
this->CombatDamage = 0;
this->ActCombatEntry = 0;
for(int i = 0; i < NARRAY(this->CombatList); i += 1){
this->CombatList[i].ID = 0;
this->CombatList[i].Damage = 0;
this->CombatList[i].TimeStamp = 0;
}
this->LearningPoints = 0;
}
void TCombat::GetWeapon(void){
this->Shield = NONE;
this->Close = NONE;
this->Missile = NONE;
this->Throw = NONE;
this->Wand = NONE;
this->Ammo = NONE;
this->Fist = true;
// TODO(fusion): Check if `Master` is NULL?
TCreature *Master = this->Master;
if(!Master->CrObject.exists()){
error("TCombat::GetWeapon: Kreatur-Objekt existiert nicht.\n");
return;
}
for(int Position = INVENTORY_HAND_FIRST;
Position <= INVENTORY_HAND_LAST;
Position += 1){
Object Obj = GetBodyObject(Master->ID, Position);
if(Obj == NONE){
continue;
}
ObjectType ObjType = Obj.getObjectType();
if(ObjType.getFlag(RESTRICTLEVEL)){
int CurrentLevel = Master->Skills[SKILL_LEVEL]->Get();
int MinimumLevel = (int)ObjType.getAttribute(MINIMUMLEVEL);
if(CurrentLevel < MinimumLevel){
continue;
}
}
if(ObjType.getFlag(RESTRICTPROFESSION) && Master->Type == PLAYER){
uint32 ProfessionMask = ObjType.getAttribute(PROFESSIONS);
uint8 Profession = ((TPlayer*)Master)->GetEffectiveProfession();
if((ProfessionMask & (1 << Profession)) == 0){
continue;
}
}
if(ObjType.getFlag(SHIELD)){
this->Shield = Obj;
}
if(ObjType.getFlag(WEAPON)){
this->Close = Obj;
this->Fist = false;
}
if(ObjType.getFlag(BOW)){
this->Missile = Obj;
this->Fist = false;
}
if(ObjType.getFlag(THROW)){
this->Throw = Obj;
this->Fist = false;
}
if(ObjType.getFlag(WAND)){
this->Wand = Obj;
this->Fist = false;
}
}
}
void TCombat::GetAmmo(void){
if(this->Missile == NONE){
if(this->Throw != NONE){
this->Ammo = this->Throw;
}else if(this->Wand != NONE){
this->Ammo = this->Wand;
}
return;
}
// TODO(fusion): Check if `Master` is NULL?
Object Ammo = GetBodyObject(this->Master->ID, INVENTORY_AMMO);
this->Ammo = NONE;
if(Ammo != NONE){
ObjectType AmmoType = Ammo.getObjectType();
if(AmmoType.getFlag(AMMO)){
ObjectType BowType = this->Missile.getObjectType();
if(AmmoType.getAttribute(AMMOTYPE) == BowType.getAttribute(BOWAMMOTYPE)){
this->Ammo = Ammo;
}
}
}
}
void TCombat::CheckCombatValues(void){
Object OldShield = this->Shield;
Object OldClose = this->Close;
Object OldMissile = this->Missile;
Object OldThrow = this->Throw;
Object OldWand = this->Wand;
Object OldAmmo = this->Ammo;
bool OldFist = this->Fist;
this->GetWeapon();
this->GetAmmo();
if(OldShield != this->Shield
|| OldClose != this->Close
|| OldMissile != this->Missile
|| OldThrow != this->Throw
|| OldWand != this->Wand
|| OldAmmo != this->Ammo
|| OldFist != this->Fist){
this->DelayAttack(2000);
}
}
static int WeaponTypeToSkill(int WeaponType){
int Result = SKILL_FIST;
switch(WeaponType){
case WEAPON_NONE: Result = SKILL_FIST; break;
case WEAPON_SWORD: Result = SKILL_SWORD; break;
case WEAPON_CLUB: Result = SKILL_CLUB; break;
case WEAPON_AXE: Result = SKILL_AXE; break;
case WEAPON_SHIELD: Result = SKILL_SHIELDING; break;
case WEAPON_AMMO: ATTR_FALLTHROUGH;
case WEAPON_THROW: Result = SKILL_DISTANCE; break;
}
return Result;
}
void TCombat::GetAttackValue(int *Value, int *SkillNr){
int AttackValue;
int WeaponType;
if(this->Close != NONE){
ObjectType CloseType = this->Close.getObjectType();
AttackValue = (int)CloseType.getAttribute(WEAPONATTACKVALUE);
WeaponType = (int)CloseType.getAttribute(WEAPONTYPE);
}else if(this->Missile != NONE){
ObjectType AmmoType = this->Ammo.getObjectType();
AttackValue = (int)AmmoType.getAttribute(AMMOATTACKVALUE);
WeaponType = WEAPON_AMMO;
}else if(this->Throw != NONE){
ObjectType ThrowType = this->Throw.getObjectType();
AttackValue = (int)ThrowType.getAttribute(THROWATTACKVALUE);
WeaponType = WEAPON_THROW;
}else if(this->Wand != NONE){
AttackValue = 0;
WeaponType = WEAPON_NONE;
}else{
AttackValue = RaceData[this->Master->Race].Attack;
WeaponType = WEAPON_NONE;
}
*Value = AttackValue;
*SkillNr = WeaponTypeToSkill(WeaponType);
}
void TCombat::GetDefendValue(int *Value, int *SkillNr){
int DefenseValue;
int WeaponType;
if(this->Shield != NONE){
ObjectType ShieldType = this->Shield.getObjectType();
DefenseValue = (int)ShieldType.getAttribute(SHIELDDEFENDVALUE);
WeaponType = WEAPON_SHIELD;
}else if(this->Close != NONE){
ObjectType CloseType = this->Close.getObjectType();
DefenseValue = (int)CloseType.getAttribute(WEAPONDEFENDVALUE);
WeaponType = (int)CloseType.getAttribute(WEAPONTYPE);
}else if(this->Throw != NONE){
ObjectType ThrowType = this->Throw.getObjectType();
DefenseValue = (int)ThrowType.getAttribute(THROWDEFENDVALUE);
WeaponType = WEAPON_THROW;
}else if(this->Missile != NONE){
// TODO(fusion): This might be correct. Having a bow equipped will reduce
// your defense to zero but having a wand equipped will give you base defense.
DefenseValue = 0;
WeaponType = WEAPON_AMMO;
}else{
DefenseValue = RaceData[this->Master->Race].Defend;
WeaponType = WEAPON_NONE;
}
*Value = DefenseValue;
*SkillNr = WeaponTypeToSkill(WeaponType);
}
int TCombat::GetAttackDamage(void){
int MaxValue, SkillNr;
this->GetAttackValue(&MaxValue, &SkillNr);
if(this->AttackMode == ATTACK_MODE_OFFENSIVE){
MaxValue += (MaxValue * 2) / 10;
}else if(this->AttackMode == ATTACK_MODE_DEFENSIVE){
MaxValue -= (MaxValue * 4) / 10;
}
TSkill *Skill = this->Master->Skills[SkillNr];
int Result = Skill->ProbeValue(MaxValue, this->LearningPoints > 0);
if(this->LearningPoints > 0){
this->LearningPoints -= 1;
}
return Result;
}
int TCombat::GetDefendDamage(void){
if(this->EarliestDefendTime > ServerMilliseconds){
return 0;
}
this->EarliestDefendTime = this->LastDefendTime + 2000;
this->LastDefendTime = ServerMilliseconds;
int AttackMode = this->AttackMode;
if(this->Following || this->AttackDest == 0){
AttackMode = ATTACK_MODE_DEFENSIVE;
}
int MaxValue, SkillNr;
this->GetDefendValue(&MaxValue, &SkillNr);
if(AttackMode == ATTACK_MODE_OFFENSIVE){
MaxValue -= (MaxValue * 4) / 10;
}else if(AttackMode == ATTACK_MODE_DEFENSIVE){
MaxValue += (MaxValue * 8) / 10;
}
TSkill *Skill = this->Master->Skills[SkillNr];
bool Increase = (this->Shield != NONE && this->LearningPoints > 0);
int Result = Skill->ProbeValue(MaxValue, Increase);
if(Increase){
this->LearningPoints -= 1;
}
Object Shield = this->Shield;
if(Shield != NONE){
ObjectType ShieldType = Shield.getObjectType();
if(ShieldType.getFlag(WEAROUT)){
uint32 RemainingUses = Shield.getAttribute(REMAININGUSES);
if(RemainingUses > 1){
Change(Shield, REMAININGUSES, RemainingUses - 1);
}else{
ObjectType WearOutType = (int)ShieldType.getAttribute(WEAROUTTARGET);
Change(Shield, WearOutType, 0);
// TODO(fusion): Probably just check anyways, to be sure.
if(!Shield.exists() || !WearOutType.getFlag(SHIELD)){
this->CheckCombatValues();
}
}
}
}
return Result;
}
int TCombat::GetArmorStrength(void){
int Armor = 0;
TCreature *Master = this->Master;
for(int Position = INVENTORY_FIRST;
Position <= INVENTORY_LAST;
Position += 1){
Object Obj = GetBodyObject(Master->ID, Position);
if(Obj.exists()){
ObjectType ObjType = Obj.getObjectType();
if(ObjType.getFlag(CLOTHES) && ObjType.getFlag(ARMOR)
&& (int)ObjType.getAttribute(BODYPOSITION) == Position){
Armor += (int)ObjType.getAttribute(ARMORVALUE);
}
}
}
Armor += RaceData[Master->Race].Armor;
if(Armor >= 2){
Armor = (Armor / 2) + rand() % (Armor / 2);
}
return Armor;
}
int TCombat::GetDistance(void){
int Distance = 0;
if(this->Close != NONE || this->Fist){
Distance = 1; // DISTANCE_CLOSE ?
}else if(this->Throw != NONE){
Distance = 2; // DISTANCE_THROW ?
}else if(this->Missile != NONE || this->Wand != NONE){
Distance = 3; // DISTANCE_RANGE ?
}
return Distance;
}
void TCombat::ActivateLearning(void){
this->LearningPoints = 30;
}
void TCombat::SetAttackMode(uint8 AttackMode){
if(AttackMode != ATTACK_MODE_OFFENSIVE
&& AttackMode != ATTACK_MODE_BALANCED
&& AttackMode != ATTACK_MODE_DEFENSIVE){
error("TCombat::SetAttackMode: Ungültiger Angriffsmodus %d.\n", AttackMode);
return;
}
if(this->AttackMode != AttackMode){
this->DelayAttack(2000);
this->AttackMode = AttackMode;
}
}
void TCombat::SetChaseMode(uint8 ChaseMode){
if(ChaseMode != CHASE_MODE_NONE && ChaseMode != CHASE_MODE_CLOSE){
error("TCombat::SetChaseMode: Ungültiger Verfolgungsmodus %d.\n", ChaseMode);
return;
}
this->ChaseMode = ChaseMode;
}
void TCombat::SetSecureMode(uint8 SecureMode){
if(SecureMode != SECURE_MODE_DISABLED && SecureMode != SECURE_MODE_ENABLED){
error("TCombat::SetSecureMode: Ungültiger Sicherheitsmodus %d.\n", SecureMode);
return;
}
this->SecureMode = SecureMode;
}
void TCombat::SetAttackDest(uint32 TargetID, bool Follow){
if(this->AttackDest == TargetID && this->Following == Follow){
return;
}
TCreature *Master = this->Master;
if(TargetID == 0 || TargetID == Master->ID){
this->StopAttack(0);
return;
}
TCreature *Target = GetCreature(TargetID);
if(Target == NULL){
this->StopAttack(0);
return;
}
if(!Follow){
if(Master->Type == PLAYER && Target->Type == PLAYER){
if(this->SecureMode == SECURE_MODE_ENABLED && WorldType == NORMAL
&& !((TPlayer*)Master)->IsAttackJustified(TargetID)){
this->StopAttack(0);
throw SECUREMODE;
}
}
if(Master->Type == PLAYER && !CheckRight(Master->ID, ATTACK_EVERYWHERE)){
if(IsProtectionZone(Master->posx, Master->posy, Master->posz)
|| IsProtectionZone(Target->posx, Target->posy, Target->posz)){
this->StopAttack(0);
throw PROTECTIONZONE;
}
}
if(Master->Type == PLAYER && CheckRight(Master->ID, NO_ATTACK)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
if(Master->Type == PLAYER && Target->Type == PLAYER){
if(((TPlayer*)Master)->GetRealProfession() == PROFESSION_NONE
&& !CheckRight(Master->ID, ATTACK_EVERYWHERE)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
}
if(Target->Type == NPC){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
if(WorldType == NON_PVP && Master->IsPeaceful() && Target->IsPeaceful()){
if(Master->Type != PLAYER || !CheckRight(Master->ID, ATTACK_EVERYWHERE)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
}
}
if(Master->Type == PLAYER && Target->Type != PLAYER){
if(Target->IsInvisible()){
this->StopAttack(0);
throw TARGETLOST;
}
}
int Distance = ObjectDistance(Master->CrObject, Target->CrObject);
if(Distance > 8){
this->StopAttack(0);
throw TARGETLOST;
}
this->AttackDest = TargetID;
this->Following = Follow;
if(!Follow){
Target->AttackStimulus(Master->ID);
Master->BlockLogout(60, Target->Type == PLAYER);
if(Master->Type == PLAYER && Target->Type == PLAYER){
((TPlayer*)Master)->RecordAttack(TargetID);
}
this->LatestAttackTime = 0;
}
}
void TCombat::CanToDoAttack(void){
if(this->AttackDest == 0){
return;
}
// TODO(fusion): There is some `CanAttack` function inlined here.
TCreature *Master = this->Master;
if(Master == NULL){
error("TCombat::CanAttack: Kein Master gesetzt!\n");
throw ERROR;
}
TCreature *Target = GetCreature(this->AttackDest);
if(Target == NULL){
this->StopAttack(0);
throw TARGETLOST;
}
if(Master->Type == PLAYER && Target->Type != PLAYER){
if(Target->IsInvisible()){
this->StopAttack(0);
throw TARGETLOST;
}
}
if(!this->Following){
if(Master->Type == PLAYER && Target->Type == PLAYER){
if(this->SecureMode == SECURE_MODE_ENABLED && WorldType == NORMAL
&& !((TPlayer*)Master)->IsAttackJustified(Target->ID)){
this->StopAttack(0);
throw SECUREMODE;
}
}
if(WorldType == NON_PVP){
if(Master->IsPeaceful() && Target->IsPeaceful()){
if(Master->Type != PLAYER || !CheckRight(Master->ID, ATTACK_EVERYWHERE)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
}
}
}
int Distance = ObjectDistance(Master->CrObject, Target->CrObject);
if(Distance > 8){
this->StopAttack(0);
throw TARGETLOST;
}
int ChaseMode = this->ChaseMode;
if(this->Following){
ChaseMode = CHASE_MODE_CLOSE;
}
if(ChaseMode == CHASE_MODE_CLOSE){
if(Distance > 1){
Master->ToDoGo(Target->posx, Target->posy, Target->posz, false, 3);
}
}else if(ChaseMode == CHASE_MODE_RANGE){
if(Distance > 4){
Master->ToDoGo(Target->posx, Target->posy, Target->posz, false, Distance - 4);
}else if(Distance < 4){
int DestX, DestY, DestZ;
if(SearchFlightField(Master->ID, Target->ID, &DestX, &DestY, &DestZ)){
Master->ToDoGo(DestX, DestY, DestZ, true, -1);
}
}
}
}
void TCombat::StopAttack(int Delay){
if(Delay == 0){
this->AttackDest = 0;
if(this->Master->Type == PLAYER){
SendClearTarget(this->Master->Connection);
}
}else{
this->LatestAttackTime = RoundNr + Delay;
}
}
void TCombat::DelayAttack(int Milliseconds){
uint32 EarliestAttackTime = ServerMilliseconds + Milliseconds;
if(this->EarliestAttackTime < EarliestAttackTime){
this->EarliestAttackTime = EarliestAttackTime;
}
}
void TCombat::Attack(void){
if(this->AttackDest == 0 || this->Following){
return;
}
// TODO(fusion): There is some `CanAttack` function inlined here.
TCreature *Master = this->Master;
if(Master == NULL){
error("TCombat::CanAttack: Kein Master gesetzt!\n");
throw ERROR;
}
TCreature *Target = GetCreature(this->AttackDest);
if(Target == NULL){
this->StopAttack(0);
throw TARGETLOST;
}
// NOTE(fusion): This probably has something to do with calling `StopAttack`
// with a non zero delay.
if(this->LatestAttackTime != 0 && this->LatestAttackTime < RoundNr){
this->StopAttack(0);
return;
}
if(Master->Type == PLAYER && Target->Type != PLAYER){
if(Target->IsInvisible()){
this->StopAttack(0);
throw TARGETLOST;
}
}
if(Master->Type == PLAYER && Target->Type == PLAYER){
if(this->SecureMode == SECURE_MODE_ENABLED && WorldType == NORMAL
&& !((TPlayer*)Master)->IsAttackJustified(Target->ID)){
this->StopAttack(0);
throw SECUREMODE;
}
}
// TODO(fusion): It is weird that max attack distance is hardcoded.
// Actually, it is related to the maximum visible distance on a
// creature's viewport.
int Distance = ObjectDistance(Master->CrObject, Target->CrObject);
if(Distance > 8){
this->StopAttack(0);
throw TARGETLOST;
}
if(Master->Type == PLAYER && Target->Type == PLAYER){
if(((TPlayer*)Master)->GetRealProfession() == PROFESSION_NONE
&& !CheckRight(Master->ID, ATTACK_EVERYWHERE)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
}
if(Master->Type == PLAYER){
if(CheckRight(Master->ID, NO_ATTACK)){
this->StopAttack(0);
throw ATTACKNOTALLOWED;
}
}
if(IsProtectionZone(Master->posx, Master->posy, Master->posz)
|| IsProtectionZone(Target->posx, Target->posy, Target->posz)){
this->StopAttack(0);
throw PROTECTIONZONE;
}
Master->BlockLogout(60, Target->Type == PLAYER);
Target->BlockLogout(60, false);
if(Master->Type == PLAYER && Target->Type == PLAYER){
((TPlayer*)Master)->RecordAttack(Target->ID);
}
this->DelayAttack(200);
// TODO(fusion): This `Range` value doesn't make a lot of sense.
int Range = this->GetDistance();
if(Range == 1){
if(Distance > 1){
throw TARGETOUTOFRANGE;
}
this->CloseAttack(Target);
}else{
if(Range < 2 || Range > 3){
throw ERROR;
}
// TODO(fusion): These are related to the maximum visible distance on
// each coordinate.
if(std::abs(Master->posx - Target->posx) > 7
|| std::abs(Master->posy - Target->posy) > 5){
throw TARGETOUTOFRANGE;
}
// NOTE(fusion): Originally, this was a single function `RangeAttack`
// and I quickly realized that readability would be massively improved
// by splitting it into `DistanceAttack` and `WandAttack`.
if(this->Missile != NONE || this->Throw != NONE){
this->DistanceAttack(Target);
}else if(this->Wand != NONE){
this->WandAttack(Target);
}else{
throw ERROR;
}
}
this->DelayAttack(2000);
if(Target->IsDead){
this->StopAttack(0);
}
}
void TCombat::CloseAttack(TCreature *Target){
int Attack = this->GetAttackDamage();
int Defense = Target->Combat.GetDefendDamage();
int Damage = Attack - Defense;
if(Damage < 0){
Damage = 0;
}
int DamageDone = Target->Damage(Master, Damage, DAMAGE_PHYSICAL);
if(DamageDone > 0){
this->ActivateLearning();
}
int Poison = GetRacePoison(Master->Race);
if(Poison != 0){
if(DamageDone > 0 || (Attack > Defense && (rand() % 5) == 0)){
int PoisonDamage = random(Poison / 2, Poison);
if(PoisonDamage > 0){
Target->Damage(Master, PoisonDamage, DAMAGE_POISON_PERIODIC);
if(Target->Type == PLAYER){
SendMessage(Target->Connection, TALK_STATUS_MESSAGE, "You are poisoned.");
}
}
}
}
Object Close = this->Close;
if(Close != NONE){
ObjectType CloseType = Close.getObjectType();
if(CloseType.getFlag(WEAROUT)){
uint32 RemainingUses = Close.getAttribute(REMAININGUSES);
if(RemainingUses > 1){
Change(Close, REMAININGUSES, RemainingUses - 1);
}else{
ObjectType WearOutType = (int)CloseType.getAttribute(WEAROUTTARGET);
Change(Close, WearOutType, 0);
this->CheckCombatValues();
}
}
}
}
void TCombat::WandAttack(TCreature *Target){
ASSERT(this->Wand != NONE);
TCreature *Master = this->Master;
int Distance = std::max<int>(
std::abs(Master->posx - Target->posx),
std::abs(Master->posy - Target->posy));
ObjectType WandType = this->Wand.getObjectType();
if(Distance > (int)WandType.getAttribute(WANDRANGE)){
throw TARGETOUTOFRANGE;
}
if(!ThrowPossible(Master->posx, Master->posy, Master->posz,
Target->posx, Target->posy, Target->posz, 0)){
throw TARGETHIDDEN;
}
int DamageType = WandType.getAttribute(WANDDAMAGETYPE);
int AnimType = WandType.getAttribute(WANDMISSILE);
int ManaConsumption = WandType.getAttribute(WANDMANACONSUMPTION);
int AttackStrength = WandType.getAttribute(WANDATTACKSTRENGTH);
int AttackVariation = (int)WandType.getAttribute(WANDATTACKVARIATION);
try{
CheckMana(Master, ManaConsumption, 0, 0);
}catch(RESULT r){
if(r == NOTENOUGHMANA){
throw OUTOFAMMO;
}else{
throw r;
}
}
int Damage = AttackStrength + random(-AttackVariation, AttackVariation);
if(Target->Damage(Master, Damage, DamageType) > 0){
this->ActivateLearning();
}
::Missile(Master->CrObject, Target->CrObject, AnimType);
}
void TCombat::DistanceAttack(TCreature *Target){
ASSERT(this->Missile != NONE || this->Throw != NONE);
int HitChance;
int DamageType;
int AnimType;
int Fragility;
int SpecialEffect;
int EffectStrength;
TCreature *Master = this->Master;
int DistanceX = std::abs(Master->posx - Target->posx);
int DistanceY = std::abs(Master->posy - Target->posy);
int Distance = std::max<int>(DistanceX, DistanceY);
if(this->Missile != NONE){
this->GetAmmo();
if(this->Ammo == NONE || !this->Ammo.exists()){
throw OUTOFAMMO;
}
ObjectType BowType = this->Missile.getObjectType();
ObjectType AmmoType = this->Ammo.getObjectType();
if(Distance > (int)BowType.getAttribute(BOWRANGE)){
throw TARGETOUTOFRANGE;
}
HitChance = 90;
DamageType = DAMAGE_PHYSICAL;
AnimType = AmmoType.getAttribute(AMMOMISSILE);
Fragility = 100;
SpecialEffect = AmmoType.getAttribute(AMMOSPECIALEFFECT);
EffectStrength = AmmoType.getAttribute(AMMOEFFECTSTRENGTH);
}else{
ASSERT(this->Throw != NONE);
ObjectType ThrowType = this->Throw.getObjectType();
if(Distance > (int)ThrowType.getAttribute(THROWRANGE)){
throw TARGETOUTOFRANGE;
}
HitChance = 75;
DamageType = DAMAGE_PHYSICAL;
AnimType = ThrowType.getAttribute(THROWMISSILE);
Fragility = ThrowType.getAttribute(THROWFRAGILITY);
SpecialEffect = ThrowType.getAttribute(THROWSPECIALEFFECT);
EffectStrength = ThrowType.getAttribute(THROWEFFECTSTRENGTH);
}
if(!ThrowPossible(Master->posx, Master->posy, Master->posz,
Target->posx, Target->posy, Target->posz, 0)){
throw TARGETHIDDEN;
}
int Difficulty = (Distance >= 2) ? Distance : 5;
bool Hit = Master->Skills[SKILL_DISTANCE]->Probe(
Difficulty * 15, HitChance, this->LearningPoints > 0);
if(this->LearningPoints > 0){
this->LearningPoints -= 1;
}
int DropX = Target->posx;
int DropY = Target->posy;
int DropZ = Target->posz;
if(Hit){
int Attack = this->GetAttackDamage();
// TODO(fusion): This doesn't make any sense. The disassembly looks
// correct but I feel we're missing something here. Or maybe defense
// doesn't work with ranged attacks but worn them out? But then only
// if the attacker is wearing a shield? This is a probably a bug.
if(this->Shield != NONE){
Target->Combat.GetDefendDamage();
}
if(Target->Damage(Master, Attack, DamageType) > 0){
this->ActivateLearning();
}
}else{
if(DistanceX > 1 || DistanceY > 1){
DropX += (rand() % 3) - 1;
DropY += (rand() % 3) - 1;
}
if(!CoordinateFlag(DropX, DropY, DropZ, BANK)
|| CoordinateFlag(DropX, DropY, DropZ, UNLAY)
|| !ThrowPossible(Master->posx, Master->posy, Master->posz, DropX, DropY, DropZ, 0)){
DropX = Target->posx;
DropY = Target->posy;
}
}
Object DropCon = GetMapContainer(DropX, DropY, DropZ);
::Missile(Master->CrObject, DropCon, AnimType);
if(SpecialEffect == 1){ // POISON ARROW
if(Hit){
Target->Damage(Master, EffectStrength, DAMAGE_POISON_PERIODIC);
}
}else if(SpecialEffect == 2){ // BURST ARROW
int Damage = ComputeDamage(Master, 0, EffectStrength, EffectStrength);
TDamageImpact Impact(Master, DAMAGE_PHYSICAL, Damage, false);
CircleShapeSpell(Master, DropX, DropY, DropZ, INT_MAX,
ANIMATION_NONE, 2, &Impact, EFFECT_FIRE_BURST);
}
try{
if(random(0, 99) < Fragility){
Delete(this->Ammo, 1);
}else{
Move(0, this->Ammo, DropCon, 1, false, NONE);
}
}catch(RESULT r){
if(r != DESTROYED){
error("TCombat::RangeAttack: Konnte Ammo nicht verschieben/löschen"
" (Exception %d, [%d,%d,%d].\n", r, DropX, DropY, DropZ);
}
}
if(!Hit){
GraphicalEffect(DropX, DropY, DropZ, EFFECT_POFF);
}
}
void TCombat::AddDamageToCombatList(uint32 Attacker, uint32 Damage){
this->CombatDamage += Damage;
for(int i = 0; i < NARRAY(this->CombatList); i += 1){
if(this->CombatList[i].ID == Attacker){
this->CombatList[i].Damage += Damage;
this->CombatList[i].TimeStamp = RoundNr;
return;
}
}
int NextEntryIndex = this->ActCombatEntry;
this->CombatList[NextEntryIndex].ID = Attacker;
this->CombatList[NextEntryIndex].Damage = Damage;
this->CombatList[NextEntryIndex].TimeStamp = RoundNr;
NextEntryIndex += 1;
if(NextEntryIndex >= NARRAY(this->CombatList)){
NextEntryIndex = 0;
}
this->ActCombatEntry = NextEntryIndex;
}
uint32 TCombat::GetDamageByCreature(uint32 CreatureID){
uint32 Damage = 0;
for(int i = 0; i < NARRAY(this->CombatList); i += 1){
if(this->CombatList[i].ID == CreatureID){
Damage = this->CombatList[i].Damage;
break;
}
}
return Damage;
}
uint32 TCombat::GetMostDangerousAttacker(void){
uint32 Attacker = 0;
uint32 MaxDamage = 0;
for(int i = 0; i < NARRAY(this->CombatList); i += 1){
if((RoundNr - this->CombatList[i].TimeStamp) < 60
&& this->CombatList[i].Damage > MaxDamage){
Attacker = this->CombatList[i].ID;
MaxDamage = this->CombatList[i].Damage;
}
}
return Attacker;
}
void TCombat::DistributeExperiencePoints(uint32 Exp){
TCreature *Master = this->Master;
print(3, "%s ist gestorben. Verteile %u EXP...\n", Master->Name, Exp);
if(this->CombatDamage == 0){
return;
}
for(int i = 0; i < NARRAY(this->CombatList); i += 1){
TCreature *Attacker = GetCreature(this->CombatList[i].ID);
if(Attacker == NULL || Attacker->IsDead){
continue;
}
int Amount = (int)((Exp * this->CombatList[i].Damage) / this->CombatDamage);
if(Master->Type == PLAYER && Attacker->Type == PLAYER){
if(((TPlayer*)Master)->InPartyWith((TPlayer*)Attacker, true)){
continue;
}
int MasterLevel = Master->Skills[SKILL_LEVEL]->Get();
int AttackerLevel = Attacker->Skills[SKILL_LEVEL]->Get();
int MaxLevel = (MasterLevel * 11) / 10;
if(AttackerLevel >= MaxLevel){
continue;
}
Amount = ((MaxLevel - AttackerLevel) * Amount) / MasterLevel;
print(3, "%s erhält %d EXP.\n", Attacker->Name, Amount);
}
if(Amount > 0){
if(Attacker->Type == PLAYER){
// NOTE(fusion): Enable soul regeneration.
int AttackerLevel = Attacker->Skills[SKILL_LEVEL]->Get();
if(Amount >= AttackerLevel){
int Interval = 120;
if(((TPlayer*)Attacker)->GetActivePromotion()){
Interval = 15;
}
int Count = Attacker->Skills[SKILL_SOUL]->TimerValue() % Interval;
if(Count == 0){
Count = Interval;
}
Attacker->SetTimer(SKILL_SOUL, (240 / Interval), Count, Interval, -1);
}
}
Attacker->Skills[SKILL_LEVEL]->Increase(Amount);
TextualEffect(Attacker->CrObject, COLOR_WHITE, "%d", Amount);
}
}
}

2140
src/game/src/crmain.cc Normal file

File diff suppressed because it is too large Load diff

3168
src/game/src/crnonpl.cc Normal file

File diff suppressed because it is too large Load diff

3181
src/game/src/crplayer.cc Normal file

File diff suppressed because it is too large Load diff

1313
src/game/src/crskill.cc Normal file

File diff suppressed because it is too large Load diff

113
src/game/src/crypto.cc Normal file
View file

@ -0,0 +1,113 @@
#include "crypto.hh"
#include <openssl/err.h>
#include <openssl/pem.h>
static void DumpOpenSSLErrors(const char *Where, const char *What){
error("OpenSSL error(s) while executing %s at %s:\n", What, Where);
ERR_print_errors_cb(
[](const char *str, usize len, void *u) -> int {
// NOTE(fusion): These error strings already have trailing newlines,
// for whatever reason.
error("> %s", str);
return 1;
}, NULL);
}
// TRSAPrivateKey
// =============================================================================
TRSAPrivateKey::TRSAPrivateKey(void){
m_RSA = NULL;
}
TRSAPrivateKey::~TRSAPrivateKey(void){
if(m_RSA){
RSA_free(m_RSA);
m_RSA = NULL;
}
}
bool TRSAPrivateKey::initFromFile(const char *FileName){
if(m_RSA != NULL){
error("TRSAPrivateKey::init: Key already initialized.\n");
return false;
}
FILE *File = fopen(FileName, "rb");
if(File == NULL){
error("TRSAPrivateKey::initFromFile: Failed to open \"%s\".\n", FileName);
return false;
}
m_RSA = PEM_read_RSAPrivateKey(File, NULL, NULL, NULL);
fclose(File);
if(m_RSA == NULL){
error("TRSAPrivateKey::initFromFile: Failed to read key from \"%s\".\n", FileName);
DumpOpenSSLErrors("TRSAPrivateKey::initFromFile", "PEM_read_RSAPrivateKey");
}else if(RSA_size(m_RSA) != 128){
error("TRSAPrivateKey::initFromFile: File \"%s\" doesn't contain a 1024-bit key", FileName);
RSA_free(m_RSA);
m_RSA = NULL;
}
return (m_RSA != NULL);
}
bool TRSAPrivateKey::decrypt(uint8 *Data){
if(m_RSA == NULL){
error("TRSAPrivateKey::decrypt: Key not initialized.\n");
return false;
}
// TODO(fusion): Pass in the length of `Data` for checking.
ASSERT(RSA_size(m_RSA) == 128);
if(RSA_private_decrypt(128, Data, Data, m_RSA, RSA_NO_PADDING) == -1){
DumpOpenSSLErrors("TRSAPrivateKey::decrypt", "RSA_private_decrypt");
return false;
}
return true;
}
// TXTEASymmetricKey
// =============================================================================
void TXTEASymmetricKey::init(TReadBuffer *Buffer){
m_SymmetricKey[0] = Buffer->readQuad();
m_SymmetricKey[1] = Buffer->readQuad();
m_SymmetricKey[2] = Buffer->readQuad();
m_SymmetricKey[3] = Buffer->readQuad();
}
void TXTEASymmetricKey::encrypt(uint8 *Data){
// TODO(fusion): This assumes both data endpoints have the same byte order.
// It's unlikely that there is anything other than little-endian but we
// should use a few helping functions to ensure compatibility.
uint32 Sum = 0x00000000UL;
uint32 Delta = 0x9E3779B9UL;
uint32 V0 = *(uint32*)(&Data[0]);
uint32 V1 = *(uint32*)(&Data[4]);
for(int i = 0; i < 32; i += 1){
V0 += (((V1 << 4) ^ (V1 >> 5)) + V1) ^ (Sum + m_SymmetricKey[Sum & 3]);
Sum += Delta;
V1 += (((V0 << 4) ^ (V0 >> 5)) + V0) ^ (Sum + m_SymmetricKey[(Sum >> 11) & 3]);
}
*(uint32*)(&Data[0]) = V0;
*(uint32*)(&Data[4]) = V1;
}
void TXTEASymmetricKey::decrypt(uint8 *Data){
// TODO(fusion): Same as above.
uint32 Sum = 0xC6EF3720UL;
uint32 Delta = 0x9E3779B9UL;
uint32 V0 = *(uint32*)(&Data[0]);
uint32 V1 = *(uint32*)(&Data[4]);
for(int i = 0; i < 32; i += 1){
V1 -= (((V0 << 4) ^ (V0 >> 5)) + V0) ^ (Sum + m_SymmetricKey[(Sum >> 11) & 3]);
Sum -= Delta;
V0 -= (((V1 << 4) ^ (V1 >> 5)) + V1) ^ (Sum + m_SymmetricKey[Sum & 3]);
}
*(uint32*)(&Data[0]) = V0;
*(uint32*)(&Data[4]) = V1;
}

28
src/game/src/crypto.hh Normal file
View file

@ -0,0 +1,28 @@
#ifndef TIBIA_CRYPTO_HH_
#define TIBIA_CRYPTO_HH_ 1
#include "common.hh"
#include <openssl/rsa.h>
struct TRSAPrivateKey{
TRSAPrivateKey(void);
~TRSAPrivateKey(void);
bool initFromFile(const char *FileName);
bool decrypt(uint8 *Data); // single 128 bytes block
// DATA
// =================
RSA *m_RSA;
};
struct TXTEASymmetricKey{
void init(TReadBuffer *Buffer);
void encrypt(uint8 *Data); // single 8 bytes block
void decrypt(uint8 *Data); // single 8 bytes block
// DATA
// =================
uint32 m_SymmetricKey[4];
};
#endif //TIBIA_CRYPTO_HH_

781
src/game/src/enums.hh Normal file
View file

@ -0,0 +1,781 @@
#ifndef TIBIA_ENUMS_HH_
#define TIBIA_ENUMS_HH_ 1
#include "common.hh"
// TODO(fusion): Probably cleanup these names? Prefix values? Its crazy that
// there are no collision problems (possibly yet).
enum AnimationType: int {
ANIMATION_NONE = 0,
ANIMATION_SPEAR = 1,
ANIMATION_BOLT = 2,
ANIMATION_ARROW = 3,
ANIMATION_FIRE = 4,
ANIMATION_ENERGY = 5,
ANIMATION_POISON_ARROW = 6,
ANIMATION_BURST_ARROW = 7,
ANIMATION_THROWING_STAR = 8,
ANIMATION_THROWING_KNIFE = 9,
ANIMATION_SMALL_STONE = 10,
ANIMATION_DEATH = 11,
ANIMATION_SNOWBALL = 13,
ANIMATION_POWER_BOLT = 14,
ANIMATION_POISON = 15,
};
// NOTE(fusion): Not in debug symbols.
enum AttackMode: uint8 {
ATTACK_MODE_OFFENSIVE = 1,
ATTACK_MODE_BALANCED = 2,
ATTACK_MODE_DEFENSIVE = 3,
};
enum BehaviourActionType: int {
BEHAVIOUR_ACTION_NONE = 0,
BEHAVIOUR_ACTION_REPLY = 1,
BEHAVIOUR_ACTION_SET_VARIABLE = 2,
BEHAVIOUR_ACTION_SET_SKILL = 3,
BEHAVIOUR_ACTION_FUNCTION2 = 4,
BEHAVIOUR_ACTION_FUNCTION1 = 5,
BEHAVIOUR_ACTION_FUNCTION0 = 6,
BEHAVIOUR_ACTION_CHANGESTATE = 7,
BEHAVIOUR_ACTION_SET_SKILL_TIMER = 8,
BEHAVIOUR_ACTION_REPEAT = 9,
BEHAVIOUR_ACTION_FUNCTION3 = 10,
};
enum BehaviourConditionType: int {
BEHAVIOUR_CONDITION_NONE = 0,
BEHAVIOUR_CONDITION_TEXT = 1,
BEHAVIOUR_CONDITION_PROPERTY = 2,
BEHAVIOUR_CONDITION_PARAMETER = 3,
BEHAVIOUR_CONDITION_EXPRESSION = 4,
BEHAVIOUR_CONDITION_SHORTCIRCUIT = 5,
};
enum BehaviourNodeType: int {
BEHAVIOUR_NODE_NONE = 0,
BEHAVIOUR_NODE_CMP_LT = 1,
BEHAVIOUR_NODE_CMP_GT = 2,
BEHAVIOUR_NODE_CMP_EQ = 3,
BEHAVIOUR_NODE_CMP_NEQ = 4,
BEHAVIOUR_NODE_CMP_LE = 5,
BEHAVIOUR_NODE_CMP_GE = 6,
BEHAVIOUR_NODE_ADD = 7,
BEHAVIOUR_NODE_SUB = 8,
BEHAVIOUR_NODE_MUL = 9,
BEHAVIOUR_NODE_PARAMETER = 10,
BEHAVIOUR_NODE_NUMBER = 11,
BEHAVIOUR_NODE_TOPIC = 12,
BEHAVIOUR_NODE_PRICE = 13,
BEHAVIOUR_NODE_AMOUNT = 14,
BEHAVIOUR_NODE_SKILL = 15,
BEHAVIOUR_NODE_COUNT = 16,
BEHAVIOUR_NODE_COUNTMONEY = 17,
BEHAVIOUR_NODE_TYPE = 18,
BEHAVIOUR_NODE_DATA = 19,
BEHAVIOUR_NODE_SPELLKNOWN = 20,
BEHAVIOUR_NODE_SPELLLEVEL = 21,
BEHAVIOUR_NODE_RANDOM = 22,
BEHAVIOUR_NODE_QUESTVALUE = 23,
};
enum BehaviourProperty: int {
BEHAVIOUR_PROPERTY_NONE = 0,
BEHAVIOUR_PROPERTY_ADDRESS = 1,
BEHAVIOUR_PROPERTY_BUSY = 2,
BEHAVIOUR_PROPERTY_VANISH = 3,
BEHAVIOUR_PROPERTY_MALE = 4,
BEHAVIOUR_PROPERTY_FEMALE = 5,
BEHAVIOUR_PROPERTY_KNIGHT = 6,
BEHAVIOUR_PROPERTY_PALADIN = 7,
BEHAVIOUR_PROPERTY_SORCERER = 8,
BEHAVIOUR_PROPERTY_DRUID = 9,
BEHAVIOUR_PROPERTY_PREMIUM = 10,
BEHAVIOUR_PROPERTY_PROMOTED = 11,
BEHAVIOUR_PROPERTY_PZBLOCK = 12,
BEHAVIOUR_PROPERTY_NONPVP = 13,
BEHAVIOUR_PROPERTY_PVPENFORCED = 14,
};
enum BloodType: int {
BT_BLOOD = 0,
BT_SLIME = 1,
BT_BONES = 2,
BT_FIRE = 3,
BT_ENERGY = 4,
};
// NOTE(fusion): Not in debug symbols.
enum ChaseMode: uint8 {
CHASE_MODE_NONE = 0,
CHASE_MODE_CLOSE = 1,
CHASE_MODE_RANGE = 2,
};
// NOTE(fusion): Not in debug symbols.
enum Color: int {
COLOR_BLACK = 0,
COLOR_BLUE = 5,
COLOR_LIGHTGREEN = 30,
COLOR_LIGHTBLUE = 35,
COLOR_LIGHTGRAY = 129,
COLOR_RED = 180,
COLOR_ORANGE = 198,
COLOR_WHITE = 215,
};
enum CONNECTIONSTATE: int {
CONNECTION_FREE = 0,
CONNECTION_ASSIGNED = 1,
CONNECTION_CONNECTED = 2,
CONNECTION_LOGIN = 3,
CONNECTION_GAME = 4,
CONNECTION_DEAD = 5,
CONNECTION_LOGOUT = 6,
CONNECTION_DISCONNECTED = 7,
};
enum CreatureType: int {
PLAYER = 0,
MONSTER = 1,
NPC = 2,
};
// NOTE(fusion): Not in debug symbols.
enum DamageType: int {
DAMAGE_NONE = 0x0000,
DAMAGE_PHYSICAL = 0x0001,
DAMAGE_POISON = 0x0002,
DAMAGE_FIRE = 0x0004,
DAMAGE_ENERGY = 0x0008,
DAMAGE_POISON_PERIODIC = 0x0020, // Better name?
DAMAGE_FIRE_PERIODIC = 0x0040, // Better name?
DAMAGE_ENERGY_PERIODIC = 0x0080, // Better name?
DAMAGE_LIFEDRAIN = 0x0100,
DAMAGE_MANADRAIN = 0x0200,
};
// NOTE(fusion): Not in debug symbols.
enum Direction: int {
DIRECTION_NONE = -1,
DIRECTION_NORTH = 0,
DIRECTION_EAST = 1,
DIRECTION_SOUTH = 2,
DIRECTION_WEST = 3,
DIRECTION_SOUTHWEST = 4,
DIRECTION_SOUTHEAST = 5,
DIRECTION_NORTHWEST = 6,
DIRECTION_NORTHEAST = 7,
};
// TODO(fusion): Review these names.
enum EffectType: int {
EFFECT_NONE = 0,
EFFECT_BLOOD_HIT = 1,
EFFECT_MANA_HIT = 2,
EFFECT_POFF = 3,
EFFECT_BLOCK_HIT = 4,
EFFECT_EXPLOSION = 5,
EFFECT_FIRE_BLAST = 6,
EFFECT_FIRE_BURST = 7,
EFFECT_REBUKE = 8, // not sure about this one
EFFECT_POISON = 9,
EFFECT_BONE_HIT = 10,
EFFECT_ENERGY = 11,
EFFECT_ENERGY_HIT = 12,
EFFECT_MAGIC_BLUE = 13,
EFFECT_MAGIC_RED = 14,
EFFECT_MAGIC_GREEN = 15,
EFFECT_FIRE = 16,
EFFECT_POISON_HIT = 17,
EFFECT_DEATH = 18,
EFFECT_MELODY_GREEN = 19,
EFFECT_MELODY_RED = 20,
EFFECT_POISON_BURST = 21,
EFFECT_MELODY_YELLOW = 22,
EFFECT_MELODY_PURPLE = 23,
EFFECT_MELODY_BLUE = 24,
EFFECT_MELODY_WHITE = 25,
};
enum FLAG: int {
BANK = 0,
CLIP = 1,
BOTTOM = 2,
TOP = 3,
CONTAINER = 4,
CHEST = 5,
CUMULATIVE = 6,
USEEVENT = 7,
CHANGEUSE = 8,
FORCEUSE = 9,
MULTIUSE = 10,
DISTUSE = 11,
MOVEMENTEVENT = 12,
COLLISIONEVENT = 13,
SEPARATIONEVENT = 14,
KEY = 15,
KEYDOOR = 16,
NAMEDOOR = 17,
LEVELDOOR = 18,
QUESTDOOR = 19,
BED = 20,
FOOD = 21,
RUNE = 22,
INFORMATION = 23,
TEXT = 24,
WRITE = 25,
WRITEONCE = 26,
LIQUIDCONTAINER = 27,
LIQUIDSOURCE = 28,
LIQUIDPOOL = 29,
TELEPORTABSOLUTE = 30,
TELEPORTRELATIVE = 31,
UNPASS = 32,
UNMOVE = 33,
UNTHROW = 34,
UNLAY = 35,
AVOID = 36,
MAGICFIELD = 37,
RESTRICTLEVEL = 38,
RESTRICTPROFESSION = 39,
TAKE = 40,
HANG = 41,
HOOKSOUTH = 42,
HOOKEAST = 43,
ROTATE = 44,
DESTROY = 45,
CLOTHES = 46,
SKILLBOOST = 47,
PROTECTION = 48,
LIGHT = 49,
ROPESPOT = 50,
CORPSE = 51,
EXPIRE = 52,
EXPIRESTOP = 53,
WEAROUT = 54,
WEAPON = 55,
SHIELD = 56,
BOW = 57,
THROW = 58,
WAND = 59,
AMMO = 60,
ARMOR = 61,
HEIGHT = 62,
DISGUISE = 63,
SHOWDETAIL = 64,
SPECIALOBJECT = 65,
};
enum GAMESTATE: int {
GAME_STARTING = 0,
GAME_RUNNING = 1,
GAME_CLOSING = 2,
GAME_ENDING = 3,
};
enum HouseList: uint8 {
GUESTLIST = 1,
SUBOWNERLIST = 2,
DOORLIST = 3,
};
enum INSTANCEATTRIBUTE: int {
CONTENT = 0,
CHESTQUESTNUMBER = 1,
AMOUNT = 2,
KEYNUMBER = 3,
KEYHOLENUMBER = 4,
DOORLEVEL = 5,
DOORQUESTNUMBER = 6,
DOORQUESTVALUE = 7,
CHARGES = 8,
TEXTSTRING = 9,
EDITOR = 10,
CONTAINERLIQUIDTYPE = 11,
POOLLIQUIDTYPE = 12,
ABSTELEPORTDESTINATION = 13,
RESPONSIBLE = 14,
REMAININGEXPIRETIME = 15,
SAVEDEXPIRETIME = 16,
REMAININGUSES = 17,
};
// NOTE(fusion): Not in debug symbols.
enum InventorySlot: int {
INVENTORY_ANY = 0,
INVENTORY_HEAD = 1,
INVENTORY_NECK = 2,
INVENTORY_BAG = 3,
INVENTORY_TORSO = 4,
INVENTORY_RIGHTHAND = 5,
INVENTORY_LEFTHAND = 6,
INVENTORY_LEGS = 7,
INVENTORY_FEET = 8,
INVENTORY_FINGER = 9,
INVENTORY_AMMO = 10,
// NOTE(fusion): For iterating over inventory slots.
INVENTORY_FIRST = INVENTORY_HEAD,
INVENTORY_LAST = INVENTORY_AMMO,
// NOTE(fusion): For iterating over hand slots.
INVENTORY_HAND_FIRST = INVENTORY_RIGHTHAND,
INVENTORY_HAND_LAST = INVENTORY_LEFTHAND,
// NOTE(fusion): For iterating over container slots.
CONTAINER_FIRST = 64,
CONTAINER_LAST = 79,
};
enum KNOWNCREATURESTATE: int {
KNOWNCREATURE_FREE = 0,
KNOWNCREATURE_UPTODATE = 1,
KNOWNCREATURE_OUTDATED = 2
};
// NOTE(fusion): Not in debug symbols.
enum LiquidColor: uint8 {
LIQUID_COLORLESS = 0,
LIQUID_BLUE = 1,
LIQUID_RED = 2,
LIQUID_BROWN = 3,
LIQUID_GREEN = 4,
LIQUID_YELLOW = 5,
LIQUID_WHITE = 6,
LIQUID_PURPLE = 7,
};
// NOTE(fusion): Not in debug symbols.
enum LiquidType: int {
LIQUID_NONE = 0,
LIQUID_WATER = 1,
LIQUID_WINE = 2,
LIQUID_BEER = 3,
LIQUID_MUD = 4,
LIQUID_BLOOD = 5,
LIQUID_SLIME = 6,
LIQUID_OIL = 7,
LIQUID_URINE = 8,
LIQUID_MILK = 9,
LIQUID_MANA = 10,
LIQUID_LIFE = 11,
LIQUID_LEMONADE = 12,
};
enum PartyShield: int {
PARTY_SHIELD_NONE = 0,
PARTY_SHIELD_HOST = 1,
PARTY_SHIELD_GUEST = 2,
PARTY_SHIELD_MEMBER = 3,
PARTY_SHIELD_LEADER = 4,
};
// NOTE(fusion): Not in debug symbols.
enum PROFESSION: uint8 {
PROFESSION_NONE = 0,
PROFESSION_KNIGHT = 1,
PROFESSION_PALADIN = 2,
PROFESSION_SORCERER = 3,
PROFESSION_DRUID = 4,
PROFESSION_PROMOTION = 10,
PROFESSION_ELITE_KNIGHT = 11,
PROFESSION_ROYAL_PALADIN = 12,
PROFESSION_MASTER_SORCERER = 13,
PROFESSION_ELDER_DRUID = 14,
};
enum RESULT: int {
ERROR = -1,
NOERROR = 0,
NOTACCESSIBLE = 1,
NOTMOVABLE = 2,
NOTTAKABLE = 3,
NOROOM = 4,
OUTOFRANGE = 5,
OUTOFHOME = 6,
CANNOTTHROW = 7,
TOOHEAVY = 8,
CROSSREFERENCE = 9,
CONTAINERFULL = 10,
WRONGPOSITION = 11,
WRONGPOSITION2 = 12,
WRONGCLOTHES = 13,
HANDSNOTFREE = 14,
HANDBLOCKED = 15,
ONEWEAPONONLY = 16,
NOMATCH = 17,
NOTCUMULABLE = 18,
TOOMANYPARTS = 19,
EMPTYCONTAINER = 20,
SPLITOBJECT = 21,
NOKEYMATCH = 22,
UPSTAIRS = 23,
DOWNSTAIRS = 24,
CREATURENOTEXISTING = 25,
PLAYERNOTEXISTING = 26,
PLAYERNOTONLINE = 27,
NAMEAMBIGUOUS = 28,
NOTUSABLE = 29,
FEDUP = 30,
DESTROYED = 31,
SPELLUNKNOWN = 32,
LOWMAGICLEVEL = 33,
MAGICITEM = 34,
NOTENOUGHMANA = 35,
NOSKILL = 36,
TARGETLOST = 37,
OUTOFAMMO = 38,
NOCREATURE = 39,
TOOLONG = 40,
TARGETOUTOFRANGE = 41,
TARGETHIDDEN = 42,
ATTACKNOTALLOWED = 43,
NOWAY = 44,
LOGINERROR = 45,
LOGINABORT = 46,
PROTECTIONZONE = 47,
ENTERPROTECTIONZONE = 48,
EXHAUSTED = 49,
NOTINVITED = 50,
NOPREMIUMACCOUNT = 51,
MOVENOTPOSSIBLE = 52,
ALREADYTRADING = 53,
PARTNERTRADING = 54,
TOOMANYOBJECTS = 55,
TOOMANYSLAVES = 56,
NOTTURNABLE = 57,
SECUREMODE = 58,
NOTENOUGHSOULPOINTS = 59,
LOWLEVEL = 60,
};
enum RIGHT: int {
PREMIUM_ACCOUNT = 0,
NOTATION = 1,
NAMELOCK = 2,
STATEMENT_REPORT = 3,
BANISHMENT = 4,
FINAL_WARNING = 5,
IP_BANISHMENT = 6,
KICK = 7,
HOME_TELEPORT = 8,
GAMEMASTER_BROADCAST = 9,
ANONYMOUS_BROADCAST = 10,
NO_BANISHMENT = 11,
ALLOW_MULTICLIENT = 12,
LOG_COMMUNICATION = 13,
READ_GAMEMASTER_CHANNEL = 14,
READ_TUTOR_CHANNEL = 15,
HIGHLIGHT_HELP_CHANNEL = 16,
SEND_BUGREPORTS = 17,
NAME_INSULTING = 18,
NAME_SENTENCE = 19,
NAME_NONSENSICAL_LETTERS = 20,
NAME_BADLY_FORMATTED = 21,
NAME_NO_PERSON = 22,
NAME_CELEBRITY = 23,
NAME_COUNTRY = 24,
NAME_FAKE_IDENTITY = 25,
NAME_FAKE_POSITION = 26,
STATEMENT_INSULTING = 27,
STATEMENT_SPAMMING = 28,
STATEMENT_ADVERT_OFFTOPIC = 29,
STATEMENT_ADVERT_MONEY = 30,
STATEMENT_NON_ENGLISH = 31,
STATEMENT_CHANNEL_OFFTOPIC = 32,
STATEMENT_VIOLATION_INCITING = 33,
CHEATING_BUG_ABUSE = 34,
CHEATING_GAME_WEAKNESS = 35,
CHEATING_MACRO_USE = 36,
CHEATING_MODIFIED_CLIENT = 37,
CHEATING_HACKING = 38,
CHEATING_MULTI_CLIENT = 39,
CHEATING_ACCOUNT_TRADING = 40,
CHEATING_ACCOUNT_SHARING = 41,
GAMEMASTER_THREATENING = 42,
GAMEMASTER_PRETENDING = 43,
GAMEMASTER_INFLUENCE = 44,
GAMEMASTER_FALSE_REPORTS = 45,
KILLING_EXCESSIVE_UNJUSTIFIED = 46,
DESTRUCTIVE_BEHAVIOUR = 47,
SPOILING_AUCTION = 48,
INVALID_PAYMENT = 49,
TELEPORT_TO_CHARACTER = 50,
TELEPORT_TO_MARK = 51,
TELEPORT_VERTICAL = 52,
TELEPORT_TO_COORDINATE = 53,
LEVITATE = 54,
SPECIAL_MOVEUSE = 55,
MODIFY_GOSTRENGTH = 56,
SHOW_COORDINATE = 57,
RETRIEVE = 58,
ENTER_HOUSES = 59,
OPEN_NAMEDOORS = 60,
INVULNERABLE = 61,
UNLIMITED_MANA = 62,
KEEP_INVENTORY = 63,
ALL_SPELLS = 64,
UNLIMITED_CAPACITY = 65,
ZERO_CAPACITY = 66,
ATTACK_EVERYWHERE = 67,
NO_ATTACK = 68,
NO_RUNES = 69,
NO_LOGOUT_BLOCK = 70,
GAMEMASTER_OUTFIT = 71,
ILLUMINATE = 72,
CHANGE_PROFESSION = 73,
IGNORED_BY_MONSTERS = 74,
SHOW_KEYHOLE_NUMBERS = 75,
CREATE_OBJECTS = 76,
CREATE_MONEY = 77,
CREATE_MONSTERS = 78,
CHANGE_SKILLS = 79,
CLEANUP_FIELDS = 80,
NO_STATISTICS = 81,
};
enum SecureMode: uint8 {
SECURE_MODE_DISABLED = 0,
SECURE_MODE_ENABLED = 1,
};
enum SITUATION: int {
DEFAULT = 0,
ADDRESS = 1,
ADDRESSQUEUE = 2,
BUSY = 3,
VANISH = 4,
};
// NOTE(fusion): Not in debug symbols.
enum Skill: int {
SKILL_LEVEL = 0,
SKILL_MAGIC_LEVEL = 1,
SKILL_HITPOINTS = 2,
SKILL_MANA = 3,
SKILL_GO_STRENGTH = 4, // speed?
SKILL_CARRY_STRENGTH = 5, // capacity?
SKILL_SHIELDING = 6,
SKILL_DISTANCE = 7,
SKILL_SWORD = 8,
SKILL_CLUB = 9,
SKILL_AXE = 10,
SKILL_FIST = 11,
SKILL_MAGIC_DEFENSE = 12,
SKILL_FISHING = 13,
SKILL_FED = 14,
SKILL_LIGHT = 15,
SKILL_ILLUSION = 16,
SKILL_POISON = 17,
SKILL_BURNING = 18,
SKILL_ENERGY = 19,
SKILL_DRUNKEN = 20,
SKILL_MANASHIELD = 21,
SKILL_SOUL = 22,
};
enum Skull: int {
SKULL_NONE = 0,
SKULL_YELLOW = 1,
SKULL_GREEN = 2,
SKULL_WHITE = 3,
SKULL_RED = 4,
};
// IMPORTANT(fusion): All `DEFAULT_*` values here were renamed from `INVENTORY_*`
// to avoid collisions with `InventorySlot`. I could also have chosen other prefix
// for inventory slots but I feel we'd be wasting them here where their meaning
// were also not clear.
enum SPECIALMEANING: int {
MONEY_ONE = 1,
MONEY_HUNDRED = 2,
MONEY_TENTHOUSAND = 3,
DEFAULT_RIGHTHAND = 10,
DEFAULT_LEFTHAND = 11,
DEFAULT_BODY_MALE = 12,
DEFAULT_BODY_FEMALE = 13,
DEFAULT_CONTAINER = 14,
DEFAULT_FOOD = 15,
DEPOT_LOCKER = 20,
DEPOT_CHEST = 21,
PARCEL_NEW = 22,
PARCEL_STAMPED = 23,
PARCEL_LABEL = 24,
LETTER_NEW = 25,
LETTER_STAMPED = 26,
BLOOD_SPLASH = 30,
BLOOD_POOL = 31,
RUNE_BLANK = 40,
MAGICFIELD_FIRE_DANGEROUS = 41,
MAGICFIELD_FIRE_HARMLESS = 42,
MAGICFIELD_POISON_DANGEROUS = 43,
MAGICFIELD_POISON_HARMLESS = 44,
MAGICFIELD_ENERGY_DANGEROUS = 45,
MAGICFIELD_ENERGY_HARMLESS = 46,
MAGICFIELD_MAGICWALL = 47,
MAGICFIELD_RUSHWOOD = 48,
};
enum SpellShapeType: int {
SHAPE_ACTOR = 0,
SHAPE_VICTIM = 1,
SHAPE_ORIGIN = 2,
SHAPE_DESTINATION = 3,
SHAPE_ANGLE = 4,
};
enum SpellImpactType: int {
IMPACT_DAMAGE = 0,
IMPACT_FIELD = 1,
IMPACT_HEALING = 2,
IMPACT_SPEED = 3,
IMPACT_DRUNKEN = 4,
IMPACT_STRENGTH = 5,
IMPACT_OUTFIT = 6,
IMPACT_SUMMON = 7,
};
enum STATE: int {
SLEEPING = 0,
IDLE = 1,
UNDERATTACK = 2,
TALKING = 3,
LEAVING = 4,
ATTACKING = 5,
PANIC = 6,
};
enum TALK_MODE: int {
TALK_SAY = 1,
TALK_WHISPER = 2,
TALK_YELL = 3,
TALK_PRIVATE_MESSAGE = 4,
TALK_CHANNEL_CALL = 5,
TALK_GAMEMASTER_REQUEST = 6,
TALK_GAMEMASTER_ANSWER = 7,
TALK_PLAYER_ANSWER = 8,
TALK_GAMEMASTER_BROADCAST = 9,
TALK_GAMEMASTER_CHANNELCALL = 10,
TALK_GAMEMASTER_MESSAGE = 11,
TALK_HIGHLIGHT_CHANNELCALL = 12,
TALK_ANONYMOUS_BROADCAST = 13,
TALK_ANONYMOUS_CHANNELCALL = 14,
TALK_ANONYMOUS_MESSAGE = 15,
TALK_ANIMAL_LOW = 16,
TALK_ANIMAL_LOUD = 17,
TALK_ADMIN_MESSAGE = 18,
TALK_EVENT_MESSAGE = 19,
TALK_LOGIN_MESSAGE = 20,
TALK_STATUS_MESSAGE = 21,
TALK_INFO_MESSAGE = 22,
TALK_FAILURE_MESSAGE = 23,
};
enum ToDoType: int {
TDWait = 0,
TDGo = 1,
TDRotate = 2,
TDMove = 3,
TDTrade = 4,
TDUse = 5,
TDTurn = 6,
TDAttack = 7,
TDTalk = 8,
TDChangeState = 9,
};
enum TOKEN: int {
ENDOFFILE = 0,
IDENTIFIER = 1,
NUMBER = 2,
STRING = 3,
BYTES = 4,
COORDINATE = 5,
SPECIAL = 6,
};
enum TYPEATTRIBUTE: int {
WAYPOINTS = 0,
CAPACITY = 1,
CHANGETARGET = 2,
KEYDOORTARGET = 3,
NAMEDOORTARGET = 4,
LEVELDOORTARGET = 5,
QUESTDOORTARGET = 6,
NUTRITION = 7,
INFORMATIONTYPE = 8,
FONTSIZE = 9,
MAXLENGTH = 10,
MAXLENGTHONCE = 11,
SOURCELIQUIDTYPE = 12,
ABSTELEPORTEFFECT = 13,
RELTELEPORTDISPLACEMENT = 14,
RELTELEPORTEFFECT = 15,
AVOIDDAMAGETYPES = 16,
MINIMUMLEVEL = 17,
PROFESSIONS = 18,
WEIGHT = 19,
ROTATETARGET = 20,
DESTROYTARGET = 21,
BODYPOSITION = 22,
SKILLNUMBER = 23,
SKILLMODIFICATION = 24,
PROTECTIONDAMAGETYPES = 25,
DAMAGEREDUCTION = 26,
BRIGHTNESS = 27,
LIGHTCOLOR = 28,
CORPSETYPE = 29,
TOTALEXPIRETIME = 30,
EXPIRETARGET = 31,
TOTALUSES = 32,
WEAROUTTARGET = 33,
WEAPONTYPE = 34,
WEAPONATTACKVALUE = 35,
WEAPONDEFENDVALUE = 36,
SHIELDDEFENDVALUE = 37,
BOWRANGE = 38,
BOWAMMOTYPE = 39,
THROWRANGE = 40,
THROWATTACKVALUE = 41,
THROWDEFENDVALUE = 42,
THROWMISSILE = 43,
THROWSPECIALEFFECT = 44,
THROWEFFECTSTRENGTH = 45,
THROWFRAGILITY = 46,
WANDRANGE = 47,
WANDMANACONSUMPTION = 48,
WANDATTACKSTRENGTH = 49,
WANDATTACKVARIATION = 50,
WANDDAMAGETYPE = 51,
WANDMISSILE = 52,
AMMOTYPE = 53,
AMMOATTACKVALUE = 54,
AMMOMISSILE = 55,
AMMOSPECIALEFFECT = 56,
AMMOEFFECTSTRENGTH = 57,
ARMORVALUE = 58,
ELEVATION = 59,
DISGUISETARGET = 60,
MEANING = 61,
};
enum TWorldType: int {
NORMAL = 0,
NON_PVP = 1,
PVP_ENFORCED = 2,
};
enum WeaponType: int {
WEAPON_NONE = 0,
WEAPON_SWORD = 1,
WEAPON_CLUB = 2,
WEAPON_AXE = 3,
WEAPON_SHIELD = 4,
WEAPON_AMMO = 5,
WEAPON_THROW = 6,
};
#endif //TIBIA_ENUMS_HH_

1966
src/game/src/houses.cc Normal file

File diff suppressed because it is too large Load diff

106
src/game/src/houses.hh Normal file
View file

@ -0,0 +1,106 @@
#ifndef TIBIA_HOUSES_HH_
#define TIBIA_HOUSES_HH_ 1
#include "common.hh"
#include "containers.hh"
#include "map.hh"
#define MAX_HOUSE_GUEST_NAME 60
struct TPlayer;
struct TPlayerData;
struct THelpDepot {
uint32 CharacterID;
Object Box;
int DepotNr;
};
struct THouseArea {
uint16 ID;
int SQMPrice;
int DepotNr;
};
struct THouseGuest {
char Name[MAX_HOUSE_GUEST_NAME];
};
struct THouse {
THouse(void);
// TODO(fusion): Same as `TChannel` in `operate.hh`.
THouse(const THouse &Other);
void operator=(const THouse &Other);
// DATA
// =================
uint16 ID;
char Name[50];
char Description[500];
int Size;
int Rent;
int DepotNr;
bool NoAuction;
bool GuildHouse;
int ExitX;
int ExitY;
int ExitZ;
int CenterX;
int CenterY;
int CenterZ;
uint32 OwnerID;
char OwnerName[30];
int LastTransition;
int PaidUntil;
vector<THouseGuest> Subowner;
int Subowners;
vector<THouseGuest> Guest;
int Guests;
int Help;
};
THouseArea *GetHouseArea(uint16 ID);
int CheckAccessRight(const char *Rule, TPlayer *Player);
THouse *GetHouse(uint16 ID);
bool IsOwner(uint16 HouseID, TPlayer *Player);
bool IsSubowner(uint16 HouseID, TPlayer *Player, int TimeStamp);
bool IsGuest(uint16 HouseID, TPlayer *Player, int TimeStamp);
bool IsInvited(uint16 HouseID, TPlayer *Player, int TimeStamp);
const char *GetHouseName(uint16 HouseID);
const char *GetHouseOwner(uint16 HouseID);
void ShowSubownerList(uint16 HouseID, TPlayer *Player, char *Buffer);
void ShowGuestList(uint16 HouseID, TPlayer *Player, char *Buffer);
void ChangeSubowners(uint16 HouseID, TPlayer *Player, const char *Buffer);
void ChangeGuests(uint16 HouseID, TPlayer *Player, const char *Buffer);
void GetExitPosition(uint16 HouseID, int *x, int *y, int *z);
void KickGuest(uint16 HouseID, TPlayer *Guest);
void KickGuest(uint16 HouseID, TPlayer *Host, TPlayer *Guest);
void KickGuests(uint16 HouseID);
bool MayOpenDoor(Object Door, TPlayer *Player);
void ShowNameDoor(Object Door, TPlayer *Player, char *Buffer);
void ChangeNameDoor(Object Door, TPlayer *Player, const char *Buffer);
void CleanField(int x, int y, int z, Object Depot);
void CleanHouse(THouse *House, TPlayerData *PlayerData);
void ClearHouse(THouse *House);
bool FinishAuctions(void);
bool TransferHouses(void);
bool EvictFreeAccounts(void);
bool EvictDeletedCharacters(void);
bool EvictExGuildLeaders(void);
void CollectRent(void);
void ProcessRent(void);
bool StartAuctions(void);
bool UpdateHouseOwners(void);
void PrepareHouseCleanup(void);
void FinishHouseCleanup(void);
void CleanHouseField(int x, int y, int z);
void LoadHouseAreas(void);
void LoadHouses(void);
void LoadOwners(void);
void SaveOwners(void);
void ProcessHouses(void);
void InitHouses(void);
void ExitHouses(void);
#endif //TIBIA_HOUSES_HH_

1434
src/game/src/info.cc Normal file

File diff suppressed because it is too large Load diff

53
src/game/src/info.hh Normal file
View file

@ -0,0 +1,53 @@
#ifndef TIBIA_INFO_HH_
#define TIBIA_INFO_HH_ 1
#include "common.hh"
#include "map.hh"
const char *GetLiquidName(int LiquidType);
uint8 GetLiquidColor(int LiquidType);
const char *GetName(Object Obj);
const char *GetInfo(Object Obj);
int GetWeight(Object Obj, int Count);
int GetCompleteWeight(Object Obj);
int GetRowWeight(Object Obj);
uint32 GetObjectCreatureID(Object Obj);
int GetObjectBodyPosition(Object Obj);
int GetObjectRNum(Object Obj);
bool ObjectInRange(uint32 CreatureID, Object Obj, int Range);
bool ObjectAccessible(uint32 CreatureID, Object Obj, int Range);
int ObjectDistance(Object Obj1, Object Obj2);
Object GetBodyContainer(uint32 CreatureID, int Position);
Object GetBodyObject(uint32 CreatureID, int Position);
Object GetTopObject(int x, int y, int z, bool Move);
Object GetContainer(uint32 CreatureID, int x, int y, int z);
Object GetObject(uint32 CreatureID, int x, int y, int z, int RNum, ObjectType Type);
Object GetRowObject(Object Obj, ObjectType Type, uint32 Value, bool Recurse);
Object GetInventoryObject(uint32 CreatureID, ObjectType Type, uint32 Value);
bool IsHeldByContainer(Object Obj, Object Con);
int CountObjectsInContainer(Object Con);
int CountObjects(Object Obj);
int CountObjects(Object Obj, ObjectType Type, uint32 Value);
int CountInventoryObjects(uint32 CreatureID, ObjectType Type, uint32 Value);
int CountMoney(Object Obj);
int CountInventoryMoney(uint32 CreatureID);
void CalculateChange(int Amount, int *Gold, int *Platinum, int *Crystal);
int GetHeight(int x, int y, int z);
bool JumpPossible(int x, int y, int z, bool AvoidPlayers);
bool FieldPossible(int x, int y, int z, int FieldType);
bool SearchFreeField(int *x, int *y, int *z, int Distance, uint16 HouseID, bool Jump);
bool SearchLoginField(int *x, int *y, int *z, int Distance, bool Player);
bool SearchSpawnField(int *x, int *y, int *z, int Distance, bool Player);
bool SearchFlightField(uint32 FugitiveID, uint32 PursuerID, int *x, int *y, int *z);
bool SearchSummonField(int *x, int *y, int *z, int Distance);
bool ThrowPossible(int OrigX, int OrigY, int OrigZ,
int DestX, int DestY, int DestZ, int Power);
void GetCreatureLight(uint32 CreatureID, int *Brightness, int *Color);
int GetInventoryWeight(uint32 CreatureID);
bool CheckRight(uint32 CharacterID, RIGHT Right);
bool CheckBanishmentRight(uint32 CharacterID, int Reason, int Action);
const char *GetBanishmentReason(int Reason);
void InitInfo(void);
void ExitInfo(void);
#endif //TIBIA_INFO_HH_

5163
src/game/src/magic.cc Normal file

File diff suppressed because it is too large Load diff

211
src/game/src/magic.hh Normal file
View file

@ -0,0 +1,211 @@
#ifndef TIBIA_MAGIC_HH_
#define TIBIA_MAGIC_HH_ 1
#include "common.hh"
#include "cr.hh"
#include "map.hh"
enum : int {
FIELD_TYPE_FIRE = 1,
FIELD_TYPE_POISON = 2,
FIELD_TYPE_ENERGY = 3,
FIELD_TYPE_MAGICWALL = 4,
FIELD_TYPE_WILDGROWTH = 5,
};
struct TImpact{
// VIRTUAL FUNCTIONS
// =========================================================================
virtual void handleField(int x, int y, int z); // VTABLE[0]
virtual void handleCreature(TCreature *Victim); // VTABLE[1]
virtual bool isAggressive(void); // VTABLE[2]
// NOTE(fusion): I don't think the original version had a destructor declared
// here but the compiler complains when calling delete (which seems to only be
// used in `TMonster::IdleStimulus`).
virtual ~TImpact(void){
// no-op
}
// DATA
// =========================================================================
//void *VTABLE; // IMPLICIT
};
struct TDamageImpact: TImpact {
TDamageImpact(TCreature *Actor, int DamageType, int Power, bool AllowDefense);
void handleCreature(TCreature *Victim) override;
TCreature *Actor;
int DamageType;
int Power;
bool AllowDefense;
};
struct TFieldImpact: TImpact {
TFieldImpact(TCreature *Actor, int FieldType);
void handleField(int x, int y, int z) override;
TCreature *Actor;
int FieldType;
};
struct THealingImpact: TImpact {
THealingImpact(TCreature *Actor, int Power);
void handleCreature(TCreature *Victim) override;
bool isAggressive(void) override;
TCreature *Actor;
int Power;
};
struct TSpeedImpact: TImpact {
TSpeedImpact(TCreature *Actor, int Percent, int Duration);
void handleCreature(TCreature *Victim) override;
TCreature *Actor;
int Percent;
int Duration;
};
struct TDrunkenImpact: TImpact {
TDrunkenImpact(TCreature *Actor, int Power, int Duration);
void handleCreature(TCreature *Victim) override;
TCreature *Actor;
int Power;
int Duration;
};
struct TStrengthImpact: TImpact {
TStrengthImpact(TCreature *Actor, int Skills, int Percent, int Duration);
void handleCreature(TCreature *Victim) override;
TCreature *Actor;
int Skills;
int Percent;
int Duration;
};
struct TOutfitImpact: TImpact {
TOutfitImpact(TCreature *Actor, TOutfit Outfit, int Duration);
void handleCreature(TCreature *Victim) override;
TCreature *Actor;
TOutfit Outfit;
int Duration;
};
struct TSummonImpact: TImpact {
TSummonImpact(TCreature *Actor, int Race, int Maximum);
void handleField(int x, int y, int z) override;
TCreature *Actor;
int Race;
int Maximum;
};
void ActorShapeSpell(TCreature *Actor, TImpact *Impact, int Effect);
void VictimShapeSpell(TCreature *Actor, TCreature *Victim,
int Range, int Animation, TImpact *Impact, int Effect);
void OriginShapeSpell(TCreature *Actor, int Radius, TImpact *Impact, int Effect);
void CircleShapeSpell(TCreature *Actor, int DestX, int DestY, int DestZ,
int Range, int Animation, int Radius, TImpact *Impact, int Effect);
void DestinationShapeSpell(TCreature *Actor, TCreature *Victim,
int Range, int Animation, int Radius, TImpact *Impact, int Effect);
void AngleShapeSpell(TCreature *Actor, int Angle, int Range, TImpact *Impact, int Effect);
void CheckSpellbook(TCreature *Actor, int SpellNr);
void CheckAccount(TCreature *Actor, int SpellNr);
void CheckLevel(TCreature *Actor, int SpellNr);
void CheckRuneLevel(TCreature *Actor, int SpellNr);
void CheckMagicItem(TCreature *Actor, ObjectType Type);
void CheckRing(TCreature *Actor, int SpellNr);
void CheckAffectedPlayers(TCreature *Actor, int x, int y, int z);
void CheckMana(TCreature *Actor, int ManaPoints, int SoulPoints, int Delay);
int ComputeDamage(TCreature *Actor, int SpellNr, int Damage, int Variation);
bool IsAggressiveSpell(int SpellNr);
void MassCombat(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints,
int Damage, int Effect, int Radius, int DamageType, int Animation);
void AngleCombat(TCreature *Actor, int ManaPoints, int SoulPoints,
int Damage, int Effect, int Range, int Angle, int DamageType);
void Combat(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints,
int Damage, int Effect, int Animation, int DamageType);
int GetDirection(int dx, int dy); // TODO(fusion): Move this one elsewhere? Maybe `info.cc`.
void KillAllMonsters(TCreature *Actor, int Effect, int Radius);
void CreateField(int x, int y, int z, int FieldType, uint32 Owner, bool Peaceful);
void CreateField(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints, int FieldType);
void CreateField(TCreature *Actor, int ManaPoints, int SoulPoints, int FieldType);
void MassCreateField(TCreature *Actor, Object Target,
int ManaPoints, int SoulPoints, int FieldType, int Radius);
void CreateFieldWall(TCreature *Actor, Object Target,
int ManaPoints, int SoulPoints, int FieldType, int Width);
void DeleteField(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints);
void CleanupField(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints);
void CleanupField(TCreature *Actor);
void Teleport(TCreature *Actor, const char *Param);
void TeleportToCreature(TCreature *Actor, const char *Name);
void TeleportPlayerToMe(TCreature *Actor, const char *Name);
void MagicRope(TCreature *Actor, int ManaPoints, int SoulPoints);
void MagicClimbing(TCreature *Actor, int ManaPoints, int SoulPoints, const char *Param);
void MagicClimbing(TCreature *Actor, const char *Param);
void CreateThing(TCreature *Actor, const char *Param1, const char *Param2);
void CreateMoney(TCreature *Actor, const char *Param);
void CreateFood(TCreature *Actor, int ManaPoints, int SoulPoints);
void CreateArrows(TCreature *Actor, int ManaPoints, int SoulPoints, int ArrowType, int Count);
void SummonCreature(TCreature *Actor, int ManaPoints, int Race, bool God);
void SummonCreature(TCreature *Actor, int ManaPoints, const char *RaceName, bool God);
void StartMonsterraid(TCreature *Actor, const char *RaidName);
void RaiseDead(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints);
void MassRaiseDead(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints, int Radius);
void Heal(TCreature *Actor, int ManaPoints, int SoulPoints, int Amount);
void MassHeal(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints, int Amount, int Radius);
void HealFriend(TCreature *Actor, const char *TargetName, int ManaPoints, int SoulPoints, int Amount);
void RefreshMana(TCreature *Actor, int ManaPoints, int SoulPoints, int Amount);
void MagicGoStrength(TCreature *Actor, TCreature *Target, int ManaPoints, int SoulPoints, int Percent, int Duration);
void Shielding(TCreature *Actor, int ManaPoints, int SoulPoints, int Duration);
void NegatePoison(TCreature *Actor, TCreature *Target, int ManaPoints, int SoulPoints);
void Enlight(TCreature *Actor, int ManaPoints, int SoulPoints, int Radius, int Duration);
void Invisibility(TCreature *Actor, int ManaPoints, int SoulPoints, int Duration);
void CancelInvisibility(TCreature *Actor, Object Target, int ManaPoints, int SoulPoints, int Radius);
void CreatureIllusion(TCreature *Actor, int ManaPoints, int SoulPoints, const char *RaceName, int Duration);
void ObjectIllusion(TCreature *Actor, int ManaPoints, int SoulPoints, Object Target, int Duration);
void ChangeData(TCreature *Actor, const char *Param);
void EnchantObject(TCreature *Actor, int ManaPoints, int SoulPoints, ObjectType OldType, ObjectType NewType);
void Convince(TCreature *Actor, TCreature *Target);
void Challenge(TCreature *Actor, int ManaPoints, int SoulPoints, int Radius);
void FindPerson(TCreature *Actor, int ManaPoints, int SoulPoints, const char *TargetName);
void GetPosition(TCreature *Actor);
void GetQuestValue(TCreature *Actor, const char *Param);
void SetQuestValue(TCreature *Actor, const char *Param1, const char *Param2);
void ClearQuestValues(TCreature *Actor);
void CreateKnowledge(TCreature *Actor, const char *Param1, const char *Param2);
void ChangeProfession(TCreature *Actor, const char *Param);
void EditGuests(TCreature *Actor);
void EditSubowners(TCreature *Actor);
void EditNameDoor(TCreature *Actor);
void KickGuest(TCreature *Actor, const char *GuestName);
void Notation(TCreature *Actor, const char *Name, const char *Comment);
void NameLock(TCreature *Actor, const char *Name);
void BanishAccount(TCreature *Actor, const char *Name, int Duration, const char *Reason);
void DeleteAccount(TCreature *Actor, const char *Name, const char *Reason);
void BanishCharacter(TCreature *Actor, const char *Name, int Duration, const char *Reason);
void DeleteCharacter(TCreature *Actor, const char *Name, const char *Reason);
void IPBanishment(TCreature *Actor, const char *Name, const char *Reason);
void SetNameRule(TCreature *Actor, const char *Name);
void KickPlayer(TCreature *Actor, const char *Name);
void HomeTeleport(TCreature *Actor, const char *Name);
// TODO(fusion): These are unsafe like strcpy.
void GetMagicItemDescription(Object Obj, char *SpellString, int *MagicLevel);
void GetSpellbook(uint32 CharacterID, char *Buffer);
int GetSpellLevel(int SpellNr);
int CheckForSpell(uint32 CreatureID, const char *Text);
void UseMagicItem(uint32 CreatureID, Object Obj, Object Dest);
void DrinkPotion(uint32 CreatureID, Object Obj);
void InitMagic(void);
void ExitMagic(void);
#endif //TIBIA_MAGIC_HH_

588
src/game/src/main.cc Normal file
View file

@ -0,0 +1,588 @@
#include "common.hh"
#include "communication.hh"
#include "config.hh"
#include "houses.hh"
#include "info.hh"
#include "map.hh"
#include "magic.hh"
#include "moveuse.hh"
#include "objects.hh"
#include "operate.hh"
#include "query.hh"
#include "reader.hh"
#include "writer.hh"
#include <signal.h>
#include <sys/stat.h>
#include <fstream>
static bool BeADaemon = false;
static bool Reboot = false;
static bool SaveMapOn = false;
static timer_t BeatTimer;
static int SigAlarmCounter = 0;
static int SigUsr1Counter = 0;
static sighandler_t SigHandler(int SigNr, sighandler_t Handler){
struct sigaction Action;
struct sigaction OldAction;
Action.sa_handler = Handler;
// TODO(fusion): I feel we should probably use `sigfillset` specially for
// signals that share the same handler.
sigemptyset(&Action.sa_mask);
if(SigNr == SIGALRM){
Action.sa_flags = SA_INTERRUPT;
}else{
Action.sa_flags = SA_RESTART;
}
if(sigaction(SigNr, &Action, &OldAction) == 0){
return OldAction.sa_handler;
}else{
return SIG_ERR;
}
}
static void SigBlock(int SigNr){
sigset_t Set;
sigemptyset(&Set);
sigaddset(&Set, SigNr);
if(sigprocmask(SIG_BLOCK, &Set, NULL) == -1){
error("SigBlock: Failed to block signal %d (%s): (%d) %s\n",
SigNr, GetSignalDescription(SigNr),
errno, GetErrorDescription(errno));
}
}
static void SigWaitAny(void){
sigset_t Set;
sigemptyset(&Set);
sigsuspend(&Set);
}
static void SigHupHandler(int SigNr){
// no-op (?)
}
static void SigAbortHandler(int SigNr){
print(1, "SigAbortHandler: schalte Writer-Thread ab.\n");
AbortWriter();
}
static void DefaultHandler(int SigNr){
print(1, "DefaultHandler: Beende Game-Server (SigNr. %d: %s).\n",
SigNr, GetSignalDescription(SigNr));
SigHandler(SIGINT, SIG_IGN);
SigHandler(SIGQUIT, SIG_IGN);
SigHandler(SIGTERM, SIG_IGN);
SigHandler(SIGXCPU, SIG_IGN);
SigHandler(SIGXFSZ, SIG_IGN);
SigHandler(SIGPWR, SIG_IGN);
SaveMapOn = (SigNr == SIGQUIT) || (SigNr == SIGTERM) || (SigNr == SIGPWR);
if(SigNr == SIGTERM){
int Hour, Minute;
GetRealTime(&Hour, &Minute);
RebootTime = (Hour * 60 + Minute + 6) % 1440;
CloseGame();
}else{
EndGame();
}
Reboot = false;
}
#if 0
// TODO(fusion): This function was exported in the binary but not referenced anywhere.
static void ErrorHandler(int SigNr){
error("ErrorHandler: SigNr. %d: %s\n", SigNr, GetSignalDescription(SigNr));
EndGame();
LogoutAllPlayers();
exit(EXIT_FAILURE);
}
#endif
static void InitSignalHandler(void){
int Count = 0;
Count += (SigHandler(SIGHUP, SigHupHandler) != SIG_ERR);
Count += (SigHandler(SIGINT, DefaultHandler) != SIG_ERR);
Count += (SigHandler(SIGQUIT, DefaultHandler) != SIG_ERR);
Count += (SigHandler(SIGABRT, SigAbortHandler) != SIG_ERR);
Count += (SigHandler(SIGUSR1, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGUSR2, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGPIPE, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGALRM, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGTERM, DefaultHandler) != SIG_ERR);
Count += (SigHandler(SIGSTKFLT, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGCHLD, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGTSTP, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGTTIN, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGTTOU, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGURG, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGXCPU, DefaultHandler) != SIG_ERR);
Count += (SigHandler(SIGXFSZ, DefaultHandler) != SIG_ERR);
Count += (SigHandler(SIGVTALRM, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGWINCH, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGPOLL, SIG_IGN) != SIG_ERR);
Count += (SigHandler(SIGPWR, DefaultHandler) != SIG_ERR);
print(1, "InitSignalHandler: %d Signalhandler eingerichtet (Soll=%d)\n", Count, 0x1c);
}
static void ExitSignalHandler(void){
// no-op
}
static void SigAlarmHandler(int SigNr){
SigAlarmCounter += (1 + timer_getoverrun(BeatTimer));
}
static void InitTime(void){
ASSERT(Beat > 0);
SigAlarmCounter = 0;
SigHandler(SIGALRM, SigAlarmHandler);
struct sigevent SigEvent = {};
SigEvent.sigev_notify = SIGEV_THREAD_ID;
SigEvent.sigev_signo = SIGALRM;
SigEvent.sigev_notify_thread_id = gettid();
if(timer_create(CLOCK_MONOTONIC, &SigEvent, &BeatTimer) == -1){
error("InitTime: Failed to create beat timer: (%d) %s\n",
errno, GetErrorDescription(errno));
throw "cannot create beat timer";
}
struct itimerspec TimerSpec = {};
TimerSpec.it_interval.tv_sec = Beat / 1000;
TimerSpec.it_interval.tv_nsec = (Beat % 1000) * 1000000;
TimerSpec.it_value = TimerSpec.it_interval;
if(timer_settime(BeatTimer, 0, &TimerSpec, NULL) == -1){
error("InitTime: Failed to start beat timer: (%d) %s\n",
errno, GetErrorDescription(errno));
throw "cannot start beat timer";
}
}
static void ExitTime(void){
if(timer_delete(BeatTimer) == -1){
error("ExitTime: Failed to delete beat timer: (%d) %s\n",
errno, GetErrorDescription(errno));
}
SigHandler(SIGALRM, SIG_IGN);
}
static void UnlockGame(void){
// TODO(fusion): Probably use snprintf to format file name?
char FileName[4096];
strcpy(FileName, SAVEPATH);
strcat(FileName, "/game.pid");
std::ifstream InputFile(FileName, std::ios_base::in);
if(!InputFile.fail()){
int Pid;
InputFile >> Pid;
if(Pid == getpid()){
unlink(FileName);
}
}
}
static void LockGame(void){
// TODO(fusion): Probably use snprintf to format file name?
char FileName[4096];
strcpy(FileName, SAVEPATH);
strcat(FileName, "/game.pid");
{
std::ifstream InputFile(FileName, std::ios_base::in);
if(!InputFile.fail()){
int Pid;
InputFile >> Pid;
if(Pid != 0){
throw "Game-Server is already running, PID file exists.";
}
}
}
{
std::ofstream OutputFile(FileName, std::ios_base::out | std::ios_base::trunc);
OutputFile << getpid();
}
atexit(UnlockGame);
}
void LoadWorldConfig(void){
TQueryManagerConnection Connection(KB(16));
if(!Connection.isConnected()){
error("LoadWorldConfig: Kann nicht zum Query-Manager verbinden.\n");
throw "cannot connect to querymanager";
}
int HelpWorldType;
int HelpGameAddress[4];
int Ret = Connection.loadWorldConfig(&HelpWorldType, &RebootTime,
HelpGameAddress, &GamePort,
&MaxPlayers, &PremiumPlayerBuffer,
&MaxNewbies, &PremiumNewbieBuffer);
if(Ret != 0){
error("LoadWorldConfig: Kann Konfigurationsdaten nicht holen.\n");
throw "cannot load world config";
}
WorldType = (TWorldType)HelpWorldType;
snprintf(GameAddress, sizeof(GameAddress), "%d.%d.%d.%d",
HelpGameAddress[0], HelpGameAddress[1],
HelpGameAddress[2], HelpGameAddress[3]);
}
static void InitAll(void){
try{
ReadConfig();
SetQueryManagerLoginData(1, WorldName);
LoadWorldConfig();
InitSHM(!BeADaemon);
LockGame();
InitLog("game");
srand(time(NULL));
InitSignalHandler();
InitConnections();
InitCommunication();
InitStrings();
InitWriter();
InitReader();
InitObjects();
InitMap();
InitInfo();
InitMoveUse();
InitMagic();
InitCr();
InitHouses();
InitTime();
ApplyPatches();
}catch(const char *str){
error("Initialisierungsfehler: %s\n", str);
exit(EXIT_FAILURE);
}
}
static void ExitAll(void){
EndGame();
ExitTime();
ExitCr();
ExitMagic();
ExitMoveUse();
ExitInfo();
ExitHouses();
ExitMap(SaveMapOn);
ExitObjects();
ExitReader();
ExitWriter();
ExitStrings();
ExitCommunication();
ExitConnections();
ExitSignalHandler();
ExitSHM();
}
static void ProcessCommand(void){
int Command = GetCommand();
if(Command != 0){
char *Buffer = GetCommandBuffer();
if(Command == 1){
if(Buffer != NULL){
BroadcastMessage(TALK_ADMIN_MESSAGE, "%s", Buffer);
}else{
error("ProcessCommand: Text für Broadcast ist NULL.\n");
}
}else{
error("ProcessCommand: Unbekanntes Kommando %d.\n", Command);
}
SetCommand(0, NULL);
}
}
static void AdvanceGame(int Delay){
static int CreatureTimeCounter = 0;
static int CronTimeCounter = 0;
static int SkillTimeCounter = 0;
static int OtherTimeCounter = 0;
static int OldAmbiente = -1;
static uint32 NextMinute = 30;
static bool Lag = false;
CreatureTimeCounter += Delay;
CronTimeCounter += Delay;
SkillTimeCounter += Delay;
OtherTimeCounter += Delay;
if(CreatureTimeCounter >= 1750){
CreatureTimeCounter -= 1000;
ProcessCreatures();
}
if(CronTimeCounter >= 1500){
CronTimeCounter -= 1000;
ProcessCronSystem();
}
if(SkillTimeCounter >= 1250){
SkillTimeCounter -= 1000;
ProcessSkills();
}
if(OtherTimeCounter >= 1000){
OtherTimeCounter -= 1000;
RoundNr += 1;
SetRoundNr(RoundNr);
ProcessConnections();
ProcessMonsterhomes();
ProcessMonsterRaids();
ProcessCommunicationControl();
ProcessReaderThreadReplies(RefreshSector, SendMails);
ProcessWriterThreadReplies();
ProcessCommand();
// TODO(fusion): Shouldn't we be checking both brightness and color?
int Brightness, Color;
GetAmbiente(&Brightness, &Color);
if(OldAmbiente != Brightness){
OldAmbiente = Brightness;
TConnection *Connection = GetFirstConnection();
while(Connection != NULL){
if(Connection->Live()){
SendAmbiente(Connection);
}
Connection = GetNextConnection();
}
}
if(RoundNr % 10 == 0){
NetLoadCheck();
}
if(RoundNr >= NextMinute){
int Hour, Minute;
GetRealTime(&Hour, &Minute);
RefreshCylinders();
if(Minute % 5 == 0){
CreatePlayerList(true);
}
if(Minute % 15 == 0){
SavePlayerDataOrder();
}
if(Minute == 0){
NetLoadSummary();
}
if(Minute == 55){
WriteKillStatistics();
}
int RealTime = Minute + Hour * 60;
if((RealTime + 5) % 1440 == RebootTime){
if(Reboot){
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is saving game in 5 minutes.\nPlease come back in 10 minutes.");
}else{
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is going down in 5 minutes.\nPlease log out.");
}
CloseGame();
}else if((RealTime + 3) % 1440 == RebootTime){
if(Reboot){
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is saving game in 3 minutes.\nPlease come back in 10 minutes.");
}else{
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is going down in 3 minutes.\nPlease log out.");
}
}else if((RealTime + 1) % 1440 == RebootTime){
if(Reboot){
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is saving game in one minute.\nPlease log out.");
}else{
BroadcastMessage(TALK_ADMIN_MESSAGE,
"Server is going down in one minute.\nPlease log out.");
}
}else if(RealTime == RebootTime){
CloseGame();
LogoutAllPlayers();
SendAll();
if(Reboot){
RefreshMap();
}
SaveMap();
SaveMapOn = false;
EndGame();
}
NextMinute = GetRoundForNextMinute();
}
CleanupDynamicStrings();
}
if(Delay > Beat){
Log("lag", "Verzögerung %d msec.\n", Delay);
}
// TODO(fusion): Why would we delay creature movement yet another beat?
if(Delay < 1000){
MoveCreatures(Delay);
Lag = false;
}else{
if(!Lag && RoundNr > 10){
error("AdvanceGame: Keine Kreaturbewegung wegen Lag (Verzögerung: %d msec).\n", Delay);
}
Lag = true;
}
SendAll();
}
static void SigUsr1Handler(int SigNr){
SigUsr1Counter += 1;
}
static void LaunchGame(void){
SaveMapOn = true;
SigUsr1Counter = 0;
SigAlarmCounter = 0;
SigBlock(SIGUSR1);
SigHandler(SIGUSR1, SigUsr1Handler);
StartGame();
print(1, "LaunchGame: Game-Server ist bereit (Pid=%d, Tid=%d).\n", getpid(), gettid());
// IMPORTANT(fusion): In general signal handlers can execute on any thread in
// the process group but the design of the server is to use signals directed
// at different threads to communicate certain events (see `CommunicationThread`
// for example).
// Even if that wasn't the case, loads/stores on x86 are always ATOMIC and when
// there is a single writer (signal handlers), even a read-modify-write will be
// atomic.
// This is to say, there should be no problem with reading from `SigUsr1Counter`,
// `SigAlarmCounter`, or `SaveMapOn`, which may be modified from signal handlers.
while(GameRunning()){
while(SigUsr1Counter == 0 && SigAlarmCounter == 0){
SigWaitAny();
}
if(SigUsr1Counter > 0){
SigUsr1Counter = 0;
ReceiveData();
}
int NumBeats = SigAlarmCounter;
if(NumBeats > 0){
SigAlarmCounter = 0;
AdvanceGame(NumBeats * Beat);
}
}
LogoutAllPlayers();
}
static bool DaemonInit(bool NoFork){
if(!NoFork){
pid_t Pid = fork();
if(Pid < 0){
return true;
}
if(Pid != 0){
exit(EXIT_SUCCESS);
}
setsid();
}
umask(0177);
// NOTE(fusion): The original binary would change directories to `SAVEPATH`
// here, but because this function is called very early at startup, no config
// values would have been loaded, leaving `SAVEPATH` empty and causing this
// next call to `chdir` to always fail with ENOENT.
//chdir(SAVEPATH);
int OpenMax = sysconf(_SC_OPEN_MAX);
if(OpenMax < 0){
OpenMax = 1024;
}
for(int fd = 0; fd < OpenMax; fd += 1){
close(fd);
}
return false;
}
int main(int argc, char **argv){
bool NoFork = false;
BeADaemon = false;
Reboot = true;
for(int i = 1; i < argc; i += 1){
if(strcmp(argv[i], "daemon") == 0){
BeADaemon = true;
}else if(strcmp(argv[i], "nofork") == 0){
NoFork = true;
}
}
// TODO(fusion): It doesn't make sense for `DaemonInit` to even return here.
// It either exits the parent or child process, or let it run.
if(BeADaemon && DaemonInit(NoFork)){
return 2;
}
puts("Tibia Game-Server\n(c) by CIP Productions, 2003.\n");
InitAll();
atexit(ExitAll);
// TODO(fusion): The original binary does use exceptions but identifying
// try..catch blocks are not as straightforward as throw statements. I'll
// leave this one at the top level but we should come back to this problem
// once we identify all throw statements and how to roughly handle them.
try{
LaunchGame();
}catch(RESULT r){
error("main: Nicht abgefangene Exception %d.\n", r);
}catch(const char *str){
error("main: Nicht abgefangene Exception \"%s\".\n", str);
}catch(const std::exception &e){
error("main: Nicht abgefangene Exception %s.\n", e.what());
}catch(...){
error("main: Nicht abgefangene Exception unbekannten Typs.\n");
}
if(!Reboot){
print(1, "Beende Game-Server...\n");
}else{
UnlockGame();
char FileName[4096];
snprintf(FileName, sizeof(FileName), "%s/reboot-daily", BINPATH);
if(FileExists(FileName)){
ExitAll();
print(1, "Starte Game-Server neu...\n");
execv(FileName, argv);
}else{
print(1, "Reboot-Skript existiert nicht.\n");
}
}
return 0;
}

2584
src/game/src/map.cc Normal file

File diff suppressed because it is too large Load diff

179
src/game/src/map.hh Normal file
View file

@ -0,0 +1,179 @@
#ifndef TIBIA_MAP_HH_
#define TIBIA_MAP_HH_ 1
#include "common.hh"
#include "objects.hh"
#include "script.hh"
// NOTE(fusion): This is used by hash table entries and sectors to tell whether
// they're currently loaded or swapped out to disk.
enum : uint8 {
STATUS_FREE = 0,
STATUS_LOADED = 1,
STATUS_SWAPPED = 2,
// TODO(fusion): It seems this is only used with the `NONE` entry in the
// hash table. I haven't seen it used **yet** but it may have a purpose
// aside from preventing swap outs.
STATUS_PERMANENT = 255,
};
// NOTE(fusion): This is used to determine precedence order of different objects
// in a map container.
enum : int {
PRIORITY_BANK = 0,
PRIORITY_CLIP = 1,
PRIORITY_BOTTOM = 2,
PRIORITY_TOP = 3,
PRIORITY_CREATURE = 4,
PRIORITY_LOW = 5,
};
struct Object {
constexpr Object(void) : ObjectID(0) {}
constexpr explicit Object(uint32 ObjectID): ObjectID(ObjectID) {}
bool exists(void);
ObjectType getObjectType(void);
void setObjectType(ObjectType Type);
Object getNextObject(void);
void setNextObject(Object NextObject);
Object getContainer(void);
void setContainer(Object Con);
uint32 getCreatureID(void);
uint32 getAttribute(INSTANCEATTRIBUTE Attribute);
void setAttribute(INSTANCEATTRIBUTE Attribute, uint32 Value);
constexpr bool operator==(const Object &Other) const {
return this->ObjectID == Other.ObjectID;
}
constexpr bool operator!=(const Object &Other) const {
return this->ObjectID != Other.ObjectID;
}
// DATA
// =================
uint32 ObjectID;
};
constexpr Object NONE;
struct TObject {
uint32 ObjectID;
Object NextObject;
Object Container;
ObjectType Type;
uint32 Attributes[4];
};
struct TObjectBlock {
TObject Object[32768];
};
struct TSector {
Object MapCon[32][32];
uint32 TimeStamp;
uint8 Status;
uint8 MapFlags;
};
struct TDepotInfo {
char Town[20];
int Size;
};
struct TMark {
char Name[20];
int x;
int y;
int z;
};
struct TCronEntry {
Object Obj;
uint32 RoundNr;
int Previous;
int Next;
};
// NOTE(fusion): Map config values.
extern int SectorXMin;
extern int SectorXMax;
extern int SectorYMin;
extern int SectorYMax;
extern int SectorZMin;
extern int SectorZMax;
extern int RefreshedCylinders;
extern int NewbieStartPositionX;
extern int NewbieStartPositionY;
extern int NewbieStartPositionZ;
extern int VeteranStartPositionX;
extern int VeteranStartPositionY;
extern int VeteranStartPositionZ;
// NOTE(fusion): Cron management functions. Most for internal use.
Object CronCheck(void);
void CronExpire(Object Obj, int Delay);
void CronChange(Object Obj, int NewDelay);
uint32 CronInfo(Object Obj, bool Delete);
uint32 CronStop(Object Obj);
// NOTE(fusion): Map management functions. Most for internal use.
void SwapObject(TWriteBinaryFile *File, Object Obj, uintptr FileNumber);
void SwapSector(void);
void UnswapSector(uintptr FileNumber);
void DeleteSwappedSectors(void);
void LoadObjects(TReadScriptFile *Script, TWriteStream *Stream, bool Skip);
void LoadObjects(TReadStream *Stream, Object Con);
void InitSector(int SectorX, int SectorY, int SectorZ);
void LoadSector(const char *FileName, int SectorX, int SectorY, int SectorZ);
void LoadMap(void);
void SaveObjects(Object Obj, TWriteStream *Stream, bool Stop);
void SaveObjects(TReadStream *Stream, TWriteScriptFile *Script);
void SaveSector(char *FileName, int SectorX, int SectorY, int SectorZ);
void SaveMap(void);
void RefreshSector(int SectorX, int SectorY, int SectorZ, TReadStream *Stream);
void PatchSector(int SectorX, int SectorY, int SectorZ, bool FullSector,
TReadScriptFile *Script, bool SaveHouses);
void InitMap(void);
void ExitMap(bool Save);
// NOTE(fusion): Object related functions.
TObject *AccessObject(Object Obj);
Object CreateObject(void);
void DeleteObject(Object Obj);
void ChangeObject(Object Obj, ObjectType NewType);
void ChangeObject(Object Obj, INSTANCEATTRIBUTE Attribute, uint32 Value);
int GetObjectPriority(Object Obj);
void PlaceObject(Object Obj, Object Con, bool Append);
void CutObject(Object Obj);
void MoveObject(Object Obj, Object Con);
Object AppendObject(Object Con, ObjectType Type);
Object SetObject(Object Con, ObjectType Type, uint32 CreatureID);
Object CopyObject(Object Con, Object Source);
Object SplitObject(Object Obj, int Count);
void MergeObjects(Object Obj, Object Dest);
Object GetFirstContainerObject(Object Con);
Object GetContainerObject(Object Con, int Index);
Object GetMapContainer(int x, int y, int z);
Object GetMapContainer(Object Obj);
Object GetFirstObject(int x, int y, int z);
Object GetFirstSpecObject(int x, int y, int z, ObjectType Type);
uint8 GetMapContainerFlags(Object Obj);
void GetObjectCoordinates(Object Obj, int *x, int *y, int *z);
bool CoordinateFlag(int x, int y, int z, FLAG Flag);
bool IsOnMap(int x, int y, int z);
bool IsPremiumArea(int x, int y, int z);
bool IsNoLogoutField(int x, int y, int z);
bool IsProtectionZone(int x, int y, int z);
bool IsHouse(int x, int y, int z);
uint16 GetHouseID(int x, int y, int z);
void SetHouseID(int x, int y, int z, uint16 ID);
int GetDepotNumber(const char *Town);
const char *GetDepotName(int DepotNumber);
int GetDepotSize(int DepotNumber, bool PremiumAccount);
bool GetMarkPosition(const char *Name, int *x, int *y, int *z);
void GetStartPosition(int *x, int *y, int *z, bool Newbie);
#endif //TIBIA_MAP_HH_

3095
src/game/src/moveuse.cc Normal file

File diff suppressed because it is too large Load diff

195
src/game/src/moveuse.hh Normal file
View file

@ -0,0 +1,195 @@
#ifndef TIBIA_MOVEUSE_HH_
#define TIBIA_MOVEUSE_HH_ 1
#include "common.hh"
#include "containers.hh"
#include "map.hh"
#include "script.hh"
#define MOVEUSE_MAX_PARAMETERS 5
struct TPlayerData;
enum MoveUseActionType: int {
MOVEUSE_ACTION_CREATEONMAP = 0,
MOVEUSE_ACTION_CREATE = 1,
MOVEUSE_ACTION_MONSTERONMAP = 2,
MOVEUSE_ACTION_MONSTER = 3,
MOVEUSE_ACTION_EFFECTONMAP = 4,
MOVEUSE_ACTION_EFFECT = 5,
MOVEUSE_ACTION_TEXTONMAP = 6,
MOVEUSE_ACTION_TEXT = 7,
MOVEUSE_ACTION_CHANGEONMAP = 8,
MOVEUSE_ACTION_CHANGE = 9,
MOVEUSE_ACTION_CHANGEREL = 10,
MOVEUSE_ACTION_SETATTRIBUTE = 11,
MOVEUSE_ACTION_CHANGEATTRIBUTE = 12,
MOVEUSE_ACTION_SETQUESTVALUE = 13,
MOVEUSE_ACTION_DAMAGE = 14,
MOVEUSE_ACTION_SETSTART = 15,
MOVEUSE_ACTION_WRITENAME = 16,
MOVEUSE_ACTION_WRITETEXT = 17,
MOVEUSE_ACTION_LOGOUT = 18,
MOVEUSE_ACTION_MOVEALLONMAP = 19,
MOVEUSE_ACTION_MOVEALL = 20,
MOVEUSE_ACTION_MOVEALLREL = 21,
MOVEUSE_ACTION_MOVETOPONMAP = 22,
MOVEUSE_ACTION_MOVETOP = 23,
MOVEUSE_ACTION_MOVETOPREL = 24,
MOVEUSE_ACTION_MOVE = 25,
MOVEUSE_ACTION_MOVEREL = 26,
MOVEUSE_ACTION_RETRIEVE = 27,
MOVEUSE_ACTION_DELETEALLONMAP = 28,
MOVEUSE_ACTION_DELETETOPONMAP = 29,
MOVEUSE_ACTION_DELETEONMAP = 30,
MOVEUSE_ACTION_DELETE = 31,
MOVEUSE_ACTION_DELETEININVENTORY = 32,
MOVEUSE_ACTION_DESCRIPTION = 33,
MOVEUSE_ACTION_LOADDEPOT = 34,
MOVEUSE_ACTION_SAVEDEPOT = 35,
MOVEUSE_ACTION_SENDMAIL = 36,
MOVEUSE_ACTION_NOP = 37,
};
enum MoveUseConditionType: int {
MOVEUSE_CONDITION_ISPOSITION = 0,
MOVEUSE_CONDITION_ISTYPE = 1,
MOVEUSE_CONDITION_ISCREATURE = 2,
MOVEUSE_CONDITION_ISPLAYER = 3,
MOVEUSE_CONDITION_HASFLAG = 4,
MOVEUSE_CONDITION_HASTYPEATTRIBUTE = 5,
MOVEUSE_CONDITION_HASINSTANCEATTRIBUTE = 6,
MOVEUSE_CONDITION_HASTEXT = 7,
MOVEUSE_CONDITION_ISPEACEFUL = 8,
MOVEUSE_CONDITION_MAYLOGOUT = 9,
MOVEUSE_CONDITION_HASPROFESSION = 10,
MOVEUSE_CONDITION_HASLEVEL = 11,
MOVEUSE_CONDITION_HASRIGHT = 12,
MOVEUSE_CONDITION_HASQUESTVALUE = 13,
MOVEUSE_CONDITION_TESTSKILL = 14,
MOVEUSE_CONDITION_COUNTOBJECTS = 15,
MOVEUSE_CONDITION_COUNTOBJECTSONMAP = 16,
MOVEUSE_CONDITION_ISOBJECTTHERE = 17,
MOVEUSE_CONDITION_ISCREATURETHERE = 18,
MOVEUSE_CONDITION_ISPLAYERTHERE = 19,
MOVEUSE_CONDITION_ISOBJECTININVENTORY = 20,
MOVEUSE_CONDITION_ISPROTECTIONZONE = 21,
MOVEUSE_CONDITION_ISHOUSE = 22,
MOVEUSE_CONDITION_ISHOUSEOWNER = 23,
MOVEUSE_CONDITION_ISDRESSED = 24,
MOVEUSE_CONDITION_RANDOM = 25,
};
enum MoveUseEventType: int {
MOVEUSE_EVENT_USE = 0,
MOVEUSE_EVENT_MULTIUSE = 1,
MOVEUSE_EVENT_MOVEMENT = 2,
MOVEUSE_EVENT_COLLISION = 3,
MOVEUSE_EVENT_SEPARATION = 4,
};
enum MoveUseModifierType: int {
MOVEUSE_MODIFIER_NORMAL = 0,
MOVEUSE_MODIFIER_INVERT = 1,
MOVEUSE_MODIFIER_TRUE = 2,
};
enum MoveUseParameterType: int {
MOVEUSE_PARAMETER_OBJECT = 0,
MOVEUSE_PARAMETER_TYPE = 1,
MOVEUSE_PARAMETER_FLAG = 2,
MOVEUSE_PARAMETER_TYPEATTRIBUTE = 3,
MOVEUSE_PARAMETER_INSTANCEATTRIBUTE = 4,
MOVEUSE_PARAMETER_COORDINATE = 5,
MOVEUSE_PARAMETER_VECTOR = 6,
MOVEUSE_PARAMETER_RIGHT = 7,
MOVEUSE_PARAMETER_SKILL = 8,
MOVEUSE_PARAMETER_NUMBER = 9,
MOVEUSE_PARAMETER_TEXT = 10,
MOVEUSE_PARAMETER_COMPARISON = 11,
};
struct TMoveUseAction {
MoveUseActionType Action;
int Parameters[MOVEUSE_MAX_PARAMETERS];
};
struct TMoveUseRule {
int FirstCondition;
int LastCondition;
int FirstAction;
int LastAction;
};
struct TMoveUseCondition {
MoveUseModifierType Modifier;
MoveUseConditionType Condition;
int Parameters[MOVEUSE_MAX_PARAMETERS];
};
struct TMoveUseDatabase {
TMoveUseDatabase(void) : Rules(1, 100, 100), NumberOfRules(0) {}
vector<TMoveUseRule> Rules;
int NumberOfRules;
};
struct TDelayedMail {
uint32 CharacterID;
int DepotNumber;
uint8 *Packet;
int PacketSize;
};
int PackAbsoluteCoordinate(int x, int y, int z);
void UnpackAbsoluteCoordinate(int Packed, int *x, int *y, int *z);
int PackRelativeCoordinate(int x, int y, int z);
void UnpackRelativeCoordinate(int Packed, int *x, int *y, int *z);
Object GetEventObject(int Nr, Object User, Object Obj1, Object Obj2, Object Temp);
bool Compare(int Value1, int Operator, int Value2);
bool CheckCondition(MoveUseEventType EventType, TMoveUseCondition *Condition,
Object User, Object Obj1, Object Obj2, Object *Temp);
Object CreateObject(Object Con, ObjectType Type, uint32 Value);
void ChangeObject(Object Obj, ObjectType NewType, uint32 Value);
void MoveOneObject(Object Obj, Object Con);
void MoveAllObjects(Object Obj, Object Dest, Object Exclude, bool MoveUnmovable);
void DeleteAllObjects(Object Obj, Object Exclude, bool DeleteUnmovable);
void ClearField(Object Obj, Object Exclude);
void LoadDepotBox(uint32 CreatureID, int Nr, Object Con);
void SaveDepotBox(uint32 CreatureID, int Nr, Object Con);
void SendMail(Object Obj);
void SendMails(TPlayerData *PlayerData);
void TextEffect(const char *Text, int x, int y, int z, int Radius);
void ExecuteAction(MoveUseEventType EventType, TMoveUseAction *Action,
Object User, Object Obj1, Object Obj2, Object *Temp);
bool HandleEvent(MoveUseEventType EventType, Object User, Object Obj1, Object Obj2);
void UseContainer(uint32 CreatureID, Object Con, int NextContainerNr);
void UseChest(uint32 CreatureID, Object Chest);
void UseLiquidContainer(uint32 CreatureID, Object Obj, Object Dest);
void UseFood(uint32 CreatureID, Object Obj);
void UseTextObject(uint32 CreatureID, Object Obj);
void UseAnnouncer(uint32 CreatureID, Object Obj);
void UseKeyDoor(uint32 CreatureID, Object Key, Object Door);
void UseNameDoor(uint32 CreatureID, Object Door);
void UseLevelDoor(uint32 CreatureID, Object Door);
void UseQuestDoor(uint32 CreatureID, Object Door);
void UseWeapon(uint32 CreatureID, Object Weapon, Object Target);
void UseChangeObject(uint32 CreatureID, Object Obj);
void UseObject(uint32 CreatureID, Object Obj);
void UseObjects(uint32 CreatureID, Object Obj1, Object Obj2);
void MovementEvent(Object Obj, Object Start, Object Dest);
void SeparationEvent(Object Obj, Object Start);
void CollisionEvent(Object Obj, Object Dest);
void LoadParameters(TReadScriptFile *Script, int *Parameters, int NumberOfParameters, ...);
void LoadCondition(TReadScriptFile *Script, TMoveUseCondition *Condition);
void LoadAction(TReadScriptFile *Script, TMoveUseAction *Action);
void LoadDataBase(void);
void InitMoveUse(void);
void ExitMoveUse(void);
#endif //TIBIA_MOVEUSE_HH_

623
src/game/src/objects.cc Normal file
View file

@ -0,0 +1,623 @@
#include "objects.hh"
#include "config.hh"
#include "containers.hh"
#include "script.hh"
#include <fstream>
static vector<TObjectType> ObjectTypes(0, 5000, 1000);
static ObjectType SpecialObjects[49];
static uint8 OldGroup[8192];
static uint8 OldNumber[8192];
static int NewType[65536];
static FLAG TypeAttributeFlags[62] = {
BANK, // WAYPOINTS
CONTAINER, // CAPACITY
CHANGEUSE, // CHANGETARGET
KEYDOOR, // KEYDOORTARGET
NAMEDOOR, // NAMEDOORTARGET
LEVELDOOR, // LEVELDOORTARGET
QUESTDOOR, // QUESTDOORTARGET
FOOD, // NUTRITION
INFORMATION, // INFORMATIONTYPE
TEXT, // FONTSIZE
WRITE, // MAXLENGTH
WRITEONCE, // MAXLENGTHONCE
LIQUIDSOURCE, // SOURCELIQUIDTYPE
TELEPORTABSOLUTE, // ABSTELEPORTEFFECT
TELEPORTRELATIVE, // RELTELEPORTDISPLACEMENT
TELEPORTRELATIVE, // RELTELEPORTEFFECT
AVOID, // AVOIDDAMAGETYPES
RESTRICTLEVEL, // MINIMUMLEVEL
RESTRICTPROFESSION, // PROFESSIONS
TAKE, // WEIGHT
ROTATE, // ROTATETARGET
DESTROY, // DESTROYTARGET
CLOTHES, // BODYPOSITION
SKILLBOOST, // SKILLNUMBER
SKILLBOOST, // SKILLMODIFICATION
PROTECTION, // PROTECTIONDAMAGETYPES
PROTECTION, // DAMAGEREDUCTION
LIGHT, // BRIGHTNESS
LIGHT, // LIGHTCOLOR
CORPSE, // CORPSETYPE
EXPIRE, // TOTALEXPIRETIME
EXPIRE, // EXPIRETARGET
WEAROUT, // TOTALUSES
WEAROUT, // WEAROUTTARGET
WEAPON, // WEAPONTYPE
WEAPON, // WEAPONATTACKVALUE
WEAPON, // WEAPONDEFENDVALUE
SHIELD, // SHIELDDEFENDVALUE
BOW, // BOWRANGE
BOW, // BOWAMMOTYPE
THROW, // THROWRANGE
THROW, // THROWATTACKVALUE
THROW, // THROWDEFENDVALUE
THROW, // THROWMISSILE
THROW, // THROWSPECIALEFFECT
THROW, // THROWEFFECTSTRENGTH
THROW, // THROWFRAGILITY
WAND, // WANDRANGE
WAND, // WANDMANACONSUMPTION
WAND, // WANDATTACKSTRENGTH
WAND, // WANDATTACKVARIATION
WAND, // WANDDAMAGETYPE
WAND, // WANDMISSILE
AMMO, // AMMOTYPE
AMMO, // AMMOATTACKVALUE
AMMO, // AMMOMISSILE
AMMO, // AMMOSPECIALEFFECT
AMMO, // AMMOEFFECTSTRENGTH
ARMOR, // ARMORVALUE
HEIGHT, // ELEVATION
DISGUISE, // DISGUISETARGET
BANK, // MEANING
};
static FLAG InstanceAttributeFlags[18] = {
CONTAINER, // CONTENT
CHEST, // CHESTQUESTNUMBER
CUMULATIVE, // AMOUNT
KEY, // KEYNUMBER
KEYDOOR, // KEYHOLENUMBER
LEVELDOOR, // DOORLEVEL
QUESTDOOR, // DOORQUESTNUMBER
QUESTDOOR, // DOORQUESTVALUE
RUNE, // CHARGES
TEXT, // TEXTSTRING
TEXT, // EDITOR
LIQUIDCONTAINER, // CONTAINERLIQUIDTYPE
LIQUIDPOOL, // POOLLIQUIDTYPE
TELEPORTABSOLUTE, // ABSTELEPORTDESTINATION
MAGICFIELD, // RESPONSIBLE
EXPIRE, // REMAININGEXPIRETIME
EXPIRESTOP, // SAVEDEXPIRETIME
WEAROUT, // REMAININGUSES
};
static const char FlagNames[66][30] = {
"Bank", // BANK
"Clip", // CLIP
"Bottom", // BOTTOM
"Top", // TOP
"Container", // CONTAINER
"Chest", // CHEST
"Cumulative", // CUMULATIVE
"UseEvent", // USEEVENT
"ChangeUse", // CHANGEUSE
"ForceUse", // FORCEUSE
"MultiUse", // MULTIUSE
"DistUse", // DISTUSE
"MovementEvent", // MOVEMENTEVENT
"CollisionEvent", // COLLISIONEVENT
"SeparationEvent", // SEPARATIONEVENT
"Key", // KEY
"KeyDoor", // KEYDOOR
"NameDoor", // NAMEDOOR
"LevelDoor", // LEVELDOOR
"QuestDoor", // QUESTDOOR
"Bed", // BED
"Food", // FOOD
"Rune", // RUNE
"Information", // INFORMATION
"Text", // TEXT
"Write", // WRITE
"WriteOnce", // WRITEONCE
"LiquidContainer", // LIQUIDCONTAINER
"LiquidSource", // LIQUIDSOURCE
"LiquidPool", // LIQUIDPOOL
"TeleportAbsolute", // TELEPORTABSOLUTE
"TeleportRelative", // TELEPORTRELATIVE
"Unpass", // UNPASS
"Unmove", // UNMOVE
"Unthrow", // UNTHROW
"Unlay", // UNLAY
"Avoid", // AVOID
"MagicField", // MAGICFIELD
"RestrictLevel", // RESTRICTLEVEL
"RestrictProfession", // RESTRICTPROFESSION
"Take", // TAKE
"Hang", // HANG
"HookSouth", // HOOKSOUTH
"HookEast", // HOOKEAST
"Rotate", // ROTATE
"Destroy", // DESTROY
"Clothes", // CLOTHES
"SkillBoost", // SKILLBOOST
"Protection", // PROTECTION
"Light", // LIGHT
"RopeSpot", // ROPESPOT
"Corpse", // CORPSE
"Expire", // EXPIRE
"ExpireStop", // EXPIRESTOP
"WearOut", // WEAROUT
"Weapon", // WEAPON
"Shield", // SHIELD
"Bow", // BOW
"Throw", // THROW
"Wand", // WAND
"Ammo", // AMMO
"Armor", // ARMOR
"Height", // HEIGHT
"Disguise", // DISGUISE
"ShowDetail", // SHOWDETAIL
"Special", // SPECIALOBJECT
};
static const char TypeAttributeNames[62][30] = {
"Waypoints", // WAYPOINTS
"Capacity", // CAPACITY
"ChangeTarget", // CHANGETARGET
"KeydoorTarget", // KEYDOORTARGET
"NamedoorTarget", // NAMEDOORTARGET
"LeveldoorTarget", // LEVELDOORTARGET
"QuestdoorTarget", // QUESTDOORTARGET
"Nutrition", // NUTRITION
"InformationType", // INFORMATIONTYPE
"FontSize", // FONTSIZE
"MaxLength", // MAXLENGTH
"MaxLengthOnce", // MAXLENGTHONCE
"SourceLiquidType", // SOURCELIQUIDTYPE
"AbsTeleportEffect", // ABSTELEPORTEFFECT
"RelTeleportDisplacement", // RELTELEPORTDISPLACEMENT
"RelTeleportEffect", // RELTELEPORTEFFECT
"AvoidDamageTypes", // AVOIDDAMAGETYPES
"MinimumLevel", // MINIMUMLEVEL
"Professions", // PROFESSIONS
"Weight", // WEIGHT
"RotateTarget", // ROTATETARGET
"DestroyTarget", // DESTROYTARGET
"BodyPosition", // BODYPOSITION
"SkillNumber", // SKILLNUMBER
"SkillModification", // SKILLMODIFICATION
"ProtectionDamageTypes", // PROTECTIONDAMAGETYPES
"DamageReduction", // DAMAGEREDUCTION
"Brightness", // BRIGHTNESS
"LightColor", // LIGHTCOLOR
"CorpseType", // CORPSETYPE
"TotalExpireTime", // TOTALEXPIRETIME
"ExpireTarget", // EXPIRETARGET
"TotalUses", // TOTALUSES
"WearoutTarget", // WEAROUTTARGET
"WeaponType", // WEAPONTYPE
"WeaponAttackValue", // WEAPONATTACKVALUE
"WeaponDefendValue", // WEAPONDEFENDVALUE
"ShieldDefendValue", // SHIELDDEFENDVALUE
"BowRange", // BOWRANGE
"BowAmmoType", // BOWAMMOTYPE
"ThrowRange", // THROWRANGE
"ThrowAttackValue", // THROWATTACKVALUE
"ThrowDefendValue", // THROWDEFENDVALUE
"ThrowMissile", // THROWMISSILE
"ThrowSpecialEffect", // THROWSPECIALEFFECT
"ThrowEffectStrength", // THROWEFFECTSTRENGTH
"ThrowFragility", // THROWFRAGILITY
"WandRange", // WANDRANGE
"WandManaConsumption", // WANDMANACONSUMPTION
"WandAttackStrength", // WANDATTACKSTRENGTH
"WandAttackVariation", // WANDATTACKVARIATION
"WandDamageType", // WANDDAMAGETYPE
"WandMissile", // WANDMISSILE
"AmmoType", // AMMOTYPE
"AmmoAttackValue", // AMMOATTACKVALUE
"AmmoMissile", // AMMOMISSILE
"AmmoSpecialEffect", // AMMOSPECIALEFFECT
"AmmoEffectStrength", // AMMOEFFECTSTRENGTH
"ArmorValue", // ARMORVALUE
"Elevation", // ELEVATION
"DisguiseTarget", // DISGUISETARGET
"Meaning", // MEANING
};
static const char InstanceAttributeNames[18][30] = {
"Content", // CONTENT
"ChestQuestNumber", // CHESTQUESTNUMBER
"Amount", // AMOUNT
"KeyNumber", // KEYNUMBER
"KeyholeNumber", // KEYHOLENUMBER
"Level", // DOORLEVEL
"DoorQuestNumber", // DOORQUESTNUMBER
"DoorQuestValue", // DOORQUESTVALUE
"Charges", // CHARGES
"String", // TEXTSTRING
"Editor", // EDITOR
"ContainerLiquidType", // CONTAINERLIQUIDTYPE
"PoolLiquidType", // POOLLIQUIDTYPE
"AbsTeleportDestination", // ABSTELEPORTDESTINATION
"Responsible", // RESPONSIBLE
"RemainingExpireTime", // REMAININGEXPIRETIME
"SavedExpireTime", // SAVEDEXPIRETIME
"RemainingUses", // REMAININGUSES
};
// ObjectType
// =============================================================================
void ObjectType::setTypeID(int TypeID){
if(!ObjectTypeExists(TypeID)){
error("ObjectType::setTypeID: Ungültiger Typ %d.\n", TypeID);
TypeID = 0;
}
this->TypeID = TypeID;
}
bool ObjectType::getFlag(FLAG Flag){
TObjectType *TypeP = ObjectTypes.at(this->TypeID);
return CheckBit(TypeP->Flags, (int)Flag);
}
uint32 ObjectType::getAttribute(TYPEATTRIBUTE Attribute){
if(!this->getFlag(TypeAttributeFlags[Attribute])){
error("ObjectType::getAttribute: Typ %d hat kein Flag %d für Attribut %d.\n",
this->TypeID, TypeAttributeFlags[Attribute], Attribute);
return 0;
}
TObjectType *TypeP = ObjectTypes.at(this->TypeID);
return TypeP->Attributes[Attribute];
}
int ObjectType::getAttributeOffset(INSTANCEATTRIBUTE Attribute){
if(!this->getFlag(InstanceAttributeFlags[Attribute])){
// NOTE(fusion): The CONTENT attribute seems to be the only one that maps
// to two object flags, which is why we have this extra check here.
if(!(Attribute == CONTENT && this->getFlag(CHEST))){
return -1;
}
}
TObjectType *TypeP = ObjectTypes.at(this->TypeID);
return TypeP->AttributeOffsets[Attribute];
}
const char *ObjectType::getName(int Count){
if(this->isCreatureContainer()){
error("ObjectType::getName: Der Kreaturtyp hat keinen Namen.\n");
return NULL;
}
TObjectType *TypeP = ObjectTypes.at(this->TypeID);
const char *Name = TypeP->Name;
if(Name == NULL){
Name = "";
}
return Plural(Name, Count);
}
const char *ObjectType::getDescription(void){
TObjectType *TypeP = ObjectTypes.at(this->TypeID);
return TypeP->Description;
}
// Object Type Related Functions
// =============================================================================
int GetFlagByName(const char *Name){
int Result = -1;
for(int i = 0; i < NARRAY(FlagNames); i += 1){
if(stricmp(FlagNames[i], Name) == 0){
Result = i;
break;
}
}
return Result;
}
int GetTypeAttributeByName(const char *Name){
int Result = -1;
for(int i = 0; i < NARRAY(TypeAttributeNames); i += 1){
if(stricmp(TypeAttributeNames[i], Name) == 0){
Result = i;
break;
}
}
return Result;
}
int GetInstanceAttributeByName(const char *Name){
int Result = -1;
for(int i = 0; i < NARRAY(InstanceAttributeNames); i += 1){
if(stricmp(InstanceAttributeNames[i], Name) == 0){
Result = i;
break;
}
}
return Result;
}
const char *GetFlagName(int Flag){
ASSERT(Flag >= 0 && Flag < NARRAY(FlagNames));
return FlagNames[Flag];
}
const char *GetTypeAttributeName(int Attribute){
ASSERT(Attribute >= 0 && Attribute < NARRAY(TypeAttributeFlags));
return TypeAttributeNames[Attribute];
}
const char *GetInstanceAttributeName(int Attribute){
ASSERT(Attribute >= 0 && Attribute < NARRAY(InstanceAttributeNames));
return InstanceAttributeNames[Attribute];
}
bool ObjectTypeExists(int TypeID){
return ObjectTypes.min <= TypeID && TypeID <= ObjectTypes.max;
}
// NOTE(fusion): Small helper to compute the index into the `NewType` array
// from old object type values.
static uint16 GetNewTypeIndex(uint8 Group, uint8 Number){
return ((uint16)Group << 8) | (uint16)Number;
}
bool ObjectTypeExists(uint8 Group, uint8 Number){
// TODO(fusion): Check bounds?
return NewType[GetNewTypeIndex(Group, Number)] >= 0;
}
ObjectType GetNewObjectType(uint8 Group, uint8 Number){
int TypeID = NewType[GetNewTypeIndex(Group, Number)];
if(TypeID < 0){
error("GetNewObjectType: Objekttyp %u/%u existiert nicht.\n", Group, Number);
TypeID = 0;
}
return ObjectType(TypeID);
}
void GetOldObjectType(ObjectType Type, uint8 *Group, uint8 *Number){
if(!ObjectTypeExists(Type.TypeID)){
error("GetOldObjectType: Ungültiger Typ %d.\n", Type.TypeID);
return;
}
// TODO(fusion): Check bounds?
*Group = OldGroup[Type.TypeID];
*Number = OldNumber[Type.TypeID];
}
ObjectType GetSpecialObject(SPECIALMEANING Meaning){
int TypeID = 0;
if(Meaning > 0 && Meaning < NARRAY(SpecialObjects)){
TypeID = SpecialObjects[Meaning].TypeID;
if(TypeID == 0){
error("GetSpecialObject: Kein Objekttyp mit Bedeutung %d definiert.\n", Meaning);
}
}else{
error("GetSpecialObject: Ungültige Bedeutung %d.\n", Meaning);
}
return ObjectType(TypeID);
}
ObjectType GetObjectTypeByName(const char *SearchName, bool Movable){
if(SearchName == NULL){
error("GetObjectTypeByName: SearchName ist NULL.\n");
return ObjectType();
}
// NOTE(fusion): We add spaces around the search term to match whole words
// or sentences. This requires use to also add spaces around the searching
// text, in case the search term is at edge.
ObjectType BestMatch;
char Help[50];
char Pattern[50];
snprintf(Pattern, sizeof(Pattern), " %s ", SearchName);
for(int TypeID = TYPEID_CREATURE_CONTAINER + 1;
TypeID <= ObjectTypes.max;
TypeID += 1){
ObjectType Type = TypeID;
if(!Movable || !Type.getFlag(UNMOVE)){
const char *TypeName = Type.getName(-1);
if(TypeName && TypeName[0] != 0){
if(stricmp(SearchName, TypeName) == 0){
BestMatch = Type;
break;
}
if(BestMatch.TypeID == 0){
snprintf(Help, sizeof(Help), " %s ", TypeName);
if(strstr(Help, Pattern) != NULL){
BestMatch = Type;
}
}
}
}
}
return BestMatch;
}
static void LoadObjects(void){
char FileName[4096];
snprintf(FileName, sizeof(FileName), "%s/objects.srv", DATAPATH);
int TypeID = -1;
TReadScriptFile Script;
Script.open(FileName);
while(true){
Script.nextToken();
if(Script.Token == ENDOFFILE){
Script.close();
break;
}
if(Script.Token != IDENTIFIER){
Script.error("Identifier expected");
}
char Identifier[MAX_IDENT_LENGTH];
strcpy(Identifier, Script.getIdentifier());
Script.readSymbol('=');
if(strcmp(Identifier, "typeid") == 0){
TypeID = Script.readNumber();
// NOTE(fusion): Initialize object type.
TObjectType *TypeP = ObjectTypes.at(TypeID);
memset(TypeP, 0, sizeof(TObjectType));
for(int i = 0; i < NARRAY(TypeP->AttributeOffsets); i += 1){
TypeP->AttributeOffsets[i] = -1;
}
}else{
if(TypeID < 0){
Script.error("Invalid type id");
}
TObjectType *TypeP = ObjectTypes.at(TypeID);
if(strcmp(Identifier, "name") == 0){
TypeP->Name = AddStaticString(Script.readString());
}else if(strcmp(Identifier, "description") == 0){
TypeP->Description = AddStaticString(Script.readString());
}else if(strcmp(Identifier, "flags") == 0){
Script.readSymbol('{');
while(true){
Script.nextToken();
if(Script.Token == SPECIAL){
char Special = Script.getSpecial();
if(Special == ',') continue;
if(Special == '}') break;
}
int Flag = GetFlagByName(Script.getIdentifier());
if(Flag == -1){
Script.error("Unknown flag");
}
SetBit(TypeP->Flags, Flag);
}
// NOTE(fusion): Assign instance attribute offsets after parsing flags.
int InstanceAttributeCount = 0;
for(int InstanceAttribute = 0;
InstanceAttribute < NARRAY(TypeP->AttributeOffsets);
InstanceAttribute += 1){
// TODO(fusion): This thing with CONTENT, CONTAINER, and CHEST have
// been a trend so my guess it that CONTENT is the only instance
// attribute that has two flags (CONTAINER and CHEST), and we need
// to check it here.
if(CheckBit(TypeP->Flags, InstanceAttributeFlags[InstanceAttribute])
|| (InstanceAttribute == CONTENT && CheckBit(TypeP->Flags, CHEST))){
TypeP->AttributeOffsets[InstanceAttribute] = InstanceAttributeCount;
InstanceAttributeCount += 1;
}
}
}else if(strcmp(Identifier, "attributes") == 0){
Script.readSymbol('{');
while(true){
Script.nextToken();
if(Script.Token == SPECIAL){
char Special = Script.getSpecial();
if(Special == ',') continue;
if(Special == '}') break;
}
int TypeAttribute = GetTypeAttributeByName(Script.getIdentifier());
if(TypeAttribute == -1){
Script.error("Unknown attribute");
}
Script.readSymbol('=');
uint32 Value = (uint32)Script.readNumber();
TypeP->Attributes[TypeAttribute] = Value;
if(TypeAttribute == MEANING){
if(Value == 0 || Value >= NARRAY(SpecialObjects)){
Script.error("Unknown meaning");
}
if(SpecialObjects[Value].TypeID != 0){
Script.error("Special object already defined");
}
SpecialObjects[Value].setTypeID(TypeID);
}
}
}else{
Script.error("Unknown object type property");
}
}
}
}
static void LoadConversionList(void){
STATIC_ASSERT(NARRAY(OldGroup) == NARRAY(OldNumber));
for(int i = 0; i < NARRAY(OldGroup); i += 1){
OldGroup[i] = 0;
OldNumber[i] = 0;
}
for(int i = 0; i < NARRAY(NewType); i += 1){
NewType[i] = -1;
}
char FileName[4096];
snprintf(FileName, sizeof(FileName), "%s/conversion.lst", DATAPATH);
std::ifstream IN(FileName, std::ios_base::in);
if(IN.fail()){
error("LoadConversionList: Kann Datei %s nicht öffnen.\n", FileName);
throw "Cannot open conversion.lst";
}
while(true){
int Group, Number, TypeID;
IN >> Group >> Number >> TypeID;
if(IN.fail()){
// TODO(fusion): if(!IN.eof()) { error(...); }
IN.close();
break;
}
// TODO(fusion): Review this?
if(TypeID <= 0 || TypeID >= NARRAY(OldGroup)){
error("LoadConversionList: Ungültiger Typ %d.\n", TypeID);
throw "Error while loading conversion.lst";
}
OldGroup[TypeID] = Group;
OldNumber[TypeID] = Number;
NewType[GetNewTypeIndex(Group, Number)] = TypeID;
}
// NOTE(fusion): Map and body containers.
for(int TypeID = 0; TypeID <= 10; TypeID += 1){
OldGroup[TypeID] = 0;
OldNumber[TypeID] = (uint8)TypeID;
NewType[GetNewTypeIndex(0, (uint8)TypeID)] = TypeID;
}
// NOTE(fusion): Creature container.
OldGroup[99] = 250;
OldNumber[99] = 0;
NewType[GetNewTypeIndex(250, 0)] = 99;
}
void InitObjects(void){
LoadObjects();
LoadConversionList();
}
void ExitObjects(void){
// no-op
}

120
src/game/src/objects.hh Normal file
View file

@ -0,0 +1,120 @@
#ifndef TIBIA_OBJECTS_HH_
#define TIBIA_OBJECTS_HH_ 1
#include "common.hh"
#include "enums.hh"
enum : int{
TYPEID_MAP_CONTAINER = 0,
TYPEID_HEAD_CONTAINER = 1,
TYPEID_NECK_CONTAINER = 2,
TYPEID_BAG_CONTAINER = 3,
TYPEID_TORSO_CONTAINER = 4,
TYPEID_RIGHTHAND_CONTAINER = 5,
TYPEID_LEFTHAND_CONTAINER = 6,
TYPEID_LEGS_CONTAINER = 7,
TYPEID_FEET_CONTAINER = 8,
TYPEID_FINGER_CONTAINER = 9,
TYPEID_AMMO_CONTAINER = 10,
TYPEID_CREATURE_CONTAINER = 99,
};
struct ObjectType {
ObjectType(void) { this->setTypeID(0); }
ObjectType(int TypeID) { this->setTypeID(TypeID); }
void setTypeID(int TypeID);
bool getFlag(FLAG Flag);
uint32 getAttribute(TYPEATTRIBUTE Attribute);
int getAttributeOffset(INSTANCEATTRIBUTE Attribute);
const char *getName(int Count);
const char *getDescription(void);
bool isMapContainer(void){
return this->TypeID == TYPEID_MAP_CONTAINER;
}
bool isBodyContainer(void){
return this->TypeID == TYPEID_HEAD_CONTAINER
|| this->TypeID == TYPEID_NECK_CONTAINER
|| this->TypeID == TYPEID_BAG_CONTAINER
|| this->TypeID == TYPEID_TORSO_CONTAINER
|| this->TypeID == TYPEID_RIGHTHAND_CONTAINER
|| this->TypeID == TYPEID_LEFTHAND_CONTAINER
|| this->TypeID == TYPEID_LEGS_CONTAINER
|| this->TypeID == TYPEID_FEET_CONTAINER
|| this->TypeID == TYPEID_FINGER_CONTAINER
|| this->TypeID == TYPEID_AMMO_CONTAINER;
}
bool isCreatureContainer(void){
return this->TypeID == TYPEID_CREATURE_CONTAINER;
}
bool isTwoHanded(void){
return this->getFlag(CLOTHES)
&& this->getAttribute(BODYPOSITION) == 0;
}
bool isWeapon(void){
return this->getFlag(WEAPON)
|| this->getFlag(BOW)
|| this->getFlag(THROW)
|| this->getFlag(WAND);
}
bool isCloseWeapon(void){
if(!this->getFlag(WEAPON)){
return false;
}
int WeaponType = this->getAttribute(WEAPONTYPE);
return WeaponType == WEAPON_SWORD
|| WeaponType == WEAPON_CLUB
|| WeaponType == WEAPON_AXE;
}
ObjectType getDisguise(void){
if(this->getFlag(DISGUISE)){
return (int)this->getAttribute(DISGUISETARGET);
}else{
return *this;
}
}
bool operator==(const ObjectType &Other) const {
return this->TypeID == Other.TypeID;
}
bool operator!=(const ObjectType &Other) const {
return this->TypeID != Other.TypeID;
}
// DATA
// =================
int TypeID;
};
struct TObjectType {
const char *Name;
const char *Description;
uint8 Flags[9];
uint32 Attributes[62];
int AttributeOffsets[18];
};
int GetFlagByName(const char *Name);
int GetTypeAttributeByName(const char *Name);
int GetInstanceAttributeByName(const char *Name);
const char *GetFlagName(int Flag);
const char *GetTypeAttributeName(int Attribute);
const char *GetInstanceAttributeName(int Attribute);
bool ObjectTypeExists(int TypeID);
bool ObjectTypeExists(uint8 Group, uint8 Number);
ObjectType GetNewObjectType(uint8 Group, uint8 Number);
void GetOldObjectType(ObjectType Type, uint8 *Group, uint8 *Number);
ObjectType GetSpecialObject(SPECIALMEANING Meaning);
ObjectType GetObjectTypeByName(const char *SearchName, bool Movable);
void InitObjects(void);
void ExitObjects(void);
#endif //TIBIA_OBJECTS_HH_

4294
src/game/src/operate.cc Normal file

File diff suppressed because it is too large Load diff

198
src/game/src/operate.hh Normal file
View file

@ -0,0 +1,198 @@
#ifndef TIBIA_OPERATE_HH_
#define TIBIA_OPERATE_HH_ 1
#include "common.hh"
#include "containers.hh"
#include "cr.hh"
#include "map.hh"
enum : int {
CREATURE_HEALTH_CHANGED = 1,
CREATURE_LIGHT_CHANGED = 2,
CREATURE_OUTFIT_CHANGED = 3,
CREATURE_SPEED_CHANGED = 4,
CREATURE_SKULL_CHANGED = 5,
CREATURE_PARTY_CHANGED = 6,
};
enum : int {
OBJECT_DELETED = 0,
OBJECT_CREATED = 1,
OBJECT_CHANGED = 2,
OBJECT_MOVED = 3,
};
enum : int {
CHANNEL_GUILD = 0,
CHANNEL_GAMEMASTER = 1,
CHANNEL_TUTOR = 2,
CHANNEL_RULEVIOLATIONS = 3,
CHANNEL_GAMECHAT = 4,
CHANNEL_TRADE = 5,
CHANNEL_RLCHAT = 6,
CHANNEL_HELP = 7,
PUBLIC_CHANNELS = 8,
FIRST_PRIVATE_CHANNEL = PUBLIC_CHANNELS,
MAX_CHANNELS = 0xFFFF,
};
struct TChannel {
TChannel(void);
// TODO(fusion): `TChannel` will primarily live inside the `Channel` vector,
// which needs to resize its internal array as needed. To resize, it needs
// to copy/swap elements, which would be impossible since `TChannel` itself
// owns a few vectors which were made NON-COPYABLE to prevent memory bugs.
// To fix this problem and allow `TChannel` to be copyable, we need to
// implement the copy constructor and assignment manually. They're annoying
// and expensive but should allow everything to compile again.
// This problem arises from the fact that our unconventional `vector` type
// has a weird interface but still manages its underlying memory. If we are
// to resolve this completely, we'd need to re-implement `vector` properly
// and preferably with move semantics (if we want to follow the C++ route,
// which we may not).
TChannel(const TChannel &Other);
void operator=(const TChannel &Other);
// DATA
// =================
uint32 Moderator;
char ModeratorName[30];
vector<uint32> Subscriber;
int Subscribers;
vector<uint32> InvitedPlayer;
int InvitedPlayers;
};
struct TParty {
TParty(void);
// TODO(fusion): Same as `TChannel`.
TParty(const TParty &Other);
void operator=(const TParty &Other);
// DATA
// =================
uint32 Leader;
vector<uint32> Member;
int Members;
vector<uint32> InvitedPlayer;
int InvitedPlayers;
};
struct TStatement {
uint32 StatementID;
int TimeStamp;
uint32 CharacterID;
int Mode;
int Channel;
uint32 Text;
bool Reported;
};
struct TListener {
uint32 StatementID;
uint32 CharacterID;
};
struct TReportedStatement {
uint32 StatementID;
int TimeStamp;
uint32 CharacterID;
int Mode;
int Channel;
char Text[256];
};
void AnnounceMovingCreature(uint32 CreatureID, Object Con);
void AnnounceChangedCreature(uint32 CreatureID, int Type);
void AnnounceChangedField(Object Obj, int Type);
void AnnounceChangedContainer(Object Obj, int Type);
void AnnounceChangedInventory(Object Obj, int Type);
void AnnounceChangedObject(Object Obj, int Type);
void AnnounceGraphicalEffect(int x, int y, int z, int Type);
void AnnounceTextualEffect(int x, int y, int z, int Color, const char *Text);
void AnnounceMissile(int OrigX, int OrigY, int OrigZ,
int DestX, int DestY, int DestZ, int Type);
void CheckTopMoveObject(uint32 CreatureID, Object Obj, Object Ignore);
void CheckTopUseObject(uint32 CreatureID, Object Obj);
void CheckTopMultiuseObject(uint32 CreatureID, Object Obj);
void CheckMoveObject(uint32 CreatureID, Object Obj, bool Take);
void CheckMapDestination(uint32 CreatureID, Object Obj, Object MapCon);
void CheckMapPlace(uint32 CreatureID, ObjectType Type, Object MapCon);
void CheckContainerDestination(Object Obj, Object Con);
void CheckContainerPlace(ObjectType Type, Object Con, Object OldObj);
void CheckDepotSpace(uint32 CreatureID, Object Source, Object Destination, int Count);
void CheckInventoryDestination(Object Obj, Object Con, bool Split);
void CheckInventoryPlace(ObjectType Type, Object Con, Object OldObj);
void CheckWeight(uint32 CreatureID, Object Obj, int Count);
void CheckWeight(uint32 CreatureID, ObjectType Type, uint32 Value, int OldWeight);
void NotifyCreature(uint32 CreatureID, Object Obj, bool Inventory);
void NotifyCreature(uint32 CreatureID, ObjectType Type, bool Inventory);
void NotifyAllCreatures(Object Obj, int Type, Object OldCon);
void NotifyTrades(Object Obj);
void NotifyDepot(uint32 CreatureID, Object Obj, int Count);
void CloseContainer(Object Con, bool Force);
Object Create(Object Con, ObjectType Type, uint32 Value);
Object Copy(Object Con, Object Source);
void Move(uint32 CreatureID, Object Obj, Object Con, int Count, bool NoMerge, Object Ignore);
void Merge(uint32 CreatureID, Object Obj, Object Dest, int Count, Object Ignore);
void Change(Object Obj, ObjectType NewType, uint32 Value);
void Change(Object Obj, INSTANCEATTRIBUTE Attribute, uint32 Value);
void Delete(Object Obj, int Count);
void Empty(Object Con, int Remainder);
void GraphicalEffect(int x, int y, int z, int Type);
void GraphicalEffect(Object Obj, int Type);
void TextualEffect(Object Obj, int Color, const char *Format, ...) ATTR_PRINTF(3, 4);
void Missile(Object Start, Object Dest, int Type);
void Look(uint32 CreatureID, Object Obj);
void Talk(uint32 CreatureID, int Mode, const char *Addressee, const char *Text, bool CheckSpamming);
void Use(uint32 CreatureID, Object Obj1, Object Obj2, uint8 Info);
void Turn(uint32 CreatureID, Object Obj);
void CreatePool(Object Con, ObjectType Type, uint32 Value);
void EditText(uint32 CreatureID, Object Obj, const char *Text);
Object CreateAtCreature(uint32 CreatureID, ObjectType Type, uint32 Value);
void DeleteAtCreature(uint32 CreatureID, ObjectType Type, int Amount, uint32 Value);
void ProcessCronSystem(void);
bool SectorRefreshable(int SectorX, int SectorY, int SectorZ);
void RefreshSector(int SectorX, int SectorY, int SectorZ, const uint8 *Data, int Count);
void RefreshMap(void);
void RefreshCylinders(void);
void ApplyPatch(int SectorX, int SectorY, int SectorZ,
bool FullSector, TReadScriptFile *Script, bool SaveHouses);
void ApplyPatches(void);
uint32 LogCommunication(uint32 CreatureID, int Mode, int Channel, const char *Text);
uint32 LogListener(uint32 StatementID, TPlayer *Player);
void ProcessCommunicationControl(void);
int GetCommunicationContext(uint32 CharacterID, uint32 StatementID,
int *NumberOfStatements, vector<TReportedStatement> **ReportedStatements);
int GetNumberOfChannels(void);
bool ChannelActive(int ChannelID);
bool ChannelAvailable(int ChannelID, uint32 CharacterID);
const char *GetChannelName(int ChannelID, uint32 CharacterID);
bool ChannelSubscribed(int ChannelID, uint32 CharacterID);
uint32 GetFirstSubscriber(int ChannelID);
uint32 GetNextSubscriber(void);
bool MayOpenChannel(uint32 CharacterID);
void OpenChannel(uint32 CharacterID);
void CloseChannel(int ChannelID);
void InviteToChannel(uint32 CharacterID, const char *Name);
void ExcludeFromChannel(uint32 CharacterID, const char *Name);
bool JoinChannel(int ChannelID, uint32 CharacterID);
void LeaveChannel(int ChannelID, uint32 CharacterID, bool Close);
void LeaveAllChannels(uint32 CharacterID);
TParty *GetParty(uint32 LeaderID);
bool IsInvitedToParty(uint32 GuestID, uint32 HostID);
void DisbandParty(uint32 LeaderID);
void InviteToParty(uint32 HostID, uint32 GuestID);
void RevokeInvitation(uint32 HostID, uint32 GuestID);
void JoinParty(uint32 GuestID, uint32 HostID);
void PassLeadership(uint32 OldLeaderID, uint32 NewLeaderID);
void LeaveParty(uint32 MemberID, bool Forced);
#endif //TIBIA_OPERATE_HH_

1770
src/game/src/query.cc Normal file

File diff suppressed because it is too large Load diff

192
src/game/src/query.hh Normal file
View file

@ -0,0 +1,192 @@
#ifndef TIBIA_QUERY_HH_
#define TIBIA_QUERY_HH_ 1
#include "common.hh"
#include "threads.hh"
enum : int {
QUERY_STATUS_OK = 0,
QUERY_STATUS_ERROR = 1,
QUERY_STATUS_FAILED = 3,
};
struct TQueryManagerConnection{
TQueryManagerConnection(void) : TQueryManagerConnection(KB(16)) {}
TQueryManagerConnection(int QueryBufferSize);
~TQueryManagerConnection(void);
void connect(void);
void disconnect(void);
int write(const uint8 *Buffer, int Size);
int read(uint8 *Buffer, int Size, int Timeout);
bool isConnected(void){
return this->Socket != -1;
}
void prepareQuery(int QueryType);
void sendFlag(bool Flag);
void sendByte(uint8 Byte);
void sendWord(uint16 Word);
void sendQuad(uint32 Quad);
void sendString(const char *String);
void sendBytes(const uint8 *Buffer, int Count);
bool getFlag(void);
uint8 getByte(void);
uint16 getWord(void);
uint32 getQuad(void);
void getString(char *Buffer, int MaxLength);
void getBytes(uint8 *Buffer, int Count);
int executeQuery(int Timeout, bool AutoReconnect);
int checkAccountPassword(uint32 AccountID, const char *Password, const char *IPAddress);
int loginAdmin(uint32 AccountID, bool PrivateWorld, int *NumberOfCharacters,
char (*Characters)[30], char (*Worlds)[30], uint8 (*IPAddresses)[4],
uint16 *Ports, uint16 *PremiumDaysLeft);
int loadWorldConfig(int *WorldType, int *RebootTime, int *IPAddress,
int *Port, int *MaxPlayers, int *PremiumPlayerBuffer, int *MaxNewbies,
int *PremiumNewbieBuffer);
int loginGame(uint32 AccountID, char *PlayerName, const char *Password,
const char *IPAddress, bool PrivateWorld, bool PremiumAccountRequired,
bool GamemasterRequired, uint32 *CharacterID, int *Sex, char *Guild,
char *Rank, char *Title, int *NumberOfBuddies, uint32 *BuddyIDs,
char (*BuddyNames)[30], uint8 *Rights, bool *PremiumAccountActivated);
int logoutGame(uint32 CharacterID, int Level, const char *Profession,
const char *Residence, time_t LastLoginTime, int TutorActivities);
int setNotation(uint32 GamemasterID, const char *PlayerName, const char *IPAddress,
const char *Reason, const char *Comment, uint32 *BanishmentID);
int setNamelock(uint32 GamemasterID, const char *PlayerName, const char *IPAddress,
const char *Reason, const char *Comment);
int banishAccount(uint32 GamemasterID, const char *PlayerName, const char *IPAddress,
const char *Reason, const char *Comment, bool *FinalWarning, int *Days,
uint32 *BanishmentID);
int reportStatement(uint32 ReporterID, const char *PlayerName, const char *Reason,
const char *Comment, uint32 BanishmentID, uint32 StatementID,
int NumberOfStatements, uint32 *StatementIDs, int *TimeStamps,
uint32 *CharacterIDs, const char (*Channels)[30], const char (*Texts)[256]);
int banishIPAddress(uint32 GamemasterID, const char *PlayerName, const char *IPAddress,
const char *Reason, const char *Comment);
int logCharacterDeath(uint32 CharacterID, int Level, uint32 Offender,
const char *Remark, bool Unjustified, time_t Time);
int addBuddy(uint32 AccountID, uint32 Buddy);
int removeBuddy(uint32 AccountID, uint32 Buddy);
int decrementIsOnline(uint32 CharacterID);
int finishAuctions(int *NumberOfAuctions, uint16 *HouseIDs,
uint32 *CharacterIDs, char (*CharacterNames)[30], int *Bids);
int excludeFromAuctions(uint32 CharacterID, bool Banish);
int transferHouses(int *NumberOfTransfers, uint16 *HouseIDs,
uint32 *NewOwnerIDs, char (*NewOwnerNames)[30], int *Prices);
int cancelHouseTransfer(uint16 HouseID);
int evictFreeAccounts(int *NumberOfEvictions, uint16 *HouseIDs, uint32 *OwnerIDs);
int evictDeletedCharacters(int *NumberOfEvictions, uint16 *HouseIDs);
int evictExGuildleaders(int NumberOfGuildhouses,
int *NumberOfEvictions, uint16 *HouseIDs, uint32 *Guildleaders);
int insertHouseOwner(uint16 HouseID, uint32 OwnerID, int PaidUntil);
int updateHouseOwner(uint16 HouseID, uint32 OwnerID, int PaidUntil);
int deleteHouseOwner(uint16 HouseID);
int getHouseOwners(int *NumberOfOwners, uint16 *HouseIDs,
uint32 *OwnerIDs, char (*OwnerNames)[30], int *PaidUntils);
int getAuctions(int *NumberOfAuctions, uint16 *HouseIDs);
int startAuction(uint16 HouseID);
int insertHouses(int NumberOfHouses, uint16 *HouseIDs,
const char **Names, int *Rents, const char **Descriptions,
int *Sizes, int *PositionsX,int *PositionsY,int *PositionsZ,
char (*Towns)[30], bool *Guildhouses);
int clearIsOnline(int *NumberOfAffectedPlayers);
int createPlayerlist(int NumberOfPlayers, const char **Names,
int *Levels, const char (*Professions)[30], bool *NewRecord);
int logKilledCreatures(int NumberOfRaces, const char **Names,
int *KilledPlayers,int *KilledCreatures);
int loadPlayers(uint32 MinimumCharacterID, int *NumberOfPlayers,
char (*Names)[30], uint32 *CharacterIDs);
int getKeptCharacters(uint32 MinimumCharacterID,
int *NumberOfPlayers, uint32 *CharacterIDs);
int getDeletedCharacters(uint32 MinimumCharacterID,
int *NumberOfPlayers, uint32 *CharacterIDs);
int deleteOldCharacter(uint32 CharacterID);
int getHiddenCharacters(uint32 MinimumCharacterID,
int *NumberOfPlayers, uint32 *CharacterIDs);
int createHighscores(int NumberOfPlayers, uint32 *CharacterIDs,
int *ExpPoints, int *ExpLevel, int *Fist, int *Club, int *Axe,
int *Sword, int *Distance, int *Shielding, int *Magic, int *Fishing);
int createCensus(void);
int createKillStatistics(void);
int getPlayersOnline(int *NumberOfWorlds, char (*Names)[30], uint16 *Players);
int getWorlds(int *NumberOfWorlds, char (*Names)[30]);
int getServerLoad(const char *World, int Period, int *Data);
int insertPaymentDataOld(uint32 PurchaseNr, uint32 ReferenceNr,
const char *FirstName, const char *LastName, const char *Company,
const char *Street, const char *Zip, const char *City, const char *Country,
const char *State, const char *Phone, const char *Fax, const char *EMail,
const char *PaymentMethod, uint32 ProductID, const char *Registrant,
uint32 AccountID, uint32 *PaymentID);
int addPaymentOld(uint32 AccountID, const char *Description,
uint32 PaymentID, int Days, int *ActionTaken);
int cancelPaymentOld(uint32 PurchaseNr, uint32 ReferenceNr,
uint32 AccountID, bool *IllegalUse, char *EMailAddress);
int insertPaymentDataNew(uint32 PurchaseNr, uint32 ReferenceNr,
const char *FirstName, const char *LastName, const char *Company,
const char *Street, const char *Zip, const char *City, const char *Country,
const char *State, const char *Phone, const char *Fax, const char *EMail,
const char *PaymentMethod, uint32 ProductID, const char *Registrant,
const char *PaymentKey, uint32 *PaymentID);
int addPaymentNew(const char *PaymentKey, uint32 PaymentID,
int *ActionTaken, char *EMailReceiver);
int cancelPaymentNew(uint32 PurchaseNr, uint32 ReferenceNr,
const char *PaymentKey, bool *IllegalUse, bool *Present,
char *EMailAddress);
// DATA
// =================
int BufferSize;
uint8 *Buffer;
TReadBuffer ReadBuffer;
TWriteBuffer WriteBuffer;
int Socket;
bool QueryOk;
};
struct TQueryManagerConnectionPool{
TQueryManagerConnectionPool(int Connections);
void init(void);
void exit(void);
TQueryManagerConnection *getConnection(void);
void releaseConnection(TQueryManagerConnection *Connection);
// DATA
// =================
int NumberOfConnections;
TQueryManagerConnection *QueryManagerConnection;
bool *QueryManagerConnectionFree;
Semaphore FreeQueryManagerConnections;
Semaphore QueryManagerConnectionMutex;
};
struct TQueryManagerPoolConnection{
TQueryManagerPoolConnection(TQueryManagerConnectionPool *Pool);
~TQueryManagerPoolConnection(void);
// TODO(fusion): I don't know if this was the indended way to access this
// structure but it is only a small wrapper and accessing members directly
// would be too verbose, specially when it is also named `QueryManagerConnection`.
TQueryManagerConnection *operator->(void){
return this->QueryManagerConnection;
}
operator bool(void) const {
return this->QueryManagerConnection != NULL;
}
// DATA
// =================
TQueryManagerConnectionPool *QueryManagerConnectionPool;
TQueryManagerConnection *QueryManagerConnection;
};
void SetQueryManagerLoginData(int Type, const char *Data);
#endif //TIBIA_QUERY_HH_

277
src/game/src/reader.cc Normal file
View file

@ -0,0 +1,277 @@
#include "reader.hh"
#include "config.hh"
#include "cr.hh"
#include "map.hh"
#include "threads.hh"
static ThreadHandle ReaderThread;
static TReaderThreadOrder OrderBuffer[200];
static int OrderPointerWrite;
static int OrderPointerRead;
static Semaphore OrderBufferEmpty(NARRAY(OrderBuffer));
static Semaphore OrderBufferFull(0);
static TReaderThreadReply ReplyBuffer[200];
static int ReplyPointerWrite;
static int ReplyPointerRead;
static TDynamicWriteBuffer HelpBuffer(KB(64));
// Reader Orders
// =============================================================================
void InitReaderBuffers(void){
OrderPointerWrite = 0;
OrderPointerRead = 0;
ReplyPointerWrite = 0;
ReplyPointerRead = 0;
}
void InsertOrder(TReaderThreadOrderType OrderType,
int SectorX, int SectorY, int SectorZ, uint32 CharacterID){
int Orders = (OrderPointerWrite - OrderPointerRead);
if(Orders >= NARRAY(OrderBuffer)){
error("InsertOrder (Reader): Order-Puffer ist voll => Vergrößern.\n");
}
OrderBufferEmpty.down();
int WritePos = OrderPointerWrite % NARRAY(OrderBuffer);
OrderBuffer[WritePos].OrderType = OrderType;
OrderBuffer[WritePos].SectorX = SectorX;
OrderBuffer[WritePos].SectorY = SectorY;
OrderBuffer[WritePos].SectorZ = SectorZ;
OrderBuffer[WritePos].CharacterID = CharacterID;
OrderPointerWrite += 1;
OrderBufferFull.up();
}
void GetOrder(TReaderThreadOrder *Order){
OrderBufferFull.down();
*Order = OrderBuffer[OrderPointerRead % NARRAY(OrderBuffer)];
OrderPointerRead += 1;
OrderBufferEmpty.up();
}
void TerminateReaderOrder(void){
InsertOrder(READER_ORDER_TERMINATE, 0, 0, 0, 0);
}
void LoadSectorOrder(int SectorX, int SectorY, int SectorZ){
InsertOrder(READER_ORDER_LOADSECTOR, SectorX, SectorY, SectorZ, 0);
}
void LoadCharacterOrder(uint32 CharacterID){
InsertOrder(READER_ORDER_LOADCHARACTER, 0, 0, 0, CharacterID);
}
void ProcessLoadSectorOrder(int SectorX, int SectorY, int SectorZ){
// TODO(fusion): We parsed sector files way too many times now. And there
// is also a drop in loader quality.
char FileName[4096];
snprintf(FileName, sizeof(FileName), "%s/%04d-%04d-%02d.sec",
ORIGMAPPATH, SectorX, SectorY, SectorZ);
if(!FileExists(FileName)){
return;
}
int OffsetX = -1;
int OffsetY = -1;
bool Refreshable = false;
HelpBuffer.Position = 0;
TReadScriptFile Script;
Script.open(FileName);
while(true){
Script.nextToken();
if(Script.Token == ENDOFFILE){
Script.close();
break;
}
if(Script.Token == SPECIAL && Script.getSpecial() == ','){
continue;
}
if(Script.Token == BYTES){
uint8 *Offset = Script.getBytesequence();
OffsetX = (int)Offset[0];
OffsetY = (int)Offset[1];
Refreshable = false;
Script.readSymbol(':');
}else if(Script.Token == IDENTIFIER){
if(OffsetX == -1 || OffsetY == -1){
Script.error("coordinate expected");
}
const char *Identifier = Script.getIdentifier();
if(strcmp(Identifier, "refresh") == 0){
Refreshable = true;
}else if(strcmp(Identifier, "content") == 0){
Script.readSymbol('=');
if(Refreshable){
HelpBuffer.writeByte((uint8)OffsetX);
HelpBuffer.writeByte((uint8)OffsetY);
}
LoadObjects(&Script, &HelpBuffer, !Refreshable);
}
}
}
int Size = HelpBuffer.Position;
if(Size > 0){
uint8 *Data = new uint8[Size];
memcpy(Data, HelpBuffer.Data, Size);
SectorReply(SectorX, SectorY, SectorZ, Data, Size);
}
}
void ProcessLoadCharacterOrder(uint32 CharacterID){
while(true){
TPlayerData *Slot = AssignPlayerPoolSlot(CharacterID, true);
if(Slot == NULL){
error("ProcessLoadCharacterOrder: Kann keinen Slot für Spielerdaten zuweisen.\n");
break;
}
if(Slot->Locked == GetGameThreadID()){
break;
}
if(Slot->Locked == gettid()){
IncreasePlayerPoolSlotSticky(Slot);
ReleasePlayerPoolSlot(Slot);
CharacterReply(CharacterID);
break;
}
DelayThread(1, 0);
}
}
int ReaderThreadLoop(void *Unused){
TReaderThreadOrder Order = {};
while(true){
GetOrder(&Order);
if(Order.OrderType == READER_ORDER_TERMINATE){
break;
}
switch(Order.OrderType){
case READER_ORDER_LOADSECTOR:{
ProcessLoadSectorOrder(Order.SectorX, Order.SectorY, Order.SectorZ);
break;
}
case READER_ORDER_LOADCHARACTER:{
ProcessLoadCharacterOrder(Order.CharacterID);
break;
}
default:{
error("ReaderThreadLoop: Unbekanntes Kommando %d.\n", Order.OrderType);
break;
}
}
}
return 0;
}
// Reader Replies
// =============================================================================
void InsertReply(TReaderThreadReplyType ReplyType,
int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size){
int Replies = (ReplyPointerWrite - ReplyPointerRead);
while(Replies > NARRAY(ReplyBuffer)){
error("InsertReply (Reader): Puffer ist voll; warte...\n");
DelayThread(5, 0);
}
int WritePos = ReplyPointerWrite % NARRAY(ReplyBuffer);
ReplyBuffer[WritePos].ReplyType = ReplyType;
ReplyBuffer[WritePos].SectorX = SectorX;
ReplyBuffer[WritePos].SectorY = SectorY;
ReplyBuffer[WritePos].SectorZ = SectorZ;
ReplyBuffer[WritePos].Data = Data;
ReplyBuffer[WritePos].Size = Size;
ReplyPointerWrite += 1;
}
bool GetReply(TReaderThreadReply *Reply){
bool Result = (ReplyPointerRead < ReplyPointerWrite);
if(Result){
*Reply = ReplyBuffer[ReplyPointerRead % NARRAY(ReplyBuffer)];
ReplyPointerRead += 1;
}
return Result;
}
void SectorReply(int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size){
InsertReply(READER_REPLY_SECTORDATA, SectorX, SectorY, SectorZ, Data, Size);
}
void CharacterReply(uint32 CharacterID){
InsertReply(READER_REPLY_CHARACTERDATA, 0, 0, 0, NULL, (int)CharacterID);
}
void ProcessSectorReply(TRefreshSectorFunction *RefreshSector,
int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size){
RefreshSector(SectorX, SectorY, SectorZ, Data, Size);
delete[] Data;
}
void ProcessCharacterReply(TSendMailsFunction *SendMails, uint32 CharacterID){
TPlayerData *Slot = AttachPlayerPoolSlot(CharacterID, true);
if(Slot == NULL){
DecreasePlayerPoolSlotSticky(Slot);
return;
}
SendMails(Slot);
DecreasePlayerPoolSlotSticky(Slot);
ReleasePlayerPoolSlot(Slot);
}
void ProcessReaderThreadReplies(TRefreshSectorFunction *RefreshSector, TSendMailsFunction *SendMails){
TReaderThreadReply Reply = {};
while(GetReply(&Reply)){
switch(Reply.ReplyType){
case READER_REPLY_SECTORDATA:{
ProcessSectorReply(RefreshSector,
Reply.SectorX, Reply.SectorY, Reply.SectorZ,
Reply.Data, Reply.Size);
break;
}
case READER_REPLY_CHARACTERDATA:{
ProcessCharacterReply(SendMails, (uint32)Reply.Size);
break;
}
default:{
error("ProcessReaderThreadReplies: Unbekannte Rückmeldung %d.\n", Reply.ReplyType);
break;
}
}
}
}
// Initialization
// =============================================================================
void InitReader(void){
InitReaderBuffers();
ReaderThread = StartThread(ReaderThreadLoop, NULL, false);
if(ReaderThread == INVALID_THREAD_HANDLE){
throw "cannot start reader thread";
}
}
void ExitReader(void){
if(ReaderThread != INVALID_THREAD_HANDLE){
TerminateReaderOrder();
JoinThread(ReaderThread);
ReaderThread = INVALID_THREAD_HANDLE;
}
}

64
src/game/src/reader.hh Normal file
View file

@ -0,0 +1,64 @@
#ifndef TIBIA_READER_HH_
#define TIBIA_READER_HH_ 1
#include "common.hh"
struct TPlayerData;
typedef void TRefreshSectorFunction(int SectorX, int SectorY, int SectorZ,
const uint8 *Data, int Size);
typedef void TSendMailsFunction(TPlayerData *PlayerData);
enum TReaderThreadOrderType: int {
READER_ORDER_TERMINATE = 0,
READER_ORDER_LOADSECTOR = 1,
READER_ORDER_LOADCHARACTER = 2,
};
enum TReaderThreadReplyType: int {
READER_REPLY_SECTORDATA = 0,
READER_REPLY_CHARACTERDATA = 1,
};
struct TReaderThreadOrder {
TReaderThreadOrderType OrderType;
int SectorX;
int SectorY;
int SectorZ;
uint32 CharacterID;
};
struct TReaderThreadReply {
TReaderThreadReplyType ReplyType;
int SectorX;
int SectorY;
int SectorZ;
uint8 *Data;
int Size;
};
void InitReaderBuffers(void);
void InsertOrder(TReaderThreadOrderType OrderType,
int SectorX, int SectorY, int SectorZ, uint32 CharacterID);
void GetOrder(TReaderThreadOrder *Order);
void TerminateReaderOrder(void);
void LoadSectorOrder(int SectorX, int SectorY, int SectorZ);
void LoadCharacterOrder(uint32 CharacterID);
void ProcessLoadSectorOrder(int SectorX, int SectorY, int SectorZ);
void ProcessLoadCharacterOrder(uint32 CharacterID);
int ReaderThreadLoop(void *Unused);
void InsertReply(TReaderThreadReplyType ReplyType,
int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size);
bool GetReply(TReaderThreadReply *Reply);
void SectorReply(int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size);
void CharacterReply(uint32 CharacterID);
void ProcessSectorReply(TRefreshSectorFunction *RefreshSector,
int SectorX, int SectorY, int SectorZ, uint8 *Data, int Size);
void ProcessCharacterReply(TSendMailsFunction *SendMails, uint32 CharacterID);
void ProcessReaderThreadReplies(TRefreshSectorFunction *RefreshSector, TSendMailsFunction *SendMails);
void InitReader(void);
void ExitReader(void);
#endif //TIBIA_READER_HH

1820
src/game/src/receiving.cc Normal file

File diff suppressed because it is too large Load diff

970
src/game/src/script.cc Normal file
View file

@ -0,0 +1,970 @@
#include "script.hh"
// NOTE(fusion): Throwing a character array on the stack as an exception won't
// work because it implicitly decays into a character pointer which would then
// point to invalid data when actually parsed. It is the reason `ErrorString` is
// declared statically, or else you'd need to throw some heap allocated string
// which then becomes ambiguous whether you should free it or not. Used in:
// - TReadScriptFile::error
// - TWriteScriptFile::error
// - TReadBinaryFile::open
// - TReadBinaryFile::error
// - TWriteBinaryFile::open
// - TWriteBinaryFile::error
static char ErrorString[100];
// Helper Functions
// =============================================================================
static void SaveFile(const char *Filename){
if(Filename == NULL){
error("SaveFile: Filename ist NULL.\n");
return;
}
char BackupFilename[4096];
strcpy(BackupFilename, Filename);
strcat(BackupFilename, "#");
FILE *Source = fopen(Filename, "rb");
if(Source == NULL){
error("SaveFile: Quelldatei %s existiert nicht.\n", Filename);
return;
}
FILE *Dest = fopen(BackupFilename, "wb");
if(Dest == NULL){
error("SaveFile: Kann Zieldatei %s nicht anlegen.\n", BackupFilename);
fclose(Source);
return;
}
// NOTE(fusion): This function was in pretty bad shape after this point. The
// reason is probably because GHIDRA didn't make sense of it using `alloca`
// or some other mechanism to allocate a buffer on the stack and copy the whole
// file in one go. It's probably not a good idea to mimic that here so we'll
// do it gradually.
char Buffer[KB(16)];
while(true){
usize n = fread(Buffer, 1, sizeof(Buffer), Source);
if(n == 0){
if(ferror(Source)){
error("SaveFile: Fehler beim Lesen der Quelldatei %s.\n", Filename);
}
break;
}
if(fwrite(Buffer, 1, n, Dest) != n){
error("SaveFile: Fehler beim Schreiben der Zieldatei %s.\n", BackupFilename);
break;
}
}
if(fclose(Source) != 0){
error("SaveFile: Fehler %d beim Schließen der Quelldatei.\n", errno);
}
if(fclose(Dest) != 0){
error("SaveFile: Fehler %d beim Schließen der Zieldatei.\n", errno);
}
}
// TReadScriptFile
//==============================================================================
TReadScriptFile::TReadScriptFile(void){
this->RecursionDepth = -1;
this->Bytes = (uint8*)this->String;
}
TReadScriptFile::~TReadScriptFile(void){
if(this->RecursionDepth != -1){
::error("TReadScriptFile::~TReadScriptFile: Datei ist noch offen.\n");
for(int Depth = this->RecursionDepth; Depth >= 0; Depth -= 1){
// TODO(fusion): Probably `TReadScriptFile::close` inlined?
if(fclose(this->File[Depth]) != 0){
::error("TReadScriptFile::close: Fehler %d beim Schließen der Datei.\n", errno);
}
}
this->RecursionDepth = -1;
}
}
void TReadScriptFile::open(const char *FileName){
int Depth = this->RecursionDepth + 1;
if(Depth >= NARRAY(this->File)){
::error("TReadScriptFile::open: Rekursionstiefe zu groß.\n");
throw "Recursion depth too high";
}
ASSERT(Depth >= 0);
// TODO(fusion): More `strcpy`s...
if(Depth > 0 && FileName[0] != '/'){
strcpy(this->Filename[Depth], this->Filename[Depth - 1]);
if(char *Slash = findLast(this->Filename[Depth], '/')){
strcpy(Slash + 1, FileName);
}else{
strcpy(this->Filename[Depth], FileName);
}
}else{
strcpy(this->Filename[Depth], FileName);
}
this->File[Depth] = fopen(this->Filename[Depth], "rb");
if(this->File[Depth] == NULL){
int ErrCode = errno;
::error("TReadScriptFile::open: Kann Datei %s nicht öffnen.\n", this->Filename[Depth]);
::error("Fehler %d: %s.\n", ErrCode, GetErrorDescription(ErrCode));
throw "Cannot open script-file";
}
this->Line[Depth] = 1;
this->RecursionDepth = Depth;
}
void TReadScriptFile::close(void){
int Depth = this->RecursionDepth;
if(Depth <= -1){
::error("TReadScriptFile::close: Keine Datei offen.\n");
return;
}
ASSERT(Depth < NARRAY(this->File));
if(fclose(this->File[Depth]) != 0){
::error("TReadScriptFile::close: Fehler %d beim Schließen der Datei.\n", errno);
}
this->RecursionDepth -= 1;
}
void TReadScriptFile::error(const char *Text){
int Depth = this->RecursionDepth;
ASSERT(Depth >= 0 && Depth < NARRAY(this->File));
const char *Filename = this->Filename[Depth];
if(const char *Slash = findLast(this->Filename[Depth], '/')){
Filename = Slash + 1;
}
snprintf(ErrorString, sizeof(ErrorString),
"error in script-file \"%s\", line %d: %s",
Filename, this->Line[Depth], Text);
// TODO(fusion): Reset? Also seems like `TReadScriptFile::close` was inlined.
for(; Depth >= 0; Depth -= 1){
if(fclose(this->File[Depth]) != 0){
::error("TReadScriptFile::close: Fehler %d beim Schließen der Datei.\n", errno);
}
}
this->RecursionDepth = -1;
throw ErrorString;
}
// NOTE(fusion): This function in particular was in pretty bad shape. It should
// be one of the few that doesn't roughly match the original version. Nevertheless,
// I think we should properly split this into a lexer and parser. We find ourselves
// parsing strings and numbers multiple times here, whereas a simple lexer and
// parser would simplify the work tremendously.
// TODO(fusion): This needs to be tested to make sure it behaves like the original.
void TReadScriptFile::nextToken(void){
if(this->RecursionDepth == -1){
::error("TReadScriptFile::nextToken: Kein Skript zum Lesen geöffnet.\n");
this->Token = ENDOFFILE;
return;
}
// NOTE(fusion): Reset any previous token state.
memset(this->String, 0, sizeof(this->String));
this->Number = 0;
this->CoordX = 0;
this->CoordY = 0;
this->CoordZ = 0;
this->Special = 0;
// NOTE(fusion): `TReadScriptFile::error` will format and throw an error
// string that must be handled up the call stack. It must be considered
// an exit point for parsing errors in this function.
while(true){
int Depth = this->RecursionDepth;
ASSERT(Depth >= 0 && Depth < NARRAY(this->File));
FILE *File = this->File[Depth];
int c;
do{
c = getc(File);
if(c == '\n'){
this->Line[Depth] += 1;
}
}while(isSpace(c));
if(c == EOF){
if(Depth == 0){
this->Token = ENDOFFILE;
return;
}
this->close();
continue;
}
switch(c){
case '#':{ // COMMENT
while(true){
int next = getc(File);
if(next == '\n' || next == EOF){
if(next == '\n'){
this->Line[Depth] += 1;
}
break;
}
}
break;
}
case '@':{ // INCLUDE
int next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(next != '"'){
this->error("syntax error");
}
int StringLength = 0;
while(true){
// TODO(fusion): I don't think new lines are even allowed in
// file names but we should keep track of the line number even
// if they happen here.
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(next == '"'){
break;
}
if(StringLength >= (NARRAY(this->String) - 1)){
this->error("string too long");
}
this->String[StringLength] = (char)next;
StringLength += 1;
}
// TODO(fusion): Maybe check if the path is empty?
this->open(this->String);
// NOTE(fusion): This is the only place we parse a string without
// returning it as a token. We need to reset it to make sure any
// subsequent string-like token will be properly parsed.
memset(this->String, 0, sizeof(this->String));
break;
}
case '"':{ // STRING
int StringLength = 0;
while(true){
int next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(next == '\\'){
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(next == 'n'){
next = '\n';
}
}else if(next == '\n'){
// TODO(fusion): Shouldn't we prevent non-escaped new
// lines inside strings?
this->Line[Depth] += 1;
}else if(next == '"'){
break;
}
if(StringLength >= (NARRAY(this->String) - 1)){
this->error("string too long");
}
this->String[StringLength] = (char)next;
StringLength += 1;
}
this->Token = STRING;
return;
}
case '[':{ // COORDINATE
// NOTE(fusion): X-Coordinate or SPECIAL '['.
int Sign = -1;
int Coord = 0;
int next = getc(File);
if(isDigit(next)){
Sign = 1;
Coord = next - '0';
}else if(next != '-'){
this->Token = SPECIAL;
this->Special = '[';
if(next != EOF){
ungetc(next, File);
}
return;
}
while(true){
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(isDigit(next)){
Coord *= 10;
Coord += next - '0';
}else if(next == ','){
break;
}else{
this->error("syntax error");
}
}
this->CoordX = Sign * Coord;
// NOTE(fusion): Y-Coordinate.
Sign = -1;
Coord = 0;
next = getc(File);
if(isDigit(next)){
Sign = 1;
Coord = next - '0';
}else if(next != '-'){
this->error("syntax error");
}
while(true){
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(isDigit(next)){
Coord *= 10;
Coord += next - '0';
}else if(next == ','){
break;
}else{
this->error("syntax error");
}
}
this->CoordY = Sign * Coord;
// NOTE(fusion): Z-Coordinate.
Sign = -1;
Coord = 0;
next = getc(File);
if(isDigit(next)){
Sign = 1;
Coord = next - '0';
}else if(next != '-'){
this->error("syntax error");
}
while(true){
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(isDigit(next)){
Coord *= 10;
Coord += next - '0';
}else if(next == ']'){
break;
}else{
this->error("syntax error");
}
}
this->CoordZ = Sign * Coord;
this->Token = COORDINATE;
return;
}
case '<':{
int next = getc(File);
if(next == '='){
this->Special = 'L';
}else if(next == '>'){
this->Special = 'N';
}else{
this->Special = '<';
if(next != EOF){
ungetc(next, File);
}
}
this->Token = SPECIAL;
return;
}
case '>':{
int next = getc(File);
if(next == '='){
this->Special = 'G';
}else{
this->Special = '>';
if(next != EOF){
ungetc(next, File);
}
}
this->Token = SPECIAL;
return;
}
case '-':{
int next = getc(File);
if(next == '>'){
this->Special = 'I';
}else{
this->Special = '-';
if(next != EOF){
ungetc(next, File);
}
}
this->Token = SPECIAL;
return;
}
default:{
if(isAlpha(c)){
int IdentLength = 1;
this->String[0] = (char)c;
while(true){
int next = getc(File);
if(isAlpha(next) || isDigit(next) || next == '_'){
if(IdentLength >= (MAX_IDENT_LENGTH - 1)){
this->error("identifier too long");
}
this->String[IdentLength] = (char)next;
IdentLength += 1;
}else{
if(next != EOF){
ungetc(next, File);
}
break;
}
}
this->Token = IDENTIFIER;
}else if(isDigit(c)){
// NOTE(fusion): `this->Bytes` points to `this->String` (set
// in the constructor) which is why we check against the size
// of the `this->String` array. It doesn't seem to store the
// number of bytes but I've only seen it used with fixed size
// arrays like outfit colors or sector offsets.
// Also, it doesn't make sense to have a null terminator in
// a byte string so the capacity check doesn't include it as
// in the case of regular strings.
// TODO(fusion): We're not checking for integer overflow at all.
int BytesLength = 0;
int Number = c - '0';
while(true){
int next = getc(File);
if(isDigit(next)){
Number *= 10;
Number += next - '0';
}else if(next == '-'){
if(BytesLength >= NARRAY(this->String)){
this->error("too many bytes");
}
this->Bytes[BytesLength] = (uint8)Number;
BytesLength += 1;
// NOTE(fusion): If there is a '-' after a number, there
// better be a second number.
next = getc(File);
if(next == EOF){
this->error("unexpected end of file");
}else if(!isDigit(next)){
this->error("syntax error");
}
Number = next - '0';
}else{
if(next != EOF){
ungetc(next, File);
}
if(BytesLength <= 0){
this->Token = NUMBER;
this->Number = Number;
}else{
if(BytesLength >= NARRAY(this->String)){
this->error("too many bytes");
}
this->Token = BYTES;
this->Bytes[BytesLength] = (uint8)Number;
BytesLength += 1;
}
break;
}
}
}else{
this->Token = SPECIAL;
this->Special = (char)c;
}
return;
}
}
}
}
char *TReadScriptFile::getIdentifier(void){
if(this->Token != IDENTIFIER){
this->error("identifier expected");
}
strLower(this->String);
return this->String;
}
int TReadScriptFile::getNumber(void){
if(this->Token != NUMBER){
this->error("number expected");
}
return this->Number;
}
char *TReadScriptFile::getString(void){
if(this->Token != STRING){
this->error("string expected");
}
return this->String;
}
uint8 *TReadScriptFile::getBytesequence(void){
if(this->Token != BYTES){
this->error("byte-sequence expected");
}
return this->Bytes;
}
void TReadScriptFile::getCoordinate(int *x, int *y, int *z){
if(this->Token != COORDINATE){
this->error("coordinates expected");
}
*x = this->CoordX;
*y = this->CoordY;
*z = this->CoordZ;
}
char TReadScriptFile::getSpecial(void){
if(this->Token != SPECIAL){
this->error("special-char expected");
}
return this->Special;
}
// TWriteScriptFile
//==============================================================================
TWriteScriptFile::TWriteScriptFile(void){
this->File = NULL;
}
TWriteScriptFile::~TWriteScriptFile(void){
if(this->File != NULL){
::error("TWriteScriptFile::~TWriteScriptFile: Datei %s ist noch offen.\n", this->Filename);
if(fclose(this->File) != 0){
::error("TWriteScriptFile::~TWriteScriptFile: Fehler %d beim Schließen der Datei.\n", errno);
}
}
}
void TWriteScriptFile::open(const char *FileName){
if(this->File != NULL){
::error("TWriteScriptFile::open: Altes Skript ist noch offen.\n");
if(fclose(this->File) != 0){
::error("TWriteScriptFile::open: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
}
this->File = fopen(FileName, "wb");
if(this->File == NULL){
int ErrCode = errno;
::error("TWriteScriptFile: Kann Datei %s nicht anlegen.\n", FileName);
::error("Fehler %d: %s.\n", ErrCode, GetErrorDescription(ErrCode));
throw "Cannot create script-file";
}
strcpy(this->Filename, FileName);
this->Line = 0;
}
void TWriteScriptFile::close(void){
if(this->File == NULL){
::error("TWriteScriptFile::close: Kein Skript offen.\n");
return;
}
if(fclose(this->File) != 0){
::error("TWriteScriptFile::close: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
}
void TWriteScriptFile::error(const char *Text){
if(this->File != NULL){
if(fclose(this->File) != 0){
::error("TWriteScriptFile::error: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
}
snprintf(ErrorString, sizeof(ErrorString),
"error in script-file \"%s\", line %d: %s",
this->Filename, this->Line, Text);
throw ErrorString;
}
void TWriteScriptFile::writeLn(void){
if(this->File == NULL){
::error("TWriteScriptFile::writeLn: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write linefeed";
}
putc('\n', this->File);
}
void TWriteScriptFile::writeText(const char *Text){
if(this->File == NULL){
::error("TWriteScriptFile::writeText: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write text";
}
if(Text == NULL){
::error("TWriteScriptFile::writeText: Text ist NULL.\n");
throw "Cannot write text";
}
for(int i = 0; Text[i] != 0; i += 1){
putc(Text[i], this->File);
}
}
void TWriteScriptFile::writeNumber(int Number){
if(this->File == NULL){
::error("TWriteScriptFile::writeNumber: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write number";
}
char s[32];
snprintf(s, sizeof(s), "%d", Number);
this->writeText(s);
}
void TWriteScriptFile::writeString(const char *Text){
if(this->File == NULL){
::error("TWriteScriptFile::writeString: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write string";
}
if(Text == NULL){
::error("TWriteScriptFile::writeString: Text ist NULL.\n");
throw "Cannot write string";
}
putc('"', this->File);
for(int i = 0; Text[i] != 0; i += 1){
if(Text[i] == '\"' || Text[i] == '\\'){
putc('\\', this->File);
putc(Text[i], this->File);
}else if(Text[i] == '\n'){
putc('\\', this->File);
putc('n', this->File);
}else{
putc(Text[i], this->File);
}
}
putc('"', this->File);
}
void TWriteScriptFile::writeCoordinate(int x ,int y ,int z){
if(this->File == NULL){
::error("TWriteScriptFile::writeCoordinate: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write coordinate";
}
// TODO(fusion): This is weird because we support loading negative coordinates values.
if(x < 0 || y < 0 || z < 0){
::error("TWriteScriptFile::writeCoordinate: Ungültige Koordinaten [%d,%d,%d].\n", x, y, z);
throw "Invalid coordinates";
}
char s[64];
snprintf(s, sizeof(s), "[%u,%u,%u]", x, y, z);
this->writeText(s);
}
void TWriteScriptFile::writeBytesequence(const uint8 *Sequence, int Length){
if(this->File == NULL){
::error("TWriteScriptFile::writeBytesequence: Kein Skript zum Schreiben geöffnet.\n");
throw "Cannot write bytesequence";
}
if(Sequence == NULL){
::error("TWriteScriptFile::writeBytesequence: Sequence ist NULL.\n");
throw "Cannot write bytesequence";
}
if(Length <= 0){
::error("TWriteScriptFile::writeBytesequence: Ungültige Sequenzlänge.\n");
throw "Cannot write bytesequence";
}
for(int i = 0; i < Length; i += 1){
if(i > 0){
putc('-', this->File);
}
char s[32];
snprintf(s, sizeof(s), "%u", Sequence[i]);
this->writeText(s);
}
}
// TReadBinaryFile REGULAR FUNCTIONS
//==============================================================================
TReadBinaryFile::TReadBinaryFile(void){
this->File = NULL;
}
void TReadBinaryFile::open(const char *FileName){
if(this->File != NULL){
this->error("File still open");
}
this->File = fopen(FileName, "rb");
if(this->File == NULL){
snprintf(ErrorString, sizeof(ErrorString),
"Cannot open file %s", FileName);
throw ErrorString;
}
strcpy(this->Filename, FileName);
this->FileSize = -1;
}
void TReadBinaryFile::close(void){
// TODO(fusion): Check if file is NULL?
if(fclose(this->File) != 0){
int ErrCode = errno;
::error("TReadBinaryFile::close: Fehler beim Schließen der Datei.\n");
::error("# Datei: %s, Fehlercode: %d (%s)\n",
this->Filename, ErrCode, GetErrorDescription(ErrCode));
}
this->File = NULL;
}
void TReadBinaryFile::error(const char *Text){
if(this->File != NULL){
if(fclose(this->File) != 0){
::error("TReadBinaryFile::error: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
}
snprintf(ErrorString, sizeof(ErrorString),
"error in binary-file \"%s\": %s.",
this->Filename, Text);
throw ErrorString;
}
int TReadBinaryFile::getPosition(void){
// TODO(fusion): Check if file is NULL?
return (int)ftell(this->File);
}
int TReadBinaryFile::getSize(void){
// TODO(fusion): Check if file is NULL?
int Size = this->FileSize;
if(Size == -1){
long Position = ftell(this->File);
fseek(this->File, 0, SEEK_END);
Size = (int)ftell(this->File);
fseek(this->File, Position, SEEK_SET);
this->FileSize = Size;
}
return Size;
}
void TReadBinaryFile::seek(int Offset){
if(this->File == NULL){
this->error("File not open for seek");
}
if(Offset < 0){
this->error("Negative offset for seek");
}
fseek(this->File, (long)Offset, 0);
}
// TReadBinaryFile VIRTUAL FUNCTIONS
//==============================================================================
uint8 TReadBinaryFile::readByte(void){
uint8 Byte;
int Result = (int)fread(&Byte, 1, 1, this->File);
if(Result != 1){
int ErrCode = errno;
int Position = this->getPosition();
::error("TReadBinaryFile::readByte: Fehler beim Lesen eines Bytes\n");
::error("# Datei: %s, Position: %d, Rückgabewert: %d, Fehlercode: %d (%s)\n",
this->Filename, Position, Result, ErrCode, GetErrorDescription(ErrCode));
// NOTE(fusion): Close file and make a backup, possibly for further inspection.
if(fclose(this->File) != 0){
::error("TReadBinaryFile::readByte: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
SaveFile(this->Filename);
this->error("Error while reading byte");
}
return Byte;
}
void TReadBinaryFile::readBytes(uint8 *Buffer, int Count){
int Result = (int)fread(Buffer, 1, Count, this->File);
if(Result != Count){
int ErrCode = errno;
int Position = this->getPosition();
::error("TReadBinaryFile::readBytes: Fehler beim Lesen von %d Bytes\n", Count);
::error("# Datei: %s, Position %d, Rückgabewert: %d, Fehlercode: %d (%s)\n",
this->Filename, Position, Result, ErrCode, GetErrorDescription(ErrCode));
// NOTE(fusion): Close file and make a backup, possibly for further inspection.
if(fclose(this->File) != 0){
::error("TReadBinaryFile::readBytes: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
SaveFile(this->Filename);
this->error("Error while reading bytes");
}
}
bool TReadBinaryFile::eof(void){
if(this->File == NULL){
this->error("File not open for eof check");
}
return this->getSize() <= this->getPosition();
}
void TReadBinaryFile::skip(int Count){
if(this->File == NULL){
this->error("File not open for skip");
}
this->seek(this->getPosition() + Count);
}
TReadBinaryFile::~TReadBinaryFile(void){
if(this->File != NULL){
::error("TReadBinaryFile::~TReadBinaryFile: Datei %s ist noch offen.\n", this->Filename);
if(fclose(this->File) != 0){
::error("TReadBinaryFile::~TReadBinaryFile: Fehler %d beim Schließen der Datei.\n", errno);
}
}
}
// TWriteBinaryFile
//==============================================================================
TWriteBinaryFile::TWriteBinaryFile(void){
this->File = NULL;
}
void TWriteBinaryFile::open(const char *FileName){
if(this->File != NULL){
this->error("File still open");
}
this->File = fopen(FileName, "wb");
if(this->File == NULL){
int ErrCode = errno;
::error("TWriteBinaryFile::open: Kann Datei %s nicht anlegen.\n", FileName);
::error("Fehler %d: %s.\n", ErrCode, GetErrorDescription(ErrCode));
snprintf(ErrorString, sizeof(ErrorString),
"Cannot create file %s.", FileName);
throw ErrorString;
}
strcpy(this->Filename, FileName);
}
void TWriteBinaryFile::close(void){
// TODO(fusion): Check if file is NULL?
if(fclose(this->File) != 0){
int ErrCode = errno;
::error("TWriteBinaryFile::close: Fehler beim Schließen der Datei.\n");
::error("# Datei: %s, Fehlercode: %d (%s)\n",
this->Filename, ErrCode, GetErrorDescription(ErrCode));
}
this->File = NULL;
}
void TWriteBinaryFile::error(const char *Text){
if(this->File != NULL){
if(fclose(this->File) != 0){
::error("TWriteBinaryFile::error: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
}
snprintf(ErrorString, sizeof(ErrorString),
"error in binary-file \"%s\": %s.",
this->Filename, Text);
throw ErrorString;
}
void TWriteBinaryFile::writeByte(uint8 Byte){
int Result = (int)fwrite(&Byte, 1, 1, this->File);
if(Result != 1){
int ErrCode = errno;
::error("TWriteBinaryFile::writeByte: Fehler beim Schreiben eines Bytes\n");
::error("# Datei: %s, Rückgabewert: %d, Fehlercode: %d (%s)\n",
this->Filename, Result, ErrCode, GetErrorDescription(ErrCode));
// NOTE(fusion): Close file and make a backup, possibly for further inspection.
if(fclose(this->File) != 0){
::error("TWriteBinaryFile::writeByte: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
SaveFile(this->Filename);
this->error("Error while writing byte");
}
}
void TWriteBinaryFile::writeBytes(const uint8 *Buffer, int Count){
int Result = (int)fwrite(Buffer, 1, Count, this->File);
if(Result != Count){
int ErrCode = errno;
::error("TWriteBinaryFile::writeBytes: Fehler beim Schreiben von %d Bytes\n", Count);
::error("# Datei: %s, Rückgabewert: %d, Fehlercode: %d (%s)\n",
this->Filename, Result, ErrCode, GetErrorDescription(ErrCode));
// NOTE(fusion): Close file and make a backup, possibly for further inspection.
if(fclose(this->File) != 0){
::error("TWriteBinaryFile::writeBytes: Fehler %d beim Schließen der Datei.\n", errno);
}
this->File = NULL;
SaveFile(this->Filename);
this->error("Error while writing bytes");
}
}
TWriteBinaryFile::~TWriteBinaryFile(void){
if(this->File != NULL){
::error("TWriteBinaryFile::~TWriteBinaryFile: Datei %s ist noch offen.\n", this->Filename);
if(fclose(this->File) != 0){
::error("TWriteBinaryFile::~TWriteBinaryFile: Fehler %d beim Schließen der Datei.\n", errno);
}
}
}

153
src/game/src/script.hh Normal file
View file

@ -0,0 +1,153 @@
#ifndef TIBIA_SCRIPT_HH_
#define TIBIA_SCRIPT_HH_ 1
#include "common.hh"
#include "enums.hh"
#define MAX_IDENT_LENGTH 30
struct TReadScriptFile {
TReadScriptFile(void);
~TReadScriptFile(void);
void open(const char *FileName);
void close(void);
void error(const char *Text);
void nextToken(void);
char *getIdentifier(void);
int getNumber(void);
char *getString(void);
uint8 *getBytesequence(void);
void getCoordinate(int *x, int *y, int *z);
char getSpecial(void);
char *readIdentifier(void){
this->nextToken();
return this->getIdentifier();
}
int readNumber(void){
this->nextToken();
int Sign = 1;
if(this->Token == SPECIAL && this->Special == '-'){
Sign = -1;
this->nextToken();
}
return Sign * this->getNumber();
}
char *readString(void){
this->nextToken();
return this->getString();
}
uint8 *readBytesequence(void){
this->nextToken();
return this->getBytesequence();
}
void readCoordinate(int *x, int *y, int *z){
this->nextToken();
this->getCoordinate(x, y, z);
}
char readSpecial(void){
this->nextToken();
return this->getSpecial();
}
void readSymbol(char Symbol){
if(this->readSpecial() != Symbol){
this->error("symbol mismatch");
}
}
// DATA
// =================
TOKEN Token;
FILE *File[3];
char Filename[3][4096];
int Line[3];
char String[4000];
int RecursionDepth;
uint8 *Bytes;
int Number;
int CoordX;
int CoordY;
int CoordZ;
char Special;
};
struct TWriteScriptFile {
TWriteScriptFile(void);
~TWriteScriptFile(void);
void open(const char *FileName);
void close(void);
void error(const char *Text);
void writeLn(void);
void writeText(const char *Text);
void writeNumber(int Number);
void writeString(const char *Text);
void writeCoordinate(int x ,int y ,int z);
void writeBytesequence(const uint8 *Sequence, int Length);
// DATA
// =================
FILE *File;
char Filename[4096];
int Line;
};
struct TReadBinaryFile: TReadStream {
TReadBinaryFile(void);
void open(const char *FileName);
void close(void);
void error(const char *Text);
int getPosition(void);
int getSize(void);
void seek(int Offset);
// VIRTUAL FUNCTIONS
// =================
uint8 readByte(void) override;
void readBytes(uint8 *Buffer, int Count) override;
bool eof(void) override;
void skip(int Count) override;
// TODO(fusion): Appended virtual functions. These are not in the base class
// VTABLE which can be problematic if we intend to use polymorphism, although
// that doesn't seem to be case.
virtual ~TReadBinaryFile(void); // VTABLE[8]
// Duplicate destructor that also calls operator delete. // VTABLE[9]
// DATA
// =================
FILE *File;
char Filename[4096];
int FileSize;
};
struct TWriteBinaryFile: TWriteStream {
TWriteBinaryFile(void);
void open(const char *FileName);
void close(void);
void error(const char *Text);
// VIRTUAL FUNCTIONS
// =================
void writeByte(uint8 Byte) override;
void writeBytes(const uint8 *Buffer, int Count) override;
// TODO(fusion): Appended virtual functions. These are not in the base class
// VTABLE which can be problematic if we intend to use polymorphism, although
// that doesn't seem to be case.
virtual ~TWriteBinaryFile(void);
// DATA
// =================
FILE *File;
char Filename[4096];
};
#endif //TIBIA_SCRIPT_HH_

1777
src/game/src/sending.cc Normal file

File diff suppressed because it is too large Load diff

402
src/game/src/shm.cc Normal file
View file

@ -0,0 +1,402 @@
#include "common.hh"
#include "config.hh"
#include "enums.hh"
#include "threads.hh"
#include "writer.hh"
#include <sys/shm.h>
// NOTE(fusion): This looks like an interface to external tools. Looking at the
// `bin` directory this program was in, there are other programs that probably
// use this interface to control certain aspects of the server. My previous
// assumption that each connection was dispatched into its own process may not
// be correct after all.
struct TSharedMemory {
int Command;
char CommandBuffer[256];
uint32 RoundNr;
uint32 ObjectCounter;
uint32 Errors;
int PlayersOnline;
int NewbiesOnline;
int PrintBufferPosition;
char PrintBuffer[200][128];
GAMESTATE GameState;
pid_t GameProcessID;
pid_t GameThreadID;
};
static TSharedMemory *SHM = NULL;
static bool IsGameServer = false;
static bool VerboseOutput = false;
void StartGame(void){
if(SHM != NULL){
if(SHM->GameState == GAME_STARTING){
SHM->GameState = GAME_RUNNING;
}
}else{
error("StartGame: SharedMemory existiert nicht.\n");
}
}
void CloseGame(void){
if(SHM != NULL){
if(SHM->GameState == GAME_RUNNING){
SHM->GameState = GAME_CLOSING;
}
}else{
error("CloseGame: SharedMemory existiert nicht.\n");
}
}
void EndGame(void){
if(SHM != NULL){
SHM->GameState = GAME_ENDING;
}else{
error("EndGame: SharedMemory existiert nicht.\n");
}
}
bool LoginAllowed(void){
bool Result = false;
if(SHM != NULL){
Result = SHM->GameState == GAME_RUNNING;
}else{
error("IsLoginAllowed: SharedMemory existiert nicht.\n");
}
return Result;
}
bool GameRunning(void){
bool Result = false;
if(SHM != NULL){
Result = SHM->GameState == GAME_STARTING
|| SHM->GameState == GAME_RUNNING
|| SHM->GameState == GAME_CLOSING;
}else{
error("GameRunning: SharedMemory existiert nicht.\n");
}
return Result;
}
bool GameStarting(void){
bool Result = false;
if(SHM != NULL){
Result = SHM->GameState == GAME_STARTING;
}else{
error("GameStarting: SharedMemory existiert nicht.\n");
}
return Result;
}
bool GameEnding(void){
bool Result = false;
if(SHM != NULL){
Result = SHM->GameState == GAME_CLOSING
|| SHM->GameState == GAME_ENDING;
}else{
error("GameEnding: SharedMemory existiert nicht.\n");
}
return Result;
}
pid_t GetGameProcessID(void){
pid_t Pid = 0;
if(SHM != NULL){
Pid = SHM->GameProcessID;
}
return Pid;
}
pid_t GetGameThreadID(void){
pid_t Pid = 0;
if(SHM != NULL){
Pid = SHM->GameThreadID;
}
return Pid;
}
static void ErrorHandler(const char *Text){
if(VerboseOutput){
printf("%s", Text);
}
if(SHM != NULL){
SHM->Errors += 1;
if(SHM->Errors <= 0x8000){
Log("error", "%s", Text);
if(SHM->Errors == 0x8000){
Log("error", "Zu viele Fehler. Keine weitere Protokollierung.\n");
}
}
}
}
static void PrintHandler(int Level, const char *Text){
static Semaphore LogfileMutex(1);
if(Level > DebugLevel){
return;
}
if(VerboseOutput){
printf("%s", Text);
}
if(SHM != NULL){
// TODO(fusion): Does it even make sense to have this Semaphore here?
// It controls writes to the print buffer but reads outside this scope
// may be partial. But then, it doesn't seem like it is read anywhere
// else. Perhaps some external monitor tool, in which case do we even
// print from multiple threads?
LogfileMutex.down();
int Line = SHM->PrintBufferPosition;
char *Buffer = SHM->PrintBuffer[Line];
// TODO(fusion): Ughh...
strncpy(Buffer, Text, sizeof(SHM->PrintBuffer[0]) - 1);
Buffer[sizeof(SHM->PrintBuffer[0]) - 2] = 0;
if(Buffer[0] != 0){
usize TextLen = strlen(Buffer);
if(Buffer[TextLen - 1] != '\n'){
strcat(Buffer, "\n");
}
}
SHM->PrintBufferPosition = (Line + 1) % NARRAY(SHM->PrintBuffer);
LogfileMutex.up();
}
}
int GetPrintlogPosition(void){
int Result = 0;
if(SHM != NULL){
Result = SHM->PrintBufferPosition;
}
return Result;
}
char *GetPrintlogLine(int Line){
char *Result = NULL;
if(SHM != NULL && Line >= 0 && Line < NARRAY(SHM->PrintBuffer)){
Result = SHM->PrintBuffer[Line];
}
return Result;
}
void IncrementObjectCounter(void){
if(SHM != NULL){
SHM->ObjectCounter += 1;
}
}
void DecrementObjectCounter(void){
if(SHM != NULL){
SHM->ObjectCounter -= 1;
}
}
uint32 GetObjectCounter(void){
uint32 ObjectCounter = 0;
if(SHM != NULL){
ObjectCounter = SHM->ObjectCounter;
}
return ObjectCounter;
}
void IncrementPlayersOnline(void){
if(SHM != NULL){
SHM->PlayersOnline += 1;
}
}
void DecrementPlayersOnline(void){
if(SHM != NULL){
SHM->PlayersOnline -= 1;
}
}
int GetPlayersOnline(void){
int PlayersOnline = 0;
if(SHM != NULL){
PlayersOnline = SHM->PlayersOnline;
}
return PlayersOnline;
}
void IncrementNewbiesOnline(void){
if(SHM != NULL){
SHM->NewbiesOnline += 1;
}
}
void DecrementNewbiesOnline(void){
if(SHM != NULL){
SHM->NewbiesOnline -= 1;
}
}
int GetNewbiesOnline(void){
int NewbiesOnline = 0;
if(SHM != NULL){
NewbiesOnline = SHM->NewbiesOnline;
}
return NewbiesOnline;
}
void SetRoundNr(uint32 RoundNr){
if(SHM != NULL){
SHM->RoundNr = RoundNr;
}
}
uint32 GetRoundNr(void){
uint32 RoundNr = 0;
if(SHM != NULL){
RoundNr = SHM->RoundNr;
}
return RoundNr;
}
void SetCommand(int Command, char *Text){
if(SHM != NULL){
SHM->Command = Command;
if(Text == NULL){
SHM->CommandBuffer[0] = 0;
}else{
strncpy(SHM->CommandBuffer, Text, sizeof(SHM->CommandBuffer));
SHM->CommandBuffer[sizeof(SHM->CommandBuffer) - 1] = 0;
}
}
}
int GetCommand(void){
int Command = 0;
if(SHM != NULL){
Command = SHM->Command;
}
return Command;
}
char *GetCommandBuffer(void){
char *Buffer = NULL;
if(SHM != NULL && SHM->Command != 0){
Buffer = SHM->CommandBuffer;
}
return Buffer;
}
static bool DeleteSHM(void){
int SHMID = shmget(SHMKey, 0, 0);
if(SHMID == -1){
if(VerboseOutput){
puts("DeleteSHM: SharedMemory existiert nicht.");
}
return true;
}
if(shmctl(SHMID, IPC_RMID, NULL) == -1){
if(VerboseOutput){
// TODO(fusion): Include `errno` in the error message?
puts("DeleteSHM: Kann SharedMemory nicht löschen.");
}
return false;
}
return true;
}
static void CreateSHM(void){
bool Deleted = false;
while(true){
int SHMID = shmget(SHMKey, sizeof(TSharedMemory), IPC_CREAT | IPC_EXCL | 0777);
if(SHMID != -1){
return;
}
if(errno != EEXIST || Deleted){
if(VerboseOutput){
printf("CreateSHM: Kann SharedMemory nicht anlegen (Fehler %d).\n", errno);
}
throw "Cannot create SharedMemory";
}
if(!DeleteSHM()){
throw "Cannot delete SharedMemory";
}
Deleted = true;
}
}
static void AttachSHM(void){
int SHMID = shmget(SHMKey, sizeof(TSharedMemory), 0);
if(SHMID == -1){
if(VerboseOutput){
// TODO(fusion): Include `errno` in the error message?
puts("AttachSHM: Kann SharedMemory nicht fassen.");
}
SHM = NULL;
throw "Cannot get SharedMemory";
}
SHM = (TSharedMemory*)shmat(SHMID, NULL, 0);
if(SHM == (void*)-1){
if(VerboseOutput){
puts("AttachSHM: Kann SharedMemory nicht anbinden.");
}
SHM = NULL;
throw "Cannot attach SharedMemory";
}
}
static void DetachSHM(void){
if(SHM != NULL){
if(shmdt(SHM) == -1 && VerboseOutput){
puts("DetachSHM: Kann SharedMemory nicht löschen.");
}
SHM = NULL;
}
}
void InitSHM(bool Verbose){
IsGameServer = true;
VerboseOutput = Verbose;
CreateSHM();
AttachSHM();
SetErrorFunction(ErrorHandler);
SetPrintFunction(PrintHandler);
// NOTE(fusion): `CreateSHM` ensures a new shared memory segment is created
// and it should be always zero initialized as per the manual. Nevertheless
// the decompiled version was also clearing SHM, probably just in case.
memset(SHM, 0, sizeof(TSharedMemory));
strncpy(SHM->PrintBuffer[0],
"SHM initialized. System printing is working!\n",
sizeof(SHM->PrintBuffer[0]));
SHM->PrintBuffer[0][sizeof(SHM->PrintBuffer[0]) - 1] = 0;
SHM->PrintBufferPosition = 1;
SHM->GameState = GAME_STARTING;
SHM->GameProcessID = getpid();
SHM->GameThreadID = gettid();
}
void ExitSHM(void){
SetErrorFunction(NULL);
SetPrintFunction(NULL);
DetachSHM();
DeleteSHM();
}
void InitSHMExtern(bool Verbose){
VerboseOutput = Verbose;
AttachSHM();
}
void ExitSHMExtern(void){
DetachSHM();
}

600
src/game/src/strings.cc Normal file
View file

@ -0,0 +1,600 @@
#include "common.hh"
#include "containers.hh"
struct TStaticStringTableBlock {
int TotalTextLength;
char Text[65536];
};
struct TDynamicStringTableBlock {
int FreeEntries;
int TotalTextLength;
bool Dirty;
uint8 EntryType[256];
uint16 StringOffset[256];
char Text[32768];
};
constexpr int StaticBlockSize = NARRAY(TStaticStringTableBlock::Text);
constexpr int DynamicBlockSize = NARRAY(TDynamicStringTableBlock::Text);
constexpr int DynamicBlockEntries = NARRAY(TDynamicStringTableBlock::EntryType);
enum : uint8 {
DYNAMIC_STRING_FREE = 0,
DYNAMIC_STRING_ALLOCATED = 1,
DYNAMIC_STRING_DELETED = 2,
};
static list<TStaticStringTableBlock> StaticStringTable;
static list<TDynamicStringTableBlock> DynamicStringTable;
const char *AddStaticString(const char *String){
int StringLen = (int)strlen(String);
if((StringLen + 1) > StaticBlockSize){
error("AddStaticString: String zu lang (%d).\n", StringLen);
return NULL;
}
if(StringLen == 0){
return "";
}
listnode<TStaticStringTableBlock> *Node = StaticStringTable.firstNode;
while(Node != NULL){
if((Node->data.TotalTextLength + StringLen + 1) <= StaticBlockSize){
break;
}
Node = Node->next;
}
if(Node == NULL){
Node = StaticStringTable.append();
memset(&Node->data, 0, sizeof(TStaticStringTableBlock));
}
TStaticStringTableBlock *Block = &Node->data;
char *Result = &Block->Text[Block->TotalTextLength];
memcpy(Result, String, StringLen + 1);
Block->TotalTextLength += StringLen + 1;
return Result;
}
uint32 AddDynamicString(const char *String){
int StringLen = (String ? (int)strlen(String) : 0);
if(StringLen == 0){
return 0;
}
if((StringLen + 1) > DynamicBlockSize){
error("AddDynamicString: String zu lang (%d)\n", StringLen);
return 0;
}
int BlockIndex = 0;
listnode<TDynamicStringTableBlock> *Node = DynamicStringTable.firstNode;
while(Node != NULL){
if(Node->data.FreeEntries > 0){
if((Node->data.TotalTextLength + StringLen + 1) <= DynamicBlockSize){
break;
}
}
Node = Node->next;
BlockIndex += 1;
}
if(Node == NULL){
Node = DynamicStringTable.append();
memset(&Node->data, 0, sizeof(TDynamicStringTableBlock));
Node->data.FreeEntries = DynamicBlockEntries;
}
TDynamicStringTableBlock *Block = &Node->data;
int EntryIndex = -1;
for(int i = 0; i < DynamicBlockEntries; i += 1){
if(Block->EntryType[i] == DYNAMIC_STRING_FREE){
EntryIndex = i;
break;
}
}
if(EntryIndex == -1){
error("AddDynamicString: Keinen freien Platz gefunden.\n");
return 0;
}
int StringOffset = Block->TotalTextLength;
Block->FreeEntries -= 1;
Block->TotalTextLength += StringLen + 1;
Block->EntryType[EntryIndex] = DYNAMIC_STRING_ALLOCATED;
Block->StringOffset[EntryIndex] = (uint16)StringOffset;
memcpy(&Block->Text[StringOffset], String, StringLen + 1);
return (uint32)(1 + BlockIndex * DynamicBlockEntries + EntryIndex);
}
const char *GetDynamicString(uint32 Number){
if(Number == 0){
return NULL;
}
int BlockIndex = (int)(Number - 1) / DynamicBlockEntries;
int EntryIndex = (int)(Number - 1) % DynamicBlockEntries;
listnode<TDynamicStringTableBlock> *Node = DynamicStringTable.firstNode;
while(BlockIndex > 0 && Node != NULL){
Node = Node->next;
BlockIndex -= 1;
}
if(Node == NULL){
error("GetDynamicString: Block für String %u existiert nicht\n", Number);
return NULL;
}
TDynamicStringTableBlock *Block = &Node->data;
if(Block->EntryType[EntryIndex] != DYNAMIC_STRING_ALLOCATED){
error("GetDynamicString: Eintrag für String %u existiert nicht\n", Number);
return NULL;
}
int StringOffset = (int)Block->StringOffset[EntryIndex];
return &Block->Text[StringOffset];
}
void DeleteDynamicString(uint32 Number){
if(Number == 0){
return;
}
int BlockIndex = (int)(Number - 1) / DynamicBlockEntries;
int EntryIndex = (int)(Number - 1) % DynamicBlockEntries;
listnode<TDynamicStringTableBlock> *Node = DynamicStringTable.firstNode;
while(BlockIndex > 0 && Node != NULL){
Node = Node->next;
BlockIndex -= 1;
}
if(Node == NULL){
error("DeleteDynamicString: Block für String %u existiert nicht\n", Number);
return;
}
TDynamicStringTableBlock *Block = &Node->data;
if(Block->EntryType[EntryIndex] != DYNAMIC_STRING_ALLOCATED){
error("DeleteDynamicString: Eintrag für String %u existiert nicht\n", Number);
return;
}
Block->EntryType[EntryIndex] = DYNAMIC_STRING_DELETED;
Block->Dirty = true;
}
void CleanupDynamicStrings(void){
// IMPORTANT(fusion): The way we manage dynamic strings also mean pointers
// returned from `GetDynamicString` aren't stable.
for(listnode<TDynamicStringTableBlock> *Node = DynamicStringTable.firstNode;
Node != NULL;
Node = Node->next){
TDynamicStringTableBlock *Block = &Node->data;
if(!Block->Dirty){
continue;
}
for(int i = 0; i < DynamicBlockEntries; i += 1){
if(Block->EntryType[i] == DYNAMIC_STRING_DELETED){
int StringOffset = Block->StringOffset[i];
char *String = &Block->Text[StringOffset];
int StringSize = (int)strlen(String) + 1;
int StringEnd = StringOffset + StringSize;
Block->EntryType[i] = DYNAMIC_STRING_FREE;
if(StringEnd > DynamicBlockSize){
error("CleanupDynamicStrings: Stringende fehlt\n");
continue;
}
if(StringEnd < DynamicBlockSize){
memmove(String, String + StringSize, DynamicBlockSize - StringEnd);
}
for(int j = 0; j < DynamicBlockEntries; j += 1){
if(Block->EntryType[j] != DYNAMIC_STRING_FREE
&& Block->StringOffset[j] > StringOffset){
ASSERT(Block->StringOffset[j] >= StringEnd);
Block->StringOffset[j] -= StringSize;
}
}
}
}
}
}
void InitStrings(void){
// no-op
}
void ExitStrings(void){
// no-op
}
// String Utility
// =============================================================================
// TODO(fusion): I'm not sure why we have these separate from the other string
// utility defined in `utils.cc`. We should probably just move them all here.
bool IsCountable(const char *s){
if(strncmp(s, "some ", 5) == 0){
return false;
}
return strncmp(s, "a ", 2) == 0
|| strncmp(s, "an ", 3) == 0;
}
const char *Plural(const char *s, int Count){
static char ObjectNameString[50];
ObjectNameString[0] = 0;
if(s == NULL){
error("Plural: Übergebener String existiert nicht.\n");
return ObjectNameString;
}
strcpy(ObjectNameString, s);
if(Count == 1 || !IsCountable(ObjectNameString)){
return ObjectNameString;
}
// NOTE(fusion): `IsCountable` will only return true for `a XXXX` or `an XXXX`.
if(ObjectNameString[1] == 'n'){
memmove(&ObjectNameString[0],
&ObjectNameString[3],
sizeof(ObjectNameString) - 3);
}else{
memmove(&ObjectNameString[0],
&ObjectNameString[2],
sizeof(ObjectNameString) - 2);
}
if(Count < 0){
return ObjectNameString;
}
char Help[sizeof(ObjectNameString)];
if(char *Suffix = strstr(ObjectNameString, " of ")){
strcpy(Help, Suffix);
Suffix[0] = 0;
}else{
Help[0] = 0;
}
// TODO(fusion): This method for pluralization is limited and incomplete but
// it probably works with the current set of object names.
if(strcmp(ObjectNameString, "knife") == 0){
strcpy(ObjectNameString, "knives");
}else if(strcmp(ObjectNameString, "throwing knife") == 0){
strcpy(ObjectNameString, "throwing knives");
}else if(strcmp(ObjectNameString, "orc spearman") == 0){
strcpy(ObjectNameString, "orc spearmen");
}else if(strcmp(ObjectNameString, "deer") != 0
&& strcmp(ObjectNameString, "dead deer") != 0
&& strcmp(ObjectNameString, "sheep") != 0
&& strcmp(ObjectNameString, "black sheep") != 0
&& strcmp(ObjectNameString, "fish") != 0){
int NameLen = (int)strlen(ObjectNameString);
if(NameLen > 0){
int Last = toLower(ObjectNameString[NameLen - 1]);
int Prev = 0;
if(NameLen > 1){
Prev = toLower(ObjectNameString[NameLen - 2]);
}
if(Last == 's' || Last == 'x'
|| (Last == 'h' && (Prev == 's' || Prev == 'c'))){
strcat(ObjectNameString, "es");
}else if(Last == 'y' && Prev != 'a' && Prev != 'e'
&& Prev != 'i' && Prev != 'o' && Prev != 'u'){
ObjectNameString[NameLen - 1] = 'i';
strcat(ObjectNameString, "es");
}else if(Last == 'f' && Prev == 'l'){
ObjectNameString[NameLen - 1] = 'v';
strcat(ObjectNameString, "es");
}else if(Last == 'o'){
strcat(ObjectNameString, "es");
}else{
strcat(ObjectNameString, "s");
}
}
}
strcat(ObjectNameString, Help);
if(Count != 0){
strcpy(Help, ObjectNameString);
snprintf(ObjectNameString, sizeof(ObjectNameString), "%d %s", Count, Help);
}
return ObjectNameString;
}
const char *SearchForWord(const char *Pattern, const char *Text){
if(Pattern == NULL || Pattern[0] == 0){
error("SearchForWord: Übergebenes Suchwort existiert nicht.\n");
return NULL;
}
if(Text == NULL){
error("SearchForWord: Übergebener Text existiert nicht.\n");
return NULL;
}
int PatternLength = (int)strlen(Pattern);
bool WholeWord = false;
if(Pattern[PatternLength - 1] == '$'){
PatternLength -= 1;
WholeWord = true;
}
bool WordStart = true;
const char *Match = NULL;
for(int i = 0; Text[i] != 0; i += 1){
// TODO(fusion): The original function would only check for spaces to
// determine the beginning of a word which can be problematic for sentences
// with punctuation.
//if(isSpace(Text[i])){
if(!isAlpha(Text[i]) && !isDigit(Text[i])){
WordStart = true;
}else if(WordStart){
int j = 0;
while(j < PatternLength){
if(toLower(Pattern[j]) != toLower(Text[i + j])){
break;
}
j += 1;
}
if(j == PatternLength){
if(!WholeWord || (!isAlpha(Text[i + j]) && !isDigit(Text[i + j]))){
Match = &Text[i];
break;
}
}
WordStart = false;
}
}
return Match;
}
const char *SearchForNumber(int Count, const char *Text){
if(Count < 1){
error("SearchForNumber: Illegale Suchnummer %d.\n", Count);
return NULL;
}
if(Text == NULL){
error("SearchForNumber: Übergebener Text existiert nicht.\n");
return NULL;
}
bool WordStart = true;
const char *Match = NULL;
for(int i = 0; Text[i] != 0; i += 1){
// TODO(fusion): Same as `SearchForWord`.
//if(isSpace(Text[i])){
if(!isAlpha(Text[i]) && !isDigit(Text[i])){
WordStart = true;
}else if(WordStart){
int j = 0;
while(isDigit(Text[i + j])){
j += 1;
}
// TODO(fusion): Same as `SearchForWord`.
//if(j > 0 && (Text[i + j] == 0 || isSpace(Text[i + j]))){
if(j > 0 && !isAlpha(Text[i + j])){
Count -= 1;
if(Count == 0){
Match = &Text[i];
break;
}
}
WordStart = false;
}
}
return Match;
}
bool MatchString(const char *Pattern, const char *String){
if(Pattern == NULL){
error("MatchString: Pattern ist NULL.\n");
return false;
}
if(String == NULL){
error("MatchString: String ist NULL.\n");
return false;
}
// NOTE(fusion): The original function was allocating an integer table on
// the stack, with dimensions (StringLength + 1) x (PatternLength + 1) to
// compute the edit distance. This made the decompiled version difficult
// to read and could potentially blow up the stack for large inputs.
// We'll use a fixed buffer instead, that will store the distances for the
// last and current table rows which is all is needed to compute the same
// edit distance.
int StringLength = (int)strlen(String);
int PatternLength = (int)strlen(Pattern);
constexpr int MaxStringLength = 255;
if(StringLength > MaxStringLength){
error("MatchString: String is too large (Length = %d, MaxLength = %d)\n",
StringLength, MaxStringLength);
return false;
}
int DistanceBuffer[2 * (MaxStringLength + 1)] = {};
int *PrevRow = &DistanceBuffer[0];
int *CurRow = &DistanceBuffer[StringLength + 1];
for(int i = 0; i < (StringLength + 1); i += 1){
PrevRow[i] = i;
}
for(int i = 0; i < PatternLength; i += 1){
int Ins = (Pattern[i] != '*');
int Del = (Pattern[i] != '*');
CurRow[0] = PrevRow[0] + Del;
for(int j = 0; j < StringLength; j += 1){
int Edit = (Pattern[i] != '?'
&& toLower(Pattern[i]) != toLower(String[j]));
int Min = PrevRow[j + 1] + Ins;
if(Min > (PrevRow[j] + Edit)){
Min = PrevRow[j] + Edit;
}
if(Min > (CurRow[j] + Del)){
Min = CurRow[j] + Del;
}
CurRow[j + 1] = Min;
}
std::swap(PrevRow, CurRow);
}
return PrevRow[StringLength] == 0;
}
// TODO(fusion): This function is unsafe like `strcpy`.
void AddSlashes(char *Destination, const char *Source){
if(Source == NULL){
error("AddSlashes: Source ist NULL.\n");
return;
}
if(Destination == NULL){
error("AddSlashes: Destination ist NULL.\n");
return;
}
int ReadIndex = 0;
int WriteIndex = 0;
while(Source[ReadIndex] != 0){
if(Source[ReadIndex] == '"' || Source[ReadIndex] == '#'
|| Source[ReadIndex] == '\'' || Source[ReadIndex] == '\\'){
Destination[WriteIndex] = '\\';
WriteIndex += 1;
}
Destination[WriteIndex] = Source[ReadIndex];
WriteIndex += 1;
ReadIndex += 1;
}
Destination[WriteIndex] = 0;
WriteIndex += 1;
}
void Trim(char *Text){
if(Text == NULL){
error("Trim: Text ist NULL.\n");
return;
}
// NOTE(fusion): `Start` is inclusive.
int Start = 0;
while(Text[Start] != 0 && isSpace(Text[Start])){
Start += 1;
}
int OldLength = Start;
while(Text[OldLength] != 0){
OldLength += 1;
}
if(Start < OldLength){
// NOTE(fusion): `End` is inclusive.
int End = OldLength - 1;
while(End > Start && isSpace(Text[End])){
End -= 1;
}
int NewLength = End - Start + 1;
memmove(&Text[0], &Text[Start], NewLength);
Text[NewLength] = 0;
}else{
Text[0] = 0;
}
}
// TODO(fusion): This is a copy of the function above, except that we write to
// `Destination` instead of modifying the original string. It is unsafe as `strcpy`.
void Trim(char *Destination, const char *Source){
if(Source == NULL){
error("Trim: Source ist NULL.\n");
return;
}
if(Destination == NULL){
error("Trim: Destination ist NULL.\n");
return;
}
int Start = 0;
while(Source[Start] != 0 && isSpace(Source[Start])){
Start += 1;
}
int OldLength = Start;
while(Source[OldLength] != 0){
OldLength += 1;
}
if(Start < OldLength){
// NOTE(fusion): `End` is inclusive.
int End = OldLength - 1;
while(End > Start && isSpace(Source[End])){
End -= 1;
}
int NewLength = End - Start + 1;
memcpy(&Destination[0], &Source[Start], NewLength);
Destination[NewLength] = 0;
}else{
Destination[0] = 0;
}
}
void ChangeWildcards(char *String){
if(String == NULL){
error("ChangeWildcards: String ist NULL.\n");
return;
}
for(int i = 0; String[i] != 0; i += 1){
if(String[i] == '*'){
String[i] = '%';
}else if(String[i] == '?'){
String[i] = '_';
}
}
}
char *Capitals(char *Text){
bool WordStart = true;
for(int i = 0; Text[i] != 0; i += 1){
// TODO(fusion): The original function wouldn't consider digits which
// I'd argue is a mistake if there is a number prefixing a word.
if(!isAlpha(Text[i]) && !isDigit(Text[i])){
WordStart = true;
}else if(WordStart){
if(isAlpha(Text[i])){
Text[i] = toUpper(Text[i]);
}
WordStart = false;
}
}
return Text;
}

170
src/game/src/threads.cc Normal file
View file

@ -0,0 +1,170 @@
#include "threads.hh"
struct TThreadStarter {
ThreadFunction *Function;
void *Argument;
bool Detach;
};
static void *ThreadStarter(void *Pointer){
TThreadStarter *Starter = (TThreadStarter*)Pointer;
ThreadFunction *Function = Starter->Function;
void *Argument = Starter->Argument;
bool Detach = Starter->Detach;
delete Starter;
int Result = Function(Argument);
// TODO(fusion): Just store the integer as a pointer and avoid allocation?
int *ResultPointer = NULL;
if(!Detach){
ResultPointer = new int;
*ResultPointer = Result;
}
pthread_exit(ResultPointer);
return NULL; // Unreachable.
}
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, bool Detach){
TThreadStarter *Starter = new TThreadStarter;
Starter->Function = Function;
Starter->Argument = Argument;
Starter->Detach = Detach;
pthread_t Handle;
int err = pthread_create(&Handle, NULL, ThreadStarter, Starter);
if(err != 0){
error("StartThread: Kann Thread nicht anlegen; Fehlercode %d.\n", err);
return INVALID_THREAD_HANDLE;
}
if(Detach){
pthread_detach(Handle);
}
return (ThreadHandle)Handle;
}
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, size_t StackSize, bool Detach){
TThreadStarter *Starter = new TThreadStarter;
Starter->Function = Function;
Starter->Argument = Argument;
Starter->Detach = Detach;
pthread_t Handle;
pthread_attr_t Attr;
pthread_attr_init(&Attr);
pthread_attr_setstacksize(&Attr, StackSize);
int err = pthread_create(&Handle, &Attr, ThreadStarter, Starter);
pthread_attr_destroy(&Attr);
if(err != 0){
error("StartThread: Kann Thread nicht anlegen; Fehlercode %d.\n", err);
return INVALID_THREAD_HANDLE;
}
if(Detach){
pthread_detach(Handle);
}
return (ThreadHandle)Handle;
}
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, void *Stack, size_t StackSize, bool Detach){
TThreadStarter *Starter = new TThreadStarter;
Starter->Function = Function;
Starter->Argument = Argument;
Starter->Detach = Detach;
pthread_t Handle;
pthread_attr_t Attr;
pthread_attr_init(&Attr);
pthread_attr_setstack(&Attr, Stack, StackSize);
int err = pthread_create(&Handle, &Attr, ThreadStarter, Starter);
pthread_attr_destroy(&Attr);
if(err != 0){
error("StartThread: Kann Thread nicht anlegen; Fehlercode %d.\n", err);
return INVALID_THREAD_HANDLE;
}
if(Detach){
pthread_detach(Handle);
}
return (ThreadHandle)Handle;
}
int JoinThread(ThreadHandle Handle){
int Result = 0;
int *ResultPointer;
pthread_join((pthread_t)Handle, (void**)&ResultPointer);
if(ResultPointer != NULL){
Result = *ResultPointer;
delete ResultPointer;
}
return Result;
}
void DelayThread(int Seconds, int MicroSeconds){
if(Seconds == 0 && MicroSeconds == 0){
sched_yield();
}else if(MicroSeconds == 0){
sleep(Seconds);
}else{
usleep(MicroSeconds + Seconds * 1000000);
}
}
Semaphore::Semaphore(int Value){
this->value = Value;
// TODO(fusion): These should probably be non-recoverable errors.
if(pthread_mutex_init(&this->mutex, NULL) != 0){
error("Semaphore::Semaphore: Kann Mutex nicht einrichten.\n");
}
if(pthread_cond_init(&this->condition, NULL) != 0){
error("Semaphore::Semaphore: Kann Wartebedingung nicht einrichten.\n");
}
}
Semaphore::~Semaphore(void){
// IMPORTANT(fusion): Due to how initialization is rolled out, `exit` may be
// called after threads are spawned but before `ExitAll` is registered as an
// exit handler. This means such threads may still be running or left global
// semaphores in an inconsistent state if abruptly terminated. Either way,
// they are still considered "in use".
// In this case, calling `destroy` on either mutex or condition variable is
// undefined behaviour as per the manual but the actual implementation would
// fail on `mutex_destroy` with `EBUSY` and hang on `cond_destroy`.
// The temporary solution is to check the result from `mutex_destroy` before
// attempting to call `cond_destroy` to avoid hanging at exit.
int ErrorCode;
if((ErrorCode = pthread_mutex_destroy(&this->mutex)) != 0){
error("Semaphore::~Semaphore: Kann Mutex nicht freigeben: (%d) %s.\n",
ErrorCode, GetErrorDescription(ErrorCode));
}else if((ErrorCode = pthread_cond_destroy(&this->condition)) != 0){
error("Semaphore::~Semaphore: Kann Wartebedingung nicht freigeben: (%d) %s.\n",
ErrorCode, GetErrorDescription(ErrorCode));
}
}
void Semaphore::down(void){
pthread_mutex_lock(&this->mutex);
while(this->value <= 0){ // TODO(fusion): Make sure this is always a load operation?
pthread_cond_wait(&this->condition, &this->mutex);
}
this->value -= 1;
pthread_mutex_unlock(&this->mutex);
}
void Semaphore::up(void){
pthread_mutex_lock(&this->mutex);
this->value += 1;
pthread_mutex_unlock(&this->mutex);
pthread_cond_signal(&this->condition);
}

33
src/game/src/threads.hh Normal file
View file

@ -0,0 +1,33 @@
#ifndef TIBIA_THREADS_HH_
#define TIBIA_THREADS_HH_ 1
#include "common.hh"
#include <pthread.h>
typedef pthread_t ThreadHandle;
typedef int (ThreadFunction)(void *);
// TODO(fusion): Probably have another way to tell whether the thread was
// successfully spawned or not?
constexpr ThreadHandle INVALID_THREAD_HANDLE = 0;
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, bool Detach);
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, size_t StackSize, bool Detach);
ThreadHandle StartThread(ThreadFunction *Function, void *Argument, void *Stack, size_t StackSize, bool Detach);
int JoinThread(ThreadHandle Handle);
void DelayThread(int Seconds, int MicroSeconds);
struct Semaphore {
Semaphore(int Value);
~Semaphore(void);
void up(void);
void down(void);
// DATA
// =================
int value;
pthread_mutex_t mutex;
pthread_cond_t condition;
};
#endif //TIBIA_THREADS_HH_

110
src/game/src/time.cc Normal file
View file

@ -0,0 +1,110 @@
#include "common.hh"
// IMPORTANT(fusion): `RoundNr` is just the number of seconds since startup which
// is why `GetRoundAtTime` and `GetRoundForNextMinute` straight up uses it as
// seconds. It is incremented every 1 second inside `AdvanceGame`.
uint32 RoundNr = 0;
uint32 ServerMilliseconds = 0;
struct tm GetLocalTimeTM(time_t t){
struct tm result;
#if COMPILER_MSVC
localtime_s(&result, &t);
#else
localtime_r(&t, &result);
#endif
return result;
}
int64 GetClockMonotonicMS(void){
#if OS_WINDOWS
LARGE_INTEGER Counter, Frequency;
QueryPerformanceCounter(&Counter);
QueryPerformanceFrequency(&Frequency);
return (int64)((Counter.QuadPart * 1000) / Frequency.QuadPart);
#else
// NOTE(fusion): The coarse monotonic clock has a larger resolution but is
// supposed to be faster, even avoiding system calls in some cases. It should
// be fine for millisecond precision which is what we're using.
struct timespec Time;
clock_gettime(CLOCK_MONOTONIC_COARSE, &Time);
return ((int64)Time.tv_sec * 1000)
+ ((int64)Time.tv_nsec / 1000000);
#endif
}
void GetRealTime(int *Hour, int *Minute){
struct tm LocalTime = GetLocalTimeTM(time(NULL));
*Hour = LocalTime.tm_hour;
*Minute = LocalTime.tm_min;
}
void GetTime(int *Hour, int *Minute){
// NOTE(fusion): This maps each real time hour to a game time day.
struct tm LocalTime = GetLocalTimeTM(time(NULL));
int Time = LocalTime.tm_sec + LocalTime.tm_min * 60;
*Hour = (Time / 150);
*Minute = (Time % 150) * 2 / 5;
}
void GetDate(int *Year, int *Cycle, int *Day){
// NOTE(fusion): This maps each real time week to a game time year.
time_t RealTime = time(NULL);
struct tm LocalTime = GetLocalTimeTM(RealTime);
*Year = (int)(((RealTime / 86400) + 4) / 7);
*Cycle = LocalTime.tm_wday;
*Day = LocalTime.tm_hour;
}
void GetAmbiente(int *Brightness, int *Color){
int Hour, Minute;
GetTime(&Hour, &Minute);
int Time = Minute + Hour * 60;
if(Time < 60){
*Brightness = 0x33;
*Color = 0xD7;
}else if(Time < 120){
*Brightness = 0x66;
*Color = 0xD7;
}else if(Time < 180){
*Brightness = 0x99;
*Color = 0xAD;
}else if(Time < 240){
*Brightness = 0xCC;
*Color = 0xAD;
}else if(Time <= 1200){
*Brightness = 0xFF;
*Color = 0xD7;
}else if(Time <= 1260){
*Brightness = 0xCC;
*Color = 0xD0;
}else if(Time <= 1320){
*Brightness = 0x99;
*Color = 0xD0;
}else if(Time <= 1380){
*Brightness = 0x66;
*Color = 0xD7;
}else{
*Brightness = 0x33;
*Color = 0xD7;
}
}
uint32 GetRoundAtTime(int Hour, int Minute){
struct tm LocalTime = GetLocalTimeTM(time(NULL));
int SecondsToTime = (Hour - LocalTime.tm_hour) * 3600
+ (Minute - LocalTime.tm_min) * 60
+ (0 - LocalTime.tm_sec);
if(SecondsToTime < 0){
SecondsToTime += 86400;
}
return SecondsToTime + RoundNr;
}
uint32 GetRoundForNextMinute(void){
struct tm LocalTime = GetLocalTimeTM(time(NULL));
int SecondsToNextMinute = 60 - LocalTime.tm_sec;
return SecondsToNextMinute + RoundNr + 30;
}

573
src/game/src/utils.cc Normal file
View file

@ -0,0 +1,573 @@
#include "common.hh"
#include <signal.h>
#include <sys/stat.h>
static TErrorFunction *ErrorFunction;
static TPrintFunction *PrintFunction;
static char StandardLogFile[4096];
void SetErrorFunction(TErrorFunction *Function){
ErrorFunction = Function;
}
void SetPrintFunction(TPrintFunction *Function){
PrintFunction = Function;
}
void SetStandardLogFile(const char *FileName){
strcpy(StandardLogFile, FileName);
}
void SilentHandler(const char *Text){
// no-op
}
void SilentHandler(int Level, const char *Text){
// no-op
}
void LogFileHandler(const char *Text){
if(StandardLogFile[0] == 0){
return;
}
FILE *File = fopen(StandardLogFile, "at");
if(File != NULL){
fprintf(File, "%s", Text);
if(fclose(File) != 0){
error("LogfileHandler: Fehler %d beim Schließen der Datei.\n", errno);
}
}
}
void LogFileHandler(int Level, const char *Text){
LogFileHandler(Text);
}
void error(const char *Text, ...){
char s[1024];
va_list ap;
va_start(ap, Text);
vsnprintf(s, sizeof(s), Text, ap);
va_end(ap);
if(ErrorFunction){
ErrorFunction(s);
}else{
printf("%s", s);
}
}
void print(int Level, const char *Text, ...){
char s[1024];
va_list ap;
va_start(ap, Text);
vsnprintf(s, sizeof(s), Text, ap);
va_end(ap);
if(PrintFunction){
PrintFunction(Level, s);
}else{
printf("%s", s);
}
}
int random(int Min, int Max){
int Range = (Max - Min) + 1;
int Result = Min;
if(Range > 0){
Result += rand() % Range;
}
return Result;
}
bool FileExists(const char *FileName){
struct stat Buffer;
bool Result = true;
if(stat(FileName, &Buffer) != 0){
if(errno != ENOENT){
error("FileExists: Unerwarteter Fehlercode %d.\n", errno);
}
Result = false;
}
return Result;
}
#if !defined(_GNU_SOURCE) || (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 32))
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
static const char *sigdescr_np(int SigNr){
const char *Description = NULL;
if(SigNr >= 0 && SigNr < NSIG){
Description = sys_siglist[SigNr];
}
return Description;
}
static const char *strerrordesc_np(int ErrCode){
const char *Description = NULL;
if(ErrCode >= 0 && ErrCode < sys_nerr){
Description = sys_errlist[ErrCode];
}
return Description;
}
# else // defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
#warning "Current LIBC/GLIBC version doesn't expose error/signal description tables."
static const char *sigdescr_np(int SigNr){ return "No signal description"; }
static const char *strerrordesc_np(int ErrCode){ return "No error description"; }
# endif // defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
#endif //!defined(_GNU_SOURCE) || (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 32))
const char *GetSignalDescription(int SigNr){
const char *Description = sigdescr_np(SigNr);
if(Description == NULL){
Description = "Invalid signal";
}
return Description;
}
const char *GetErrorDescription(int ErrCode){
const char *Description = strerrordesc_np(ErrCode);
if(Description == NULL){
Description = "Invalid error";
}
return Description;
}
// String Utility
// =============================================================================
bool isSpace(int c){
return c == ' '
|| c == '\t'
|| c == '\n'
|| c == '\r'
|| c == '\v'
|| c == '\f';
}
bool isAlpha(int c){
// TODO(fusion): This is most likely wrong! We're assuming a direct conversion
// from `char` to `int` which will cause sign extension for negative values. This
// wouldn't be a problem if we expected to parse only streams of `char[]` but can
// be problematic for the output of `getc` which returns bytes as `unsigned char`
// converted to `int`.
// TLDR: The parameter `c` should be `uint8`.
return ('A' <= c && c <= 'Z')
|| ('a' <= c && c <= 'z')
|| c == -0x1C // E4 => ä
|| c == -0x0A // F6 => ö
|| c == -0x04 // FC => ü
|| c == -0x3C // C4 => Ä
|| c == -0x2A // D6 => Ö
|| c == -0x24 // DC => Ü
|| c == -0x21; // DF => ß
}
bool isEngAlpha(int c){
return ('A' <= c && c <= 'Z')
|| ('a' <= c && c <= 'z');
}
bool isDigit(int c){
return ('0' <= c && c <= '9');
}
int toLower(int c){
// TODO(fusion): Same problem as `isAlpha`.
if(('A' <= c && c <= 'Z') || (0xC0 <= c && c <= 0xDE && c != 0xD7)){
c += 32;
}
return c;
}
int toUpper(int c){
// TODO(fusion): Same problem as `isAlpha`.
if(('a' <= c && c <= 'z') || (0xE0 <= c && c <= 0xFE && c != 0xF7)){
c -= 32;
}
return c;
}
char *strLower(char *s){
for(int i = 0; s[i] != 0; i += 1){
s[i] = (char)toLower(s[i]);
}
return s;
}
char *strUpper(char *s){
for(int i = 0; s[i] != 0; i += 1){
s[i] = (char)toUpper(s[i]);
}
return s;
}
int stricmp(const char *s1, const char *s2, int Max /*= INT_MAX*/){
for(int i = 0; i < Max; i += 1){
int c1 = toLower(s1[i]);
int c2 = toLower(s2[i]);
if(c1 > c2){
return 1;
}else if(c1 < c2){
return -1;
}else{
ASSERT(c1 == c2);
if(c1 == 0){
break;
}
}
}
return 0;
}
char *findFirst(char *s, char c){
return strchr(s, (int)c);
}
char *findLast(char *s, char c){
char *Current = s;
char *Last = NULL;
while(true){
Current = strchr(Current, (int)c);
if(Current == NULL)
break;
Last = Current;
Current += 1; // skip character
}
return Last;
}
// BitSet Utility
// =============================================================================
bool CheckBitIndex(int BitSetBytes, int Index){
return Index >= 0 && Index < (BitSetBytes * 8);
}
bool CheckBit(uint8 *BitSet, int Index){
int ByteIndex = (int)(Index / 8);
uint8 BitMask = (uint8)(1 << (Index % 8));
return (BitSet[ByteIndex] & BitMask) != 0;
}
void SetBit(uint8 *BitSet, int Index){
int ByteIndex = (int)(Index / 8);
uint8 BitMask = (uint8)(1 << (Index % 8));
BitSet[ByteIndex] |= BitMask;
}
void ClearBit(uint8 *BitSet, int Index){
int ByteIndex = (int)(Index / 8);
uint8 BitMask = (uint8)(1 << (Index % 8));
BitSet[ByteIndex] &= ~BitMask;
}
// TReadStream
// =============================================================================
bool TReadStream::readFlag(void){
return this->readByte() != 0;
}
uint16 TReadStream::readWord(void){
// NOTE(fusion): Data is encoded in little endian.
uint8 Byte0 = this->readByte();
uint8 Byte1 = this->readByte();
return ((uint16)Byte1 << 8) | (uint16)Byte0;
}
uint32 TReadStream::readQuad(void){
// NOTE(fusion): Data is encoded in little endian.
uint8 Byte0 = this->readByte();
uint8 Byte1 = this->readByte();
uint8 Byte2 = this->readByte();
uint8 Byte3 = this->readByte();
return ((uint32)Byte3 << 24) | ((uint32)Byte2 << 16)
| ((uint32)Byte1 << 8) | (uint32)Byte0;
}
void TReadStream::readString(char *Buffer, int MaxLength){
if(Buffer == NULL || MaxLength == 0){
error("TReadStream::readString: Übergebener Puffer existiert nicht.\n");
throw "internal error";
}
int Length = (int)this->readWord();
if(Length == 0xFFFF){
Length = (int)this->readQuad();
}
if(Length > 0){
if(MaxLength < 0 || MaxLength > Length){
this->readBytes((uint8*)Buffer, Length);
Buffer[Length] = 0;
}else{
this->readBytes((uint8*)Buffer, MaxLength - 1);
this->skip(Length - MaxLength + 1);
Buffer[MaxLength - 1] = 0;
}
}else{
Buffer[0] = 0;
}
}
void TReadStream::readBytes(uint8 *Buffer, int Count){
if(Buffer == NULL){
error("TReadStream::readBytes: Übergebener Puffer existiert nicht.\n");
throw "internal error";
}
for(int i = 0; i < Count; i += 1){
Buffer[i] = this->readByte();
}
}
// TReadBuffer
// =============================================================================
TReadBuffer::TReadBuffer(const uint8 *Data, int Size){
if(Data == NULL){
error("TReadBuffer::TReadBuffer: data ist NULL.\n");
Size = 0;
}else if(Size < 0){
error("TReadBuffer::TReadBuffer: Ungültige Datengröße %d.\n", Size);
Size = 0;
}
this->Data = Data;
this->Size = Size;
this->Position = 0;
}
uint8 TReadBuffer::readByte(void){
if((this->Size - this->Position) < 1){
throw "buffer empty";
}
uint8 Byte = this->Data[this->Position];
this->Position += 1;
return Byte;
}
uint16 TReadBuffer::readWord(void){
if((this->Size - this->Position) < 2){
throw "buffer empty";
}
uint8 Byte0 = this->Data[this->Position];
uint8 Byte1 = this->Data[this->Position + 1];
this->Position += 2;
return ((uint16)Byte1 << 8) | (uint16)Byte0;
}
uint32 TReadBuffer::readQuad(void){
if((this->Size - this->Position) < 4){
throw "buffer empty";
}
uint8 Byte0 = this->Data[this->Position];
uint8 Byte1 = this->Data[this->Position + 1];
uint8 Byte2 = this->Data[this->Position + 2];
uint8 Byte3 = this->Data[this->Position + 3];
this->Position += 4;
return ((uint32)Byte3 << 24) | ((uint32)Byte2 << 16)
| ((uint32)Byte1 << 8) | (uint32)Byte0;
}
void TReadBuffer::readBytes(uint8 *Buffer, int Count){
if(Buffer == NULL || Count <= 0){
error("TReadBuffer::readBytes: Übergebener Puffer existiert nicht.\n");
throw "buffer not existing";
}
if((this->Size - this->Position) < Count){
throw "buffer empty";
}
memcpy(Buffer, &this->Data[this->Position], Count);
this->Position += Count;
}
bool TReadBuffer::eof(void){
return this->Size <= this->Position;
}
void TReadBuffer::skip(int Count){
if((this->Size - this->Position) < Count){
throw "buffer empty";
}
this->Position += Count;
}
// TWriteStream
// =============================================================================
void TWriteStream::writeFlag(bool Flag){
this->writeByte((uint8)Flag);
}
void TWriteStream::writeWord(uint16 Word){
this->writeByte((uint8)(Word));
this->writeByte((uint8)(Word >> 8));
}
void TWriteStream::writeQuad(uint32 Quad){
this->writeByte((uint8)(Quad));
this->writeByte((uint8)(Quad >> 8));
this->writeByte((uint8)(Quad >> 16));
this->writeByte((uint8)(Quad >> 24));
}
void TWriteStream::writeString(const char *String){
if(String == NULL){
this->writeWord(0);
return;
}
int StringLength = (int)strlen(String);
ASSERT(StringLength >= 0);
if(StringLength < 0xFFFF){
this->writeWord((uint16)StringLength);
}else{
this->writeWord(0xFFFF);
this->writeQuad((uint32)StringLength);
}
if(StringLength > 0){
this->writeBytes((const uint8*)String, StringLength);
}
}
void TWriteStream::writeBytes(const uint8 *Buffer, int Count){
if(Buffer == NULL){
error("TWriteStream::writeBytes: Übergebener Puffer existiert nicht.\n");
throw "internal error";
}
for(int i = 0; i < Count; i += 1){
this->writeByte(Buffer[i]);
}
}
// TWriteBuffer
// =============================================================================
TWriteBuffer::TWriteBuffer(uint8 *Data, int Size){
if(Data == NULL){
error("TWriteBuffer::TWriteBuffer: data ist NULL.\n");
Size = 0;
}else if(Size < 0){
error("TWriteBuffer::TWriteBuffer: Ungültige Datengröße %d.\n", Size);
Size = 0;
}
this->Data = Data;
this->Size = Size;
this->Position = 0;
}
void TWriteBuffer::writeByte(uint8 Byte){
if((this->Size - this->Position) < 1){
throw "buffer full";
}
this->Data[this->Position] = Byte;
this->Position += 1;
}
void TWriteBuffer::writeWord(uint16 Word){
if((this->Size - this->Position) < 2){
throw "buffer full";
}
this->Data[this->Position] = (uint8)(Word);
this->Data[this->Position + 1] = (uint8)(Word >> 8);
this->Position += 2;
}
void TWriteBuffer::writeQuad(uint32 Quad){
if((this->Size - this->Position) < 4){
throw "buffer full";
}
this->Data[this->Position] = (uint8)(Quad);
this->Data[this->Position + 1] = (uint8)(Quad >> 8);
this->Data[this->Position + 2] = (uint8)(Quad >> 16);
this->Data[this->Position + 3] = (uint8)(Quad >> 24);
this->Position += 4;
}
void TWriteBuffer::writeBytes(const uint8 *Buffer, int Count){
if((this->Size - this->Position) < Count){
throw "buffer full";
}
memcpy(&this->Data[this->Position], Buffer, Count);
this->Position += Count;
}
// TDynamicWriteBuffer
// =============================================================================
TDynamicWriteBuffer::TDynamicWriteBuffer(int InitialSize)
: TWriteBuffer(new uint8[InitialSize], InitialSize)
{
// no-op
}
void TDynamicWriteBuffer::resizeBuffer(void){
ASSERT(this->Size > 0);
int Size = this->Size * 2;
uint8 *Data = new uint8[Size];
if(this->Data != NULL){
memcpy(Data, this->Data, this->Size);
delete[] this->Data;
}
this->Data = Data;
this->Size = Size;
}
void TDynamicWriteBuffer::writeByte(uint8 Byte){
while((this->Size - this->Position) < 1){
this->resizeBuffer();
}
this->Data[this->Position] = Byte;
this->Position += 1;
}
void TDynamicWriteBuffer::writeWord(uint16 Word){
while((this->Size - this->Position) < 2){
this->resizeBuffer();
}
this->Data[this->Position] = (uint8)(Word);
this->Data[this->Position + 1] = (uint8)(Word >> 8);
this->Position += 2;
}
void TDynamicWriteBuffer::writeQuad(uint32 Quad){
while((this->Size - this->Position) < 4){
this->resizeBuffer();
}
this->Data[this->Position] = (uint8)(Quad);
this->Data[this->Position + 1] = (uint8)(Quad >> 8);
this->Data[this->Position + 2] = (uint8)(Quad >> 16);
this->Data[this->Position + 3] = (uint8)(Quad >> 24);
this->Position += 4;
}
void TDynamicWriteBuffer::writeBytes(const uint8 *Buffer, int Count){
while((this->Size - this->Position) < Count){
this->resizeBuffer();
}
memcpy(&this->Data[this->Position], Buffer, Count);
this->Position += Count;
}
TDynamicWriteBuffer::~TDynamicWriteBuffer(void){
if(this->Data != NULL){
delete[] this->Data;
}
}

1046
src/game/src/writer.cc Normal file

File diff suppressed because it is too large Load diff

155
src/game/src/writer.hh Normal file
View file

@ -0,0 +1,155 @@
#ifndef TIBIA_WRITER_HH_
#define TIBIA_WRITER_HH_ 1
#include "common.hh"
#include "containers.hh"
#include "operate.hh"
enum TWriterThreadOrderType: int {
WRITER_ORDER_TERMINATE = 0,
WRITER_ORDER_LOGOUT = 1,
WRITER_ORDER_PLAYERLIST = 2,
WRITER_ORDER_KILLSTATISTICS = 3,
WRITER_ORDER_PUNISHMENT = 4,
WRITER_ORDER_CHARACTERDEATH = 5,
WRITER_ORDER_ADDBUDDY = 6,
WRITER_ORDER_REMOVEBUDDY = 7,
WRITER_ORDER_DECREMENTISONLINE = 8,
WRITER_ORDER_SAVEPLAYERDATA = 9,
};
enum TWriterThreadReplyType: int {
WRITER_REPLY_BROADCAST = 0,
WRITER_REPLY_DIRECT = 1,
WRITER_REPLY_LOGOUT = 2,
};
struct TProtocolThreadOrder{
char ProtocolName[20];
char Text[256];
};
struct TWriterThreadOrder{
TWriterThreadOrderType OrderType;
const void *Data;
};
struct TLogoutOrderData{
uint32 CharacterID;
int Level;
int Profession;
time_t LastLoginTime;
int TutorActivities;
char Residence[30];
};
struct TPlayerlistOrderData{
int NumberOfPlayers;
const char *PlayerNames;
int *PlayerLevels;
int *PlayerProfessions;
};
struct TKillStatisticsOrderData{
int NumberOfRaces;
const char *RaceNames;
int *KilledPlayers;
int *KilledCreatures;
};
struct TPunishmentOrderData{
uint32 GamemasterID;
char GamemasterName[30];
char CriminalName[30];
char CriminalIPAddress[16];
int Reason;
int Action;
char Comment[200];
int NumberOfStatements;
vector<TReportedStatement> *ReportedStatements;
uint32 StatementID;
bool IPBanishment;
};
struct TCharacterDeathOrderData{
uint32 CharacterID;
int Level;
uint32 Offender;
char Remark[30];
bool Unjustified;
time_t Time;
};
struct TBuddyOrderData{
uint32 AccountID;
uint32 Buddy;
};
struct TWriterThreadReply{
TWriterThreadReplyType ReplyType;
const void *Data;
};
struct TBroadcastReplyData{
char Message[100];
};
struct TDirectReplyData{
uint32 CharacterID;
char Message[100];
};
void InitProtocol(void);
void InsertProtocolOrder(const char *ProtocolName, const char *Text);
void GetProtocolOrder(TProtocolThreadOrder *Order);
void WriteProtocol(const char *ProtocolName, const char *Text);
int ProtocolThreadLoop(void *Unused);
void InitLog(const char *ProtocolName);
void Log(const char *ProtocolName, const char *Text, ...) ATTR_PRINTF(2, 3);
void InitWriterBuffers(void);
int GetOrderBufferSpace(void);
void InsertOrder(TWriterThreadOrderType OrderType, const void *Data);
void GetOrder(TWriterThreadOrder *Order);
void TerminateWriterOrder(void);
void LogoutOrder(TPlayer *Player);
void PlayerlistOrder(int NumberOfPlayers, const char *PlayerNames,
int *PlayerLevels, int *PlayerProfessions);
void KillStatisticsOrder(int NumberOfRaces, const char *RaceNames,
int *KilledPlayers, int *KilledCreatures);
void PunishmentOrder(TCreature *Gamemaster, const char *Name, const char *IPAddress,
int Reason, int Action, const char *Comment, int NumberOfStatements,
vector<TReportedStatement> *ReportedStatements, uint32 StatementID,
bool IPBanishment);
void CharacterDeathOrder(TCreature *Creature, int OldLevel,
uint32 OffenderID, const char *Remark, bool Unjustified);
void AddBuddyOrder(TCreature *Creature, uint32 BuddyID);
void RemoveBuddyOrder(TCreature *Creature, uint32 BuddyID);
void DecrementIsOnlineOrder(uint32 CharacterID);
void SavePlayerDataOrder(void);
void ProcessLogoutOrder(TLogoutOrderData *Data);
void ProcessPlayerlistOrder(TPlayerlistOrderData *Data);
void ProcessKillStatisticsOrder(TKillStatisticsOrderData *Data);
void ProcessPunishmentOrder(TPunishmentOrderData *Data);
void ProcessCharacterDeathOrder(TCharacterDeathOrderData *Data);
void ProcessAddBuddyOrder(TBuddyOrderData *Data);
void ProcessRemoveBuddyOrder(TBuddyOrderData *Data);
void ProcessDecrementIsOnlineOrder(uint32 CharacterID);
int WriterThreadLoop(void *Unused);
void InsertReply(TWriterThreadReplyType ReplyType, const void *Data);
void BroadcastReply(const char *Text, ...) ATTR_PRINTF(1, 2);
void DirectReply(uint32 CharacterID, const char *Text, ...) ATTR_PRINTF(2, 3);
void LogoutReply(const char *PlayerName);
bool GetReply(TWriterThreadReply *Reply);
void ProcessBroadcastReply(TBroadcastReplyData *Data);
void ProcessDirectReply(TDirectReplyData *Data);
void ProcessLogoutReply(const char *Name);
void ProcessWriterThreadReplies(void);
void ClearPlayers(void);
void InitWriter(void);
void AbortWriter(void);
void ExitWriter(void);
#endif //TIBIA_WRITER_HH_

View file

@ -0,0 +1,26 @@
# Basic SYSTEMD service file for the Tibia Game Server
[Unit]
Description=Tibia Game Server
After=network.target tibia-querymanager.service
Requires=tibia-querymanager.service
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=tibia-game
Group=tibia-game
ExecStart=/opt/tibia/game/bin/game
WorkingDirectory=/opt/tibia/game
Restart=always
RestartSec=10
# After a SIGTERM, the server will issue shutdown warnings for 5 minutes and
# take another minute or two to save everything and exit. Not waiting for this
# process to complete would cause data to not be properly saved.
TimeoutStopSec=900
LimitCORE=infinity
StandardOutput=journal
StandardError=journal
SyslogIdentifier=%n

15
src/game/tibia.pem Normal file
View file

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDLoibNahc41DeQhZUTth3FrhMNYek5xbQrlZ0O4BFr0LukdGY1
A3xHKAXt4d6Y539cQxpKqVPb+eSo44076c1PfL31BTDNFToN4uB3eUsOw3hROPSx
0Jkh72FAIhl6QynId0AHyrqeAgY59ZsTyXyJCSCWpFnl0WvK3Qf6nVBH/wIDAQAB
AoGAB9DoA19sl8JRhasS70hAuUs2sP9Ol+iWQ0wBVMZV9Nj0stnC6IsDNKn9HEXc
qOrN0SlEM5RvQxTC6ZaeX6vYNQDSJj/aigSyiNTMvw+38TD09z6EBlI4+0piGIJd
qY1ky0w3bdVhWiY2VFyGZ50NkfwjrpZSdLmsbhExzR4b/mkCQQDldLUeePo3RKZD
7+CVLFkTX/Yof8RLPOh1nukgftpvgaGcD1FXSwrIyKCHVAuwFnGgPfEr/2OAj60D
7Ya6XPeHAkEA4zC3U67ukzQxfyELrLTUBnsnKfkxejySsJ/M29SKCuHV2NOWxO8W
s9/c0RFvp0wI4uOxH00fIPYyI2h6TpxZyQJBAKQ0ZPktskKjCilMHPgkCIro/Yv2
A0+kgubJliP/I+rwZer8u0UxGsKdcOPnrYWSSjZWnaTS2y5Bo5tP/D6aETkCQDAc
AtZPtumpJcob/1LlP/jXX2W+BUIzTYTlcgYjLdA8HoK527V8Q7x3bVVAcfplWYRi
XwGX3T2npNpmp2+6IDECQBZuNbXiwHhDdsH7sSt36BGTFJNtVk3GJl/Bf50VrL6N
6NBNU3d4jQwArvSsanFYrZw+ayxS4rcJdZasO5mm+EI=
-----END RSA PRIVATE KEY-----

98
src/game/tools/genpem.go Normal file
View file

@ -0,0 +1,98 @@
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"math/big"
"os"
"slices"
)
func GenerateDefaultKey() (*rsa.PrivateKey, error) {
// NOTE(fusion): Generate key from known P, Q, and E. There isn't a helper
// function from the standard library so we need to build the private key
// ourselves.
const (
P = "1201758001370723323398753778257470257713354828752713123415294815" +
"0506251412291888866940292054989907714155267326586216043845592229" +
"084368540020196135619327879"
Q = "1189892136861686835188050824611210139447876026576932541274639840" +
"5473436969889506919017477758618276066588858607419440134394668095" +
"105156501566867770737187273"
E = "65537"
)
p, ok := new(big.Int).SetString(P, 10)
if !ok || !p.ProbablyPrime(4) {
return nil, errors.New("invalid default P prime")
}
q, ok := new(big.Int).SetString(Q, 10)
if !ok || !q.ProbablyPrime(4) {
return nil, errors.New("invalid default Q prime")
}
e, ok := new(big.Int).SetString(E, 10)
if !ok || !e.IsInt64() || !e.ProbablyPrime(4) {
return nil, errors.New("invalid default E prime")
}
pMinus1 := new(big.Int).Sub(p, big.NewInt(1))
qMinus1 := new(big.Int).Sub(q, big.NewInt(1))
gcd := new(big.Int).GCD(nil, nil, pMinus1, qMinus1)
phi := new(big.Int).Mul(pMinus1, qMinus1)
lambda := new(big.Int).Div(phi, gcd)
d := new(big.Int).ModInverse(e, lambda)
n := new(big.Int).Mul(p, q)
privateKey := rsa.PrivateKey{
PublicKey: rsa.PublicKey{
N: n,
E: int(e.Int64()),
},
D: d,
Primes: []*big.Int{p, q},
}
return &privateKey, nil
}
func GenerateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, 1024)
}
func main() {
var (
privateKey *rsa.PrivateKey
err error
)
if len(os.Args) > 1 && slices.Contains(os.Args[1:], "-default") {
privateKey, err = GenerateDefaultKey()
} else {
privateKey, err = GenerateKey()
}
if err != nil {
panic("failed to generate key: " + err.Error())
}
// NOTE(fusion): `Validate()` will only perform minor sanity checks. To actually
// check that the output key is valid use `openssl rsa -in KEY.PEM -check`.
err = privateKey.Validate()
if err != nil {
panic("invalid private key: " + err.Error())
}
// NOTE(fusion): Dump private key into stdout.
block := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
pem.Encode(os.Stdout, &block)
}

121
src/game/tools/makefile.go Normal file
View file

@ -0,0 +1,121 @@
package main
import (
"bytes"
"fmt"
"io/fs"
"os"
"path"
"strings"
)
var (
outputExe = "game"
compilerExe = "g++"
compilerOptions = []string{
"-m64",
"-fno-strict-aliasing",
"-pedantic",
"-Wall",
"-Wextra",
"-Wno-deprecated-declarations",
"-Wno-unused-parameter",
"-Wno-format-truncation",
"-std=c++11",
"-pthread",
"-DOS_LINUX=1",
"-DARCH_X64=1",
}
debugOptions = []string{"-g", "-Og", "-DENABLE_ASSERTIONS=1"}
releaseOptions = []string{"-O2"}
linkerOptions = []string{
"-Wl,-t",
"-lrt",
"-lcrypto",
}
)
func main() {
if len(os.Args) < 2 {
fmt.Println("USAGE: makefile.exe SRCDIR")
os.Exit(1)
}
sourceDir := os.Args[1]
buildDir := path.Join(path.Dir(sourceDir), "build")
type Object struct{ obj, src string }
objectFiles := []Object{}
headerFiles := []string{}
fs.WalkDir(os.DirFS(sourceDir), ".",
func(rel string, d fs.DirEntry, err error) error {
if err == nil && !d.IsDir() {
ext := path.Ext(rel)
switch ext {
case ".cpp", ".cxx", ".cc", ".c":
src := rel
obj := rel[:len(src)-len(ext)] + ".obj"
objectFiles = append(objectFiles, Object{obj, src})
case ".hpp", ".hxx", ".hh", ".h":
hdr := rel
headerFiles = append(headerFiles, hdr)
}
}
return nil
})
output := bytes.Buffer{}
// VARIABLES
fmt.Fprintf(&output, "SRCDIR = %v\n", sourceDir)
fmt.Fprintf(&output, "BUILDDIR = %v\n", buildDir)
fmt.Fprintf(&output, "OUTPUTEXE = %v\n", outputExe)
fmt.Fprint(&output, "\n")
fmt.Fprintf(&output, "CC = %v\n", compilerExe)
fmt.Fprintf(&output, "CFLAGS = %v\n", strings.Join(compilerOptions, " "))
fmt.Fprintf(&output, "LFLAGS = %v\n", strings.Join(linkerOptions, " "))
fmt.Fprint(&output, "\n")
// DEBUG SWITCH
fmt.Fprint(&output, "DEBUG ?= 0\n")
fmt.Fprint(&output, "ifneq ($(DEBUG), 0)\n")
fmt.Fprintf(&output, " CFLAGS += %v\n", strings.Join(debugOptions, " "))
fmt.Fprint(&output, "else\n")
fmt.Fprintf(&output, " CFLAGS += %v\n", strings.Join(releaseOptions, " "))
fmt.Fprint(&output, "endif\n\n")
// HEADERS
fmt.Fprint(&output, "HEADERS =")
for _, header := range headerFiles {
fmt.Fprintf(&output, " $(SRCDIR)/%v", header)
}
fmt.Fprint(&output, "\n\n")
// EXECUTABLE
fmt.Fprint(&output, "$(BUILDDIR)/$(OUTPUTEXE):")
for _, object := range objectFiles {
fmt.Fprintf(&output, " $(BUILDDIR)/%v", object.obj)
}
fmt.Fprint(&output, "\n")
fmt.Fprint(&output, "\t$(CC) $(CFLAGS) -o $@ $^ $(LFLAGS)\n\n")
// OBJECTS
for _, object := range objectFiles {
fmt.Fprintf(&output, "$(BUILDDIR)/%v: $(SRCDIR)/%v $(HEADERS)\n", object.obj, object.src)
fmt.Fprint(&output, "\t@mkdir -p $(@D)\n")
fmt.Fprint(&output, "\t$(CC) -c $(CFLAGS) -o $@ $<\n\n")
}
// PHONY
fmt.Fprint(&output, ".PHONY: clean\n\n")
fmt.Fprint(&output, "clean:\n\t@rm -rf $(BUILDDIR)\n\n")
if err := os.WriteFile("Makefile", output.Bytes(), 0644); err != nil {
fmt.Printf("failed to write Makefile: %v\n", err)
os.Exit(1)
}
return
}

34
src/game/tools/pubkey.go Normal file
View file

@ -0,0 +1,34 @@
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
)
func main() {
keyFile := "key.pem"
if len(os.Args) > 1 {
keyFile = os.Args[1]
}
keyData, err := os.ReadFile(keyFile)
if err != nil {
log.Panicf("failed to read key \"%v\": %v", keyFile, err)
}
keyBlock, _ := pem.Decode(keyData)
if keyBlock == nil {
log.Panicf("key \"%v\" is empty")
}
privateKey, err := x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
if err != nil {
log.Panic("failed to read PKCS1 RSA private key: %v", err)
}
fmt.Println("N", privateKey.N)
fmt.Println("E", privateKey.E)
}

5
src/ipchanger/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
.vscode
bin
build
local
servers.txt

View file

@ -0,0 +1,6 @@
{
"upstream": "https://kaplar.net/tibia/ipchanger.git",
"commit": "8215db18abbae05b62bcbd5c4f086856168283a4",
"branch": "master",
"vendoredAt": "2026-11-12"
}

24
src/ipchanger/LICENSE.txt Normal file
View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>

4
src/ipchanger/README.md Normal file
View file

@ -0,0 +1,4 @@
# Tibia IP-Changer
This is a simple command line IP-Changer for old Tibia clients. Its main feature is having multiple server configurations stored in a configuration file (see `ipchanger.exe -help`). Only a few client versions are currently supported (7.7, 8.1, 8.6) but it should be straighforward to expand to others. There is also a memory scan tool that can be used to help with scanning memory addresses for yet unsupported clients.
Both are Windows specific and can be compiled by running `build.bat` from the visual studio shell. They're very simple so I wont bother explaining them further. For more details, the source code should be very readable.

15
src/ipchanger/build.bat Normal file
View file

@ -0,0 +1,15 @@
@SETLOCAL
@SET CFLAGS=-W3 -WX -Zi -D_CRT_SECURE_NO_WARNINGS=1
@SET LFLAGS=-subsystem:console -incremental:no -opt:ref -dynamicbase user32.lib
pushd %~dp0
del /q .\build\*
mkdir .\build
pushd .\build
cl %* -Fe:"ipchanger.exe" %CFLAGS% "../ipchanger.cc" /link %LFLAGS%
cl %* -Fe:"memscan.exe" %CFLAGS% "../memscan.cc" /link %LFLAGS%
popd
popd
@ENDLOCAL

492
src/ipchanger/ipchanger.cc Normal file
View file

@ -0,0 +1,492 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#define NARRAY(Array) (int)(sizeof(Array) / sizeof(Array[0]))
typedef uint8_t uint8;
typedef uintptr_t uintptr;
struct ServerEntry{
ServerEntry *Next;
int Version;
char Alias[100];
char HostName[100];
int Port;
char RsaModulus[1024];
};
struct TibiaVersion{
int Version;
const char *VersionString;
int NumLoginEndpoints;
int LoginEndpointStride;
int MaxHostNameSize;
int MaxRsaModulusSize;
uintptr VersionStringAddr;
uintptr FirstLoginHostNameAddr;
uintptr FirstLoginPortAddr;
uintptr RsaModulusAddr;
};
struct AutoHandleClose{
private:
HANDLE m_Handle;
public:
AutoHandleClose(HANDLE Handle){
m_Handle = Handle;
}
~AutoHandleClose(void){
if(m_Handle != NULL){
CloseHandle(m_Handle);
}
}
};
bool StringEqN(const char *A, const char *B, int N){
int Index = 0;
while(true){
if(Index >= N){
return true;
}else if(A[Index] != B[Index] || A[Index] == 0){
return false;
}
Index += 1;
}
}
bool StringEqCI(const char *A, const char *B){
int Index = 0;
while(true){
if(tolower(A[Index]) != tolower(B[Index])){
return false;
}else if(A[Index] == 0){
return true;
}
Index += 1;
}
}
void PrintLastError(const char *Context){
DWORD ErrorCode = GetLastError();
char ErrorString[256];
DWORD Ret = FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
ErrorString, sizeof(ErrorString), NULL);
if(Ret == 0){
strcpy(ErrorString, "unknown error");
}
printf("%s | error(%d): %s\n", Context, ErrorCode, ErrorString);
}
void DebugPrintBuf(uintptr Address, const uint8 *Buffer, int Count){
const int BytesPerLine = 16;
int FullLines = Count / BytesPerLine;
int Remainder = Count % BytesPerLine;
for(int i = 0; i < FullLines; i += 1){
printf("%16" PRIXPTR " | ", (Address + i * BytesPerLine));
for(int j = 0; j < BytesPerLine; j += 1){
if(j > 0) putchar(' ');
printf("%02X", Buffer[i * BytesPerLine + j]);
}
printf(" | ");
for(int j = 0; j < BytesPerLine; j += 1){
int ch = Buffer[i * BytesPerLine + j];
printf("%c", isprint(ch) ? ch : '.');
}
putchar('\n');
}
if(Remainder > 0){
printf("%16" PRIXPTR " | ", (Address + FullLines * BytesPerLine));
for(int j = 0; j < BytesPerLine; j += 1){
if(j > 0) putchar(' ');
if(j < Remainder){
printf("%02X", Buffer[FullLines * BytesPerLine + j]);
}else{
printf(" ");
}
}
printf(" | ");
for(int j = 0; j < BytesPerLine; j += 1){
if(j < Remainder){
int ch = Buffer[FullLines * BytesPerLine + j];
printf("%c", isprint(ch) ? ch : '.');
}else{
printf(" ");
}
}
putchar('\n');
}
}
bool ChangeIP(const TibiaVersion *V, const char *HostName, int Port, const char *RsaModulus){
int HostNameSize = (int)strlen(HostName) + 1;
if(HostNameSize > V->MaxHostNameSize){
printf("ChangeIP: HostName size exceeds limit for version %d (%d > %d).\n",
V->Version, HostNameSize, V->MaxHostNameSize);
return false;
}
if(Port <= 0 || Port > 0xFFFF){
printf("ChangeIP: Invalid port number %d.\n", Port);
return false;
}
HWND Window = FindWindowA("TibiaClient", NULL);
if(Window == NULL){
printf("ChangeIP: No client running.\n");
return false;
}
DWORD ProcessID;
GetWindowThreadProcessId(Window, &ProcessID);
HANDLE Process = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, ProcessID);
if(Process == NULL){
PrintLastError("OpenProcess");
return false;
}
AutoHandleClose HandleClose(Process);
if(V->VersionString != NULL && V->VersionStringAddr != 0){
uint8 VersionString[128];
if(!ReadProcessMemory(Process, (void*)V->VersionStringAddr,
VersionString, sizeof(VersionString), NULL)){
PrintLastError("ReadProcessMemory(VersionString)");
return false;
}
int VersionStringLen = (int)strlen(V->VersionString);
if(!StringEqN(V->VersionString, (char*)VersionString, VersionStringLen)){
printf("ChangeIP: Invalid client version.\n");
return false;
}
}
if(V->FirstLoginHostNameAddr != 0 && V->FirstLoginPortAddr != 0){
uint8 HelpPort[4];
HelpPort[0] = (uint8)(Port >> 0);
HelpPort[1] = (uint8)(Port >> 8);
HelpPort[2] = (uint8)(Port >> 16);
HelpPort[3] = (uint8)(Port >> 24);
for(int i = 0; i < V->NumLoginEndpoints; i += 1){
uintptr HostNameAddr = V->FirstLoginHostNameAddr + i * V->LoginEndpointStride;
uintptr PortAddr = V->FirstLoginPortAddr + i * V->LoginEndpointStride;
if(!WriteProcessMemory(Process, (void*)HostNameAddr, HostName, HostNameSize, NULL)){
PrintLastError("WriteProcessMemory(HostName)");
return false;
}
if(!WriteProcessMemory(Process, (void*)PortAddr, HelpPort, sizeof(HelpPort), NULL)){
PrintLastError("WriteProcessMemory(Port)");
return false;
}
}
}
if(RsaModulus != NULL && V->RsaModulusAddr != 0){
int RsaModulusSize = (int)strlen(RsaModulus) + 1;
if(RsaModulusSize > V->MaxRsaModulusSize){
printf("ChangeIP: RsaModulus size exceeds limit for version %d (%d > %d).\n",
V->Version, RsaModulusSize, V->MaxRsaModulusSize);
return false;
}
// NOTE(fusion): The RSA modulus lives in READONLY memory.
DWORD OldProtection;
if(!VirtualProtectEx(Process, (void*)V->RsaModulusAddr,
V->MaxRsaModulusSize, PAGE_READWRITE, &OldProtection)){
PrintLastError("VirtualProtectEx(RsaModulus, READWRITE)");
return false;
}
if(!WriteProcessMemory(Process, (void*)V->RsaModulusAddr, RsaModulus, RsaModulusSize, NULL)){
PrintLastError("WriteProcessMemory(RsaModulus)");
return false;
}
DWORD Dummy;
if(!VirtualProtectEx(Process, (void*)V->RsaModulusAddr,
V->MaxRsaModulusSize, OldProtection, &Dummy)){
PrintLastError("VirtualProtectEx(RsaModulus, OldProtection)");
return false;
}
}
return true;
}
int ReadLine(FILE *File, char *Buffer, int BufferSize, bool *OutEndOfFile, bool *OutClamped){
int LineSize = 0;
bool EndOfFile = false;
bool Clamped = false;
while(true){
int ch = fgetc(File);
if(ch == EOF || ch == '\n'){
EndOfFile = (ch == EOF);
break;
}
if(LineSize < BufferSize){
Buffer[LineSize] = (char)ch;
}
LineSize += 1;
}
if(LineSize >= BufferSize){
LineSize = BufferSize - 1;
Clamped = true;
}
if(!EndOfFile && LineSize > 0 && Buffer[LineSize - 1] == '\r'){
LineSize -= 1;
}
Buffer[LineSize] = 0;
if(OutEndOfFile) *OutEndOfFile = EndOfFile;
if(OutClamped) *OutClamped = Clamped;
return LineSize;
}
void NextValue(const char *Line, int Delim, int *Cursor, char *Buffer, int BufferSize){
int Size = 0;
while(Line[*Cursor] != 0 && Line[*Cursor] != Delim){
if(Size < BufferSize){
Buffer[Size] = Line[*Cursor];
}
*Cursor += 1;
Size += 1;
}
if(Line[*Cursor] != 0){
*Cursor += 1;
}
if(Size >= BufferSize){
Size = BufferSize - 1;
}
Buffer[Size] = 0;
}
ServerEntry *ParseServerEntry(const char *Line, int LineNumber){
int LineStart = 0;
while(Line[LineStart] != 0 && isspace(Line[LineStart])){
LineStart += 1;
}
if(Line[LineStart] == 0 || Line[LineStart] == '#'){
return NULL;
}
char HelpVersion[16];
char HelpPort[16];
int Cursor = LineStart;
ServerEntry *Server = (ServerEntry*)calloc(1, sizeof(ServerEntry));
NextValue(Line, ';', &Cursor, HelpVersion, sizeof(HelpVersion));
NextValue(Line, ';', &Cursor, Server->Alias, sizeof(Server->Alias));
NextValue(Line, ';', &Cursor, Server->HostName, sizeof(Server->HostName));
NextValue(Line, ';', &Cursor, HelpPort, sizeof(HelpPort));
NextValue(Line, ';', &Cursor, Server->RsaModulus, sizeof(Server->RsaModulus));
Server->Version = atoi(HelpVersion);
Server->Port = atoi(HelpPort);
return Server;
}
ServerEntry *ReadServerList(const char *FileName){
FILE *File = fopen(FileName, "r");
if(File == NULL){
printf("ReadServerList: Failed to open \"%s\" for reading.\n", FileName);
return NULL;
}
ServerEntry *ServerList = NULL;
for(int LineNumber = 1; true; LineNumber += 1){
char Line[4096];
bool EndOfFile;
bool Clamped;
int LineSize = ReadLine(File, Line, sizeof(Line), &EndOfFile, &Clamped);
if(LineSize > 0){
ServerEntry *Server = ParseServerEntry(Line, LineNumber);
if(Server){
Server->Next = ServerList;
ServerList = Server;
}
}
if(EndOfFile){
break;
}
}
fclose(File);
return ServerList;
}
void CreateSampleServerList(const char *FileName){
FILE *File = fopen(FileName, "w");
if(File == NULL){
printf("CreateSampleServerList: Failed to open \"%s\" for writing.\n", FileName);
return;
}
fprintf(File,
"# Each server entry should be in a SINGLE line and have the\n"
"# format \"VERSION;ALIAS;HOSTNAME;PORT;RSAMODULUS\". Empty\n"
"# lines and lines starting with # are discarded. The server\n"
"# alias may be empty, meaning you'll need to specify its\n"
"# host name instead. For versions without RSA encryption,\n"
"# the RSA modulus is ignored.\n"
"\n"
"# Example for the default 7.7 tibia login server:\n"
"770;tibia;server.tibia.com;7171;"
"1429962396241639952007017738289889555079540334546615321747051608"
"2934737582776038882967213386204600674145392845853859217990626450"
"9724520840657286865659265687630979195970404721891201847792002125"
"5354012927791239372074475745966927885136471792353355293072513505"
"70728407373705564708871762033017096809910315212883967\n"
"\n"
"# Example for a regular 8.6 otserv:\n"
"860;otserv;server.otserv.com;7171;"
"1091201329673994292788609605089955415282375029027981291234687579"
"3726629149257644633073969600111060390723088861007265581882535850"
"3429057592827629436413108566029093628212635953836686562675849720"
"6207862794310902180176810615217550567108238764764442605581471797"
"07119674283982419152118103759076030616683978566631413\n");
fclose(File);
}
int main(int argc, char **argv){
// TODO(fusion): This could be loaded at runtime from some `versions.txt` file.
static const TibiaVersion Versions[] = {
{
770, // Version
"Version 7.7", // VersionString
5, // NumLoginEndpoints
112, // LoginEndpointStride
100, // MaxHostNameSize
312, // MaxRsaModulusSize
0x51765D, // VersionStringAddr
0x6BB2F0, // FirstLoginHostNameAddr
0x6BB354, // FirstLoginPortAddr
0x516620, // RsaModulusAddr
},
{
772, // Version
"Version 7.72", // VersionString
5, // NumLoginEndpoints
112, // LoginEndpointStride
100, // MaxHostNameSize
312, // MaxRsaModulusSize
0x55C65D, // VersionStringAddr
0x7152F8, // FirstLoginHostNameAddr
0x71535C, // FirstLoginPortAddr
0x55B620, // RsaModulusAddr
},
{
810, // Version
"Version 8.10", // VersionString
10, // NumLoginEndpoints
112, // LoginEndpointStride
100, // MaxHostNameSize
312, // MaxRsaModulusSize
0x61B64D, // VersionStringAddr
0x763BB8, // FirstLoginHostNameAddr
0x763C1C, // FirstLoginPortAddr
0x597610, // RsaModulusAddr
},
{
860, // Version
"Version 8.60", // VersionString
10, // NumLoginEndpoints
112, // LoginEndpointStride
100, // MaxHostNameSize
312, // MaxRsaModulusSize
0x64C2AD, // VersionStringAddr
0x7947F8, // FirstLoginHostNameAddr
0x79485C, // FirstLoginPortAddr
0x5B8980, // RsaModulusAddr
},
};
if(argc <= 1 || argv[1][0] == 0 || argv[1][0] == '-'){
if(argc > 1 && StringEqCI(argv[1], "-sample")){
CreateSampleServerList("servers.txt");
printf("The file `server.txt` was created/rewritten with"
" instructions on how to add or modify servers.\n");
}else{
printf(
"USAGE: ipchanger.exe ALIAS|HOSTNAME # modify client\n"
" ipchanger.exe -sample # create/reset `servers.txt`\n"
" ipchanger.exe -help # print this message\n");
}
return EXIT_FAILURE;
}
ServerEntry *ServerList = ReadServerList("servers.txt");
if(ServerList == NULL){
printf("No server information was found.\n");
return EXIT_FAILURE;
}
ServerEntry *Server = ServerList;
const char *AliasOrHostName = argv[1];
while(Server != NULL){
if(StringEqCI(Server->Alias, AliasOrHostName)
|| StringEqCI(Server->HostName, AliasOrHostName)){
break;
}
Server = Server->Next;
}
if(Server == NULL){
printf("No server with alias or hostname \"%s\" found.\n", AliasOrHostName);
return EXIT_FAILURE;
}
const TibiaVersion *Version = NULL;
for(int i = 0; i < NARRAY(Versions); i += 1){
if(Versions[i].Version == Server->Version){
Version = &Versions[i];
break;
}
}
if(Version == NULL){
printf("Server \"%s\" is defined with version %d which is not"
" currently supported.\n", AliasOrHostName, Server->Version);
return EXIT_FAILURE;
}
if(!ChangeIP(Version, Server->HostName, Server->Port, Server->RsaModulus)){
printf("There was a problem with changing the client's IP.\n");
return EXIT_FAILURE;
}
printf("Client is now configured to connect to %s:%d.\n", Server->HostName, Server->Port);
return EXIT_SUCCESS;
}

236
src/ipchanger/memscan.cc Normal file
View file

@ -0,0 +1,236 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
typedef uint8_t uint8;
typedef uintptr_t uintptr;
void PrintLastError(const char *Context){
DWORD ErrorCode = GetLastError();
char ErrorString[256];
DWORD Ret = FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
ErrorString, sizeof(ErrorString), NULL);
if(Ret == 0){
strcpy(ErrorString, "unknown error");
}
printf("%s | error(%d): %s\n", Context, ErrorCode, ErrorString);
}
void DebugPrintBuf(uintptr Address, const uint8 *Buffer, int Count){
const int BytesPerLine = 16;
int FullLines = Count / BytesPerLine;
int Remainder = Count % BytesPerLine;
for(int i = 0; i < FullLines; i += 1){
printf("%16" PRIXPTR " | ", (Address + i * BytesPerLine));
for(int j = 0; j < BytesPerLine; j += 1){
if(j > 0) putchar(' ');
printf("%02X", Buffer[i * BytesPerLine + j]);
}
printf(" | ");
for(int j = 0; j < BytesPerLine; j += 1){
int ch = Buffer[i * BytesPerLine + j];
printf("%c", isprint(ch) ? ch : '.');
}
putchar('\n');
}
if(Remainder > 0){
printf("%16" PRIXPTR " | ", (Address + FullLines * BytesPerLine));
for(int j = 0; j < BytesPerLine; j += 1){
if(j > 0) putchar(' ');
if(j < Remainder){
printf("%02X", Buffer[FullLines * BytesPerLine + j]);
}else{
printf(" ");
}
}
printf(" | ");
for(int j = 0; j < BytesPerLine; j += 1){
if(j < Remainder){
int ch = Buffer[FullLines * BytesPerLine + j];
printf("%c", isprint(ch) ? ch : '.');
}else{
printf(" ");
}
}
putchar('\n');
}
}
void DumpProcessMemory(HANDLE Process, uintptr BaseAddr, SIZE_T Size){
uintptr Addr = BaseAddr;
uintptr End = BaseAddr + Size;
while(Addr < End){
uint8 Buffer[32 * 1024];
SIZE_T BytesToRead = End - Addr;
if(BytesToRead > sizeof(Buffer)){
BytesToRead = sizeof(Buffer);
}
SIZE_T BytesRead;
if(!ReadProcessMemory(Process, (void*)Addr, Buffer, BytesToRead, &BytesRead)){
PrintLastError("DumpProcessMemory>ReadProcessMemory");
return;
}
DebugPrintBuf(Addr, Buffer, (int)BytesRead);
Addr += BytesRead;
}
}
int BufferFind(const uint8 *Buffer, int BufferSize, const uint8 *Data, int DataSize){
for(int i = 0; i < (BufferSize - DataSize); i += 1){
if(memcmp(Buffer + i, Data, DataSize) == 0){
return i;
}
}
return -1;
}
void ScanProcessMemory(HANDLE Process, uintptr BaseAddr, SIZE_T Size,
const uint8 *Data, SIZE_T DataSize, int ContextWindow){
uintptr Addr = BaseAddr;
uintptr End = BaseAddr + Size;
while(Addr < End){
uint8 Buffer[32 * 1024];
SIZE_T BytesToRead = End - Addr;
if(BytesToRead > sizeof(Buffer)){
BytesToRead = sizeof(Buffer);
}
SIZE_T BytesRead;
if(!ReadProcessMemory(Process, (void*)Addr, Buffer, BytesToRead, &BytesRead)){
PrintLastError("ScanProcessMemory>ReadProcessMemory");
return;
}
// TODO(fusion): This will work most of the time but is not the best way
// to scan for something because the data we're looking for may be split
// between reads, depending on the size of `Buffer`.
int Cursor = 0;
while(true){
int Offset = BufferFind(Buffer + Cursor, (int)BytesRead - Cursor, Data, (int)DataSize);
if(Offset == -1){
break;
}
Cursor += Offset;
int PrintStart = Cursor - ContextWindow;
int PrintEnd = Cursor + (int)DataSize + ContextWindow;
if(PrintStart < 0){
PrintStart = 0;
}
if(PrintEnd > (int)BytesRead){
PrintEnd = (int)BytesRead;
}
DebugPrintBuf(Addr + PrintStart, Buffer + PrintStart, PrintEnd - PrintStart);
Cursor += (int)DataSize;
}
Addr += BytesRead;
}
}
int main(int argc, char **argv){
uint8 Data[128];
int DataSize = 0;
int ContextWindow = 10;
for(int i = 1; i < argc; i += 1){
if(argv[i][0] == '-'){
if((i + 1) >= argc){
printf("missing \"%s\" value", argv[i]);
break;
}
if(strcmp(argv[i], "-c") == 0){
ContextWindow = atoi(argv[i + 1]);
}else if(strcmp(argv[i], "-byte") == 0){
int Num = atoi(argv[i + 1]);
Data[0] = (uint8)Num;
DataSize = 1;
}else if(strcmp(argv[i], "-le16") == 0){
int Num = atoi(argv[i + 1]);
Data[0] = (uint8)(Num >> 0);
Data[1] = (uint8)(Num >> 8);
DataSize = 2;
}else if(strcmp(argv[i], "-be16") == 0){
int Num = atoi(argv[i + 1]);
Data[0] = (uint8)(Num >> 8);
Data[1] = (uint8)(Num >> 0);
DataSize = 2;
}else if(strcmp(argv[i], "-le32") == 0){
int Num = atoi(argv[i + 1]);
Data[0] = (uint8)(Num >> 0);
Data[1] = (uint8)(Num >> 8);
Data[2] = (uint8)(Num >> 16);
Data[3] = (uint8)(Num >> 24);
DataSize = 4;
}else if(strcmp(argv[i], "-be32") == 0){
int Num = atoi(argv[i + 1]);
Data[0] = (uint8)(Num >> 24);
Data[1] = (uint8)(Num >> 16);
Data[2] = (uint8)(Num >> 8);
Data[3] = (uint8)(Num >> 0);
DataSize = 4;
}
i += 1;
}else{
DataSize = (int)strlen(argv[i]);
if(DataSize > (int)sizeof(Data)){
DataSize = (int)sizeof(Data);
}
memcpy(Data, argv[i], DataSize);
}
}
if(DataSize == 0){
printf("Invalid usage. See `memscan.cc`.\n");
return 1;
}
HWND Window = FindWindowA("TibiaClient", NULL);
if(Window == NULL){
PrintLastError("FindWindowA");
return -1;
}
DWORD ProcessID;
GetWindowThreadProcessId(Window, &ProcessID);
HANDLE Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessID);
if(Process == NULL){
PrintLastError("OpenProcess");
return -1;
}
uintptr BaseAddr = 0;
MEMORY_BASIC_INFORMATION Info;
while(VirtualQueryEx(Process, (void*)BaseAddr, &Info, sizeof(Info)) != 0){
if((Info.State & MEM_COMMIT) && !(Info.Protect & PAGE_NOACCESS) && !(Info.Protect & PAGE_GUARD)){
ScanProcessMemory(Process, (uintptr)Info.BaseAddress, Info.RegionSize, Data, DataSize, ContextWindow);
}
BaseAddr = (uintptr)Info.BaseAddress + Info.RegionSize;
}
CloseHandle(Process);
return 0;
}

7
src/login/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
.vscode
.cache
bin
build
local
config.cfg
compile_commands.json

6
src/login/.upstream.json Normal file
View file

@ -0,0 +1,6 @@
{
"upstream": "https://kaplar.net/tibia/login.git",
"commit": "aef5e1605a25c891b4d648ffc87a6da556077e2e",
"branch": "master",
"vendoredAt": "2026-11-12"
}

43
src/login/CMakeLists.txt Normal file
View file

@ -0,0 +1,43 @@
cmake_minimum_required(VERSION 3.16)
project(login LANGUAGES CXX)
find_package(OpenSSL REQUIRED) # -lcrypto
find_package(Threads REQUIRED) # -pthread
add_executable(login
src/main.cc
src/crypto.cc
src/connections.cc
src/query.cc
src/status.cc
)
target_include_directories(login PRIVATE SRC)
# Original Makefile flags
target_compile_options(login PRIVATE
-fno-strict-aliasing
-Wno-deprecated-declarations
-pedantic -Wall -Wextra
)
# C++11 (Original standard used for the build)
set_target_properties(login PROPERTIES
CXX_STANDARD 11
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
# ENABLE_ASSERTIONS in Debug builds (Makefile DEBUG=1 equivalent)
target_compile_definitions(login PRIVATE
$<$<CONFIG:Debug>:ENABLE_ASSERTIONS=1>
)
target_link_libraries(login PRIVATE
crypto
pthread
)
install(TARGETS login RUNTIME DESTINATION bin)

24
src/login/LICENSE.txt Normal file
View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>

44
src/login/Makefile Normal file
View file

@ -0,0 +1,44 @@
SRCDIR = src
BUILDDIR = build
OUTPUTEXE = login
CXX = g++
CXXFLAGS = -m64 -fno-strict-aliasing -Wno-deprecated-declarations -pedantic -Wall -Wextra -pthread --std=c++11
LFLAGS = -Wl,-t -lcrypto
DEBUG ?= 0
ifneq ($(DEBUG), 0)
CXXFLAGS += -g -Og -DENABLE_ASSERTIONS=1
else
CXXFLAGS += -O2
endif
$(BUILDDIR)/$(OUTPUTEXE): $(BUILDDIR)/crypto.obj $(BUILDDIR)/connections.obj $(BUILDDIR)/main.obj $(BUILDDIR)/query.obj $(BUILDDIR)/status.obj
@mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -o $@ $^ $(LFLAGS)
$(BUILDDIR)/crypto.obj: $(SRCDIR)/crypto.cc $(SRCDIR)/common.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/connections.obj: $(SRCDIR)/connections.cc $(SRCDIR)/common.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/main.obj: $(SRCDIR)/main.cc $(SRCDIR)/common.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/status.obj: $(SRCDIR)/status.cc $(SRCDIR)/common.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/query.obj: $(SRCDIR)/query.cc $(SRCDIR)/common.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
.PHONY: clean
clean:
@rm -rf $(BUILDDIR)

22
src/login/README.md Normal file
View file

@ -0,0 +1,22 @@
# Tibia 7.7 Login Server
This is a simple login server designed to support [Tibia Game Server](https://github.com/fusion32/tibia-game). It also serves OpenTibia XML STATUS requests, although the response may not conform to server list demands of filtering the player number by IP address. Doing so is possible but would require additional data such as idle time and IP address to be included in the online characters table, which then requires changes to the original protocol, which would break compatibility.
## Compiling
Even though there are no Linux specific features being used, it will currently only compile on Linux. It should be simple enough to support compiling on Windows but I don't think it would add any value, considering the querymanager will be running on Linux and that they need to be both on the same machine. The makefile is very simple and should work as long as OpenSSL's libcrypto, which is the only dependency, is installed.
```
make -B DEBUG=0 # rebuild in release mode
make -B DEBUG=1 # rebuild in debug mode
make clean # remove `build` directory
```
### Extra Features (Advanced)
There are also some extra features that can be enabled by appending the following definitions to the `CFLAGS` variable in your `Makefile`. They're completely optional but can be useful in specific scenarios.
- `-DTIBIA772=1`
- Check for client version 7.72 rather than 7.7. The login protocols for both versions are the same, but because the game protocols are not, there is no reason to allow both to go through.
- `-DALLOW_LOCAL_PROXY=1`
- Allow **local** connections to send a proxy header. Ideally we'd have a list of trusted proxies to prevent clients from spoofing their addresses. In reality, it is almost always simpler to have a **local** relay. This is also the only way to get a multi-route proxy without having to drastically change the way connections are handled.
## Running
Similar to the game server, the login server won't boot up if it's not able to connect to the [Query Manager](https://github.com/fusion32/tibia-querymanager). That said, running it is straighforward, requiring only the RSA private key `tibia.pem` and `config.cfg` files to be in the working directory. For testing purposes you could simply compile and launch the application from the shell, but if you plan to run the game server on a dedicated machine, it is recommended that it is setup as a service. There is a *systemd* configuration file (`tibia-login.service`) in the repository that may be used for that purpose. The process is very similar to the one described in the [Game Server](https://github.com/fusion32/tibia-game) so I won't repeat myself here.

19
src/login/config.cfg.dist Normal file
View file

@ -0,0 +1,19 @@
# Service Config
LoginPort = 7171
ConnectionTimeout = 5s
MaxConnections = 10
MaxStatusRecords = 1024
MinStatusInterval = 5m
QueryManagerHost = "127.0.0.1"
QueryManagerPort = 7173
QueryManagerPassword = "a6glaf0c"
# Service Info
StatusWorld = ""
URL = ""
Location = ""
ServerType = "Tibia"
ServerVersion = "7.7"
ClientVersion = "7.7"
MOTD = "Welcome to Tibia!"

589
src/login/src/common.hh Normal file
View file

@ -0,0 +1,589 @@
#ifndef TIBIA_COMMON_HH_
#define TIBIA_COMMON_HH_ 1
#include <ctype.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
#define STATIC_ASSERT(expr) static_assert((expr), "static assertion failed: " #expr)
#define NARRAY(arr) (int)(sizeof(arr) / sizeof(arr[0]))
#define ISPOW2(x) ((x) != 0 && ((x) & ((x) - 1)) == 0)
#define KB(x) ((x) * 1024)
#if defined(_WIN32)
# define OS_WINDOWS 1
#elif defined(__linux__) || defined(__gnu_linux__)
# define OS_LINUX 1
#else
# error "Operating system not supported."
#endif
#if defined(_MSC_VER)
# define COMPILER_MSVC 1
#elif defined(__GNUC__)
# define COMPILER_GCC 1
#elif defined(__clang__)
# define COMPILER_CLANG 1
#endif
#if COMPILER_GCC || COMPILER_CLANG
# define ATTR_FALLTHROUGH __attribute__((fallthrough))
# define ATTR_PRINTF(x, y) __attribute__((format(printf, x, y)))
#else
# define ATTR_FALLTHROUGH
# define ATTR_PRINTF(x, y)
#endif
#if COMPILER_MSVC
# define TRAP() __debugbreak()
#elif COMPILER_GCC || COMPILER_CLANG
# define TRAP() __builtin_trap()
#else
# define TRAP() abort()
#endif
#define ASSERT_ALWAYS(expr) if(!(expr)) { TRAP(); }
#if ENABLE_ASSERTIONS
# define ASSERT(expr) ASSERT_ALWAYS(expr)
#else
# define ASSERT(expr) ((void)(expr))
#endif
#define LOG(...) LogAdd("INFO", __VA_ARGS__)
#define LOG_WARN(...) LogAddVerbose("WARN", __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__)
#define LOG_ERR(...) LogAddVerbose("ERR", __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__)
#define PANIC(...) \
do{ \
LogAddVerbose("PANIC", __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__); \
TRAP(); \
}while(0)
struct TConfig {
// Service Config
int LoginPort;
int ConnectionTimeout;
int MaxConnections;
int MaxStatusRecords;
int MinStatusInterval;
char QueryManagerHost[100];
int QueryManagerPort;
char QueryManagerPassword[30];
// Service Info
char StatusWorld[30];
char Url[100];
char Location[30];
char ServerType[30];
char ServerVersion[30];
char ClientVersion[30];
char Motd[256];
};
extern TConfig g_Config;
void LogAdd(const char *Prefix, const char *Format, ...) ATTR_PRINTF(2, 3);
void LogAddVerbose(const char *Prefix, const char *Function,
const char *File, int Line, const char *Format, ...) ATTR_PRINTF(5, 6);
struct tm GetLocalTime(time_t t);
struct tm GetGMTime(time_t t);
int64 GetClockMonotonicMS(void);
int GetMonotonicUptime(void);
bool StringEmpty(const char *String);
bool StringEq(const char *A, const char *B);
bool StringEqCI(const char *A, const char *B);
bool StringCopy(char *Dest, int DestCapacity, const char *Src);
bool StringCopyN(char *Dest, int DestCapacity, const char *Src, int SrcLength);
bool StringFormat(char *Dest, int DestCapacity, const char *Format, ...) ATTR_PRINTF(3, 4);
bool StringFormatTime(char *Dest, int DestCapacity, const char *Format, int Timestamp);
void StringClear(char *Dest, int DestCapacity);
uint32 StringHash(const char *String);
bool StringEscape(char *Dest, int DestCapacity, const char *Src);
int UTF8SequenceSize(uint8 LeadingByte);
bool UTF8IsTrailingByte(uint8 Byte);
int UTF8EncodedSize(int Codepoint);
int UTF8FindNextLeadingByte(const char *Src, int SrcLength);
int UTF8DecodeOne(const uint8 *Src, int SrcLength, int *OutCodepoint);
int UTF8EncodeOne(uint8 *Dest, int DestCapacity, int Codepoint);
int UTF8ToLatin1(char *Dest, int DestCapacity, const char *Src, int SrcLength);
int Latin1ToUTF8(char *Dest, int DestCapacity, const char *Src, int SrcLength);
bool ParseBoolean(bool *Dest, const char *String);
bool ParseInteger(int *Dest, const char *String);
bool ParseDuration(int *Dest, const char *String);
bool ParseSize(int *Dest, const char *String);
bool ParseString(char *Dest, int DestCapacity, const char *String);
void ParseMotd(char *Dest, int DestCapacity, const char *String);
bool ReadConfig(const char *FileName, TConfig *Config);
// IMPORTANT(fusion): These macros should only be used when `Dest` is a char array
// to simplify the call to `StringCopy` where we'd use `sizeof(Dest)` to determine
// the size of the destination anyways.
#define StringBufCopy(Dest, Src) StringCopy(Dest, sizeof(Dest), Src)
#define StringBufCopyN(Dest, Src, SrcLength) StringCopyN(Dest, sizeof(Dest), Src, SrcLength)
#define StringBufFormat(Dest, ...) StringFormat(Dest, sizeof(Dest), __VA_ARGS__)
#define StringBufFormatTime(Dest, Format, Timestamp) \
StringFormatTime(Dest, sizeof(Dest), Format, Timestamp)
#define StringBufClear(Dest) StringClear(Dest, sizeof(Dest));
#define StringBufEscape(Dest, Src) StringEscape(Dest, sizeof(Dest), Src)
#define ParseStringBuf(Dest, String) ParseString(Dest, sizeof(Dest), String)
// Buffer Utility
//==============================================================================
inline uint8 BufferRead8(const uint8 *Buffer){
return Buffer[0];
}
inline uint16 BufferRead16LE(const uint8 *Buffer){
return (uint16)Buffer[0]
| ((uint16)Buffer[1] << 8);
}
inline uint16 BufferRead16BE(const uint8 *Buffer){
return ((uint16)Buffer[0] << 8)
| (uint16)Buffer[1];
}
inline uint32 BufferRead32LE(const uint8 *Buffer){
return (uint32)Buffer[0]
| ((uint32)Buffer[1] << 8)
| ((uint32)Buffer[2] << 16)
| ((uint32)Buffer[3] << 24);
}
inline uint32 BufferRead32BE(const uint8 *Buffer){
return ((uint32)Buffer[0] << 24)
| ((uint32)Buffer[1] << 16)
| ((uint32)Buffer[2] << 8)
| (uint32)Buffer[3];
}
inline uint64 BufferRead64LE(const uint8 *Buffer){
return (uint64)Buffer[0]
| ((uint64)Buffer[1] << 8)
| ((uint64)Buffer[2] << 16)
| ((uint64)Buffer[3] << 24)
| ((uint64)Buffer[4] << 32)
| ((uint64)Buffer[5] << 40)
| ((uint64)Buffer[6] << 48)
| ((uint64)Buffer[7] << 56);
}
inline uint64 BufferRead64BE(const uint8 *Buffer){
return ((uint64)Buffer[0] << 56)
| ((uint64)Buffer[1] << 48)
| ((uint64)Buffer[2] << 40)
| ((uint64)Buffer[3] << 32)
| ((uint64)Buffer[4] << 24)
| ((uint64)Buffer[5] << 16)
| ((uint64)Buffer[6] << 8)
| (uint64)Buffer[7];
}
inline void BufferWrite8(uint8 *Buffer, uint8 Value){
Buffer[0] = Value;
}
inline void BufferWrite16LE(uint8 *Buffer, uint16 Value){
Buffer[0] = (uint8)(Value >> 0);
Buffer[1] = (uint8)(Value >> 8);
}
inline void BufferWrite16BE(uint8 *Buffer, uint16 Value){
Buffer[0] = (uint8)(Value >> 8);
Buffer[1] = (uint8)(Value >> 0);
}
inline void BufferWrite32LE(uint8 *Buffer, uint32 Value){
Buffer[0] = (uint8)(Value >> 0);
Buffer[1] = (uint8)(Value >> 8);
Buffer[2] = (uint8)(Value >> 16);
Buffer[3] = (uint8)(Value >> 24);
}
inline void BufferWrite32BE(uint8 *Buffer, uint32 Value){
Buffer[0] = (uint8)(Value >> 24);
Buffer[1] = (uint8)(Value >> 16);
Buffer[2] = (uint8)(Value >> 8);
Buffer[3] = (uint8)(Value >> 0);
}
inline void BufferWrite64LE(uint8 *Buffer, uint64 Value){
Buffer[0] = (uint8)(Value >> 0);
Buffer[1] = (uint8)(Value >> 8);
Buffer[2] = (uint8)(Value >> 16);
Buffer[3] = (uint8)(Value >> 24);
Buffer[4] = (uint8)(Value >> 32);
Buffer[5] = (uint8)(Value >> 40);
Buffer[6] = (uint8)(Value >> 48);
Buffer[7] = (uint8)(Value >> 56);
}
inline void BufferWrite64BE(uint8 *Buffer, uint64 Value){
Buffer[0] = (uint8)(Value >> 56);
Buffer[1] = (uint8)(Value >> 48);
Buffer[2] = (uint8)(Value >> 40);
Buffer[3] = (uint8)(Value >> 32);
Buffer[4] = (uint8)(Value >> 24);
Buffer[5] = (uint8)(Value >> 16);
Buffer[6] = (uint8)(Value >> 8);
Buffer[7] = (uint8)(Value >> 0);
}
struct TReadBuffer{
uint8 *Buffer;
int Size;
int Position;
TReadBuffer(void) : TReadBuffer(NULL, 0) {}
TReadBuffer(uint8 *Buffer, int Size)
: Buffer(Buffer), Size(Size), Position(0) {}
bool CanRead(int Bytes){
return (this->Position + Bytes) <= this->Size;
}
bool Overflowed(void){
return this->Position > this->Size;
}
bool ReadFlag(void){
return this->Read8() != 0x00;
}
uint8 Read8(void){
uint8 Result = 0;
if(this->CanRead(1)){
Result = BufferRead8(this->Buffer + this->Position);
}
this->Position += 1;
return Result;
}
uint16 Read16(void){
uint16 Result = 0;
if(this->CanRead(2)){
Result = BufferRead16LE(this->Buffer + this->Position);
}
this->Position += 2;
return Result;
}
uint16 Read16BE(void){
uint16 Result = 0;
if(this->CanRead(2)){
Result = BufferRead16BE(this->Buffer + this->Position);
}
this->Position += 2;
return Result;
}
uint32 Read32(void){
uint32 Result = 0;
if(this->CanRead(4)){
Result = BufferRead32LE(this->Buffer + this->Position);
}
this->Position += 4;
return Result;
}
uint32 Read32BE(void){
uint32 Result = 0;
if(this->CanRead(4)){
Result = BufferRead32BE(this->Buffer + this->Position);
}
this->Position += 4;
return Result;
}
#if CLIENT_ENCODING_UTF8
void ReadString(char *Dest, int DestCapacity){
int Length = (int)this->Read16();
if(Length == 0xFFFF){
Length = (int)this->Read32();
}
if(Dest != NULL && DestCapacity > 0){
int Written = 0;
if(this->CanRead(Length) && Length < DestCapacity){
memcpy(Dest, this->Buffer + this->Position, Length);
Written = Length;
}
memset((Dest + Written), 0, (DestCapacity - Written));
}
this->Position += Length;
}
#else
void ReadString(char *Dest, int DestCapacity){
int Length = (int)this->Read16();
if(Length == 0xFFFF){
Length = (int)this->Read32();
}
if(Dest != NULL && DestCapacity > 0){
int Written = 0;
if(this->CanRead(Length)){
const char *Src = (const char*)(this->Buffer + this->Position);
Written = Latin1ToUTF8(Dest, DestCapacity, Src, Length);
if(Written >= DestCapacity){
Written = 0;
}
}
memset((Dest + Written), 0, (DestCapacity - Written));
}
this->Position += Length;
}
#endif
void ReadBytes(uint8 *Buffer, int Count){
if(this->CanRead(Count)){
memcpy(Buffer, this->Buffer + this->Position, Count);
}
this->Position += Count;
}
};
struct TWriteBuffer{
uint8 *Buffer;
int Size;
int Position;
TWriteBuffer(void) : TWriteBuffer(NULL, 0) {}
TWriteBuffer(uint8 *Buffer, int Size)
: Buffer(Buffer), Size(Size), Position(0) {}
bool CanWrite(int Bytes){
return (this->Position + Bytes) <= this->Size;
}
bool Overflowed(void){
return this->Position > this->Size;
}
void WriteFlag(bool Value){
this->Write8(Value ? 0x01 : 0x00);
}
void Write8(uint8 Value){
if(this->CanWrite(1)){
BufferWrite8(this->Buffer + this->Position, Value);
}
this->Position += 1;
}
void Write16(uint16 Value){
if(this->CanWrite(2)){
BufferWrite16LE(this->Buffer + this->Position, Value);
}
this->Position += 2;
}
void Write16BE(uint16 Value){
if(this->CanWrite(2)){
BufferWrite16BE(this->Buffer + this->Position, Value);
}
this->Position += 2;
}
void Write32(uint32 Value){
if(this->CanWrite(4)){
BufferWrite32LE(this->Buffer + this->Position, Value);
}
this->Position += 4;
}
void Write32BE(uint32 Value){
if(this->CanWrite(4)){
BufferWrite32BE(this->Buffer + this->Position, Value);
}
this->Position += 4;
}
#if CLIENT_ENCODING_UTF8
void WriteString(const char *String){
int StringLength = 0;
if(String != NULL){
StringLength = (int)strlen(String);
}
if(StringLength < 0xFFFF){
this->Write16((uint16)StringLength);
}else{
this->Write16(0xFFFF);
this->Write32((uint32)StringLength);
}
if(StringLength > 0 && this->CanWrite(StringLength)){
memcpy(this->Buffer + this->Position, String, StringLength);
}
this->Position += StringLength;
}
#else
void WriteString(const char *String){
int StringLength = 0;
int OutputLength = 0;
if(String != NULL){
StringLength = (int)strlen(String);
OutputLength = UTF8ToLatin1(NULL, 0, String, (int)strlen(String));
}
if(OutputLength < 0xFFFF){
this->Write16((uint16)OutputLength);
}else{
this->Write16(0xFFFF);
this->Write32((uint32)OutputLength);
}
if(OutputLength > 0 && this->CanWrite(OutputLength)){
int Written = UTF8ToLatin1((char*)(this->Buffer + this->Position),
(this->Size - this->Position), String, StringLength);
ASSERT(Written == OutputLength);
}
this->Position += OutputLength;
}
#endif
void Rewrite16(int Position, uint16 Value){
if((Position + 2) <= this->Position && !this->Overflowed()){
BufferWrite16LE(this->Buffer + Position, Value);
}
}
void Insert32(int Position, uint32 Value){
if(Position <= this->Position){
if(this->CanWrite(4)){
memmove(this->Buffer + Position + 4,
this->Buffer + Position,
this->Position - Position);
BufferWrite32LE(this->Buffer + Position, Value);
}
this->Position += 4;
}
}
};
// crypto.cc
//==============================================================================
typedef void RSAKey;
RSAKey *RSALoadPEM(const char *FileName);
void RSAFree(RSAKey *Key);
bool RSADecrypt(RSAKey *Key, uint8 *Data, int Size);
void XTEAEncrypt(const uint32 *Key, uint8 *Data, int Size);
void XTEADecrypt(const uint32 *Key, uint8 *Data, int Size);
// query.cc
//==============================================================================
enum {
APPLICATION_TYPE_GAME = 1,
APPLICATION_TYPE_LOGIN = 2,
APPLICATION_TYPE_WEB = 3,
};
enum {
QUERY_STATUS_OK = 0,
QUERY_STATUS_ERROR = 1,
QUERY_STATUS_FAILED = 3,
};
enum {
QUERY_LOGIN = 0,
QUERY_LOGIN_ACCOUNT = 11,
QUERY_GET_WORLDS = 150,
};
struct TQueryManagerConnection{
int Socket;
};
struct TCharacterLoginData{
char Name[30];
char WorldName[30];
int WorldAddress;
int WorldPort;
};
struct TWorld {
char Name[30];
int Type;
int NumPlayers;
int MaxPlayers;
int OnlinePeak;
int OnlinePeakTimestamp;
int LastStartup;
int LastShutdown;
};
bool Connect(TQueryManagerConnection *Connection);
void Disconnect(TQueryManagerConnection *Connection);
bool IsConnected(TQueryManagerConnection *Connection);
TWriteBuffer PrepareQuery(int QueryType, uint8 *Buffer, int BufferSize);
int ExecuteQuery(TQueryManagerConnection *Connection, bool AutoReconnect,
TWriteBuffer *WriteBuffer, TReadBuffer *OutReadBuffer);
int LoginAccount(int AccountID, const char *Password, const char *IPAddress,
int MaxCharacters, int *NumCharacters, TCharacterLoginData *Characters,
int *PremiumDays);
int GetWorld(const char *WorldName, TWorld *OutWorld);
bool InitQuery(void);
void ExitQuery(void);
// status.cc
//==============================================================================
const char *GetStatusString(void);
// connections.cc
//==============================================================================
enum ConnectionState {
CONNECTION_FREE = 0,
CONNECTION_READING = 1,
CONNECTION_PROCESSING = 2,
CONNECTION_WRITING = 3,
};
struct TConnection {
ConnectionState State;
int Socket;
int IPAddress;
int RemotePort;
int StartTime;
int RWSize;
int RWPosition;
#if ALLOW_LOCAL_PROXY
bool ReadingProxyHeader;
#endif
uint32 RandomSeed;
uint32 XTEA[4];
char RemoteAddress[32];
uint8 Buffer[KB(2)];
};
struct TStatusRecord {
int IPAddress;
int Timestamp;
};
void ProcessConnections(void);
bool InitConnections(void);
void ExitConnections(void);
void ProcessLoginRequest(TConnection *Connection);
void ProcessStatusRequest(TConnection *Connection);
#endif //TIBIA_COMMON_H_

View file

@ -0,0 +1,784 @@
#include "common.hh"
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#if TIBIA772
static const int TERMINALVERSION[] = {772, 772, 772};
#else
static const int TERMINALVERSION[] = {770, 770, 770};
#endif
static RSAKey *g_PrivateKey;
static int g_Listener = -1;
static TConnection *g_Connections;
static int g_MaxConnections;
static TStatusRecord *g_StatusRecords;
static int g_MaxStatusRecords;
// Connection Handling
//==============================================================================
static int ListenerBind(uint16 Port){
int Socket = socket(AF_INET, SOCK_STREAM, 0);
if(Socket == -1){
LOG_ERR("Failed to create listener socket: (%d) %s", errno, strerrordesc_np(errno));
return -1;
}
int ReuseAddr = 1;
if(setsockopt(Socket, SOL_SOCKET, SO_REUSEADDR, &ReuseAddr, sizeof(ReuseAddr)) == -1){
LOG_ERR("Failed to set SO_REUSADDR: (%d) %s", errno, strerrordesc_np(errno));
close(Socket);
return -1;
}
int Flags = fcntl(Socket, F_GETFL);
if(Flags == -1){
LOG_ERR("Failed to get socket flags: (%d) %s", errno, strerrordesc_np(errno));
close(Socket);
return -1;
}
if(fcntl(Socket, F_SETFL, Flags | O_NONBLOCK) == -1){
LOG_ERR("Failed to set socket flags: (%d) %s", errno, strerrordesc_np(errno));
close(Socket);
return -1;
}
sockaddr_in Addr = {};
Addr.sin_family = AF_INET;
Addr.sin_port = htons(Port);
Addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(Socket, (sockaddr*)&Addr, sizeof(Addr)) == -1){
LOG_ERR("Failed to bind socket to port %d: (%d) %s", Port, errno, strerrordesc_np(errno));
close(Socket);
return -1;
}
if(listen(Socket, 128) == -1){
LOG_ERR("Failed to listen to port %d: (%d) %s", Port, errno, strerrordesc_np(errno));
close(Socket);
return -1;
}
return Socket;
}
static int ListenerAccept(int Listener, uint32 *OutAddr, uint16 *OutPort){
while(true){
sockaddr_in SocketAddr = {};
socklen_t SocketAddrLen = sizeof(SocketAddr);
int Socket = accept(Listener, (sockaddr*)&SocketAddr, &SocketAddrLen);
if(Socket == -1){
if(errno != EAGAIN){
LOG_ERR("Failed to accept connection: (%d) %s", errno, strerrordesc_np(errno));
}
return -1;
}
int Flags = fcntl(Socket, F_GETFL);
if(Flags == -1){
LOG_ERR("Failed to get socket flags: (%d) %s", errno, strerrordesc_np(errno));
close(Socket);
continue;
}
if(fcntl(Socket, F_SETFL, Flags | O_NONBLOCK) == -1){
LOG_ERR("Failed to set socket flags: (%d) %s", errno, strerrordesc_np(errno));
close(Socket);
continue;
}
if(OutAddr){
*OutAddr = ntohl(SocketAddr.sin_addr.s_addr);
}
if(OutPort){
*OutPort = ntohs(SocketAddr.sin_port);
}
return Socket;
}
}
static void CloseConnection(TConnection *Connection){
if(Connection->Socket != -1){
close(Connection->Socket);
Connection->Socket = -1;
}
}
static TConnection *AssignConnection(int Socket, uint32 Addr, uint16 Port){
int ConnectionIndex = -1;
for(int i = 0; i < g_Config.MaxConnections; i += 1){
if(g_Connections[i].State == CONNECTION_FREE){
ConnectionIndex = i;
break;
}
}
TConnection *Connection = NULL;
if(ConnectionIndex != -1){
Connection = &g_Connections[ConnectionIndex];
Connection->State = CONNECTION_READING;
Connection->Socket = Socket;
Connection->IPAddress = (int)Addr;
Connection->RemotePort = (int)Port;
Connection->StartTime = GetMonotonicUptime();
Connection->RandomSeed = (uint32)rand();
StringBufFormat(Connection->RemoteAddress,
"%d.%d.%d.%d:%d",
((Connection->IPAddress >> 24) & 0xFF),
((Connection->IPAddress >> 16) & 0xFF),
((Connection->IPAddress >> 8) & 0xFF),
((Connection->IPAddress >> 0) & 0xFF),
Connection->RemotePort);
LOG("Connection %s assigned to slot %d",
Connection->RemoteAddress, ConnectionIndex);
}
return Connection;
}
static void ReleaseConnection(TConnection *Connection){
if(Connection->State != CONNECTION_FREE){
LOG("Connection %s released", Connection->RemoteAddress);
CloseConnection(Connection);
memset(Connection, 0, sizeof(TConnection));
Connection->State = CONNECTION_FREE;
}
}
static void CheckConnectionInput(TConnection *Connection, int Events){
if(Connection->Socket == -1 || (Events & POLLIN) == 0){
return;
}
if(Connection->State != CONNECTION_READING){
LOG_ERR("Connection %s (State: %d) sending out-of-order data",
Connection->RemoteAddress, Connection->State);
CloseConnection(Connection);
return;
}
while(true){
int ReadSize = (Connection->RWSize > 0 ? Connection->RWSize : 2);
int BytesRead = (int)read(Connection->Socket,
(Connection->Buffer + Connection->RWPosition),
(ReadSize - Connection->RWPosition));
if(BytesRead == -1){
if(errno != EAGAIN){
// NOTE(fusion): Connection error.
CloseConnection(Connection);
}
break;
}else if(BytesRead == 0){
// NOTE(fusion): Graceful close.
CloseConnection(Connection);
break;
}
Connection->RWPosition += BytesRead;
if(Connection->RWPosition >= ReadSize){
ASSERT(Connection->RWPosition == ReadSize);
if(Connection->RWSize == 0){
#if ALLOW_LOCAL_PROXY
if(Connection->Buffer[0] == 0x0D && Connection->Buffer[1] == 0x0A){
ASSERT(sizeof(Connection->Buffer) >= 28);
Connection->RWSize = 28;
Connection->ReadingProxyHeader = true;
}else if(Connection->Buffer[0] == 0xD9 && Connection->Buffer[1] == 0xFF){
ASSERT(sizeof(Connection->Buffer) >= 6);
Connection->RWSize = 6;
Connection->ReadingProxyHeader = true;
}else
#endif
{
int PayloadSize = (int)BufferRead16LE(Connection->Buffer);
if(PayloadSize <= 0 || PayloadSize > (int)sizeof(Connection->Buffer)){
CloseConnection(Connection);
break;
}
Connection->RWSize = PayloadSize;
Connection->RWPosition = 0;
}
}
#if ALLOW_LOCAL_PROXY
else if(Connection->ReadingProxyHeader){
uint8 *SourceAddr = NULL;
if(Connection->Buffer[0] == 0x0D && Connection->Buffer[1] == 0x0A){
ASSERT(ReadSize == 28);
// NOTE(fusion): HAProxy-V2 header.
static const uint8_t HAProxyV2Signature[] = {
0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51,
0x55, 0x49, 0x54, 0x0A,
};
if(memcmp(Connection->Buffer, HAProxyV2Signature, 12) == 0){
SourceAddr = Connection->Buffer + 16;
}
}else if(Connection->Buffer[0] == 0xD9 && Connection->Buffer[1] == 0xFF){
// NOTE(fusion): Our custom proxy.
ASSERT(ReadSize == 6);
SourceAddr = Connection->Buffer + 2;
}
if(SourceAddr == NULL || Connection->IPAddress != INADDR_LOOPBACK){
ASSERT(ReadSize >= 2);
if(SourceAddr == NULL){
LOG_ERR("Invalid proxy header (%02X, %02X) from host %s",
(int)Connection->Buffer[0], (int)Connection->Buffer[1],
Connection->RemoteAddress);
}
if(Connection->IPAddress != INADDR_LOOPBACK){
LOG_ERR("Received proxy header (%02X, %02X) from unknown host %s",
(int)Connection->Buffer[0], (int)Connection->Buffer[1],
Connection->RemoteAddress);
}
CloseConnection(Connection);
break;
}
LOG("Connection proxy header %s -> %d.%d.%d.%d:%d",
Connection->RemoteAddress,
(int)SourceAddr[0], (int)SourceAddr[1],
(int)SourceAddr[2], (int)SourceAddr[3],
Connection->RemotePort);
Connection->IPAddress = BufferRead32BE(SourceAddr);
StringBufFormat(Connection->RemoteAddress,
"%d.%d.%d.%d:%d",
(int)SourceAddr[0], (int)SourceAddr[1],
(int)SourceAddr[2], (int)SourceAddr[3],
Connection->RemotePort);
Connection->RWSize = 0;
Connection->RWPosition = 0;
Connection->ReadingProxyHeader = false;
}
#endif
else{
Connection->State = CONNECTION_PROCESSING;
break;
}
}
}
}
static void CheckConnectionRequest(TConnection *Connection){
if(Connection->Socket == -1){
return;
}
if(Connection->State != CONNECTION_PROCESSING){
return;
}
// PARANOID(fusion): A non-empty payload is guaranteed, due to how we parse
// input in `CheckConnectionInput` just above.
ASSERT(Connection->RWSize > 0);
int Command = Connection->Buffer[0];
if(Command == 1){
ProcessLoginRequest(Connection);
}else if(Command == 255){
ProcessStatusRequest(Connection);
}else{
LOG_ERR("Invalid command %d from %s (expected 1 or 255)",
Command, Connection->RemoteAddress);
CloseConnection(Connection);
}
}
static void CheckConnectionOutput(TConnection *Connection, int Events){
// NOTE(fusion): We're only polling `POLLOUT` when the connection is WRITING,
// but we want to allow requests to complete in a single cycle, so we always
// check for output if the connection is WRITING.
(void)Events;
if(Connection->Socket == -1){
return;
}
if(Connection->State != CONNECTION_WRITING){
return;
}
while(true){
int BytesWritten = (int)write(Connection->Socket,
(Connection->Buffer + Connection->RWPosition),
(Connection->RWSize - Connection->RWPosition));
if(BytesWritten == -1){
if(errno != EAGAIN){
CloseConnection(Connection);
}
break;
}
// NOTE(fusion): Both login and status protocols will serve a single
// request so we always close the connection after it is served.
Connection->RWPosition += BytesWritten;
if(Connection->RWPosition >= Connection->RWSize){
ASSERT(Connection->RWPosition == Connection->RWSize);
CloseConnection(Connection);
break;
}
}
}
static void CheckConnection(TConnection *Connection, int Events){
ASSERT((Events & POLLNVAL) == 0);
if((Events & (POLLERR | POLLHUP)) != 0){
CloseConnection(Connection);
}
if(g_Config.ConnectionTimeout > 0){
int ElapsedTime = GetMonotonicUptime() - Connection->StartTime;
if(ElapsedTime >= g_Config.ConnectionTimeout){
LOG_WARN("Connection %s TIMEDOUT (ElapsedTime: %ds, Timeout: %ds)",
Connection->RemoteAddress, ElapsedTime, g_Config.ConnectionTimeout);
CloseConnection(Connection);
}
}
if(Connection->Socket == -1){
ReleaseConnection(Connection);
}
}
static void AcceptConnections(int Events){
ASSERT(g_Listener != -1);
if((Events & POLLIN) == 0){
return;
}
while(true){
uint32 Addr;
uint16 Port;
int Socket = ListenerAccept(g_Listener, &Addr, &Port);
if(Socket == -1){
break;
}
if(AssignConnection(Socket, Addr, Port) == NULL){
LOG_ERR("Rejecting connection %08X:%d:"
" max number of connections reached (%d)",
Addr, Port, g_Config.MaxConnections);
close(Socket);
}
}
}
void ProcessConnections(void){
int NumFds = 0;
int MaxFds = g_MaxConnections + 1;
pollfd *Fds = (pollfd*)alloca(MaxFds * sizeof(pollfd));
int *ConnectionIndices = (int*)alloca(MaxFds * sizeof(int));
if(g_Listener != -1){
Fds[NumFds].fd = g_Listener;
Fds[NumFds].events = POLLIN;
Fds[NumFds].revents = 0;
ConnectionIndices[NumFds] = -1;
NumFds += 1;
}
for(int i = 0; i < g_Config.MaxConnections; i += 1){
if(g_Connections[i].State == CONNECTION_FREE){
continue;
}
Fds[NumFds].fd = g_Connections[i].Socket;
Fds[NumFds].events = POLLIN;
if(g_Connections[i].State == CONNECTION_WRITING){
Fds[NumFds].events |= POLLOUT;
}
Fds[NumFds].revents = 0;
ConnectionIndices[NumFds] = i;
NumFds += 1;
}
// NOTE(fusion): Block for 1 second at most, so we can properly timeout
// idle connections.
ASSERT(NumFds > 0);
int NumEvents = poll(Fds, NumFds, 1000);
if(NumEvents == -1){
if(errno != ETIMEDOUT && errno != EINTR){
LOG_ERR("Failed to poll connections: (%d) %s",
errno, strerrordesc_np(errno));
}
return;
}
// NOTE(fusion): Process connections.
for(int i = 0; i < NumFds; i += 1){
int Index = ConnectionIndices[i];
int Events = (int)Fds[i].revents;
if(Index >= 0 && Index < g_Config.MaxConnections){
TConnection *Connection = &g_Connections[Index];
CheckConnectionInput(Connection, Events);
CheckConnectionRequest(Connection);
CheckConnectionOutput(Connection, Events);
CheckConnection(Connection, Events);
}else if(Index == -1 && Fds[i].fd == g_Listener){
AcceptConnections(Events);
}else{
LOG_ERR("Unknown connection index %d", Index);
}
}
}
bool InitConnections(void){
ASSERT(g_PrivateKey == NULL);
ASSERT(g_Listener == -1);
ASSERT(g_Connections == NULL);
ASSERT(g_StatusRecords == NULL);
g_PrivateKey = RSALoadPEM("tibia.pem");
if(g_PrivateKey == NULL){
LOG_ERR("Failed to load RSA key");
return false;
}
g_Listener = ListenerBind((uint16)g_Config.LoginPort);
if(g_Listener == -1){
LOG_ERR("Failed to bind listener to port %d", g_Config.LoginPort);
return false;
}
g_MaxConnections = g_Config.MaxConnections;
g_Connections = (TConnection*)calloc(
g_MaxConnections, sizeof(TConnection));
for(int i = 0; i < g_MaxConnections; i += 1){
g_Connections[i].State = CONNECTION_FREE;
}
g_MaxStatusRecords = g_Config.MaxStatusRecords;
g_StatusRecords = (TStatusRecord*)calloc(
g_MaxStatusRecords, sizeof(TStatusRecord));
return true;
}
void ExitConnections(void){
if(g_PrivateKey != NULL){
RSAFree(g_PrivateKey);
g_PrivateKey = NULL;
}
if(g_Listener != -1){
close(g_Listener);
g_Listener = -1;
}
if(g_Connections != NULL){
for(int i = 0; i < g_MaxConnections; i += 1){
ReleaseConnection(&g_Connections[i]);
}
free(g_Connections);
g_Connections = NULL;
}
if(g_StatusRecords != NULL){
free(g_StatusRecords);
g_StatusRecords = NULL;
}
}
// Login Request
//==============================================================================
static TWriteBuffer PrepareXTEAResponse(TConnection *Connection){
if(Connection->State != CONNECTION_PROCESSING){
LOG_ERR("Connection %s is not PROCESSING (State: %d)",
Connection->RemoteAddress, Connection->State);
CloseConnection(Connection);
return TWriteBuffer(NULL, 0);
}
TWriteBuffer WriteBuffer(Connection->Buffer, sizeof(Connection->Buffer));
WriteBuffer.Write16(0); // Encrypted Size
WriteBuffer.Write16(0); // Data Size
return WriteBuffer;
}
static void SendXTEAResponse(TConnection *Connection, TWriteBuffer *WriteBuffer){
if(Connection->State != CONNECTION_PROCESSING){
LOG_ERR("Connection %s is not PROCESSING (State: %d)",
Connection->RemoteAddress, Connection->State);
CloseConnection(Connection);
return;
}
ASSERT(WriteBuffer != NULL
&& WriteBuffer->Buffer == Connection->Buffer
&& WriteBuffer->Size == sizeof(Connection->Buffer)
&& WriteBuffer->Position > 4);
int DataSize = WriteBuffer->Position - 4;
int EncryptedSize = WriteBuffer->Position - 2;
while((EncryptedSize % 8) != 0){
WriteBuffer->Write8(rand_r(&Connection->RandomSeed));
EncryptedSize += 1;
}
if(WriteBuffer->Overflowed()){
LOG_ERR("Write buffer overflowed when writing response to %s",
Connection->RemoteAddress);
CloseConnection(Connection);
return;
}
WriteBuffer->Rewrite16(0, EncryptedSize);
WriteBuffer->Rewrite16(2, DataSize);
XTEAEncrypt(Connection->XTEA,
WriteBuffer->Buffer + 2,
WriteBuffer->Position - 2);
Connection->State = CONNECTION_WRITING;
Connection->RWSize = WriteBuffer->Position;
Connection->RWPosition = 0;
}
static void SendLoginError(TConnection *Connection, const char *Message){
TWriteBuffer WriteBuffer = PrepareXTEAResponse(Connection);
WriteBuffer.Write8(10); // LOGIN_ERROR
WriteBuffer.WriteString(Message);
SendXTEAResponse(Connection, &WriteBuffer);
}
static void SendCharacterList(TConnection *Connection, int NumCharacters,
TCharacterLoginData *Characters, int PremiumDays){
TWriteBuffer WriteBuffer = PrepareXTEAResponse(Connection);
if(g_Config.Motd[0] != 0){
WriteBuffer.Write8(20); // MOTD
WriteBuffer.WriteString(g_Config.Motd);
}
WriteBuffer.Write8(100); // CHARACTER_LIST
if(NumCharacters > UINT8_MAX){
NumCharacters = UINT8_MAX;
}
WriteBuffer.Write8(NumCharacters);
for(int i = 0; i < NumCharacters; i += 1){
WriteBuffer.WriteString(Characters[i].Name);
WriteBuffer.WriteString(Characters[i].WorldName);
WriteBuffer.Write32BE((uint32)Characters[i].WorldAddress);
WriteBuffer.Write16((uint16)Characters[i].WorldPort);
}
WriteBuffer.Write16((uint16)PremiumDays);
SendXTEAResponse(Connection, &WriteBuffer);
}
void ProcessLoginRequest(TConnection *Connection){
if(Connection->RWSize != 145){
LOG_ERR("Invalid login request size from %s (expected 145, got %d)",
Connection->RemoteAddress, Connection->RWSize);
CloseConnection(Connection);
return;
}
TReadBuffer ReadBuffer(Connection->Buffer, Connection->RWSize);
ReadBuffer.Read8(); // always 1 for a login request
int TerminalType = ReadBuffer.Read16();
int TerminalVersion = ReadBuffer.Read16();
ReadBuffer.Read32(); // DATSIGNATURE
ReadBuffer.Read32(); // SPRSIGNATURE
ReadBuffer.Read32(); // PICSIGNATURE
uint8 AsymmetricData[128];
ReadBuffer.ReadBytes(AsymmetricData, sizeof(AsymmetricData));
if(ReadBuffer.Overflowed()){
LOG_ERR("Input buffer overflowed while reading login command from %s",
Connection->RemoteAddress);
CloseConnection(Connection);
return;
}
// IMPORTANT(fusion): Without a checksum, there is no way of validating
// the asymmetric data. The best we can do is to verify that the first
// plaintext byte is ZERO, but that alone isn't enough.
if(!RSADecrypt(g_PrivateKey, AsymmetricData, sizeof(AsymmetricData)) || AsymmetricData[0] != 0){
LOG_ERR("Failed to decrypt asymmetric data from %s",
Connection->RemoteAddress);
CloseConnection(Connection);
return;
}
ReadBuffer = TReadBuffer(AsymmetricData, sizeof(AsymmetricData));
ReadBuffer.Read8(); // always zero
Connection->XTEA[0] = ReadBuffer.Read32();
Connection->XTEA[1] = ReadBuffer.Read32();
Connection->XTEA[2] = ReadBuffer.Read32();
Connection->XTEA[3] = ReadBuffer.Read32();
char Password[30];
int AccountID = ReadBuffer.Read32();
ReadBuffer.ReadString(Password, sizeof(Password));
if(ReadBuffer.Overflowed()){
LOG_ERR("Malformed asymmetric data from %s", Connection->RemoteAddress);
CloseConnection(Connection);
return;
}
if(AccountID <= 0){
SendLoginError(Connection, "You must enter an account number.");
return;
}
if(TerminalType < 0 || TerminalType >= NARRAY(TERMINALVERSION)
|| TERMINALVERSION[TerminalType] != TerminalVersion){
SendLoginError(Connection,
"Your terminal version is too old.\n"
"Please get a new version at\n"
"http://www.tibia.com.");
return;
}
char IPString[16];
StringBufFormat(IPString, "%d.%d.%d.%d",
((Connection->IPAddress >> 24) & 0xFF),
((Connection->IPAddress >> 16) & 0xFF),
((Connection->IPAddress >> 8) & 0xFF),
((Connection->IPAddress >> 0) & 0xFF));
int NumCharacters = 0;
int PremiumDays = 0;
TCharacterLoginData Characters[50];
int LoginCode = LoginAccount(AccountID, Password, IPString,
NARRAY(Characters), &NumCharacters, Characters, &PremiumDays);
switch(LoginCode){
case 0:{
SendCharacterList(Connection, NumCharacters, Characters, PremiumDays);
break;
}
case 1: // Invalid account number
case 2:{ // Invalid password
SendLoginError(Connection, "Accountnumber or password is not correct.");
break;
}
case 3:{
SendLoginError(Connection, "Account disabled for five minutes. Please wait.");
break;
}
case 4:{
SendLoginError(Connection, "IP address blocked for 30 minutes. Please wait.");
break;
}
case 5:{
SendLoginError(Connection, "Your account is banished.");
break;
}
case 6:{
SendLoginError(Connection, "Your IP address is banished.");
break;
}
default:{
if(LoginCode != -1){
LOG_ERR("Invalid login code %d", LoginCode);
}
SendLoginError(Connection, "Internal error, closing connection.");
break;
}
}
}
// Status Request
//==============================================================================
static bool AllowStatusRequest(int IPAddress){
TStatusRecord *Record = NULL;
int LeastRecentlyUsedIndex = 0;
int LeastRecentlyUsedTime = g_StatusRecords[0].Timestamp;
int TimeNow = GetMonotonicUptime();
for(int i = 0; i < g_MaxStatusRecords; i += 1){
if(g_StatusRecords[i].Timestamp < LeastRecentlyUsedTime){
LeastRecentlyUsedIndex = i;
LeastRecentlyUsedTime = g_StatusRecords[i].Timestamp;
}
if(g_StatusRecords[i].IPAddress == IPAddress){
Record = &g_StatusRecords[i];
break;
}
}
bool Result = false;
if(Record == NULL){
Record = &g_StatusRecords[LeastRecentlyUsedIndex];
Record->IPAddress = IPAddress;
Record->Timestamp = TimeNow;
Result = true;
}else if((TimeNow - Record->Timestamp) >= g_Config.MinStatusInterval){
Record->Timestamp = TimeNow;
Result = true;
}
return Result;
}
static void SendStatusString(TConnection *Connection, const char *StatusString){
if(Connection->State != CONNECTION_PROCESSING){
LOG_ERR("Connection %s is not PROCESSING (State: %d)",
Connection->RemoteAddress, Connection->State);
CloseConnection(Connection);
return;
}
int Length = (int)strlen(StatusString);
if(Length > (int)sizeof(Connection->Buffer)){
Length = (int)sizeof(Connection->Buffer);
}
Connection->RWSize = Length;
Connection->RWPosition = 0;
memcpy(Connection->Buffer, StatusString, Length);
Connection->State = CONNECTION_WRITING;
}
void ProcessStatusRequest(TConnection *Connection){
if(!AllowStatusRequest(Connection->IPAddress)){
LOG_ERR("Too many status requests from %s", Connection->RemoteAddress);
CloseConnection(Connection);
return;
}
TReadBuffer ReadBuffer(Connection->Buffer, Connection->RWSize);
ReadBuffer.Read8(); // always 255 for a status request
int Format = (int)ReadBuffer.Read8();
if(Format == 255){ // XML
char Request[5] = {};
ReadBuffer.ReadBytes((uint8*)Request, 4);
if(StringEqCI(Request, "info")){
const char *StatusString = GetStatusString();
SendStatusString(Connection, StatusString);
}else{
LOG_WARN("Invalid status request \"%s\" from %s",
Request, Connection->RemoteAddress);
CloseConnection(Connection);
}
}else{
LOG_WARN("Invalid status format %d from %s",
Format, Connection->RemoteAddress);
CloseConnection(Connection);
}
}

104
src/login/src/crypto.cc Normal file
View file

@ -0,0 +1,104 @@
#include "common.hh"
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
static void DumpOpenSSLErrors(const char *Where, const char *What){
LOG_ERR("OpenSSL error(s) while executing %s at %s:", What, Where);
ERR_print_errors_cb(
[](const char *str, size_t len, void *u) -> int {
(void)u;
// NOTE(fusion): These error strings already have trailing newlines,
// for whatever reason.
if(len > 0 && str[len - 1] == '\n'){
len -= 1;
}
if(len > 0){
LOG_ERR("> %.*s", (int)len, str);
}
return 1;
}, NULL);
}
RSAKey *RSALoadPEM(const char *FileName){
FILE *File = fopen(FileName, "rb");
if(File == NULL){
LOG_ERR("Failed to open \"%s\"", FileName);
return NULL;
}
RSA *Key = PEM_read_RSAPrivateKey(File, NULL, NULL, NULL);
fclose(File);
if(Key == NULL){
LOG_ERR("Failed to read key from \"%s\"", FileName);
DumpOpenSSLErrors("RSALoadPem", "PEM_read_PrivateKey");
}
return (RSAKey*)Key;
}
void RSAFree(RSAKey *Key){
RSA_free((RSA*)Key);
}
bool RSADecrypt(RSAKey *Key, uint8 *Data, int Size){
ASSERT(Data != NULL && Size > 0);
if(Key == NULL){
LOG_ERR("Key not initialized");
return false;
}
if(Size != RSA_size((RSA*)Key)){
LOG_ERR("Invalid data size %d (expected %d)", Size, RSA_size((RSA*)Key));
return false;
}
if(RSA_private_decrypt(Size, Data, Data, (RSA*)Key, RSA_NO_PADDING) == -1){
DumpOpenSSLErrors("RSADecrypt", "RSA_private_decrypt");
return false;
}
return true;
}
void XTEAEncrypt(const uint32 *Key, uint8 *Data, int Size){
ASSERT(Key != NULL);
while(Size >= 8){
uint32 Sum = 0x00000000UL;
uint32 Delta = 0x9E3779B9UL;
uint32 V0 = BufferRead32LE(&Data[0]);
uint32 V1 = BufferRead32LE(&Data[4]);
for(int i = 0; i < 32; i += 1){
V0 += (((V1 << 4) ^ (V1 >> 5)) + V1) ^ (Sum + Key[Sum & 3]);
Sum += Delta;
V1 += (((V0 << 4) ^ (V0 >> 5)) + V0) ^ (Sum + Key[(Sum >> 11) & 3]);
}
BufferWrite32LE(&Data[0], V0);
BufferWrite32LE(&Data[4], V1);
Data += 8;
Size -= 8;
}
}
void XTEADecrypt(const uint32 *Key, uint8 *Data, int Size){
ASSERT(Key != NULL);
while(Size >= 8){
uint32 Sum = 0xC6EF3720UL;
uint32 Delta = 0x9E3779B9UL;
uint32 V0 = BufferRead32LE(&Data[0]);
uint32 V1 = BufferRead32LE(&Data[4]);
for(int i = 0; i < 32; i += 1){
V1 -= (((V0 << 4) ^ (V0 >> 5)) + V0) ^ (Sum + Key[(Sum >> 11) & 3]);
Sum -= Delta;
V0 -= (((V1 << 4) ^ (V1 >> 5)) + V1) ^ (Sum + Key[Sum & 3]);
}
BufferWrite32LE(&Data[0], V0);
BufferWrite32LE(&Data[4], V1);
Data += 8;
Size -= 8;
}
}

707
src/login/src/main.cc Normal file
View file

@ -0,0 +1,707 @@
#include "common.hh"
#include <errno.h>
#include <signal.h>
int64 g_StartTimeMS = 0;
int g_ShutdownSignal = 0;
TConfig g_Config = {};
void LogAdd(const char *Prefix, const char *Format, ...){
char Entry[4096];
va_list ap;
va_start(ap, Format);
vsnprintf(Entry, sizeof(Entry), Format, ap);
va_end(ap);
// NOTE(fusion): Trim trailing whitespace.
int Length = (int)strlen(Entry);
while(Length > 0 && isspace(Entry[Length - 1])){
Entry[Length - 1] = 0;
Length -= 1;
}
if(Length > 0){
char TimeString[128];
StringBufFormatTime(TimeString, "%Y-%m-%d %H:%M:%S", (int)time(NULL));
fprintf(stdout, "%s [%s] %s\n", TimeString, Prefix, Entry);
fflush(stdout);
}
}
void LogAddVerbose(const char *Prefix, const char *Function,
const char *File, int Line, const char *Format, ...){
char Entry[4096];
va_list ap;
va_start(ap, Format);
vsnprintf(Entry, sizeof(Entry), Format, ap);
va_end(ap);
// NOTE(fusion): Trim trailing whitespace.
int Length = (int)strlen(Entry);
while(Length > 0 && isspace(Entry[Length - 1])){
Entry[Length - 1] = 0;
Length -= 1;
}
if(Length > 0){
(void)File;
(void)Line;
char TimeString[128];
StringBufFormatTime(TimeString, "%Y-%m-%d %H:%M:%S", (int)time(NULL));
fprintf(stdout, "%s [%s] %s: %s\n", TimeString, Prefix, Function, Entry);
fflush(stdout);
}
}
struct tm GetLocalTime(time_t t){
struct tm result;
#if COMPILER_MSVC
localtime_s(&result, &t);
#else
localtime_r(&t, &result);
#endif
return result;
}
struct tm GetGMTime(time_t t){
struct tm result;
#if COMPILER_MSVC
gmtime_s(&result, &t);
#else
gmtime_r(&t, &result);
#endif
return result;
}
int64 GetClockMonotonicMS(void){
#if OS_WINDOWS
LARGE_INTEGER Counter, Frequency;
QueryPerformanceCounter(&Counter);
QueryPerformanceFrequency(&Frequency);
return (int64)((Counter.QuadPart * 1000) / Frequency.QuadPart);
#else
// NOTE(fusion): The coarse monotonic clock has a larger resolution but is
// supposed to be faster, even avoiding system calls in some cases. It should
// be fine for millisecond precision which is what we're using.
struct timespec Time;
clock_gettime(CLOCK_MONOTONIC_COARSE, &Time);
return ((int64)Time.tv_sec * 1000)
+ ((int64)Time.tv_nsec / 1000000);
#endif
}
int GetMonotonicUptime(void){
return (int)((GetClockMonotonicMS() - g_StartTimeMS) / 1000);
}
bool StringEmpty(const char *String){
return String[0] == 0;
}
bool StringEq(const char *A, const char *B){
int Index = 0;
while(A[Index] != 0 && A[Index] == B[Index]){
Index += 1;
}
return A[Index] == B[Index];
}
bool StringEqCI(const char *A, const char *B){
int Index = 0;
while(A[Index] != 0 && tolower(A[Index]) == tolower(B[Index])){
Index += 1;
}
return tolower(A[Index]) == tolower(B[Index]);
}
bool StringCopy(char *Dest, int DestCapacity, const char *Src){
int SrcLength = (Src != NULL ? (int)strlen(Src) : 0);
return StringCopyN(Dest, DestCapacity, Src, SrcLength);
}
bool StringCopyN(char *Dest, int DestCapacity, const char *Src, int SrcLength){
ASSERT(DestCapacity > 0);
bool Result = (SrcLength < DestCapacity);
if(Result && SrcLength > 0){
memcpy(Dest, Src, SrcLength);
Dest[SrcLength] = 0;
}else{
Dest[0] = 0;
}
return Result;
}
bool StringFormat(char *Dest, int DestCapacity, const char *Format, ...){
va_list ap;
va_start(ap, Format);
int Written = vsnprintf(Dest, DestCapacity, Format, ap);
va_end(ap);
return Written >= 0 && Written < DestCapacity;
}
bool StringFormatTime(char *Dest, int DestCapacity, const char *Format, int Timestamp){
struct tm tm = GetLocalTime((time_t)Timestamp);
int Result = (int)strftime(Dest, DestCapacity, Format, &tm);
// NOTE(fusion): `strftime` will return ZERO if it's unable to fit the result
// in the supplied buffer, which is annoying because ZERO may not represent a
// failure if the result is an empty string.
ASSERT(Result >= 0 && Result < DestCapacity);
if(Result == 0){
memset(Dest, 0, DestCapacity);
}
return Result != 0;
}
void StringClear(char *Dest, int DestCapacity){
ASSERT(DestCapacity > 0);
memset(Dest, 0, DestCapacity);
}
uint32 StringHash(const char *String){
// FNV1a 32-bits
uint32 Hash = 0x811C9DC5U;
for(int i = 0; String[i] != 0; i += 1){
Hash ^= (uint32)String[i];
Hash *= 0x01000193U;
}
return Hash;
}
bool StringEscape(char *Dest, int DestCapacity, const char *Src){
int WritePos = 0;
for(int ReadPos = 0; Src[ReadPos] != 0 && WritePos < DestCapacity; ReadPos += 1){
int EscapeCh = -1;
switch(Src[ReadPos]){
case '\a': EscapeCh = 'a'; break;
case '\b': EscapeCh = 'b'; break;
case '\t': EscapeCh = 't'; break;
case '\n': EscapeCh = 'n'; break;
case '\v': EscapeCh = 'v'; break;
case '\f': EscapeCh = 'f'; break;
case '\r': EscapeCh = 'r'; break;
case '\"': EscapeCh = '\"'; break;
case '\'': EscapeCh = '\''; break;
case '\\': EscapeCh = '\\'; break;
}
if(EscapeCh != -1){
if((WritePos + 1) <= DestCapacity){
Dest[WritePos] = '\\';
WritePos += 1;
}
if((WritePos + 1) <= DestCapacity){
Dest[WritePos] = EscapeCh;
WritePos += 1;
}
}else{
if((WritePos + 1) <= DestCapacity){
Dest[WritePos] = Src[ReadPos];
WritePos += 1;
}
}
}
if(WritePos < DestCapacity){
Dest[WritePos] = 0;
return true;
}else{
Dest[DestCapacity - 1] = 0;
return false;
}
}
int UTF8SequenceSize(uint8 LeadingByte){
if((LeadingByte & 0x80) == 0){
return 1;
}else if((LeadingByte & 0xE0) == 0xC0){
return 2;
}else if((LeadingByte & 0xF0) == 0xE0){
return 3;
}else if((LeadingByte & 0xF8) == 0xF0){
return 4;
}else{
return 0;
}
}
bool UTF8IsTrailingByte(uint8 Byte){
return (Byte & 0xC0) == 0x80;
}
int UTF8EncodedSize(int Codepoint){
if(Codepoint < 0){
return 0;
}else if(Codepoint <= 0x7F){
return 1;
}else if(Codepoint <= 0x07FF){
return 2;
}else if(Codepoint <= 0xFFFF){
return 3;
}else if(Codepoint <= 0x10FFFF){
return 4;
}else{
return 0;
}
}
int UTF8FindNextLeadingByte(const char *Src, int SrcLength){
int Offset = 0;
while(Offset < SrcLength){
// NOTE(fusion): Allow the first byte to be a leading byte, in case we
// just want to advance from one leading byte to another.
if(Offset > 0 && !UTF8IsTrailingByte(Src[Offset])){
break;
}
Offset += 1;
}
return Offset;
}
int UTF8DecodeOne(const uint8 *Src, int SrcLength, int *OutCodepoint){
if(SrcLength <= 0){
return 0;
}
int Size = UTF8SequenceSize(Src[0]);
if(Size <= 0 || Size > SrcLength){
return 0;
}
for(int i = 1; i < Size; i += 1){
if(!UTF8IsTrailingByte(Src[i])){
return 0;
}
}
int Codepoint = 0;
switch(Size){
case 1:{
Codepoint = (int)Src[0];
break;
}
case 2:{
Codepoint = ((int)(Src[0] & 0x1F) << 6)
| ((int)(Src[1] & 0x3F) << 0);
break;
}
case 3:{
Codepoint = ((int)(Src[0] & 0x0F) << 12)
| ((int)(Src[1] & 0x3F) << 6)
| ((int)(Src[2] & 0x3F) << 0);
break;
}
case 4:{
Codepoint = ((int)(Src[0] & 0x07) << 18)
| ((int)(Src[1] & 0x3F) << 12)
| ((int)(Src[2] & 0x3F) << 6)
| ((int)(Src[3] & 0x3F) << 0);
break;
}
}
if(OutCodepoint){
*OutCodepoint = Codepoint;
}
return Size;
}
int UTF8EncodeOne(uint8 *Dest, int DestCapacity, int Codepoint){
int Size = UTF8EncodedSize(Codepoint);
if(Size > 0 && Size <= DestCapacity){
switch(Size){
case 1:{
Dest[0] = (uint8)Codepoint;
break;
}
case 2:{
Dest[0] = (uint8)(0xC0 | (0x1F & (Codepoint >> 6)));
Dest[1] = (uint8)(0x80 | (0x3F & (Codepoint >> 0)));
break;
}
case 3:{
Dest[0] = (uint8)(0xE0 | (0x0F & (Codepoint >> 12)));
Dest[1] = (uint8)(0x80 | (0x3F & (Codepoint >> 6)));
Dest[2] = (uint8)(0x80 | (0x3F & (Codepoint >> 0)));
break;
}
case 4:{
Dest[0] = (uint8)(0xF0 | (0x07 & (Codepoint >> 18)));
Dest[1] = (uint8)(0x80 | (0x3F & (Codepoint >> 12)));
Dest[2] = (uint8)(0x80 | (0x3F & (Codepoint >> 6)));
Dest[3] = (uint8)(0x80 | (0x3F & (Codepoint >> 0)));
break;
}
}
}
return Size;
}
// IMPORTANT(fusion): This function WON'T handle null-termination. It'll rather
// convert any characters, INCLUDING the null-terminator, contained in the src
// string. Invalid or NON-LATIN1 codepoints are translated into '?'.
int UTF8ToLatin1(char *Dest, int DestCapacity, const char *Src, int SrcLength){
int ReadPos = 0;
int WritePos = 0;
while(ReadPos < SrcLength){
int Codepoint = -1;
int Size = UTF8DecodeOne((uint8*)(Src + ReadPos), (SrcLength - ReadPos), &Codepoint);
if(Size > 0){
ReadPos += Size;
}else{
ReadPos += UTF8FindNextLeadingByte((Src + ReadPos), (SrcLength - ReadPos));
}
if(WritePos < DestCapacity){
if(Codepoint >= 0 && Codepoint <= 0xFF){
Dest[WritePos] = (char)Codepoint;
}else{
Dest[WritePos] = '?';
}
}
WritePos += 1;
}
return WritePos;
}
// IMPORTANT(fusion): This function WON'T handle null-termination. It'll rather
// convert any characters, INCLUDING the null-terminator, contained in the src
// string. Note that LATIN1 characters translates directly into UNICODE codepoints.
int Latin1ToUTF8(char *Dest, int DestCapacity, const char *Src, int SrcLength){
int WritePos = 0;
for(int ReadPos = 0; ReadPos < SrcLength; ReadPos += 1){
WritePos += UTF8EncodeOne((uint8*)(Dest + WritePos),
(DestCapacity - WritePos), (uint8)Src[ReadPos]);
}
return WritePos;
}
bool ParseBoolean(bool *Dest, const char *String){
ASSERT(Dest && String);
*Dest = StringEqCI(String, "true")
|| StringEqCI(String, "on")
|| StringEqCI(String, "yes");
return *Dest
|| StringEqCI(String, "false")
|| StringEqCI(String, "off")
|| StringEqCI(String, "no");
}
bool ParseInteger(int *Dest, const char *String){
ASSERT(Dest && String);
const char *StringEnd;
*Dest = (int)strtol(String, (char**)&StringEnd, 0);
return StringEnd > String;
}
bool ParseDuration(int *Dest, const char *String){
ASSERT(Dest && String);
const char *Suffix;
*Dest = (int)strtol(String, (char**)&Suffix, 0);
if(Suffix == String){
return false;
}
while(Suffix[0] != 0 && isspace(Suffix[0])){
Suffix += 1;
}
if(Suffix[0] == 'S' || Suffix[0] == 's'){
*Dest *= (1);
}else if(Suffix[0] == 'M' || Suffix[0] == 'm'){
*Dest *= (60);
}else if(Suffix[0] == 'H' || Suffix[0] == 'h'){
*Dest *= (60 * 60);
}
return true;
}
bool ParseSize(int *Dest, const char *String){
ASSERT(Dest && String);
const char *Suffix;
*Dest = (int)strtol(String, (char**)&Suffix, 0);
if(Suffix == String){
return false;
}
while(Suffix[0] != 0 && isspace(Suffix[0])){
Suffix += 1;
}
if(Suffix[0] == 'K' || Suffix[0] == 'k'){
*Dest *= (1024);
}else if(Suffix[0] == 'M' || Suffix[0] == 'm'){
*Dest *= (1024 * 1024);
}
return true;
}
bool ParseString(char *Dest, int DestCapacity, const char *String){
ASSERT(Dest && DestCapacity > 0 && String);
int StringStart = 0;
int StringEnd = (int)strlen(String);
if(StringEnd >= 2){
if((String[0] == '"' && String[StringEnd - 1] == '"')
|| (String[0] == '\'' && String[StringEnd - 1] == '\'')
|| (String[0] == '`' && String[StringEnd - 1] == '`')){
StringStart += 1;
StringEnd -= 1;
}
}
return StringCopyN(Dest, DestCapacity,
&String[StringStart], (StringEnd - StringStart));
}
void ParseMotd(char *Dest, int DestCapacity, const char *String){
char *Motd = (char*)alloca(DestCapacity);
ParseString(Motd, DestCapacity, String);
if(Motd[0] != 0){
StringFormat(Dest, DestCapacity, "%u\n%s", StringHash(Motd), Motd);
}
}
bool ReadConfig(const char *FileName, TConfig *Config){
FILE *File = fopen(FileName, "rb");
if(File == NULL){
LOG_ERR("Failed to open config file \"%s\"", FileName);
return false;
}
bool EndOfFile = false;
for(int LineNumber = 1; !EndOfFile; LineNumber += 1){
const int MaxLineSize = 1024;
char Line[MaxLineSize];
int LineSize = 0;
int KeyStart = -1;
int EqualPos = -1;
while(true){
int ch = fgetc(File);
if(ch == EOF || ch == '\n'){
if(ch == EOF){
EndOfFile = true;
}
break;
}
if(LineSize < MaxLineSize){
Line[LineSize] = (char)ch;
}
if(KeyStart == -1 && !isspace(ch)){
KeyStart = LineSize;
}
if(EqualPos == -1 && ch == '='){
EqualPos = LineSize;
}
LineSize += 1;
}
// NOTE(fusion): Check line size limit.
if(LineSize > MaxLineSize){
LOG_WARN("%s:%d: Exceeded line size limit of %d characters",
FileName, LineNumber, MaxLineSize);
continue;
}
// NOTE(fusion): Check empty line or comment.
if(KeyStart == -1 || Line[KeyStart] == '#'){
continue;
}
// NOTE(fusion): Check assignment.
if(EqualPos == -1){
LOG_WARN("%s:%d: No assignment found on non empty line",
FileName, LineNumber);
continue;
}
// NOTE(fusion): Check empty key.
int KeyEnd = EqualPos;
while(KeyEnd > KeyStart && isspace(Line[KeyEnd - 1])){
KeyEnd -= 1;
}
if(KeyStart == KeyEnd){
LOG_WARN("%s:%d: Empty key", FileName, LineNumber);
continue;
}
// NOTE(fusion): Check empty value.
int ValStart = EqualPos + 1;
int ValEnd = LineSize;
while(ValStart < ValEnd && isspace(Line[ValStart])){
ValStart += 1;
}
while(ValEnd > ValStart && isspace(Line[ValEnd - 1])){
ValEnd -= 1;
}
if(ValStart == ValEnd){
LOG_WARN("%s:%d: Empty value", FileName, LineNumber);
continue;
}
// NOTE(fusion): Parse KV pair.
char Key[256];
if(!StringBufCopyN(Key, &Line[KeyStart], (KeyEnd - KeyStart))){
LOG_WARN("%s:%d: Exceeded key size limit of %d characters",
FileName, LineNumber, (int)(sizeof(Key) - 1));
continue;
}
char Val[256];
if(!StringBufCopyN(Val, &Line[ValStart], (ValEnd - ValStart))){
LOG_WARN("%s:%d: Exceeded value size limit of %d characters",
FileName, LineNumber, (int)(sizeof(Val) - 1));
continue;
}
if(StringEqCI(Key, "LoginPort")){
ParseInteger(&Config->LoginPort, Val);
}else if(StringEqCI(Key, "ConnectionTimeout")){
ParseDuration(&Config->ConnectionTimeout, Val);
}else if(StringEqCI(Key, "MaxConnections")){
ParseInteger(&Config->MaxConnections, Val);
}else if(StringEqCI(Key, "MaxStatusRecords")){
ParseInteger(&Config->MaxStatusRecords, Val);
}else if(StringEqCI(Key, "MinStatusInterval")){
ParseDuration(&Config->MinStatusInterval, Val);
}else if(StringEqCI(Key, "QueryManagerHost")){
ParseStringBuf(Config->QueryManagerHost, Val);
}else if(StringEqCI(Key, "QueryManagerPort")){
ParseInteger(&Config->QueryManagerPort, Val);
}else if(StringEqCI(Key, "QueryManagerPassword")){
ParseStringBuf(Config->QueryManagerPassword, Val);
}else if(StringEqCI(Key, "StatusWorld")){
ParseStringBuf(Config->StatusWorld, Val);
}else if(StringEqCI(Key, "URL")){
ParseStringBuf(Config->Url, Val);
}else if(StringEqCI(Key, "Location")){
ParseStringBuf(Config->Location, Val);
}else if(StringEqCI(Key, "ServerType")){
ParseStringBuf(Config->ServerType, Val);
}else if(StringEqCI(Key, "ServerVersion")){
ParseStringBuf(Config->ServerVersion, Val);
}else if(StringEqCI(Key, "ClientVersion")){
ParseStringBuf(Config->ClientVersion, Val);
}else if(StringEqCI(Key, "MOTD")){
ParseMotd(Config->Motd, sizeof(Config->Motd), Val);
}else{
LOG_WARN("Unknown config \"%s\"", Key);
}
}
fclose(File);
return true;
}
static bool SigHandler(int SigNr, sighandler_t Handler){
struct sigaction Action = {};
Action.sa_handler = Handler;
sigfillset(&Action.sa_mask);
if(sigaction(SigNr, &Action, NULL) == -1){
LOG_ERR("Failed to change handler for signal %d (%s): (%d) %s",
SigNr, sigdescr_np(SigNr), errno, strerrordesc_np(errno));
return false;
}
return true;
}
static void ShutdownHandler(int SigNr){
g_ShutdownSignal = SigNr;
//WakeConnections?
}
int main(int argc, const char **argv){
(void)argc;
(void)argv;
g_StartTimeMS = GetClockMonotonicMS();
g_ShutdownSignal = 0;
if(!SigHandler(SIGPIPE, SIG_IGN)
|| !SigHandler(SIGINT, ShutdownHandler)
|| !SigHandler(SIGTERM, ShutdownHandler)){
return EXIT_FAILURE;
}
// Service Config
g_Config.LoginPort = 7171;
g_Config.ConnectionTimeout = 5; // seconds
g_Config.MaxConnections = 10;
g_Config.MaxStatusRecords = 1024;
g_Config.MinStatusInterval = 300; // seconds
StringBufCopy(g_Config.QueryManagerHost, "127.0.0.1");
g_Config.QueryManagerPort = 7173;
StringBufCopy(g_Config.QueryManagerPassword, "");
// Service Info
StringBufCopy(g_Config.StatusWorld, "");
StringBufCopy(g_Config.Url, "");
StringBufCopy(g_Config.Location, "");
StringBufCopy(g_Config.ServerType, "");
StringBufCopy(g_Config.ServerVersion, "");
StringBufCopy(g_Config.ClientVersion, "");
StringBufCopy(g_Config.Motd, "");
LOG("Tibia Login v0.2");
if(!ReadConfig("config.cfg", &g_Config)){
return EXIT_FAILURE;
}
LOG("Login port: %d", g_Config.LoginPort);
LOG("Connection timeout: %ds", g_Config.ConnectionTimeout);
LOG("Max connections: %d", g_Config.MaxConnections);
LOG("Max status records: %d", g_Config.MaxStatusRecords);
LOG("Min status interval: %ds", g_Config.MinStatusInterval);
LOG("Query manager host: \"%s\"", g_Config.QueryManagerHost);
LOG("Query manager port: %d", g_Config.QueryManagerPort);
LOG("Status world: \"%s\"", g_Config.StatusWorld);
LOG("URL: \"%s\"", g_Config.Url);
LOG("Location: \"%s\"", g_Config.Location);
LOG("Server type: \"%s\"", g_Config.ServerType);
LOG("Server version: \"%s\"", g_Config.ServerVersion);
LOG("Client version: \"%s\"", g_Config.ClientVersion);
{ // NOTE(fusion): Print MOTD preview with escape codes.
char MotdPreview[30];
if(StringBufEscape(MotdPreview, g_Config.Motd)){
LOG("MOTD: \"%s\"", MotdPreview);
}else{
LOG("MOTD: \"%s...\"", MotdPreview);
}
}
atexit(ExitQuery);
atexit(ExitConnections);
if(!InitQuery() || !InitConnections()){
return EXIT_FAILURE;
}
LOG("Running...");
while(g_ShutdownSignal == 0){
ProcessConnections();
}
LOG("Received signal %d (%s), shutting down...",
g_ShutdownSignal, sigdescr_np(g_ShutdownSignal));
return EXIT_SUCCESS;
}

301
src/login/src/query.cc Normal file
View file

@ -0,0 +1,301 @@
#include "common.hh"
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
static TQueryManagerConnection *g_QueryManagerConnection;
static bool ResolveHostName(const char *HostName, in_addr_t *OutAddr){
ASSERT(HostName != NULL && OutAddr != NULL);
addrinfo *Result = NULL;
addrinfo Hints = {};
Hints.ai_family = AF_INET;
Hints.ai_socktype = SOCK_STREAM;
int ErrCode = getaddrinfo(HostName, NULL, &Hints, &Result);
if(ErrCode != 0){
LOG_ERR("Failed to resolve hostname \"%s\": %s", HostName, gai_strerror(ErrCode));
return false;
}
bool Resolved = false;
for(addrinfo *AddrInfo = Result;
AddrInfo != NULL;
AddrInfo = AddrInfo->ai_next){
if(AddrInfo->ai_family == AF_INET && AddrInfo->ai_socktype == SOCK_STREAM){
ASSERT(AddrInfo->ai_addrlen == sizeof(sockaddr_in));
*OutAddr = ((sockaddr_in*)AddrInfo->ai_addr)->sin_addr.s_addr;
Resolved = true;
break;
}
}
freeaddrinfo(Result);
return Resolved;
}
static bool WriteExact(int Fd, const uint8 *Buffer, int Size){
int BytesToWrite = Size;
const uint8 *WritePtr = Buffer;
while(BytesToWrite > 0){
int Ret = (int)write(Fd, WritePtr, BytesToWrite);
if(Ret == -1){
return false;
}
BytesToWrite -= Ret;
WritePtr += Ret;
}
return true;
}
static bool ReadExact(int Fd, uint8 *Buffer, int Size){
int BytesToRead = Size;
uint8 *ReadPtr = Buffer;
while(BytesToRead > 0){
int Ret = (int)read(Fd, ReadPtr, BytesToRead);
if(Ret == -1 || Ret == 0){
return false;
}
BytesToRead -= Ret;
ReadPtr += Ret;
}
return true;
}
bool Connect(TQueryManagerConnection *Connection){
if(Connection->Socket != -1){
LOG_ERR("Already connected");
return false;
}
in_addr_t Addr;
if(!ResolveHostName(g_Config.QueryManagerHost, &Addr)){
LOG_ERR("Failed to resolve query manager's host name \"%s\"", g_Config.QueryManagerHost);
return false;
}
Connection->Socket = socket(AF_INET, SOCK_STREAM, 0);
if(Connection->Socket == -1){
LOG_ERR("Failed to create socket: (%d) %s", errno, strerrordesc_np(errno));
return false;
}
sockaddr_in QueryManagerAddress = {};
QueryManagerAddress.sin_family = AF_INET;
QueryManagerAddress.sin_port = htons((uint16)g_Config.QueryManagerPort);
QueryManagerAddress.sin_addr.s_addr = Addr;
if(connect(Connection->Socket, (sockaddr*)&QueryManagerAddress, sizeof(QueryManagerAddress)) == -1){
LOG_ERR("Failed to connect: (%d) %s", errno, strerrordesc_np(errno));
Disconnect(Connection);
return false;
}
uint8 LoginBuffer[1024];
TWriteBuffer WriteBuffer = PrepareQuery(QUERY_LOGIN, LoginBuffer, sizeof(LoginBuffer));
WriteBuffer.Write8((uint8)APPLICATION_TYPE_LOGIN);
WriteBuffer.WriteString(g_Config.QueryManagerPassword);
int Status = ExecuteQuery(Connection, false, &WriteBuffer, NULL);
if(Status != QUERY_STATUS_OK){
LOG_ERR("Failed to login to query manager (%d)", Status);
Disconnect(Connection);
return false;
}
return true;
}
void Disconnect(TQueryManagerConnection *Connection){
if(Connection->Socket != -1){
close(Connection->Socket);
Connection->Socket = -1;
}
}
bool IsConnected(TQueryManagerConnection *Connection){
return Connection->Socket != -1;
}
TWriteBuffer PrepareQuery(int QueryType, uint8 *Buffer, int BufferSize){
TWriteBuffer WriteBuffer(Buffer, BufferSize);
WriteBuffer.Write16(0); // Request Size
WriteBuffer.Write8((uint8)QueryType);
return WriteBuffer;
}
int ExecuteQuery(TQueryManagerConnection *Connection, bool AutoReconnect,
TWriteBuffer *WriteBuffer, TReadBuffer *OutReadBuffer){
// IMPORTANT(fusion): This is similar to the Go version where there is no
// connection buffer, and the response is read into the same buffer used
// by `WriteBuffer. This helps prevent allocating and moving data around
// when reconnecting in the middle of a query.
ASSERT(WriteBuffer != NULL && WriteBuffer->Position > 2);
int RequestSize = WriteBuffer->Position - 2;
if(RequestSize < 0xFFFF){
WriteBuffer->Rewrite16(0, (uint16)RequestSize);
}else{
WriteBuffer->Rewrite16(0, 0xFFFF);
WriteBuffer->Insert32(2, (uint32)RequestSize);
}
if(WriteBuffer->Overflowed()){
LOG_ERR("Write buffer overflowed when writing request");
return QUERY_STATUS_FAILED;
}
const int MaxAttempts = 2;
uint8 *Buffer = WriteBuffer->Buffer;
int BufferSize = WriteBuffer->Size;
int WriteSize = WriteBuffer->Position;
for(int Attempt = 1; true; Attempt += 1){
if(!IsConnected(Connection) && (!AutoReconnect || !Connect(Connection))){
return QUERY_STATUS_FAILED;
}
if(!WriteExact(Connection->Socket, Buffer, WriteSize)){
Disconnect(Connection);
if(Attempt >= MaxAttempts){
LOG_ERR("Failed to write request");
return QUERY_STATUS_FAILED;
}
continue;
}
uint8 Help[4];
if(!ReadExact(Connection->Socket, Help, 2)){
Disconnect(Connection);
if(Attempt >= MaxAttempts){
LOG_ERR("Failed to read response size");
return QUERY_STATUS_FAILED;
}
continue;
}
int ResponseSize = BufferRead16LE(Help);
if(ResponseSize == 0xFFFF){
if(!ReadExact(Connection->Socket, Help, 4)){
Disconnect(Connection);
LOG_ERR("Failed to read response extended size");
return QUERY_STATUS_FAILED;
}
ResponseSize = BufferRead32LE(Help);
}
if(ResponseSize <= 0 || ResponseSize > BufferSize){
Disconnect(Connection);
LOG_ERR("Invalid response size %d (BufferSize: %d)",
ResponseSize, BufferSize);
return QUERY_STATUS_FAILED;
}
if(!ReadExact(Connection->Socket, Buffer, ResponseSize)){
Disconnect(Connection);
LOG_ERR("Failed to read response");
return QUERY_STATUS_FAILED;
}
TReadBuffer ReadBuffer(Buffer, ResponseSize);
int Status = ReadBuffer.Read8();
if(OutReadBuffer){
*OutReadBuffer = ReadBuffer;
}
return Status;
}
}
int LoginAccount(int AccountID, const char *Password, const char *IPAddress,
int MaxCharacters, int *NumCharacters, TCharacterLoginData *Characters,
int *PremiumDays){
uint8 Buffer[KB(4)];
TWriteBuffer WriteBuffer = PrepareQuery(QUERY_LOGIN_ACCOUNT, Buffer, sizeof(Buffer));
WriteBuffer.Write32((uint32)AccountID);
WriteBuffer.WriteString(Password);
WriteBuffer.WriteString(IPAddress);
TReadBuffer ReadBuffer;
int Status = ExecuteQuery(g_QueryManagerConnection, true, &WriteBuffer, &ReadBuffer);
int Result = (Status == QUERY_STATUS_OK ? 0 : -1);
if(Status == QUERY_STATUS_OK){
*NumCharacters = ReadBuffer.Read8();
if(*NumCharacters > MaxCharacters){
LOG_ERR("Too many characters");
return -1;
}
for(int i = 0; i < *NumCharacters; i += 1){
ReadBuffer.ReadString(Characters[i].Name, sizeof(Characters[i].Name));
ReadBuffer.ReadString(Characters[i].WorldName, sizeof(Characters[i].WorldName));
Characters[i].WorldAddress = ReadBuffer.Read32BE();
Characters[i].WorldPort = ReadBuffer.Read16();
}
*PremiumDays = ReadBuffer.Read16();
}else if(Status == QUERY_STATUS_ERROR){
int ErrorCode = ReadBuffer.Read8();
if(ErrorCode >= 1 && ErrorCode <= 6){
Result = ErrorCode;
}else{
LOG_ERR("Invalid error code %d", ErrorCode);
}
}else{
LOG_ERR("Request failed");
}
return Result;
}
int GetWorld(const char *WorldName, TWorld *OutWorld){
ASSERT(WorldName && OutWorld);
uint8 Buffer[4096];
TReadBuffer ReadBuffer;
TWriteBuffer WriteBuffer = PrepareQuery(QUERY_GET_WORLDS, Buffer, sizeof(Buffer));
int Status = ExecuteQuery(g_QueryManagerConnection, true, &WriteBuffer, &ReadBuffer);
int Result = (Status == QUERY_STATUS_OK ? 0 : -1);
memset(OutWorld, 0, sizeof(TWorld));
if(Status == QUERY_STATUS_OK){
int NumWorlds = (int)ReadBuffer.Read8();
for(int i = 0; i < NumWorlds; i += 1){
TWorld World = {};
ReadBuffer.ReadString(World.Name, sizeof(World.Name));
World.Type = (int)ReadBuffer.Read8();
World.NumPlayers = (int)ReadBuffer.Read16();
World.MaxPlayers = (int)ReadBuffer.Read16();
World.OnlinePeak = (int)ReadBuffer.Read16();
World.OnlinePeakTimestamp = (int)ReadBuffer.Read32();
World.LastStartup = (int)ReadBuffer.Read32();
World.LastShutdown = (int)ReadBuffer.Read32();
if(StringEmpty(WorldName)){
// NOTE(fusion): Pick the world with the most players.
if(i == 0 || World.NumPlayers > OutWorld->NumPlayers){
*OutWorld = World;
}
}else if(StringEqCI(WorldName, World.Name)){
*OutWorld = World;
break;
}
}
}else{
LOG_ERR("Request failed");
}
return Result;
}
bool InitQuery(void){
ASSERT(g_QueryManagerConnection == NULL);
g_QueryManagerConnection = (TQueryManagerConnection*)calloc(1, sizeof(TQueryManagerConnection));
g_QueryManagerConnection->Socket = -1;
if(!Connect(g_QueryManagerConnection)){
LOG_ERR("Failed to connect to query manager");
return false;
}
return true;
}
void ExitQuery(void){
if(g_QueryManagerConnection != NULL){
Disconnect(g_QueryManagerConnection);
free(g_QueryManagerConnection);
g_QueryManagerConnection = NULL;
}
}

215
src/login/src/status.cc Normal file
View file

@ -0,0 +1,215 @@
#include "common.hh"
static int g_LastStatusRefresh;
static char g_StatusString[KB(2)];
struct XMLBuffer{
char *Data;
int Size;
int Position;
};
static void XMLNullTerminate(XMLBuffer *Buffer){
ASSERT(Buffer->Size > 0);
if(Buffer->Position < Buffer->Size){
Buffer->Data[Buffer->Position] = 0;
}else{
Buffer->Data[Buffer->Size - 1] = 0;
}
}
static void XMLAppendChar(XMLBuffer *Buffer, char Ch){
if(Buffer->Position < Buffer->Size){
Buffer->Data[Buffer->Position] = Ch;
}
Buffer->Position += 1;
}
static void XMLAppendNumber(XMLBuffer *Buffer, int64 Num){
if(Num == 0){
XMLAppendChar(Buffer, '0');
return;
}
if(Num < 0){
XMLAppendChar(Buffer, '-');
Num = -Num;
}
char String[64] = {};
int StringLen = 0;
while(Num > 0){
ASSERT(StringLen < (int)sizeof(String));
String[StringLen] = (Num % 10) + '0';
Num = (Num / 10);
StringLen += 1;
}
for(int i = 0; i < StringLen; i += 1){
XMLAppendChar(Buffer, String[(StringLen - 1) - i]);
}
}
static void XMLAppendString(XMLBuffer *Buffer, const char *String){
const char *P = String;
while(P[0]){
XMLAppendChar(Buffer, P[0]);
P += 1;
}
}
static void XMLAppendStringEscaped(XMLBuffer *Buffer, const char *String){
const char *P = String;
while(P[0]){
switch(P[0]){
case '\t': XMLAppendString(Buffer, "&#9;"); break;
case '\n': XMLAppendString(Buffer, "&#10;"); break;
case '"': XMLAppendString(Buffer, "&quot;"); break;
case '&': XMLAppendString(Buffer, "&amp;"); break;
case '\'': XMLAppendString(Buffer, "&apos;"); break;
case '<': XMLAppendString(Buffer, "&lt;"); break;
case '>': XMLAppendString(Buffer, "&gt;"); break;
default: XMLAppendChar(Buffer, P[0]); break;
}
P += 1;
}
}
static void XMLAppendStringFV(XMLBuffer *Buffer, const char *Format, va_list Args){
const char *P = Format;
while(P[0]){
// IMPORTANT(fusion): This function only implements a small subset of
// the printf syntax.
if(P[0] == '%'){
P += 1;
// IMPORTANT(fusion): Small integral parameters such as char and short
// are promoted to int, similar to how they're promoted in arithmetic
// operations. This means there are only really 4 and 8 bytes integers.
int Length = 4;
if(P[0] == 'h' && P[1] == 'h'){
P += 2;
}else if(P[0] == 'l' && P[1] == 'l'){
Length = 8;
P += 2;
}else if(P[0] == 'h'){
P += 1;
}else if(P[0] == 'l'){
Length = 8;
P += 1;
}
switch(P[0]){
case '%':{
XMLAppendChar(Buffer, '%');
break;
}
case 'c':{
int Ch = va_arg(Args, int);
XMLAppendChar(Buffer, (char)Ch);
break;
}
case 'd':{
int64 Num = (Length == 4 ? va_arg(Args, int) : va_arg(Args, int64));
XMLAppendNumber(Buffer, Num);
break;
}
case 's':{
const char *String = va_arg(Args, const char*);
XMLAppendStringEscaped(Buffer, String);
break;
}
default:{
LOG_ERR("Invalid XML format specifier \"%c\"", P[0]);
break;
}
}
if(P[0]){
P += 1;
}
}else{
XMLAppendChar(Buffer, P[0]);
P += 1;
}
}
}
static void XMLAppendStringF(XMLBuffer *Buffer, const char *Format, ...){
va_list Args;
va_start(Args, Format);
XMLAppendStringFV(Buffer, Format, Args);
va_end(Args);
}
const char *GetStatusString(void){
int TimeNow = (int)time(NULL);
if((TimeNow - g_LastStatusRefresh) >= g_Config.MinStatusInterval){
const char *WorldName = "";
int Uptime = 0;
int NumPlayers = 0;
int MaxPlayers = 0;
int OnlinePeak = 0;
TWorld World = {};
if(GetWorld(g_Config.StatusWorld, &World) == 0){
WorldName = World.Name;
if(World.LastStartup != 0 && World.LastStartup > World.LastShutdown){
Uptime = TimeNow - World.LastStartup;
}
NumPlayers = World.NumPlayers;
MaxPlayers = World.MaxPlayers;
OnlinePeak = World.OnlinePeak;
// IMPORTANT(fusion): This could be a common behaviour but, on OTSERVLIST,
// the server will show as OFFLINE if the the online peak is less than
// the number of online players. This shouldn't usually be a problem since
// the online character list and online peak are updated together in the
// same CREATE_PLAYERLIST query, but is something to keep in mind.
if(OnlinePeak < NumPlayers){
OnlinePeak = NumPlayers;
}
}else{
LOG_ERR("Failed to query world data...");
}
// NOTE(fusion): Skip line with MOTD hash.
const char *Motd = g_Config.Motd;
while(Motd[0]){
if(Motd[0] == '\n'){
Motd += 1;
break;
}
Motd += 1;
}
XMLBuffer Buffer = {};
Buffer.Data = g_StatusString;
Buffer.Size = sizeof(g_StatusString);
XMLAppendString(&Buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
XMLAppendString(&Buffer, "<tsqp version=\"1.0\">");
XMLAppendStringF(&Buffer,
"<serverinfo servername=\"%s\" uptime=\"%d\" url=\"%s\""
" location=\"%s\" server=\"%s\" version=\"%s\""
" client=\"%s\"/>",
WorldName, Uptime, g_Config.Url, g_Config.Location,
g_Config.ServerType, g_Config.ServerVersion,
g_Config.ClientVersion);
XMLAppendStringF(&Buffer,
"<players online=\"%d\" max=\"%d\" peak=\"%d\"/>",
NumPlayers, MaxPlayers, OnlinePeak);
XMLAppendStringF(&Buffer, "<motd>%s</motd>", Motd);
XMLAppendString(&Buffer, "</tsqp>");
XMLNullTerminate(&Buffer);
g_LastStatusRefresh = TimeNow;
}
return g_StatusString;
}

View file

@ -0,0 +1,22 @@
# Basic SYSTEMD service file for the Tibia Login Server
[Unit]
Description=Tibia Login Server
After=network.target tibia-querymanager.service
Requires=tibia-querymanager.service
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=tibia-login
Group=tibia-login
ExecStart=/opt/tibia/login/login
WorkingDirectory=/opt/tibia/login/
Restart=always
RestartSec=10
LimitCORE=infinity
StandardOutput=journal
StandardError=journal
SyslogIdentifier=%n

15
src/login/tibia.pem Normal file
View file

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDLoibNahc41DeQhZUTth3FrhMNYek5xbQrlZ0O4BFr0LukdGY1
A3xHKAXt4d6Y539cQxpKqVPb+eSo44076c1PfL31BTDNFToN4uB3eUsOw3hROPSx
0Jkh72FAIhl6QynId0AHyrqeAgY59ZsTyXyJCSCWpFnl0WvK3Qf6nVBH/wIDAQAB
AoGAB9DoA19sl8JRhasS70hAuUs2sP9Ol+iWQ0wBVMZV9Nj0stnC6IsDNKn9HEXc
qOrN0SlEM5RvQxTC6ZaeX6vYNQDSJj/aigSyiNTMvw+38TD09z6EBlI4+0piGIJd
qY1ky0w3bdVhWiY2VFyGZ50NkfwjrpZSdLmsbhExzR4b/mkCQQDldLUeePo3RKZD
7+CVLFkTX/Yof8RLPOh1nukgftpvgaGcD1FXSwrIyKCHVAuwFnGgPfEr/2OAj60D
7Ya6XPeHAkEA4zC3U67ukzQxfyELrLTUBnsnKfkxejySsJ/M29SKCuHV2NOWxO8W
s9/c0RFvp0wI4uOxH00fIPYyI2h6TpxZyQJBAKQ0ZPktskKjCilMHPgkCIro/Yv2
A0+kgubJliP/I+rwZer8u0UxGsKdcOPnrYWSSjZWnaTS2y5Bo5tP/D6aETkCQDAc
AtZPtumpJcob/1LlP/jXX2W+BUIzTYTlcgYjLdA8HoK527V8Q7x3bVVAcfplWYRi
XwGX3T2npNpmp2+6IDECQBZuNbXiwHhDdsH7sSt36BGTFJNtVk3GJl/Bf50VrL6N
6NBNU3d4jQwArvSsanFYrZw+ayxS4rcJdZasO5mm+EI=
-----END RSA PRIVATE KEY-----

10
src/querymanager/.gitignore vendored Normal file
View file

@ -0,0 +1,10 @@
.vscode
.cache
bin
build
local
*.log
*.db
config.cfg
compile_commands.json

View file

@ -0,0 +1,6 @@
{
"upstream": "https://kaplar.net/tibia/querymanager.git",
"commit": "edea08d11cc306955d8d732164ec383d37ea1f62",
"branch": "master",
"vendoredAt": "2026-11-12"
}

View file

@ -0,0 +1,64 @@
cmake_minimum_required(VERSION 3.16)
project(querymanager LANGUAGES C CXX)
set(QM_DATABASE "sqlite" CACHE STRING "DB backend: sqlite | mariadb | mysql")
set_property(CACHE QM_DATABASE PROPERTY STRINGS sqlite postgres mariadb)
if(NOT QM_DATABASE MATCHES "^(sqlite|postgres|mariadb)$")
message(FATAL_ERROR "QM_DATABASE not supported: $(QM_DATABASE)")
endif()
# Common objects (querymanager.hh its the header)
set(QM_COMMON
src/querymanager.cc
src/connections.cc
src/hostcache.cc
src/query.cc
src/sha256.cc
)
add_executable(querymanager ${QM_COMMON})
if(QM_DATABASE STREQUAL "sqlite")
target_sources(querymanager PRIVATE
src/database_sqlite.cc
src/sqlite3.c
)
target_compile_definitions(querymanager PRIVATE DATABASE_SQLITE=1)
elseif(QM_DATABASE STREQUAL "postgres")
target_sources(querymanager PRIVATE src/database_postgres.cc)
target_compile_definitions(querymanager PRIVATE DATABASE_POSTGRESQL=1)
target_compile_definitions(querymanager PRIVATE usr/include/postgresql)
target_link_libraries(querymanager PRIVATE pq)
elseif(QM_DATABASE STREQUAL "mariadb")
target_sources(querymanager PRIVATE src/database_mariadb.cc)
target_compile_definitions(querymanager PRIVATE DATABASE_MARIADB=1)
target_include_directories(querymanager PRIVATE /usr/include/mariadb)
target_link_libraries(querymanager PRIVATE mariadb)
endif()
target_include_directories(querymanager PRIVATE src)
# Original Makefile Flags
target_compile_options(querymanager PRIVATE
-fno-strict-aliasing
-pedantic
-Wall
-Wextra
)
set_target_properties(querymanager PROPERTIES
CXX_STANDARD 11
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
target_compile_definitions(querymanager PRIVATE
$<$<CONFIG:Debug>:ENABLE_ASSERTIONS=1>
)
target_link_libraries(querymanager PRIVATE pthread)
install(TARGETS querymanager RUNTIME DESTINATION bin)

View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>

83
src/querymanager/Makefile Normal file
View file

@ -0,0 +1,83 @@
SRCDIR = src
BUILDDIR = build
OUTPUTEXE = querymanager
CC = gcc
CXX = g++
CFLAGS = -m64 -fno-strict-aliasing -pedantic -Wall -Wextra -pthread
CXXFLAGS = $(CFLAGS) --std=c++11
LFLAGS = -Wl,-t
# IMPORTANT(fusion): Using TABS outside recipes may cause errors in some cases.
# This is because .RECIPEPREFIX defaults to it and any line starting with it is
# assumed to introduce another recipe command. If indentation is needed before
# any target is specified, use SPACES.
DEBUG ?= 0
ifneq ($(DEBUG), 0)
CFLAGS += -g -Og -DENABLE_ASSERTIONS=1
else
CFLAGS += -O2
endif
DATABASE ?= sqlite
ifeq ($(DATABASE), sqlite)
DATABASEOBJ = $(BUILDDIR)/database_sqlite.obj $(BUILDDIR)/sqlite3.obj
CFLAGS += -DDATABASE_SQLITE=1
else ifeq ($(DATABASE), postgres)
DATABASEOBJ = $(BUILDDIR)/database_postgres.obj
CFLAGS += -DDATABASE_POSTGRESQL=1 -I/usr/include/postgresql
LFLAGS += -lpq
else ifeq ($(DATABASE), mariadb)
DATABASEOBJ = $(BUILDDIR)/database_mariadb.obj
CFLAGS += -DDATABASE_MARIADB=1 -I/usr/include/mariadb
LFLAGS += -lmariadb
else
$(error Unsupported DATABASE: `$(DATABASE)`. Valid options are `sqlite`, `postgres`, or `mariadb`)
endif
$(BUILDDIR)/$(OUTPUTEXE): $(BUILDDIR)/connections.obj $(BUILDDIR)/hostcache.obj $(BUILDDIR)/query.obj $(BUILDDIR)/querymanager.obj $(BUILDDIR)/sha256.obj $(DATABASEOBJ)
@mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -o $@ $^ $(LFLAGS)
$(BUILDDIR)/connections.obj: $(SRCDIR)/connections.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/hostcache.obj: $(SRCDIR)/hostcache.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/query.obj: $(SRCDIR)/query.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/querymanager.obj: $(SRCDIR)/querymanager.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/sha256.obj: $(SRCDIR)/sha256.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/database_sqlite.obj: $(SRCDIR)/database_sqlite.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/database_postgres.obj: $(SRCDIR)/database_postgres.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/database_mariadb.obj: $(SRCDIR)/database_mariadb.cc $(SRCDIR)/querymanager.hh
@mkdir -p $(@D)
$(CXX) -c $(CXXFLAGS) -o $@ $<
$(BUILDDIR)/sqlite3.obj: $(SRCDIR)/sqlite3.c $(SRCDIR)/sqlite3.h
@mkdir -p $(@D)
$(CC) -c $(CFLAGS) -o $@ $<
.PHONY: clean
clean:
@rm -rf $(BUILDDIR)

View file

@ -0,0 +1,31 @@
# Tibia 7.7 Query Manager
This is a query manager designed to support [Tibia Game Server](https://github.com/fusion32/tibia-game), [Tibia Login Server](https://github.com/fusion32/tibia-login), and [Tibia Web Server](https://github.com/fusion32/tibia-web). It should be able to support any database system, but only SQLite and PostgreSQL are currently implemented. For SQLite, it uses the SQLite3 3.50.2 amalgamation, which avoids external dependencies and effectivelly turns the query manager into the database itself. For PostgreSQL, you'll need to link against *libpq*, but the query manager turns into a relay to the actual database. The communication protocol is NOT encrypted at all and it's configured to listen to local connections only. If you need a distributed infrastructure, use PostgreSQL!
## Compiling
Currently only Linux is supported. It shouldn't be too difficult to support Windows but I don't think it would add any value, considering the game server is somewhat bound to Linux, and that both need to run on the same machine. The only dependency is *libpq* when using PostgreSQL. The makefile is very simple but there are a few parameters that can be modified to customize compilation:
- *DEBUG* can be set to a non-zero value to build in debug mode. Defaults to zero.
- *DATABASE* can be set to either *sqlite* or *postgres* to modify the database system. Defaults to *sqlite*.
Compiling different translation units with different compilation parameters may cause things to blow up so it is recommended to always do a full rebuild. This can be achieved by running `make clean` before compiling or specifying the `-B` option to *make*. Here is a list of recommended commands:
```
make -B DEBUG=0 DATABASE=sqlite # build in release mode with SQLite
make -B DEBUG=1 DATABASE=sqlite # build in debug mode with SQLite
make -B DEBUG=0 DATABASE=postgres # build in release mode with PostgreSQL
make -B DEBUG=1 DATABASE=postgres # build in debug mode with PostgreSQL
make clean # remove `build` directory
```
## Running (SQLite)
The query manager becomes the database, automatically initializing and maintaining the schema, based on the files in `sqlite/` (see `sqlite/README.txt`). The default schema file won't automatically insert any initial data but that can be changed by using a patch (again, see `sqlite/README.txt`). There are a few configuration options, and in particular `SQLite.*` options that can be adjusted in `config.cfg` but the defaults should work for most use cases.
## Running (PostgreSQL)
The query manager becomes a relay to the actual database. And with PostgreSQL being a distributed database system, it makes no sense to have individual clients managing the schema, since there could be multiple, each with their own assumptions. For that reason there is a `SchemaInfo` table with a `VERSION` row that will be queried at startup and compared against `POSTGRESQL_SCHEMA_VERSION`, defined in `src/database_postgres.cc`, to make sure there is an agreement on the schema version. It is hardcoded because schema changes will usually result in query changes.
Aside from having to properly setup and startup a PostgreSQL server (see `postgres/README.txt`), there are quite a few specific extra options (`PostgreSQL.*`) that should be properly configured to be able to reach the database.
## Running
For testing purposes you could simply compile and launch the application from the shell, but if you plan to run the game server on a dedicated machine, it is recommended that it is setup as a service. There is a *systemd* configuration file (`tibia-querymanager.service`) in the repository that may be used for that purpose. The process is very similar to the one described in the [Game Server](https://github.com/fusion32/tibia-game) so I won't repeat myself here.
## Text Encoding
The original game client and server uses LATIN1 text encoding, which can be a problem if we're assuming strings are UTF8 encoded. For that reason, `TReadBuffer::ReadString` will automatically convert from LATIN1 to UTF8, and `TWriteBuffer::WriteString` will automatically convert from UTF8 to LATIN1, to ensure that LATIN1 is still used as the text encoding of the underlying protocol. This behaviour can be disabled with the `-DCLIENT_ENCODING_UTF8=1` compilation flag but unless you move this encoding bridge to the server-client boundary, you'll have problems. And it's not such a simple task either. Upgrading the game server to UTF8 would require updating game files, changing the script parser, and would ultimately make it incompatible with the leaked game files.

View file

@ -0,0 +1,41 @@
# HostCache Config
MaxCachedHostNames = 100
HostNameExpireTime = 30m
# SQLite Config
SQLite.File = "tibia.db"
SQLite.MaxCachedStatements = 100
# PostgreSQL Config
# NOTE(fusion): These options are passed directly to `PQconnectdbParams`.
# Empty values are ignored, meaning their defaults will be used instead.
# For more information see:
# https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
PostgreSQL.Host = ""
PostgreSQL.Port = ""
PostgreSQL.DBName = "tibia"
PostgreSQL.User = "tibia"
PostgreSQL.Password = ""
PostgreSQL.ConnectTimeout = ""
PostgreSQL.ApplicationName = "QueryManager"
PostgreSQL.SSLMode = ""
PostgreSQL.SSLRootCert = ""
PostgreSQL.MaxCachedStatements = 100
# MariaDB Config
MariaDB.Host = "localhost"
MariaDB.Port = "3306"
MariaDB.DBName = "tibia"
MariaDB.User = "tibia"
MariaDB.Password = ""
MariaDB.UnixSocket = ""
MariaDB.MaxCachedStatements = 100
# Connection Config
QueryManagerPort = 7173
QueryManagerPassword = "a6glaf0c"
QueryWorkerThreads = 1
QueryBufferSize = 1M
QueryMaxAttempts = 3
MaxConnections = 25
MaxConnectionIdleTime = 5m

View file

@ -0,0 +1,146 @@
WARNING: This is not meant to be a complete guide on PostgreSQL, but rather a
"first steps" kind of guide. It'll only cover things on the surface level. For
a deep dive into how the database operates, how to properly configure it, and
ultimately properly administrate it, you MUST refer to the PostgreSQL manual
for your version. The most current version of the manual will describe the most
recent features, but not all features are present in all versions.
If anything, you should absolutely consult the section that regards server
administration "III. Server Administration".
MANUAL https://www.postgresql.org/docs/current/index.html
Installation
------------
PostgreSQL is available in most Linux distributions as a package which is
the preferred way to get it installed. Some will automatically setup a service,
create service users, initialize the database cluster, etc... If not, you might
need to do one or more steps manually. If you're having trouble, most systems
will have specific instructions on how to set everything up. Just as an example
here are a few links for common systems:
DEBIAN https://www.postgresql.org/download/linux/debian/
REDHAT https://www.postgresql.org/download/linux/redhat/
SUSE https://www.postgresql.org/download/linux/suse/
UBUNTU https://www.postgresql.org/download/linux/ubuntu/
ARCH https://wiki.archlinux.org/title/PostgreSQL
Configuration
-------------
By default, configuration files will be in the `data` directory which can
change locations depending on how the server was installed but is usually in
`/var/lib/postgres/data`.
All files in the `data` directory are OWNED by the *postgres* SYSTEM user,
meaning you'll only be able to modify them if you're logged in as *postgres*,
by using *sudo* privileges, or both with `sudo su postgres`.
The bulk of the configuration is inside `postgresql.conf` which has multiple
options, but of particular interest are the "CONNECTIONS AND AUTHENTICATION"
options. I won't go over specifics here but if you're planning on accepting
remote connections, you MUST properly configure SSL communication.
Access to the database is controlled with `pg_hba.conf`. This is different
from MySQL where you'd specify users as 'user'@'host' with SQL to restrict
them to certain hosts. Instead you need to specify how certain users/roles
may connect to the database in this file. Properly configuring it is probably
the most important step in securing the database, aside from configuring SSL
communication.
The last file is `pg_ident.conf` which declares mappings from system users
to database users. These mappings alone don't do anything. They must be
explicitly referenced as `map=MAPNAME` in `pg_hba.conf` for supported
authentication methods.
Here is an example of a `pg_hba.conf` + `pg_ident.conf` local access config.
It'll allow *systemuser* to connect as *postgres* to any database using the
*peer* method which checks the system user name. It'll also allow the *tibia*
user to connect to the *tibia* database using the *scram-sha-256* password
authentication scheme. Local connections will use UNIX-domain sockets and for
that matter you'd leave `PostgreSQL.Host` empty.
```
# pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer map=super
local tibia tibia scram-sha-256
# pg_ident.conf
# MAPNAME SYSTEM-USERNAME PG-USERNAME
super systemuser postgres
```
MANUAL https://www.postgresql.org/docs/current/runtime-config.html
MANUAL https://www.postgresql.org/docs/current/client-authentication.html
Database Setup
--------------
It is highly advised to not use a SUPERUSER when connecting to the database
from the query manager, or any other service for that matter. This warrants the
creation of a secondary user that has access, but not administrative privileges.
I figured it would be simpler to have a sequence of *PSQL* commands with their
descriptions. Having a database minimaly ready for the query manager should be
a matter of following this sequence.
Unless a database is specified, *PSQL* will connect to one with the same name
as the specified user. If the user is not explicitly specified, the system user
name will be used. Running `psql -U postgres` will connect to *postgres* as the
user *postgres*. Note that you can't connect without a database, so you'd connect
to *postgres* in order to create new databases.
1 - Create and connect to a new database. Note that the `OWNER = postgres` clause
is redundant here but it's just to show that having the database owned by the
super user is intended.
```
psql -U postgres -c "CREATE DATABASE tibia OWNER = postgres;"
psql -U postgres tibia
```
2 - Set default privileges. Newly created databases may have some default PUBLIC
privileges that we'll want to revoke to make sure the set of users that are able
to connect is tighly controlled. Then, for users that are able to connect, we
want to grant default access privileges on tables, while revoking the ability to
create or rename objects (tables, views, sequences, indexes). Note that a schema
in PostgreSQL is just a namespace for objects and new databases should have the
*public* schema created by default.
```
REVOKE ALL ON DATABASE tibia FROM PUBLIC;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE
ON TABLES TO PUBLIC;
```
3 - Initialize schema. This is done by executing commands from `postgres/schema.sql`,
and optionally `postgres/initial-data.sql`. Note that since we set default privileges
before creating any tables, they should already have the approppriate privileges.
If done the other way around, we'd need to manually update table privileges.
```
\i postgres/schema.sql
\i postgres/initial-data.sql
```
4 - Create secondary user. This is straighforward. Create a user with *LOGIN*
privileges and a *PASSWORD*. Then grant *CONNECT* privileges to the database.
```
CREATE ROLE tibia WITH LOGIN PASSWORD '********';
GRANT CONNECT ON DATABASE tibia TO tibia;
```
This is just one way. There are probably other, more optimal setups, but
for a small testing bench, it will do. And don't take my word on anything.
You should always check the manual for a complete description on how things
work.
To wrap, here is a list of helpful commands available in *PSQL*. They'll
show up along with a lot of other commands when running `\?`.
```
\q # quit
\l # list databases (will show database privileges)
\du # list users (will show user privileges)
\dO # list collations
\dt # list tables
\dv # list views
\ds # list sequences
\di # list indexes
\d NAME # describe table/view/sequence/index
\dp # list privileges
\ddp # list default privileges
```
MANUAL https://www.postgresql.org/docs/current/sql-commands.html

View file

@ -0,0 +1,333 @@
-- NOTE(fusion): Everything is inside a transaction to avoid errors from leaving
-- the database in some partial state. Also, notice we don't use `IF NOT EXISTS`
-- because it could also leave the database in a bad state if for example, some
-- old version of a table already existed.
--==============================================================================
BEGIN;
-- IMPORTANT(fusion): PosgreSQL doesn't have a defined `NOCASE` collation like
-- SQLite and doesn't use a default case-insensitive collation like MySQL. The
-- simplest alternative is to create a custom non-deterministic ICU collation.
-- ICU as a collation provider is supported with PostgreSQL 10+, while
-- non-deterministic collations are supported with PostgreSQL 12+. Either way,
-- it should be safe to assume that it's widely supported, given that version
-- 12 is roughly 6 years old and well past its end-of-life.
-- There are also drawbacks from using these types of collations but I won't
-- go into details. For more information see:
-- https://www.postgresql.org/docs/current/collation.html
CREATE COLLATION NOCASE (
provider = icu,
deterministic = false,
locale = 'und-u-ks-level2'
);
-- IMPORTANT(fusion): Since we're already assuming PostgreSQL 12+ for collations,
-- it's probably a good idea to use IDENTITY columns instead of SERIAL. They're
-- supported with PostgreSQL 10+ and are supposed so fix some shortcommings of
-- SERIAL.
-- TODO(fusion): SQLite tables didn't use foreign key constraints so I'm also not
-- using them here. It might be a good idea for consistency, but it's not a hard
-- requirement.
-- NOTE(fusion): A table with schema information. It currently only contains the
-- schema version which is checked at startup against `POSTGRESQL_SCHEMA_VERSION`,
-- defined in `database_postgres.cc`. The query manager will only startup if the
-- versions match.
CREATE TABLE SchemaInfo (
Key TEXT NOT NULL COLLATE NOCASE,
Value TEXT NOT NULL,
PRIMARY KEY (Key)
);
INSERT INTO SchemaInfo (Key, Value) VALUES ('VERSION', '1');
-- Primary Tables
--==============================================================================
CREATE TABLE Worlds (
WorldID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
Name TEXT NOT NULL COLLATE NOCASE,
Type SMALLINT NOT NULL,
RebootTime SMALLINT NOT NULL,
Host TEXT NOT NULL,
Port INTEGER NOT NULL,
MaxPlayers SMALLINT NOT NULL,
PremiumPlayerBuffer SMALLINT NOT NULL,
MaxNewbies SMALLINT NOT NULL,
PremiumNewbieBuffer SMALLINT NOT NULL,
OnlinePeak SMALLINT NOT NULL DEFAULT 0,
OnlinePeakTimestamp TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
LastStartup TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
LastShutdown TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
PRIMARY KEY (WorldID),
UNIQUE (Name)
);
CREATE TABLE Accounts (
AccountID INTEGER NOT NULL,
Email TEXT NOT NULL COLLATE NOCASE,
Auth BYTEA NOT NULL,
PremiumEnd TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
PendingPremiumDays SMALLINT NOT NULL DEFAULT 0,
Deleted BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (AccountID),
UNIQUE (Email)
);
CREATE TABLE Characters (
WorldID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
AccountID INTEGER NOT NULL,
Name TEXT NOT NULL COLLATE NOCASE,
Sex SMALLINT NOT NULL,
Level SMALLINT NOT NULL DEFAULT 0,
Profession TEXT NOT NULL DEFAULT '',
Residence TEXT NOT NULL DEFAULT '',
LastLoginTime TIMESTAMPTZ NOT NULL DEFAULT 'epoch',
TutorActivities INTEGER NOT NULL DEFAULT 0,
IsOnline SMALLINT NOT NULL DEFAULT 0,
Deleted BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (CharacterID),
UNIQUE (Name)
);
CREATE INDEX CharactersWorldIndex ON Characters(WorldID, IsOnline);
CREATE INDEX CharactersAccountIndex ON Characters(AccountID, IsOnline);
-- NOTE(fusion): It seems `RIGHT` is a reserved keyword and trying to use
-- it as a column name will generate an error.
CREATE TABLE CharacterRights (
CharacterID INTEGER NOT NULL,
Name TEXT NOT NULL COLLATE NOCASE,
PRIMARY KEY(CharacterID, Name)
);
CREATE TABLE CharacterDeaths (
CharacterID INTEGER NOT NULL,
Level SMALLINT NOT NULL,
OffenderID INTEGER NOT NULL,
Remark TEXT NOT NULL,
Unjustified BOOLEAN NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL
);
CREATE INDEX CharacterDeathsCharacterIndex ON CharacterDeaths(CharacterID, Timestamp);
CREATE INDEX CharacterDeathsOffenderIndex ON CharacterDeaths(OffenderID, Timestamp);
CREATE INDEX CharacterDeathsTimeIndex ON CharacterDeaths(Timestamp);
CREATE TABLE Buddies (
WorldID INTEGER NOT NULL,
AccountID INTEGER NOT NULL,
BuddyID INTEGER NOT NULL,
PRIMARY KEY (WorldID, AccountID, BuddyID)
);
CREATE TABLE WorldInvitations (
WorldID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL,
PRIMARY KEY (WorldID, CharacterID)
);
CREATE TABLE LoginAttempts (
AccountID INTEGER NOT NULL,
IPAddress INET NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL,
Failed BOOLEAN NOT NULL
);
CREATE INDEX LoginAttemptsAccountIndex ON LoginAttempts(AccountID, Timestamp);
CREATE INDEX LoginAttemptsAddressIndex ON LoginAttempts(IPAddress, Timestamp);
-- Guild Tables
--==============================================================================
CREATE TABLE Guilds (
WorldID INTEGER NOT NULL,
GuildID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
Name TEXT NOT NULL COLLATE NOCASE,
LeaderID INTEGER NOT NULL,
Created TIMESTAMPTZ NOT NULL,
PRIMARY KEY (GuildID),
UNIQUE (Name),
UNIQUE (LeaderID)
);
CREATE TABLE GuildRanks (
GuildID INTEGER NOT NULL,
Rank SMALLINT NOT NULL,
Name TEXT NOT NULL,
PRIMARY KEY (GuildID, Rank)
);
CREATE TABLE GuildMembers (
GuildID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL,
Rank SMALLINT NOT NULL,
Title TEXT NOT NULL,
Joined TIMESTAMPTZ NOT NULL,
PRIMARY KEY (CharacterID)
);
CREATE INDEX GuildMembersGuildIndex ON GuildMembers(GuildID, Rank);
CREATE TABLE GuildInvites (
GuildID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL,
RecruiterID INTEGER NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL,
PRIMARY KEY (GuildID, CharacterID)
);
CREATE INDEX GuildInvitesCharacterIndex ON GuildInvites(CharacterID);
CREATE INDEX GuildInvitesRecruiterIndex ON GuildInvites(RecruiterID);
-- House Tables
--==============================================================================
CREATE TABLE Houses (
WorldID INTEGER NOT NULL,
HouseID INTEGER NOT NULL,
Name TEXT NOT NULL,
Rent INTEGER NOT NULL,
Description TEXT NOT NULL,
Size INTEGER NOT NULL,
PositionX INTEGER NOT NULL,
PositionY INTEGER NOT NULL,
PositionZ INTEGER NOT NULL,
Town TEXT NOT NULL,
GuildHouse BOOLEAN NOT NULL,
PRIMARY KEY (WorldID, HouseID)
);
CREATE TABLE HouseOwners (
WorldID INTEGER NOT NULL,
HouseID INTEGER NOT NULL,
OwnerID INTEGER NOT NULL,
PaidUntil TIMESTAMPTZ NOT NULL,
PRIMARY KEY (WorldID, HouseID)
);
-- NOTE(fusion): Auctions with a NULL `FinishTime` aren't active, to avoid running
-- multiple times with no actual bidder. It should be set after the first bid along
-- with `BidderID` and `BidAmount`.
CREATE TABLE HouseAuctions (
WorldID INTEGER NOT NULL,
HouseID INTEGER NOT NULL,
BidderID INTEGER DEFAULT NULL,
BidAmount INTEGER DEFAULT NULL,
FinishTime TIMESTAMPTZ DEFAULT NULL,
PRIMARY KEY (WorldID, HouseID)
);
CREATE TABLE HouseTransfers (
WorldID INTEGER NOT NULL,
HouseID INTEGER NOT NULL,
NewOwnerID INTEGER NOT NULL,
Price INTEGER NOT NULL,
PRIMARY KEY (WorldID, HouseID)
);
CREATE TABLE HouseAuctionExclusions (
CharacterID INTEGER NOT NULL,
Issued TIMESTAMPTZ NOT NULL,
Until TIMESTAMPTZ NOT NULL,
BanishmentID INTEGER NOT NULL
);
CREATE INDEX HouseAuctionExclusionsIndex ON HouseAuctionExclusions(CharacterID, Until);
CREATE TABLE HouseAssignments (
WorldID INTEGER NOT NULL,
HouseID INTEGER NOT NULL,
OwnerID INTEGER NOT NULL,
Price INTEGER NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL
);
CREATE INDEX HouseAssignmentsHouseIndex ON HouseAssignments(WorldID, HouseID);
CREATE INDEX HouseAssignmentsTimeIndex ON HouseAssignments(WorldID, Timestamp);
CREATE INDEX HouseAssignmentsOwnerIndex ON HouseAssignments(OwnerID);
-- Banishment Tables
--==============================================================================
CREATE TABLE Banishments (
BanishmentID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
AccountID INTEGER NOT NULL,
IPAddress INET NOT NULL,
GamemasterID INTEGER NOT NULL,
Reason TEXT NOT NULL,
Comment TEXT NOT NULL,
FinalWarning BOOLEAN NOT NULL,
Issued TIMESTAMPTZ NOT NULL,
Until TIMESTAMPTZ NOT NULL,
PRIMARY KEY (BanishmentID)
);
CREATE INDEX BanishmentsAccountIndex ON Banishments(AccountID, Until, FinalWarning);
CREATE TABLE IPBanishments (
CharacterID INTEGER NOT NULL,
IPAddress INET NOT NULL,
GamemasterID INTEGER NOT NULL,
Reason TEXT NOT NULL,
Comment TEXT NOT NULL,
Issued TIMESTAMPTZ NOT NULL,
Until TIMESTAMPTZ NOT NULL
);
CREATE INDEX IPBanishmentsAddressIndex ON IPBanishments(IPAddress);
CREATE INDEX IPBanishmentsCharacterIndex ON IPBanishments(CharacterID);
CREATE TABLE Namelocks (
CharacterID INTEGER NOT NULL,
IPAddress INET NOT NULL,
GamemasterID INTEGER NOT NULL,
Reason TEXT NOT NULL,
Comment TEXT NOT NULL,
Attempts INTEGER NOT NULL DEFAULT 0,
Approved BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (CharacterID)
);
CREATE TABLE Notations (
CharacterID INTEGER NOT NULL,
IPAddress INET NOT NULL,
GamemasterID INTEGER NOT NULL,
Reason TEXT NOT NULL,
Comment TEXT NOT NULL
);
CREATE INDEX NotationsCharacterIndex ON Notations(CharacterID);
CREATE TABLE Statements (
WorldID INTEGER NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL,
StatementID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL,
Channel TEXT NOT NULL,
Text TEXT NOT NULL,
PRIMARY KEY (WorldID, Timestamp, StatementID)
);
CREATE INDEX StatementsCharacterIndex ON Statements(CharacterID, Timestamp);
CREATE TABLE ReportedStatements (
WorldID INTEGER NOT NULL,
Timestamp TIMESTAMPTZ NOT NULL,
StatementID INTEGER NOT NULL,
CharacterID INTEGER NOT NULL,
BanishmentID INTEGER NOT NULL,
ReporterID INTEGER NOT NULL,
Reason TEXT NOT NULL,
Comment TEXT NOT NULL,
PRIMARY KEY (WorldID, Timestamp, StatementID)
);
CREATE INDEX ReportedStatementsCharacterIndex ON ReportedStatements(CharacterID, Timestamp);
CREATE INDEX ReportedStatementsBanishmentIndex ON ReportedStatements(BanishmentID);
-- Info Tables
--==============================================================================
CREATE TABLE KillStatistics (
WorldID INTEGER NOT NULL,
RaceName TEXT NOT NULL COLLATE NOCASE,
TimesKilled INTEGER NOT NULL,
PlayersKilled INTEGER NOT NULL,
PRIMARY KEY (WorldID, RaceName)
);
CREATE TABLE OnlineCharacters (
WorldID INTEGER NOT NULL,
Name TEXT NOT NULL COLLATE NOCASE,
Level SMALLINT NOT NULL,
Profession TEXT NOT NULL,
PRIMARY KEY (WorldID, Name)
);
COMMIT;

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