1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// http://docs.haproxy.org/2.7/configuration.html#4.1

use std::collections::HashMap;
use std::net::Ipv4Addr;

use super::section::borrowed::Section;
use crate::section::{AddressRef, HostRef};
use crate::line::borrowed::Line; 

mod global;
pub use global::Global;
mod frontend;
pub use frontend::Frontend;
mod backend;
pub use backend::Backend;
mod listen;
pub use listen::Listen;
mod userlist;
pub use userlist::{Userlist, User, Group, Password};
mod error;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Acl {
    pub name: String,
    pub rule: String,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Bind {
    pub addr: Address,
    pub config: Option<String>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Server {
    pub name: String,
    pub addr: Address,
    pub option: Option<String>,
}

/// Owned variant of [`AddressRef`]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Address {
    pub host: Host,
    pub port: Option<u16>,
}

impl From<&AddressRef<'_>> for Address {
    fn from(r: &AddressRef<'_>) -> Self {
        Address {
            host: Host::from(&r.host),
            port: r.port,
        }
    }
}

/// Owned variant of [`HostRef`]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum Host {
    Ipv4(Ipv4Addr),
    Dns(String),
    Wildcard,
}

impl From<&HostRef<'_>> for Host {
    fn from(h: &HostRef<'_>) -> Self {
        match h {
            HostRef::Ipv4(a) => Host::Ipv4(*a),
            HostRef::Dns(s) => Host::Dns((*s).to_string()),
            HostRef::Wildcard => Host::Wildcard,
        }
    }
}

pub type Name = String;

/// A haproxy config where everything except config and options are fully typed. Can be created
/// from a list of [`Sections`](Section) using [`TryFrom`]. This type does not borrow its input.
///
/// Returns Err if the config contains errors or sections or grammar we don not supported. For
/// example conditional blocks.
///
/// # Examples
/// Build a config from a list of just parsed sections.
/// ```
/// use haproxy_config::parse_sections;
/// use haproxy_config::Config;
///
/// let file = include_str!("../tests/medium_haproxy.cfg");
/// let sections = parse_sections(file).unwrap();
///
/// let config = Config::try_from(&sections).unwrap();
/// ```
///
/// The same as above however we filter out unknown lines that
/// would result in an error. This only works for lines
/// above the first section as anything unknown after a section starts
/// is parsed as a config option.
/// ```
/// use haproxy_config::parse_sections;
/// use haproxy_config::{Config, section::borrowed::Section};
///
/// let file = include_str!("../tests/unsupported/nonesens.cfg");
/// let sections = dbg!(parse_sections(file).unwrap());
/// let supported_sections: Vec<_> = sections.into_iter().filter(|s| !std::matches!(s,
/// Section::UnknownLine{..})).collect();
///
/// let config = Config::try_from(&supported_sections).unwrap();
/// 
/// // `nonesens.cfg` contained the line `this will be seen as config unfortunatly`
/// // its stats frontend. This is not recognised as an error unfortunatly:
/// assert_eq!(config.frontends
///     .get("stats")
///     .unwrap()
///     .config.get("this")
///     .unwrap()
///     .as_ref()
///     .unwrap(), "will be seen as a config value unfortunatly");
/// ```
#[derive(Debug)]
pub struct Config {
    pub global: Global,
    pub default: Default,
    pub frontends: HashMap<Name, Frontend>,
    pub backends: HashMap<Name, Backend>,
    pub listen: HashMap<Name, Listen>,
    pub userlists: HashMap<Name, Userlist>,
}

impl<'a> TryFrom<&'a Vec<Section<'a>>> for Config {
    type Error = error::Error;

    fn try_from(vec: &'a Vec<Section<'a>>) -> Result<Self, Self::Error> {
        Config::try_from(vec.as_slice())
    }
}

impl<'a> TryFrom<&'a [Section<'a>]> for Config {
    type Error = error::Error;

    fn try_from(entries: &'a [Section<'a>]) -> Result<Self, Self::Error> {
        let unknown_lines: Vec<_> = entries
            .iter()
            .filter_map(|l| match l {
                Section::UnknownLine { line } => Some(*line),
                _ => None,
            })
            .collect();

        if !unknown_lines.is_empty() {
            return Err(error::Error::unknown_lines(unknown_lines));
        }

        Ok(Config {
            global: Global::try_from(entries)?,
            default: Default::try_from(entries)?,
            frontends: Frontend::parse_multiple(entries)?,
            backends: Backend::parse_multiple(entries)?,
            listen: Listen::parse_multiple(entries)?,
            userlists: Userlist::parse_multiple(entries)?,
        })
    }
}


#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Default {
    pub proxy: Option<String>,
    pub config: HashMap<String, Option<String>>,
    pub options: HashMap<String, Option<String>>,
}

impl<'a> TryFrom<&'a [Section<'a>]> for Default {
    type Error = error::Error;

    fn try_from(entries: &'a [Section<'_>]) -> Result<Self, Self::Error> {
        let default_entries: Vec<_> = entries
            .iter()
            .filter(|e| matches!(e, Section::Default { .. }))
            .collect();

        if default_entries.len() > 1 {
            return Err(error::Error::multiple_default_entries(default_entries));
        }

        let Some(Section::Default{ proxy, lines, ..}) = default_entries.first() else {
            return Ok(Default::default());
        };

        let mut config = HashMap::new();
        let mut options = HashMap::new();
        let mut other = Vec::new();
        for line in lines
            .iter()
            .filter(|l| !matches!(l, Line::Blank | Line::Comment(_)))
        {
            match line {
                Line::Config { key, value, .. } => {
                    let key = (*key).to_string();
                    let value = value.map(ToOwned::to_owned);
                    config.insert(key, value);
                }
                Line::Option {
                    keyword: key,
                    value,
                    ..
                } => {
                    let key = (*key).to_string();
                    let value = value.map(ToOwned::to_owned);
                    options.insert(key, value);
                }
                o => other.push(o),
            }
        }

        if !other.is_empty() {
            return Err(error::Error::wrong_default_lines(other));
        }

        Ok(Default {
            proxy: proxy.map(ToOwned::to_owned),
            config,
            options,
        })
    }
}