implement automatic receiving of tun messages from elixir code

This commit is contained in:
lilly 2026-05-21 13:59:10 +02:00
commit 486fea2088
Signed by: lilly
SSH key fingerprint: SHA256:y9T5GFw2A20WVklhetIxG1+kcg/Ce0shnQmbu1LQ37g
10 changed files with 119 additions and 106 deletions

View file

@ -0,0 +1,52 @@
defmodule P2pChat.Transport.GenTun do
require Logger
use Rustler, otp_app: :p2p_chat, crate: "p2pchat_transport_gen_tun"
@behaviour GenServer
defstruct [:tun_handle]
#
# Server API
#
@impl true
def init(args) do
{:ok, tun_handle} = make_tun_device()
state = %__MODULE__{tun_handle: tun_handle}
{ :ok, state, { :continue, :recv } }
end
@impl true
def handle_continue(:recv, state) do
case tun_recv(state.tun_handle) do
{:ok, buf} ->
Logger.debug("Received #{byte_size(buf)} bytes")
{:error, :would_block} -> {}
{:error, e} ->
Logger.error("Error during receive: #{e}")
end
{:noreply, state, { :continue, :recv }}
end
@impl true
def handle_call({:recv}, _from, state) do
data = tun_recv(state.tun_handle)
{ :reply, data, state }
end
#
# Client API
#
def open() do
GenServer.start_link(__MODULE__, nil)
end
#
# NIFs
#
defp make_tun_device(), do: :erlang.nif_error(:nif_not_loaded)
defp tun_recv(_handle, _bufsize \\ 2*16), do: :erlang.nif_error(:nif_not_loaded)
end