Source file local.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
external sun_path_size : unit -> int = "caml_eio_net_sun_path_size"

let max_path_length = sun_path_size () - 1

type fd = Unix.file_descr

external connect_at_dir : fd -> fd -> string -> unit = "caml_eio_net_connect_at"
external bind_at : fd -> fd -> string -> unit = "caml_eio_net_bind_at"
external private_dir : fd -> string -> fd = "caml_eio_net_private_dir"
external chmod_at : fd -> string -> int -> unit = "caml_eio_net_chmod_at"
external id_at : fd -> string -> bool * int64 * int64 = "caml_eio_net_id_at"
external link_at : fd -> string -> fd -> string -> unit = "caml_eio_net_link_at"

external rename_at : fd -> string -> fd -> string -> unit
  = "caml_eio_net_rename_at"

external unlink_at : fd -> string -> bool -> unit = "caml_eio_net_unlink_at"

let eio f =
  try f ()
  with Unix.Unix_error (e, fn, arg) -> raise (Eio_unix.Err.v e fn arg)

let receive ~sw ~max_fds ~max_length flow =
  let b = Buffer.create 4096 and buf = Cstruct.create 65536 in
  let rec go fds =
    let room = max_fds - List.length fds in
    match Eio_unix.Net.recv_msg_with_fds flow ~sw ~max_fds:room [ buf ] with
    | exception End_of_file -> Ok (Buffer.contents b, fds)
    | 0, got -> Ok (Buffer.contents b, fds @ got)
    | n, got when Buffer.length b + n > max_length ->
        List.iter Eio_unix.Fd.close (fds @ got);
        Error `Too_long
    | n, got ->
        Buffer.add_string b (Cstruct.to_string ~len:n buf);
        go (fds @ got)
  in
  go []

(* The directory that holds [path], opened through [path]'s own capability, so
   that a confined directory confines its resolution, and [path]'s base name.
   Opening it for reading gives the descriptor the system calls below resolve
   the name from. [fn] names the caller in a message. *)
let parent ~fn ~sw path =
  match Eio.Path.split path with
  | Some (dir, name) when name <> "." && name <> ".." -> (
      let flow = Eio.Path.open_in ~sw dir in
      match Eio_unix.Resource.fd_opt flow with
      | Some fd -> (fd, name)
      | None ->
          Fmt.invalid_arg
            "%s: path is in %a, which is not a directory of the host" fn
            Eio.Path.pp dir)
  | _ ->
      Fmt.invalid_arg "%s: path is %a, which names no file" fn Eio.Path.pp path

(* unix-socket.c, unix_sockaddr_init reaches a long path from its directory
   (local_stubs.c). The socket is non-blocking, so each attempt returns at
   once: Linux refuses a connect to a full backlog with EAGAIN, and it is
   tried again after a pause, doubled up to [max_pause], which a
   cancellation ends. *)
let max_pause = 0.1

let connect ~sw ~net:_ path =
  let sock = eio (fun () -> Unix.socket ~cloexec:true PF_UNIX SOCK_STREAM 0) in
  match
    Unix.set_nonblock sock;
    Eio.Switch.run ~name:"Eio_net_unix.Local.connect" @@ fun dsw ->
    let dir, name = parent ~fn:"Eio_net_unix.Local.connect" ~sw:dsw path in
    Eio_unix.Fd.use_exn "Eio_net_unix.Local.connect" dir @@ fun dir ->
    let rec attempt pause =
      match connect_at_dir dir sock name with
      | () -> ()
      | exception Unix.Unix_error (EINPROGRESS, _, _) -> (
          Eio_unix.await_writable sock;
          match Unix.getsockopt_error sock with
          | None -> ()
          | Some e -> raise (Unix.Unix_error (e, "connect", name)))
      | exception Unix.Unix_error ((EAGAIN | EWOULDBLOCK), _, _) ->
          Eio_unix.sleep pause;
          attempt (Float.min max_pause (2. *. pause))
    in
    eio (fun () -> attempt 0.001)
  with
  | () -> Eio_unix.Net.import_socket_stream ~sw ~close_unix:true sock
  | exception e ->
      Unix.close sock;
      raise e

let ignore_unix_error f = try f () with Unix.Unix_error _ -> ()

(* A private directory in [dir], whose name nobody else holds. *)
let rec private_dir_in dir ~attempts =
  let name =
    Fmt.str ".eio-net-%d-%08x" (Unix.getpid ())
      (Random.State.bits (Random.State.make_self_init ()))
  in
  match private_dir dir name with
  | fd -> (name, fd)
  | exception Unix.Unix_error (EEXIST, _, _) when attempts > 1 ->
      private_dir_in dir ~attempts:(attempts - 1)

(* bind(2) makes the socket's file with the modes the process's umask leaves,
   and changing the umask would change them for every thread. The socket is
   bound in a directory of its own, which no other user can enter, its mode
   set there, and it listens before it is linked to [name]: a peer reaches it
   only with its final mode. linkat(2) refuses a name that is taken;
   renameat(2), when [replace], takes the place of a socket. *)
let bind_and_place dir ~replace ~backlog ~perm name =
  let tmp, private_fd = private_dir_in dir ~attempts:16 in
  Fun.protect ~finally:(fun () ->
      ignore_unix_error (fun () -> unlink_at private_fd "s" false);
      Unix.close private_fd;
      ignore_unix_error (fun () -> unlink_at dir tmp true))
  @@ fun () ->
  let sock = Unix.socket ~cloexec:true PF_UNIX SOCK_STREAM 0 in
  match
    bind_at private_fd sock "s";
    chmod_at private_fd "s" perm;
    let _, dev, ino = id_at private_fd "s" in
    Unix.listen sock backlog;
    let in_use () = raise (Unix.Unix_error (EADDRINUSE, "bind", name)) in
    (match id_at dir name with
    | exception Unix.Unix_error (ENOENT, _, _) -> (
        try link_at private_fd "s" dir name
        with Unix.Unix_error (EEXIST, _, _) -> in_use ())
    | true, _, _ when replace -> rename_at private_fd "s" dir name
    | _ -> in_use ());
    Unix.set_nonblock sock;
    (dev, ino)
  with
  | id -> (sock, id)
  | exception e ->
      Unix.close sock;
      raise e

(* The kernel names a listener by the path it was bound at, in its private
   directory, so its address is the path given to [listen] instead. *)
module Listening = struct
  type tag = [ `Generic | `Unix ]

  type t = {
    socket : [ `Unix_fd | tag Eio.Net.listening_socket_ty ] Eio.Resource.t;
    addr : Eio.Net.Sockaddr.stream;
  }

  let accept t ~sw = Eio.Net.accept ~sw t.socket
  let close t = Eio.Resource.close t.socket
  let listening_addr t = t.addr
  let fd t = Eio_unix.Resource.fd t.socket

  let setsockopt : type a. t -> a Eio.Net.Sockopt.t -> a -> unit =
   fun t opt v -> Eio.Net.setsockopt t.socket opt v

  let getsockopt : type a. t -> a Eio.Net.Sockopt.t -> a =
   fun t opt -> Eio.Net.getsockopt t.socket opt
end

let listening_handler = Eio_unix.Pi.listening_socket_handler (module Listening)

let listen ?(replace = false) ~sw ~net:_ ~backlog ~perm path =
  let addr = `Unix (Option.value (Eio.Path.native path) ~default:(snd path)) in
  let dir, name = parent ~fn:"Eio_net_unix.Local.listen" ~sw path in
  let sock, id =
    Eio_unix.Fd.use_exn "Eio_net_unix.Local.listen" dir @@ fun dir ->
    eio @@ fun () ->
    Eio_unix.run_in_systhread ~label:"local-listen" (fun () ->
        bind_and_place dir ~replace ~backlog ~perm name)
  in
  let socket = Eio_unix.Net.import_socket_listening ~sw ~close_unix:true sock in
  (* Release runs its hooks last registered first, so [dir], opened on [sw]
     before this hook, is still open. *)
  Eio.Switch.on_release sw (fun () ->
      Eio_unix.Fd.use_exn "Eio_net_unix.Local.listen" dir @@ fun dir ->
      ignore_unix_error (fun () ->
          let _, dev, ino = id_at dir name in
          if (dev, ino) = id then unlink_at dir name false));
  Eio.Resource.T (Listening.{ socket; addr }, listening_handler)