ranch_tcp.erl 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. %% Copyright (c) 2011-2018, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(ranch_tcp).
  15. -behaviour(ranch_transport).
  16. -export([name/0]).
  17. -export([secure/0]).
  18. -export([messages/0]).
  19. -export([listen/1]).
  20. -export([disallowed_listen_options/0]).
  21. -export([accept/2]).
  22. -export([handshake/3]).
  23. -export([connect/3]).
  24. -export([connect/4]).
  25. -export([recv/3]).
  26. -export([recv_proxy_header/2]).
  27. -export([send/2]).
  28. -export([sendfile/2]).
  29. -export([sendfile/4]).
  30. -export([sendfile/5]).
  31. -export([setopts/2]).
  32. -export([getopts/2]).
  33. -export([getstat/1]).
  34. -export([getstat/2]).
  35. -export([controlling_process/2]).
  36. -export([peername/1]).
  37. -export([sockname/1]).
  38. -export([shutdown/2]).
  39. -export([close/1]).
  40. -type opt() :: {backlog, non_neg_integer()}
  41. | {buffer, non_neg_integer()}
  42. | {delay_send, boolean()}
  43. | {dontroute, boolean()}
  44. | {exit_on_close, boolean()}
  45. | {fd, non_neg_integer()}
  46. | {high_msgq_watermark, non_neg_integer()}
  47. | {high_watermark, non_neg_integer()}
  48. | inet
  49. | inet6
  50. | {ip, inet:ip_address() | inet:local_address()}
  51. | {ipv6_v6only, boolean()}
  52. | {keepalive, boolean()}
  53. | {linger, {boolean(), non_neg_integer()}}
  54. | {low_msgq_watermark, non_neg_integer()}
  55. | {low_watermark, non_neg_integer()}
  56. | {nodelay, boolean()}
  57. | {port, inet:port_number()}
  58. | {priority, integer()}
  59. | {raw, non_neg_integer(), non_neg_integer(), binary()}
  60. | {recbuf, non_neg_integer()}
  61. | {send_timeout, timeout()}
  62. | {send_timeout_close, boolean()}
  63. | {sndbuf, non_neg_integer()}
  64. | {tos, integer()}.
  65. -export_type([opt/0]).
  66. -type opts() :: [opt()].
  67. -export_type([opts/0]).
  68. name() -> tcp.
  69. -spec secure() -> boolean().
  70. secure() ->
  71. false.
  72. messages() -> {tcp, tcp_closed, tcp_error, tcp_passive}.
  73. -spec listen(ranch:transport_opts(opts())) -> {ok, inet:socket()} | {error, atom()}.
  74. listen(TransOpts) ->
  75. Logger = maps:get(logger, TransOpts, logger),
  76. SocketOpts0 = maps:get(socket_opts, TransOpts, []),
  77. SocketOpts1 = ranch:set_option_default(SocketOpts0, backlog, 1024),
  78. SocketOpts2 = ranch:set_option_default(SocketOpts1, nodelay, true),
  79. SocketOpts3 = ranch:set_option_default(SocketOpts2, send_timeout, 30000),
  80. SocketOpts4 = ranch:set_option_default(SocketOpts3, send_timeout_close, true),
  81. %% We set the port to 0 because it is given in the Opts directly.
  82. %% The port in the options takes precedence over the one in the
  83. %% first argument.
  84. gen_tcp:listen(0, ranch:filter_options(SocketOpts4, disallowed_listen_options(),
  85. [binary, {active, false}, {packet, raw}, {reuseaddr, true}], Logger)).
  86. %% 'binary' and 'list' are disallowed but they are handled
  87. %% specifically as they do not have 2-tuple equivalents.
  88. disallowed_listen_options() ->
  89. [active, header, mode, packet, packet_size, line_delimiter, reuseaddr].
  90. -spec accept(inet:socket(), timeout())
  91. -> {ok, inet:socket()} | {error, closed | timeout | atom()}.
  92. accept(LSocket, Timeout) ->
  93. gen_tcp:accept(LSocket, Timeout).
  94. -spec handshake(inet:socket(), opts(), timeout()) -> {ok, inet:socket()}.
  95. handshake(CSocket, _, _) ->
  96. {ok, CSocket}.
  97. %% @todo Probably filter Opts?
  98. -spec connect(inet:ip_address() | inet:hostname(),
  99. inet:port_number(), any())
  100. -> {ok, inet:socket()} | {error, atom()}.
  101. connect(Host, Port, Opts) when is_integer(Port) ->
  102. gen_tcp:connect(Host, Port,
  103. Opts ++ [binary, {active, false}, {packet, raw}]).
  104. %% @todo Probably filter Opts?
  105. -spec connect(inet:ip_address() | inet:hostname(),
  106. inet:port_number(), any(), timeout())
  107. -> {ok, inet:socket()} | {error, atom()}.
  108. connect(Host, Port, Opts, Timeout) when is_integer(Port) ->
  109. gen_tcp:connect(Host, Port,
  110. Opts ++ [binary, {active, false}, {packet, raw}],
  111. Timeout).
  112. -spec recv(inet:socket(), non_neg_integer(), timeout())
  113. -> {ok, any()} | {error, closed | atom()}.
  114. recv(Socket, Length, Timeout) ->
  115. gen_tcp:recv(Socket, Length, Timeout).
  116. -spec recv_proxy_header(inet:socket(), timeout())
  117. -> {ok, ranch_proxy_header:proxy_info()}
  118. | {error, closed | atom()}
  119. | {error, protocol_error, atom()}.
  120. recv_proxy_header(Socket, Timeout) ->
  121. case recv(Socket, 0, Timeout) of
  122. {ok, Data} ->
  123. case ranch_proxy_header:parse(Data) of
  124. {ok, ProxyInfo, <<>>} ->
  125. {ok, ProxyInfo};
  126. {ok, ProxyInfo, Rest} ->
  127. case gen_tcp:unrecv(Socket, Rest) of
  128. ok ->
  129. {ok, ProxyInfo};
  130. Error ->
  131. Error
  132. end;
  133. {error, HumanReadable} ->
  134. {error, protocol_error, HumanReadable}
  135. end;
  136. Error ->
  137. Error
  138. end.
  139. -spec send(inet:socket(), iodata()) -> ok | {error, atom()}.
  140. send(Socket, Packet) ->
  141. gen_tcp:send(Socket, Packet).
  142. -spec sendfile(inet:socket(), file:name_all() | file:fd())
  143. -> {ok, non_neg_integer()} | {error, atom()}.
  144. sendfile(Socket, Filename) ->
  145. sendfile(Socket, Filename, 0, 0, []).
  146. -spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
  147. non_neg_integer())
  148. -> {ok, non_neg_integer()} | {error, atom()}.
  149. sendfile(Socket, File, Offset, Bytes) ->
  150. sendfile(Socket, File, Offset, Bytes, []).
  151. -spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
  152. non_neg_integer(), [{chunk_size, non_neg_integer()}])
  153. -> {ok, non_neg_integer()} | {error, atom()}.
  154. sendfile(Socket, Filename, Offset, Bytes, Opts)
  155. when is_list(Filename) orelse is_atom(Filename)
  156. orelse is_binary(Filename) ->
  157. case file:open(Filename, [read, raw, binary]) of
  158. {ok, RawFile} ->
  159. try sendfile(Socket, RawFile, Offset, Bytes, Opts) of
  160. Result -> Result
  161. after
  162. ok = file:close(RawFile)
  163. end;
  164. {error, _} = Error ->
  165. Error
  166. end;
  167. sendfile(Socket, RawFile, Offset, Bytes, Opts) ->
  168. Opts2 = case Opts of
  169. [] -> [{chunk_size, 16#1FFF}];
  170. _ -> Opts
  171. end,
  172. try file:sendfile(RawFile, Socket, Offset, Bytes, Opts2) of
  173. Result -> Result
  174. catch
  175. error:{badmatch, {error, enotconn}} ->
  176. %% file:sendfile/5 might fail by throwing a
  177. %% {badmatch, {error, enotconn}}. This is because its
  178. %% implementation fails with a badmatch in
  179. %% prim_file:sendfile/10 if the socket is not connected.
  180. {error, closed}
  181. end.
  182. %% @todo Probably filter Opts?
  183. -spec setopts(inet:socket(), list()) -> ok | {error, atom()}.
  184. setopts(Socket, Opts) ->
  185. inet:setopts(Socket, Opts).
  186. -spec getopts(inet:socket(), [atom()]) -> {ok, list()} | {error, atom()}.
  187. getopts(Socket, Opts) ->
  188. inet:getopts(Socket, Opts).
  189. -spec getstat(inet:socket()) -> {ok, list()} | {error, atom()}.
  190. getstat(Socket) ->
  191. inet:getstat(Socket).
  192. -spec getstat(inet:socket(), [atom()]) -> {ok, list()} | {error, atom()}.
  193. getstat(Socket, OptionNames) ->
  194. inet:getstat(Socket, OptionNames).
  195. -spec controlling_process(inet:socket(), pid())
  196. -> ok | {error, closed | not_owner | atom()}.
  197. controlling_process(Socket, Pid) ->
  198. gen_tcp:controlling_process(Socket, Pid).
  199. -spec peername(inet:socket())
  200. -> {ok, {inet:ip_address(), inet:port_number()} | {local, binary()}} | {error, atom()}.
  201. peername(Socket) ->
  202. inet:peername(Socket).
  203. -spec sockname(inet:socket())
  204. -> {ok, {inet:ip_address(), inet:port_number()} | {local, binary()}} | {error, atom()}.
  205. sockname(Socket) ->
  206. inet:sockname(Socket).
  207. -spec shutdown(inet:socket(), read | write | read_write)
  208. -> ok | {error, atom()}.
  209. shutdown(Socket, How) ->
  210. gen_tcp:shutdown(Socket, How).
  211. -spec close(inet:socket()) -> ok.
  212. close(Socket) ->
  213. gen_tcp:close(Socket).