# 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.Stage1 do @moduledoc """ This module contains the stage 1 (Handshaking) server logic. """ require Logger alias Amethyst.Minecraft.Read @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 ## DESERIALIZATION # Handshake https://wiki.vg/Protocol#Handshake @spec deserialize(0, binary()) :: {:handshake, any(), any(), any(), :login | :status | :transfer} def deserialize(0x00, <>) do {[ver, addr, port, next], ""} = Read.start(data) |> Read.varint() |> Read.string() |> Read.ushort() |> Read.varint() |> Read.stop() next = case next do 1 -> :status 2 -> :login 3 -> :transfer _ -> raise RuntimeError, "Client requested moving to an unknown state!" end {:handshake, ver, addr, port, next} end def deserialize(type, _) do raise RuntimeError, "Got unknown packet type #{type}!" end ## HANDLING # Handshake https://wiki.vg/Protocol#Handshake @spec handle(any(), any()) :: no_return() def handle({:handshake, ver, addr, port, next}, client) do Logger.info("Got handshake, version #{ver} on #{addr}:#{port}. Wants to move to #{next}") case next do :status -> Amethyst.Server.Status.serve(client) _ -> raise RuntimeError, "Unhandled move to next mode #{next}" end end def handle(tuple, _) do Logger.error("Unhandled but known packet #{elem(tuple, 0)}") end end