summaryrefslogtreecommitdiffstats
path: root/wallace/module_signature.py
blob: dda2d92396c7c6032600b47ec294aa463ee8daa0 (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
# -*- coding: utf-8 -*-
# Copyright 2010-2019 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import json
import os
import re
import tempfile

from email.encoders import encode_quopri
from email.parser import Parser
from email.utils import getaddresses

import modules
import pykolab

from pykolab.auth import Auth
from pykolab.translate import _

# pylint: disable=invalid-name
log = pykolab.getLogger('pykolab.wallace/signature')
extra_log_params = {'qid': '-'}
log = pykolab.logger.LoggerAdapter(log, extra_log_params)
conf = pykolab.getConf()

mybasepath = '/var/spool/pykolab/wallace/signature/'


def __init__():
    modules.register('signature', execute, description=description())


def description():
    return """Append a signature to messages."""


def set_part_content(part, content):
    # Reset old encoding and use quoted-printable (#5414)
    del part['Content-Transfer-Encoding']
    part.set_payload(content)
    encode_quopri(part)

    return True


def attr_resolve(sender_info, attr):
    try:
        attr, attr_val = attr.split(':')
    except ValueError:
        return None

    auth = Auth()
    auth.connect()

    values = []

    if not isinstance(sender_info[attr], list):
        sender_info[attr] = [sender_info[attr]]

    for sender_attr_val in sender_info[attr]:
        values.append(auth.get_entry_attribute(None, sender_attr_val, attr_val))

    return ", ".join(values)


# pylint: disable=too-many-branches,too-many-locals,too-many-statements
def execute(*args, **kw):  # noqa: C901
    global extra_log_params

    # TODO: Test for correct call.
    filepath = args[0]

    extra_log_params['qid'] = os.path.basename(filepath)

    if not os.path.isdir(mybasepath):
        os.makedirs(mybasepath)

    for stage in ['incoming', 'ACCEPT']:
        if not os.path.isdir(os.path.join(mybasepath, stage)):
            os.makedirs(os.path.join(mybasepath, stage))

    if 'stage' in kw:
        log.debug(_("Issuing callback after processing to stage %s") % (kw['stage']), level=8)
        log.debug(_("Testing cb_action_%s()") % (kw['stage']), level=8)
        if hasattr(modules, 'cb_action_%s' % (kw['stage'])):
            log.debug(_("Attempting to execute cb_action_%s()") % (kw['stage']), level=8)
            exec('modules.cb_action_%s(%r, %r)' % (kw['stage'], 'signature', filepath))
            return

    log.debug(_("Executing module signature for %r, %r") % (args, kw), level=8)

    new_filepath = os.path.join(
        '/var/spool/pykolab/wallace/signature/incoming',
        os.path.basename(filepath)
    )

    os.rename(filepath, new_filepath)
    filepath = new_filepath

    # parse message
    message = Parser().parse(open(filepath, 'r'))

    sender_address = [
        address for displayname, address in getaddresses(message.get_all('X-Kolab-From'))
    ][0]

    auth = Auth()
    auth.connect()

    sender_dn = auth.find_recipient(sender_address)
    if not sender_dn:
        exec('modules.cb_action_%s(%r, %r)' % ('ACCEPT', 'signature', filepath))
        return

    sender_info = auth.get_entry_attributes(None, sender_dn, ['*', 'entrydn', 'manager'])

    log.debug("Sender info: %r" % (sender_info), level=7)

    signature_rules = conf.get_raw('wallace', 'signature_rules')

    if signature_rules:
        signature_rules = json.loads(signature_rules)

    log.debug("Signature rules: %r" % (signature_rules), level=7)

    signature_html = None
    signature_text = None

    sig_html_conf = conf.get_raw('wallace', 'signature_file_html')
    sig_text_conf = conf.get_raw('wallace', 'signature_file_text')

    if sig_html_conf and sig_text_conf:
        _sig_html_conf = sig_html_conf % sender_info
        _sig_text_conf = sig_text_conf % sender_info

        if not os.path.exists(_sig_html_conf):
            _sig_html_conf = '/etc/kolab/signature.d/default.html'

        if not os.path.exists(_sig_text_conf):
            _sig_text_conf = '/etc/kolab/signature.d/default.txt'

        if os.path.exists(_sig_html_conf):
            signature_html = open(_sig_html_conf, 'r').read()

        if os.path.exists(_sig_text_conf):
            signature_text = open(_sig_text_conf, 'r').read()

    if not signature_html and not signature_text and signature_rules is not None:
        for signature_rule in signature_rules:
            try:
                for attr, regex in signature_rule.iteritems():
                    if attr == "html":
                        if not os.path.exists(signature_rule['html']):
                            raise ValueError
                        continue

                    if attr == "text":
                        if not os.path.exists(signature_rule['text']):
                            raise ValueError
                        continue

                    if attr in sender_info and re.match(regex, sender_info[attr], flags=re.IGNORECASE):
                        success = False

                        while not success:
                            try:
                                signature_html = open(signature_rule['html'], 'r').read() % sender_info
                                signature_text = open(signature_rule['text'], 'r').read() % sender_info

                                success = True

                            except KeyError as errmsg:
                                sender_info[errmsg] = attr_resolve(sender_info, errmsg)
            except ValueError:
                continue

    if signature_html is None and signature_text is None:
        exec('modules.cb_action_%s(%r, %r)' % ('ACCEPT', 'signature', filepath))
        return

    signature_added = False

    try:
        _signature_added = message.get("X-Wallace-Signature")

    # pylint: disable=broad-except
    except Exception:
        pass

    if _signature_added == "YES":
        exec('modules.cb_action_%s(%r, %r)' % ('ACCEPT','signature', filepath))
        return

    for part in message.walk():
        disposition = None

        try:
            content_type = part.get_content_type()

        # pylint: disable=broad-except
        except Exception:
            continue

        try:
            disposition = part.get("Content-Disposition")

        # pylint: disable=broad-except
        except Exception:
            pass

        log.debug("Walking message part: %s; disposition = %r" % (content_type, disposition), level=8)

        if disposition is not None:
            continue

        if content_type == "text/plain":
            content = part.get_payload(decode=True)
            content += "\n\n-- \n%s" % (signature_text)
            signature_added = set_part_content(part, content)

        elif content_type == "text/html":
            content = part.get_payload(decode=True)
            append = "\n<!-- signature appended by Wallace -->\n" + signature_html
            if "</body>" in content:
                content = content.replace("</body>", append + "</body>")
            else:
                content = "<html><body>" + content + append + "</body></html>"
            signature_added = set_part_content(part, content)

    if signature_added:
        log.debug("Signature attached.", level=8)
        message.add_header("X-Wallace-Signature", "YES")

    (fp, new_filepath) = tempfile.mkstemp(dir="/var/spool/pykolab/wallace/signature/ACCEPT")
    os.write(fp, message.as_string())
    os.close(fp)
    os.unlink(filepath)

    exec('modules.cb_action_%s(%r, %r)' % ('ACCEPT','signature', new_filepath))