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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use std::{
borrow::Cow,
convert::TryInto,
fs::OpenOptions,
io::{BufWriter, Read, Seek, Write},
path::{Path, PathBuf},
};
use crate::{errors::*, Configuration, Connection, DbVal, MailingList, PostPolicy};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PostfixConfiguration {
pub user: Cow<'static, str>,
pub group: Option<Cow<'static, str>>,
pub binary_path: PathBuf,
#[serde(default)]
pub process_limit: Option<u64>,
#[serde(default)]
pub map_output_path: Option<PathBuf>,
#[serde(default)]
pub transport_name: Option<Cow<'static, str>>,
}
impl Default for PostfixConfiguration {
fn default() -> Self {
Self {
user: "user".into(),
group: None,
binary_path: Path::new("/usr/bin/mailpot").to_path_buf(),
process_limit: None,
map_output_path: None,
transport_name: None,
}
}
}
impl PostfixConfiguration {
pub fn generate_master_cf_entry(&self, config: &Configuration, config_path: &Path) -> String {
let transport_name = self.transport_name.as_deref().unwrap_or("mailpot");
format!(
"{transport_name} unix - n n - {process_limit} pipe
flags=RX user={username}{group_sep}{groupname} directory={{{data_dir}}} argv={{{binary_path}}} -c \
{{{config_path}}} post",
username = &self.user,
group_sep = if self.group.is_none() { "" } else { ":" },
groupname = self.group.as_deref().unwrap_or_default(),
process_limit = self.process_limit.unwrap_or(1),
binary_path = &self.binary_path.display(),
config_path = &config_path.display(),
data_dir = &config.data_path.display()
)
}
pub fn generate_maps(
&self,
lists: &[(DbVal<MailingList>, Option<DbVal<PostPolicy>>)],
) -> String {
let transport_name = self.transport_name.as_deref().unwrap_or("mailpot");
let mut ret = String::new();
ret.push_str("# Automatically generated by mailpot.\n");
ret.push_str(
"# Upon its creation and every time it is modified, postmap(1) must be called for the \
changes to take effect:\n",
);
ret.push_str("# postmap /path/to/map_file\n\n");
let calc_width = |list: &MailingList, policy: Option<&PostPolicy>| -> usize {
let addr = list.address.len();
match policy {
None => 0,
Some(PostPolicy { .. }) => addr + "+request".len(),
}
};
let Some(width): Option<usize> = lists.iter().map(|(l, p)| calc_width(l, p.as_deref())).max() else {
return ret;
};
for (list, policy) in lists {
macro_rules! push_addr {
($addr:expr) => {{
let addr = &$addr;
ret.push_str(addr);
for _ in 0..(width - addr.len() + 5) {
ret.push(' ');
}
ret.push_str(transport_name);
ret.push_str(":\n");
}};
}
match policy.as_deref() {
None => log::debug!(
"Not generating postfix map entry for list {} because it has no post_policy \
set.",
list.id
),
Some(PostPolicy { open: true, .. }) => {
push_addr!(list.address);
ret.push('\n');
}
Some(PostPolicy { .. }) => {
push_addr!(list.address);
push_addr!(list.subscription_mailto().address);
push_addr!(list.owner_mailto().address);
ret.push('\n');
}
}
}
ret.pop();
ret
}
pub fn save_master_cf_entry(
&self,
config: &Configuration,
config_path: &Path,
master_cf_path: Option<&Path>,
) -> Result<()> {
let new_entry = self.generate_master_cf_entry(config, config_path);
let path = master_cf_path.unwrap_or_else(|| Path::new("/etc/postfix/master.cf"));
let path_bkp = path.with_extension("cf.bkp");
std::fs::copy(path, &path_bkp).context(format!(
"Could not create master.cf backup {}",
path_bkp.display()
))?;
log::info!(
"Created backup of {} to {}.",
path.display(),
path_bkp.display()
);
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(false)
.open(path)
.context(format!("Could not open {}", path.display()))?;
let mut previous_content = String::new();
file.rewind()
.context(format!("Could not access {}", path.display()))?;
file.read_to_string(&mut previous_content)
.context(format!("Could not access {}", path.display()))?;
let original_size = previous_content.len();
let lines = previous_content.lines().collect::<Vec<&str>>();
let transport_name = self.transport_name.as_deref().unwrap_or("mailpot");
if let Some(line) = lines.iter().find(|l| l.starts_with(transport_name)) {
let pos = previous_content.find(line).ok_or_else(|| {
Error::from(ErrorKind::Bug("Unepected logical error.".to_string()))
})?;
let end_needle = " argv=";
let end_pos = previous_content[pos..]
.find(end_needle)
.and_then(|pos2| {
previous_content[(pos + pos2 + end_needle.len())..]
.find('\n')
.map(|p| p + pos + pos2 + end_needle.len())
})
.ok_or_else(|| {
Error::from(ErrorKind::Bug("Unepected logical error.".to_string()))
})?;
previous_content.replace_range(pos..end_pos, &new_entry);
} else {
previous_content.push_str(&new_entry);
previous_content.push('\n');
}
file.rewind()?;
if previous_content.len() < original_size {
file.set_len(
previous_content
.len()
.try_into()
.expect("Could not convert usize file size to u64"),
)?;
}
let mut file = BufWriter::new(file);
file.write_all(previous_content.as_bytes())
.context(format!("Could not access {}", path.display()))?;
file.flush()
.context(format!("Could not access {}", path.display()))?;
log::debug!("Saved new master.cf to {}.", path.display(),);
Ok(())
}
pub fn save_maps(&self, config: &Configuration) -> Result<()> {
let db = Connection::open_db(config.clone())?;
let Some(postmap) = find_binary_in_path("postmap") else {
return Err(Error::from(ErrorKind::External(anyhow::Error::msg("Could not find postmap binary in PATH."))));
};
let lists = db.lists()?;
let lists_post_policies = lists
.into_iter()
.map(|l| {
let pk = l.pk;
Ok((l, db.list_post_policy(pk)?))
})
.collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
let content = self.generate_maps(&lists_post_policies);
let path = self
.map_output_path
.as_deref()
.unwrap_or(&config.data_path)
.join("mailpot_postfix_map");
let mut file = BufWriter::new(
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
.context(format!("Could not open {}", path.display()))?,
);
file.write_all(content.as_bytes())
.context(format!("Could not write to {}", path.display()))?;
file.flush()
.context(format!("Could not write to {}", path.display()))?;
let output = std::process::Command::new("sh")
.arg("-c")
.arg(&format!("{} {}", postmap.display(), path.display()))
.output()
.with_context(|| {
format!(
"Could not execute `postmap` binary in path {}",
postmap.display()
)
})?;
if !output.status.success() {
use std::os::unix::process::ExitStatusExt;
if let Some(code) = output.status.code() {
return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
format!(
"{} exited with {}.\nstderr was:\n---{}---\nstdout was\n---{}---\n",
code,
postmap.display(),
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
),
))));
} else if let Some(signum) = output.status.signal() {
return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
format!(
"{} was killed with signal {}.\nstderr was:\n---{}---\nstdout \
was\n---{}---\n",
signum,
postmap.display(),
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
),
))));
} else {
return Err(Error::from(ErrorKind::External(anyhow::Error::msg(
format!(
"{} failed for unknown reason.\nstderr was:\n---{}---\nstdout \
was\n---{}---\n",
postmap.display(),
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
),
))));
}
}
Ok(())
}
}
fn find_binary_in_path(binary_name: &str) -> Option<PathBuf> {
std::env::var_os("PATH").and_then(|paths| {
std::env::split_paths(&paths).find_map(|dir| {
let full_path = dir.join(binary_name);
if full_path.is_file() {
Some(full_path)
} else {
None
}
})
})
}
#[test]
fn test_postfix_generation() -> Result<()> {
use tempfile::TempDir;
use crate::*;
crate::init_stderr_logging();
fn get_smtp_conf() -> melib::smtp::SmtpServerConf {
use melib::smtp::*;
SmtpServerConf {
hostname: "127.0.0.1".into(),
port: 1025,
envelope_from: "foo-chat@example.com".into(),
auth: SmtpAuth::None,
security: SmtpSecurity::None,
extensions: Default::default(),
}
}
let tmp_dir = TempDir::new()?;
let db_path = tmp_dir.path().join("mpot.db");
let config = Configuration {
send_mail: SendMail::Smtp(get_smtp_conf()),
db_path,
data_path: tmp_dir.path().to_path_buf(),
administrators: vec![],
};
let config_path = tmp_dir.path().join("conf.toml");
{
let mut conf = OpenOptions::new()
.write(true)
.create(true)
.open(&config_path)?;
conf.write_all(config.to_toml().as_bytes())?;
conf.flush()?;
}
let db = Connection::open_or_create_db(config)?.trusted();
assert!(db.lists()?.is_empty());
let first = db.create_list(MailingList {
pk: 0,
name: "first".into(),
id: "first".into(),
address: "first@example.com".into(),
description: None,
archive_url: None,
})?;
assert_eq!(first.pk(), 1);
let second = db.create_list(MailingList {
pk: 0,
name: "second".into(),
id: "second".into(),
address: "second@example.com".into(),
description: None,
archive_url: None,
})?;
assert_eq!(second.pk(), 2);
let post_policy = db.set_list_post_policy(PostPolicy {
pk: 0,
list: second.pk(),
announce_only: false,
subscription_only: false,
approval_needed: false,
open: true,
custom: false,
})?;
assert_eq!(post_policy.pk(), 1);
let third = db.create_list(MailingList {
pk: 0,
name: "third".into(),
id: "third".into(),
address: "third@example.com".into(),
description: None,
archive_url: None,
})?;
assert_eq!(third.pk(), 3);
let post_policy = db.set_list_post_policy(PostPolicy {
pk: 0,
list: third.pk(),
announce_only: false,
subscription_only: false,
approval_needed: true,
open: false,
custom: false,
})?;
assert_eq!(post_policy.pk(), 2);
let mut postfix_conf = PostfixConfiguration::default();
let expected_mastercf_entry = format!(
"mailpot unix - n n - 1 pipe
flags=RX user={} directory={{{}}} argv={{/usr/bin/mailpot}} -c {{{}}} post\n",
&postfix_conf.user,
tmp_dir.path().display(),
config_path.display()
);
assert_eq!(
expected_mastercf_entry.trim_end(),
postfix_conf.generate_master_cf_entry(db.conf(), &config_path)
);
let lists = db.lists()?;
let lists_post_policies = lists
.into_iter()
.map(|l| {
let pk = l.pk;
Ok((l, db.list_post_policy(pk)?))
})
.collect::<Result<Vec<(DbVal<MailingList>, Option<DbVal<PostPolicy>>)>>>()?;
let maps = postfix_conf.generate_maps(&lists_post_policies);
let expected = "second@example.com mailpot:
third@example.com mailpot:
third+request@example.com mailpot:
third+owner@example.com mailpot:
";
assert!(
maps.ends_with(expected),
"maps has unexpected contents: has\n{:?}\nand should have ended with\n{:?}",
maps,
expected
);
let master_edit_value = r#"#
# Postfix master process configuration file. For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (no) (never) (100)
# ==========================================================================
smtp inet n - y - - smtpd
pickup unix n - y 60 1 pickup
cleanup unix n - y - 0 cleanup
qmgr unix n - n 300 1 qmgr
#qmgr unix n - n 300 1 oqmgr
tlsmgr unix - - y 1000? 1 tlsmgr
rewrite unix - - y - - trivial-rewrite
bounce unix - - y - 0 bounce
defer unix - - y - 0 bounce
trace unix - - y - 0 bounce
verify unix - - y - 1 verify
flush unix n - y 1000? 0 flush
proxymap unix - - n - - proxymap
proxywrite unix - - n - 1 proxymap
smtp unix - - y - - smtp
relay unix - - y - - smtp
-o syslog_name=postfix/$service_name
showq unix n - y - - showq
error unix - - y - - error
retry unix - - y - - error
discard unix - - y - - discard
local unix - n n - - local
virtual unix - n n - - virtual
lmtp unix - - y - - lmtp
anvil unix - - y - 1 anvil
scache unix - - y - 1 scache
postlog unix-dgram n - n - 1 postlogd
maildrop unix - n n - - pipe
flags=DRXhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
uucp unix - n n - - pipe
flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail unix - n n - - pipe
flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp unix - n n - - pipe
flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix - n n - 2 pipe
flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman unix - n n - - pipe
flags=FRX user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py ${nexthop} ${user}
"#;
let path = tmp_dir.path().join("master.cf");
{
let mut mastercf = OpenOptions::new().write(true).create(true).open(&path)?;
mastercf.write_all(master_edit_value.as_bytes())?;
mastercf.flush()?;
}
postfix_conf.save_master_cf_entry(db.conf(), &config_path, Some(&path))?;
let mut first = String::new();
{
let mut mastercf = OpenOptions::new()
.write(false)
.read(true)
.create(false)
.open(&path)?;
mastercf.read_to_string(&mut first)?;
}
assert!(
first.ends_with(&expected_mastercf_entry),
"edited master.cf has unexpected contents: has\n{:?}\nand should have ended with\n{:?}",
first,
expected_mastercf_entry
);
postfix_conf.user = "nobody".into();
postfix_conf.save_master_cf_entry(db.conf(), &config_path, Some(&path))?;
let mut second = String::new();
{
let mut mastercf = OpenOptions::new()
.write(false)
.read(true)
.create(false)
.open(&path)?;
mastercf.read_to_string(&mut second)?;
}
let expected_mastercf_entry = format!(
"mailpot unix - n n - 1 pipe
flags=RX user=nobody directory={{{}}} argv={{/usr/bin/mailpot}} -c {{{}}} post\n",
tmp_dir.path().display(),
config_path.display()
);
assert!(
second.ends_with(&expected_mastercf_entry),
"doubly edited master.cf has unexpected contents: has\n{:?}\nand should have ended \
with\n{:?}",
second,
expected_mastercf_entry
);
postfix_conf.user = "hackerman".into();
postfix_conf.save_master_cf_entry(db.conf(), &config_path, Some(&path))?;
let mut third = String::new();
{
let mut mastercf = OpenOptions::new()
.write(false)
.read(true)
.create(false)
.open(&path)?;
mastercf.read_to_string(&mut third)?;
}
let expected_mastercf_entry = format!(
"mailpot unix - n n - 1 pipe
flags=RX user=hackerman directory={{{}}} argv={{/usr/bin/mailpot}} -c {{{}}} post\n",
tmp_dir.path().display(),
config_path.display(),
);
assert!(
third.ends_with(&expected_mastercf_entry),
"triply edited master.cf has unexpected contents: has\n{:?}\nand should have ended \
with\n{:?}",
third,
expected_mastercf_entry
);
postfix_conf.group = Some("nobody".into());
postfix_conf.save_master_cf_entry(db.conf(), &config_path, Some(&path))?;
let mut fourth = String::new();
{
let mut mastercf = OpenOptions::new()
.write(false)
.read(true)
.create(false)
.open(&path)?;
mastercf.read_to_string(&mut fourth)?;
}
let expected_mastercf_entry = format!(
"mailpot unix - n n - 1 pipe
flags=RX user=hackerman:nobody directory={{{}}} argv={{/usr/bin/mailpot}} -c {{{}}} post\n",
tmp_dir.path().display(),
config_path.display(),
);
assert!(
fourth.ends_with(&expected_mastercf_entry),
"fourthly edited master.cf has unexpected contents: has\n{:?}\nand should have ended \
with\n{:?}",
fourth,
expected_mastercf_entry
);
Ok(())
}