1use crate::error::{TerminalScope, WireErrorCode};
8use crate::frame::Frame;
9use crate::handshake::HandshakeSequenceError;
10use crate::version::ProtocolVersion;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13enum CloseReason {
14 UnsolicitedFrame,
15 MismatchedAcknowledgment,
16 UnexpectedDuringHandshake,
17 WrongDirectionOrRepeatedHandshake,
18 InvalidErrorEnvelope,
19 ServerTerminalError,
20}
21
22impl CloseReason {
23 const fn phrase(self) -> &'static str {
24 match self {
25 Self::UnsolicitedFrame => "an unsolicited frame before a handshake was sent",
26 Self::MismatchedAcknowledgment => "an acknowledgment of a version that was not offered",
27 Self::UnexpectedDuringHandshake => "an unexpected frame during the handshake",
28 Self::WrongDirectionOrRepeatedHandshake => {
29 "a direction or repeated-handshake violation"
30 }
31 Self::InvalidErrorEnvelope => "an invalid server error frame",
32 Self::ServerTerminalError => "a connection-terminal server error",
33 }
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38enum State {
39 Fresh,
40 Outstanding(ProtocolVersion),
41 Completed(ProtocolVersion),
42 Closed(CloseReason),
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
50pub enum ClientHandshakeStartError {
51 #[error("cannot record a sent handshake for protocol version zero")]
53 VersionZero,
54 #[error("a handshake has already been sent on this connection")]
56 AlreadyStarted,
57 #[error("the client handshake gate is permanently closed")]
59 Closed,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum ClientHandshakeOutcome {
65 Completed { version: ProtocolVersion },
67 Admitted,
69 ServerTerminated,
75}
76
77#[derive(Debug)]
89pub struct ClientHandshakeGate {
90 state: State,
91}
92
93impl ClientHandshakeGate {
94 pub fn new() -> Self {
96 Self {
97 state: State::Fresh,
98 }
99 }
100
101 pub fn record_handshake_sent(
110 &mut self,
111 offered: ProtocolVersion,
112 ) -> Result<(), ClientHandshakeStartError> {
113 match self.state {
114 State::Fresh => {
115 if offered.get() == 0 {
116 return Err(ClientHandshakeStartError::VersionZero);
117 }
118 self.state = State::Outstanding(offered);
119 Ok(())
120 }
121 State::Outstanding(_) | State::Completed(_) => {
122 Err(ClientHandshakeStartError::AlreadyStarted)
123 }
124 State::Closed(_) => Err(ClientHandshakeStartError::Closed),
125 }
126 }
127
128 pub fn is_complete(&self) -> bool {
130 matches!(self.state, State::Completed(_))
131 }
132
133 pub fn offered_version(&self) -> Option<ProtocolVersion> {
135 match self.state {
136 State::Outstanding(version) => Some(version),
137 _ => None,
138 }
139 }
140
141 pub fn accepted_version(&self) -> Option<ProtocolVersion> {
143 match self.state {
144 State::Completed(version) => Some(version),
145 _ => None,
146 }
147 }
148
149 pub fn is_closed(&self) -> bool {
152 matches!(self.state, State::Closed(_))
153 }
154
155 pub fn admit(
168 &mut self,
169 frame: &Frame,
170 ) -> Result<ClientHandshakeOutcome, HandshakeSequenceError> {
171 match (self.state, frame) {
172 (State::Fresh, _) => self.reject(
173 CloseReason::UnsolicitedFrame,
174 format!("received {:?} before the client sent a handshake", frame.kind()),
175 ),
176 (State::Outstanding(offered), Frame::HandshakeAck { version }) => {
177 if *version == offered {
178 self.state = State::Completed(offered);
179 Ok(ClientHandshakeOutcome::Completed { version: offered })
180 } else {
181 self.reject(
182 CloseReason::MismatchedAcknowledgment,
183 format!("handshake acknowledgment names version {version}, but the client offered {offered}"),
184 )
185 }
186 }
187 (State::Completed(_), Frame::Error { id: None, unrecognized_code: Some(_), .. }) => self.reject(
188 CloseReason::InvalidErrorEnvelope,
189 "a server error with an unrecognized code must identify an operation".to_string(),
190 ),
191 (State::Completed(_), Frame::Error { id: Some(_), code, .. })
192 if code.terminal_scope() == TerminalScope::Connection =>
193 {
194 self.reject(
195 CloseReason::InvalidErrorEnvelope,
196 "a connection-terminal server error must not identify an operation".to_string(),
197 )
198 }
199 (State::Completed(_), Frame::Error { id: None, code, .. })
200 if code.terminal_scope() == TerminalScope::Request =>
201 {
202 self.reject(
203 CloseReason::InvalidErrorEnvelope,
204 "a request-terminal server error must identify an operation".to_string(),
205 )
206 }
207 (State::Outstanding(_) | State::Completed(_), Frame::Error { id: None, code, .. })
208 if code.terminal_scope() == TerminalScope::Connection =>
209 {
210 self.state = State::Closed(CloseReason::ServerTerminalError);
211 Ok(ClientHandshakeOutcome::ServerTerminated)
212 }
213 (State::Outstanding(_), _) => self.reject(
214 CloseReason::UnexpectedDuringHandshake,
215 format!("expected the offered-version acknowledgment or a connection-terminal error, got {:?}", frame.kind()),
216 ),
217 (State::Completed(_), Frame::Response { .. }
218 | Frame::Error { .. }
219 | Frame::SubscribeAck { .. }
220 | Frame::UnsubscribeAck { .. }
221 | Frame::Event { .. }) => Ok(ClientHandshakeOutcome::Admitted),
222 (State::Completed(_), _) => self.reject(
223 CloseReason::WrongDirectionOrRepeatedHandshake,
224 format!("frame kind {:?} is not admissible at a client after handshake completion", frame.kind()),
225 ),
226 (State::Closed(reason), _) => Err(sequence_error(format!(
227 "connection already closed by {}",
228 reason.phrase()
229 ))),
230 }
231 }
232
233 fn reject(
234 &mut self,
235 reason: CloseReason,
236 message: String,
237 ) -> Result<ClientHandshakeOutcome, HandshakeSequenceError> {
238 self.state = State::Closed(reason);
239 Err(sequence_error(message))
240 }
241}
242
243fn sequence_error(message: String) -> HandshakeSequenceError {
244 HandshakeSequenceError {
245 error: Box::new(Frame::Error {
246 id: None,
247 code: WireErrorCode::MalformedFrame,
248 message,
249 unrecognized_code: None,
250 }),
251 }
252}
253
254impl Default for ClientHandshakeGate {
255 fn default() -> Self {
256 Self::new()
257 }
258}
259
260#[cfg(test)]
261#[path = "client_handshake_tests.rs"]
262mod tests;