FeatherMC/src/network/Protocol.cpp

109 lines
3.3 KiB
C++

#include "Protocol.h"
#include "PacketReader.h"
#include "PacketTypes.h"
#include <string>
using std::string;
namespace Feather::Network
{
void Protocol::HandlePacket(PacketReader& packet)
{
int id = packet.ReadVarInt();
printf("PacketReader[%u]: ID = %u\n", packet.Length(), id);
switch (m_state)
{
case ProtocolState::HANDSHAKING:
{
if (id != 0) {
// this could be, for example, Legacy Server List Ping 0xFE
printf("[Protocol] Client sent packet with non-zero ID 0x%x while state was HANDSHAKING\n", id);
break;
}
int clientProtocolVersion = packet.ReadVarInt();
string serverIp = packet.ReadString();
uint16_t port = packet.Read<uint16_t>();
// next desired state
ProtocolState intention = (ProtocolState)(packet.ReadVarInt());
printf("[Protocol] Client Intention Packet: version=%d, serverIp=%s, port=%u, intention=%d\n",
clientProtocolVersion,
serverIp.c_str(),
port,
intention
);
SetState(intention);
break;
}
case ProtocolState::STATUS:
{
ServerboundPacketType type = (ServerboundPacketType)id;
printf("[Protocol] [STATUS mode] Client sent packet ID %d (%d)\n", id, type);
switch (type)
{
case ServerboundPacketType::STATUS_PING_REQUEST:
{
printf("[Protocol] Client sent STATUS_PING_REQUEST\n");
const std::string json_template =
R"({
"version": {
"name": "1.16.1",
"protocol": 736
},
"players": {
"max": 10,
"online": 10,
"sample": [
{
"name": "thinkofdeath",
"id": "4566e69f-c907-48ee-8d71-d7ba5aa00d20"
}
]
},
"description": {
"text": "Hello Nukem!"
}
})";
/*DynamicNetworkMessage msg(VARINT_MAX_SIZE + json_template.length());
// Packet ID
msg.WriteVarInt(0);
// JSON Contents
msg.WriteString(json_template.c_str(), static_cast<int32_t>(json_template.length()));
m_client->SendPacket(&msg);*/
break;
}
case ServerboundPacketType::STATUS_PING:
int64_t timestamp = packet.Read<int64_t>();
printf("[Protocol] Client sent STATUS_PING: %lld\n", timestamp);
/*DynamicNetworkMessage msg(VARINT_MAX_SIZE + sizeof(int64_t));
msg.WriteVarInt(1);
msg.WriteLong(timestamp);
m_client->SendPacket(&msg);*/
break;
}
break;
}
}
}
void Protocol::SetState(ProtocolState state)
{
printf("[Protocol] Switching state from %d to %d\n", m_state, state);
// TODO: validate state here
m_state = state;
}
}