gix_protocol/command.rs
1//! V2 command abstraction to validate invocations and arguments, like a database of what we know about them.
2use super::Command;
3
4/// A feature name known at compile time and its optional owned value.
5pub type Feature = (&'static str, Option<String>);
6
7impl Command {
8 /// Produce the name of the command as known by the server side.
9 pub fn as_str(&self) -> &'static str {
10 match self {
11 Command::LsRefs => "ls-refs",
12 Command::Fetch => "fetch",
13 }
14 }
15}
16
17#[cfg(any(test, feature = "async-client", feature = "blocking-client"))]
18mod with_io {
19 use bstr::{BString, ByteSlice};
20 use gix_error::ExnMessageResult;
21 use gix_transport::client::Capabilities;
22
23 use crate::{Command, command::Feature};
24
25 impl Command {
26 /// Only V2
27 fn all_argument_prefixes(&self) -> &'static [&'static str] {
28 match self {
29 Command::LsRefs => &["symrefs", "peel", "ref-prefix ", "unborn"],
30 Command::Fetch => &[
31 "want ", // hex oid
32 "have ", // hex oid
33 "done",
34 "thin-pack",
35 "no-progress",
36 "include-tag",
37 "ofs-delta",
38 // Shallow feature/capability
39 "shallow ", // hex oid
40 "deepen ", // commit depth
41 "deepen-relative",
42 "deepen-since ", // time-stamp
43 "deepen-not ", // rev
44 // filter feature/capability
45 "filter ", // filter-spec
46 // ref-in-want feature
47 "want-ref ", // ref path
48 // sideband-all feature
49 "sideband-all",
50 // packfile-uris feature
51 "packfile-uris ", // protocols
52 // wait-for-done feature
53 "wait-for-done",
54 ],
55 }
56 }
57
58 fn all_features(&self, version: gix_transport::Protocol) -> &'static [&'static str] {
59 match self {
60 Command::LsRefs => &[],
61 Command::Fetch => match version {
62 gix_transport::Protocol::V0 | gix_transport::Protocol::V1 => &[
63 "multi_ack",
64 "thin-pack",
65 "side-band",
66 "side-band-64k",
67 "ofs-delta",
68 "shallow",
69 "deepen-since",
70 "deepen-not",
71 "deepen-relative",
72 "no-progress",
73 "include-tag",
74 "multi_ack_detailed",
75 "allow-tip-sha1-in-want",
76 "allow-reachable-sha1-in-want",
77 "no-done",
78 "filter",
79 ],
80 gix_transport::Protocol::V2 => &[
81 "shallow",
82 "filter",
83 "ref-in-want",
84 "sideband-all",
85 "packfile-uris",
86 "wait-for-done",
87 ],
88 },
89 }
90 }
91
92 /// Provide the initial arguments based on the given `features`.
93 /// They are typically provided by the [`Self::default_features`] method.
94 /// Only useful for V2, and based on heuristics/experimentation.
95 pub fn initial_v2_arguments(&self, features: &[Feature]) -> Vec<BString> {
96 match self {
97 Command::Fetch => ["thin-pack", "ofs-delta"]
98 .iter()
99 .map(|s| s.as_bytes().as_bstr().to_owned())
100 .chain(
101 [
102 "sideband-all",
103 /* "packfile-uris" */ // packfile-uris must be configurable and can't just be used. Some servers advertise it and reject it later.
104 ]
105 .iter()
106 .filter(|f| features.iter().any(|(sf, _)| sf == *f))
107 .map(|f| f.as_bytes().as_bstr().to_owned()),
108 )
109 .collect(),
110 Command::LsRefs => vec![b"symrefs".as_bstr().to_owned(), b"peel".as_bstr().to_owned()],
111 }
112 }
113
114 /// Turns on all modern features for V1 and all supported features for V2, returning them as a vector of features.
115 /// Note that this is the basis for any fetch operation as these features fulfil basic requirements and reasonably up-to-date servers.
116 pub fn default_features(
117 &self,
118 version: gix_transport::Protocol,
119 server_capabilities: &Capabilities,
120 ) -> Vec<Feature> {
121 let mut features = match self {
122 Command::Fetch => match version {
123 gix_transport::Protocol::V0 | gix_transport::Protocol::V1 => {
124 let has_multi_ack_detailed = server_capabilities.contains("multi_ack_detailed");
125 let has_sideband_64k = server_capabilities.contains("side-band-64k");
126 self.all_features(version)
127 .iter()
128 .copied()
129 .filter(|feature| match *feature {
130 "side-band" if has_sideband_64k => false,
131 "multi_ack" if has_multi_ack_detailed => false,
132 "no-progress" => false,
133 feature => server_capabilities.contains(feature),
134 })
135 .map(|s| (s, None))
136 .collect()
137 }
138 gix_transport::Protocol::V2 => {
139 let supported_features: Vec<_> = server_capabilities
140 .iter()
141 .find_map(|c| {
142 if c.name() == Command::Fetch.as_str() {
143 c.values().map(|v| v.map(ToOwned::to_owned).collect())
144 } else {
145 None
146 }
147 })
148 .unwrap_or_default();
149 self.all_features(version)
150 .iter()
151 .copied()
152 .filter(|feature| supported_features.iter().any(|supported| supported == feature))
153 .map(|s| (s, None))
154 .collect()
155 }
156 },
157 Command::LsRefs => vec![],
158 };
159 // Echo the server's object format in every v2 command.
160 // A stateless transport like HTTP sends each command as its own request, so without this,
161 // the server assumes SHA1 and aborts any command against a SHA-256 repository.
162 if matches!(version, gix_transport::Protocol::V2)
163 && let Some(object_format) = server_capabilities
164 .capability("object-format")
165 .and_then(|c| c.value())
166 .and_then(|value| value.to_str().ok())
167 {
168 features.push(("object-format", Some(object_format.to_owned())));
169 }
170 features
171 }
172 /// Return an error if the given `arguments` and `features` don't match what's statically known.
173 pub fn validate_argument_prefixes(
174 &self,
175 version: gix_transport::Protocol,
176 server: &Capabilities,
177 arguments: &[BString],
178 features: &[Feature],
179 ) -> ExnMessageResult {
180 let allowed = self.all_argument_prefixes();
181 for arg in arguments {
182 if allowed.iter().any(|allowed| arg.starts_with(allowed.as_bytes())) {
183 continue;
184 }
185 return Err(gix_error::validation(format!(
186 "{}: argument {arg} is not known or allowed",
187 self.as_str()
188 ))
189 .into());
190 }
191 match version {
192 gix_transport::Protocol::V0 | gix_transport::Protocol::V1 => {
193 for (feature, _) in features {
194 if server
195 .iter()
196 .any(|c| feature.starts_with(c.name().to_str_lossy().as_ref()))
197 {
198 continue;
199 }
200 return Err(gix_error::validation(format!(
201 "{}: capability {feature} is not supported",
202 self.as_str()
203 ))
204 .into());
205 }
206 }
207 gix_transport::Protocol::V2 => {
208 let allowed = server
209 .iter()
210 .find_map(|c| {
211 if c.name() == self.as_str() {
212 c.values().map(|v| v.map(ToString::to_string).collect::<Vec<_>>())
213 } else {
214 None
215 }
216 })
217 .unwrap_or_default();
218 for (feature, _) in features {
219 if allowed.iter().any(|allowed| feature == allowed) {
220 continue;
221 }
222 match *feature {
223 "agent" | "object-format" => {}
224 _ => {
225 return Err(gix_error::validation(format!(
226 "{}: capability {feature} is not supported",
227 self.as_str()
228 ))
229 .into());
230 }
231 }
232 }
233 }
234 }
235 Ok(())
236 }
237 }
238}