6 Commits

Author SHA1 Message Date
a87c8aadbd Merge 91589b18c1 into 8568fd1c46 2024-10-27 18:56:26 +00:00
91589b18c1 More cleanup 2024-10-27 11:56:19 -07:00
02a5632147 Get rid of unnecessary templating 2024-10-27 01:50:45 -07:00
bfa3a8c04e Use increased buffer size for 728 and 1013 protocols 2024-10-27 01:25:58 -07:00
gsemaj
95181b1058 Fix build 2024-10-27 00:39:49 -07:00
83ba121f5f Use FE2CL_..._AROUND, _AROUND_DEL packets 2024-10-27 00:33:14 -07:00
26 changed files with 244 additions and 395 deletions

View File

@@ -1,33 +1,28 @@
# build # build
FROM alpine:3 as build FROM debian:stable-slim AS build
WORKDIR /usr/src/app WORKDIR /usr/src/app
RUN apk update && apk upgrade && apk add \ RUN apt-get -y update && apt-get install -y \
linux-headers \
git \ git \
clang18 \ clang \
make \ make \
sqlite-dev libsqlite3-dev
COPY src ./src COPY src ./src
COPY vendor ./vendor COPY vendor ./vendor
COPY .git ./.git COPY .git ./.git
COPY Makefile CMakeLists.txt version.h.in ./ COPY Makefile CMakeLists.txt version.h.in ./
RUN sed -i 's/^CC=clang$/&-18/' Makefile
RUN sed -i 's/^CXX=clang++$/&-18/' Makefile
RUN make nosandbox -j$(nproc) RUN make nosandbox -j$(nproc)
# prod # prod
FROM alpine:3 FROM debian:stable-slim
WORKDIR /usr/src/app WORKDIR /usr/src/app
RUN apk update && apk upgrade && apk add \ RUN apt-get -y update && apt-get install -y \
libstdc++ \ libsqlite3-dev
sqlite-dev
COPY --from=build /usr/src/app/bin/fusion /bin/fusion COPY --from=build /usr/src/app/bin/fusion /bin/fusion
COPY sql ./sql COPY sql ./sql
@@ -36,6 +31,6 @@ CMD ["/bin/fusion"]
EXPOSE 23000/tcp EXPOSE 23000/tcp
EXPOSE 23001/tcp EXPOSE 23001/tcp
EXPOSE 8003/tcp EXPOSE 8001/tcp
LABEL Name=openfusion Version=1.6.0 LABEL Name=openfusion Version=1.6.0

View File

@@ -115,7 +115,6 @@ CXXHDR=\
src/settings.hpp\ src/settings.hpp\
src/Transport.hpp\ src/Transport.hpp\
src/TableData.hpp\ src/TableData.hpp\
src/Bucket.hpp\
src/Chunking.hpp\ src/Chunking.hpp\
src/Buddies.hpp\ src/Buddies.hpp\
src/Groups.hpp\ src/Groups.hpp\

View File

@@ -18,8 +18,8 @@ acceptallcustomnames=true
# automatically create them? # automatically create them?
autocreateaccounts=true autocreateaccounts=true
# list of supported authentication methods (comma-separated) # list of supported authentication methods (comma-separated)
# password = allow logging in with plaintext passwords # password = allow login type 1 with plaintext passwords
# cookie = allow logging in with one-shot auth cookies # cookie = allow login type 2 with one-shot auth cookies
authmethods=password authmethods=password
# how often should everything be flushed to the database? # how often should everything be flushed to the database?
# the default is 4 minutes # the default is 4 minutes

View File

@@ -1,8 +0,0 @@
BEGIN TRANSACTION;
-- New Columns
ALTER TABLE Accounts ADD Email TEXT DEFAULT '' NOT NULL;
ALTER TABLE Accounts ADD LastPasswordReset INTEGER DEFAULT 0 NOT NULL;
-- Update DB Version
UPDATE Meta SET Value = 6 WHERE Key = 'DatabaseVersion';
UPDATE Meta SET Value = strftime('%s', 'now') WHERE Key = 'LastMigration';
COMMIT;

View File

@@ -1,16 +1,14 @@
CREATE TABLE IF NOT EXISTS Accounts ( CREATE TABLE IF NOT EXISTS Accounts (
AccountID INTEGER NOT NULL, AccountID INTEGER NOT NULL,
Login TEXT NOT NULL UNIQUE COLLATE NOCASE, Login TEXT NOT NULL UNIQUE COLLATE NOCASE,
Password TEXT NOT NULL, Password TEXT NOT NULL,
Selected INTEGER DEFAULT 1 NOT NULL, Selected INTEGER DEFAULT 1 NOT NULL,
AccountLevel INTEGER NOT NULL, AccountLevel INTEGER NOT NULL,
Created INTEGER DEFAULT (strftime('%s', 'now')) NOT NULL, Created INTEGER DEFAULT (strftime('%s', 'now')) NOT NULL,
LastLogin INTEGER DEFAULT (strftime('%s', 'now')) NOT NULL, LastLogin INTEGER DEFAULT (strftime('%s', 'now')) NOT NULL,
BannedUntil INTEGER DEFAULT 0 NOT NULL, BannedUntil INTEGER DEFAULT 0 NOT NULL,
BannedSince INTEGER DEFAULT 0 NOT NULL, BannedSince INTEGER DEFAULT 0 NOT NULL,
BanReason TEXT DEFAULT '' NOT NULL, BanReason TEXT DEFAULT '' NOT NULL,
Email TEXT DEFAULT '' NOT NULL,
LastPasswordReset INTEGER DEFAULT 0 NOT NULL,
PRIMARY KEY(AccountID AUTOINCREMENT) PRIMARY KEY(AccountID AUTOINCREMENT)
); );

View File

