diff options
author | LaG1924 <12997935+LaG1924@users.noreply.github.com> | 2017-08-03 17:03:59 +0200 |
---|---|---|
committer | LaG1924 <12997935+LaG1924@users.noreply.github.com> | 2017-08-03 17:03:59 +0200 |
commit | f7decf41d8d0062901cd39c42a3669a80537c7df (patch) | |
tree | d3032265df11eee6e3eaf8b4b081524bef5e72b2 /src/network | |
parent | 2017-07-29 (diff) | |
download | AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar.gz AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar.bz2 AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar.lz AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar.xz AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.tar.zst AltCraft-f7decf41d8d0062901cd39c42a3669a80537c7df.zip |
Diffstat (limited to '')
-rw-r--r-- | src/network/Network.cpp | 220 | ||||
-rw-r--r-- | src/network/NetworkClient.cpp | 93 | ||||
-rw-r--r-- | src/network/Socket.cpp | 29 | ||||
-rw-r--r-- | src/network/Stream.cpp | 349 |
4 files changed, 0 insertions, 691 deletions
diff --git a/src/network/Network.cpp b/src/network/Network.cpp deleted file mode 100644 index 91cb481..0000000 --- a/src/network/Network.cpp +++ /dev/null @@ -1,220 +0,0 @@ -#include <network/Network.hpp> - -Network::Network(std::string address, unsigned short port) { - socket = new Socket(address, port); - stream = new StreamSocket(socket); -} - -Network::~Network() { - delete stream; - delete socket; -} - -std::shared_ptr<Packet> Network::ReceivePacket(ConnectionState state) { - int packetSize = stream->ReadVarInt(); - auto packetData = stream->ReadByteArray(packetSize); - StreamBuffer streamBuffer(packetData.data(), packetData.size()); - int packetId = streamBuffer.ReadVarInt(); - auto packet = ReceivePacketByPacketId(packetId, state, streamBuffer); - return packet; -} - -void Network::SendPacket(Packet &packet) { - StreamCounter packetSize; - packetSize.WriteVarInt(packet.GetPacketId()); - packet.ToStream(&packetSize); - stream->WriteVarInt(packetSize.GetCountedSize()); - stream->WriteVarInt(packet.GetPacketId()); - packet.ToStream(stream); -} - -std::shared_ptr<Packet> Network::ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &stream) { - std::shared_ptr<Packet> packet(nullptr); - switch (state) { - case Handshaking: - switch (packetId) { - case PacketNameHandshakingCB::Handshake: - packet = std::make_shared<PacketHandshake>(); - break; - } - case Login: - switch (packetId) { - case PacketNameLoginCB::LoginSuccess: - packet = std::make_shared<PacketLoginSuccess>(); - break; - } - break; - case Play: - packet = ParsePacketPlay((PacketNamePlayCB) packetId); - break; - case Status: - break; - } - if (packet.get() != nullptr) - packet->FromStream(&stream); - return packet; -} - -std::shared_ptr<Packet> Network::ParsePacketPlay(PacketNamePlayCB id) { - switch (id) { - case SpawnObject: - break; - case SpawnExperienceOrb: - break; - case SpawnGlobalEntity: - break; - case SpawnMob: - break; - case SpawnPainting: - break; - case SpawnPlayer: - break; - case AnimationCB: - break; - case Statistics: - break; - case BlockBreakAnimation: - break; - case UpdateBlockEntity: - break; - case BlockAction: - break; - case BlockChange: - break; - case BossBar: - break; - case ServerDifficulty: - break; - case TabCompleteCB: - break; - case ChatMessageCB: - break; - case MultiBlockChange: - break; - case ConfirmTransactionCB: - break; - case CloseWindowCB: - break; - case OpenWindow: - break; - case WindowItems: - break; - case WindowProperty: - break; - case SetSlot: - break; - case SetCooldown: - break; - case PluginMessageCB: - break; - case NamedSoundEffect: - break; - case DisconnectPlay: - return std::make_shared<PacketDisconnectPlay>(); - case EntityStatus: - break; - case Explosion: - break; - case UnloadChunk: - break; - case ChangeGameState: - break; - case KeepAliveCB: - return std::make_shared<PacketKeepAliveCB>(); - case ChunkData: - return std::make_shared<PacketChunkData>(); - case Effect: - break; - case Particle: - break; - case JoinGame: - return std::make_shared<PacketJoinGame>(); - case Map: - break; - case EntityRelativeMove: - break; - case EntityLookAndRelativeMove: - break; - case EntityLook: - break; - case Entity: - break; - case VehicleMove: - break; - case OpenSignEditor: - break; - case PlayerAbilitiesCB: - break; - case CombatEvent: - break; - case PlayerListItem: - break; - case PlayerPositionAndLookCB: - return std::make_shared<PacketPlayerPositionAndLookCB>(); - case UseBed: - break; - case DestroyEntities: - break; - case RemoveEntityEffect: - break; - case ResourcePackSend: - break; - case Respawn: - break; - case EntityHeadLook: - break; - case WorldBorder: - break; - case Camera: - break; - case HeldItemChangeCB: - break; - case DisplayScoreboard: - break; - case EntityMetadata: - break; - case AttachEntity: - break; - case EntityVelocity: - break; - case EntityEquipment: - break; - case SetExperience: - break; - case UpdateHealth: - return std::make_shared<PacketUpdateHealth>(); - case ScoreboardObjective: - break; - case SetPassengers: - break; - case Teams: - break; - case UpdateScore: - break; - case SpawnPosition: - return std::make_shared<PacketSpawnPosition>(); - case TimeUpdate: - break; - case Title: - break; - case SoundEffect: - break; - case PlayerListHeaderAndFooter: - break; - case CollectItem: - break; - case EntityTeleport: - break; - case EntityProperties: - break; - case EntityEffect: - break; - case UnlockRecipes: - break; - case SelectAdvancementTab: - break; - case Advancements: - break; - } - return nullptr; -} diff --git a/src/network/NetworkClient.cpp b/src/network/NetworkClient.cpp deleted file mode 100644 index 73880cf..0000000 --- a/src/network/NetworkClient.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include <network/NetworkClient.hpp> - -NetworkClient::NetworkClient(std::string address, unsigned short port, std::string username, bool &quit) - : network(address, port), isRunning(quit) { - state = Handshaking; - - PacketHandshake handshake; - handshake.protocolVersion = 335; - handshake.serverAddress = "127.0.0.1"; - handshake.serverPort = 25565; - handshake.nextState = 2; - network.SendPacket(handshake); - state = Login; - - PacketLoginStart loginStart; - loginStart.Username = "HelloOne"; - network.SendPacket(loginStart); - - auto response = std::static_pointer_cast<PacketLoginSuccess>(network.ReceivePacket(Login)); - if (response->Username != username) { - throw std::logic_error("Received username is not sended username"); - } - - state = Play; - - isActive = true; - std::thread thread(&NetworkClient::NetworkLoop, this); - std::swap(networkThread, thread); -} - -NetworkClient::~NetworkClient() { - isActive = false; - networkThread.join(); -} - -std::shared_ptr<Packet> NetworkClient::ReceivePacket() { - if (toReceive.empty()) - return std::shared_ptr<Packet>(nullptr); - toReceiveMutex.lock(); - auto ret = toReceive.front(); - toReceive.pop(); - toReceiveMutex.unlock(); - return ret; -} - -void NetworkClient::SendPacket(std::shared_ptr<Packet> packet) { - toSendMutex.lock(); - toSend.push(packet); - toSendMutex.unlock(); -} - -void NetworkClient::NetworkLoop() { - auto timeOfLastKeepAlivePacket = std::chrono::steady_clock::now(); - el::Helpers::setThreadName("Network"); - LOG(INFO) << "Network thread is started"; - try { - while (isActive) { - toSendMutex.lock(); - while (!toSend.empty()) { - if (toSend.front()!=nullptr) - network.SendPacket(*toSend.front()); - toSend.pop(); - } - toSendMutex.unlock(); - auto packet = network.ReceivePacket(state); - if (packet.get() != nullptr) { - if (packet->GetPacketId() != PacketNamePlayCB::KeepAliveCB) { - toReceiveMutex.lock(); - toReceive.push(packet); - toReceiveMutex.unlock(); - } else { - timeOfLastKeepAlivePacket = std::chrono::steady_clock::now(); - auto packetKeepAlive = std::static_pointer_cast<PacketKeepAliveCB>(packet); - auto packetKeepAliveSB = std::make_shared<PacketKeepAliveSB>(packetKeepAlive->KeepAliveId); - network.SendPacket(*packetKeepAliveSB); - } - } - using namespace std::chrono_literals; - if (std::chrono::steady_clock::now() - timeOfLastKeepAlivePacket > 20s) { - auto disconnectPacket = std::make_shared<PacketDisconnectPlay>(); - disconnectPacket->Reason = "Timeout"; - toReceiveMutex.lock(); - toReceive.push(disconnectPacket); - toReceiveMutex.unlock(); - break; - } - } - } catch (std::exception &e) { - LOG(ERROR) << "Exception catched in NetworkLoop: " << e.what(); - isRunning = false; - } - LOG(INFO) << "Network thread is stopped"; -} diff --git a/src/network/Socket.cpp b/src/network/Socket.cpp deleted file mode 100644 index f4e6787..0000000 --- a/src/network/Socket.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include <network/Socket.hpp> - -Socket::Socket(std::string address, unsigned short port) { - sf::Socket::Status connectionStatus = socket.connect(sf::IpAddress(address), port); - if (connectionStatus == sf::Socket::Status::Error) - throw std::runtime_error("Can't connect to remote server"); - else if (connectionStatus != sf::Socket::Status::Done) - throw std::runtime_error("Connection failed with unknown reason"); -} - -Socket::~Socket() { - socket.disconnect(); -} - -void Socket::Read(unsigned char *buffPtr, size_t buffLen) { - size_t received = 0; - socket.receive(buffPtr, buffLen, received); - size_t totalReceived = received; - while (totalReceived < buffLen) { - if (socket.receive(buffPtr + totalReceived, buffLen - totalReceived, received) != sf::Socket::Done) - throw std::runtime_error("Raw socket data receiving is failed"); - totalReceived += received; - } -} - -void Socket::Write(unsigned char *buffPtr, size_t buffLen) { - if (socket.send(buffPtr, buffLen) != sf::Socket::Done) - throw std::runtime_error("Raw socket data sending is failed"); -} diff --git a/src/network/Stream.cpp b/src/network/Stream.cpp deleted file mode 100644 index 447b13f..0000000 --- a/src/network/Stream.cpp +++ /dev/null @@ -1,349 +0,0 @@ -#include <network/Stream.hpp> - -const int MAX_VARINT_LENGTH = 5; - -bool StreamInput::ReadBool() { - unsigned char value; - ReadData(&value, 1); - return value != 0; -} - -signed char StreamInput::ReadByte() { - signed char value; - ReadData((unsigned char *) &value, 1); - endswap(value); - return value; -} - -unsigned char StreamInput::ReadUByte() { - unsigned char value; - ReadData(&value, 1); - endswap(value); - return value; -} - -short StreamInput::ReadShort() { - unsigned short value; - ReadData((unsigned char *) &value, 2); - endswap(value); - return value; -} - -unsigned short StreamInput::ReadUShort() { - unsigned char buff[2]; - ReadData(buff, 2); - unsigned short val = *(reinterpret_cast<unsigned short *>(buff)); - endswap(val); - return val; -} - -int StreamInput::ReadInt() { - int value; - ReadData((unsigned char *) &value, 4); - endswap(value); - return value; -} - -long long StreamInput::ReadLong() { - long long value; - ReadData((unsigned char *) &value, 8); - endswap(value); - return value; -} - -float StreamInput::ReadFloat() { - float value; - ReadData((unsigned char *) &value, 4); - endswap(value); - return value; -} - -double StreamInput::ReadDouble() { - double value; - ReadData((unsigned char *) &value, 8); - endswap(value); - return value; -} - -std::string StreamInput::ReadString() { - int strLength = ReadVarInt(); - unsigned char *buff = new unsigned char[strLength + 1]; - ReadData(buff, strLength); - buff[strLength] = 0; - std::string str((char *) buff); - delete buff; - return str; -} - -std::string StreamInput::ReadChat() { - std::string str, jsonStr = ReadString(); - nlohmann::json json; - try { - json = nlohmann::json::parse(jsonStr); - } catch (std::exception &e) { - LOG(WARNING) << "Chat json parsing failed: " << e.what(); - LOG(WARNING) << "Corrupted json: " << jsonStr; - return ""; - } - if (json.find("translate") != json.end()) - if (json["translate"].get<std::string>() == "multiplayer.disconnect.kicked") - return "kicked by operator"; - for (auto &it:json["extra"]) { - str += it["text"].get<std::string>(); - } - return str; -} - -int StreamInput::ReadVarInt() { - unsigned char data[MAX_VARINT_LENGTH] = {0}; - size_t dataLen = 0; - do { - ReadData(&data[dataLen], 1); - } while ((data[dataLen++] & 0x80) != 0); - - int readed = 0; - int result = 0; - char read; - do { - read = data[readed]; - int value = (read & 0b01111111); - result |= (value << (7 * readed)); - readed++; - } while ((read & 0b10000000) != 0); - - return result; -} - -long long StreamInput::ReadVarLong() { - return 0; -} - -std::vector<unsigned char> StreamInput::ReadEntityMetadata() { - return std::vector<unsigned char>(); -} - -std::vector<unsigned char> StreamInput::ReadSlot() { - return std::vector<unsigned char>(); -} - -std::vector<unsigned char> StreamInput::ReadNbtTag() { - return std::vector<unsigned char>(); -} - -Vector StreamInput::ReadPosition() { - unsigned long long t = ReadLong(); - int x = t >> 38; - int y = (t >> 26) & 0xFFF; - int z = t << 38 >> 38; - if (x >= pow(2, 25)) { - x -= pow(2, 26); - } - if (y >= pow(2, 11)) { - y -= pow(2, 12); - } - if (z >= pow(2, 25)) { - z -= pow(2, 26); - } - return Vector(x, y, z); -} - -unsigned char StreamInput::ReadAngle() { - return ReadUByte(); -} - -std::vector<unsigned char> StreamInput::ReadUuid() { - unsigned char buff[16]; - ReadData(buff, 16); - endswap(buff, 16); - return std::vector<unsigned char>(buff, buff + 16); -} - -std::vector<unsigned char> StreamInput::ReadByteArray(size_t arrLength) { - unsigned char *buffer = new unsigned char[arrLength]; - ReadData(buffer, arrLength); - std::vector<unsigned char> ret(buffer, buffer + arrLength); - delete buffer; - return ret; - -} - -void StreamOutput::WriteBool(bool value) { - unsigned char val = value ? 1 : 0; - endswap(val); - WriteData(&val, 1); -} - -void StreamOutput::WriteByte(signed char value) { - endswap(value); - WriteData((unsigned char *) &value, 1); -} - -void StreamOutput::WriteUByte(unsigned char value) { - endswap(value); - WriteData(&value, 1); -} - -void StreamOutput::WriteShort(short value) { - endswap(value); - WriteData((unsigned char *) &value, 2); -} - -void StreamOutput::WriteUShort(unsigned short value) { - endswap(value); - WriteData((unsigned char *) &value, 2); -} - -void StreamOutput::WriteInt(int value) { - endswap(value); - WriteData((unsigned char *) &value, 4); -} - -void StreamOutput::WriteLong(long long value) { - endswap(value); - WriteData((unsigned char *) &value, 8); -} - -void StreamOutput::WriteFloat(float value) { - endswap(value); - WriteData((unsigned char *) &value, 4); -} - -void StreamOutput::WriteDouble(double value) { - endswap(value); - WriteData((unsigned char *) &value, 8); -} - -void StreamOutput::WriteString(std::string value) { - WriteVarInt(value.size()); - WriteData((unsigned char *) value.data(), value.size()); -} - -void StreamOutput::WriteChat(std::string value) { - WriteString(value); -} - -void StreamOutput::WriteVarInt(int value) { - unsigned char buff[5]; - size_t len = 0; - do { - unsigned char temp = (unsigned char) (value & 0b01111111); - value >>= 7; - if (value != 0) { - temp |= 0b10000000; - } - buff[len] = temp; - len++; - } while (value != 0); - WriteData(buff, len); -} - -void StreamOutput::WriteVarLong(long long value) { - unsigned char buff[10]; - size_t len = 0; - do { - unsigned char temp = (unsigned char) (value & 0b01111111); - value >>= 7; - if (value != 0) { - temp |= 0b10000000; - } - buff[len] = temp; - len++; - } while (value != 0); - WriteData(buff, len); -} - -void StreamOutput::WriteEntityMetadata(std::vector<unsigned char> value) { - LOG(FATAL) << "Used unimplemented WriteEntityMetadata: " << value.size(); -} - -void StreamOutput::WriteSlot(std::vector<unsigned char> value) { - LOG(FATAL) << "Used unimplemented WriteSlot " << value.size(); -} - -void StreamOutput::WriteNbtTag(std::vector<unsigned char> value) { - LOG(FATAL) << "Used unimplemented WriteNbtTag " << value.size(); -} - -void StreamOutput::WritePosition(Vector value) { - LOG(FATAL) << "Used unimplemented Position: " << value.GetX() << ", " << value.GetY() << " " << value.GetZ(); -} - -void StreamOutput::WriteAngle(unsigned char value) { - WriteUByte(value); -} - -void StreamOutput::WriteUuid(std::vector<unsigned char> value) { - WriteByteArray(value); -} - -void StreamOutput::WriteByteArray(std::vector<unsigned char> value) { - WriteData(value.data(), value.size()); -} - -void StreamBuffer::ReadData(unsigned char *buffPtr, size_t buffLen) { - size_t bufferLengthLeft = buffer + bufferLength - bufferPtr; - if (bufferLengthLeft < buffLen) - throw std::runtime_error("Required data is more, than in buffer available"); - std::memcpy(buffPtr, bufferPtr, buffLen); - bufferPtr += buffLen; -} - -void StreamBuffer::WriteData(unsigned char *buffPtr, size_t buffLen) { - size_t bufferLengthLeft = buffer + bufferLength - bufferPtr; - if (bufferLengthLeft < buffLen) - throw std::runtime_error("Required data is more, than in buffer available"); - std::memcpy(bufferPtr, buffPtr, buffLen); - bufferPtr += buffLen; -} - -StreamBuffer::StreamBuffer(unsigned char *data, size_t dataLen) { - buffer = new unsigned char[dataLen]; - bufferPtr = buffer; - bufferLength = dataLen; - std::memcpy(buffer, data, dataLen); -} - -StreamBuffer::StreamBuffer(size_t bufferLen) { - buffer = new unsigned char[bufferLen]; - bufferPtr = buffer; - bufferLength = bufferLen; - for (unsigned char *p = buffer; p != buffer + bufferLength; ++p) - *p = 0; -} - -StreamBuffer::~StreamBuffer() { - delete buffer; -} - -std::vector<unsigned char> StreamBuffer::GetBuffer() { - return std::vector<unsigned char>(buffer, buffer + bufferLength); -} - -void StreamCounter::WriteData(unsigned char *buffPtr, size_t buffLen) { - buffPtr++; - size += buffLen; -} - -StreamCounter::StreamCounter(size_t initialSize) : size(initialSize) { - -} - -StreamCounter::~StreamCounter() { - -} - -size_t StreamCounter::GetCountedSize() { - return size; -} - -void StreamSocket::ReadData(unsigned char *buffPtr, size_t buffLen) { - socket->Read(buffPtr, buffLen); -} - -void StreamSocket::WriteData(unsigned char *buffPtr, size_t buffLen) { - socket->Write(buffPtr, buffLen); -} - -StreamSocket::StreamSocket(Socket *socketPtr) : socket(socketPtr) { - -}
\ No newline at end of file |