1
2
3
4
5
6
7
|
1
2
3
4
5
6
7
8
9
10
11
12
|
+
+
+
+
+
|
//! SMTP server implementation for receiving and processing emails.
//!
//! This module handles SMTP connections, email parsing, and forwarding to
//! Telegram.
use crate::{
Cursor,
telegram::TelegramTransport,
utils::{
Attachment,
RE_DOMAIN,
validate,
|
| ︙ | | |
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
+
|
INVALID_CREDENTIALS,
NO_MAILBOX,
OK
},
};
use regex::{
Regex,
RegexBuilder,
escape,
};
use stacked_errors::{
Result,
StackableErr,
bail,
};
|
| ︙ | | |
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
|
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
|
-
+
-
-
+
+
+
+
+
+
+
+
+
-
+
-
+
-
-
+
+
+
-
+
+
+
+
-
+
-
-
-
-
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
+
+
-
-
-
-
+
-
-
-
+
+
-
-
+
-
-
+
|
}
/// `MailServer` Central object with TG api and configuration
#[derive(Clone, Debug)]
pub struct MailServer {
data: Vec<u8>,
headers: Option<SomeHeaders>,
relay: bool,
tg: Arc<TelegramTransport>,
fields: HashSet<String>,
address: Regex,
}
impl MailServer {
/// Initializes the mail server: sets up the Telegram API client and
/// Initialize API and read configuration
pub fn new(settings: config::Config) -> Result<MailServer> {
/// validates all required configuration values.
///
/// # Arguments
/// * `settings` - Parsed application configuration.
///
/// # Errors
/// Returns an error if required configuration values are missing or invalid.
/// server fails to start.
pub fn new (settings: config::Config) -> Result<MailServer> {
let api_key = settings.get_string("api_key")
.context("[smtp2tg.toml] missing \"api_key\" parameter.\n")?;
let mut recipients = HashMap::new();
for (name, value) in settings.get_table("recipients")
.expect("[smtp2tg.toml] missing table \"recipients\".\n")
.context("[smtp2tg.toml] missing table \"recipients\".\n")?
{
let value = value.into_int()
.context("[smtp2tg.toml] \"recipient\" table values should be integers.\n")?;
recipients.insert(name, value);
recipients.insert(name.to_lowercase(), value);
}
let tg = Arc::new(TelegramTransport::new(api_key, recipients, &settings)?);
let fields = HashSet::<String>::from_iter(settings.get_array("fields")
.expect("[smtp2tg.toml] \"fields\" should be an array")
.iter().map(|x| x.clone().into_string().expect("should be strings")));
.context("[smtp2tg.toml] \"fields\" should be an array")?
.iter().map(|x| x.clone().into_string().context("should be strings"))
.collect::<Result<Vec<String>>>()?);
let mut domains: HashSet<String> = HashSet::new();
let extra_domains = settings.get_array("domains").stack()?;
for domain in extra_domains {
let domain = domain.to_string().to_lowercase();
if RE_DOMAIN.is_match(&domain) {
domains.insert(domain);
} else {
panic!("[smtp2tg.toml] can't check of domains in \"domains\": {domain}");
bail!("[smtp2tg.toml] can't check domains in \"domains\": {domain}");
}
}
if domains.is_empty() {
bail!("No domains, need at least one: default `localhost` would do.");
}
let domains = domains.into_iter().map(|s| escape(&s))
.collect::<Vec<String>>().join("|");
let address = Regex::new(&format!("^(?P<user>[a-z0-9][-a-z0-9])(@({domains}))$")).stack()?;
let address = RegexBuilder::new(&format!("^[a-z0-9][a-z0-9.-]*(@({domains}))?$"))
let relay = match settings.get_string("unknown")
.context("[smtp2tg.toml] can't get \"unknown\" policy.\n")?.as_str()
{
"relay" => true,
.case_insensitive(true).build().stack()?;
"deny" => false,
_ => {
bail!("[smtp2tg.toml] \"unknown\" should be either \"relay\" or \"deny\".\n");
},
};
Ok(MailServer {
data: vec!(),
headers: None,
relay,
tg,
fields,
address,
})
}
/// Retrieves the Telegram chat ID for a given email address, checks that
/// used domain is allowed.
///
/// # Arguments
/// * `name` - Email address or username to look up.
///
/// Returns id for provided email address
pub fn get_id (&self, name_str: &str) -> Result<&ChatPeerId> {
/// # Returns
/// * `Result<ChatPeerId>` - Telegram chat ID for the address, or default if
/// not found.
pub fn get_id (&self, name: &str) -> Result<&ChatPeerId> {
// here we need to store String locally to borrow it after
let mut link = name_str;
let name: String;
if let Some(caps) = self.address.captures(link) {
if self.address.is_match(name) {
name = caps["name"].to_string();
link = &name;
}
Ok(self.tg.get(name).unwrap_or(&self.tg.default))
} else {
match self.tg.get(link) {
Ok(addr) => Ok(addr),
bail!("Doesn't look like address from one of our domains.");
Err(_) => Ok(&self.tg.default),
}
}
/// Attempt to deliver one message
async fn relay_mail (&self) -> Result<()> {
if let Some(headers) = &self.headers {
let mail = mail_parser::MessageParser::new().parse(&self.data)
.context("Failed to parse mail.")?;
// Adding all known addresses to recipient list, for anyone else adding default
// Also if list is empty also adding default
let mut rcpt: HashSet<&ChatPeerId> = HashSet::new();
if headers.to.is_empty() && !self.relay {
if headers.to.is_empty() {
bail!("Relaying is disabled, and there's no destination address");
}
for item in &headers.to {
rcpt.insert(self.get_id(item)?);
};
if rcpt.is_empty() {
self.tg.debug("No recipient or envelope address.").await?;
|
| ︙ | | |
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
|
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
|
+
-
-
-
-
+
-
-
-
-
-
-
+
+
+
-
-
-
|
} else {
bail!("Required headers were not found.");
}
Ok(())
}
}
/// SMTP handler implementation for mailin-embedded.
impl mailin_embedded::Handler for MailServer {
/// Just deny login auth
fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
INVALID_CREDENTIALS
}
/// Just deny plain auth
fn auth_plain (&mut self, _authorization_id: &str, _authentication_id: &str, _password: &str) -> Response {
INVALID_CREDENTIALS
}
/// Verify whether address is deliverable
fn rcpt (&mut self, to: &str) -> Response {
if self.relay {
OK
} else {
match self.get_id(to) {
if self.get_id(to).is_ok() {
Ok(_) => OK,
Err(_) => {
if self.relay {
OK
} else {
NO_MAILBOX
OK
} else {
NO_MAILBOX
}
}
}
}
}
/// Save headers we need
fn data_start (&mut self, _domain: &str, from: &str, _is8bit: bool, to: &[String]) -> Response {
self.headers = Some(SomeHeaders{
from: from.to_string(),
|
| ︙ | | |
| | | | |