(* Copyright (c) 2024-2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. *) module Reader = Bytesrw.Bytes.Reader module Slice = Bytesrw.Bytes.Slice let src = Logs.Src.create "git.ssh" ~doc:"Git fetch over SSH" module L = (val Logs.src_log src : Logs.LOG) open Result.Syntax type operation_probe = { operation : string; host : string; path : string } let operation_span = Probe.span "git.ssh.operation" ~doc:"Git operation over SSH" Probe.Fields.( obj (fun operation host path -> { operation; host; path }) |> field "operation" string ~enc:(fun t -> t.operation) |> field "host" string ~enc:(fun t -> t.host) |> field "path" string ~enc:(fun t -> t.path) |> seal) type channel_probe = { operation : string; channel : int64; direction : string; bytes : int; } let channel_event = Probe.event "git.ssh.channel" ~doc:"Git SSH channel I/O" Probe.Fields.( obj (fun operation channel direction bytes -> { operation; channel; direction; bytes }) |> field "operation" string ~enc:(fun t -> t.operation) |> field "channel" int64 ~enc:(fun t -> t.channel) |> field "direction" string ~enc:(fun t -> t.direction) |> field "bytes" int ~enc:(fun t -> t.bytes) |> seal) let emit_channel ~operation ~channel ~direction ~bytes = if bytes > 0 then Probe.emit channel_event { operation; channel = Int64.of_int32 channel; direction; bytes } let with_operation ~operation ~host ~path f = Probe.with_span operation_span { operation; host; path } f let log_remote_stderr msg = if msg = "" || msg = "Welcome to this knot!" then L.debug (fun m -> m "remote: %s" msg) else L.info (fun m -> m "remote: %s" msg) let close_client_channel client id = try Ssh_eio.Client.close client ~id with Ssh_eio.Ssh_error _ | Eio.Io _ | End_of_file -> () (* Channel [id]'s stdout as a pull reader, over {!Ssh_eio.Client.channel_reader}: it owns the receiver fiber, EOF/exit-status handling, and the bytesrw bridge. The two git-specific concerns wrap it here -- the [git.ssh.channel] rx probe via {!Reader.tap}, and buffering the remote's stderr so a failed operation can surface the server's message. The stderr is a peer's display text (RFC 4251 section 9.2), filtered once where it arrives, so the log line and the error show its controls escaped; [on_progress] has it as {!Git.Progress.Remote} lines, and is told the last of them by the [flush] this returns. *) let channel_reader ?stall ?on_progress ~sw client id = let remote_stderr = Buffer.create 128 in let lines = Option.map Git.Progress.lines on_progress in let on_stderr msg = Option.iter (fun l -> Git.Progress.feed l msg) lines; let msg = Ssh.Core.filter_control (String.trim msg) in log_remote_stderr msg; if msg <> "" then begin if Buffer.length remote_stderr > 0 then Buffer.add_char remote_stderr '\n'; Buffer.add_string remote_stderr msg end in let reader, exit_status = Ssh_eio.Client.channel_reader ~sw ~on_stderr client ~id in let reader = Reader.tap (fun s -> emit_channel ~operation:"ssh_channel" ~channel:id ~direction:"rx" ~bytes:(Slice.length s)) reader in let reader = match stall with | None -> reader | Some p -> Eio_net.Progress.reader p reader in let flush () = Option.iter Git.Progress.flush lines in (reader, exit_status, (fun () -> Buffer.contents remote_stderr), flush) (* A failure the transport saw, named by what the remote wrote when it wrote anything: [band], its side-band text, then its stderr. *) let explain ?(band = "") remote_stderr transport_error = match List.filter (( <> ) "") [ String.trim band; String.trim (remote_stderr ()) ] with | [] -> transport_error | msgs -> "remote: " ^ String.concat "\n" msgs let remote_or_transport_error ?band remote_stderr transport_error = Error (`Msg (explain ?band remote_stderr transport_error)) (* The text of side-bands 2 and 3 in what is left of [reader] (gitprotocol-pack(5), "Packfile Data"), one line per message and each the peer's display text as its stderr is; it ends where the stream stops reading as side-band pkt-lines. *) let side_band_text reader = let b = Buffer.create 128 in let add text = List.iter (fun line -> let line = Ssh.Core.filter_control (String.trim line) in if line <> "" then begin if Buffer.length b > 0 then Buffer.add_char b '\n'; Buffer.add_string b line end) (String.split_on_char '\n' text) in let rec go () = match Git.Smart.Packet.of_reader reader with | Ok (Data payload) -> ( match Git.Smart.Message.Side_band.of_payload payload with | Ok (Progress text | Error text) -> add text; go () | Ok (Pack _) -> go () | Error _ -> ()) | Ok (Flush | Delim | Response_end) -> go () | Error _ -> () in (try go () with Ssh_eio.Ssh_error _ | Git.Store.Wire_budget_exceeded | End_of_file -> ()); Buffer.contents b let ok_or_remote_exit exit_status ok = match exit_status () with | Some status when status <> 0l -> Fmt.error_msg "remote command exited with status %ld" status | _ -> ok (* [service] on the repository at [path], as Git asks an SSH server to run it (connect.c, quoted with sq_quote_buf in quote.c): the path in single quotes, each ' as '\'' and each ! as '\!', so the server's shell reads it back as one argument. *) let command service path = let b = Buffer.create (String.length path + 32) in Buffer.add_string b service; Buffer.add_string b " '"; String.iter (function | ('\'' | '!') as c -> Buffer.add_string b "'\\"; Buffer.add_char b c; Buffer.add_char b '\'' | c -> Buffer.add_char b c) path; Buffer.add_char b '\''; Buffer.contents b let known_hosts_name ~host ~port = if port = 22 then host else Fmt.str "[%s]:%d" host port let rec recorded = function | `Key k -> [ k ] | `Any l -> List.concat_map recorded l | `Observed (a, _) -> recorded a | `No_authentication | `Fingerprint _ | `Sha256 _ -> [] type host_key_error = | Unknown_host of { host : string; offered : Ssh.Hostkey.pub } | Changed_key of { host : string; offered : Ssh.Hostkey.pub; recorded : Ssh.Hostkey.pub list; } type auth_error = | No_identity of { files : string list; identities_only : bool } | Denied of { user : string; host : string; offered : string list; why : string; } type error = [ `Msg of string | `Host_key of host_key_error | `Auth of auth_error ] let pp_key ppf k = Fmt.pf ppf "%s %s" (Ssh.Hostkey.sshname k) (Ssh.Keys.fingerprint k) (* The key as a known_hosts line writes it after the host: type and base64. *) let key_line k = match String.split_on_char ' ' (String.trim (Ssh.Hostkey.openssh_of_pubkey k)) with | t :: b :: _ -> t ^ " " ^ b | _ -> Ssh.Hostkey.sshname k (* With no key recorded the refusal gives the known_hosts line that would trust the host; with another key recorded it names both fingerprints, as OpenSSH's "REMOTE HOST IDENTIFICATION HAS CHANGED" does. *) let pp_host_key_error ppf = function | Unknown_host { host; offered } -> Fmt.pf ppf "ssh: no host key is known for %s, which offered %a; if that is its \ key, add this line to ~/.ssh/known_hosts: %s %s" host pp_key offered host (key_line offered) | Changed_key { host; offered; recorded } -> Fmt.pf ppf "ssh: the host key of %s has changed: it offered %a, and known_hosts \ records %a; nothing was sent, since the server may not be the one you \ know" host pp_key offered Fmt.(list ~sep:(any ", ") pp_key) recorded (* [l] as a sentence lists it: "a, b or c". *) let pp_alternatives ppf l = match List.rev l with | [] -> () | [ x ] -> Fmt.string ppf x | last :: rest -> Fmt.pf ppf "%s or %s" (String.concat ", " (List.rev rest)) last (* OpenSSH's "Permission denied (publickey)", with the keys offered and the cure it asks of the user: a key the server knows, given to ssh. *) let pp_auth_error ppf = function | No_identity { files; identities_only = false } -> Fmt.pf ppf "ssh: no usable key in ssh-agent or at %a; add one with ssh-add" pp_alternatives files | No_identity { files; identities_only = true } -> Fmt.pf ppf "ssh: no usable key at %a (IdentitiesOnly is set); name your key with \ IdentityFile in ~/.ssh/config" pp_alternatives files | Denied { user; host; offered = []; why } -> Fmt.pf ppf "ssh: %s@%s: permission denied (%s)" user host why | Denied { user; host; offered; why } -> Fmt.pf ppf "ssh: %s@%s: permission denied for %s (%s); add the key the server \ knows with ssh-add" user host (String.concat ", " offered) why let pp_error ppf = function | `Msg m -> Fmt.string ppf m | `Host_key e -> pp_host_key_error ppf e | `Auth e -> pp_auth_error ppf e (* The system's words for a network failure, as strerror(3) gives them and OpenSSH prints them, from the error Eio raised. *) let system_reason = function | Eio_unix.Unix_error (code, _, _) -> Some (Unix.error_message code) | _ -> None let net_reason (e : Eio.Exn.err) = let backend b ~default = Option.value (system_reason b) ~default in String.uncapitalize_ascii (match e with | Eio.Net.E (Connection_failure (Refused b)) -> backend b ~default:"Connection refused" | Eio.Net.E (Connection_failure Timeout) -> "Operation timed out" | Eio.Net.E (Connection_reset b) -> backend b ~default:"Connection reset" | Eio.Net.E (Address_lookup_failed g) -> Eio.Net.Getaddrinfo_error.to_message g | Eio.Exn.X b | Eio.Fs.E (Already_exists b | Not_found b | Permission_denied b) -> backend b ~default:(Fmt.str "%a" Eio.Exn.pp_err e) | e -> Fmt.str "%a" Eio.Exn.pp_err e) (* A network failure as OpenSSH words it (ssh.c, sshconnect.c, packet.c): before the connection is made, the host that could not be resolved or the host and port that could not be reached; once made, the host and port that reset or failed it. *) let net_error ~connected ~host ~port (e : Eio.Exn.err) = match (connected, e) with | false, Eio.Net.E (Address_lookup_failed _) -> Fmt.error_msg "ssh: could not resolve hostname %s: %s" host (net_reason e) | false, _ -> Fmt.error_msg "ssh: connect to host %s port %d: %s" host port (net_reason e) | true, Eio.Net.E (Connection_reset _) -> Fmt.error_msg "ssh: connection reset by %s port %d" host port | true, _ -> Fmt.error_msg "ssh: connection to %s port %d: %s" host port (net_reason e) (* The names of the identities [credential] offers. *) let offered = function | `Identities ids -> List.map Ssh.Identity.name ids | `Pubkey _ | `Password _ -> [] (* ssh_config(5), StrictHostKeyChecking yes: the refusal of the host key [offered], which the authenticator does not accept. With no key recorded the host is unknown; with another one, its key has changed. *) let host_key_refusal ~host ~port authenticator offered = let host = known_hosts_name ~host ~port in match recorded authenticator with | [] -> Error (`Host_key (Unknown_host { host; offered })) | recorded -> Error (`Host_key (Changed_key { host; offered; recorded })) exception Connect_timed_out (* The TCP connection to [addr] within [connect_timeout] (ssh_config(5) ConnectTimeout), and what is left of it for the server's identification string, as ssh.c hands the rest of its timeout to the banner exchange. *) let tcp_connect ?connect_timeout ~sw ~net ~mono addr = match connect_timeout with | None -> (Eio.Net.connect ~sw net addr, None) | Some span -> ( let start = Eio.Time.Mono.now mono in match Eio.Fiber.first (fun () -> Some (Eio.Net.connect ~sw net addr)) (fun () -> Eio.Time.Mono.sleep_span mono span; None) with | None -> raise Connect_timed_out | Some flow -> let spent = Mtime.span start (Eio.Time.Mono.now mono) in let left = if Mtime.Span.compare spent span >= 0 then Mtime.Span.zero else Mtime.Span.abs_diff span spent in (flow, Some left)) (* Connect to [host] and authenticate [user] with [credential], on [sw]. Transport exceptions become errors, a network one in OpenSSH's words ({!net_error}); a host key the authenticator refuses is named ({!host_key_refusal}), an authentication the server ends without success is [`Auth], and a process with no random generator for the key exchange is told so rather than failing [sw]. *) let open_connection ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host = let refused = ref None in let observed = `Observed (authenticator, fun k ok -> if not ok then refused := Some k) in let failed fallback = match !refused with | Some k -> host_key_refusal ~host ~port authenticator k | None -> fallback () in let connected = ref false in try match Eio.Net.getaddrinfo_stream net host ~service:(string_of_int port) with | [] -> Fmt.error_msg "ssh: could not resolve hostname %s" host | addr :: _ -> let flow, banner = tcp_connect ?connect_timeout ~sw ~net ~mono addr in connected := true; Ok (Ssh_eio.Client.connect ~sw ~mono ?alive ?connect_timeout:banner flow ~authenticator:observed ~user credential) with | Ssh_eio.Userauth_failed why -> failed (fun () -> Error (`Auth (Denied { user; host; offered = offered credential; why }))) | Ssh_eio.Ssh_error msg -> failed (fun () -> Fmt.error_msg "ssh: %s" msg) | Connect_timed_out -> Fmt.error_msg "ssh: connect to host %s port %d: Operation timed out" host port | Crypto_rng.No_default_generator -> Fmt.error_msg "ssh: connection to %s port %d: this process installed no random \ generator for the key exchange (Crypto_rng_unix.use_default)" host port | Eio.Io (e, _) -> failed (fun () -> net_error ~connected:!connected ~host ~port e) module Connection = struct (* An authenticated connection, on a switch of its own that ends once the session is closed and its last channel is done. [connect] consumes the first channel's [`Established] event and keeps that channel open, so the connection stays up between commands: each command runs on a channel opened for it. A transport failure on a channel [broke] the session. *) type t = { client : Ssh_eio.Client.t; host : string; port : int; mutable channels : int; mutable closing : bool; mutable broken : bool; finished : unit Eio.Promise.t; finish : unit Eio.Promise.u; } let ended t = if t.closing && t.channels = 0 && not (Eio.Promise.is_resolved t.finished) then Eio.Promise.resolve t.finish () let close t = t.closing <- true; ended t let is_open t = (not t.closing) && (not t.broken) && not (Ssh_eio.Client.closed t.client) let connect ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ?(port = 22) ~user credential ~host () = with_operation ~operation:"connect" ~host ~path:"" @@ fun () -> let started, start = Eio.Promise.create () in let finished, finish = Eio.Promise.create () in let answer r = if not (Eio.Promise.is_resolved started) then Eio.Promise.resolve start r in (* Whatever ends the connection's fiber, its caller has an answer. *) let unmade () = answer (Fmt.error_msg "ssh: connection to %s port %d: ended before it was made" host port) in Eio.Fiber.fork_daemon ~sw (fun () -> Fun.protect ~finally:unmade (fun () -> Eio.Switch.run @@ fun sw -> match open_connection ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host with | Error _ as e -> answer e | Ok client -> answer (Ok { client; host; port; channels = 0; closing = false; broken = false; finished; finish; }); Eio.Promise.await finished); `Stop_daemon); Eio.Promise.await started (* Run [command] on a fresh channel of [t] and call [f ~sw client id], [sw] being the command's own switch, which bounds the channel's reader. Transport exceptions become errors and break the session, a network one in OpenSSH's words ({!net_error}). *) let on_channel ?(env = []) t ~command f = let broke r = t.broken <- true; r in if not (is_open t) then Fmt.error_msg "ssh: connection to %s port %d: closed" t.host t.port else begin t.channels <- t.channels + 1; Fun.protect ~finally:(fun () -> t.channels <- t.channels - 1; ended t) @@ fun () -> try Eio.Switch.run @@ fun sw -> let client = t.client in let id = Ssh_eio.Client.open_channel client in List.iter (fun v -> Ssh_eio.Client.request client ~id (Ssh.Message.Env v)) env; L.debug (fun m -> m "exec %s" command); Ssh_eio.Client.exec client ~id command; f ~sw client id with | Ssh_eio.Ssh_error msg -> broke (Fmt.error_msg "ssh: %s" msg) | Eio_net.Progress.Too_slow { limit; window } -> broke (Fmt.error_msg "ssh: connection to %s port %d: %a" t.host t.port Eio_net.Progress.pp_too_slow (limit, window)) | Eio.Io (e, _) -> broke (net_error ~connected:true ~host:t.host ~port:t.port e) end end (* [f s] on a session of its own, closed once [f] returns. *) let with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host f = match Connection.connect ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host () with | Error e -> Error (e :> [> error ]) | Ok s -> Fun.protect ~finally:(fun () -> Connection.close s) (fun () -> f s) (* A session's own failure, as one of {!error}. *) let session (r : ('a, [ `Msg of string ]) result) = (r :> ('a, error) result) (* The window-paced write of [body] on channel [id] and its flush, within [stall] when given: each piece the peer's window takes is a move, so a peer that stops taking data, whose window stays spent, ends the session even while its keepalives are answered. *) let piece = 32 * 1024 let send ?stall client id body = match stall with | None -> Ssh_eio.Client.write client ~id body; Ssh_eio.Client.flush client | Some p -> let n = String.length body in let rec go pos = if pos < n then begin let len = min piece (n - pos) in ignore (Eio_net.Progress.move p (fun () -> Ssh_eio.Client.write client ~id (String.sub body pos len); len) : int); go (pos + len) end in go 0; ignore (Eio_net.Progress.move p (fun () -> Ssh_eio.Client.flush client; 0) : int) (* The request [body] written slice by slice as it is read, so a pack goes out as it is made; then the end of the request, and the answer is read on the channel's reader. *) let streamed_send ?stall ~operation client id reader body = let rec go bytes = let s = Reader.read body in if Slice.is_eod s then bytes else begin send ?stall client id (Slice.to_string s); go (bytes + Slice.length s) end in let bytes = go 0 in emit_channel ~operation ~channel:id ~direction:"tx" ~bytes; Ssh_eio.Client.eof client ~id; Ssh_eio.Client.flush client; Ok reader (* [reader] bounded by what [budget] has left: a read past it raises [Wire_budget_exceeded], which {!bounded} names. *) let limit budget reader = match budget with | None -> reader | Some budget -> Reader.limit ~action:(fun _ _ -> raise Git.Store.Wire_budget_exceeded) (Git.Store.remaining_wire budget) reader (* [f ()], a session that reads at most what [budget] has left; a server that sends more is refused, naming that bound. *) let bounded ~host ~service budget f = let bound = Option.map Git.Store.remaining_wire budget in try f () with Git.Store.Wire_budget_exceeded -> Fmt.error_msg "ssh: %s on %s sent more than %d bytes, this session's bound" service host (Option.value bound ~default:0) (* gitprotocol-v2(5), "SSH and File Transport": over SSH a client asks for v2 with GIT_PROTOCOL, set by an env request (RFC 4254, 6.4) before the exec. *) let git_protocol_v2 = ("GIT_PROTOCOL", "version=2") (* A channel write, flushed so the server sees it before its reply is read. *) let channel_write ?stall ~operation client id body = emit_channel ~operation ~channel:id ~direction:"tx" ~bytes:(String.length body); send ?stall client id body (* [git-upload-pack ''] on session [s], asking for protocol v2, as one {!Git_eio.Fetch} session on the channel, [f ~explain channel]: the remote's stderr names a failure to read the server's first answer when it wrote one. *) let with_upload_pack ?budget ?stall ?on_progress ~operation (s : Connection.t) path f = let host = s.host in bounded ~host ~service:"git-upload-pack" budget @@ fun () -> with_operation ~operation ~host ~path @@ fun () -> Connection.on_channel ~env:[ git_protocol_v2 ] s ~command:(command "git-upload-pack" path) @@ fun ~sw client id -> session @@ let reader, _, remote_stderr, flush = channel_reader ?stall ?on_progress ~sw client id in let channel = { Git_eio.Fetch.write = channel_write ?stall ~operation client id; reader = limit budget reader; eof = (fun () -> Ssh_eio.Client.eof client ~id; Ssh_eio.Client.flush client); } in Fun.protect ~finally:(fun () -> flush (); close_client_channel client id) @@ fun () -> f ~explain:(explain remote_stderr) channel let session_fetch ?on_progress s ?depth ~dst ~ref_name path = with_upload_pack ?on_progress ~operation:"fetch" s path @@ fun ~explain channel -> Git_eio.Fetch.session_fetch ?on_progress ?depth ~explain ~ref_name channel dst let fetch ?alive ?connect_timeout ?on_progress ~sw ~net ~mono ~authenticator ?(port = 22) ?depth ~user credential ~host ~dst ~ref_name path = with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host @@ fun s -> session_fetch ?on_progress s ?depth ~dst ~ref_name path let fetch_refs ?budget ?prefixes ?alive ?connect_timeout ?stall ?on_progress ~sw ~net ~mono ~authenticator ?(port = 22) ~user credential ~host ~dst ~select path = with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host @@ fun s -> with_upload_pack ?budget ?stall ?on_progress ~operation:"fetch" s path @@ fun ~explain channel -> Git_eio.Fetch.session_fetch_refs ?budget ?on_progress ~explain ?prefixes ~select channel dst let ls_refs ?budget ?prefixes ?alive ?connect_timeout ?stall ~sw ~net ~mono ~authenticator ?(port = 22) ~user credential ~host path = with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host @@ fun s -> with_upload_pack ?budget ?stall ~operation:"ls-refs" s path @@ fun ~explain channel -> Git_eio.Fetch.session_ls_refs ~explain ?prefixes channel (* Run [git-receive-pack ''] on session [s], read the advertisement it streams back, and call [f ~client ~adv ~send] with a [send] over the same channel. The remote's stderr names a failure when it wrote one, and a non-zero exit status turns a success into a failure. *) let with_receive_pack ?budget ?stall ?on_progress ?(on_sent = ignore) (s : Connection.t) ~host_path f = bounded ~host:s.host ~service:"git-receive-pack" budget @@ fun () -> Connection.on_channel s ~command:(command "git-receive-pack" host_path) @@ fun ~sw client id -> let reader, exit_status, remote_stderr, flush = channel_reader ?stall ?on_progress ~sw client id in let reader = limit budget reader in match Git.Smart.Client.Push.advertisement Git.Smart.Client.Push.v reader with | Error (`Msg msg) -> remote_or_transport_error remote_stderr msg | Ok (push, adv) -> Fun.protect ~finally:(fun () -> flush (); close_client_channel client id) (fun () -> (* A remote that refuses the request while it is still going out closes the channel, and the next write fails on it: the side-band text of what it sent before the close, then its stderr, name why. *) match f ~client:push ~adv ~send:(fun body -> on_sent (); streamed_send ?stall ~operation:"push" client id reader body) with | exception Ssh_eio.Ssh_error msg -> let band = side_band_text reader in remote_or_transport_error ~band remote_stderr ("ssh: " ^ msg) | Error (`Msg msg) -> remote_or_transport_error remote_stderr msg | Error _ as e -> e | Ok _ as ok -> ok_or_remote_exit exit_status ok) (* The dual of {!fetch}: drive the transport-independent push negotiation over a [git-receive-pack] channel. *) let session_push ?on_progress (s : Connection.t) ~src ~src_hash ~dst_ref ~force ~host_path () = with_operation ~operation:"push" ~host:s.host ~path:host_path @@ fun () -> with_receive_pack ?on_progress s ~host_path @@ fun ~client ~adv ~send -> (Git_eio.Push.negotiate ?on_progress ~client ~adv ~src ~src_hash ~dst_ref ~force ~send () :> ( _, [ error | `Rejected of string * Git.Hash.t * Git.Hash.t | `Declined of string ] ) result) let push ?alive ?connect_timeout ?on_progress ~sw ~net ~mono ~authenticator ?(port = 22) ~user credential ~host ~src ~src_hash ~dst_ref ~force ~host_path () = with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host @@ fun s -> session_push ?on_progress s ~src ~src_hash ~dst_ref ~force ~host_path () (* A failure before the remote's advertisement is read, a connection, a session or the advertisement itself, sent nothing: the remote is unreachable for this push, as git push says "Could not read from remote repository" (connect.c). A refused host key stays its own error. *) let push_updates ?budget ?on_sent ?(require_atomic = false) ?alive ?connect_timeout ?stall ?on_progress ~sw ~net ~mono ~authenticator ?(port = 22) ~user credential ~host ~src ~host_path updates = with_operation ~operation:"push" ~host ~path:host_path @@ fun () -> let advertised = ref false in match with_session ?alive ?connect_timeout ~sw ~net ~mono ~authenticator ~port ~user credential ~host @@ fun s -> with_receive_pack ?budget ?stall ?on_progress ?on_sent s ~host_path @@ fun ~client ~adv ~send -> advertised := true; (Git_eio.Push.negotiate_updates ~require_atomic ?on_progress ~client ~adv ~src ~send updates :> ( _, [ Git_eio.Push.remote_update_error | `Host_key of host_key_error | `Auth of auth_error ] ) result) with | Error (`Msg m) when not !advertised -> Error (`Unreachable m) | Error ((`Host_key _ | `Auth _) as e) -> Error e | Error (#Git_eio.Push.remote_update_error as e) -> Error (e :> [ Git_eio.Push.remote_update_error | `Unreachable of string | `Host_key of host_key_error | `Auth of auth_error ]) | Ok refs -> Ok refs module Session = struct include Connection let fetch = session_fetch let push = session_push end (* {1 Reading the user's ~/.ssh, as OpenSSH does} *) type credential = [ `Pubkey of Ssh.Hostkey.priv | `Identities of Ssh.Identity.t list | `Password of string ] (* [Ok None] when the file is absent; a file that is there but cannot be read is an error naming it, never mistaken for an absent one. *) let load_file ((_, name) as path) = match Eio.Path.load path with | content -> Ok (Some content) | exception Eio.Io (Eio.Fs.E (Not_found _), _) -> Ok None | exception (Eio.Io _ as e) -> Fmt.error_msg "ssh: cannot read %s: %a" name Eio.Exn.pp e let home () = match Sys.getenv_opt "HOME" with | None | Some "" -> Fmt.error_msg "ssh: HOME is unset, so ~/.ssh cannot be found" | Some h -> Ok h let local_user () = match Sys.getenv_opt "USER" with | Some u when u <> "" -> u | _ -> ( match Sys.getenv_opt "LOGNAME" with Some u -> u | None -> "") (* ssh_config(5) "Include": a relative path is under ~/.ssh for the user file and /etc/ssh for the system one; a [*] or [?] in the last component names every matching file, in lexical order. *) let include_loader ~dir ~home arg = let path = if String.starts_with ~prefix:"~/" arg then Eio.Path.(home / String.sub arg 2 (String.length arg - 2)) else Eio.Path.(dir / arg) in match Eio.Path.split path with | Some (((_, parent_name) as parent), base) when String.exists (fun c -> c = '*' || c = '?') base -> ( match Eio.Path.read_dir parent with | exception Eio.Io (Eio.Fs.E (Not_found _), _) -> Ok [] | exception (Eio.Io _ as e) -> Fmt.error "cannot list %s: %a" parent_name Eio.Exn.pp e | names -> let names = List.sort String.compare (List.filter (fun n -> Ssh.Pattern.glob base n) names) in List.fold_left (fun acc n -> let* acc = acc in match load_file Eio.Path.(parent / n) with | Ok (Some c) -> Ok (acc @ [ c ]) | Ok None -> Ok acc | Error (`Msg m) -> Error m) (Ok []) names) | _ -> ( match load_file path with | Ok (Some c) -> Ok [ c ] | Ok None -> Ok [] | Error (`Msg m) -> Error m) (* The user's ~/.ssh/config, then /etc/ssh/ssh_config: the first value obtained wins (ssh_config(5)). *) let config_options ~fs ~home ~host = let home = Eio.Path.(fs / home) in let read ~dir ((_, name) as path) init = let* content = load_file path in match content with | None -> Ok init | Some c -> ( match Ssh.Config.parse ~include_:(include_loader ~dir ~home) c with | Error m -> Fmt.error_msg "ssh: %s: %s" name m | Ok t -> Ok (Ssh.Config.options ~init t ~host)) in let user = Eio.Path.(home / ".ssh") in let system = Eio.Path.(fs / "/etc/ssh") in let* o = read ~dir:user Eio.Path.(user / "config") Ssh.Config.empty in let* o = read ~dir:system Eio.Path.(system / "ssh_config") o in List.iter (fun line -> L.warn (fun m -> m "ssh config: %s is not evaluated; its block is not applied" line)) o.unsupported; Ok o type target = { host : string; port : int; user : string; credential : credential; authenticator : Ssh.Keys.authenticator; server_alive_interval : Mtime.Span.t option; server_alive_count_max : int option; connect_timeout : Mtime.Span.t option; } let expand tokens s = match Ssh.Config.expand tokens s with | Ok s -> Ok s | Error m -> Fmt.error_msg "ssh config: %s" m let rec expand_all tokens = function | [] -> Ok [] | s :: rest -> ( match expand tokens s with | Error _ as e -> e | Ok s -> Result.map (fun r -> s :: r) (expand_all tokens rest)) (* sshd(8) SSH_KNOWN_HOSTS FILE FORMAT: every file is read, user files then global ones, and a host's keys are those of all its entries; a @revoked entry in any file revokes the key in all. *) let known_hosts ~fs ~files ~name = let* entries = List.fold_left (fun acc path -> let* acc = acc in let* c = load_file Eio.Path.(fs / path) in match c with | None -> Ok acc | Some c -> Ok (acc @ Ssh.Known_hosts.parse c)) (Ok []) files in Ok (Ssh.Known_hosts.authenticator entries ~host:name) let default_user_known_hosts = [ "~/.ssh/known_hosts"; "~/.ssh/known_hosts2" ] let default_global_known_hosts = [ "/etc/ssh/ssh_known_hosts"; "/etc/ssh/ssh_known_hosts2" ] (* OpenSSH 10's default IdentityFile list; the types this client cannot use are passed over when read. *) let default_identity_files = [ "~/.ssh/id_rsa"; "~/.ssh/id_ecdsa"; "~/.ssh/id_ecdsa_sk"; "~/.ssh/id_ed25519"; "~/.ssh/id_ed25519_sk"; "~/.ssh/id_mldsa44_ed25519"; ] let known_hosts_authenticator ~fs ~host ?(port = 22) () = let* home = home () in let tokens = { Ssh.Config.home; local_user = local_user (); host; original_host = host; port; remote_user = ""; } in let* files = expand_all tokens (default_user_known_hosts @ default_global_known_hosts) in known_hosts ~fs ~files ~name:(known_hosts_name ~host ~port) (* Apply a fail-closed host-key policy to a known_hosts lookup: an unknown host ([None] from {!known_hosts_authenticator}) is refused unless the caller opts into [insecure], which downgrades to accepting any key. Refusing by default keeps a client from connecting to an unverified host it cannot authenticate -- the MITM opening. *) let host_authenticator ~insecure ~host = function | Some a -> Ok a | None -> if insecure then Ok `No_authentication else Fmt.error_msg "host %s is not in ~/.ssh/known_hosts; refusing to connect without \ host-key verification (pass --insecure-ssh-host-key to skip)" host (* The agent ssh_config(5) IdentityAgent names: "none" is no agent, "SSH_AUTH_SOCK" or no value is that variable, "$VAR" another variable, and anything else a path. *) let agent_path ~tokens = function | Some "none" -> Ok None | None | Some "SSH_AUTH_SOCK" -> ( match Sys.getenv_opt "SSH_AUTH_SOCK" with | None | Some "" -> Ok None | Some p -> Ok (Some p)) | Some v when String.length v > 1 && v.[0] = '$' -> ( let var = let v = String.sub v 1 (String.length v - 1) in if String.length v > 2 && v.[0] = '{' && v.[String.length v - 1] = '}' then String.sub v 1 (String.length v - 2) else v in match Sys.getenv_opt var with | None | Some "" -> Ok None | Some p -> Ok (Some p)) | Some v -> Result.map Option.some (expand tokens v) type key_file = | Plain of Ssh.Hostkey.priv | Locked of Ssh.Hostkey.pub (** encrypted; its public key is known *) | Unusable of string (** a type this client cannot use *) (* An identity file as OpenSSH reads it: the openssh-key-v1 format carries its public key in the clear even when the private half is encrypted; a PEM key that is encrypted needs its [.pub] beside it. *) let read_key_file ~fs path content = let pub_of_blob blob = match Ssh.Hostkey.pubkey_of_blob blob with | Ok pub -> Ok (Some pub) | Error _ -> Ok None in match Ssh.Hostkey.openssh_private_public content with | Ok (cipher, blob) -> ( let* pub = pub_of_blob blob in match pub with | None -> Ok (Unusable "its key type is not supported") | Some pub -> ( if cipher <> "none" then Ok (Locked pub) else match Ssh.Hostkey.privkey_of_openssh content with | Ok (priv, _) -> Ok (Plain priv) | Error m -> Fmt.error_msg "ssh: %s: %s" path m)) | Error _ -> ( let encrypted = let re = "ENCRYPTED" in let n = String.length re in let rec has i = i + n <= String.length content && (String.sub content i n = re || has (i + 1)) in has 0 in if encrypted then let* pub = load_file Eio.Path.(fs / (path ^ ".pub")) in match pub with | None -> Fmt.error_msg "ssh: %s is encrypted and %s.pub, which names its public key, is \ missing" path path | Some p -> ( match Ssh.Hostkey.pubkey_of_openssh (String.trim p) with | Ok pub -> Ok (Locked pub) | Error _ -> Ok (Unusable "its key type is not supported")) else match Ssh.Hostkey.privkey_of_pem content with | Ok priv -> Ok (Plain priv) | Error _ -> Ok (Unusable "it is not a key this client can read")) (* [path] as a user writes it: under [~] when it lies in [home]. *) let tilde ~home path = let prefix = home ^ "/" in match String.starts_with ~prefix path with | true -> "~/" ^ String.sub path (String.length prefix) (String.length path - String.length prefix) | false -> path let locked_fix path = Fmt.str "%s is encrypted and no ssh-agent holds it: add it to your agent with \ `ssh-add %s` (and start one with `eval $(ssh-agent)` if SSH_AUTH_SOCK is \ unset)" path path (* The agent's identities; an agent that cannot be reached is none, as for OpenSSH, which then goes on with the key files. *) let agent_identities ~net ~tokens (o : Ssh.Config.options) = let* path = agent_path ~tokens o.identity_agent in match path with | None -> Ok [] | Some path -> ( match Ssh_eio.Agent.identities ~net path with | Ok ids -> Ok ids | Error m -> L.warn (fun f -> f "%s" m); Ok []) (* The identity one key file gives: the agent's when it holds the key, else the file's own, named [name], and for an encrypted file a signer that refuses naming the file and the fix. *) let file_identity ~fs ~agent ~name path = let in_agent pub = List.find_opt (fun id -> Ssh.Hostkey.pub_eq (Ssh.Identity.pub id) pub) agent in let* content = load_file Eio.Path.(fs / path) in match content with | None -> Ok None | Some content -> ( let* key = read_key_file ~fs path content in match key with | Unusable why -> L.info (fun m -> m "ssh: %s is passed over: %s" path why); Ok None | Plain priv -> let pub = Ssh.Hostkey.pub_of_priv priv in Ok (Some (Option.value (in_agent pub) ~default:(Ssh.Identity.of_priv ~name priv))) | Locked pub -> let locked () = let fix = locked_fix name in Ssh.Identity.v ~name pub (fun _ _ -> Error fix) in Ok (Some (match in_agent pub with Some id -> id | None -> locked ()))) (* OpenSSH's order (sshconnect2.c pubkey_prepare): the configured files, each signed by the agent when it holds the key, then the agent's other keys unless IdentitiesOnly. An encrypted file the agent does not hold stays in its place and refuses to sign, naming the file and the fix, when the server accepts its key: OpenSSH would ask for the passphrase there. A file is named as the user writes it, under [~] ({!tilde}). *) let identities ~fs ~net ~(tokens : Ssh.Config.tokens) (o : Ssh.Config.options) = let* agent = agent_identities ~net ~tokens o in let files = match o.identity_files with [] -> default_identity_files | l -> l in let* files = expand_all tokens files in let* from_files = List.fold_left (fun acc path -> let* acc = acc in let name = tilde ~home:tokens.home path in let* id = file_identity ~fs ~agent ~name path in Ok (acc @ Option.to_list id)) (Ok []) files in let used id = List.exists (fun f -> Ssh.Hostkey.pub_eq (Ssh.Identity.pub f) (Ssh.Identity.pub id)) from_files in let only = o.identities_only = Some true in let rest = if only then [] else List.filter (fun id -> not (used id)) agent in match from_files @ rest with | [] -> let files = List.map (tilde ~home:tokens.home) files in Error (`Auth (No_identity { files; identities_only = only })) | ids -> Ok ids (* The host key authenticator for [hostname] on [port], from the known_hosts files the options name, or OpenSSH's defaults. *) let host_key_authenticator ~fs ~tokens ~hostname ~port (o : Ssh.Config.options) = let* user_files = expand_all tokens (Option.value o.user_known_hosts_files ~default:default_user_known_hosts) in let* global_files = expand_all tokens (Option.value o.global_known_hosts_files ~default:default_global_known_hosts) in let files = List.filter (fun f -> f <> "none") (user_files @ global_files) in let name = known_hosts_name ~host:(Option.value o.host_key_alias ~default:hostname) ~port in (* A host no file names accepts no key: the connection is refused when the server offers its own, naming it (with_command). *) let* auth = known_hosts ~fs ~files ~name in Ok (Option.value auth ~default:(`Any [])) let first_some a b = match a with Some _ -> a | None -> b let resolve ~fs ~net ?user ?port ~host () = let* home = home () in let* o = config_options ~fs ~home ~host in let local_user = local_user () in let base = { Ssh.Config.home; local_user; host; original_host = host; port = 22; remote_user = ""; } in let* hostname = match o.hostname with None -> Ok host | Some h -> expand base h in let port = Option.value (first_some port o.port) ~default:22 in let user = Option.value (first_some user o.user) ~default:local_user in let tokens = { base with host = hostname; port; remote_user = user } in let* authenticator = host_key_authenticator ~fs ~tokens ~hostname ~port o in let* ids = identities ~fs ~net ~tokens o in (* ssh_config(5): an interval or a ConnectTimeout of 0 is none. *) let seconds = function | Some n when n > 0 -> Some Mtime.Span.(n * s) | _ -> None in Ok { host = hostname; port; user; credential = `Identities ids; authenticator; server_alive_interval = seconds o.server_alive_interval; server_alive_count_max = o.server_alive_count_max; connect_timeout = seconds o.connect_timeout; } (** {1 Server: serve clone/fetch/push over SSH} The dual of {!fetch}: run an SSH server that, when a client execs [git-upload-pack ''] (or [git-receive-pack]), streams the advertisement on the channel, reads each request to its end as the protocol frames it, without waiting for the client to end its stream, then writes the {!Git_eio.Serve} response. *) (* A v0 upload-pack channel: the bytes received so far plus the multi-round server state machine they drive. All framing and protocol logic lives in {!Git.Smart.Server.Upload_pack}; this only feeds it bytes and writes back what it returns. *) type upload = { ubuf : Buffer.t; mutable ust : Git.Smart.Server.Upload_pack.t } (* A push request, read as receive-pack frames it ({!Git.Serve.Limits.frame}) by a fiber of its own: [data] carries each piece the client sends, [None] at the end of its stream, and [status] says whether the fiber needs more or has the whole request. The fiber runs only while the event loop waits on [status], so the session's state is only ever changed, and its bytes sent, by the loop. *) type receive = { data : string option Eio.Stream.t; status : [ `More | `Request of (string, [ `Msg of string ]) result ] Eio.Stream.t; } (* Per-channel state. [Upload] is the v0 fetch state machine; [Receive] reads a single push request; [V2] is the protocol-v2 command stream (several ls-refs / fetch commands on one channel). *) type chan_state = Upload of upload | Receive of receive | V2 of Buffer.t let start_receive ~sw ~limits = let data = Eio.Stream.create 1 and status = Eio.Stream.create 1 in let reader = Reader.make (fun () -> Eio.Stream.add status `More; match Eio.Stream.take data with | Some s -> Slice.of_string s | None -> Slice.eod) in Eio.Fiber.fork ~sw (fun () -> let r = Git.Serve.Limits.frame limits reader in Eio.Stream.add status (`Request r)); (* The fiber has stopped at its first read. *) ignore (Eio.Stream.take status); { data; status } (* Give the request's fiber [piece] ([None] at the end of the stream) and wait until it needs more or has the whole request. *) let feed r piece = Eio.Stream.add r.data piece; Eio.Stream.take r.status (* Does the client's GIT_PROTOCOL env request protocol v2? git sets it to e.g. "version=2" before the git-upload-pack exec. *) let wants_v2 env = match Hashtbl.find_opt env "GIT_PROTOCOL" with | Some v -> List.exists (fun s -> String.trim s = "version=2") (String.split_on_char ':' v) | None -> false (* eof + exit-status 0 + close: a git client over ssh treats a channel that ends without an exit-status as a transport error, even after a complete response. *) let close_chan t chans chan = Ssh_eio.Server.eof t chan; Ssh_eio.Server.exit_status t chan 0l; Ssh_eio.Server.close t chan; Hashtbl.remove chans chan (* A command that cannot start, as git's upload-pack and receive-pack die before their advertisement: the channel closed with exit status 128. *) let fail_chan t chans chan m = L.warn (fun f -> f "ssh: %s" m); Ssh_eio.Server.eof t chan; Ssh_eio.Server.exit_status t chan 128l; Ssh_eio.Server.close t chan; Hashtbl.remove chans chan (* A push request read whole is answered, then the channel closed; one that cannot be read whole is closed unanswered. *) let respond_receive ?context ~limits t chans repo chan = function | Error (`Msg m) -> L.warn (fun f -> f "ssh receive-pack: %s" m); close_chan t chans chan | Ok request -> ( match Git_eio.Serve.receive_pack ?context ~limits repo (Reader.of_string request) with | Ok r -> emit_channel ~operation:"serve_receive_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length r); (* A push that asked for no report-status is answered nothing. *) if r <> "" then Ssh_eio.Server.send t chan r; close_chan t chans chan | Error (`Msg m) -> L.warn (fun f -> f "ssh receive-pack: %s" m); close_chan t chans chan) let consume_upload_buffer u consumed = let s = Buffer.contents u.ubuf in Buffer.clear u.ubuf; Buffer.add_string u.ubuf (String.sub s consumed (String.length s - consumed)) let emit_upload_request_event st = function | Git.Smart.Server.Upload_pack.Wants _ -> Git.Smart.Event.emit_probe (Wanted { wants = 1; haves = 0 }) | Haves _ -> let commons = Git.Smart.Server.Upload_pack.commons st in Git.Smart.Event.emit_probe (Round { commons = List.length commons; ready = commons <> [] }) let send_upload_pack repo send fail chan st ~commons ~wants = let answer = Result.bind (Git.Smart.Server.Upload_pack.respond st) @@ fun (_, head, packfile) -> Git_eio.Serve.answer repo { Git.Serve.head; packfile; haves = commons; wants } in match answer with | Error (`Msg m) -> fail m | Ok resp -> emit_channel ~operation:"serve_upload_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length resp); send resp (* v0 upload-pack: feed buffered bytes to the multi-round server state machine one complete request at a time, writing back each round's reply, until [done] yields the pack -- then respond and close. Real git keeps the channel open waiting for the pack, so we never wait for its EOF. All framing and protocol decisions are {!Git.Smart.Server.Upload_pack}'s; this loop only shuttles bytes and asks {!Git_eio.Serve.answer} for the response the machine agreed on. *) let drive_upload t chans repo chan u = let send = Ssh_eio.Server.send t chan in let fail m = L.warn (fun f -> f "ssh upload-pack: %s" m); close_chan t chans chan in let rec loop () = match Git.Smart.Server.Upload_pack.frame u.ust (Buffer.contents u.ubuf) with | Error (`Msg m) -> fail m | Ok None -> () | Ok (Some (request, consumed)) -> ( consume_upload_buffer u consumed; match Git.Smart.Server.Upload_pack.handle ~has:(Git_eio.Repository.exists repo) u.ust request with | Error (`Msg m) -> fail m | Ok (st, action) -> ( u.ust <- st; emit_upload_request_event st request; match action with | `Idle -> loop () | `Reply bytes -> emit_channel ~operation:"serve_upload_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length bytes); send bytes; loop () | `Build_pack (commons, wants) -> send_upload_pack repo send fail chan st ~commons ~wants; close_chan t chans chan)) in loop () (* v2: respond to each complete command request as it arrives, leaving the channel open for the next command; the client closes when done. *) let drain_v2 ~on_request t chans repo chan b = let rec loop () = let s = Buffer.contents b in match Git.Smart.Message.V2.request_end s with | None -> if String.length s > Git.Smart.Message.V2.max_request then close_chan t chans chan | Some off -> let req = String.sub s 0 off in let rest = String.sub s off (String.length s - off) in Buffer.clear b; Buffer.add_string b rest; (match Git.Smart.Message.V2.read_request (Reader.of_string req) with | Ok (Some r) -> on_request r.command | Ok None | Error _ -> ()); (match Git_eio.Serve.v2_serve repo (Reader.of_string req) with | Ok r -> emit_channel ~operation:"serve_upload_pack_v2" ~channel:chan ~direction:"tx" ~bytes:(String.length r); Ssh_eio.Server.send t chan r | Error (`Msg m) -> L.warn (fun f -> f "ssh v2: %s" m)); loop () in loop () (* Dispatch one git-upload-pack / git-receive-pack exec, choosing v0 or v2: v2 when the client asked for it and the server passes GIT_PROTOCOL to the command, as sshd does whose AcceptEnv names it. *) let exec ~sw ~limits ~accept_git_protocol t chans env repo chan cmd = let send = Ssh_eio.Server.send t chan in if String.starts_with ~prefix:"git-upload-pack" cmd then ( if accept_git_protocol && wants_v2 env then ( (* v2: advertise capabilities (no service announce over SSH). *) let adv = Git_eio.Serve.v2_advertise repo in emit_channel ~operation:"serve_upload_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length adv); send adv; Hashtbl.replace chans chan (V2 (Buffer.create 256))) else match Git_eio.Serve.advertise repo with | Error (`Msg m) -> fail_chan t chans chan ("upload-pack: " ^ m) | Ok adv -> emit_channel ~operation:"serve_upload_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length adv); send adv; Hashtbl.replace chans chan (Upload { ubuf = Buffer.create 256; ust = Git.Smart.Server.Upload_pack.v; })) else if String.starts_with ~prefix:"git-receive-pack" cmd then ( match Git_eio.Serve.advertise ~receive:true repo with | Error (`Msg m) -> fail_chan t chans chan ("receive-pack: " ^ m) | Ok adv -> emit_channel ~operation:"serve_receive_pack" ~channel:chan ~direction:"tx" ~bytes:(String.length adv); send adv; Hashtbl.replace chans chan (Receive (start_receive ~sw ~limits))) else L.warn (fun f -> f "ssh: unsupported command %S" cmd) let serve_connection ?context ?(limits = Git.Serve.Limits.default) ?(on_exec = ignore) ?(on_request = ignore) ?(accept_git_protocol = true) ?head ~mono ~host_key ~authenticate repo flow = with_operation ~operation:"serve" ~host:"" ~path:"" @@ fun () -> Eio.Switch.run @@ fun sw -> let chans : (int32, chan_state) Hashtbl.t = Hashtbl.create 4 in (* Environment variables the client set on the channel before its exec. *) let env : (string, string) Hashtbl.t = Hashtbl.create 4 in let on_event t ev = match ev with | Ssh.Server.Set_env (_, (k, v)) -> Hashtbl.replace env k v | Ssh.Server.Channel_exec (chan, cmd) -> on_exec cmd; exec ~sw ~limits ~accept_git_protocol t chans env repo chan (String.trim cmd) | Ssh.Server.Channel_data (chan, data) -> ( emit_channel ~operation:"serve" ~channel:chan ~direction:"rx" ~bytes:(String.length data); match Hashtbl.find_opt chans chan with | Some (Upload u) -> Buffer.add_string u.ubuf data; drive_upload t chans repo chan u | Some (V2 b) -> Buffer.add_string b data; drain_v2 ~on_request t chans repo chan b | Some (Receive r) when data <> "" -> ( match feed r (Some data) with | `More -> () | `Request req -> respond_receive ?context ~limits t chans repo chan req) | Some (Receive _) | None -> ()) | Ssh.Server.Channel_eof chan -> ( match Hashtbl.find_opt chans chan with (* Upload responds and closes itself on [done]; v2 is answered per command; a push request is answered once whole, so a stream that ends first ends an incomplete one. *) | Some (Upload _ | V2 _) -> close_chan t chans chan | Some (Receive r) -> ( match feed r None with | `More -> close_chan t chans chan | `Request req -> respond_receive ?context ~limits t chans repo chan req) | None -> ()) | _ -> () in Ssh_eio.Server.serve ?head ~mono flow ~host_key ~authenticate ~on_event; (* A connection that ends with a request unread ends its fiber. *) Hashtbl.iter (fun _ -> function Receive r -> ignore (feed r None) | _ -> ()) chans let serve ?context ?limits ?on_exec ?on_request ?accept_git_protocol ?(on_listen = ignore) ~max_connections ~sw ~net ~mono ~host_key ~authenticate ~addr repo = let sock = Eio.Net.listen ~sw ~backlog:8 ~reuse_addr:true net addr in on_listen (Eio.Net.listening_addr sock); Eio_net_accept.run ~max_connections ~on_error:(fun ex -> L.warn (fun f -> f "ssh: %s" (Printexc.to_string ex))) sock (fun head flow _addr -> serve_connection ?context ?limits ?on_exec ?on_request ?accept_git_protocol ~head ~mono ~host_key ~authenticate repo flow)