summaryrefslogtreecommitdiff
path: root/old/server_receiver.py
blob: e22b8689683d8da2ebc02e1ba5cf2f33836897ce (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
#!/usr/bin/env python3
#
# Federated Electronic Memo Server written in Python.
#
# vim: colorcolumn=72
#

from __future__ import annotations
from typing import Awaitable, Callable

from time import time
from pprint import pprint
import certifi
import os
import ssl
import re
import socket
import threading
import _thread
import logging

from config import *

LOCAL_RECIPIENTS_LOWERCASED = {}
for k, v in LOCAL_RECIPIENTS.items():
    LOCAL_RECIPIENTS_LOWERCASED[k.lower()] = v

from ememo_common_old import parse_address, parse_header_line

logging.basicConfig(level=logging.INFO)


def connection_session(conn, addr):
    cert = conn.getpeercert()
    domains = [d[1] for d in cert["subjectAltName"]]

    buffer = b""
    maintext = b""
    headers = {}
    while True:
        newly_received = conn.recv(1024)
        if newly_received == b"":
            conn.close()
            return
        buffer += newly_received
        lines = buffer.split(b"\n")
        if len(lines) < 2:
            # If a complete line was just received correctly, `lines'
            # should be [b"something\n", b""].  If `lines' only contains
            # one item, that means buffer hasn't got a complete line
            # yet, and we continue receiving.
            continue
        # Now since we at least have one complete message, and the last
        # item of `lines' is incomplete, we put the incomplete part back
        # into the buffer to be used as the start of the next received
        # line, and process the current complete lines.
        buffer = lines[-1]
        complete_lines = lines[0:-1]
        finished_header = False
        for line in complete_lines:
            if line and not finished_header:
                k, v = parse_header_line(line)
                if isinstance(k, type) and issubclass(k, Exception):
                    conn.send(b"Header format error: " + v + b"\n")
                    conn.close()
                    return
                headers[k.lower()] = v
            elif not line and not finished_header:
                # There's an empty line, indicating that the headers
                # have finished, and we're entering the maintext section.
                # Since some of the maintext section might have been already
                # read, we need to add them to the read maintext: Both maintext
                # that have already been seperated into lines, and
                # remaining raw maintext that hasn't formed a line still in
                # the read buffer.  We do the latter here.
                maintext += buffer
                buffer = b""  # Good habit to clear the buffer when its
                # contents are already used elsewhere.
                finished_header = True
                # We don't break the for loop here, because there may
                # still be maintext lines lying in `complete_lines', which
                # need to be added to the maintext.
            elif finished_header:
                maintext += line + b"\n"
        if finished_header:
            break

    # Process the parsed header maintext.
    try:
        maintext_size = headers[b"maintext-size"]
        from_ = headers[b"from"]
        to = headers.get(b"to", None)
        subject = headers[b"subject"]
        cc = headers.get(b"cc", None)
        bcc = headers.get(b"bcc", None)  # Should never appear in the
        # delivered message in a user's
        # mailbox.
        send_time = headers.get(b"send-time", b"unknown")
        in_reply_to = headers.get(b"in-reply-to", None)
        mailer = headers.get(
            b"mailer", None
        )  # For example, mailing lists should set mailer
        # to the list address.  When mailer is present, its host is verfied rather than the
        # the From header's host.
        message_id = headers.get(b"message-id", b"unknown")
    except KeyError as e:
        conn.send(
            b"Missing header: "
            + repr(e.args[0]).encode("utf-8")
            + b" expected but not found.\n"
        )
        conn.close()
        return

    if mailer:
        sender_tuple = parse_address(mailer)
    else:
        sender_tuple = parse_address(from_)

    if sender_tuple[2].decode("utf-8", "surrogateescape") not in domains:
        conn.send(b"Unauthorized message: Unauthorized to send for domain.\n")
        conn.close()
        return

    try:
        maintext_size = int(maintext_size.decode("ascii"))
    except (UnicodeDecodeError, ValueError):
        conn.send(
            b"Faulty header: maintext-size should but does not represent an integer.\n"
        )
        conn.close()
        return

    afterword = b""
    if len(maintext) == maintext_size:
        pass  # Nothing to do, just note that this is possible.

    while len(maintext) < maintext_size:
        to_get = min(1024, maintext_size - len(maintext))
        newly_received = recv(to_get)
        if newly_received == b"":
            conn.close()
            return
        maintext += newly_received

    # Don't make the following block an else block.  The length of maintext
    # is altered in the last loop (len(maintext) < maintext_size) and now
    # the afterword may have been read into the maintext section (or that
    # could have even happened when we were processing the header).
    if len(maintext) > maintext_size:
        afterword += maintext[maintext_size:]
        maintext = maintext[0:maintext_size]

    assert len(maintext) == maintext_size

    received_time = str(time()).encode("ascii")

    delivery_message = b"""subject: %s
maintext-size: %s
from: %s
send-time: %s
received-time: %s
message-id: %s
""" % (
        subject,
        str(maintext_size).encode("ascii"),
        from_,
        send_time,
        received_time,
        message_id,
    )

    if to:
        delivery_message += b"to: %s\n" % to
    if cc:
        delivery_message += b"cc: %s\n" % cc
    if mailer:
        delivery_message += b"mailer: %s\n" % mailer
    if in_reply_to:
        delivery_message += b"in-reply-to: %s\n" % in_reply_to
    # BCC should not be included in the final delivery message.

    delivery_message += b"\n"
    delivery_message += maintext

    recipients = []
    if to:
        recipients += [parse_address(a) for a in to.split(b", ")]
    if cc:
        recipients += [parse_address(a) for a in cc.split(b", ")]
    if bcc:
        recipients += [parse_address(a) for a in bcc.split(b", ")]

    deliver_queue = []

    for r in recipients:
        addr = (r[1] + b"@" + r[2]).lower()
        if r[2] in MY_DOMAINS:
            try:
                deliver_queue.append((addr, LOCAL_RECIPIENTS_LOWERCASED[addr]))
            except KeyError:
                conn.send(
                    b"User not found error: Local recipients table does not contain "
                    + addr
                    + b" but "
                    + r[2]
                    + b" is a local domain.\n"
                )
                conn.close()
                return
        elif addr in LOCAL_RECIPIENTS_LOWERCASED:
            deliver_queue.append((addr, LOCAL_RECIPIENTS_LOWERCASED[addr]))
        else:
            conn.send(b"Ignoring %s (non-local recipient).\n" % (addr))

    for addr, loc in deliver_queue:
        if loc.startswith("|"):
            conn.send(b"Delivery to command standard input is not implemented.\n")
            conn.close()
            return
        else:
            try:
                with open(
                    os.path.join(loc, received_time.decode("ascii")) + ".emo",
                    "wb",
                ) as f:
                    f.write(delivery_message)
                    f.close()
            except Exception as e:
                logging.warning(repr(e) + " while trying to deliver mail.")
                conn.send(
                    b"Unable to deliver: Cannot write to mailbox.  Please contact this server's postmaster for details.\n"
                )
                conn.close()
                return
            else:
                conn.send(b"Delivered memo to %s.\n" % addr)
                logging.info(
                    "Delivered memo %s to %s." % (received_time.decode("ascii"), loc)
                )

    try:
        conn.shutdown(socket.SHUT_RDWR)
    except OSError:
        pass
    conn.close()


def raw_socket_connection_session(c, addr):
    tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    tls_context.verify_mode = ssl.CERT_REQUIRED
    tls_context.load_cert_chain(
        S2S_LISTEN_CERT,
        S2S_LISTEN_KEY,
    )
    tls_context.load_verify_locations(cafile=certifi.where())

    try:
        conn = tls_context.wrap_socket(c, server_side=True)
    except ssl.SSLError:
        # Probably it's because the client isn't using a valid (as in
        # PKI-valid) client certificate, just drop the conneciton.
        c.close()
        return None
    return connection_session(conn, addr)


def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((S2S_LISTEN_ADDR, S2S_LISTEN_PORT))
    s.listen(S2S_LISTEN_BACKLOG)
    while True:
        c, addr = s.accept()
        logging.info("Socket connection from %s port %s." % (addr[0], addr[1]))
        _thread.start_new_thread(
            raw_socket_connection_session,
            (c, addr),
        )
    s.close()


if __name__ == "__main__":
    main()