# 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. """ defmacro __using__(_opts) do quote do @spec serve(:gen_tcp.socket()) :: no_return() def serve(client) do {id, data} = Amethyst.Server.Generic.get_packet(client) packet = deserialize(id, data) Logger.debug("Got packet #{inspect(packet)}") handle(packet, client) serve(client) end def transmit(packet, client) do Logger.debug("Transmitting #{inspect(packet)}") data = serialize(packet) length = byte_size(data) |> Amethyst.Minecraft.Write.varint() :gen_tcp.send(client, length <> data) end end end end