| 1 | // Copyright (c) 2019 Parity Technologies (UK) Ltd. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 |
| 4 | // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT |
| 5 | // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | // option. All files in the project carrying such notice may not be copied, |
| 7 | // modified, or distributed except according to those terms. |
| 8 | |
| 9 | //! Deflate compression extension mostly conformant with [RFC 7692][rfc7692]. |
| 10 | //! |
| 11 | //! [rfc7692]: https://tools.ietf.org/html/rfc7692 |
| 12 | |
| 13 | use crate::{ |
| 14 | as_u64, |
| 15 | base::{Header, OpCode}, |
| 16 | connection::Mode, |
| 17 | extension::{Extension, Param}, |
| 18 | BoxedError, Storage, |
| 19 | }; |
| 20 | use flate2::{write::DeflateDecoder, Compress, Compression, FlushCompress, Status}; |
| 21 | use std::{ |
| 22 | convert::TryInto, |
| 23 | io::{self, Write}, |
| 24 | mem, |
| 25 | }; |
| 26 | |
| 27 | const SERVER_NO_CONTEXT_TAKEOVER: &str = "server_no_context_takeover"; |
| 28 | const SERVER_MAX_WINDOW_BITS: &str = "server_max_window_bits"; |
| 29 | |
| 30 | const CLIENT_NO_CONTEXT_TAKEOVER: &str = "client_no_context_takeover"; |
| 31 | const CLIENT_MAX_WINDOW_BITS: &str = "client_max_window_bits"; |
| 32 | |
| 33 | /// The deflate extension type. |
| 34 | /// |
| 35 | /// The extension does currently not support max. window bits other than the |
| 36 | /// default, which is 15 and will ask for no context takeover during handshake. |
| 37 | #[derive(Debug)] |
| 38 | pub struct Deflate { |
| 39 | mode: Mode, |
| 40 | enabled: bool, |
| 41 | buffer: Vec<u8>, |
| 42 | params: Vec<Param<'static>>, |
| 43 | our_max_window_bits: u8, |
| 44 | their_max_window_bits: u8, |
| 45 | await_last_fragment: bool, |
| 46 | } |
| 47 | |
| 48 | impl Deflate { |
| 49 | /// Create a new deflate extension either on client or server side. |
| 50 | pub fn new(mode: Mode) -> Self { |
| 51 | let params = match mode { |
| 52 | Mode::Server => Vec::new(), |
| 53 | Mode::Client => { |
| 54 | let mut params = Vec::new(); |
| 55 | params.push(Param::new(SERVER_NO_CONTEXT_TAKEOVER)); |
| 56 | params.push(Param::new(CLIENT_NO_CONTEXT_TAKEOVER)); |
| 57 | params.push(Param::new(CLIENT_MAX_WINDOW_BITS)); |
| 58 | params |
| 59 | } |
| 60 | }; |
| 61 | Deflate { |
| 62 | mode, |
| 63 | enabled: false, |
| 64 | buffer: Vec::new(), |
| 65 | params, |
| 66 | our_max_window_bits: 15, |
| 67 | their_max_window_bits: 15, |
| 68 | await_last_fragment: false, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Set the server's max. window bits. |
| 73 | /// |
| 74 | /// The value must be within 9 ..= 15. |
| 75 | /// The extension must be in client mode. |
| 76 | /// |
| 77 | /// By including this parameter, a client limits the LZ77 sliding window |
| 78 | /// size that the server will use to compress messages. A server accepts |
| 79 | /// by including the "server_max_window_bits" extension parameter in the |
| 80 | /// response with the same or smaller value as the offer. |
| 81 | pub fn set_max_server_window_bits(&mut self, max: u8) { |
| 82 | assert!(self.mode == Mode::Client, "setting max. server window bits requires client mode"); |
| 83 | assert!(max > 8 && max <= 15, "max. server window bits have to be within 9 ..= 15"); |
| 84 | self.their_max_window_bits = max; // upper bound of the server's window |
| 85 | let mut p = Param::new(SERVER_MAX_WINDOW_BITS); |
| 86 | p.set_value(Some(max.to_string())); |
| 87 | self.params.push(p) |
| 88 | } |
| 89 | |
| 90 | /// Set the client's max. window bits. |
| 91 | /// |
| 92 | /// The value must be within 9 ..= 15. |
| 93 | /// The extension must be in client mode. |
| 94 | /// |
| 95 | /// The parameter informs the server that even if it doesn't include the |
| 96 | /// "client_max_window_bits" extension parameter in the response with a |
| 97 | /// value greater than the one in the negotiation offer or if it doesn't |
| 98 | /// include the extension parameter at all, the client is not going to |
| 99 | /// use an LZ77 sliding window size greater than one given here. |
| 100 | /// The server may also respond with a smaller value which allows the client |
| 101 | /// to reduce its sliding window even more. |
| 102 | pub fn set_max_client_window_bits(&mut self, max: u8) { |
| 103 | assert!(self.mode == Mode::Client, "setting max. client window bits requires client mode"); |
| 104 | assert!(max > 8 && max <= 15, "max. client window bits have to be within 9 ..= 15"); |
| 105 | self.our_max_window_bits = max; // upper bound of the client's window |
| 106 | if let Some(p) = self.params.iter_mut().find(|p| p.name() == CLIENT_MAX_WINDOW_BITS) { |
| 107 | p.set_value(Some(max.to_string())); |
| 108 | } else { |
| 109 | let mut p = Param::new(CLIENT_MAX_WINDOW_BITS); |
| 110 | p.set_value(Some(max.to_string())); |
| 111 | self.params.push(p) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn set_their_max_window_bits(&mut self, p: &Param, expected: Option<u8>) -> Result<(), ()> { |
| 116 | if let Some(Ok(v)) = p.value().map(|s| s.parse::<u8>()) { |
| 117 | if v < 8 || v > 15 { |
| 118 | log::debug!("invalid {}: {} (expected range: 8 ..= 15)", p.name(), v); |
| 119 | return Err(()); |
| 120 | } |
| 121 | if let Some(x) = expected { |
| 122 | if v > x { |
| 123 | log::debug!("invalid {}: {} (expected: {} <= {})", p.name(), v, v, x); |
| 124 | return Err(()); |
| 125 | } |
| 126 | } |
| 127 | self.their_max_window_bits = std::cmp::max(9, v); |
| 128 | } |
| 129 | Ok(()) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl Extension for Deflate { |
| 134 | fn name(&self) -> &str { |
| 135 | "permessage-deflate" |
| 136 | } |
| 137 | |
| 138 | fn is_enabled(&self) -> bool { |
| 139 | self.enabled |
| 140 | } |
| 141 | |
| 142 | fn params(&self) -> &[Param] { |
| 143 | &self.params |
| 144 | } |
| 145 | |
| 146 | fn configure(&mut self, params: &[Param]) -> Result<(), BoxedError> { |
| 147 | match self.mode { |
| 148 | Mode::Server => { |
| 149 | self.params.clear(); |
| 150 | for p in params { |
| 151 | log::trace!("configure server with: {}", p); |
| 152 | match p.name() { |
| 153 | CLIENT_MAX_WINDOW_BITS => { |
| 154 | if self.set_their_max_window_bits(&p, None).is_err() { |
| 155 | // we just accept the client's offer as is => no need to reply |
| 156 | return Ok(()); |
| 157 | } |
| 158 | } |
| 159 | SERVER_MAX_WINDOW_BITS => { |
| 160 | if let Some(Ok(v)) = p.value().map(|s| s.parse::<u8>()) { |
| 161 | // The RFC allows 8 to 15 bits, but due to zlib limitations we |
| 162 | // only support 9 to 15. |
| 163 | if v < 9 || v > 15 { |
| 164 | log::debug!("unacceptable server_max_window_bits: {}", v); |
| 165 | return Ok(()); |
| 166 | } |
| 167 | let mut x = Param::new(SERVER_MAX_WINDOW_BITS); |
| 168 | x.set_value(Some(v.to_string())); |
| 169 | self.params.push(x); |
| 170 | self.our_max_window_bits = v; |
| 171 | } else { |
| 172 | log::debug!("invalid server_max_window_bits: {:?}", p.value()); |
| 173 | return Ok(()); |
| 174 | } |
| 175 | } |
| 176 | CLIENT_NO_CONTEXT_TAKEOVER => self.params.push(Param::new(CLIENT_NO_CONTEXT_TAKEOVER)), |
| 177 | SERVER_NO_CONTEXT_TAKEOVER => self.params.push(Param::new(SERVER_NO_CONTEXT_TAKEOVER)), |
| 178 | _ => { |
| 179 | log::debug!("{}: unknown parameter: {}", self.name(), p.name()); |
| 180 | return Ok(()); |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | Mode::Client => { |
| 186 | let mut server_no_context_takeover = false; |
| 187 | for p in params { |
| 188 | log::trace!("configure client with: {}", p); |
| 189 | match p.name() { |
| 190 | SERVER_NO_CONTEXT_TAKEOVER => server_no_context_takeover = true, |
| 191 | CLIENT_NO_CONTEXT_TAKEOVER => {} // must be supported |
| 192 | SERVER_MAX_WINDOW_BITS => { |
| 193 | let expected = Some(self.their_max_window_bits); |
| 194 | if self.set_their_max_window_bits(&p, expected).is_err() { |
| 195 | return Ok(()); |
| 196 | } |
| 197 | } |
| 198 | CLIENT_MAX_WINDOW_BITS => { |
| 199 | if let Some(Ok(v)) = p.value().map(|s| s.parse::<u8>()) { |
| 200 | if v < 8 || v > 15 { |
| 201 | log::debug!("unacceptable client_max_window_bits: {}", v); |
| 202 | return Ok(()); |
| 203 | } |
| 204 | use std::cmp::{max, min}; |
| 205 | // Due to zlib limitations we have to use 9 as a lower bound |
| 206 | // here, even if the server allowed us to go down to 8 bits. |
| 207 | self.our_max_window_bits = min(self.our_max_window_bits, max(9, v)); |
| 208 | } |
| 209 | } |
| 210 | _ => { |
| 211 | log::debug!("{}: unknown parameter: {}", self.name(), p.name()); |
| 212 | return Ok(()); |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | if !server_no_context_takeover { |
| 217 | log::debug!("{}: server did not confirm no context takeover", self.name()); |
| 218 | return Ok(()); |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | self.enabled = true; |
| 223 | Ok(()) |
| 224 | } |
| 225 | |
| 226 | fn reserved_bits(&self) -> (bool, bool, bool) { |
| 227 | (true, false, false) |
| 228 | } |
| 229 | |
| 230 | fn decode(&mut self, header: &mut Header, data: &mut Vec<u8>) -> Result<(), BoxedError> { |
| 231 | if data.is_empty() { |
| 232 | return Ok(()); |
| 233 | } |
| 234 | |
| 235 | match header.opcode() { |
| 236 | OpCode::Binary | OpCode::Text if header.is_rsv1() => { |
| 237 | if !header.is_fin() { |
| 238 | self.await_last_fragment = true; |
| 239 | log::trace!("deflate: not decoding {}; awaiting last fragment", header); |
| 240 | return Ok(()); |
| 241 | } |
| 242 | log::trace!("deflate: decoding {}", header) |
| 243 | } |
| 244 | OpCode::Continue if header.is_fin() && self.await_last_fragment => { |
| 245 | self.await_last_fragment = false; |
| 246 | log::trace!("deflate: decoding {}", header) |
| 247 | } |
| 248 | _ => { |
| 249 | log::trace!("deflate: not decoding {}", header); |
| 250 | return Ok(()); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // Restore LEN and NLEN: |
| 255 | data.extend_from_slice(&[0, 0, 0xFF, 0xFF]); // cf. RFC 7692, 7.2.2 |
| 256 | |
| 257 | self.buffer.clear(); |
| 258 | let mut decoder = DeflateDecoder::new(&mut self.buffer); |
| 259 | decoder.write_all(&data)?; |
| 260 | decoder.finish()?; |
| 261 | mem::swap(data, &mut self.buffer); |
| 262 | |
| 263 | header.set_rsv1(false); |
| 264 | header.set_payload_len(data.len()); |
| 265 | |
| 266 | Ok(()) |
| 267 | } |
| 268 | |
| 269 | fn encode(&mut self, header: &mut Header, data: &mut Storage) -> Result<(), BoxedError> { |
| 270 | if data.as_ref().is_empty() { |
| 271 | return Ok(()); |
| 272 | } |
| 273 | |
| 274 | if let OpCode::Binary | OpCode::Text = header.opcode() { |
| 275 | log::trace!("deflate: encoding {}", header) |
| 276 | } else { |
| 277 | log::trace!("deflate: not encoding {}", header); |
| 278 | return Ok(()); |
| 279 | } |
| 280 | |
| 281 | self.buffer.clear(); |
| 282 | self.buffer.reserve(data.as_ref().len()); |
| 283 | |
| 284 | let mut encoder = Compress::new_with_window_bits(Compression::fast(), false, self.our_max_window_bits); |
| 285 | |
| 286 | // Compress all input bytes. |
| 287 | while encoder.total_in() < as_u64(data.as_ref().len()) { |
| 288 | let i: usize = encoder.total_in().try_into()?; |
| 289 | match encoder.compress_vec(&data.as_ref()[i..], &mut self.buffer, FlushCompress::None)? { |
| 290 | Status::BufError => self.buffer.reserve(4096), |
| 291 | Status::Ok => continue, |
| 292 | Status::StreamEnd => break, |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // We need to append an empty deflate block if not there yet (RFC 7692, 7.2.1). |
| 297 | while !self.buffer.ends_with(&[0, 0, 0xFF, 0xFF]) { |
| 298 | self.buffer.reserve(5); // Make sure there is room for the trailing end bytes. |
| 299 | match encoder.compress_vec(&[], &mut self.buffer, FlushCompress::Sync)? { |
| 300 | Status::Ok => continue, |
| 301 | Status::BufError => continue, // more capacity is reserved above |
| 302 | Status::StreamEnd => break, |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | // If we still have not seen the empty deflate block appended, something is wrong. |
| 307 | if !self.buffer.ends_with(&[0, 0, 0xFF, 0xFF]) { |
| 308 | log::error!("missing 00 00 FF FF"); |
| 309 | return Err(io::Error::new(io::ErrorKind::Other, "missing 00 00 FF FF").into()); |
| 310 | } |
| 311 | |
| 312 | self.buffer.truncate(self.buffer.len() - 4); // Remove 00 00 FF FF; cf. RFC 7692, 7.2.1 |
| 313 | |
| 314 | if let Storage::Owned(d) = data { |
| 315 | mem::swap(d, &mut self.buffer) |
| 316 | } else { |
| 317 | *data = Storage::Owned(mem::take(&mut self.buffer)) |
| 318 | } |
| 319 | header.set_rsv1(true); |
| 320 | header.set_payload_len(data.as_ref().len()); |
| 321 | Ok(()) |
| 322 | } |
| 323 | } |