(* 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. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (** Native git fetch, functored over a {!Store.S}. The object-graph walk and the protocol drivers are I/O-free; the transport (HTTP/SSH) only moves bytes. *) module Hash = Object_hash let src = Logs.Src.create "git.fetch" ~doc:"Git fetch operations" module L = (val Logs.src_log src : Logs.LOG) let err_msgf fmt = Fmt.kstr (fun s -> Error (`Msg s)) fmt exception Invalid_closure of string let fail_closure fmt = Fmt.kstr (fun s -> raise (Invalid_closure s)) fmt let read_closure_value ~read hash expected_kind = let value = match read hash with | Ok value -> value | Error (`Msg message) -> fail_closure "cannot read object %a: %s" Hash.pp hash message in if Value.kind value <> expected_kind then fail_closure "object %a has unexpected kind" Hash.pp hash; if not (Hash.equal (Value.digest value) hash) then fail_closure "object %a has incorrect digest" Hash.pp hash; value let push_closure_children push = function | Value.Commit commit -> List.iter (fun parent -> push parent `Commit) (Commit.parents commit); push (Commit.tree commit) `Tree | Value.Tree tree -> Tree.iter (fun (entry : Tree.entry) -> match entry.perm with | `Dir -> push entry.hash `Tree | `Normal | `Everybody | `Exec | `Link -> push entry.hash `Blob | `Commit -> ()) tree | Value.Blob _ -> () | Value.Tag _ -> assert false let visit_closure ~read ~seen ~pending ~total_bytes ~max_objects ~max_bytes hash expected_kind = match Hashtbl.find_opt seen hash with | Some kind when kind <> expected_kind -> fail_closure "object %a is referenced with conflicting kinds" Hash.pp hash | Some _ -> () | None -> if Hashtbl.length seen >= max_objects then raise (Invalid_closure "git closure object count exceeds bound"); let value = read_closure_value ~read:(read (max_bytes - !total_bytes)) hash expected_kind in let size = Value.length value in if size > max_bytes - !total_bytes then raise (Invalid_closure "git closure decoded bytes exceed bound"); total_bytes := !total_bytes + size; Hashtbl.add seen hash expected_kind; Stack.push (hash, expected_kind, true) pending; let push hash kind = Stack.push (hash, kind, false) pending in push_closure_children push value let validate_roots ~read ~max_objects ~max_bytes roots = if max_objects <= 0 || max_bytes < 0 then err_msgf "git closure validation requires positive object and byte bounds" else try let seen = Hashtbl.create 1024 in let pending = Stack.create () in let result = ref [] in let total_bytes = ref 0 in List.iter (fun (root, kind) -> Stack.push (root, kind, false) pending) (List.rev roots); while not (Stack.is_empty pending) do let hash, expected_kind, expanded = Stack.pop pending in if expanded then result := hash :: !result else visit_closure ~read ~seen ~pending ~total_bytes ~max_objects ~max_bytes hash expected_kind done; Ok (List.rev !result) with Invalid_closure message -> Error (`Msg message) let validate_closure ~read ~max_objects ~max_bytes root = validate_roots ~read:(fun _ -> read) ~max_objects ~max_bytes [ (root, `Commit) ] let validate_trees ~read ~max_objects ~max_bytes roots = validate_roots ~read:(fun _ -> read) ~max_objects ~max_bytes (List.map (fun root -> (root, `Tree)) roots) let validate_trees_bounded ~read ~max_objects ~max_bytes roots = validate_roots ~read:(fun remaining -> read ~max_bytes:remaining) ~max_objects ~max_bytes (List.map (fun root -> (root, `Tree)) roots) (** {1 URL parsing} *) let parse_url s = match Uri.of_string s with | `File path -> `File path | `Ssh _ | `Git _ -> `Other s | `Url url -> `Other url (** {1 Pure object-graph walk} *) exception Unreadable_object of Hash.t * string exception Over_budget of string (* The path of the entry [name] of the tree at [dir]: the root tree is at [""], as git's rev-list --objects names it. *) let entry_path dir name = if dir = "" then name else dir ^ "/" ^ name (* The children of [value], reached at [path], each with how it is handled: [`Read] objects and a commit's [`Parent]s are read to find theirs; blobs, known by their tree-entry mode, have none. A commit's tree is at [""], and a commit or a tag reaches its other targets by no path. Submodule gitlinks point outside this repository and are skipped. *) let named_children ~shallow h path = function | Value.Blob _ -> [] | Value.Commit c when shallow h -> [ (Commit.tree c, Some "", `Read) ] | Value.Commit c -> (Commit.tree c, Some "", `Read) :: List.map (fun p -> (p, None, `Parent)) (Commit.parents c) | Value.Tree t -> let dir = Option.value ~default:"" path in let acc = ref [] in Tree.iter (fun (e : Tree.entry) -> let path = Some (entry_path dir e.name) in match e.perm with | `Dir -> acc := (e.hash, path, `Read) :: !acc | `Normal | `Everybody | `Exec | `Link -> acc := (e.hash, path, `Leaf) :: !acc | `Commit -> ()) t; List.rev !acc | Value.Tag t -> [ (Tag.obj t, None, `Read) ] let kind_of_value = function | Value.Commit _ -> `Commit | Value.Tree _ -> `Tree | Value.Blob _ -> `Blob | Value.Tag _ -> `Tag let walk_named ?(shallow = fun _ -> false) ?(edge = ignore) ?(counted = ignore) ~read ~exists root = (* Iterative DFS with a colour map: White (not visited), Grey (on the stack), Black (fully processed). Post-order produces the bottom-up output. *) let color = Hashtbl.create 1024 in let edges = Hashtbl.create 16 in let stack = Stack.create () in let result = ref [] in let needed h = (not (Hashtbl.mem color h)) && not (exists h) in let emit_leaf h path = if needed h then begin Hashtbl.replace color h `Black; result := (h, `Blob, path) :: !result; counted () end in let expand h path = match read h with | Error (`Msg m) -> raise (Unreadable_object (h, m)) | Ok value -> if not (Hash.equal (Value.digest value) h) then raise (Unreadable_object (h, "object hash mismatch")); Stack.push (`Done (h, kind_of_value value, path)) stack; List.iter (fun (child, path, how) -> match how with | `Leaf -> emit_leaf child path | (`Read | `Parent) when needed child -> Stack.push (`Visit (child, path)) stack | `Read -> () | `Parent -> if exists child && not (Hashtbl.mem edges child) then begin Hashtbl.replace edges child (); edge child end) (named_children ~shallow h path value) in if needed root then Stack.push (`Visit (root, None)) stack; while not (Stack.is_empty stack) do match Stack.pop stack with | `Done (h, kind, path) -> Hashtbl.replace color h `Black; result := (h, kind, path) :: !result; counted () | `Visit (h, path) -> if not (Hashtbl.mem color h) then begin Hashtbl.replace color h `Grey; expand h path end done; List.rev !result let reachable_from ?shallow ?counted ~read ~exists root = List.map (fun (h, _, _) -> h) (walk_named ?shallow ?counted ~read ~exists root) let reachable_named ?shallow ?edge ?counted ~read ~exists root = List.map (fun (hash, kind, path) -> Store.pack_object ?path kind hash) (walk_named ?shallow ?edge ?counted ~read ~exists root) (* The entry at [path] under the tree [root], [tree] reading a tree. *) let rec entry_at ~tree root = function | [] -> None | [ name ] -> Option.bind (tree root) (Tree.find ~name) | dir :: rest -> ( match Option.bind (tree root) (Tree.find ~name:dir) with | Some { Tree.perm = `Dir; hash; _ } -> entry_at ~tree hash rest | _ -> None) (* builtin/pack-objects.c, add_preferred_base and add_preferred_base_object: the trees of the first [window] edges, then, for the first object of each name hash, the object at its path in each of them, a gitlink left out. *) let preferred_bases ?(window = 10) ~read ~edges objects = let tree_of h = match read h with | Ok (Value.Commit c) -> Some (Commit.tree c) | Ok (Value.Tree _) -> Some h | _ -> None in let roots = List.sort_uniq Hash.compare (List.filter_map tree_of (List.filteri (fun i _ -> i < window) edges)) in let trees = Hashtbl.create 64 in let tree h = match Hashtbl.find_opt trees h with | Some t -> t | None -> let t = match read h with Ok (Value.Tree t) -> Some t | _ -> None in Hashtbl.replace trees h t; t in let sent = Hashtbl.create (List.length objects) in List.iter (fun (o : Store.pack_object) -> Hashtbl.replace sent o.hash ()) objects; let looked = Hashtbl.create 64 and bases = Hashtbl.create 64 in let base path kind hash = if not (Hashtbl.mem sent hash || Hashtbl.mem bases hash) then begin Hashtbl.replace bases hash (); Some (Store.pack_object ~path kind hash) end else None in List.concat_map (fun (o : Store.pack_object) -> match o.path with | None -> [] | Some _ when Hashtbl.mem looked (Store.name_hash o) -> [] | Some "" -> Hashtbl.replace looked (Store.name_hash o) (); List.filter_map (base "" `Tree) roots | Some path -> Hashtbl.replace looked (Store.name_hash o) (); List.filter_map (fun root -> match entry_at ~tree root (String.split_on_char '/' path) with | Some { Tree.perm = `Commit; _ } | None -> None | Some { Tree.perm = `Dir; hash; _ } -> base path `Tree hash | Some { hash; _ } -> base path `Blob hash) roots) objects (** {1 Smart-protocol helpers (pure)} *) let agent = "nox-git/0" (* A 40-char hex [ref_name] is an object id, not a symbolic ref. *) let is_sha1_hex s = String.length s = 40 && String.for_all (function '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true | _ -> false) s (* Resolve [ref_name] against the advertised refs. Accepts a branch short name, a fully-qualified ref, a tag, "HEAD", or a 40-char object id. *) let resolve_want adv ref_name = let open Smart.Message.Advertisement in if is_sha1_hex ref_name then Some (Hash.of_hex ref_name) else let candidates = [ find_ref adv ref_name; find_branch adv ref_name; find_ref adv ("refs/tags/" ^ ref_name); ] in List.find_map Fun.id candidates (* Capabilities to request: only those advertised that we can honour. *) let client_caps adv = let caps = adv.Smart.Message.Advertisement.capabilities in let base = List.filter (Smart.Message.Capability.mem caps) [ "multi_ack_detailed"; "side-band-64k"; "ofs-delta" ] in let with_agent = if Smart.Message.Capability.mem caps "agent" then base @ [ "agent=" ^ agent ] else base in (with_agent, List.mem "side-band-64k" base) type channel = { write : string -> unit; (** Send bytes to the server and flush, so the server sees them before the next {!field-reader} read. *) reader : Bytesrw.Bytes.Reader.t; (** The persistent server-to-client byte stream for the whole exchange. *) eof : unit -> unit; (** End the client's side of the stream, once a v0 fetch has its pack or the session asks nothing more. *) } (** A persistent duplex channel the multi-round driver shuttles bytes over. *) (* Resolve [ref_name] against an ls-refs result. The SHA case takes priority. "HEAD" is not a trailing fallback: an unmatched name returns [None]. *) let resolve_v2 (refs : Smart.Message.V2.ls_ref list) ref_name = if is_sha1_hex ref_name then Some (Hash.of_hex ref_name) else let by_name n = List.find_map (fun (r : Smart.Message.V2.ls_ref) -> if r.name = n then Some r.hash else None) refs in List.find_map by_name [ ref_name; "refs/heads/" ^ ref_name; "refs/tags/" ^ ref_name ] let v2_request command args = Smart.Message.V2.request_to_string { Smart.Message.V2.command; capabilities = [ "object-format=sha1" ]; args } module Make (S : Store.S) = struct (** {1 Local file:// fetch} *) let resolve_ref src name = let candidates = [ name; "refs/heads/" ^ name; "refs/remotes/origin/" ^ name; "refs/tags/" ^ name; ] in let rec try_each = function | [] -> Ok (if String.length name = 40 then try Some (Hash.of_hex name) with Invalid_argument _ -> None else None) | c :: rest -> ( match S.read_ref src c with | Ok None -> try_each rest | (Ok (Some _) | Error _) as answer -> answer) in try_each candidates let err_ref_not_found ref_name = Error (`Msg (Fmt.str "local: ref not found in source: %s" ref_name)) (* Copy to [dst] the objects reachable from [targets] in [src] that [dst] lacks, each once and checking each one's digest: [on_progress] is told each one counted, then each one copied. With [budget], every read of [src], the walk's included, is held to the per-object limit, and each object copied is charged to the decoded total once. *) let copy_closure ?(on_progress = ignore) ?budget ~src ~dst targets = let read = match budget with | None -> S.read src | Some budget -> S.read_bounded src ~max_bytes:(Pack.max_object_size (Store.decode_budget budget)) in let charge value = match budget with | None -> Ok () | Some budget -> Pack.charge (Store.decode_budget budget) ~kind:(Fmt.str "%a" Value.pp_kind (Value.kind value)) (Value.length value) in let seen = Hashtbl.create 64 in let exists h = Hashtbl.mem seen h || S.exists dst h in let counted = Progress.counter on_progress in let to_copy = List.concat_map (fun target -> let objects = reachable_from ~counted ~read ~exists target in List.iter (fun h -> Hashtbl.replace seen h ()) objects; objects) targets in List.iteri (fun i h -> match read h with | Error (`Msg m) -> raise (Unreadable_object (h, m)) | Ok value -> if not (Hash.equal (Value.digest value) h) then raise (Unreadable_object (h, "object hash mismatch")); (match charge value with | Ok () -> () | Error (`Msg m) -> raise (Over_budget m)); let _ : Hash.t = S.write dst value in on_progress (Progress.Written (i + 1))) to_copy let local ?on_progress ?budget ~src ~dst ~ref_name () = try match resolve_ref src ref_name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> err_ref_not_found ref_name | Ok (Some target) -> L.info (fun m -> m "local: %s -> %s" ref_name (Hash.to_hex target)); copy_closure ?on_progress ?budget ~src ~dst [ target ]; S.write_ref dst "FETCH_HEAD" target; let tracking_ref = if String.starts_with ~prefix:"refs/" ref_name then let stripped = if String.starts_with ~prefix:"refs/heads/" ref_name then String.sub ref_name 11 (String.length ref_name - 11) else ref_name in "refs/remotes/origin/" ^ stripped else "refs/remotes/origin/" ^ ref_name in S.write_ref dst tracking_ref target; Ok target with | Unreadable_object (h, m) -> err_msgf "local: unreadable object %s: %s" (Hash.to_hex h) m | Over_budget m -> err_msgf "local: %s" m let local_refs ?on_progress ~src ~dst ~select () = let ( let* ) = Result.bind in let rec selected acc = function | [] -> Ok (List.rev acc) | name :: rest -> ( match select name with | None -> selected acc rest | Some local -> ( match S.read_ref src name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> selected acc rest | Ok (Some h) -> selected ((local, h) :: acc) rest)) in try let* selected = selected [] (List.sort String.compare (S.list_refs src)) in copy_closure ?on_progress ~src ~dst (List.map snd selected); Ok selected with Unreadable_object (h, m) -> err_msgf "local: unreadable object %s: %s" (Hash.to_hex h) m (** {1 Pack import} *) let import_pack dst pack = match S.write_pack dst pack with | Error _ as e -> e | Ok n -> L.debug (fun m -> m "import: stored pack of %d objects" n); Ok n let record_fetch dst ~ref_name ~target = S.write_ref dst "FETCH_HEAD" target; let tracking = if String.starts_with ~prefix:"refs/heads/" ref_name then "refs/remotes/origin/" ^ String.sub ref_name 11 (String.length ref_name - 11) else if String.starts_with ~prefix:"refs/" ref_name then ref_name else "refs/remotes/origin/" ^ ref_name in S.write_ref dst tracking target (* The tips of the refs of [dst], or the first that cannot be read. *) let local_tips dst = let rec go acc = function | [] -> Ok (List.rev acc) | name :: rest -> ( match S.read_ref dst name with | Error (`Msg m) -> Error (`Msg m) | Ok None -> go acc rest | Ok (Some h) -> go (h :: acc) rest) in go [] (S.list_refs dst) (* The haves [dst] offers ({!Negotiator}), [known] the advertised values it holds, or why a ref of it cannot be read. *) let negotiator ~known dst = let commit h = match S.read dst h with | Ok (Value.Commit c) -> Some (User.date (Commit.committer c), Commit.parents c) | Ok _ | Error _ -> None in Result.map (Negotiator.v ~commit ~known) (local_tips dst) let rec take neg n acc = if n <= 0 then List.rev acc else match Negotiator.next neg with | None -> List.rev acc | Some h -> take neg (n - 1) (h :: acc) (* fetch-pack.c's negotiation: rounds of haves from [neg], the first of {!Negotiator.initial_flush}, each answered by the server's acknowledgements, until it is ready, the haves run out, or {!Negotiator.max_in_vain} go unacknowledged after a first acknowledgement; then [finish ~commons haves] sends [done]. [round ~commons haves] sends [haves] after the [commons] acknowledged so far, and is [`Acks (acks, ready)], or [`Done r] when the answer carried the pack. *) let rounds neg ~round ~finish = let ( let* ) = Result.bind in let rec go ~flush ~sent ~in_vain ~acked commons = match take neg (flush - sent) [] with | [] -> finish ~commons [] | haves -> ( let* answer = round ~commons haves in match answer with | `Done r -> Ok r | `Acks (acks, ready) -> let fresh = List.filter (Negotiator.ack neg) acks in let n = List.length haves in let in_vain = if fresh = [] then in_vain + n else 0 in let acked = acked || acks <> [] in Smart.Event.emit_probe (Round { commons = List.length acks; ready }); if ready || (acked && in_vain >= Negotiator.max_in_vain) then finish ~commons:(commons @ fresh) [] else go ~flush:(Negotiator.next_flush flush) ~sent:(sent + n) ~in_vain ~acked (commons @ fresh)) in go ~flush:Negotiator.initial_flush ~sent:0 ~in_vain:0 ~acked:false [] (* The advertised values [dst] holds. *) let held dst hashes = List.filter (S.exists dst) hashes (* [deepen ] for a depth-limited request; [None] asks for full history. *) let deepen_of_depth depth = Option.map (fun d -> `Depth d) depth (* Fold the server's shallow section into the store's boundary: [Shallow] commits join the cut, [Unshallow] ones this fetch filled in leave it. An empty section means the server sent none, which must leave an existing boundary alone rather than clear it. *) let record_shallow dst = function | [] -> () | entries -> let add, remove = List.partition_map (function | Smart.Message.Shallow.Shallow h -> Either.Left h | Smart.Message.Shallow.Unshallow h -> Either.Right h) entries in let dropped h = List.exists (Hash.equal h) remove in let boundary = List.filter (fun h -> not (dropped h)) (S.read_shallow dst @ add) in S.write_shallow dst boundary (* [S.stream_pack], [read ~progress ~writer] reading the pack phase: [on_progress] is told the pack bytes [writer] takes, each line the remote writes on side band 2, and the objects of the pack once it is stored. *) let stream_pack ?budget ?on_progress dst read = match on_progress with | None -> S.stream_pack ?budget dst (fun ~writer -> read ~progress:ignore ~writer) | Some f -> let lines = Progress.lines f in let received = ref 0 in let stored = S.stream_pack ?budget dst (fun ~writer -> let writer = Bytesrw.Bytes.Writer.tap (fun s -> if not (Bytesrw.Bytes.Slice.is_eod s) then begin received := !received + Bytesrw.Bytes.Slice.length s; f (Progress.Received !received) end) writer in read ~progress:(Progress.feed lines) ~writer) in Progress.flush lines; Result.iter (fun (_, n) -> f (Progress.Written n)) stored; stored (* The pack phase of a v0 or v1 fetch, after [client]'s request. *) let read_pack ?budget ?on_progress dst client reader = stream_pack ?budget ?on_progress dst (fun ~progress ~writer -> Smart.Client.Fetch.read_response_to ~progress ~writer client reader |> Result.map snd) (* gitprotocol-http(5), "Smart Service git-upload-pack": every stateless request repeats the wants and the acknowledged common commits, followed by new haves. Only the final request carries done and receives a pack. *) let stateless_pack ?budget ?on_progress ~client ~adv ~want ~send dst = let ( let* ) = Result.bind in let known = held dst (List.map (fun (r : Smart.Message.ref_entry) -> r.hash) adv.Smart.Message.Advertisement.refs) in let* neg = negotiator ~known dst in let* negotiating, wants = Smart.Client.Fetch.want client want in let round ~commons haves = let* c, bytes = Smart.Client.Fetch.have_round negotiating ~last:false (commons @ haves) in let* reader = send (wants ^ bytes) in let* _, (r : Smart.Message.Upload_pack.round) = Smart.Client.Fetch.read_round c reader in Ok (`Acks (r.commons, r.ready <> None)) in let finish ~commons haves = let* c, bytes = Smart.Client.Fetch.have_round negotiating ~last:true (commons @ haves) in let* reader = send (wants ^ bytes) in read_pack ?budget ?on_progress dst c reader in rounds neg ~round ~finish (* Drive the upload-pack negotiation over a ready advertisement. *) let negotiate ?budget ?on_progress ?depth ~client ~adv ~ref_name ~send dst = let ( let* ) = Result.bind in match resolve_want adv ref_name with | None -> err_msgf "fetch: ref not found on remote: %s" ref_name | Some target -> Smart.Event.emit_probe (Advertised { refs = List.length adv.Smart.Message.Advertisement.refs }); let caps, _ = client_caps adv in let want = Smart.Message.Want.v ~capabilities:caps ?deepen:(deepen_of_depth depth) ~shallows:(S.read_shallow dst) [ target ] in Smart.Event.emit_probe (Wanted { wants = 1; haves = 0 }); let* (head : Smart.Message.Upload_pack.head), (n : int) = stateless_pack ?budget ?on_progress ~client ~adv ~want ~send dst in record_shallow dst head.shallows; Smart.Event.emit_probe (Packed { objects = n }); L.debug (fun m -> m "fetch: stored pack of %d objects" n); record_fetch dst ~ref_name ~target; Ok target (* The refs of [adv] that [select] keeps, each [(local, value)], after [pack want] fetched those [dst] lacks. *) let fetch_selected ~adv ~select ~pack dst = let ( let* ) = Result.bind in let selected = List.filter_map (fun (r : Smart.Message.ref_entry) -> if String.ends_with ~suffix:"^{}" r.name then None else Option.map (fun local -> (local, r.hash)) (select r.name)) adv.Smart.Message.Advertisement.refs in let wants = List.sort_uniq Hash.compare (List.filter_map (fun (_, h) -> if S.exists dst h then None else Some h) selected) in match wants with | [] -> Ok selected | _ -> ( let caps, _ = client_caps adv in let want = Smart.Message.Want.v ~capabilities:caps ~shallows:(S.read_shallow dst) wants in let* (head : Smart.Message.Upload_pack.head), (n : int) = pack ~wants want in record_shallow dst head.shallows; Smart.Event.emit_probe (Packed { objects = n }); match List.find_opt (fun h -> not (S.exists dst h)) wants with | Some h -> err_msgf "fetch: the pack lacks %s" (Hash.to_hex h) | None -> Ok selected) let negotiate_refs ?budget ?on_progress ~client ~adv ~select ~send dst = fetch_selected ~adv ~select dst ~pack:(fun ~wants want -> Smart.Event.emit_probe (Wanted { wants = List.length wants; haves = 0 }); stateless_pack ?budget ?on_progress ~client ~adv ~want ~send dst) (** {1 Multi-round negotiation} *) (* A [multi_ack_detailed] fetch of [want] over [channel], which keeps the server's state between rounds: the want-list, then each round a batch of haves and a flush, the last [done], then the pack. *) let stateful_pack ?budget ?on_progress ~client ~want ~known ~channel dst = let ( let* ) = Result.bind in let* neg = negotiator ~known dst in let* client, want_bytes = Smart.Client.Fetch.want client want in channel.write want_bytes; let client = ref client in let round ~commons:_ haves = let* c, hb = Smart.Client.Fetch.have_round !client ~last:false haves in channel.write hb; let* c, (r : Smart.Message.Upload_pack.round) = Smart.Client.Fetch.read_round c channel.reader in client := c; Ok (`Acks (r.commons, r.ready <> None)) in let finish ~commons:_ haves = let* c, hb = Smart.Client.Fetch.have_round !client ~last:true haves in channel.write hb; let* pack = read_pack ?budget ?on_progress dst c channel.reader in channel.eof (); Ok pack in rounds neg ~round ~finish let negotiate_stateful ?budget ?on_progress ?depth ~client ~adv ~ref_name ~channel dst = let ( let* ) = Result.bind in match resolve_want adv ref_name with | None -> err_msgf "fetch: ref not found on remote: %s" ref_name | Some target -> let refs = adv.Smart.Message.Advertisement.refs in Smart.Event.emit_probe (Advertised { refs = List.length refs }); let caps, _ = client_caps adv in let want = Smart.Message.Want.v ~capabilities:caps ?deepen:(deepen_of_depth depth) ~shallows:(S.read_shallow dst) [ target ] in Smart.Event.emit_probe (Wanted { wants = 1; haves = 0 }); let known = held dst (List.map (fun (r : Smart.Message.ref_entry) -> r.hash) refs) in let* (head : Smart.Message.Upload_pack.head), (n : int) = stateful_pack ?budget ?on_progress ~client ~want ~known ~channel dst in record_shallow dst head.shallows; Smart.Event.emit_probe (Packed { objects = n }); L.debug (fun m -> m "fetch: stored pack of %d objects (multi-round)" n); record_fetch dst ~ref_name ~target; Ok target (** {1 Protocol v2 negotiation} *) let v2_read_pack ?budget ?on_progress ?on_shallow dst reader = stream_pack ?budget ?on_progress dst (fun ~progress ~writer -> Smart.Message.V2.read_fetch_to ?on_shallow ~progress ~writer reader) (* A [deepen] request must carry the boundary the client already has, so the server can work out which commits to unshallow. The server sends its progress unless asked for [no-progress], as git asks when it shows none (fetch-pack.c). *) let v2_fetch_args ?depth ~progress dst targets = let shallow_args = List.map (fun h -> "shallow " ^ Hash.to_hex h) (S.read_shallow dst) in let deepen_args = match depth with None -> [] | Some d -> [ "deepen " ^ string_of_int d ] in ("ofs-delta" :: (if progress then [] else [ "no-progress" ])) @ List.map (fun h -> "want " ^ Hash.to_hex h) targets @ shallow_args @ deepen_args (* [reader] past the acknowledgments it held, charged to [budget] for them and bounded by what is left of it. *) let charged budget ~start reader = match budget with | None -> reader | Some budget -> let used = Bytesrw.Bytes.Reader.read_length reader - start in if not (Store.charge_wire budget used) then raise Store.Wire_budget_exceeded; Bytesrw.Bytes.Reader.limit ~action:(fun _ _ -> raise Store.Wire_budget_exceeded) (Store.remaining_wire budget) reader (* A v2 fetch of [base]'s wants in {!rounds}: each fetch command stands alone (gitprotocol-v2(5), "fetch"), so it repeats the commons found so far before its new haves, and the server answers acknowledgments, or ready and the pack. *) let v2_fetch_pack ?budget ?on_progress ?on_shallow ~send ~known dst base = let ( let* ) = Result.bind in let* neg = negotiator ~known dst in let request ~commons haves last = v2_request "fetch" (base @ List.map (fun h -> "have " ^ Hash.to_hex h) (commons @ haves) @ last) in let round ~commons haves = let* probe = send ~buffered:false (request ~commons haves []) in let start = Bytesrw.Bytes.Reader.read_length probe in let* acks = Smart.Message.V2.read_acknowledgments probe in if acks.Smart.Message.V2.ready then Result.map (fun r -> `Done r) (v2_read_pack ?budget ?on_progress ?on_shallow dst (charged budget ~start probe)) else Ok (`Acks (acks.Smart.Message.V2.commons, false)) in let finish ~commons haves = let* reader = send ~buffered:false (request ~commons haves [ "done" ]) in v2_read_pack ?budget ?on_progress ?on_shallow dst reader in rounds neg ~round ~finish (* Drive a v2 fetch: [send body] issues one command request and returns a reader over the response. *) let negotiate_v2 ?budget ?on_progress ?depth ~ref_name ~send dst = let ( let* ) = Result.bind in let* ls_reader = send ~buffered:true (v2_request "ls-refs" [ "symrefs"; "peel"; "ref-prefix refs/"; "ref-prefix HEAD" ]) in let* refs = Smart.Message.V2.read_ls_refs ls_reader in match resolve_v2 refs ref_name with | None -> err_msgf "fetch: ref not found on remote: %s" ref_name | Some target -> let base = v2_fetch_args ?depth ~progress:(Option.is_some on_progress) dst [ target ] in let known = held dst (List.map (fun (r : Smart.Message.V2.ls_ref) -> r.hash) refs) in let shallows = ref [] in let on_shallow entries = shallows := entries in let* (), (n : int) = v2_fetch_pack ?budget ?on_progress ~on_shallow ~send ~known dst base in record_shallow dst !shallows; L.debug (fun m -> m "fetch(v2): stored pack of %d objects" n); record_fetch dst ~ref_name ~target; Ok target let ls_refs_v2 ~prefixes ~send = let ( let* ) = Result.bind in let* reader = send ~buffered:true (v2_request "ls-refs" ([ "symrefs"; "peel" ] @ List.map (fun p -> "ref-prefix " ^ p) prefixes)) in Smart.Message.V2.read_ls_refs reader let negotiate_refs_v2 ?budget ?on_progress ~refs ~select ~send dst = let ( let* ) = Result.bind in let selected = List.filter_map (fun (r : Smart.Message.V2.ls_ref) -> Option.map (fun local -> (local, r.hash)) (select r.name)) refs in let wants = List.sort_uniq Hash.compare (List.filter_map (fun (_, h) -> if S.exists dst h then None else Some h) selected) in match wants with | [] -> Ok selected | _ -> ( let base = v2_fetch_args ~progress:(Option.is_some on_progress) dst wants in let known = held dst (List.map (fun (r : Smart.Message.V2.ls_ref) -> r.hash) refs) in Smart.Event.emit_probe (Wanted { wants = List.length wants; haves = 0 }); let shallows = ref [] in let on_shallow entries = shallows := entries in let* (), (n : int) = v2_fetch_pack ?budget ?on_progress ~on_shallow ~send ~known dst base in record_shallow dst !shallows; Smart.Event.emit_probe (Packed { objects = n }); match List.find_opt (fun h -> not (S.exists dst h)) wants with | Some h -> err_msgf "fetch: the pack lacks %s" (Hash.to_hex h) | None -> Ok selected) (** {1 An upload-pack session} *) (* gitprotocol-pack(5) and gitprotocol-v2(5): a client ends an upload-pack session it has nothing more to ask of with a flush-pkt, as git does. *) let end_session c = c.write "0000"; c.eof () (* A request sent on the stream, which stays open: git ends its side of an upload-pack session only once it has the answer (transport.c, fetch_refs_via_pack), and upload-pack answers without that end. *) let send c body = c.write body; Ok c.reader (* The server's first answer says which protocol it speaks (gitprotocol-v2(5), "Initial Client Request"): [v2 ~send] runs, each [send] a command on the stream, which stays open for the next, after a v2 greeting; [v0 ~client ~adv] after a v0 or v1 advertisement. *) let session ?(explain = Fun.id) c ~v2 ~v0 = match Smart.Message.read_error c.reader with | Some why -> err_msgf "remote: %s" why | None -> ( match Smart.Message.V2.read_greeting c.reader with | Error (`Msg m) -> Error (`Msg (explain m)) | Ok (`V2 _) -> let r = v2 ~send:(fun ~buffered:_ -> send c) in if Result.is_ok r then end_session c; r | Ok `V0 -> ( match Smart.Client.Fetch.advertisement Smart.Client.Fetch.v c.reader with | Error (`Msg m) -> Error (`Msg (explain m)) | Ok (client, adv) -> v0 ~client ~adv)) let session_ls_refs ?explain ?(prefixes = []) c = session ?explain c ~v2:(fun ~send -> Result.map Smart.Message.V2.advertisement (ls_refs_v2 ~prefixes ~send)) ~v0:(fun ~client:_ ~adv -> end_session c; Ok adv) let session_fetch_refs ?budget ?on_progress ?explain ?(prefixes = []) ~select c dst = session ?explain c ~v2:(fun ~send -> Result.bind (ls_refs_v2 ~prefixes ~send) @@ fun refs -> negotiate_refs_v2 ?budget ?on_progress ~refs ~select ~send dst) ~v0:(fun ~client ~adv -> fetch_selected ~adv ~select dst ~pack:(fun ~wants want -> Smart.Event.emit_probe (Wanted { wants = List.length wants; haves = 0 }); let known = held dst (List.map (fun (r : Smart.Message.ref_entry) -> r.hash) adv.Smart.Message.Advertisement.refs) in stateful_pack ?budget ?on_progress ~client ~want ~known ~channel:c dst)) let session_fetch ?budget ?on_progress ?depth ?explain ~ref_name c dst = session ?explain c ~v2:(fun ~send -> negotiate_v2 ?budget ?on_progress ?depth ~ref_name ~send dst) ~v0:(fun ~client ~adv -> negotiate_stateful ?budget ?on_progress ?depth ~client ~adv ~ref_name ~channel:c dst) end