amethyst/lib/servers/generic.ex

76 lines
2.6 KiB
Elixir
Raw Normal View History

2024-07-07 19:05:32 +02:00
# Amethyst - An experimental Minecraft server written in Elixir.
# Copyright (C) 2024 KodiCraft
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
defmodule Amethyst.Server.Generic do
@moduledoc """
This module includes generic logic which may be used by all stages of the server, including,
for instance, listening for packets.
"""
alias Amethyst.Minecraft.Read
def get_packet(client) do
2024-07-07 22:46:18 +02:00
{[length], ""} = get_varint(client, "")
2024-07-08 17:59:44 +02:00
recv = :gen_tcp.recv(client, length)
case recv do
{:ok, full_packet} -> ({[id], data} = Read.start(full_packet) |> Read.varint() |> Read.stop()
{id, data})
{:error, :closed} -> raise RuntimeError, "TODO: Handle disconnections reasonably"
{:error, error} -> raise RuntimeError, "An error has occured while waiting on a packet: #{error}"
end
2024-07-07 19:05:32 +02:00
end
defp get_varint(client, acc) do
{:ok, byte} = :gen_tcp.recv(client, 1)
case byte do
<<0::1, _::7>> -> Read.start(acc <> byte) |> Read.varint() |> Read.stop()
<<1::1, _::7>> -> get_varint(client, acc <> byte)
end
end
end
defmodule Amethyst.Server do
@moduledoc """
This module includes shared boilerplate code for all stages of the server.
"""
require Logger
defmacro __using__(_opts) do
quote do
@spec serve(:gen_tcp.socket()) :: no_return()
2024-07-09 18:57:09 +02:00
def serve(client, state \\ []) do
{id, data} = Amethyst.Server.Generic.get_packet(client)
packet = deserialize(id, data)
Logger.debug("Got packet #{inspect(packet)}")
2024-07-09 18:57:09 +02:00
{result, state} = handle(packet, client, state)
if result != :ok do
Logger.warning("Handler returned result #{result}")
end
serve(client, state)
end
def transmit(packet, client) do
Logger.debug("Transmitting #{inspect(packet)}")
data = serialize(packet)
length = byte_size(data) |> Amethyst.Minecraft.Write.varint()
Logger.debug("Sending #{inspect(length <> data)}")
:gen_tcp.send(client, length <> data)
end
end
end
end