|
| 1 | +defmodule Hermes.Transport.STDIO do |
| 2 | + @moduledoc """ |
| 3 | + A transport implementation that uses standard input/output. |
| 4 | + """ |
| 5 | + |
| 6 | + use GenServer |
| 7 | + |
| 8 | + import Peri |
| 9 | + |
| 10 | + alias Hermes.Transport.Behaviour, as: Transport |
| 11 | + |
| 12 | + require Logger |
| 13 | + |
| 14 | + @behaviour Transport |
| 15 | + |
| 16 | + @type params_t :: Enumerable.t(option) |
| 17 | + @type option :: |
| 18 | + {:command, Path.t()} |
| 19 | + | {:args, list(String.t()) | nil} |
| 20 | + | {:env, map() | nil} |
| 21 | + | {:cwd, Path.t() | nil} |
| 22 | + | Supervisor.init_option() |
| 23 | + |
| 24 | + defschema :options_schema, %{ |
| 25 | + name: {:atom, {:default, __MODULE__}}, |
| 26 | + client: {:required, {:either, {:pid, :atom}}}, |
| 27 | + command: {:required, :string}, |
| 28 | + args: {{:list, :string}, {:default, nil}}, |
| 29 | + env: {:map, {:default, nil}}, |
| 30 | + cwd: {:string, {:default, nil}} |
| 31 | + } |
| 32 | + |
| 33 | + @win32_default_env [ |
| 34 | + "APPDATA", |
| 35 | + "HOMEDRIVE", |
| 36 | + "HOMEPATH", |
| 37 | + "LOCALAPPDATA", |
| 38 | + "PATH", |
| 39 | + "PROCESSOR_ARCHITECTURE", |
| 40 | + "SYSTEMDRIVE", |
| 41 | + "SYSTEMROOT", |
| 42 | + "TEMP", |
| 43 | + "USERNAME", |
| 44 | + "USERPROFILE" |
| 45 | + ] |
| 46 | + @unix_default_env ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"] |
| 47 | + |
| 48 | + @impl Transport |
| 49 | + @spec start_link(params_t) :: Supervisor.on_start() |
| 50 | + def start_link(opts \\ []) do |
| 51 | + opts = options_schema!(opts) |
| 52 | + GenServer.start_link(__MODULE__, Map.new(opts), name: opts[:name]) |
| 53 | + end |
| 54 | + |
| 55 | + @impl Transport |
| 56 | + def send_message(pid \\ __MODULE__, message) when is_binary(message) do |
| 57 | + GenServer.call(pid, {:send, message}) |
| 58 | + end |
| 59 | + |
| 60 | + @impl GenServer |
| 61 | + def init(%{} = opts) do |
| 62 | + state = Map.merge(opts, %{port: nil, ref: nil}) |
| 63 | + |
| 64 | + {:ok, state, {:continue, :spawn}} |
| 65 | + end |
| 66 | + |
| 67 | + @impl GenServer |
| 68 | + def handle_continue(:spawn, state) do |
| 69 | + if cmd = System.find_executable(state.command) do |
| 70 | + port = spawn_port(cmd, state) |
| 71 | + ref = Port.monitor(port) |
| 72 | + |
| 73 | + {:noreply, %{state | port: port, ref: ref}} |
| 74 | + else |
| 75 | + {:stop, {:error, "Command not found: #{state.command}"}, state} |
| 76 | + end |
| 77 | + end |
| 78 | + |
| 79 | + @impl GenServer |
| 80 | + def handle_call({:send, message}, _, %{port: port} = state) when is_port(port) do |
| 81 | + result = if Port.command(port, message), do: :ok, else: {:error, :port_not_connected} |
| 82 | + {:reply, result, state} |
| 83 | + end |
| 84 | + |
| 85 | + def handle_call({:send, _message}, _, state) do |
| 86 | + {:reply, {:error, :port_not_connected}, state} |
| 87 | + end |
| 88 | + |
| 89 | + @impl GenServer |
| 90 | + def handle_info({port, {:data, data}}, %{port: port} = state) do |
| 91 | + Logger.info("Received data: #{inspect(data)}") |
| 92 | + Process.send(state.client, {:response, data}, [:noconnect]) |
| 93 | + {:noreply, state} |
| 94 | + end |
| 95 | + |
| 96 | + def handle_info({port, :closed}, %{port: port} = state) do |
| 97 | + Logger.warning("Port closed, restarting") |
| 98 | + {:stop, :normal, state} |
| 99 | + end |
| 100 | + |
| 101 | + def handle_info({port, {:exit_status, status}}, %{port: port} = state) do |
| 102 | + Logger.warning("Port exited with status: #{status}") |
| 103 | + {:stop, status, state} |
| 104 | + end |
| 105 | + |
| 106 | + def handle_info({:DOWN, ref, :port, port, reason}, %{ref: ref, port: port} = state) do |
| 107 | + Logger.error("Port monitor DOWN: #{inspect(reason)}") |
| 108 | + {:stop, reason, state} |
| 109 | + end |
| 110 | + |
| 111 | + def handle_info({:EXIT, port, reason}, %{port: port} = state) do |
| 112 | + Logger.error("Port exited: #{inspect(reason)}") |
| 113 | + {:stop, reason, state} |
| 114 | + end |
| 115 | + |
| 116 | + @impl GenServer |
| 117 | + def handle_cast(:close_port, %{port: port} = state) do |
| 118 | + Port.close(port) |
| 119 | + {:stop, :normal, state} |
| 120 | + end |
| 121 | + |
| 122 | + defp spawn_port(cmd, state) do |
| 123 | + default_env = get_default_env() |
| 124 | + env = if is_nil(state.env), do: default_env, else: Map.merge(default_env, state.env) |
| 125 | + env = normalize_env_for_erlang(env) |
| 126 | + |
| 127 | + opts = |
| 128 | + [:binary] |
| 129 | + |> then(&if is_nil(state.args), do: &1, else: Enum.concat(&1, args: state.args)) |
| 130 | + |> then(&if is_nil(state.env), do: &1, else: Enum.concat(&1, env: env)) |
| 131 | + |> then(&if is_nil(state.cwd), do: &1, else: Enum.concat(&1, cd: state.cwd)) |
| 132 | + |
| 133 | + Port.open({:spawn_executable, cmd}, opts) |
| 134 | + end |
| 135 | + |
| 136 | + defp get_default_env do |
| 137 | + default_env = if :os.type() == {:win32, :nt}, do: @win32_default_env, else: @unix_default_env |
| 138 | + |
| 139 | + System.get_env() |
| 140 | + |> Enum.filter(fn {k, _} -> Enum.member?(default_env, k) end) |
| 141 | + # remove functions, for security risks |
| 142 | + |> Enum.reject(fn {_, v} -> String.starts_with?(v, "()") end) |
| 143 | + |> Enum.into(%{}) |
| 144 | + end |
| 145 | + |
| 146 | + defp normalize_env_for_erlang(%{} = env) do |
| 147 | + env |
| 148 | + |> Map.new(fn {k, v} -> {to_charlist(k), to_charlist(v)} end) |
| 149 | + |> Enum.into([]) |
| 150 | + end |
| 151 | +end |
0 commit comments