(* 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. *) (** Git smart-protocol fetch over SSH. The transport opens a session, asks for protocol v2 as git does over SSH ({{:https://git-scm.com/docs/gitprotocol-v2}gitprotocol-v2(5)}, "SSH and File Transport": [GIT_PROTOCOL=version=2] in an env request before the exec), runs [git-upload-pack ''] on the remote, and lists and fetches with the v2 commands ls-refs and fetch of a server that answers v2, and in protocol v0 with {!Git_eio.Fetch.negotiate} from one that answers v0 or v1, as an OpenSSH server does whose [AcceptEnv] does not name the variable. There is no [# service=] line: the greeting arrives as the command starts. The path is quoted as Git quotes it (sq_quote_buf): in single quotes, each ['] as ['\''] and each [!] as ['\!'], so the server's shell reads it back as one argument. An RNG must be installed first. *) type credential = [ `Pubkey of Ssh.Hostkey.priv | `Identities of Ssh.Identity.t list | `Password of string ] (** The type for how a user authenticates: one private key, identities offered in turn ({!Ssh.Client.v}), or a password. *) (** The type for host keys refused as [StrictHostKeyChecking yes] refuses them (ssh_config(5)), before anything is sent. Each names the host as known_hosts records it: its name, or ["[name]:port"] for another port than 22. *) type host_key_error = | Unknown_host of { host : string; offered : Ssh.Hostkey.pub } (** No key is recorded for [host], which offered [offered]. *) | Changed_key of { host : string; offered : Ssh.Hostkey.pub; recorded : Ssh.Hostkey.pub list; } (** [host] offered [offered], and the keys recorded for it are [recorded]. *) val pp_host_key_error : host_key_error Fmt.t (** [pp_host_key_error] formats the refusal as a sentence. For an unknown host it names the key type and fingerprint offered and the known_hosts line that would trust it; for a changed key, both fingerprints. *) (** The type for authentications that cannot succeed, as OpenSSH's "Permission denied (publickey)" is: each is the user's to fix by giving ssh a key the server knows. A file is named as the user writes it, under [~] when it lies in the home directory. *) type auth_error = | No_identity of { files : string list; identities_only : bool } (** No ssh-agent key, and none of the identity files [files] is a key this client can use; [identities_only] is [IdentitiesOnly yes], which keeps the agent's other keys from being offered. *) | Denied of { user : string; host : string; offered : string list; why : string; } (** [host] ended [user]'s authentication without accepting any of the identities [offered], by name, for the client's reason [why]. *) val pp_auth_error : auth_error Fmt.t (** [pp_auth_error] formats the refusal as a sentence naming the files read or the keys offered, and how to give ssh a key: [ssh-add], or under [IdentitiesOnly] an [IdentityFile] line in [~/.ssh/config]. *) type error = [ `Msg of string | `Host_key of host_key_error | `Auth of auth_error ] (** The type for errors of a session: a refused host key, an authentication the server ended without success, or why the session failed. A network failure is worded as OpenSSH words it: the host that could not be resolved, the host and port that could not be reached with the system's reason (["ssh: connect to host H port P: connection refused"]), or the host and port that reset the connection. Each session below takes [?alive] and [?connect_timeout] (default: none), ssh_config(5)'s [ServerAliveInterval] and [ServerAliveCountMax], and [ConnectTimeout], with OpenSSH's meanings: the connect bound covers the TCP connection, ["ssh: connect to host H port P: Operation timed out"], and what is left of it the server's identification string; with [alive], a server that stops answering ends the session ({!Ssh_eio.Client.connect}), its error ["ssh: "] and the reason. {!ls_refs}, {!fetch_refs} and {!push_updates} also take [?stall], a stall watchdog: the channel's reads and writes are moves of it ({!Eio_net.Progress}), so a server that answers keepalives while its command sends and takes nothing ends the session with ["ssh: connection to H port P: "] and curl's words for the low speed. {!fetch}, {!fetch_refs}, {!push} and {!push_updates} also take [?on_progress], a display feed that bounds nothing: it is told what the transfer moves ({!Git.Progress.event}), as {!Git_eio.Fetch.negotiate} and {!Git_eio.Push.negotiate} tell it, and each line the remote writes on its standard error ({!Git.Progress.Remote}). *) val pp_error : error Fmt.t (** [pp_error] formats an error as a sentence. *) val fetch : ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> ?on_progress:(Git.Progress.event -> unit) -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> ?depth:int -> user:string -> credential -> host:string -> dst:Git_eio.Repository.t -> ref_name:string -> string -> (Git.Hash.t, error) result (** [fetch ~sw ~net ~mono ~authenticator ?port ?depth ~user credential ~host ~dst ~ref_name path] connects to [host] on [port] (defaults to [22]), checks the host key with [authenticator], authenticates [user] with [credential], runs [git-upload-pack ''] and imports [ref_name] into [dst], with [FETCH_HEAD] and the remote-tracking ref, and is the fetched object. [depth] limits the history to that many commits. It asks for protocol v2 ({!Git_eio.Fetch.negotiate_v2}), and fetches in multi-round v0 from a server that answers v0 ({!Git_eio.Fetch.negotiate_stateful}). A host key [authenticator] does not accept is [`Host_key]. *) val push : ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> ?on_progress:(Git.Progress.event -> unit) -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> user:string -> credential -> host:string -> src:Git_eio.Repository.t -> src_hash:string -> dst_ref:string -> force:bool -> host_path:string -> unit -> ( Git.Hash.t * Git_eio.Push.pushed, [ error | `Rejected of string * Git.Hash.t * Git.Hash.t | `Declined of string ] ) result (** [push ~sw ~net ~mono ~authenticator ?port ~user credential ~host ~src ~src_hash ~dst_ref ~force ~host_path ()] pushes [src_hash] from [src] to the repository at [host_path] on [host] over SSH. It connects and authenticates as {!fetch} does, runs [git-receive-pack ''], reads the advertisement and pushes with {!Git_eio.Push.negotiate}: without [force], a push that would drop the remote's commits is refused before anything is sent. *) val push_updates : ?budget:Git.Store.pack_budget -> ?on_sent:(unit -> unit) -> ?require_atomic:bool -> ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> ?stall:Eio_net.Progress.t -> ?on_progress:(Git.Progress.event -> unit) -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> user:string -> credential -> host:string -> src:Git_eio.Repository.t -> host_path:string -> Git_eio.Push.update list -> ( string list, [ Git_eio.Push.remote_update_error | `Unreachable of string | `Host_key of host_key_error | `Auth of auth_error ] ) result (** [push_updates ~sw ~net ~mono ~authenticator ?port ~user credential ~host ~src ~host_path updates] applies [updates] to the repository at [host_path] on [host] in one [git-receive-pack] request, connecting as {!push} does, and is the refs it changed ({!Git_eio.Push.negotiate_updates}). [require_atomic] forwards its required capability and exact guard semantics. [budget] bounds the bytes the session reads, the advertisement and the status report: a server that sends more is refused, naming the bound. [on_sent] (default nothing) is called when the request starts to go out: an error after it, such as a status report past the bound or a dropped connection, leaves unknown whether the server took the push. A host key [authenticator] does not accept is [`Host_key], an authentication the server ends without success [`Auth]; any other failure before the remote advertised its refs, a connection, a session the remote ended or an advertisement past the bound, is [Error (`Unreachable why)]: nothing was sent. *) val fetch_refs : ?budget:Git.Store.pack_budget -> ?prefixes:string list -> ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> ?stall:Eio_net.Progress.t -> ?on_progress:(Git.Progress.event -> unit) -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> user:string -> credential -> host:string -> dst:Git_eio.Repository.t -> select:(string -> string option) -> string -> ((string * Git.Hash.t) list, error) result (** [fetch_refs ?budget ~sw ~net ~mono ~authenticator ?port ~user credential ~host ~dst ~select path] fetches into [dst], in one [git-upload-pack] request, the objects of each ref [r] of the repository at [path] on [host] for which [select r] is [Some l], and is each such [(l, value)] ({!Git_eio.Fetch.negotiate_refs_v2}, or {!Git_eio.Fetch.negotiate_refs} for a server that answers v0). It writes no ref of [dst]. [budget] bounds the advertisement, wire response, pack and decoded objects; a server that sends more bytes than it allows is refused, naming the bound. A v2 server lists only the refs starting with one of [prefixes], when given ({!Git_eio.Fetch.ls_refs_v2}). *) val ls_refs : ?budget:Git.Store.pack_budget -> ?prefixes:string list -> ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> ?stall:Eio_net.Progress.t -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> user:string -> credential -> host:string -> string -> (Git.Smart.Message.Advertisement.t, error) result (** [ls_refs ~sw ~net ~mono ~authenticator ?port ~user credential ~host path] is the advertisement of the repository at [path] on [host], as [git ls-remote] reads it: every ref with its value, and the capabilities, among them HEAD's [symref=HEAD:refs/heads/B]. It connects as {!fetch} does, runs [git-upload-pack ''], reads the ls-refs answer of a server that answers v2 ({!Git.Smart.Message.V2.advertisement}) or the advertisement of one that answers v0, and ends the session with a flush-pkt, so nothing is fetched. [budget] bounds the bytes the session reads: a server that sends more is refused, naming the bound. A v2 server lists only the refs starting with one of [prefixes], when given ({!Git_eio.Fetch.ls_refs_v2}). *) (** {1:sessions Sessions} A session is one authenticated connection that carries a channel per command, as OpenSSH's ControlMaster gives git: the handshake and the authentication are paid once for every command a client runs on one host. The functions above run their command on a session of their own. *) module Session : sig type t (** The type for sessions. *) val connect : ?alive:Ssh_eio.Client.alive -> ?connect_timeout:Mtime.Span.t -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> authenticator:Ssh.Keys.authenticator -> ?port:int -> user:string -> credential -> host:string -> unit -> (t, error) result (** [connect ~sw ~net ~mono ~authenticator ?port ~user credential ~host ()] connects to [host] on [port] (defaults to [22]), checks its host key with [authenticator] and authenticates [user] with [credential], with the errors of {!fetch}. The connection lives until {!close} or the end of [sw]; each connection made is a [git.ssh.operation] span whose operation is [connect]. *) val close : t -> unit (** [close t] ends the connection once the commands running on it are done. No command starts on it after. *) val is_open : t -> bool (** [is_open t] is [true] until [t] is closed, its connection ends, or a command on it fails in its transport, such as a dropped connection or a channel the server refuses: a command that failed on a session that is no longer open may succeed on a new one. *) val fetch : ?on_progress:(Git.Progress.event -> unit) -> t -> ?depth:int -> dst:Git_eio.Repository.t -> ref_name:string -> string -> (Git.Hash.t, error) result (** [fetch t ~dst ~ref_name path] is {!val-fetch} on a channel of [t]. *) val push : ?on_progress:(Git.Progress.event -> unit) -> t -> src:Git_eio.Repository.t -> src_hash:string -> dst_ref:string -> force:bool -> host_path:string -> unit -> ( Git.Hash.t * Git_eio.Push.pushed, [ error | `Rejected of string * Git.Hash.t * Git.Hash.t | `Declined of string ] ) result (** [push t ~src ~src_hash ~dst_ref ~force ~host_path ()] is {!val-push} on a channel of [t]. Commands on one session run at once, each on its own channel. *) end (** {1:ssh_dir The user's [~/.ssh]} *) val known_hosts_authenticator : fs:Eio.Fs.dir_ty Eio.Path.t -> host:string -> ?port:int -> unit -> (Ssh.Keys.authenticator option, [ `Msg of string ]) result (** [known_hosts_authenticator ~fs ~host ?port ()] is an authenticator that accepts exactly the host keys of [host], or ["[host]:port"] for another port than 22, in OpenSSH's default files: [~/.ssh/known_hosts], [~/.ssh/known_hosts2], [/etc/ssh/ssh_known_hosts] and [/etc/ssh/ssh_known_hosts2], plain or hashed, read with {!Ssh.Known_hosts}. This is [Ok None] if no entry names [host], and [Error] naming a file that is there but cannot be read, or if [HOME] is unset. *) val host_authenticator : insecure:bool -> host:string -> Ssh.Keys.authenticator option -> (Ssh.Keys.authenticator, [ `Msg of string ]) result (** [host_authenticator ~insecure ~host known] is [Ok a] if [known] is [Some a], [Ok `No_authentication] if [known] is [None] and [insecure] is [true], and [Error] otherwise. *) type target = { host : string; (** The host to connect to, after [HostName]. *) port : int; user : string; credential : credential; authenticator : Ssh.Keys.authenticator; server_alive_interval : Mtime.Span.t option; (** [ServerAliveInterval], [None] when unset or [0]. *) server_alive_count_max : int option; (** [ServerAliveCountMax]. *) connect_timeout : Mtime.Span.t option; (** [ConnectTimeout], [None] when unset or [0]. *) } (** How to reach and authenticate to a host, as OpenSSH would. *) val resolve : fs:Eio.Fs.dir_ty Eio.Path.t -> net:_ Eio.Net.t -> ?user:string -> ?port:int -> host:string -> unit -> (target, [ `Msg of string | `Auth of auth_error ]) result (** [resolve ~fs ~net ?user ?port ~host ()] reads, as OpenSSH's client does: - [~/.ssh/config] then [/etc/ssh/ssh_config] ({!Ssh.Config}) for [host]: [HostName], [User], [Port], [IdentityFile], [IdentitiesOnly], [IdentityAgent], [UserKnownHostsFile], [GlobalKnownHostsFile], [HostKeyAlias], [ServerAliveInterval], [ServerAliveCountMax] and [ConnectTimeout]. [user] and [port], when given, win over the files. - The known_hosts files, [~/.ssh/known_hosts] and [~/.ssh/known_hosts2] then [/etc/ssh/ssh_known_hosts] and [/etc/ssh/ssh_known_hosts2] unless configured, for the host after [HostName] (or [HostKeyAlias]). A host none of them names accepts no key, as [StrictHostKeyChecking yes] does: a session is refused once the server offers its key, as {!constructor-Unknown_host}, and a host whose recorded key is not the one offered as {!constructor-Changed_key}. - The identities: each configured [IdentityFile] (OpenSSH's default list when none is), signed by the agent at [SSH_AUTH_SOCK] (or [IdentityAgent]) when it holds the key, then the agent's other keys unless [IdentitiesOnly]. An encrypted file the agent does not hold is offered by its public key and, when the server accepts it, refuses to sign with an error naming the file and [ssh-add]. Key types this client cannot use are passed over. With no identity left, this is [`Auth (No_identity _)]. A file that is there but cannot be read is an error naming it. *) (** {1:server Server} *) val serve_connection : ?context:Git_eio.Repository.ref_context -> ?limits:Git.Serve.Limits.t -> ?on_exec:(string -> unit) -> ?on_request:(string -> unit) -> ?accept_git_protocol:bool -> ?head:Eio_net_accept.head -> mono:_ Eio.Time.Mono.t -> host_key:Ssh.Hostkey.priv -> authenticate:(string -> Ssh.Server.userauth -> bool) -> Git_eio.Repository.t -> _ Eio.Flow.two_way -> unit (** [serve_connection ~mono ~host_key ~authenticate repo flow] serves one SSH connection on [flow]. For a [git-upload-pack] or [git-receive-pack] command it sends the advertisement, reads the request to its end as the protocol frames it, a push's with {!Git.Serve.Limits.frame}, so the client need not end the channel, and writes the {!Git_eio.Serve} response. [authenticate user cred] decides user authentication. [on_exec] (default nothing) is given each command a client runs, as it arrives, and [on_request] (default nothing) the name of each protocol v2 command, such as ls-refs or fetch. A client that sets [GIT_PROTOCOL] to [version=2] is answered in protocol v2 when [accept_git_protocol] is [true] (the default), and in v0 otherwise, as by an OpenSSH server whose [AcceptEnv] does not name the variable. [head] is the connection's head in the {!Eio_net_accept.run} loop serving it ({!Ssh_eio.Server.serve}). The [limits] default to {!Git.Serve.Limits.default}; request framing and pack indexing use the same receive bounds. *) val serve : ?context:Git_eio.Repository.ref_context -> ?limits:Git.Serve.Limits.t -> ?on_exec:(string -> unit) -> ?on_request:(string -> unit) -> ?accept_git_protocol:bool -> ?on_listen:(Eio.Net.Sockaddr.stream -> unit) -> max_connections:int -> sw:Eio.Switch.t -> net:_ Eio.Net.t -> mono:_ Eio.Time.Mono.t -> host_key:Ssh.Hostkey.priv -> authenticate:(string -> Ssh.Server.userauth -> bool) -> addr:Eio.Net.Sockaddr.stream -> Git_eio.Repository.t -> unit (** [serve ~max_connections ~sw ~net ~mono ~host_key ~authenticate ~addr repo] listens on [addr] and serves each accepted SSH connection with {!serve_connection} on {!Eio_net_accept.run}, at most [max_connections] at once, until [sw] is cancelled. Under pressure it sheds the connection whose handshake is not authenticated and has made the least progress; an aborted accept, or one with no descriptor left, leaves it serving. [on_listen] is called once with the address the listener is bound to, after the bind and before the first connection is accepted: with port [0] in [addr] it carries the port the system chose. Default: nothing. An RNG must be installed first, for example with [Crypto_rng_unix.use_default ()]. *)