Debian Codegraph @

third_party/rust/neqo-transport/src/connection/state.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{cmp::min, rc::Rc, time::Instant};
8
9 use neqo_common::Encoder;
10
11 use crate::{
12 frame::FrameType, packet::PacketBuilder, path::PathRef, recovery::RecoveryToken, CloseReason,
13 Error,
14 };
15
16 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
17 /// The state of the Connection.
18 pub enum State {
19 /// A newly created connection.
20 Init,
21 /// Waiting for the first Initial packet.
22 WaitInitial,
23 /// Waiting to confirm which version was selected.
24 /// For a client, this is confirmed when a CRYPTO frame is received;
25 /// the version of the packet determines the version.
26 /// For a server, this is confirmed when transport parameters are
27 /// received and processed.
28 WaitVersion,
29 /// Exchanging Handshake packets.
30 Handshaking,
31 Connected,
32 Confirmed,
33 Closing {
34 error: CloseReason,
35 timeout: Instant,
36 },
37 Draining {
38 error: CloseReason,
39 timeout: Instant,
40 },
41 Closed(CloseReason),
42 }
43
44 impl State {
45 #[must_use]
46 pub const fn connected(&self) -> bool {
47 matches!(self, Self::Connected | Self::Confirmed)
48 }
49
50 #[must_use]
51 pub const fn closed(&self) -> bool {
52 matches!(
53 self,
54 Self::Closing { .. } | Self::Draining { .. } | Self::Closed(_)
55 )
56 }
57
58 #[must_use]
59 pub const fn error(&self) -> Option<&CloseReason> {
60 if let Self::Closing { error, .. } | Self::Draining { error, .. } | Self::Closed(error) =
61 self
62 {
63 Some(error)
64 } else {
65 None
66 }
67 }
68
69 #[must_use]
70 pub const fn closing(&self) -> bool {
71 matches!(self, Self::Closing { .. } | Self::Draining { .. })
72 }
73 }
74
75 #[derive(Debug, Clone)]
76 pub struct ClosingFrame {
77 path: PathRef,
78 error: CloseReason,
79 frame_type: FrameType,
80 reason_phrase: Vec<u8>,
81 }
82
83 impl ClosingFrame {
84 fn new(
85 path: PathRef,
86 error: CloseReason,
87 frame_type: FrameType,
88 message: impl AsRef<str>,
89 ) -> Self {
90 let reason_phrase = message.as_ref().as_bytes().to_vec();
91 Self {
92 path,
93 error,
94 frame_type,
95 reason_phrase,
96 }
97 }
98
99 pub const fn path(&self) -> &PathRef {
100 &self.path
101 }
102
103 pub fn sanitize(&self) -> Option<Self> {
104 if let CloseReason::Application(_) = self.error {
105 // The default CONNECTION_CLOSE frame that is sent when an application
106 // error code needs to be sent in an Initial or Handshake packet.
107 Some(Self {
108 path: Rc::clone(&self.path),
109 error: CloseReason::Transport(Error::ApplicationError),
110 frame_type: FrameType::Padding,
111 reason_phrase: Vec::new(),
112 })
113 } else {
114 None
115 }
116 }
117
118 /// Length of a closing frame with a truncated `reason_length`. Allow 8 bytes for the reason
119 /// phrase to ensure that if it needs to be truncated there is still at least a few bytes of
120 /// the value.
121 pub const MIN_LENGTH: usize = 1 + 8 + 8 + 2 + 8;
122
123 pub fn write_frame(&self, builder: &mut PacketBuilder) {
124 if builder.remaining() < Self::MIN_LENGTH {
125 return;
126 }
127 match &self.error {
128 CloseReason::Transport(e) => {
129 builder.encode_varint(FrameType::ConnectionCloseTransport);
130 builder.encode_varint(e.code());
131 builder.encode_varint(self.frame_type);
132 }
133 CloseReason::Application(code) => {
134 builder.encode_varint(FrameType::ConnectionCloseApplication);
135 builder.encode_varint(*code);
136 }
137 }
138 // Truncate the reason phrase if it doesn't fit. As we send this frame in
139 // multiple packet number spaces, limit the overall size to 256.
140 let available = min(256, builder.remaining());
141 let reason = if available < Encoder::vvec_len(self.reason_phrase.len()) {
142 &self.reason_phrase[..available - 2]
143 } else {
144 &self.reason_phrase
145 };
146 builder.encode_vvec(reason);
147 }
148 }
149
150 /// `StateSignaling` manages whether we need to send `HANDSHAKE_DONE` and `CONNECTION_CLOSE`.
151 /// Valid state transitions are:
152 /// * Idle -> `HandshakeDone`: at the server when the handshake completes
153 /// * `HandshakeDone` -> Idle: when a `HANDSHAKE_DONE` frame is sent
154 /// * Idle/HandshakeDone -> Closing/Draining: when closing or draining
155 /// * Closing/Draining -> `CloseSent`: after sending `CONNECTION_CLOSE`
156 /// * `CloseSent` -> Closing: any time a new `CONNECTION_CLOSE` is needed
157 /// * -> Reset: from any state in case of a stateless reset
158 #[derive(Debug, Clone)]
159 pub enum StateSignaling {
160 Idle,
161 HandshakeDone,
162 /// These states save the frame that needs to be sent.
163 Closing(ClosingFrame),
164 Draining(ClosingFrame),
165 /// This state saves the frame that might need to be sent again.
166 /// If it is `None`, then we are draining and don't send.
167 CloseSent(Option<ClosingFrame>),
168 Reset,
169 }
170
171 impl StateSignaling {
172 pub fn handshake_done(&mut self) {
173 if !matches!(self, Self::Idle) {
174 return;
175 }
176 *self = Self::HandshakeDone;
177 }
178
179 pub fn write_done(&mut self, builder: &mut PacketBuilder) -> Option<RecoveryToken> {
180 (matches!(self, Self::HandshakeDone) && builder.remaining() >= 1).then(|| {
181 *self = Self::Idle;
182 builder.encode_varint(FrameType::HandshakeDone);
183 RecoveryToken::HandshakeDone
184 })
185 }
186
187 pub fn close(
188 &mut self,
189 path: PathRef,
190 error: CloseReason,
191 frame_type: FrameType,
192 message: impl AsRef<str>,
193 ) {
194 if !matches!(self, Self::Reset) {
195 *self = Self::Closing(ClosingFrame::new(path, error, frame_type, message));
196 }
197 }
198
199 pub fn drain(
200 &mut self,
201 path: PathRef,
202 error: CloseReason,
203 frame_type: FrameType,
204 message: impl AsRef<str>,
205 ) {
206 if !matches!(self, Self::Reset) {
207 *self = Self::Draining(ClosingFrame::new(path, error, frame_type, message));
208 }
209 }
210
211 /// If a close is pending, take a frame.
212 pub fn close_frame(&mut self) -> Option<ClosingFrame> {
213 match self {
214 Self::Closing(frame) => {
215 // When we are closing, we might need to send the close frame again.
216 let res = Some(frame.clone());
217 *self = Self::CloseSent(Some(frame.clone()));
218 res
219 }
220 Self::Draining(frame) => {
221 // When we are draining, just send once.
222 let res = Some(frame.clone());
223 *self = Self::CloseSent(None);
224 res
225 }
226 _ => None,
227 }
228 }
229
230 /// If a close can be sent again, prepare to send it again.
231 pub fn send_close(&mut self) {
232 if let Self::CloseSent(Some(frame)) = self {
233 *self = Self::Closing(frame.clone());
234 }
235 }
236
237 /// We just got a stateless reset. Terminate.
238 pub fn reset(&mut self) {
239 *self = Self::Reset;
240 }
241 }