# 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 . 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 {[length], ""} = get_varint(client, "") 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 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 @callback init(any()) :: any() @callback deserialize(integer(), binary()) :: any() @callback serialize(any()) :: binary() @callback handle(any(), :gen_tcp.socket(), any()) :: {:ok, any()} | {:unhandled, any()} defmacro __using__(_opts) do quote do @behaviour Amethyst.Server @spec serve(:gen_tcp.socket(), any()) :: no_return() def serve(client, state \\ []) do Logger.debug("#{__MODULE__} serving client #{inspect(client)}") serve(client, init(state)) end defp serve_loop(client, state) do {id, data} = Amethyst.Server.Generic.get_packet(client) Logger.debug("State: #{inspect(state)}") packet = deserialize(id, data) Logger.debug("Got packet #{inspect(packet)}") {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