summaryrefslogtreecommitdiff
path: root/crates/common/src/addresses.rs
blob: d56385b10e0c95467b116e928fa4ced76b0f83c0 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::borrow::Cow;

use directory::Directory;
use utils::config::{utils::AsKey, Config};

use crate::{
    config::smtp::session::AddressMapping,
    expr::{
        functions::ResolveVariable, if_block::IfBlock, tokenizer::TokenMap, Variable, V_RECIPIENT,
    },
    Server,
};

impl Server {
    pub async fn email_to_ids(
        &self,
        directory: &Directory,
        email: &str,
        session_id: u64,
    ) -> trc::Result<Vec<u32>> {
        let mut address = self
            .core
            .smtp
            .session
            .rcpt
            .subaddressing
            .to_subaddress(self, email, session_id)
            .await;

        for _ in 0..2 {
            let result = directory.email_to_ids(address.as_ref()).await?;

            if !result.is_empty() {
                return Ok(result);
            } else if let Some(catch_all) = self
                .core
                .smtp
                .session
                .rcpt
                .catch_all
                .to_catch_all(self, email, session_id)
                .await
            {
                address = catch_all;
            } else {
                break;
            }
        }

        Ok(vec![])
    }

    pub async fn rcpt(
        &self,
        directory: &Directory,
        email: &str,
        session_id: u64,
    ) -> trc::Result<bool> {
        // Expand subaddress
        let mut address = self
            .core
            .smtp
            .session
            .rcpt
            .subaddressing
            .to_subaddress(self, email, session_id)
            .await;

        for _ in 0..2 {
            if directory.rcpt(address.as_ref()).await? {
                return Ok(true);
            } else if let Some(catch_all) = self
                .core
                .smtp
                .session
                .rcpt
                .catch_all
                .to_catch_all(self, email, session_id)
                .await
            {
                address = catch_all;
            } else {
                break;
            }
        }

        Ok(false)
    }

    pub async fn vrfy(
        &self,
        directory: &Directory,
        address: &str,
        session_id: u64,
    ) -> trc::Result<Vec<String>> {
        directory
            .vrfy(
                self.core
                    .smtp
                    .session
                    .rcpt
                    .subaddressing
                    .to_subaddress(self, address, session_id)
                    .await
                    .as_ref(),
            )
            .await
    }

    pub async fn expn(
        &self,
        directory: &Directory,
        address: &str,
        session_id: u64,
    ) -> trc::Result<Vec<String>> {
        directory
            .expn(
                self.core
                    .smtp
                    .session
                    .rcpt
                    .subaddressing
                    .to_subaddress(self, address, session_id)
                    .await
                    .as_ref(),
            )
            .await
    }
}

impl AddressMapping {
    pub fn parse(config: &mut Config, key: impl AsKey) -> Self {
        let key = key.as_key();
        if let Some(value) = config.value(key.as_str()) {
            match value {
                "true" => AddressMapping::Enable,
                "false" => AddressMapping::Disable,
                _ => {
                    config.new_parse_error(
                        key,
                        format!("Invalid value for address mapping {value:?}",),
                    );
                    AddressMapping::Disable
                }
            }
        } else if let Some(if_block) = IfBlock::try_parse(
            config,
            key,
            &TokenMap::default().with_variables_map([
                ("address", V_RECIPIENT),
                ("email", V_RECIPIENT),
                ("rcpt", V_RECIPIENT),
            ]),
        ) {
            AddressMapping::Custom(if_block)
        } else {
            AddressMapping::Enable
        }
    }
}

struct Address<'x>(&'x str);

impl ResolveVariable for Address<'_> {
    fn resolve_variable(&self, _: u32) -> crate::expr::Variable {
        Variable::from(self.0)
    }
}

impl AddressMapping {
    pub async fn to_subaddress<'x, 'y: 'x>(
        &'x self,
        core: &Server,
        address: &'y str,
        session_id: u64,
    ) -> Cow<'x, str> {
        match self {
            AddressMapping::Enable => {
                if let Some((local_part, domain_part)) = address.rsplit_once('@') {
                    if let Some((local_part, _)) = local_part.split_once('+') {
                        return format!("{}@{}", local_part, domain_part).into();
                    }
                }
            }
            AddressMapping::Custom(if_block) => {
                if let Some(result) = core
                    .eval_if::<String, _>(if_block, &Address(address), session_id)
                    .await
                {
                    return result.into();
                }
            }
            AddressMapping::Disable => (),
        }

        address.into()
    }

    pub async fn to_catch_all<'x, 'y: 'x>(
        &'x self,
        core: &Server,
        address: &'y str,
        session_id: u64,
    ) -> Option<Cow<'x, str>> {
        match self {
            AddressMapping::Enable => address
                .rsplit_once('@')
                .map(|(_, domain_part)| format!("@{}", domain_part))
                .map(Cow::Owned),
            AddressMapping::Custom(if_block) => core
                .eval_if::<String, _>(if_block, &Address(address), session_id)
                .await
                .map(Cow::Owned),
            AddressMapping::Disable => None,
        }
    }
}