summaryrefslogtreecommitdiff
path: root/script/extract.py
blob: f311fba1fceb3401cd18fa0d78d064c9d899078a (plain)
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
#!/usr/bin/env python3

"""qmauth.py

Extract delivers information about emails from a maildir.
Runs with elevated privileges.

This program is started by qmail-authuser with elevated privileges after a
successful login.
"""

import email.parser
import email.policy
import logging
import re
import socket
from base64 import b64encode
from datetime import datetime
from email.message import EmailMessage
from itertools import islice
from mailbox import Maildir, MaildirMessage, NoSuchMailboxError
from os import environ, getpid, mkdir, path, setuid, stat
from pathlib import Path
from pwd import getpwnam
from sys import exit as sysexit

import varlink


class MyMaildir(Maildir):
    def __init__(self, dirname, parent=None, *args, **kwargs):
        self.__path = Path(dirname)
        self.set_msgtype("MaildirMessage")

        super().__init__(dirname, *args, **kwargs)

    def set_msgtype(self, typ):
        if typ == "MaildirMessage":
            self._factory = None
        elif typ == "EmailMessage":
            self._factory = lambda mail_file: email.parser.BytesParser(
                policy=email.policy.default
            ).parse(mail_file)
        elif typ == "Maildir(EmailMessageHeader)":

            def factory(mail_file):
                """
                Copy from implementation.
                """
                name = Path(mail_file._file.name).name
                msg = MaildirMessage(
                    email.parser.BytesHeaderParser(policy=email.policy.default).parse(
                        mail_file
                    )
                )
                if self.colon in name:
                    msg.set_info(name.split(self.colon)[-1])
                return msg

            self._factory = factory

        elif typ == "None":
            self._factory = lambda _file: MaildirMessage(None)
        else:
            raise ValueError(typ)

    def get_filename(self, mid):
        return self.__path / self._lookup(mid)

    def get_folder(self, folder):
        """
        This is an internal copy of the implementation of Maildir.

        This is because Maildir was not designed with inheritance in mind
        and this method does hence not return an instance of itself but
        rather only and instance of Maildir.

        This override corrects this but can not anticipate additional state
        introduced in more derived classes.
        """
        return type(self)(
            path.join(self._path, "." + folder),
            create=False,
        )

    def _refresh(self):
        """
        This override of internal method _refresh that strips out 'hidden' files.
        """
        super()._refresh()
        rm = [r for r in self._toc if r.startswith(".")]
        for r in rm:
            del self._toc[r]


service = varlink.Service(
    vendor="JWebmail",
    product="Mail Storage Interface",
    version="1",
    url="https://www.fehcom.de/cgit/jwebmail2",
    interface_dir=path.join(path.dirname(__file__), "../src/jwebmail/model/"),
)


class InvalidUserError(varlink.VarlinkError):

    def __init__(self, unix_user):
        super().__init__(
            {
                "error": "de.jmhoffmann.jwebmail.mail-storage.InvalidUser",
                "parameters": {
                    "unix_user": unix_user,
                },
            }
        )


class NotInitializedError(varlink.VarlinkError):

    def __init__(self):
        super().__init__(
            {"error": "de.jmhoffmann.jwebmail.mail-storage.NotInitialized"}
        )


class InvalidMailboxError(varlink.VarlinkError):

    def __init__(self, path, not_a_mailbox, user_mismatch):
        super().__init__(
            {
                "error": "de.jmhoffmann.jwebmail.mail-storage.InvalidMailbox",
                "parameters": {
                    "path": path,
                    "not_a_mailbox": not_a_mailbox,
                    "user_mismatch": user_mismatch,
                },
            }
        )


class InvalidMIDError(varlink.VarlinkError):

    def __init__(self, folder, mid):
        super().__init__(
            {
                "error": "de.jmhoffmann.jwebmail.mail-storage.InvalidMID",
                "parameters": {
                    "folder": folder,
                    "mid": mid,
                },
            }
        )


class InvalidPathInMailError(varlink.VarlinkError):

    def __init__(self, folder, mid, path):
        super().__init__(
            {
                "error": "de.jmhoffmann.jwebmail.mail-storage.InvalidPathInMail",
                "parameters": {
                    "folder": folder,
                    "mid": mid,
                    "path": path,
                },
            }
        )


