-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinymta
executable file
·227 lines (185 loc) · 6.28 KB
/
tinymta
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
#!/usr/bin/env python3
# Author: Jan Larres <[email protected]>
# License: MIT/X11
#
# Extremely simple MTA that accepts local mail by simulating a sendmail binary
# and forwards it to a real mail server. Heavily inspired by ssmtp.
#
# Copy/symlink it to:
# - /usr/sbin/sendmail
# - /usr/lib/sendmail
# - /usr/bin/mailq
# - /usr/bin/newaliases
#
# Example config file (/etc/tinymta.conf or ~/.config/tinymta.conf):
#
# [DEFAULT]
# recipient = [email protected]
# smarthost = mail.example.com
# username = foo
# password = password
import argparse
import configparser
import email
import email.utils
import os
import pwd
import socket
import sys
import syslog
from collections.abc import Sequence
from email.message import Message
from pathlib import Path
from smtplib import SMTP_SSL
from typing import Any
unsupported_args = ["ba", "bd", "bs", "bt", "bv", "bz"]
ignored_args = [
("B", 1),
("bi", 0),
("bm", 0),
("E", 0),
("h", 1),
("i", 0),
("m", 0),
("M", 1),
("n", 0),
("N", 1),
("o", 1),
("R", 1),
]
# Unsupported arguments raise an error
class UnsupportedAction(argparse.Action):
def __call__(
self,
_parser: argparse.ArgumentParser,
_namespace: argparse.Namespace,
_values: str | Sequence[Any] | None,
option_string: str | None = None,
) -> None:
print(f"{option_string} option not supported")
sys.exit(1)
class IgnoredAction(argparse.Action):
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None,
) -> None:
pass
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="tinymta", add_help=False)
parser.add_argument("rcpts", nargs="*")
parser.add_argument("-F", dest="fullname")
parser.add_argument("-f", "-r", dest="fromaddr")
parser.add_argument("-t", action="store_true", dest="extract_rcpts", default=False)
parser.add_argument("-d", "--debug", action="store_true", default=False)
for arg in unsupported_args:
parser.add_argument("-" + arg, action=UnsupportedAction, nargs=0)
for [arg, nargs] in ignored_args:
parser.add_argument("-" + arg, action=IgnoredAction, nargs=nargs)
# simulated args
parser.add_argument("-bp", action="store_true", default=False)
parser.add_argument("-q", nargs="?", default=argparse.SUPPRESS)
return parser.parse_args()
# Print message and exit successfully
def exit_success(s: str) -> None:
print(s)
sys.exit(0)
# Log error message to syslog and exit with an error code
def die(s: str | Exception, msg: email.message.Message | None = None) -> None:
syslog.syslog(syslog.LOG_WARNING, repr(s))
if msg is not None:
home = Path(pwd.getpwuid(os.getuid()).pw_dir)
path = home / "dead.letter"
syslog.syslog(syslog.LOG_WARNING, f"Writing mail to {path}")
nl = "\n" if path.exists() else ""
with path.open("a") as f:
f.write(nl)
f.write(msg.as_string())
if isinstance(s, Exception) and sys.stdout.isatty():
raise s
print(str(s))
sys.exit(1)
# Get recipients from the message and command line arguments, then map them to
# remote recipients according to the config file(s)
def get_recipients(
rcpts: list[str],
extract_rcpts: bool,
msg: email.message.Message,
config: configparser.ConfigParser,
) -> list[str]:
rcpts = [a[1] for a in email.utils.getaddresses(rcpts)]
if extract_rcpts:
for header in ["To", "Cc", "Bcc"]:
addresses = msg.get_all(header)
if addresses is None:
continue
rcpts += [a[1] for a in email.utils.getaddresses(addresses)]
result = []
for rcpt in rcpts:
user = rcpt.split("@")[0]
conf = config[user] if user in config else config["DEFAULT"]
result.append(conf["recipient"])
return result
def send_message(
msg: Message,
rcpts: list[str],
extract_rcpts: bool,
fromaddr: str | None,
debug: bool,
) -> None:
syslog.openlog(ident="tinymta", facility=syslog.LOG_MAIL)
# Get user info from passwd file
pw = pwd.getpwuid(os.getuid())
# Read configuration, with user config overriding system-wide one
# TODO: Proper per-user/recipient configuration
config = configparser.ConfigParser()
config.read(["/etc/tinymta.conf", Path(pw.pw_dir, ".config/tinymta.conf")])
defaultconf = config["DEFAULT"]
rcpts = get_recipients(rcpts, extract_rcpts, msg, config)
if len(rcpts) == 0:
die("No recipients specified", msg)
# Construct a "From" header from explicit argument, existing header,
# or username
if fromaddr is None:
fromaddr = msg.get("From")
if fromaddr is None:
fromaddr = pw.pw_name
if "@" not in fromaddr:
fromaddr += "@" + socket.getfqdn()
if "From" in msg:
msg.replace_header("From", fromaddr)
else:
msg.add_header("From", fromaddr)
if msg.get("Date") is None:
msg.add_header("Date", email.utils.formatdate(localtime=True))
# Send the mail
with SMTP_SSL(defaultconf["smarthost"]) as smtp:
if debug:
smtp.set_debuglevel(1)
smtp.login(defaultconf["username"], defaultconf["password"])
smtp.send_message(msg, from_addr=fromaddr, to_addrs=rcpts)
syslog.syslog(
syslog.LOG_INFO, f"Sent mail with subject '{msg.get('Subject')}' to {rcpts}"
)
# Main function
def main(args: argparse.Namespace) -> None:
name = Path(sys.argv[0]).name
# Simulate the "mailq" and "newaliases" commands
if name == "mailq" or args.bp or "q" in args:
exit_success(f"{name}: Mail queue is empty")
if name == "newaliases":
exit_success(f"{name}: Aliases are not used in tinymta")
if len(args.rcpts) == 0 and not args.extract_rcpts:
exit_success(f"{name}: No recipients supplied - mail will not be sent")
# Parse mail passed in through stdin
msg = email.message_from_bytes(sys.stdin.buffer.read())
try:
send_message(msg, args.rcpts, args.extract_rcpts, args.fromaddr, args.debug)
except Exception as e:
if sys.stdin.isatty():
raise
die(e, msg)
if __name__ == "__main__":
main(parse_args())