aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Twisted/py3/twisted/mail/scripts/mailmail.py
blob: cf1e58f5b6b9ca943424e4eaa82158bf7b0144a1 (plain) (blame)
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
# -*- test-case-name: twisted.mail.test.test_mailmail -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Implementation module for the I{mailmail} command.
"""


import email.utils
import getpass
import os
import sys
from configparser import ConfigParser
from io import StringIO

from twisted.copyright import version
from twisted.internet import reactor
from twisted.logger import Logger, textFileLogObserver
from twisted.mail import smtp

GLOBAL_CFG = "/etc/mailmail"
LOCAL_CFG = os.path.expanduser("~/.twisted/mailmail")
SMARTHOST = "127.0.0.1"

ERROR_FMT = """\
Subject: Failed Message Delivery

  Message delivery failed.  The following occurred:

  %s
--
The Twisted sendmail application.
"""

_logObserver = textFileLogObserver(sys.stderr)
_log = Logger(observer=_logObserver)


class Options:
    """
    Store the values of the parsed command-line options to the I{mailmail}
    script.

    @type to: L{list} of L{str}
    @ivar to: The addresses to which to deliver this message.

    @type sender: L{str}
    @ivar sender: The address from which this message is being sent.

    @type body: C{file}
    @ivar body: The object from which the message is to be read.
    """


def getlogin():
    try:
        return os.getlogin()
    except BaseException:
        return getpass.getuser()


_unsupportedOption = SystemExit("Unsupported option.")


def parseOptions(argv):
    o = Options()
    o.to = [e for e in argv if not e.startswith("-")]
    o.sender = getlogin()

    # Just be very stupid

    # Skip -bm -- it is the default

    # Add a non-standard option for querying the version of this tool.
    if "--version" in argv:
        print("mailmail version:", version)
        raise SystemExit()

    # -bp lists queue information.  Screw that.
    if "-bp" in argv:
        raise _unsupportedOption

    # -bs makes sendmail use stdin/stdout as its transport.  Screw that.
    if "-bs" in argv:
        raise _unsupportedOption

    # -F sets who the mail is from, but is overridable by the From header
    if "-F" in argv:
        o.sender = argv[argv.index("-F") + 1]
        o.to.remove(o.sender)

    # -i and -oi makes us ignore lone "."
    if ("-i" in argv) or ("-oi" in argv):
        raise _unsupportedOption

    # -odb is background delivery
    if "-odb" in argv:
        o.background = True
    else:
        o.background = False

    # -odf is foreground delivery
    if "-odf" in argv:
        o.background = False
    else:
        o.background = True

    # -oem and -em cause errors to be mailed back to the sender.
    # It is also the default.

    # -oep and -ep cause errors to be printed to stderr
    if ("-oep" in argv) or ("-ep" in argv):
        o.printErrors = True
    else:
        o.printErrors = False

    # -om causes a copy of the message to be sent to the sender if the sender
    # appears in an alias expansion.  We do not support aliases.
    if "-om" in argv:
        raise _unsupportedOption

    # -t causes us to pick the recipients of the message from
    # the To, Cc, and Bcc headers, and to remove the Bcc header
    # if present.
    if "-t" in argv:
        o.recipientsFromHeaders = True
        o.excludeAddresses = o.to
        o.to = []
    else:
        o.recipientsFromHeaders = False
        o.exludeAddresses = []

    requiredHeaders = {
        "from": [],
        "to": [],
        "cc": [],
        "bcc": [],
        "date": [],
    }

    buffer = StringIO()
    while 1:
        write = 1
        line = sys.stdin.readline()
        if not line.strip():
            break

        hdrs = line.split(": ", 1)

        hdr = hdrs[0].lower()
        if o.recipientsFromHeaders and hdr in ("to", "cc", "bcc"):
            o.to.extend([email.utils.parseaddr(hdrs[1])[1]])
            if hdr == "bcc":
                write = 0
        elif hdr == "from":
            o.sender = email.utils.parseaddr(hdrs[1])[1]

        if hdr in requiredHeaders:
            requiredHeaders[hdr].append(hdrs[1])

        if write:
            buffer.write(line)

    if not requiredHeaders["from"]:
        buffer.write(f"From: {o.sender}\r\n")
    if not requiredHeaders["to"]:
        if not o.to:
            raise SystemExit("No recipients specified.")
        buffer.write("To: {}\r\n".format(", ".join(o.to)))
    if not requiredHeaders["date"]:
        buffer.write(f"Date: {smtp.rfc822date()}\r\n")

    buffer.write(line)

    if o.recipientsFromHeaders:
        for a in o.excludeAddresses:
            try:
                o.to.remove(a)
            except BaseException:
                pass

    buffer.seek(0, 0)
    o.body = StringIO(buffer.getvalue() + sys.stdin.read())
    return o


class Configuration:
    """

    @ivar allowUIDs: A list of UIDs which are allowed to send mail.
    @ivar allowGIDs: A list of GIDs which are allowed to send mail.
    @ivar denyUIDs: A list of UIDs which are not allowed to send mail.
    @ivar denyGIDs: A list of GIDs which are not allowed to send mail.

    @type defaultAccess: L{bool}
    @ivar defaultAccess: L{True} if access will be allowed when no other access
    control rule matches or L{False} if it will be denied in that case.

    @ivar useraccess: Either C{'allow'} to check C{allowUID} first
    or C{'deny'} to check C{denyUID} first.

    @ivar groupaccess: Either C{'allow'} to check C{allowGID} first or
    C{'deny'} to check C{denyGID} first.

    @ivar identities: A L{dict} mapping hostnames to credentials to use when
    sending mail to that host.

    @ivar smarthost: L{None} or a hostname through which all outgoing mail will
    be sent.

    @ivar domain: L{None} or the hostname with which to identify ourselves when
    connecting to an MTA.
    """

    def __init__(self):
        self.allowUIDs = []
        self.denyUIDs = []
        self.allowGIDs = []
        self.denyGIDs = []
        self.useraccess = "deny"
        self.groupaccess = "deny"

        self.identities = {}
        self.smarthost = None
        self.domain = None

        self.defaultAccess = True


def loadConfig(path):
    # [useraccess]
    # allow=uid1,uid2,...
    # deny=uid1,uid2,...
    # order=allow,deny
    # [groupaccess]
    # allow=gid1,gid2,...
    # deny=gid1,gid2,...
    # order=deny,allow
    # [identity]
    # host1=username:password
    # host2=username:password
    # [addresses]
    # smarthost=a.b.c.d
    # default_domain=x.y.z

    c = Configuration()

    if not os.access(path, os.R_OK):
        return c

    p = ConfigParser()
    p.read(path)

    au = c.allowUIDs
    du = c.denyUIDs
    ag = c.allowGIDs
    dg = c.denyGIDs
    for section, a, d in (("useraccess", au, du), ("groupaccess", ag, dg)):
        if p.has_section(section):
            for mode, L in (("allow", a), ("deny", d)):
                if p.has_option(section, mode) and p.get(section, mode):
                    for sectionID in p.get(section, mode).split(","):
                        try:
                            sectionID = int(sectionID)
                        except ValueError:
                            _log.error(
                                "Illegal {prefix}ID in "
                                "[{section}] section: {sectionID}",
                                prefix=section[0].upper(),
                                section=section,
                                sectionID=sectionID,
                            )
                        else:
                            L.append(sectionID)
            order = p.get(section, "order")
            order = [s.split() for s in [s.lower() for s in order.split(",")]]
            if order[0] == "allow":
                setattr(c, section, "allow")
            else:
                setattr(c, section, "deny")

    if p.has_section("identity"):
        for host, up in p.items("identity"):
            parts = up.split(":", 1)
            if len(parts) != 2:
                _log.error("Illegal entry in [identity] section: {section}", section=up)
                continue
            c.identities[host] = parts

    if p.has_section("addresses"):
        if p.has_option("addresses", "smarthost"):
            c.smarthost = p.get("addresses", "smarthost")
        if p.has_option("addresses", "default_domain"):
            c.domain = p.get("addresses", "default_domain")

    return c


def success(result):
    reactor.stop()


failed = None


def failure(f):
    global failed
    reactor.stop()
    failed = f


def sendmail(host, options, ident):
    d = smtp.sendmail(host, options.sender, options.to, options.body)
    d.addCallbacks(success, failure)
    reactor.run()


def senderror(failure, options):
    recipient = [options.sender]
    sender = '"Internally Generated Message ({})"<postmaster@{}>'.format(
        sys.argv[0], smtp.DNSNAME.decode("ascii")
    )
    error = StringIO()
    failure.printTraceback(file=error)
    body = StringIO(ERROR_FMT % error.getvalue())
    d = smtp.sendmail("localhost", sender, recipient, body)
    d.addBoth(lambda _: reactor.stop())


def deny(conf):
    uid = os.getuid()
    gid = os.getgid()

    if conf.useraccess == "deny":
        if uid in conf.denyUIDs:
            return True
        if uid in conf.allowUIDs:
            return False
    else:
        if uid in conf.allowUIDs:
            return False
        if uid in conf.denyUIDs:
            return True

    if conf.groupaccess == "deny":
        if gid in conf.denyGIDs:
            return True
        if gid in conf.allowGIDs:
            return False
    else:
        if gid in conf.allowGIDs:
            return False
        if gid in conf.denyGIDs:
            return True

    return not conf.defaultAccess


def run():
    o = parseOptions(sys.argv[1:])
    gConf = loadConfig(GLOBAL_CFG)
    lConf = loadConfig(LOCAL_CFG)

    if deny(gConf) or deny(lConf):
        _log.error("Permission denied")
        return

    host = lConf.smarthost or gConf.smarthost or SMARTHOST

    ident = gConf.identities.copy()
    ident.update(lConf.identities)

    if lConf.domain:
        smtp.DNSNAME = lConf.domain
    elif gConf.domain:
        smtp.DNSNAME = gConf.domain

    sendmail(host, o, ident)

    if failed:
        if o.printErrors:
            failed.printTraceback(file=sys.stderr)
            raise SystemExit(1)
        else:
            senderror(failed, o)