@@ -334,8 +334,8 @@ void Abilities::useNanoSkill(CNSocket* sock, SkillData* skill, sNano& nano, std:
size_t resplen = sizeof(sP_FE2CL_NANO_SKILL_USE_SUCC); size_t resplen = sizeof(sP_FE2CL_NANO_SKILL_USE_SUCC);
for(SkillResult& sr : results) for(SkillResult& sr : results)
resplen += sr.size; resplen += sr.size;
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_NANO_SKILL_USE_SUCC* pkt = (sP_FE2CL_NANO_SKILL_USE_SUCC*)respbuf; sP_FE2CL_NANO_SKILL_USE_SUCC* pkt = (sP_FE2CL_NANO_SKILL_USE_SUCC*)respbuf;
pkt->iPC_ID = plr->iID; pkt->iPC_ID = plr->iID;
@@ -379,8 +379,8 @@ void Abilities::useNPCSkill(EntityRef npc, int skillID, std::vector<ICombatant*>
size_t resplen = sizeof(sP_FE2CL_NPC_SKILL_HIT); size_t resplen = sizeof(sP_FE2CL_NPC_SKILL_HIT);
for(SkillResult& sr : results) for(SkillResult& sr : results)
resplen += sr.size; resplen += sr.size;
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_NPC_SKILL_HIT* pkt = (sP_FE2CL_NPC_SKILL_HIT*)respbuf; sP_FE2CL_NPC_SKILL_HIT* pkt = (sP_FE2CL_NPC_SKILL_HIT*)respbuf;
pkt->iNPC_ID = npc.id; pkt->iNPC_ID = npc.id;

View File

@@ -1,40 +0,0 @@
#pragma once
#include <array>
#include <optional>
#include <assert.h>
template<class T, size_t N>
class Bucket {
std::array<T, N> buf;
size_t sz;
public:
Bucket() {
sz = 0;
}
void add(const T& item) {
assert(sz < N);
buf[sz++] = item;
}
std::optional<T> get(size_t idx) const {
if (idx < sz) {
return buf[idx];
}
return std::nullopt;
}
size_t size() const {
return sz;
}
bool isFull() const {
return sz == N;
}
void clear() {
sz = 0;
}
};

View File

@@ -41,9 +41,9 @@ void Buddies::sendBuddyList(CNSocket* sock) {
// initialize response struct // initialize response struct
size_t resplen = sizeof(sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC) + buddyCnt * sizeof(sBuddyBaseInfo); size_t resplen = sizeof(sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC) + buddyCnt * sizeof(sBuddyBaseInfo);
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC* resp = (sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC*)respbuf; sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC* resp = (sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC*)respbuf;
sBuddyBaseInfo* respdata = (sBuddyBaseInfo*)(respbuf + sizeof(sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC)); sBuddyBaseInfo* respdata = (sBuddyBaseInfo*)(respbuf + sizeof(sP_FE2CL_REP_PC_BUDDYLIST_INFO_SUCC));

View File

@@ -178,9 +178,9 @@ void Buffs::tickDrain(EntityRef self, Buff* buff, int mult) {
int dealt = combatant->takeDamage(buff->getLastSource(), damage); int dealt = combatant->takeDamage(buff->getLastSource(), damage);
size_t resplen = sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK) + sizeof(sSkillResult_Damage); size_t resplen = sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK) + sizeof(sSkillResult_Damage);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK *pkt = (sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK*)respbuf; sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK *pkt = (sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK*)respbuf;
pkt->iID = self.id; pkt->iID = self.id;

View File

@@ -3,7 +3,6 @@
#include "Player.hpp" #include "Player.hpp"
#include "MobAI.hpp" #include "MobAI.hpp"
#include "NPCManager.hpp" #include "NPCManager.hpp"
#include "Bucket.hpp"
#include <assert.h> #include <assert.h>
@@ -13,12 +12,11 @@ using namespace Chunking;
* The initial chunkPos value before a player is placed into the world. * The initial chunkPos value before a player is placed into the world.
*/ */
const ChunkPos Chunking::INVALID_CHUNK = {}; const ChunkPos Chunking::INVALID_CHUNK = {};
constexpr size_t MAX_PC_PER_AROUND = (CN_PACKET_BODY_SIZE - sizeof(int32_t)) / sizeof(sPCAppearanceData); constexpr size_t MAX_PC_PER_AROUND = (CN_PACKET_BUFFER_SIZE - 4) / sizeof(sPCAppearanceData);
constexpr size_t MAX_NPC_PER_AROUND = (CN_PACKET_BODY_SIZE - sizeof(int32_t)) / sizeof(sNPCAppearanceData); constexpr size_t MAX_NPC_PER_AROUND = (CN_PACKET_BUFFER_SIZE - 4) / sizeof(sNPCAppearanceData);
constexpr size_t MAX_SHINY_PER_AROUND = (CN_PACKET_BODY_SIZE - sizeof(int32_t)) / sizeof(sShinyAppearanceData); constexpr size_t MAX_SHINY_PER_AROUND = (CN_PACKET_BUFFER_SIZE - 4) / sizeof(sShinyAppearanceData);
constexpr size_t MAX_TRANSPORTATION_PER_AROUND = (CN_PACKET_BODY_SIZE - sizeof(int32_t)) / sizeof(sTransportationAppearanceData); constexpr size_t MAX_TRANSPORTATION_PER_AROUND = (CN_PACKET_BUFFER_SIZE - 4) / sizeof(sTransportationAppearanceData);
constexpr size_t MAX_IDS_PER_AROUND_DEL = (CN_PACKET_BODY_SIZE - sizeof(int32_t)) / sizeof(int32_t); constexpr size_t MAX_IDS_PER_AROUND_DEL = (CN_PACKET_BUFFER_SIZE - 4) / sizeof(int32_t);
constexpr size_t MAX_TRANSPORTATION_IDS_PER_AROUND_DEL = MAX_IDS_PER_AROUND_DEL - 1; // 1 less for eTT
std::map<ChunkPos, Chunk*> Chunking::chunks; std::map<ChunkPos, Chunk*> Chunking::chunks;
@@ -83,35 +81,39 @@ void Chunking::untrackEntity(ChunkPos chunkPos, const EntityRef ref) {
deleteChunk(chunkPos); deleteChunk(chunkPos);
} }
template<class T, size_t N> template<class T>
static void sendAroundPackets(const EntityRef recipient, std::vector<Bucket<T, N>>& buckets, uint32_t packetId) { static void sendAroundPacket(const EntityRef recipient, std::vector<std::vector<T>>& slices, size_t maxCnt, uint32_t packetId) {
assert(recipient.kind == EntityKind::PLAYER); assert(recipient.kind == EntityKind::PLAYER);
uint8_t pktBuf[CN_PACKET_BODY_SIZE]; uint8_t pktBuf[CN_PACKET_BUFFER_SIZE];
for (const auto& bucket : buckets) { for (const auto& slice : slices) {
memset(pktBuf, 0, CN_PACKET_BODY_SIZE); memset(pktBuf, 0, CN_PACKET_BUFFER_SIZE);
int count = bucket.size(); int count = slice.size();
assert(count <= maxCnt);
*((int32_t*)pktBuf) = count; *((int32_t*)pktBuf) = count;
T* data = (T*)(pktBuf + sizeof(int32_t)); T* data = (T*)(pktBuf + sizeof(int32_t));
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
data[i] = bucket.get(i).value(); data[i] = slice[i];
} }
recipient.sock->sendPacket(pktBuf, packetId, sizeof(int32_t) + (count * sizeof(T))); recipient.sock->sendPacket(pktBuf, packetId, sizeof(int32_t) + (count * sizeof(T)));
} }
} }
template<size_t N> static void sendAroundDelPacket(const EntityRef recipient, std::vector<std::vector<int32_t>>& slices, bool isTransportation, uint32_t packetId) {
static void sendAroundDelPackets(const EntityRef recipient, std::vector<Bucket<int32_t, N>>& buckets, uint32_t packetId) {
assert(recipient.kind == EntityKind::PLAYER); assert(recipient.kind == EntityKind::PLAYER);
uint8_t pktBuf[CN_PACKET_BODY_SIZE]; size_t maxCnt = MAX_IDS_PER_AROUND_DEL;
for (const auto& bucket : buckets) { if (isTransportation)
memset(pktBuf, 0, CN_PACKET_BODY_SIZE); maxCnt -= 1; // account for eTT. sad.
int count = bucket.size();
assert(count <= N); uint8_t pktBuf[CN_PACKET_BUFFER_SIZE];
for (const auto& slice : slices) {
memset(pktBuf, 0, CN_PACKET_BUFFER_SIZE);
int count = slice.size();
assert(count <= maxCnt);
size_t baseSize; size_t baseSize;
if (packetId == P_FE2CL_AROUND_DEL_TRANSPORTATION) { if (isTransportation) {
sP_FE2CL_AROUND_DEL_TRANSPORTATION* pkt = (sP_FE2CL_AROUND_DEL_TRANSPORTATION*)pktBuf; sP_FE2CL_AROUND_DEL_TRANSPORTATION* pkt = (sP_FE2CL_AROUND_DEL_TRANSPORTATION*)pktBuf;
pkt->eTT = 3; pkt->eTT = 3;
pkt->iCnt = count; pkt->iCnt = count;
@@ -123,40 +125,39 @@ static void sendAroundDelPackets(const EntityRef recipient, std::vector<Bucket<i
int32_t* ids = (int32_t*)(pktBuf + baseSize); int32_t* ids = (int32_t*)(pktBuf + baseSize);
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
ids[i] = bucket.get(i).value(); ids[i] = slice[i];
} }
recipient.sock->sendPacket(pktBuf, packetId, baseSize + (count * sizeof(int32_t))); recipient.sock->sendPacket(pktBuf, packetId, baseSize + (count * sizeof(int32_t)));
} }
} }
template<class T, size_t N> template<class T>
static void bufferAppearanceData(std::vector<Bucket<T, N>>& buckets, const T& data) { static void bufferAppearanceData(std::vector<std::vector<T>>& slices, const T& data, size_t maxCnt) {
if (buckets.empty()) if (slices.empty())
buckets.push_back({}); slices.push_back(std::vector<T>());
auto& bucket = buckets[buckets.size() - 1]; std::vector<T>& slice = slices[slices.size() - 1];
bucket.add(data); slice.push_back(data);
if (bucket.isFull()) if (slice.size() == maxCnt)
buckets.push_back({}); slices.push_back(std::vector<T>());
} }
template<size_t N> static void bufferIdForDisappearance(std::vector<std::vector<int32_t>>& slices, int32_t id, size_t maxCnt) {
static void bufferIdForDisappearance(std::vector<Bucket<int32_t, N>>& buckets, int32_t id) { if (slices.empty())
if (buckets.empty()) slices.push_back(std::vector<int32_t>());
buckets.push_back({}); std::vector<int32_t>& slice = slices[slices.size() - 1];
auto& bucket = buckets[buckets.size() - 1]; slice.push_back(id);
bucket.add(id); if (slice.size() == maxCnt)
if (bucket.isFull()) slices.push_back(std::vector<int32_t>());
buckets.push_back({});
} }
void Chunking::addEntityToChunks(std::set<Chunk*> chnks, const EntityRef ref) { void Chunking::addEntityToChunks(std::set<Chunk*> chnks, const EntityRef ref) {
Entity *ent = ref.getEntity(); Entity *ent = ref.getEntity();
bool alive = ent->isExtant(); bool alive = ent->isExtant();
std::vector<Bucket<sPCAppearanceData, MAX_PC_PER_AROUND>> pcAppearances; std::vector<std::vector<sPCAppearanceData>> pcAppearances;
std::vector<Bucket<sNPCAppearanceData, MAX_NPC_PER_AROUND>> npcAppearances; std::vector<std::vector<sNPCAppearanceData>> npcAppearances;
std::vector<Bucket<sShinyAppearanceData, MAX_SHINY_PER_AROUND>> shinyAppearances; std::vector<std::vector<sShinyAppearanceData>> shinyAppearances;
std::vector<Bucket<sTransportationAppearanceData, MAX_TRANSPORTATION_PER_AROUND>> transportationAppearances; std::vector<std::vector<sTransportationAppearanceData>> transportationAppearances;
for (Chunk *chunk : chnks) { for (Chunk *chunk : chnks) {
for (const EntityRef otherRef : chunk->entities) { for (const EntityRef otherRef : chunk->entities) {
// skip oneself // skip oneself
@@ -176,30 +177,31 @@ void Chunking::addEntityToChunks(std::set<Chunk*> chnks, const EntityRef ref) {
sNPCAppearanceData npcData; sNPCAppearanceData npcData;
sShinyAppearanceData eggData; sShinyAppearanceData eggData;
sTransportationAppearanceData busData; sTransportationAppearanceData busData;
switch(otherRef.kind) { switch(otherRef.kind)
{
case EntityKind::PLAYER: case EntityKind::PLAYER:
pcData = dynamic_cast<Player*>(other)->getAppearanceData(); pcData = dynamic_cast<Player*>(other)->getAppearanceData();
bufferAppearanceData(pcAppearances, pcData); bufferAppearanceData(pcAppearances, pcData, MAX_PC_PER_AROUND);
break; break;
case EntityKind::SIMPLE_NPC: case EntityKind::SIMPLE_NPC:
npcData = dynamic_cast<BaseNPC*>(other)->getAppearanceData(); npcData = dynamic_cast<BaseNPC*>(other)->getAppearanceData();
bufferAppearanceData(npcAppearances, npcData); bufferAppearanceData(npcAppearances, npcData, MAX_NPC_PER_AROUND);
break; break;
case EntityKind::COMBAT_NPC: case EntityKind::COMBAT_NPC:
npcData = dynamic_cast<CombatNPC*>(other)->getAppearanceData(); npcData = dynamic_cast<CombatNPC*>(other)->getAppearanceData();
bufferAppearanceData(npcAppearances, npcData); bufferAppearanceData(npcAppearances, npcData, MAX_NPC_PER_AROUND);
break; break;
case EntityKind::MOB: case EntityKind::MOB:
npcData = dynamic_cast<Mob*>(other)->getAppearanceData(); npcData = dynamic_cast<Mob*>(other)->getAppearanceData();
bufferAppearanceData(npcAppearances, npcData); bufferAppearanceData(npcAppearances, npcData, MAX_NPC_PER_AROUND);
break; break;
case EntityKind::EGG: case EntityKind::EGG:
eggData = dynamic_cast<Egg*>(other)->getShinyAppearanceData(); eggData = dynamic_cast<Egg*>(other)->getShinyAppearanceData();
bufferAppearanceData(shinyAppearances, eggData); bufferAppearanceData(shinyAppearances, eggData, MAX_SHINY_PER_AROUND);
break; break;
case EntityKind::BUS: case EntityKind::BUS:
busData = dynamic_cast<Bus*>(other)->getTransportationAppearanceData(); busData = dynamic_cast<Bus*>(other)->getTransportationAppearanceData();
bufferAppearanceData(transportationAppearances, busData); bufferAppearanceData(transportationAppearances, busData, MAX_TRANSPORTATION_PER_AROUND);
break; break;
default: default:
break; break;
@@ -214,26 +216,27 @@ void Chunking::addEntityToChunks(std::set<Chunk*> chnks, const EntityRef ref) {
} }
} }
if (ref.kind == EntityKind::PLAYER) { if (ref.kind != EntityKind::PLAYER)
if (!pcAppearances.empty()) return; // nothing to send
sendAroundPackets(ref, pcAppearances, P_FE2CL_PC_AROUND);
if (!npcAppearances.empty()) if (!pcAppearances.empty())
sendAroundPackets(ref, npcAppearances, P_FE2CL_NPC_AROUND); sendAroundPacket(ref, pcAppearances, MAX_PC_PER_AROUND, P_FE2CL_PC_AROUND);
if (!shinyAppearances.empty()) if (!npcAppearances.empty())
sendAroundPackets(ref, shinyAppearances, P_FE2CL_SHINY_AROUND); sendAroundPacket(ref, npcAppearances, MAX_NPC_PER_AROUND, P_FE2CL_NPC_AROUND);
if (!transportationAppearances.empty()) if (!shinyAppearances.empty())
sendAroundPackets(ref, transportationAppearances, P_FE2CL_TRANSPORTATION_AROUND); sendAroundPacket(ref, shinyAppearances, MAX_SHINY_PER_AROUND, P_FE2CL_SHINY_AROUND);
} if (!transportationAppearances.empty())
sendAroundPacket(ref, transportationAppearances, MAX_TRANSPORTATION_PER_AROUND, P_FE2CL_TRANSPORTATION_AROUND);
} }
void Chunking::removeEntityFromChunks(std::set<Chunk*> chnks, const EntityRef ref) { void Chunking::removeEntityFromChunks(std::set<Chunk*> chnks, const EntityRef ref) {
Entity *ent = ref.getEntity(); Entity *ent = ref.getEntity();
bool alive = ent->isExtant(); bool alive = ent->isExtant();
std::vector<Bucket<int32_t, MAX_IDS_PER_AROUND_DEL>> pcDisappearances; std::vector<std::vector<int32_t>> pcDisappearances;
std::vector<Bucket<int32_t, MAX_IDS_PER_AROUND_DEL>> npcDisappearances; std::vector<std::vector<int32_t>> npcDisappearances;
std::vector<Bucket<int32_t, MAX_IDS_PER_AROUND_DEL>> shinyDisappearances; std::vector<std::vector<int32_t>> shinyDisappearances;
std::vector<Bucket<int32_t, MAX_TRANSPORTATION_IDS_PER_AROUND_DEL>> transportationDisappearances; std::vector<std::vector<int32_t>> transportationDisappearances;
for (Chunk *chunk : chnks) { for (Chunk *chunk : chnks) {
for (const EntityRef otherRef : chunk->entities) { for (const EntityRef otherRef : chunk->entities) {
// skip oneself // skip oneself
@@ -250,24 +253,25 @@ void Chunking::removeEntityFromChunks(std::set<Chunk*> chnks, const EntityRef re
// notify this *player* of the departure of all visible Entities // notify this *player* of the departure of all visible Entities
if (ref.kind == EntityKind::PLAYER && other->isExtant()) { if (ref.kind == EntityKind::PLAYER && other->isExtant()) {
int32_t id; int32_t id;
switch(otherRef.kind) { switch(otherRef.kind)
{
case EntityKind::PLAYER: case EntityKind::PLAYER:
id = dynamic_cast<Player*>(other)->iID; id = dynamic_cast<Player*>(other)->iID;
bufferIdForDisappearance(pcDisappearances, id); bufferIdForDisappearance(pcDisappearances, id, MAX_IDS_PER_AROUND_DEL);
break; break;
case EntityKind::SIMPLE_NPC: case EntityKind::SIMPLE_NPC:
case EntityKind::COMBAT_NPC: case EntityKind::COMBAT_NPC:
case EntityKind::MOB: case EntityKind::MOB:
id = dynamic_cast<BaseNPC*>(other)->id; id = dynamic_cast<BaseNPC*>(other)->id;
bufferIdForDisappearance(npcDisappearances, id); bufferIdForDisappearance(npcDisappearances, id, MAX_IDS_PER_AROUND_DEL);
break; break;
case EntityKind::EGG: case EntityKind::EGG:
id = dynamic_cast<Egg*>(other)->id; id = dynamic_cast<Egg*>(other)->id;
bufferIdForDisappearance(shinyDisappearances, id); bufferIdForDisappearance(shinyDisappearances, id, MAX_IDS_PER_AROUND_DEL);
break; break;
case EntityKind::BUS: case EntityKind::BUS:
id = dynamic_cast<Bus*>(other)->id; id = dynamic_cast<Bus*>(other)->id;
bufferIdForDisappearance(transportationDisappearances, id); bufferIdForDisappearance(transportationDisappearances, id, MAX_IDS_PER_AROUND_DEL - 1);
break; break;
default: default:
break; break;
@@ -282,16 +286,17 @@ void Chunking::removeEntityFromChunks(std::set<Chunk*> chnks, const EntityRef re
} }
} }
if (ref.kind == EntityKind::PLAYER) { if (ref.kind != EntityKind::PLAYER)
if (!pcDisappearances.empty()) return; // nothing to send
sendAroundDelPackets(ref, pcDisappearances, P_FE2CL_AROUND_DEL_PC);
if (!npcDisappearances.empty()) if (!pcDisappearances.empty())
sendAroundDelPackets(ref, npcDisappearances, P_FE2CL_AROUND_DEL_NPC); sendAroundDelPacket(ref, pcDisappearances, false, P_FE2CL_AROUND_DEL_PC);
if (!shinyDisappearances.empty()) if (!npcDisappearances.empty())
sendAroundDelPackets(ref, shinyDisappearances, P_FE2CL_AROUND_DEL_SHINY); sendAroundDelPacket(ref, npcDisappearances, false, P_FE2CL_AROUND_DEL_NPC);
if (!transportationDisappearances.empty()) if (!shinyDisappearances.empty())
sendAroundDelPackets(ref, transportationDisappearances, P_FE2CL_AROUND_DEL_TRANSPORTATION); sendAroundDelPacket(ref, shinyDisappearances, false, P_FE2CL_AROUND_DEL_SHINY);
} if (!transportationDisappearances.empty())
sendAroundDelPacket(ref, transportationDisappearances, true, P_FE2CL_AROUND_DEL_TRANSPORTATION);
} }
static void emptyChunk(ChunkPos chunkPos) { static void emptyChunk(ChunkPos chunkPos) {

View File

@@ -539,9 +539,9 @@ static void dealGooDamage(CNSocket *sock) {
return; // ignore completely return; // ignore completely
size_t resplen = sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK) + sizeof(sSkillResult_DotDamage); size_t resplen = sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK) + sizeof(sSkillResult_DotDamage);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK *pkt = (sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK*)respbuf; sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK *pkt = (sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK*)respbuf;
sSkillResult_DotDamage *dmg = (sSkillResult_DotDamage*)(respbuf + sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK)); sSkillResult_DotDamage *dmg = (sSkillResult_DotDamage*)(respbuf + sizeof(sP_FE2CL_CHAR_TIME_BUFF_TIME_TICK));
@@ -633,9 +633,9 @@ static void pcAttackChars(CNSocket *sock, CNPacketData *data) {
// initialize response struct // initialize response struct
size_t resplen = sizeof(sP_FE2CL_PC_ATTACK_CHARs_SUCC) + pkt->iTargetCnt * sizeof(sAttackResult); size_t resplen = sizeof(sP_FE2CL_PC_ATTACK_CHARs_SUCC) + pkt->iTargetCnt * sizeof(sAttackResult);
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_PC_ATTACK_CHARs_SUCC *resp = (sP_FE2CL_PC_ATTACK_CHARs_SUCC*)respbuf; sP_FE2CL_PC_ATTACK_CHARs_SUCC *resp = (sP_FE2CL_PC_ATTACK_CHARs_SUCC*)respbuf;
sAttackResult *respdata = (sAttackResult*)(respbuf+sizeof(sP_FE2CL_PC_ATTACK_CHARs_SUCC)); sAttackResult *respdata = (sAttackResult*)(respbuf+sizeof(sP_FE2CL_PC_ATTACK_CHARs_SUCC));
@@ -847,9 +847,9 @@ static void projectileHit(CNSocket* sock, CNPacketData* data) {
*/ */
size_t resplen = sizeof(sP_FE2CL_PC_GRENADE_STYLE_HIT) + pkt->iTargetCnt * sizeof(sAttackResult); size_t resplen = sizeof(sP_FE2CL_PC_GRENADE_STYLE_HIT) + pkt->iTargetCnt * sizeof(sAttackResult);
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_PC_GRENADE_STYLE_HIT* resp = (sP_FE2CL_PC_GRENADE_STYLE_HIT*)respbuf; sP_FE2CL_PC_GRENADE_STYLE_HIT* resp = (sP_FE2CL_PC_GRENADE_STYLE_HIT*)respbuf;
sAttackResult* respdata = (sAttackResult*)(respbuf + sizeof(sP_FE2CL_PC_GRENADE_STYLE_HIT)); sAttackResult* respdata = (sAttackResult*)(respbuf + sizeof(sP_FE2CL_PC_GRENADE_STYLE_HIT));

View File

@@ -87,8 +87,8 @@ void Eggs::eggBuffPlayer(CNSocket* sock, int skillId, int eggId, int duration) {
// initialize response struct // initialize response struct
size_t resplen = sizeof(sP_FE2CL_NPC_SKILL_HIT) + result.size; size_t resplen = sizeof(sP_FE2CL_NPC_SKILL_HIT) + result.size;
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_NPC_SKILL_HIT* pkt = (sP_FE2CL_NPC_SKILL_HIT*)respbuf; sP_FE2CL_NPC_SKILL_HIT* pkt = (sP_FE2CL_NPC_SKILL_HIT*)respbuf;
pkt->iNPC_ID = eggId; pkt->iNPC_ID = eggId;
@@ -183,7 +183,7 @@ static void eggPickup(CNSocket* sock, CNPacketData* data) {
// drop // drop
if (type->dropCrateId != 0) { if (type->dropCrateId != 0) {
const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward); const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
uint8_t respbuf[resplen]; // not a variable length array, don't worry uint8_t respbuf[resplen]; // not a variable length array, don't worry

View File

@@ -87,8 +87,8 @@ void Groups::addToGroup(Group* group, EntityRef member) {
size_t pcCount = pcs.size(); size_t pcCount = pcs.size();
size_t npcCount = npcs.size(); size_t npcCount = npcs.size();
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, CN_PACKET_BUFFER_SIZE);
sP_FE2CL_PC_GROUP_JOIN* pkt = (sP_FE2CL_PC_GROUP_JOIN*)respbuf; sP_FE2CL_PC_GROUP_JOIN* pkt = (sP_FE2CL_PC_GROUP_JOIN*)respbuf;
pkt->iID_NewMember = PlayerManager::getPlayer(member.sock)->iID; pkt->iID_NewMember = PlayerManager::getPlayer(member.sock)->iID;
@@ -143,8 +143,8 @@ bool Groups::removeFromGroup(Group* group, EntityRef member) {
size_t pcCount = pcs.size(); size_t pcCount = pcs.size();
size_t npcCount = npcs.size(); size_t npcCount = npcs.size();
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, CN_PACKET_BUFFER_SIZE);
sP_FE2CL_PC_GROUP_LEAVE* pkt = (sP_FE2CL_PC_GROUP_LEAVE*)respbuf; sP_FE2CL_PC_GROUP_LEAVE* pkt = (sP_FE2CL_PC_GROUP_LEAVE*)respbuf;
pkt->iID_LeaveMember = PlayerManager::getPlayer(member.sock)->iID; pkt->iID_LeaveMember = PlayerManager::getPlayer(member.sock)->iID;
@@ -288,8 +288,8 @@ void Groups::groupTickInfo(CNSocket* sock) {
size_t pcCount = pcs.size(); size_t pcCount = pcs.size();
size_t npcCount = npcs.size(); size_t npcCount = npcs.size();
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, CN_PACKET_BUFFER_SIZE);
sP_FE2CL_PC_GROUP_MEMBER_INFO* pkt = (sP_FE2CL_PC_GROUP_MEMBER_INFO*)respbuf; sP_FE2CL_PC_GROUP_MEMBER_INFO* pkt = (sP_FE2CL_PC_GROUP_MEMBER_INFO*)respbuf;
pkt->iID = plr->iID; pkt->iID = plr->iID;

View File

@@ -46,7 +46,7 @@ static void nanoCapsuleHandler(CNSocket* sock, int slot, sItemBase *chest) {
// in order to remove capsule form inventory, we have to send item reward packet with empty item // in order to remove capsule form inventory, we have to send item reward packet with empty item
const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward); const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
uint8_t respbuf[resplen]; // not a variable length array, don't worry uint8_t respbuf[resplen]; // not a variable length array, don't worry
@@ -475,8 +475,8 @@ static void itemUseHandler(CNSocket* sock, CNPacketData* data) {
if (gumball.iOpt == 0) if (gumball.iOpt == 0)
gumball = {}; gumball = {};
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_REP_PC_ITEM_USE_SUCC *resp = (sP_FE2CL_REP_PC_ITEM_USE_SUCC*)respbuf; sP_FE2CL_REP_PC_ITEM_USE_SUCC *resp = (sP_FE2CL_REP_PC_ITEM_USE_SUCC*)respbuf;
sSkillResult_Buff *respdata = (sSkillResult_Buff*)(respbuf+sizeof(sP_FE2CL_NANO_SKILL_USE_SUCC)); sSkillResult_Buff *respdata = (sSkillResult_Buff*)(respbuf+sizeof(sP_FE2CL_NANO_SKILL_USE_SUCC));
@@ -556,7 +556,7 @@ static void chestOpenHandler(CNSocket *sock, CNPacketData *data) {
// item giving packet // item giving packet
const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward); const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
uint8_t respbuf[resplen]; // not a variable length array, don't worry uint8_t respbuf[resplen]; // not a variable length array, don't worry
@@ -645,7 +645,7 @@ void Items::checkItemExpire(CNSocket* sock, Player* player) {
*/ */
const size_t resplen = sizeof(sP_FE2CL_PC_DELETE_TIME_LIMIT_ITEM) + sizeof(sTimeLimitItemDeleteInfo2CL); const size_t resplen = sizeof(sP_FE2CL_PC_DELETE_TIME_LIMIT_ITEM) + sizeof(sTimeLimitItemDeleteInfo2CL);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
uint8_t respbuf[resplen]; // not a variable length array, don't worry uint8_t respbuf[resplen]; // not a variable length array, don't worry
auto packet = (sP_FE2CL_PC_DELETE_TIME_LIMIT_ITEM*)respbuf; auto packet = (sP_FE2CL_PC_DELETE_TIME_LIMIT_ITEM*)respbuf;
@@ -715,7 +715,7 @@ static void giveSingleDrop(CNSocket *sock, Mob* mob, int mobDropId, const DropRo
Player *plr = PlayerManager::getPlayer(sock); Player *plr = PlayerManager::getPlayer(sock);
const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward); const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE - 8);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
uint8_t respbuf[resplen]; // not a variable length array, don't worry uint8_t respbuf[resplen]; // not a variable length array, don't worry

View File

@@ -64,7 +64,7 @@ static bool isQuestItemFull(CNSocket* sock, int itemId, int itemCount) {
static void dropQuestItem(CNSocket *sock, int task, int count, int id, int mobid) { static void dropQuestItem(CNSocket *sock, int task, int count, int id, int mobid) {
std::cout << "Altered item id " << id << " by " << count << " for task id " << task << std::endl; std::cout << "Altered item id " << id << " by " << count << " for task id " << task << std::endl;
const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward); const size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE);
// we know it's only one trailing struct, so we can skip full validation // we know it's only one trailing struct, so we can skip full validation
Player *plr = PlayerManager::getPlayer(sock); Player *plr = PlayerManager::getPlayer(sock);
@@ -152,14 +152,14 @@ static int giveMissionReward(CNSocket *sock, int task, int choice=0) {
plr->Inven[slots[i]] = { 999, 999, 999, 0 }; // temp item; overwritten later plr->Inven[slots[i]] = { 999, 999, 999, 0 }; // temp item; overwritten later
} }
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + nrewards * sizeof(sItemReward); size_t resplen = sizeof(sP_FE2CL_REP_REWARD_ITEM) + nrewards * sizeof(sItemReward);
assert(resplen < CN_PACKET_BODY_SIZE); assert(resplen < CN_PACKET_BUFFER_SIZE);
sP_FE2CL_REP_REWARD_ITEM *resp = (sP_FE2CL_REP_REWARD_ITEM *)respbuf; sP_FE2CL_REP_REWARD_ITEM *resp = (sP_FE2CL_REP_REWARD_ITEM *)respbuf;
sItemReward *item = (sItemReward *)(respbuf + sizeof(sP_FE2CL_REP_REWARD_ITEM)); sItemReward *item = (sItemReward *)(respbuf + sizeof(sP_FE2CL_REP_REWARD_ITEM));
// don't forget to zero the buffer! // don't forget to zero the buffer!
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
// update player // update player
plr->money += reward->money; plr->money += reward->money;

View File

@@ -238,8 +238,8 @@ static void dealCorruption(Mob *mob, std::vector<int> targetData, int skillID, i
return; return;
} }
uint8_t respbuf[CN_PACKET_BODY_SIZE]; uint8_t respbuf[CN_PACKET_BUFFER_SIZE];
memset(respbuf, 0, CN_PACKET_BODY_SIZE); memset(respbuf, 0, resplen);
sP_FE2CL_NPC_SKILL_CORRUPTION_HIT *resp = (sP_FE2CL_NPC_SKILL_CORRUPTION_HIT*)respbuf; sP_FE2CL_NPC_SKILL_CORRUPTION_HIT *resp = (sP_FE2CL_NPC_SKILL_CORRUPTION_HIT*)respbuf;
sCAttackResult *respdata = (sCAttackResult*)(respbuf+sizeof(sP_FE2CL_NPC_SKILL_CORRUPTION_HIT)); sCAttackResult *respdata = (sCAttackResult*)(respbuf+sizeof(sP_FE2CL_NPC_SKILL_CORRUPTION_HIT));

View File

@@ -396,14 +396,6 @@ static void heartbeatPlayer(CNSocket* sock, CNPacketData* data) {
static void exitGame(CNSocket* sock, CNPacketData* data) { static void exitGame(CNSocket* sock, CNPacketData* data) {
auto exitData = (sP_CL2FE_REQ_PC_EXIT*)data->buf; auto exitData = (sP_CL2FE_REQ_PC_EXIT*)data->buf;
// Refresh any auth cookie, in case "change character" was used
Player* plr = getPlayer(sock);
if (plr != nullptr) {
// 5 seconds should be enough to log in again
Database::refreshCookie(plr->accountId, 5);
}
INITSTRUCT(sP_FE2CL_REP_PC_EXIT_SUCC, response); INITSTRUCT(sP_FE2CL_REP_PC_EXIT_SUCC, response);
response.iID = exitData->iID; response.iID = exitData->iID;

View File

@@ -95,14 +95,14 @@ inline constexpr bool isOutboundPacketID(uint32_t id) {
// for outbound packets // for outbound packets
inline constexpr bool validOutVarPacket(size_t base, size_t npayloads, size_t plsize) { inline constexpr bool validOutVarPacket(size_t base, size_t npayloads, size_t plsize) {
// check for multiplication overflow // check for multiplication overflow
if (npayloads > 0 && (CN_PACKET_BODY_SIZE) / (size_t)npayloads < plsize) if (npayloads > 0 && (CN_PACKET_BUFFER_SIZE - 8) / (size_t)npayloads < plsize)
return false; return false;
// it's safe to multiply // it's safe to multiply
size_t trailing = npayloads * plsize; size_t trailing = npayloads * plsize;
// does it fit in a packet? // does it fit in a packet?
if (base + trailing > CN_PACKET_BODY_SIZE) if (base + trailing > CN_PACKET_BUFFER_SIZE - 8)
return false; return false;
// everything is a-ok! // everything is a-ok!
@@ -112,14 +112,14 @@ inline constexpr bool validOutVarPacket(size_t base, size_t npayloads, size_t pl
// for inbound packets // for inbound packets
inline constexpr bool validInVarPacket(size_t base, size_t npayloads, size_t plsize, size_t datasize) { inline constexpr bool validInVarPacket(size_t base, size_t npayloads, size_t plsize, size_t datasize) {
// check for multiplication overflow // check for multiplication overflow
if (npayloads > 0 && CN_PACKET_BODY_SIZE / (size_t)npayloads < plsize) if (npayloads > 0 && (CN_PACKET_BUFFER_SIZE - 8) / (size_t)npayloads < plsize)
return false; return false;
// it's safe to multiply // it's safe to multiply
size_t trailing = npayloads * plsize; size_t trailing = npayloads * plsize;
// make sure size is exact // make sure size is exact
// datasize has already been validated against CN_PACKET_BODY_SIZE // datasize has already been validated against CN_PACKET_BUFFER_SIZE
if (datasize != base + trailing) if (datasize != base + trailing)
return false; return false;

View File

@@ -29,8 +29,8 @@
#define INITSTRUCT(T, x) T x; \ #define INITSTRUCT(T, x) T x; \
memset(&x, 0, sizeof(T)); memset(&x, 0, sizeof(T));
#define INITVARPACKET(_buf, _Pkt, _pkt, _Trailer, _trailer) uint8_t _buf[CN_PACKET_BODY_SIZE]; \ #define INITVARPACKET(_buf, _Pkt, _pkt, _Trailer, _trailer) uint8_t _buf[CN_PACKET_BUFFER_SIZE]; \
memset(&_buf, 0, CN_PACKET_BODY_SIZE); \ memset(&_buf, 0, CN_PACKET_BUFFER_SIZE); \
auto _pkt = (_Pkt*)_buf; \ auto _pkt = (_Pkt*)_buf; \
auto _trailer = (_Trailer*)(_pkt + 1); auto _trailer = (_Trailer*)(_pkt + 1);
@@ -49,7 +49,6 @@ std::string U16toU8(char16_t* src, size_t max);
size_t U8toU16(std::string src, char16_t* des, size_t max); // returns number of char16_t that was written at des size_t U8toU16(std::string src, char16_t* des, size_t max); // returns number of char16_t that was written at des
time_t getTime(); time_t getTime();
time_t getTimestamp(); time_t getTimestamp();
int timingSafeStrcmp(const char* a, const char* b);
void terminate(int); void terminate(int);
// The PROTOCOL_VERSION definition can be defined by the build system. // The PROTOCOL_VERSION definition can be defined by the build system.

View File

@@ -942,8 +942,3 @@ enum {
N_PACKETS = N_CL2LS + N_CL2FE + N_FE2CL + N_LS2CL N_PACKETS = N_CL2LS + N_CL2FE + N_FE2CL + N_LS2CL
}; };
/*
* Usable space in the packet buffer = CN_PACKET_BUFFER_SIZE - type - size
*/
constexpr size_t CN_PACKET_BODY_SIZE = CN_PACKET_BUFFER_SIZE - 2 * sizeof(int32_t);

View File

@@ -5,7 +5,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#define DATABASE_VERSION 6 #define DATABASE_VERSION 5
namespace Database { namespace Database {
@@ -56,7 +56,6 @@ namespace Database {
// return true if cookie is valid for the account. // return true if cookie is valid for the account.
// invalidates the stored cookie afterwards // invalidates the stored cookie afterwards
bool checkCookie(int accountId, const char *cookie); bool checkCookie(int accountId, const char *cookie);
void refreshCookie(int accountId, int durationSec);
// interface for the /ban command // interface for the /ban command
bool banPlayer(int playerId, std::string& reason); bool banPlayer(int playerId, std::string& reason);

View File

@@ -1,5 +1,3 @@
#include "core/CNStructs.hpp"
#include "db/internal.hpp" #include "db/internal.hpp"
#include "bcrypt/BCrypt.hpp" #include "bcrypt/BCrypt.hpp"
@@ -132,44 +130,21 @@ bool Database::checkCookie(int accountId, const char *tryCookie) {
return false; return false;
} }
bool match = (timingSafeStrcmp(cookie, tryCookie) == 0); /*
* since cookies are immediately invalidated, we don't need to be concerned about
* timing-related side channel attacks, so strcmp is fine here
*/
bool match = (strcmp(cookie, tryCookie) == 0);
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
/* sqlite3_prepare_v2(db, sql_invalidate, -1, &stmt, NULL);
* Only invalidate the cookie if it was correct. This prevents sqlite3_bind_int(stmt, 1, accountId);
* replay attacks without enabling DOS attacks on accounts. rc = sqlite3_step(stmt);
*/
if (match) {
sqlite3_prepare_v2(db, sql_invalidate, -1, &stmt, NULL);
sqlite3_bind_int(stmt, 1, accountId);
rc = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (rc != SQLITE_DONE)
std::cout << "[WARN] Database fail on checkCookie(): " << sqlite3_errmsg(db) << std::endl;
}
return match;
}
void Database::refreshCookie(int accountId, int durationSec) {
std::lock_guard<std::mutex> lock(dbCrit);
const char* sql = R"(
UPDATE Auth
SET Expires = ?
WHERE AccountID = ?;
)";
int expires = getTimestamp() + durationSec;
sqlite3_stmt* stmt;
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
sqlite3_bind_int(stmt, 1, expires);
sqlite3_bind_int(stmt, 2, accountId);
int rc = sqlite3_step(stmt);
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
if (rc != SQLITE_DONE) if (rc != SQLITE_DONE)
std::cout << "[WARN] Database fail on refreshCookie(): " << sqlite3_errmsg(db) << std::endl; std::cout << "[WARN] Database fail on checkCookie(): " << sqlite3_errmsg(db) << std::endl;
return match;
} }
void Database::updateSelected(int accountId, int slot) { void Database::updateSelected(int accountId, int slot) {

View File

@@ -222,17 +222,6 @@ time_t getTimestamp() {
return (time_t)value.count(); return (time_t)value.count();
} }
// timing safe strcmp implementation for e.g. cookie validation
int timingSafeStrcmp(const char* a, const char* b) {
int diff = 0;
while (*a && *b) {
diff |= *a++ ^ *b++;
}
diff |= *a;
diff |= *b;
return diff;
}
// convert integer timestamp (in s) to FF systime struct // convert integer timestamp (in s) to FF systime struct
sSYSTEMTIME timeStampToStruct(uint64_t time) { sSYSTEMTIME timeStampToStruct(uint64_t time) {

View File

@@ -109,17 +109,11 @@ void CNLoginServer::login(CNSocket* sock, CNPacketData* data) {
std::string userLogin; std::string userLogin;
std::string userToken; // could be password or auth cookie std::string userToken; // could be password or auth cookie
/*
* In this context, "cookie auth" just means the credentials were sent
* in the szCookie fields instead of szID and szPassword.
*/
bool isCookieAuth = login->iLoginType == USE_COOKIE_FIELDS;
/* /*
* The std::string -> char* -> std::string maneuver should remove any * The std::string -> char* -> std::string maneuver should remove any
* trailing garbage after the null terminator. * trailing garbage after the null terminator.
*/ */
if (isCookieAuth) { if (login->iLoginType == (int32_t)LoginType::COOKIE) {
userLogin = std::string(AUTOU8(login->szCookie_TEGid).c_str()); userLogin = std::string(AUTOU8(login->szCookie_TEGid).c_str());
userToken = std::string(AUTOU8(login->szCookie_authid).c_str()); userToken = std::string(AUTOU8(login->szCookie_authid).c_str());
} else { } else {
@@ -127,41 +121,99 @@ void CNLoginServer::login(CNSocket* sock, CNPacketData* data) {
userToken = std::string(AUTOU16TOU8(login->szPassword).c_str()); userToken = std::string(AUTOU16TOU8(login->szPassword).c_str());
} }
if (!CNLoginServer::checkUsername(sock, userLogin)) { // check username regex
if (!CNLoginServer::isUsernameGood(userLogin)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Invalid login\n";
text += "Login has to be 4 - 32 characters long and can't contain special characters other than dash and underscore";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 10;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
// we still have to send login fail to prevent softlock
return loginFail(LoginError::LOGIN_ERROR, userLogin, sock); return loginFail(LoginError::LOGIN_ERROR, userLogin, sock);
} }
// we only interpret the token as a cookie if cookie login was used and it's allowed.
// otherwise we interpret it as a password, and this maintains compatibility with
// the auto-login trick used on older clients
bool isCookieAuth = login->iLoginType == (int32_t)LoginType::COOKIE
&& CNLoginServer::isLoginTypeAllowed(LoginType::COOKIE);
// password login checks
if (!isCookieAuth) { if (!isCookieAuth) {
// password was sent in plaintext // bail if password auth isn't allowed
if (!CNLoginServer::checkPassword(sock, userToken)) { if (!CNLoginServer::isLoginTypeAllowed(LoginType::PASSWORD)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Password login disabled\n";
text += "This server has disabled logging in with plaintext passwords.\n";
text += "Please contact an admin for assistance.";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 12;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
// we still have to send login fail to prevent softlock
return loginFail(LoginError::LOGIN_ERROR, userLogin, sock);
}
// check regex
if (!CNLoginServer::isPasswordGood(userToken)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Invalid password\n";
text += "Password has to be 8 - 32 characters long";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 10;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
// we still have to send login fail to prevent softlock
return loginFail(LoginError::LOGIN_ERROR, userLogin, sock); return loginFail(LoginError::LOGIN_ERROR, userLogin, sock);
} }
} }
Database::Account findUser = {}; Database::Account findUser = {};
Database::findAccount(&findUser, userLogin); Database::findAccount(&findUser, userLogin);
// account was not found // account was not found
if (findUser.AccountID == 0) { if (findUser.AccountID == 0) {
/* // don't auto-create an account if it's a cookie auth for whatever reason
* Don't auto-create accounts if it's a cookie login. if (settings::AUTOCREATEACCOUNTS && !isCookieAuth)
* It'll either be a bad cookie or a plaintext password sent by auto-login;
* either way, we only want to allow auto-creation if the user explicitly entered their credentials.
*/
if (settings::AUTOCREATEACCOUNTS && !isCookieAuth) {
return newAccount(sock, userLogin, userToken, login->iClientVerC); return newAccount(sock, userLogin, userToken, login->iClientVerC);
}
return loginFail(LoginError::ID_DOESNT_EXIST, userLogin, sock); return loginFail(LoginError::ID_DOESNT_EXIST, userLogin, sock);
} }
// make sure either a valid cookie or password was sent if (isCookieAuth) {
if (!CNLoginServer::checkToken(sock, findUser, userToken, isCookieAuth)) { const char *cookie = userToken.c_str();
return loginFail(LoginError::ID_AND_PASSWORD_DO_NOT_MATCH, userLogin, sock); if (!Database::checkCookie(findUser.AccountID, cookie))
return loginFail(LoginError::ID_AND_PASSWORD_DO_NOT_MATCH, userLogin, sock);
} else {
// simple password check
if (!CNLoginServer::isPasswordCorrect(findUser.Password, userToken))
return loginFail(LoginError::ID_AND_PASSWORD_DO_NOT_MATCH, userLogin, sock);
} }
if (CNLoginServer::checkBan(sock, findUser)) { // is the account banned
return; // don't send fail packet if (findUser.BannedUntil > getTimestamp()) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
// ceiling devision
int64_t remainingDays = (findUser.BannedUntil-getTimestamp()) / 86400 + ((findUser.BannedUntil - getTimestamp()) % 86400 != 0);
std::string text = "Your account has been banned. \nReason: ";
text += findUser.BanReason;
text += "\nBan expires in " + std::to_string(remainingDays) + " day";
if (remainingDays > 1)
text += "s";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 99999999;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
// don't send fail packet
return;
} }
/* /*
@@ -607,12 +659,12 @@ bool CNLoginServer::exitDuplicate(int accountId) {
return false; return false;
} }
bool CNLoginServer::isUsernameGood(std::string& login) { bool CNLoginServer::isUsernameGood(std::string login) {
const std::regex loginRegex("[a-zA-Z0-9_-]{4,32}"); const std::regex loginRegex("[a-zA-Z0-9_-]{4,32}");
return (std::regex_match(login, loginRegex)); return (std::regex_match(login, loginRegex));
} }
bool CNLoginServer::isPasswordGood(std::string& password) { bool CNLoginServer::isPasswordGood(std::string password) {
const std::regex passwordRegex("[a-zA-Z0-9!@#$%^&*()_+]{8,32}"); const std::regex passwordRegex("[a-zA-Z0-9!@#$%^&*()_+]{8,32}");
return (std::regex_match(password, passwordRegex)); return (std::regex_match(password, passwordRegex));
} }
@@ -628,107 +680,16 @@ bool CNLoginServer::isCharacterNameGood(std::string Firstname, std::string Lastn
return (std::regex_match(Firstname, firstnamecheck) && std::regex_match(Lastname, lastnamecheck)); return (std::regex_match(Firstname, firstnamecheck) && std::regex_match(Lastname, lastnamecheck));
} }
bool CNLoginServer::isAuthMethodAllowed(AuthMethod authMethod) { bool CNLoginServer::isLoginTypeAllowed(LoginType loginType) {
// the config file specifies "comma-separated" but tbh we don't care // the config file specifies "comma-separated" but tbh we don't care
switch (authMethod) { switch (loginType) {
case AuthMethod::PASSWORD: case LoginType::PASSWORD:
return settings::AUTHMETHODS.find("password") != std::string::npos; return settings::AUTHMETHODS.find("password") != std::string::npos;
case AuthMethod::COOKIE: case LoginType::COOKIE:
return settings::AUTHMETHODS.find("cookie") != std::string::npos; return settings::AUTHMETHODS.find("cookie") != std::string::npos;
default: default:
break; break;
} }
return false; return false;
} }
bool CNLoginServer::checkPassword(CNSocket* sock, std::string& password) {
// check password auth allowed
if (!CNLoginServer::isAuthMethodAllowed(AuthMethod::PASSWORD)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Password login disabled\n";
text += "This server has disabled logging in with plaintext passwords.\n";
text += "Please contact an admin for assistance.";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 12;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
return false;
}
// check regex
if (!CNLoginServer::isPasswordGood(password)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Invalid password\n";
text += "Password has to be 8 - 32 characters long";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 10;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
return false;
}
return true;
}
bool CNLoginServer::checkUsername(CNSocket* sock, std::string& username) {
// check username regex
if (!CNLoginServer::isUsernameGood(username)) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
std::string text = "Invalid login\n";
text += "Login has to be 4 - 32 characters long and can't contain special characters other than dash and underscore";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 10;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
return false;
}
return true;
}
bool CNLoginServer::checkToken(CNSocket* sock, Database::Account& account, std::string& token, bool isCookieAuth) {
// check for valid cookie first
if (isCookieAuth && CNLoginServer::isAuthMethodAllowed(AuthMethod::COOKIE)) {
const char *cookie = token.c_str();
if (Database::checkCookie(account.AccountID, cookie)) {
return true;
}
}
// cookie check disabled or failed; check to see if it's a plaintext password
if (CNLoginServer::isAuthMethodAllowed(AuthMethod::PASSWORD)
&& CNLoginServer::isPasswordCorrect(account.Password, token)) {
return true;
}
return false;
}
bool CNLoginServer::checkBan(CNSocket* sock, Database::Account& account) {
// check if the account is banned
if (account.BannedUntil > getTimestamp()) {
// send a custom error message
INITSTRUCT(sP_FE2CL_GM_REP_PC_ANNOUNCE, msg);
// ceiling devision
int64_t remainingDays = (account.BannedUntil-getTimestamp()) / 86400 + ((account.BannedUntil - getTimestamp()) % 86400 != 0);
std::string text = "Your account has been banned. \nReason: ";
text += account.BanReason;
text += "\nBan expires in " + std::to_string(remainingDays) + " day";
if (remainingDays > 1)
text += "s";
U8toU16(text, msg.szAnnounceMsg, sizeof(msg.szAnnounceMsg));
msg.iDuringTime = 99999999;
sock->sendPacket(msg, P_FE2CL_GM_REP_PC_ANNOUNCE);
return true;
}
return false;
}
#pragma endregion #pragma endregion

View File

@@ -1,7 +1,6 @@
#pragma once #pragma once
#include "core/Core.hpp" #include "core/Core.hpp"
#include "db/Database.hpp"
#include "Player.hpp" #include "Player.hpp"
@@ -24,9 +23,7 @@ enum class LoginError {
UPDATED_EUALA_REQUIRED = 9 UPDATED_EUALA_REQUIRED = 9
}; };
#define USE_COOKIE_FIELDS 2 enum class LoginType {
enum class AuthMethod {
PASSWORD = 1, PASSWORD = 1,
COOKIE = 2 COOKIE = 2
}; };
@@ -47,17 +44,12 @@ private:
static void changeName(CNSocket* sock, CNPacketData* data); static void changeName(CNSocket* sock, CNPacketData* data);
static void duplicateExit(CNSocket* sock, CNPacketData* data); static void duplicateExit(CNSocket* sock, CNPacketData* data);
static bool isUsernameGood(std::string& login); static bool isUsernameGood(std::string login);
static bool isPasswordGood(std::string& password); static bool isPasswordGood(std::string password);
static bool isPasswordCorrect(std::string actualPassword, std::string tryPassword); static bool isPasswordCorrect(std::string actualPassword, std::string tryPassword);
static bool isAccountInUse(int accountId); static bool isAccountInUse(int accountId);
static bool isCharacterNameGood(std::string Firstname, std::string Lastname); static bool isCharacterNameGood(std::string Firstname, std::string Lastname);
static bool isAuthMethodAllowed(AuthMethod authMethod); static bool isLoginTypeAllowed(LoginType loginType);
static bool checkUsername(CNSocket* sock, std::string& username);
static bool checkPassword(CNSocket* sock, std::string& password);
static bool checkToken(CNSocket* sock, Database::Account& account, std::string& token, bool isCookieAuth);
static bool checkBan(CNSocket* sock, Database::Account& account);
static void newAccount(CNSocket* sock, std::string userLogin, std::string userPassword, int32_t clientVerC); static void newAccount(CNSocket* sock, std::string userLogin, std::string userPassword, int32_t clientVerC);
// returns true if success // returns true if success
static bool exitDuplicate(int accountId); static bool exitDuplicate(int accountId);

View File

@@ -1,8 +1,6 @@
#pragma once #pragma once
#include <stdint.h>
#include <string> #include <string>
#include <time.h>
namespace settings { namespace settings {
extern int VERBOSITY; extern int VERBOSITY;