package mgit

Build not yet checked
  1. Overview
  2. Docs
Git in OCaml

Install

dune-project
 Dependency

Authors

Maintainers

Sources

mgit-0.1.0.tbz
sha256=6fad812ce53e69e045c4d53d958fc0f12c13900841348dd37f0ba6dd0db2ba8d
sha512=3c2427bc9ee42748aa99540582125aea989dca574493ef46cae70d67ab005c517f079c6c537507b3cb53544811864d52d30df22993b7c297f6a6521f6484ff82

doc/src/mgit.unix/flow.ml.html

Source file flow.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
let error_msgf fmt = Fmt.kstr (fun msg -> Error (`Msg msg)) fmt
let ( let* ) = Result.bind
let inhibit fn value = try fn value with _exn -> ()

type ctx = {
    ssh: string
  ; authenticator: X509.Authenticator.t option
  ; happy_eyeballs: Happy_eyeballs.t option
  ; nameservers:
      (Dns.proto * Dns_client_miou_unix.Transport.io_addr list) option
  ; mutable service: Happy_eyeballs_miou_unix.t option
  ; mutable dns: Dns_client_miou_unix.t option
}

let ctx ?happy_eyeballs ?nameservers ?(ssh = "ssh") ?authenticator () =
  { ssh; authenticator; happy_eyeballs; nameservers; service= None; dns= None }

let daemon ctx =
  match ctx.happy_eyeballs with
  | Some happy_eyeballs ->
      let daemon, t = Happy_eyeballs_miou_unix.create ~happy_eyeballs () in
      let dns = Dns_client_miou_unix.create ?nameservers:ctx.nameservers t in
      let getaddrinfo record domain_name =
        match record with
        | `A ->
            let* ipaddr = Dns_client_miou_unix.gethostbyname dns domain_name in
            Ok Ipaddr.(Set.singleton (V4 ipaddr))
        | `AAAA ->
            let* ipaddr = Dns_client_miou_unix.gethostbyname6 dns domain_name in
            Ok Ipaddr.(Set.singleton (V6 ipaddr))
      in
      Happy_eyeballs_miou_unix.inject t getaddrinfo;
      let finally () = Happy_eyeballs_miou_unix.kill daemon in
      ctx.service <- Some t;
      ctx.dns <- Some dns;
      finally
  | None -> ignore

let daemon ctx = Option.map daemon ctx |> Option.value ~default:ignore

(* TCP/IP *)

let resolve ctx host port =
  match ctx.dns with
  | None -> begin
      let hints = Unix.[ AI_SOCKTYPE SOCK_STREAM; AI_FAMILY PF_INET ] in
      match Unix.getaddrinfo host (string_of_int port) hints with
      | [] -> error_msgf "%s:%d: no address" host port
      | infos -> Ok (List.map (fun { Unix.ai_addr; _ } -> ai_addr) infos)
      | exception Unix.Unix_error (err, _, _) ->
          error_msgf "%s: %s" host (Unix.error_message err)
    end
  | Some dns ->
      let* domain_name = Domain_name.of_string host in
      let* domain_name = Domain_name.host domain_name in
      let* ipaddr = Dns_client_miou_unix.gethostbyname dns domain_name in
      Ok [ Unix.ADDR_INET (Ipaddr_unix.to_inet_addr (Ipaddr.V4 ipaddr), port) ]

let pp_sockaddr ppf = function
  | Unix.ADDR_UNIX name -> Format.fprintf ppf "<%s>" name
  | Unix.ADDR_INET (inet_addr, port) ->
      Format.fprintf ppf "%s:%d" (Unix.string_of_inet_addr inet_addr) port

let connect_system ctx ?port ?tls_config host =
  let port =
    match (port, tls_config) with
    | None, None -> 80
    | None, Some _ -> 443
    | Some port, _ -> port
  in
  let* addr = Result.map List.hd (resolve ctx host port) in
  let[@warning "-8"] (Unix.ADDR_INET (inet_addr, port)) = addr in
  let socket =
    if Unix.is_inet6_addr inet_addr then Miou_unix.tcpv6 ()
    else Miou_unix.tcpv4 ()
  in
  let timeout = Miou.async @@ fun () -> Miou_unix.sleep 5.0; `Timeout in
  let connect =
    Miou.async @@ fun () ->
    Miou_unix.connect socket addr;
    `Connected
  in
  match Miou.await_first [ timeout; connect ] with
  | Error exn ->
      Miou_unix.close socket;
      error_msgf "Got an unexpected exception while connecting (%a): %s"
        pp_sockaddr addr (Printexc.to_string exn)
  | Ok `Timeout ->
      Miou_unix.close socket;
      error_msgf "Connection to %s (via %a) timeout" host pp_sockaddr addr
  | Ok `Connected -> begin
      let ipaddr = Ipaddr_unix.of_inet_addr inet_addr in
      match tls_config with
      | Some tls_config ->
          let tls = Tls_miou_unix.client_of_fd tls_config socket in
          let epoch = Tls_miou_unix.epoch tls in
          Ok (`Tls tls, ipaddr, port, epoch)
      | None -> Ok (`Tcp socket, ipaddr, port, None)
    end

let connect_happy_eyeballs ?port ?tls_config happy_eyeballs host =
  let port =
    match (port, tls_config) with
    | None, None -> 80
    | None, Some _ -> 443
    | Some port, _ -> port
  in
  let* (ipaddr, port), fd =
    Happy_eyeballs_miou_unix.connect happy_eyeballs host [ port ]
  in
  match tls_config with
  | None -> Ok (`Tcp fd, ipaddr, port, None)
  | Some tls_config ->
      let tls = Tls_miou_unix.client_of_fd tls_config fd in
      let epoch = Tls_miou_unix.epoch tls in
      Ok (`Tls tls, ipaddr, port, epoch)

let connect ctx ?port ?tls_config host =
  match ctx.service with
  | Some happy_eyeballs ->
      connect_happy_eyeballs ?port ?tls_config happy_eyeballs host
  | None -> connect_system ctx ?port ?tls_config host

let owned ~finally value =
  let resource = Miou.Ownership.create ~finally value in
  Miou.Ownership.own resource;
  resource

let socket = function
  | Unix.ADDR_INET (inet, _) when Unix.is_inet6_addr inet -> Miou_unix.tcpv6 ()
  | _ -> Miou_unix.tcpv4 ()

let rec attempt = function
  | [] -> error_msgf "Connection refused"
  | sockaddr :: rest ->
      let fd = socket sockaddr in
      let finally fd = inhibit Unix.close (Miou_unix.to_file_descr fd) in
      let resource = owned ~finally fd in
      begin match Miou_unix.connect fd sockaddr with
      | () -> Ok (fd, resource)
      | exception Unix.Unix_error (err, _, _) ->
          Miou_unix.close fd;
          Miou.Ownership.disown resource;
          begin match rest with
          | [] -> error_msgf "Connection failed: %s" (Unix.error_message err)
          | rest -> attempt rest
          end
      end

(* SSH *)

type process = {
    pid: int
  ; stdin: Miou_unix.file_descr
  ; stdout: Miou_unix.file_descr
}

let quote str =
  let buf = Buffer.create (String.length str + 2) in
  Buffer.add_char buf '\'';
  String.iter
    (function
      | '\'' -> Buffer.add_string buf "'\\''" | chr -> Buffer.add_char buf chr)
    str;
  Buffer.add_char buf '\'';
  Buffer.contents buf

(* The process is killed (and reaped) if the task which spawned it ends
   abnormally. *)
let abort { pid; stdin; stdout } =
  inhibit Unix.close (Miou_unix.to_file_descr stdin);
  inhibit Unix.close (Miou_unix.to_file_descr stdout);
  inhibit (fun () -> Unix.kill pid Sys.sigkill) ();
  inhibit (fun () -> ignore (Unix.waitpid [] pid)) ()

let spawn prog args env =
  let in_r, in_w = Unix.pipe ~cloexec:true () in
  let out_r, out_w = Unix.pipe ~cloexec:true () in
  match
    Unix.create_process_env prog
      (Array.of_list (prog :: args))
      env in_r out_w Unix.stderr
  with
  | pid ->
      Unix.close in_r;
      Unix.close out_w;
      let process =
        {
          pid
        ; stdin= Miou_unix.of_file_descr ~non_blocking:true in_w
        ; stdout= Miou_unix.of_file_descr ~non_blocking:true out_r
        }
      in
      Ok (process, owned ~finally:abort process)
  | exception Unix.Unix_error (err, _, _) ->
      List.iter Unix.close [ in_r; in_w; out_r; out_w ];
      error_msgf "%s: %s" prog (Unix.error_message err)

let ssh ctx edn ~service ~version =
  let host =
    match edn.Mgit_sync.Endpoint.user with
    | Some user -> user ^ "@" ^ edn.Mgit_sync.Endpoint.host
    | None -> edn.Mgit_sync.Endpoint.host
  in
  let port =
    match edn.Mgit_sync.Endpoint.port with
    | Some port -> [ "-p"; string_of_int port ]
    | None -> []
  in
  (* NOTE(dinosaure): the version of the protocol is given to the remote as
     [GIT_PROTOCOL], if the SSH server accepts it. *)
  let env, send_env =
    if version >= 2 then
      ( Array.append (Unix.environment ())
          [| Fmt.str "GIT_PROTOCOL=version=%d" version |]
      , [ "-o"; "SendEnv=GIT_PROTOCOL" ] )
    else (Unix.environment (), [])
  in
  let command = Fmt.str "%s %s" service (quote edn.Mgit_sync.Endpoint.path) in
  spawn ctx.ssh (send_env @ port @ [ host; command ]) env

(* HTTP *)

module Client = struct
  type nonrec ctx = ctx

  let request ctx ~meth ~headers ?body ~uri fn =
    let body = Option.map Httpcats.stream body in
    let handler _meta _req resp () = function
      | Some str when Httpcats.Status.is_successful resp.Httpcats.status ->
          fn str
      | _ -> ()
    in
    let meth = (meth :> H1.Method.t) in
    let resolver = `User (connect ctx) in
    let authenticator = ctx.authenticator in
    let follow_redirect = true in
    let fn = handler in
    match
      Httpcats.request ~resolver ?authenticator ~follow_redirect ~meth ~headers
        ?body ~fn ~uri ()
    with
    | Ok (resp, ()) when Httpcats.Status.is_successful resp.Httpcats.status ->
        Ok ()
    | Ok (resp, ()) ->
        error_msgf "%s: %a" uri Httpcats.Status.pp_hum resp.Httpcats.status
    | Error err -> error_msgf "%s: %a" uri Httpcats.pp_error err
end

module Http = Mgit_http.Make (Client)

(* Git_flow *)

type flow = Tcp of Miou_unix.file_descr | Ssh of process | Http of Http.t
type t = { flow: flow; resource: Miou.Ownership.t }

let connect ctx edn ~service ~version =
  match edn.Mgit_sync.Endpoint.scheme with
  | `Git ->
      let host = edn.Mgit_sync.Endpoint.host
      and port = Mgit_sync.Endpoint.port edn in
      let* targets = resolve ctx host port in
      let* fd, resource = attempt targets in
      Ok { flow= Tcp fd; resource }
  | `SSH ->
      let* process, resource = ssh ctx edn ~service ~version in
      Ok { flow= Ssh process; resource }
  | `HTTP | `HTTPS ->
      let* http = Http.connect ctx edn ~service ~version in
      Ok { flow= Http http; resource= owned ~finally:Http.abort http }

let read fd buf ~off ~len =
  match Miou_unix.read fd ~off ~len buf with
  | 0 -> Ok `End
  | len -> Ok (`Len len)
  | exception Unix.Unix_error (err, _, _) ->
      error_msgf "recv: %s" (Unix.error_message err)

let write fd str ~off ~len =
  match Miou_unix.write fd ~off ~len str with
  | () -> Ok len
  | exception Unix.Unix_error (err, _, _) ->
      error_msgf "send: %s" (Unix.error_message err)

let recv t buf ~off ~len =
  match t.flow with
  | Tcp fd -> read fd buf ~off ~len
  | Ssh { stdout; _ } -> read stdout buf ~off ~len
  | Http http -> Http.recv http buf ~off ~len

let send t str ~off ~len =
  match t.flow with
  | Tcp fd -> write fd str ~off ~len
  | Ssh { stdin; _ } -> write stdin str ~off ~len
  | Http http -> Http.send http str ~off ~len

let close_fd fd = try Miou_unix.close fd with Unix.Unix_error _ -> ()

let close t =
  begin match t.flow with
  | Tcp fd -> close_fd fd
  | Ssh { pid; stdin; stdout } -> (
      close_fd stdin;
      close_fd stdout;
      try ignore (Unix.waitpid [] pid) with Unix.Unix_error _ -> ())
  | Http http -> Http.close http
  end;
  Miou.Ownership.disown t.resource