Skip to content

Commit

Permalink
Expose listen in linux
Browse files Browse the repository at this point in the history
  • Loading branch information
patricoferris committed Feb 28, 2024
1 parent 5e34c4e commit ece7355
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
1 change: 0 additions & 1 deletion lib_eio_linux/eio_linux.ml
Expand Up @@ -262,7 +262,6 @@ let connect ~sw connect_addr =
let sock = Fd.of_unix ~sw ~seekable:false ~close_unix:true sock_unix in
Low_level.connect sock addr;
(flow sock :> _ Eio_unix.Net.stream_socket)

module Impl = struct
type t = unit
type tag = [`Unix | `Generic]
Expand Down
22 changes: 22 additions & 0 deletions lib_eio_linux/eio_linux.mli
Expand Up @@ -147,6 +147,14 @@ module Low_level : sig
val connect : fd -> Unix.sockaddr -> unit
(** [connect fd addr] attempts to connect socket [fd] to [addr]. *)

val listen :
reuse_addr:bool ->
reuse_port:bool ->
backlog:int ->
sw:Switch.t ->
Eio.Net.Sockaddr.stream ->
fd

val await_readable : fd -> unit
(** [await_readable fd] blocks until [fd] is readable (or has an error). *)

Expand Down Expand Up @@ -251,3 +259,17 @@ module Low_level : sig
end

end

val flow :
fd ->
[< `Close
| `File
| `Flow
| `Platform of [ `Generic | `Unix ]
| `R
| `Shutdown
| `Socket
| `Stream
| `Unix_fd
| `W ]
r
29 changes: 29 additions & 0 deletions lib_eio_linux/low_level.ml
Expand Up @@ -233,6 +233,35 @@ let connect fd addr =
raise ex
)

let listen ~reuse_addr ~reuse_port ~backlog ~sw listen_addr =
if reuse_addr then (
match listen_addr with
| `Tcp _ -> ()
| `Unix path ->
match Unix.lstat path with
| Unix.{ st_kind = S_SOCK; _ } -> Unix.unlink path
| _ -> ()
| exception Unix.Unix_error (Unix.ENOENT, _, _) -> ()
| exception Unix.Unix_error (code, name, arg) -> raise @@ Err.wrap code name arg
);
let addr = Eio_unix.Net.sockaddr_to_unix listen_addr in
let sock_unix = Unix.socket ~cloexec:true (Eio_unix.Net.socket_domain_of listen_addr) Unix.SOCK_STREAM 0 in
let sock = Fd.of_unix ~sw ~seekable:false ~close_unix:true sock_unix in
(* For Unix domain sockets, remove the path when done (except for abstract sockets). *)
begin match listen_addr with
| `Unix path ->
if String.length path > 0 && path.[0] <> Char.chr 0 then
Switch.on_release sw (fun () -> Unix.unlink path)
| `Tcp _ -> ()
end;
if reuse_addr then
Unix.setsockopt sock_unix Unix.SO_REUSEADDR true;
if reuse_port then
Unix.setsockopt sock_unix Unix.SO_REUSEPORT true;
Unix.bind sock_unix addr;
Unix.listen sock_unix backlog;
sock

let send_msg fd ?(fds=[]) ?dst buf =
Fd.use_exn "send_msg" fd @@ fun fd ->
Fd.use_exn_list "send_msg" fds @@ fun fds ->
Expand Down

0 comments on commit ece7355

Please sign in to comment.