Annotation For src/mail.rs
Logged in as anonymous

Lines of src/mail.rs from check-in 1723b63d69 that are changed by the sequence of edits moving toward check-in 158c9cffc6:

                         1: //! SMTP server implementation for receiving and processing emails.
                         2: //!
                         3: //! This module handles SMTP connections, email parsing, and forwarding to
                         4: //! Telegram.
                         5: 
                         6: use crate::{
                         7: 	Cursor,
                         8: 	telegram::TelegramTransport,
                         9: 	utils::{
                        10: 		Attachment,
                        11: 		RE_DOMAIN,
                        12: 		validate,
                        13: 	},
                        14: };
                        15: 
                        16: use std::{
                        17: 	collections::{
                        18: 		HashMap,
                        19: 		HashSet,
                        20: 	},
                        21: 	io::Error,
                        22: 	sync::Arc,
                        23: };
                        24: 
                        25: use async_compat::Compat;
                        26: use mailin_embedded::{
                        27: 	Response,
                        28: 	response::{
                        29: 		INTERNAL_ERROR,
                        30: 		INVALID_CREDENTIALS,
                        31: 		NO_MAILBOX,
                        32: 		OK
                        33: 	},
                        34: };
                        35: use regex::{
                        36: 	Regex,
                        37: 	escape,
                        38: };
                        39: use stacked_errors::{
                        40: 	Result,
                        41: 	StackableErr,
                        42: 	bail,
                        43: };
                        44: use tgbot::types::ChatPeerId;
                        45: 
                        46: /// `SomeHeaders` object to store data through SMTP session
                        47: #[derive(Clone, Debug)]
                        48: struct SomeHeaders {
                        49: 	from: String,
                        50: 	to: Vec<String>,
                        51: }
                        52: 
                        53: /// `MailServer` Central object with TG api and configuration
                        54: #[derive(Clone, Debug)]
                        55: pub struct MailServer {
                        56: 	data: Vec<u8>,
                        57: 	headers: Option<SomeHeaders>,
1723b63d69 2026-08-01   58: 	relay: bool,
                        59: 	tg: Arc<TelegramTransport>,
                        60: 	fields: HashSet<String>,
                        61: 	address: Regex,
                        62: }
                        63: 
                        64: impl MailServer {
                        65: 	/// Initializes the mail server: sets up the Telegram API client and
                        66: 	/// validates all required configuration values.
                        67: 	///
                        68: 	/// # Arguments
                        69: 	/// * `settings` - Parsed application configuration.
                        70: 	///
                        71: 	/// # Errors
                        72: 	/// Returns an error if required configuration values are missing or invalid.
                        73: 	/// server fails to start.
                        74: 	pub fn new (settings: config::Config) -> Result<MailServer> {
                        75: 		let api_key = settings.get_string("api_key")
                        76: 			.context("[smtp2tg.toml] missing \"api_key\" parameter.\n")?;
                        77: 		let mut recipients = HashMap::new();
                        78: 		for (name, value) in settings.get_table("recipients")
                        79: 			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
                        80: 		{
                        81: 			let value = value.into_int()
                        82: 				.context("[smtp2tg.toml] \"recipient\" table values should be integers.\n")?;
1723b63d69 2026-08-01   83: 			recipients.insert(name, value);
                        84: 		}
                        85: 
                        86: 		let tg = Arc::new(TelegramTransport::new(api_key, recipients, &settings)?);
                        87: 		let fields = HashSet::<String>::from_iter(settings.get_array("fields")
                        88: 			.expect("[smtp2tg.toml] \"fields\" should be an array")
                        89: 			.iter().map(|x| x.clone().into_string().expect("should be strings")));
                        90: 		let mut domains: HashSet<String> = HashSet::new();
                        91: 		let extra_domains = settings.get_array("domains").stack()?;
                        92: 		for domain in extra_domains {
                        93: 			let domain = domain.to_string().to_lowercase();
                        94: 			if RE_DOMAIN.is_match(&domain) {
                        95: 				domains.insert(domain);
                        96: 			} else {
                        97: 				panic!("[smtp2tg.toml] can't check of domains in \"domains\": {domain}");
                        98: 			}
                        99: 		}
                       100: 		let domains = domains.into_iter().map(|s| escape(&s))
                       101: 			.collect::<Vec<String>>().join("|");
1723b63d69 2026-08-01  102: 		let address = Regex::new(&format!("^[a-z0-9][-a-z0-9]*(@({domains}))?$")).stack()?;
1723b63d69 2026-08-01  103: 		let relay = match settings.get_string("unknown")
1723b63d69 2026-08-01  104: 			.context("[smtp2tg.toml] can't get \"unknown\" policy.\n")?.as_str()
1723b63d69 2026-08-01  105: 		{
1723b63d69 2026-08-01  106: 			"relay" => true,
1723b63d69 2026-08-01  107: 			"deny" => false,
1723b63d69 2026-08-01  108: 			_ => {
1723b63d69 2026-08-01  109: 				bail!("[smtp2tg.toml] \"unknown\" should be either \"relay\" or \"deny\".\n");
1723b63d69 2026-08-01  110: 			},
1723b63d69 2026-08-01  111: 		};
                       112: 
                       113: 		Ok(MailServer {
                       114: 			data: vec!(),
                       115: 			headers: None,
1723b63d69 2026-08-01  116: 			relay,
                       117: 			tg,
                       118: 			fields,
                       119: 			address,
                       120: 		})
                       121: 	}
                       122: 
                       123: 	/// Retrieves the Telegram chat ID for a given email address, checks that
                       124: 	/// used domain is allowed.
                       125: 	///
                       126: 	/// # Arguments
                       127: 	/// * `name` - Email address or username to look up.
                       128: 	///
                       129: 	/// # Returns
                       130: 	/// * `Result<ChatPeerId>` - Telegram chat ID for the address, or default if
                       131: 	///   not found.
                       132: 	pub fn get_id (&self, name: &str) -> Result<&ChatPeerId> {
                       133: 		if self.address.is_match(name) {
                       134: 			Ok(self.tg.get(name).unwrap_or(&self.tg.default))
                       135: 		} else {
                       136: 			bail!("Doesn't look like address from one of our domains.");
                       137: 		}
                       138: 	}
                       139: 
                       140: 	/// Attempt to deliver one message
                       141: 	async fn relay_mail (&self) -> Result<()> {
                       142: 		if let Some(headers) = &self.headers {
                       143: 			let mail = mail_parser::MessageParser::new().parse(&self.data)
                       144: 				.context("Failed to parse mail.")?;
                       145: 
                       146: 			// Adding all known addresses to recipient list, for anyone else adding default
                       147: 			// Also if list is empty also adding default
                       148: 			let mut rcpt: HashSet<&ChatPeerId> = HashSet::new();
1723b63d69 2026-08-01  149: 			if headers.to.is_empty() && !self.relay {
                       150: 				bail!("Relaying is disabled, and there's no destination address");
                       151: 			}
                       152: 			for item in &headers.to {
                       153: 				rcpt.insert(self.get_id(item)?);
                       154: 			};
                       155: 			if rcpt.is_empty() {
                       156: 				self.tg.debug("No recipient or envelope address.").await?;
                       157: 				rcpt.insert(&self.tg.default);
                       158: 			};
                       159: 
                       160: 			// preparing message header
                       161: 			let mut reply: Vec<String> = vec!["<blockquote expandable>".into()];
                       162: 			if self.fields.contains("subject") {
                       163: 				if let Some(subject) = mail.subject() {
                       164: 					reply.push(format!("<u><i>Subject:</i></u> <code>{}</code>", validate(subject).stack()?));
                       165: 				} else if let Some(thread) = mail.thread_name() {
                       166: 					reply.push(format!("<u><i>Thread:</i></u> <code>{}</code>", validate(thread).stack()?));
                       167: 				}
                       168: 			}
                       169: 			// do we need to replace spaces here?
                       170: 			if self.fields.contains("from") {
                       171: 				reply.push(format!("<u><i>From:</i></u> <code>{}</code>", validate(&headers.from).stack()?));
                       172: 			}
                       173: 			if self.fields.contains("date")
                       174: 				&& let Some(date) = mail.date()
                       175: 			{
                       176: 				reply.push(format!("<u><i>Date:</i></u> <code>{date}</code>"));
                       177: 			}
                       178: 			reply.push("</blockquote><pre>".into());
                       179: 			let reply = reply.join("\n");
                       180: 
                       181: 			let html_parts = mail.html_body_count();
                       182: 			let text_parts = mail.text_body_count();
                       183: 			let attachments = mail.attachment_count();
                       184: 			if html_parts != text_parts {
                       185: 				self.tg.debug(&format!("Hm, we have {html_parts} HTML parts and {text_parts} text parts.")).await?;
                       186: 			}
                       187: 			//let mut html_num = 0;
                       188: 			let mut text_num = 0;
                       189: 			let mut file_num = 0;
                       190: 			// let's display first html or text part as body
                       191: 			let mut body: String = "".into();
                       192: 			/*
                       193: 			 * actually I don't wanna parse that html stuff
                       194: 			if html_parts > 0 {
                       195: 				let text = mail.body_html(0).stack()?;
                       196: 				if text.len() < 4096 - header_size {
                       197: 					body = text;
                       198: 					html_num = 1;
                       199: 				}
                       200: 			};
                       201: 			*/
                       202: 			if body.is_empty() && text_parts > 0 {
                       203: 				let text = mail.body_text(0)
                       204: 					.context("Failed to extract text from message")?
                       205: 					.replace("\r\n", "\n");
                       206: 				let text = validate(&text).stack()?;
                       207: 				// 6:
                       208: 				// - (headers)
                       209: 				// - (mail text)
                       210: 				// - 6: </pre>
                       211: 				if text.len() < 4096 - ( reply.len() + 6 ) {
                       212: 					body = text.to_string();
                       213: 					text_num = 1;
                       214: 				}
                       215: 			};
                       216: 			let msg = format!("{}{}</pre>", reply, body);
                       217: 
                       218: 			// and let's collect all other attachment parts
                       219: 			let mut files_to_send = vec![];
                       220: 			/*
                       221: 			 * let's just skip html parts for now, they just duplicate text?
                       222: 			while html_num < html_parts {
                       223: 				files_to_send.push(mail.html_part(html_num).stack()?);
                       224: 				html_num += 1;
                       225: 			}
                       226: 			*/
                       227: 			while text_num < text_parts {
                       228: 				files_to_send.push(mail.text_part(text_num.try_into().stack()?)
                       229: 					.context("Failed to get text part from message.")?);
                       230: 				text_num += 1;
                       231: 			}
                       232: 			while file_num < attachments {
                       233: 				files_to_send.push(mail.attachment(file_num.try_into().stack()?)
                       234: 					.context("Failed to get file part from message.")?);
                       235: 				file_num += 1;
                       236: 			}
                       237: 
                       238: 			for chat in rcpt {
                       239: 				if !files_to_send.is_empty() {
                       240: 					let mut files = vec![];
                       241: 					// let mut first_one = true;
                       242: 					for chunk in &files_to_send {
                       243: 						let data: Vec<u8> = chunk.contents().to_vec();
                       244: 						let mut filename: Option<String> = None;
                       245: 						for header in chunk.headers() {
                       246: 							if header.name() == "Content-Type" {
                       247: 								match header.value() {
                       248: 									mail_parser::HeaderValue::ContentType(contenttype) => {
                       249: 										if let Some(fname) = contenttype.attribute("name") {
                       250: 											filename = Some(fname.to_owned());
                       251: 										}
                       252: 									},
                       253: 									_ => {
                       254: 										self.tg.debug("Attachment has bad ContentType header.").await?;
                       255: 									},
                       256: 								};
                       257: 							};
                       258: 						};
                       259: 						let filename = if let Some(fname) = filename {
                       260: 							fname
                       261: 						} else {
                       262: 							"Attachment.txt".into()
                       263: 						};
                       264: 						files.push(Attachment {
                       265: 							data: Cursor::new(data),
                       266: 							name: filename,
                       267: 						});
                       268: 					}
                       269: 					self.tg.sendgroup(chat, files, &msg).await?;
                       270: 				} else {
                       271: 					self.tg.send(chat, &msg).await?;
                       272: 				}
                       273: 			}
                       274: 		} else {
                       275: 			bail!("Required headers were not found.");
                       276: 		}
                       277: 		Ok(())
                       278: 	}
                       279: }
                       280: 
                       281: /// SMTP handler implementation for mailin-embedded.
                       282: impl mailin_embedded::Handler for MailServer {
                       283: 	/// Just deny login auth
                       284: 	fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
                       285: 		INVALID_CREDENTIALS
                       286: 	}
                       287: 
                       288: 	/// Just deny plain auth
                       289: 	fn auth_plain (&mut self, _authorization_id: &str, _authentication_id: &str, _password: &str) -> Response {
                       290: 		INVALID_CREDENTIALS
                       291: 	}
                       292: 
                       293: 	/// Verify whether address is deliverable
                       294: 	fn rcpt (&mut self, to: &str) -> Response {
1723b63d69 2026-08-01  295: 		if self.relay || self.get_id(to).is_ok() {
                       296: 			OK
                       297: 		} else {
                       298: 			NO_MAILBOX
                       299: 		}
                       300: 	}
                       301: 
                       302: 	/// Save headers we need
                       303: 	fn data_start (&mut self, _domain: &str, from: &str, _is8bit: bool, to: &[String]) -> Response {
                       304: 		self.headers = Some(SomeHeaders{
                       305: 			from: from.to_string(),
                       306: 			to: to.to_vec(),
                       307: 		});
                       308: 		OK
                       309: 	}
                       310: 
                       311: 	/// Save chunk(?) of data
                       312: 	fn data (&mut self, buf: &[u8]) -> std::result::Result<(), Error> {
                       313: 		self.data.append(buf.to_vec().as_mut());
                       314: 		Ok(())
                       315: 	}
                       316: 
                       317: 	/// Attempt to send email, return temporary error if that fails
                       318: 	fn data_end (&mut self) -> Response {
                       319: 		let mut result = OK;
                       320: 		smol::block_on(Compat::new(async {
                       321: 			// relay mail
                       322: 			if let Err(err) = self.relay_mail().await {
                       323: 				result = INTERNAL_ERROR;
                       324: 				// in case that fails - inform default recipient
                       325: 				if let Err(err) = self.tg.debug(&format!("Sending emails failed:\n{err:}")).await {
                       326: 					// in case that also fails - write some logs and bail
                       327: 					eprintln!("{err:?}");
                       328: 				};
                       329: 			};
                       330: 		}));
                       331: 		// clear - just in case
                       332: 		self.data = vec![];
                       333: 		self.headers = None;
                       334: 		result
                       335: 	}
                       336: }