puffin/
put_registry.rs

1use std::collections::HashMap;
2use std::fmt;
3
4use crate::agent::AgentDescriptor;
5use crate::claims::GlobalClaimList;
6use crate::error::Error;
7use crate::protocol::{ProtocolBehavior, ProtocolTypes};
8use crate::put::{Put, PutDescriptor, PutOptions};
9
10// FIXME TCP_PUT should be defined in the tlspuffin package
11//
12//     The TCP PUT is specific to TLS and is therefore defined in the `tlspuffin` package. However,
13//     we expose it here in `puffin` so that the generic CLI is able to provide the `tcp` command.
14//
15//     Once we factor out the `tcp` command, we can move this definition into `tlspuffin`.
16pub const TCP_PUT: &str = "tcp";
17
18/// Registry for [Factories](Factory). An instance of this is usually defined statically and then
19/// used throughout the fuzzer.
20pub struct PutRegistry<PB> {
21    factories: HashMap<String, Box<dyn Factory<PB>>>,
22    default_put: PutDescriptor,
23}
24
25impl<PB> PutRegistry<PB> {
26    #[must_use]
27    pub fn set_default_factory(&mut self, name: &str) -> Result<(), String> {
28        if !self.factories.contains_key(name) {
29            return Err(format!("PUT {} not found in registry", name));
30        }
31        self.default_put.factory = String::from(name);
32        Ok(())
33    }
34
35    #[must_use]
36    pub fn set_default(&mut self, default: PutDescriptor) -> Result<(), String> {
37        self.set_default_factory(&default.factory)?;
38        self.set_default_options(default.options);
39        Ok(())
40    }
41
42    pub fn set_default_options(&mut self, put_config: PutOptions) {
43        self.default_put.options = put_config;
44    }
45
46    pub fn default_put_name(&self) -> &str {
47        &self.default_put.factory
48    }
49
50    pub fn default_put_options(&self) -> &PutOptions {
51        &self.default_put.options
52    }
53
54    pub fn default_put_descriptor(&self) -> PutDescriptor {
55        PutDescriptor::new(self.default_put_name(), self.default_put_options().clone())
56    }
57}
58
59impl<PB: ProtocolBehavior> PartialEq for PutRegistry<PB> {
60    fn eq(&self, other: &Self) -> bool {
61        self.default_put == other.default_put
62            && self.factories.len() == other.factories.len()
63            && self
64                .factories
65                .keys()
66                .all(|id| other.factories.contains_key(id))
67    }
68}
69
70impl<PB: ProtocolBehavior> fmt::Debug for PutRegistry<PB> {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("PutRegistry (default only)")
73            .field("default factory", &self.default().name())
74            .field("default options", &self.default_put().options)
75            .finish()
76    }
77}
78
79impl<PB: ProtocolBehavior> PutRegistry<PB> {
80    pub fn new<SI, I>(puts: I, default_put: PutDescriptor) -> Self
81    where
82        SI: Into<String>,
83        I: IntoIterator<Item = (SI, Box<dyn Factory<PB>>)>,
84    {
85        let result = Self {
86            factories: puts
87                .into_iter()
88                .map(|(id, f)| (Into::<String>::into(id), f))
89                .collect(),
90            default_put,
91        };
92
93        // check that the default PUT is actually in the registry
94        let _ = result.find_by_id(result.default_put_name());
95
96        result
97    }
98
99    #[must_use]
100    pub fn default(&self) -> &dyn Factory<PB> {
101        self.find_by_id(&self.default_put.factory)
102            .unwrap_or_else(|| {
103                panic!(
104                    "default PUT {} is not in registry",
105                    &self.default_put.factory
106                )
107            })
108    }
109
110    pub fn default_put(&self) -> &PutDescriptor {
111        &self.default_put
112    }
113
114    pub fn puts(&self) -> impl Iterator<Item = (&str, &dyn Factory<PB>)> {
115        self.factories
116            .iter()
117            .map(|(n, f)| (n.as_str(), f.to_owned().as_ref()))
118    }
119
120    pub fn find_by_id<S: AsRef<str>>(&self, id: S) -> Option<&dyn Factory<PB>> {
121        self.factories
122            .get(id.as_ref())
123            .map(|f| f.to_owned().as_ref())
124    }
125
126    pub fn determinism_reseed_all_factories(&self) {
127        log::debug!("[RNG] reseed all PUT factories");
128        for factory in self.factories.values() {
129            factory.rng_reseed();
130        }
131    }
132}
133
134impl<PB: ProtocolBehavior> Clone for PutRegistry<PB> {
135    fn clone(&self) -> Self {
136        Self::new(
137            self.factories
138                .iter()
139                .map(|(n, f)| (n.clone(), f.clone_factory())),
140            self.default_put.clone(),
141        )
142    }
143}
144
145/// Factory for instantiating programs-under-test.
146pub trait Factory<PB: ProtocolBehavior> {
147    fn create(
148        &self,
149        agent_descriptor: &AgentDescriptor<
150            <<PB as ProtocolBehavior>::ProtocolTypes as ProtocolTypes>::PUTConfig,
151        >,
152        claims: &GlobalClaimList<PB::Claim>,
153        options: &PutOptions,
154    ) -> Result<Box<dyn Put<PB>>, Error>;
155
156    fn name(&self) -> String;
157    fn versions(&self) -> Vec<(String, String)>;
158
159    fn supports(&self, capability: &str) -> bool;
160
161    fn clone_factory(&self) -> Box<dyn Factory<PB>>;
162
163    fn rng_reseed(&self) {
164        log::warn!("[RNG] reseed failed ({}): not supported", self.name());
165    }
166}