Skip to content

Commit a613a03

Browse files
committed
into develop
2 parents d88e3a6 + a31cd0a commit a613a03

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

‎lib/shadowsocks/listener.ex‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ defmodule Shadowsocks.Listener do
99
@opts [:binary, {:backlog, 20},{:nodelay, true},
1010
{:active, false}, {:packet, :raw},{:reuseaddr, true},
1111
{:send_timeout_close, true}, {:buffer, 16384}]
12+
@tcp_fastopen_queue_length 5
1213

1314
@default_arg %{ota: false, method: "rc4-md5", udp: false, type: :server}
1415

@@ -17,6 +18,10 @@ defmodule Shadowsocks.Listener do
1718
@min_time Application.get_env(:shadowsocks, :report, [])
1819
|> Keyword.get(:port_min_time, 60 * 1000)
1920

21+
# constants
22+
@sol_tcp 6
23+
@tcp_fastopen_linux 23
24+
2025
def update(pid, args) when is_list(args) do
2126
map_arg = for {k, v} <- args, do: {k,v}, into: %{}
2227
update(pid, map_arg)
@@ -51,6 +56,7 @@ defmodule Shadowsocks.Listener do
5156
end
5257

5358
with {:ok, lsock} <- :gen_tcp.listen(args.port, opts),
59+
_ <- enable_tcp_fastopen(lsock),
5460
{:ok, _} <- :prim_inet.async_accept(lsock, -1),
5561
{:ok, udp_pid} <- start_udprelay(args) do
5662
Shadowsocks.Event.start_listener(args.port)
@@ -88,7 +94,9 @@ defmodule Shadowsocks.Listener do
8894
{:reply, port, state}
8995
end
9096

91-
def handle_info({:inet_async, _, _, {:ok, csock}}, state) do
97+
def handle_info({:inet_async, lsock, _, {:ok, csock}}, state) do
98+
{:ok, opts} = :inet.getopts(lsock, [:active, :nodelay, :keepalive, :delay_send, :priority, :tos])
99+
:ok = :inet.setopts(csock, opts)
92100
true = :inet_db.register_socket(csock, :inet_tcp)
93101
{:ok, pid} = Shadowsocks.Conn.start_link(csock, state(state, :args))
94102
Process.put(pid, {0, 0})
@@ -160,6 +168,19 @@ defmodule Shadowsocks.Listener do
160168
{:ok, nil}
161169
end
162170

171+
defp enable_tcp_fastopen(lsock) do
172+
try do
173+
case :os.type do
174+
{:unix, :linux} ->
175+
:inet.setopts(lsock, [{:raw, @sol_tcp, @tcp_fastopen_linux, <<@tcp_fastopen_queue_length::native-32>>}]);
176+
os ->
177+
{:error, {:unknown_os, os}}
178+
end
179+
catch
180+
_, err -> {:error, err}
181+
end
182+
end
183+
163184
defp merge_args(old_args, args) do
164185
Map.merge(old_args, args)
165186
|> validate_arg(:port, :required)

0 commit comments

Comments
 (0)