Debian Codegraph @

third_party/rust/neqo-bin/src/server/http09.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 #![expect(clippy::unwrap_used, reason = "This is example code.")]
8
9 use std::{
10 borrow::Cow,
11 cell::RefCell,
12 collections::HashMap,
13 fmt::{self, Display, Formatter},
14 rc::Rc,
15 slice, str,
16 time::Instant,
17 };
18
19 use neqo_common::{event::Provider as _, hex, qdebug, qerror, qinfo, qwarn, Datagram};
20 use neqo_crypto::{generate_ech_keys, random, AllowZeroRtt, AntiReplay};
21 use neqo_http3::Error;
22 use neqo_transport::{
23 server::{ConnectionRef, Server, ValidateAddress},
24 ConnectionEvent, ConnectionIdGenerator, Output, State, StreamId,
25 };
26 use regex::Regex;
27
28 use super::{qns_read_response, Args};
29 use crate::{send_data::SendData, STREAM_IO_BUFFER_SIZE};
30
31 #[derive(Default)]
32 struct HttpStreamState {
33 writable: bool,
34 data_to_send: Option<SendData>,
35 }
36
37 pub struct HttpServer {
38 server: Server,
39 write_state: HashMap<StreamId, HttpStreamState>,
40 read_state: HashMap<StreamId, Vec<u8>>,
41 is_qns_test: bool,
42 regex: Regex,
43 read_buffer: Vec<u8>,
44 }
45
46 impl HttpServer {
47 pub fn new(
48 args: &Args,
49 anti_replay: AntiReplay,
50 cid_manager: Rc<RefCell<dyn ConnectionIdGenerator>>,
51 ) -> Result<Self, Error> {
52 let mut server = Server::new(
53 args.now(),
54 slice::from_ref(&args.key),
55 slice::from_ref(&args.shared.alpn),
56 anti_replay,
57 Box::new(AllowZeroRtt {}),
58 cid_manager,
59 args.shared.quic_parameters.get(&args.shared.alpn),
60 )?;
61
62 server.set_ciphers(args.get_ciphers());
63 server.set_qlog_dir(args.shared.qlog_dir.clone());
64 if args.retry {
65 server.set_validation(ValidateAddress::Always);
66 }
67 if args.ech {
68 let (sk, pk) = generate_ech_keys().map_err(|_| Error::Internal)?;
69 server
70 .enable_ech(random::<1>()[0], "public.example", &sk, &pk)
71 .map_err(|_| Error::Internal)?;
72 qinfo!("ECHConfigList: {}", hex(server.ech_config()));
73 }
74
75 let is_qns_test = args.shared.qns_test.is_some();
76 Ok(Self {
77 server,
78 write_state: HashMap::new(),
79 read_state: HashMap::new(),
80 is_qns_test,
81 regex: if is_qns_test {
82 Regex::new(r"GET +/(\S+)(?:\r)?\n").map_err(|_| Error::Internal)?
83 } else {
84 Regex::new(r"GET +/(\d+)(?:\r)?\n").map_err(|_| Error::Internal)?
85 },
86 read_buffer: vec![0; STREAM_IO_BUFFER_SIZE],
87 })
88 }
89
90 fn save_partial(&mut self, stream_id: StreamId, partial: Vec<u8>, conn: &ConnectionRef) {
91 if partial.len() < 4096 {
92 qdebug!(
93 "Saving partial URL: {}",
94 String::from_utf8(partial.clone())
95 .unwrap_or_else(|_| format!("<invalid UTF-8: {}>", hex(&partial)))
96 );
97 self.read_state.insert(stream_id, partial);
98 } else {
99 qdebug!(
100 "Giving up on partial URL {}",
101 String::from_utf8(partial.clone())
102 .unwrap_or_else(|_| format!("<invalid UTF-8: {}>", hex(&partial)))
103 );
104 conn.borrow_mut().stream_stop_sending(stream_id, 0).unwrap();
105 }
106 }
107
108 fn stream_readable(&mut self, stream_id: StreamId, conn: &ConnectionRef) {
109 if !stream_id.is_client_initiated() || !stream_id.is_bidi() {
110 qdebug!("Stream {stream_id} not client-initiated bidi, ignoring");
111 return;
112 }
113 let (sz, fin) = conn
114 .borrow_mut()
115 .stream_recv(stream_id, &mut self.read_buffer)
116 .expect("Read should succeed");
117
118 if sz == 0 {
119 if !fin {
120 qdebug!("size 0 but !fin");
121 }
122 return;
123 }
124 let read_buffer = &self.read_buffer[..sz];
125
126 let buf = self.read_state.remove(&stream_id).map_or(
127 Cow::Borrowed(read_buffer),
128 |mut existing| {
129 existing.extend_from_slice(read_buffer);
130 Cow::Owned(existing)
131 },
132 );
133
134 let Ok(msg) = str::from_utf8(&buf[..]) else {
135 self.save_partial(stream_id, buf.to_vec(), conn);
136 return;
137 };
138
139 let m = self.regex.captures(msg);
140 let Some(path) = m.and_then(|m| m.get(1)) else {
141 self.save_partial(stream_id, buf.to_vec(), conn);
142 return;
143 };
144
145 let resp: SendData = {
146 let path = path.as_str();
147 qdebug!("Path = '{path}'");
148 if self.is_qns_test {
149 match qns_read_response(path) {
150 Ok(data) => data.into(),
151 Err(e) => {
152 qerror!("Failed to read {path}: {e}");
153 b"404".to_vec().into()
154 }
155 }
156 } else {
157 let count = path.parse().unwrap();
158 SendData::zeroes(count)
159 }
160 };
161
162 if let Some(stream_state) = self.write_state.get_mut(&stream_id) {
163 match stream_state.data_to_send {
164 None => stream_state.data_to_send = Some(resp),
165 Some(_) => {
166 qdebug!("Data already set, doing nothing");
167 }
168 }
169 if stream_state.writable {
170 self.stream_writable(stream_id, conn);
171 }
172 } else {
173 self.write_state.insert(
174 stream_id,
175 HttpStreamState {
176 writable: false,
177 data_to_send: Some(resp),
178 },
179 );
180 }
181 }
182
183 fn stream_writable(&mut self, stream_id: StreamId, conn: &ConnectionRef) {
184 let Some(stream_state) = self.write_state.get_mut(&stream_id) else {
185 qwarn!("Unknown stream {stream_id}, ignoring event");
186 return;
187 };
188
189 stream_state.writable = true;
190 if let Some(resp) = &mut stream_state.data_to_send {
191 let done = resp.send(|chunk| conn.borrow_mut().stream_send(stream_id, chunk).unwrap());
192 if done {
193 conn.borrow_mut().stream_close_send(stream_id).unwrap();
194 self.write_state.remove(&stream_id);
195 } else {
196 stream_state.writable = false;
197 }
198 }
199 }
200 }
201
202 impl super::HttpServer for HttpServer {
203 fn process(&mut self, dgram: Option<Datagram<&mut [u8]>>, now: Instant) -> Output {
204 self.server.process(dgram, now)
205 }
206
207 fn process_events(&mut self, now: Instant) {
208 #[expect(
209 clippy::mutable_key_type,
210 reason = "ActiveConnectionRef::Hash doesn't access any of the interior mutable types"
211 )]
212 let active_conns = self.server.active_connections();
213 #[expect(
214 clippy::iter_over_hash_type,
215 reason = "OK to loop over active connections in an undefined order."
216 )]
217 for acr in active_conns {
218 loop {
219 let Some(event) = acr.borrow_mut().next_event() else {
220 break;
221 };
222 match event {
223 ConnectionEvent::NewStream { stream_id } => {
224 self.write_state
225 .insert(stream_id, HttpStreamState::default());
226 }
227 ConnectionEvent::RecvStreamReadable { stream_id } => {
228 self.stream_readable(stream_id, &acr);
229 }
230 ConnectionEvent::SendStreamWritable { stream_id } => {
231 self.stream_writable(stream_id, &acr);
232 }
233 ConnectionEvent::StateChange(State::Connected) => {
234 acr.connection()
235 .borrow_mut()
236 .send_ticket(now, b"hi!")
237 .unwrap();
238 }
239 ConnectionEvent::StateChange(_)
240 | ConnectionEvent::SendStreamCreatable { .. }
241 | ConnectionEvent::SendStreamComplete { .. } => (),
242 e => qwarn!("unhandled event {e:?}"),
243 }
244 }
245 }
246 }
247
248 fn has_events(&self) -> bool {
249 self.server.has_active_connections()
250 }
251 }
252
253 impl Display for HttpServer {
254 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
255 write!(f, "Http 0.9 server ")
256 }
257 }