@service.interface("de.jmhoffmann.jwebmail.mail-storage")
class MailStorage:

    def __init__(self):
        self.maildir = None

    def Init(self, su, maildir):
        del environ["PATH"]

        try:
            uid = getpwnam(su).pw_uid
            if not uid:
                raise InvalidUserError(su)

            setuid(uid)

            if stat(maildir).st_uid != uid:
                raise InvalidMailboxError(
                    maildir, not_a_mailbox=False, user_mismatch=True
                )

            self.maildir = MyMaildir(maildir, create=False)
        except KeyError:
            raise InvalidUserError(su)
        except (FileNotFoundError, NoSuchMailboxError):
            raise InvalidMailboxError(maildir, not_a_mailbox=True, user_mismatch=False)

    def List(self, folder, start, end, sort):
        if self.maildir is None:
            raise NotInitializedError()

        assert 0 <= start <= end

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("Maildir(EmailMessageHeader)")

        if start == end:
            return []

        kfn, reverse = self._sort_mails(maildir, sort)
        msgs = list(maildir.items())
        msgs.sort(key=kfn, reverse=reverse)
        msgs = msgs[start : min(len(msgs), end)]

        def _get_rcv_time(mid):
            return float(mid[: mid.index(".")])

        items = [
            {
                "mid": mid,
                "byte_size": path.getsize(maildir.get_filename(mid)),
                "unread": "S" not in msg.get_flags(),
                "rec_date": datetime.fromtimestamp(_get_rcv_time(mid)).isoformat(),
                "header": self._get_head_info(msg),
            }
            for mid, msg in msgs
        ]
        return {"mail_heads": items}

    def Stats(self, folder):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("None")

        return dict(
            mail_count=len(maildir),
            unread_count=len([1 for m in maildir if "S" in m.get_flags()]),
            byte_size=sum(
                path.getsize(maildir.get_filename(mid)) for mid in maildir.keys()
            ),
        )

    def Show(self, folder, mid):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("EmailMessage")

        msg = maildir.get(mid, None)
        if not msg:
            raise InvalidMIDError(folder, mid)

        maildir.set_msgtype("MaildirMessage")

        maildir[mid].add_flag("S")

        return {
            "mail": dict(
                head=self._get_head_info(msg),
                body=self._get_body(msg),
            )
        }

    def Raw(self, folder, mid, path):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("EmailMessage")

        msg = maildir.get(mid, None)
        if not msg:
            raise InvalidMIDError(folder, mid)

        pth = [int(seg) for seg in path.split(".")] if path else []
        h = dict(mime_type={"main_type": "message", "sub_type": "rfc822"})
        b = msg

        for n in pth:
            mctype = h["mime_type"]["main_type"]

            if mctype == "multipart":
                try:
                    res = next(islice(b, n, None))
                except StopIteration:
                    raise InvalidPathInMailError(folder, mid, pth)
                (h, b) = self._descent(res)
            elif mctype == "message":
                assert n == 0
                (h, b) = self._descent(b)
            else:
                raise InvalidPathInMailError(
                    f"can not descent into non multipart content type {mctype}"
                )

        if hasattr(b, "__next__"):
            # can not stop at multipart section
            raise InvalidPathInMailError(folder=folder, mid=mid, path=pth)
        elif isinstance(b, str):
            b = b.encode()
        elif isinstance(b, EmailMessage):
            b = b.as_bytes()

        return dict(header=h, body=b64encode(b).decode("ASCII"))

    def Search(self, folder, pattern):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("EmailMessage")

        res = [
            dict(header=self._get_head_info(msg))
            for msg in maildir.values()
            if self._matches(msg, pattern)
        ]
        return {"found": res}

    def Folders(self):
        if self.maildir is None:
            raise NotInitializedError()

        return {"folders": self.maildir.list_folders()}

    def Move(self, mid, from_folder, to_folder):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if from_folder:
            maildir = maildir.get_folder(from_folder)

        fname = Path(maildir.get_filename(mid))

        assert to_folder in self.maildir.list_folders() or to_folder == ""

        sep = -2 if not from_folder else -3

        if to_folder:
            res = fname.parts[:sep] + ("." + to_folder,) + fname.parts[-2:]
        else:
            res = fname.parts[:sep] + fname.parts[-2:]

        fname.rename(Path(*res))

    def Remove(self, folder, mid):
        if self.maildir is None:
            raise NotInitializedError()

        maildir = self.maildir
        if folder:
            maildir = maildir.get_folder(folder)

        maildir.set_msgtype("MaildirMessage")

        maildir[mid].add_flag("T")

    def AddFolder(self, name):
        if self.maildir is None:
            raise NotInitializedError()

        name = path.join(
            self.maildir._path, "." + name.translate(str.maketrans("/", "."))
        )

        if path.isdir(name):
            return {"status": "skipped"}

        mkdir(name)
        mkdir(path.join(name, "cur"))
        mkdir(path.join(name, "new"))
        mkdir(path.join(name, "tmp"))

        return {"status": "created"}

    @staticmethod
    def _adr(addrs):
        if addrs is None:
            return []

        ret = []
        for addr in addrs.addresses:
            struct = {"address": addr.addr_spec}
            if addr.display_name:
                struct["name"] = addr.display_name
            ret.append(struct)
        return ret

    @staticmethod
    def _get_mime_head_info(msg):
        mh = dict(
            mime_type={
                "main_type": msg.get_content_maintype(),
                "sub_type": msg.get_content_subtype(),
            }
        )
        if (cd := msg.get_content_disposition()) == "inline":
            mh["content_dispo"] = "inline"
        elif cd == "attachment":
            mh["content_dispo"] = "attachment"
        elif cd is None:
            mh["content_dispo"] = "none"
        else:
            assert False

        if fn := msg.get_filename():
            mh["file_name"] = fn

        return mh

    def _get_head_info(self, msg):
        mh = dict(
            send_date=msg["date"].datetime.isoformat(),
            written_from=self._adr(msg["from"]),
            reply_to=self._adr(msg["reply-to"]),
            send_to=self._adr(msg["to"]),
            cc=self._adr(msg["cc"]),
            bcc=self._adr(msg["bcc"]),
            subject=msg["subject"],
            comments=msg["comments"],
            keywords=msg["keywords"],
            mime=self._get_mime_head_info(msg),
        )

        if s := self._adr(msg["sender"]):
            mh.sender = s[0]

        return mh

    def _get_body(self, mail):
        if not mail.is_multipart():
            if mail.get_content_maintype() == "text":
                return dict(discrete=mail.get_content())
            else:
                ret = mail.get_content()
                if ret.isascii():
                    return dict(discrete=ret.decode(encoding="ASCII"))
                elif len(ret) <= 128 * 1024:
                    return dict(discrete=b64encode(ret).decode(encoding="ASCII"))
                else:
                    raise ValueError(
                        "non attachment part too large (>512kB)", size=len(ret)
                    )

        if (mctype := mail.get_content_maintype()) == "message":
            msg = mail.get_content()
            return dict(
                mail=dict(head=self._get_head_info(msg), body=self._get_body(msg))
            )
        elif mctype == "multipart":
            ret = dict(
                preamble=mail.preamble,
                parts=[],
                epilogue=mail.epilogue,
            )
            for part in mail.iter_parts():
                head = self._get_mime_head_info(part)
                if head["content_dispo"] != "attachment":
                    body = self._get_body(part)
                else:
                    body = None
                ret["parts"].append(dict(mime_header=head, body=body))
            return dict(multipart=ret)
        else:
            raise ValueError(f"unknown major content-type {mctype!r}")

    def _descent(self, xx):
        head = self._get_mime_head_info(xx)
        if (mctype := head["mime_type"]["main_type"]) == "message":
            body = xx.get_content()
        elif mctype == "multipart":
            body = xx.iter_parts()
        else:
            body = xx.get_content()
        return head, body

    @staticmethod
    def _matches(m, pattern):
        if m.is_multipart():
            return any(
                1
                for part in m.body.parts
                if re.search(pattern, part.decoded())
                or re.search(pattern, part.subject)
            )
        return re.search(pattern, m.body.decoded()) or re.search(pattern, m.subject)

    @staticmethod
    def _sort_mails(f, sort):

        match sort["direction"]:
            case "asc":
                reverse = False
            case "desc":
                pass
                reverse = True
            case sort_direct:
                raise ValueError(f"unknown sort direction {sort_direct!r}")

        def _sort_by_sender(midmsg):
            _, msg = midmsg

            if len(addrs := msg["from"].addresses) == 1:
                return addrs[0].addr_spec
            else:
                return msg["sender"].address.addr_spec

        def by_rec_date(midmsg):
            return float(re.match(r"\d+\.\d+", midmsg[0], re.ASCII)[0])

        match sort["parameter"]:
            case "date":
                keyfn = by_rec_date
            case "sender":
                keyfn = _sort_by_sender
            case "subject":
                # fmt: off
                def keyfn(midmsg): return midmsg[1]["subject"]
                # fmt: on
            case "size":
                # fmt: off
                def keyfn(midmsg): return path.getsize(f.get_filename(midmsg[0]))
                # fmt: on
            case sort_param:
                logging.warning("unknown sort-verb %r", sort_param)
                reverse = False
                keyfn = by_rec_date

        return keyfn, reverse


class RequestHandler(varlink.RequestHandler):
    service = service


def main():
    try:
        logging.basicConfig(
            level="INFO",
            format="%(levelname)s:" + str(getpid()) + ":%(message)s",
        )

        if environ["LISTEN_FDS"] == "1":
            sok = socket.fromfd(3, socket.AF_UNIX, socket.SOCK_STREAM)
            RequestHandler(sok, None, None)
            return

        types = environ["LISTEN_FDNAMES"].split(":")
        assert len(types) == int(environ["LISTEN_FDS"])

        for i, typ in enumerate(types):
            if typ == "varlink":
                sok = socket.fromfd(3 + i, socket.AF_UNIX, socket.SOCK_STREAM)
                RequestHandler(sok, None, None)
                sok.close()
    except Exception:
        logging.exception("qmauth.py error")
        sysexit(4)


if __name__ == "__main__":
    main()