use crate::error::Error;
use crate::websocket_connection_shared::SharedConnectionState;
use crate::websocket_connection_types::{ConnectionOutput, RandomSource};
use crate::websocket_frame::Frame;
pub(crate) trait FramePolicy {
fn verify_frame_masking(&self, masked: bool) -> Result<(), Error>;
fn encode_and_send(&mut self, frame: &Frame, shared: &mut SharedConnectionState);
}
pub(crate) struct ClientFramePolicy<R: RandomSource> {
random: R,
}
impl<R: RandomSource> ClientFramePolicy<R> {
pub(crate) fn new(random: R) -> Self {
Self { random }
}
pub(crate) fn nonce(&mut self) -> [u8; 16] {
self.random.nonce()
}
}
impl<R: RandomSource> FramePolicy for ClientFramePolicy<R> {
fn verify_frame_masking(&self, masked: bool) -> Result<(), Error> {
if masked {
return Err(Error::protocol_violation("masked server frame"));
}
Ok(())
}
fn encode_and_send(&mut self, frame: &Frame, shared: &mut SharedConnectionState) {
let masking_key = self.random.masking_key();
let encoded = frame.encode(masking_key);
shared.enqueue_output(ConnectionOutput::SendData(encoded));
}
}
pub(crate) struct ServerFramePolicy;
impl FramePolicy for ServerFramePolicy {
fn verify_frame_masking(&self, masked: bool) -> Result<(), Error> {
if !masked {
return Err(Error::protocol_violation("unmasked client frame"));
}
Ok(())
}
fn encode_and_send(&mut self, frame: &Frame, shared: &mut SharedConnectionState) {
let encoded = frame.encode_unmasked();
shared.enqueue_output(ConnectionOutput::SendData(encoded));
}
}