1use regex::Regex;
2use std::sync::LazyLock;
3
4const MAX_URL_LENGTH: usize = 4096;
10
11const MAX_SUBJECT_THREAD_LENGTH: usize = 2048;
16
17static URL_RE: LazyLock<Regex> =
18 LazyLock::new(|| Regex::new(r#"(?i)((https?|ftp)://[^\s<>"']+|www\.[^\s<>"']+)"#).unwrap());
19
20static EMAIL_RE: LazyLock<Regex> =
21 LazyLock::new(|| Regex::new(r"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})").unwrap());
22
23static UNRE_RE: LazyLock<Regex> = LazyLock::new(|| {
24 Regex::new(r"(?i)^(\s*(re|fwd?|aw|ang|sv|vs|odp|antw)\s*[\[:\]>#]*\s*)+")
25 .expect("UNRE_RE compile")
26});
27
28static ONEUNRE_RE: LazyLock<Regex> = LazyLock::new(|| {
29 Regex::new(r"(?i)^\s*(re|fwd?|aw|ang|sv|vs|odp|antw)\s*[\[:\]>#]*\s*")
30 .expect("ONEUNRE_RE compile")
31});
32
33static STRIPZONE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+\([^)]*\)\s*$").unwrap());
34
35static NUM_REF_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"&#(\d+);").unwrap());
36
37pub fn unre(subject: &str) -> String {
56 let truncated = if subject.len() > MAX_SUBJECT_THREAD_LENGTH {
59 &subject[..subject.floor_char_boundary(MAX_SUBJECT_THREAD_LENGTH)]
60 } else {
61 subject
62 };
63
64 UNRE_RE.replace(truncated, "").trim().to_string()
65}
66
67pub fn oneunre(subject: &str) -> String {
69 let truncated = if subject.len() > MAX_SUBJECT_THREAD_LENGTH {
72 &subject[..subject.floor_char_boundary(MAX_SUBJECT_THREAD_LENGTH)]
73 } else {
74 subject
75 };
76
77 ONEUNRE_RE.replace(truncated, "").trim().to_string()
78}
79
80pub fn parse_url(s: &str, url: &mut String) -> Option<usize> {
82 if let Some(m) = URL_RE.find(s) {
83 url.push_str(m.as_str());
84 Some(m.len())
85 } else {
86 None
87 }
88}
89
90pub fn conv_urls(line: &str) -> String {
108 if line.len() > MAX_URL_LENGTH * 10 {
111 return crate::txt2html::escape_html(line);
112 }
113
114 let mut result = String::new();
115 let mut end = 0;
116 for matched in URL_RE.find_iter(line) {
117 result.push_str(&crate::txt2html::escape_html(&line[end..matched.start()]));
118 let url = matched.as_str();
119
120 if url.len() > MAX_URL_LENGTH {
122 result.push_str(&crate::txt2html::escape_html(url));
123 } else {
124 let href = if url.starts_with("www.") {
125 format!("https://{}", url)
126 } else {
127 url.to_string()
128 };
129 result.push_str(&format!(
130 "<a href=\"{}\" rel=\"noopener noreferrer\">{}</a>",
131 escape_html_attr(&href),
132 escape_html_attr(url)
133 ));
134 }
135 end = matched.end();
136 }
137 result.push_str(&crate::txt2html::escape_html(&line[end..]));
138 result
139}
140
141fn escape_html_attr(s: &str) -> String {
143 let mut result = String::with_capacity(s.len());
144 for c in s.chars() {
145 match c {
146 '&' => result.push_str("&"),
147 '"' => result.push_str("""),
148 '<' => result.push_str("<"),
149 '>' => result.push_str(">"),
150 '\'' => result.push_str("'"),
151 c => result.push(c),
152 }
153 }
154 result
155}
156
157pub fn obfuscate_email_address(s: &str) -> String {
159 let mut result = String::with_capacity(s.len());
160 for c in s.chars() {
161 match c {
162 '@' => result.push_str("@"),
163 '.' => result.push('.'),
164 '-' => result.push('-'),
165 '_' => result.push('_'),
166 c if c.is_ascii_alphanumeric() => {
167 let code = c as u32;
168 result.push_str(&format!("&#{};", code));
169 },
170 c => result.push(c),
171 }
172 }
173 result
174}
175
176pub fn unobfuscate_email_address(s: &str) -> String {
178 NUM_REF_RE
179 .replace_all(s, |caps: ®ex::Captures| {
180 let code: u32 = caps[1].parse().unwrap_or(0);
181 char::from_u32(code).map_or(String::new(), |c| c.to_string())
182 })
183 .to_string()
184}
185
186pub fn spamify(
190 s: &str,
191 antispam_at: &str,
192 antispamdomain: Option<&str>,
193 spamprotect: bool,
194 spamprotect_id: bool,
195) -> String {
196 if !spamprotect && !spamprotect_id {
197 return s.to_string();
198 }
199
200 if !EMAIL_RE.is_match(s) {
201 return s.to_string();
202 }
203
204 let result = EMAIL_RE.replace_all(s, |caps: ®ex::Captures| {
205 let email = &caps[1];
206 if let Some(domain) = antispamdomain {
207 if let Some(at_pos) = email.find('@') {
208 let local = &email[..at_pos];
209 return format!("{}@{}", local, domain);
210 }
211 }
212 if spamprotect {
213 email.replace('@', antispam_at)
214 } else {
215 email.to_string()
216 }
217 });
218
219 result.to_string()
220}
221
222pub fn convchars(s: &str, chars: &str) -> String {
224 let mut result = String::with_capacity(s.len());
225 for c in s.chars() {
226 if chars.contains(c) {
227 result.push('_');
228 } else {
229 result.push(c);
230 }
231 }
232 result
233}
234
235pub fn stripzone(s: &str) -> String {
237 STRIPZONE_RE.replace(s.trim(), "").to_string()
238}
239
240pub fn getvalue(s: &str) -> Option<&str> {
242 let s = s.trim();
243 if s.is_empty() || s.eq_ignore_ascii_case("NONE") {
244 None
245 } else {
246 Some(s)
247 }
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 #[test]
255 fn test_unre() {
256 assert_eq!(unre("Re: Hello"), "Hello");
257 assert_eq!(unre("Re: Re: Hello"), "Hello");
258 assert_eq!(unre("Fwd: Hello"), "Hello");
259 assert_eq!(unre("Hello"), "Hello");
260 }
261
262 #[test]
263 fn test_conv_urls() {
264 let result = conv_urls("Visit https://example.com today");
265 assert!(result.contains("<a href=\"https://example.com\""));
266 assert!(result.contains("rel=\"noopener noreferrer\""));
267 }
268
269 #[test]
270 fn test_obfuscate_email() {
271 let ob = obfuscate_email_address("a@b.com");
272 assert!(ob.contains("a"));
273 assert!(ob.contains("@"));
274 }
275
276 #[test]
277 fn test_spamify() {
278 let result = spamify("a@b.com", " at ", None, true, false);
279 assert_eq!(result, "a at b.com");
280 }
281
282 #[test]
283 fn test_spamify_with_domain() {
284 let result = spamify("a@b.com", "@", Some("example.com"), true, false);
285 assert_eq!(result, "a@example.com");
286 }
287
288 #[test]
289 fn test_stripzone() {
290 let result = stripzone("Mon, 15 Mar 2021 12:00:00 +0000 (UTC)");
291 assert!(!result.contains("(UTC)"));
292 }
293
294 #[test]
295 fn test_getvalue() {
296 assert_eq!(getvalue("test"), Some("test"));
297 assert_eq!(getvalue("NONE"), None);
298 assert_eq!(getvalue(""), None);
299 }
300
301 #[test]
302 fn test_spamify_antispamdomain_replaces_domain() {
303 let result = spamify("user@real-domain.com", "_at_", Some("nospam.invalid"), true, false);
304 assert!(result.contains("nospam.invalid"), "domain should be replaced");
305 assert!(!result.contains("real-domain.com"), "original domain should be gone");
306 }
307
308 #[test]
309 fn test_spamify_antispamdomain_none_falls_back_to_at_replacement() {
310 let result = spamify("user@real-domain.com", "_at_", None, true, false);
311 assert!(result.contains("_at_"), "should use antispam_at when no antispamdomain");
312 assert!(!result.contains('@'), "@ should be replaced");
313 }
314
315 #[test]
316 fn test_convchars() {
317 assert_eq!(convchars("hello world", " "), "hello_world");
318 }
319
320 #[test]
321 fn test_oneunre_strips_single_prefix() {
322 assert_eq!(oneunre("Re: Hello"), "Hello");
323 assert_eq!(oneunre("Re: Re: Hello"), "Re: Hello");
324 assert_eq!(oneunre("Hello"), "Hello");
325 }
326
327 #[test]
328 fn test_parse_url_found() {
329 let mut url = String::new();
330 let len = parse_url("https://example.com/path?q=1", &mut url);
331 assert!(len.is_some());
332 assert_eq!(url, "https://example.com/path?q=1");
333 }
334
335 #[test]
336 fn test_parse_url_not_found() {
337 let mut url = String::new();
338 let len = parse_url("plain text no url", &mut url);
339 assert!(len.is_none());
340 assert!(url.is_empty());
341 }
342
343 #[test]
344 fn test_unobfuscate_roundtrip() {
345 let original = "user@example.com";
346 let obfuscated = obfuscate_email_address(original);
347 let restored = unobfuscate_email_address(&obfuscated);
348 assert_eq!(restored, original);
349 }
350
351 #[test]
352 fn test_spamify_no_email_unchanged() {
353 let result = spamify("no email here", " at ", None, true, false);
354 assert_eq!(result, "no email here");
355 }
356
357 #[test]
358 fn test_spamify_disabled_unchanged() {
359 let result = spamify("user@example.com", " at ", None, false, false);
360 assert_eq!(result, "user@example.com");
361 }
362
363 #[test]
364 fn test_conv_urls_escapes_href_with_quotes() {
365 let result = conv_urls(r#"Visit https://evil.com/a"onmouseover="alert(1) today"#);
366 assert!(
367 !result.contains(r#""onmouseover"#),
368 "raw double-quote injection must not appear: {}",
369 result
370 );
371 }
372
373 #[test]
374 fn test_conv_urls_escapes_special_chars_in_href() {
375 let result = conv_urls("https://example.com/search?a=1&b=2");
377 assert_eq!(
378 result,
379 "<a href=\"https://example.com/search?a=1&b=2\" rel=\"noopener noreferrer\">https://example.com/search?a=1&b=2</a>"
380 );
381 }
382
383 #[test]
384 fn test_conv_urls_escapes_angle_brackets() {
385 let result = conv_urls("https://evil.com/<script>");
387 assert!(
388 !result.contains("<script>"),
389 "angle brackets should not appear raw in link output: {}",
390 result
391 );
392 }
393
394 #[test]
395 fn test_conv_urls_length_limit_still_escapes_html() {
396 let input = format!("<script>{}</script>", "x".repeat(MAX_URL_LENGTH * 10));
397 let result = conv_urls(&input);
398 assert!(result.starts_with("<script>"));
399 assert!(!result.contains("<script>"));
400 }
401
402 #[test]
403 fn test_unre_utf8_at_truncation_boundary() {
404 let prefix = "Re: ";
407 let filler = "ä".repeat(1024); let subject = format!("{}{}", prefix, filler);
409 let result = unre(&subject);
411 assert!(!result.is_empty(), "should handle UTF-8 at truncation boundary");
412 }
413
414 #[test]
415 fn test_oneunre_utf8_at_truncation_boundary() {
416 let filler = "ö".repeat(1025); let subject = format!("Re: {}", filler);
418 let result = oneunre(&subject);
420 assert!(!result.is_empty());
421 }
422}