Skip to main content

gix_protocol/fetch/response/
io.rs

1use std::io;
2
3#[crate::bisync::only_async]
4use crate::transport::client::async_io::ExtendedBufRead;
5#[crate::bisync::only_sync]
6use crate::transport::client::blocking_io::ExtendedBufRead;
7use gix_error::{Error, ErrorExt, Result, bail, message};
8use gix_transport::{Protocol, client, client::MessageKind};
9
10use crate::fetch::{
11    Response,
12    response::{Acknowledgement, ShallowUpdate, WantedRef, shallow_update_from_line},
13};
14
15#[crate::bisync::bisync]
16async fn parse_v2_section<'a, T>(
17    line: &mut String,
18    reader: &mut impl ExtendedBufRead<'a>,
19    res: &mut Vec<T>,
20    parse: impl Fn(&str) -> Result<T>,
21) -> Result<bool> {
22    line.clear();
23    while reader.readline_str(line).await.map_err(read_error)? != 0 {
24        res.push(parse(line)?);
25        line.clear();
26    }
27    // End of message, or end of section?
28    Ok(if reader.stopped_at() == Some(MessageKind::Delimiter) {
29        // try reading more sections
30        reader.reset(Protocol::V2);
31        false
32    } else {
33        // we are done, there is no pack
34        true
35    })
36}
37
38impl Response {
39    /// Parse a response of the given `version` of the protocol from `reader`.
40    ///
41    /// `client_expects_pack` is only relevant for V1 stateful connections, and if `false`, causes us to stop parsing when seeing `NAK`,
42    /// and if `true` we will keep parsing until we get a pack as the client already signalled to the server that it's done.
43    /// This way of doing things allows us to exploit knowledge about more recent versions of the protocol, which keeps code easier
44    /// and more localized without having to support all the cruft that there is.
45    ///
46    /// `wants_to_negotiate` should be `false` for clones which is when we don't have sent any haves. The reason for this flag to exist
47    /// is to predict how to parse V1 output only, and neither `client_expects_pack` nor `wants_to_negotiate` are relevant for V2.
48    /// This ugliness is in place to avoid having to resort to an [an even more complex ugliness](https://github.com/git/git/blob/9e49351c3060e1fa6e0d2de64505b7becf157f28/fetch-pack.c#L583-L594)
49    /// that `git` has to use to predict how many acks are supposed to be read. We also genuinely hope that this covers it all….
50    #[crate::bisync::bisync]
51    pub async fn from_line_reader<'a>(
52        version: Protocol,
53        reader: &mut impl ExtendedBufRead<'a>,
54        client_expects_pack: bool,
55        wants_to_negotiate: bool,
56    ) -> Result<Response> {
57        match version {
58            Protocol::V0 | Protocol::V1 => {
59                let mut line = String::new();
60                let mut acks = Vec::<Acknowledgement>::new();
61                let mut shallows = Vec::<ShallowUpdate>::new();
62                let mut saw_ready = false;
63                let has_pack = 'lines: loop {
64                    line.clear();
65                    let peeked_line = match reader.peek_data_line().await {
66                        Some(Ok(Ok(line))) => String::from_utf8_lossy(line),
67                        // This special case (hang/block forever) deals with a single NAK being a legitimate EOF sometimes
68                        // Note that this might block forever in stateful connections as there it's not really clear
69                        // if something will be following or not by just looking at the response. Instead you have to know
70                        // [a lot](https://github.com/git/git/blob/9e49351c3060e1fa6e0d2de64505b7becf157f28/fetch-pack.c#L583-L594)
71                        // to deal with this correctly.
72                        // For now this is acceptable, as V2 can be used as a workaround, which also is the default.
73                        Some(Err(err)) if err.kind() == io::ErrorKind::UnexpectedEof => break 'lines false,
74                        Some(Err(err)) => return Err(read_error(err)),
75                        Some(Ok(Err(err))) => return Err(transport_error(err)),
76                        None => {
77                            // maybe we saw a shallow flush packet, let's reset and retry
78                            debug_assert_eq!(
79                                reader.stopped_at(),
80                                Some(MessageKind::Flush),
81                                "If this isn't a flush packet, we don't know what's going on"
82                            );
83                            reader.readline_str(&mut line).await.map_err(read_error)?;
84                            reader.reset(Protocol::V1);
85                            match reader.peek_data_line().await {
86                                Some(Ok(Ok(line))) => String::from_utf8_lossy(line),
87                                Some(Err(err)) => return Err(read_error(err)),
88                                Some(Ok(Err(err))) => return Err(transport_error(err)),
89                                None => break 'lines false, // EOF
90                            }
91                        }
92                    };
93
94                    if Response::parse_v1_ack_or_shallow_or_assume_pack(&mut acks, &mut shallows, &peeked_line) {
95                        break 'lines true;
96                    }
97                    assert_ne!(
98                        reader.readline_str(&mut line).await.map_err(read_error)?,
99                        0,
100                        "consuming a peeked line works"
101                    );
102                    // When the server sends ready, we know there is going to be a pack so no need to stop early.
103                    saw_ready |= matches!(acks.last(), Some(Acknowledgement::Ready));
104                    if let Some(Acknowledgement::Nak) = acks.last().filter(|_| !client_expects_pack || !saw_ready) {
105                        if !wants_to_negotiate {
106                            continue;
107                        }
108                        break 'lines false;
109                    }
110                };
111                Ok(Response {
112                    acks,
113                    shallows,
114                    wanted_refs: vec![],
115                    has_pack,
116                })
117            }
118            Protocol::V2 => {
119                // NOTE: We only read acknowledgements and scrub to the pack file, until we have use for the other features
120                let mut line = String::new();
121                reader.reset(Protocol::V2);
122                let mut acks = Vec::<Acknowledgement>::new();
123                let mut shallows = Vec::<ShallowUpdate>::new();
124                let mut wanted_refs = Vec::<WantedRef>::new();
125                let has_pack = 'section: loop {
126                    line.clear();
127                    if reader.readline_str(&mut line).await.map_err(read_error)? == 0 {
128                        return Err(read_error(io::Error::new(
129                            io::ErrorKind::UnexpectedEof,
130                            "Could not read message headline",
131                        )));
132                    }
133
134                    match line.trim_end() {
135                        "acknowledgments" => {
136                            if parse_v2_section(&mut line, reader, &mut acks, Acknowledgement::from_line).await? {
137                                break 'section false;
138                            }
139                        }
140                        "shallow-info" => {
141                            if parse_v2_section(&mut line, reader, &mut shallows, shallow_update_from_line).await? {
142                                break 'section false;
143                            }
144                        }
145                        "wanted-refs" => {
146                            if parse_v2_section(&mut line, reader, &mut wanted_refs, WantedRef::from_line).await? {
147                                break 'section false;
148                            }
149                        }
150                        "packfile" => {
151                            // what follows is the packfile itself, which can be read with a sideband enabled reader
152                            break 'section true;
153                        }
154                        _ => {
155                            bail!("Unknown or unsupported header: {line:?}".corrupted());
156                        }
157                    }
158                };
159                Ok(Response {
160                    acks,
161                    shallows,
162                    wanted_refs,
163                    has_pack,
164                })
165            }
166        }
167    }
168}
169
170fn read_error(err: io::Error) -> Error {
171    let err = if err.kind() == io::ErrorKind::Other {
172        match err.into_inner() {
173            Some(err) => match err.downcast::<gix_transport::packetline::read::Error>() {
174                Ok(err) => {
175                    return (*err).and_raise(message("Failed to read from line reader"));
176                }
177                Err(err) => io::Error::other(err),
178            },
179            None => io::ErrorKind::Other.into(),
180        }
181    } else {
182        err
183    };
184    transport_error(err.into())
185}
186
187fn transport_error(err: client::Error) -> Error {
188    err.and_raise(message("Failed to read from line reader"))
189}
190
191#[cfg(test)]
192mod tests {
193    #[test]
194    fn line_reader_io_preserves_classification() {
195        let err = super::read_error(std::io::ErrorKind::ConnectionAborted.into());
196        insta::assert_debug_snapshot!(err, "connection failures remain retryable while reading packet lines", @"
197        Failed to read from line reader
198
199        Caused by:
200            0: An IO error occurred when talking to the server
201            1: connection aborted
202        ");
203        assert!(
204            err.can_retry_lenient(),
205            "connection failures remain retryable while reading packet lines"
206        );
207        assert!(!err.can_retry(), "connection failures require the lenient policy");
208        assert!(
209            !err.is_retryable(),
210            "wrapping I/O does not add an explicit retry marker"
211        );
212
213        let err = super::read_error(std::io::ErrorKind::OutOfMemory.into());
214        insta::assert_debug_snapshot!(err, "memory exhaustion isn't retryable by the conservative policy", @"
215        Failed to read from line reader
216
217        Caused by:
218            0: An IO error occurred when talking to the server
219            1: out of memory
220        ");
221        assert!(
222            !err.can_retry(),
223            "memory exhaustion isn't retryable by the conservative policy"
224        );
225        assert!(err.can_retry_lenient(), "the lenient policy includes memory exhaustion");
226        assert!(
227            err.is_resource_exhausted(),
228            "the allocation failure remains recognizable"
229        );
230    }
231}