summaryrefslogtreecommitdiff
path: root/pykolab/setup/setup_imap.py
blob: 5cf60a99c822566c5f24c306fa7a3cf50e4c3d4a (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
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
# Copyright 2013, 2014 Paul Boddie <paul@boddie.org.uk>
#
# 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 components

import pykolab

from pykolab import utils
from pykolab.constants import *
from pykolab.setup.services import *
from pykolab.translate import _
import re

log = pykolab.getLogger('pykolab.setup')
conf = pykolab.getConf()

def __init__():
    components.register(
            'imap',
            execute,
            description=description(),
            after=['ldap']
        )

def cli_options():
    imap_group = conf.add_cli_parser_option_group(_("IMAP Options"))

    imap_group.add_option(
            "--choose-imap-server",
            dest    = "choose_imap_server",
            action  = "store_true",
            default = False,
            help    = _("Provide a choice of IMAP server.")
        )

def description():
    return _("Setup IMAP.")

def execute(*args, **kw):

    # Signal that interaction may occur. This will involve debconf and similar
    # system-specific mechanisms if available.

    start_interaction("kolab-conf/title-imap")
    try:
        _execute(*args, **kw)
    finally:
        stop_interaction()

def _execute(*args, **kw):
    """
        Apply the necessary settings to /etc/imapd.conf
    """

    unconfigured = conf.get('imap', 'admin_password') == "Welcome123"

    ask_for_server = unconfigured or conf.choose_imap_server

    # Where the IMAP server is to be chosen explicitly, interact with the user.

    if not conf.has_section('imap'):
        conf.add_section('imap')

    imap_uri = conf.get('imap', 'uri')
    imap_uri_default = "imaps://localhost:993/"

    if not conf.check_only:
        if ask_for_server:
            imap_uri = ask_question("kolab-conf/imap-server-selection",
                    _("""
                        Please indicate the IMAP server to be used by the Kolab
                        components. (If this is a remote server, no attempt will be
                        made to set up server instances or to configure services.)
                        """),
                    _("IMAP URI"),
                    default=(imap_uri or imap_uri_default)
                ).strip()

    # Remember the chosen server, used to connect and perform work.

    conf.command_set('imap', 'uri', imap_uri or imap_uri_default)

    imap_server = get_host_from_url(conf.get('imap', 'uri'))
    local_server = imap_server == "localhost"
    local_server_type = local_server and have_local_imap_server()

    # Only attempt to configure a local server.

    if local_server and not local_server_type:
        if conf.check_only:
            utils.setup_status("imap", _("not installed"))
        return

    # If there wasn't any URI specified, indicate that setup needs doing.

    elif not local_server:
        if conf.check_only:
            utils.setup_status("imap", not imap_uri and _("needs setup") or _("setup done"))
        return

    # Propagate the IMAP URI to any local server setting.

    if local_server:
        if not conf.has_section(local_server_type):
            conf.add_section(local_server_type)
        conf.command_set(local_server_type, 'uri', conf.get('imap', 'uri'))

    conf.command_set('kolab', 'imap_backend', local_server_type or 'remote-imap')

    # Obtain the settings.

    imapd_settings = get_imap_settings()

    # Apply the settings.

    if local_server_type == "cyrus-imap":
        matching_config = configure_cyrus_imapd(imapd_settings)
    elif local_server_type == "dovecot-imap":
        matching_config = configure_dovecot_imapd(imapd_settings)
    else:
        matching_config = True

    # When only checking, test the annotations file, give the status and return.

    if conf.check_only:
        if local_server_type == "cyrus-imap":
            matching_config = matching_config and file_contains_data('/etc/imapd.annotations.conf', annotations, exact=True)
        utils.setup_status("imap", matching_config and _("setup done") or _("needs setup"))
        return

    # Write the annotations file.

    if local_server_type == "cyrus-imap":
        fp = open('/etc/imapd.annotations.conf', 'w')
        fp.write(annotations)
        fp.close()

    # Update the configuration file.

    fp = open(conf.defaults.config_file, "w+")
    conf.cfg_parser.write(fp)
    fp.close()

    # Administer any local server.

    if local_server_type == "cyrus-imap":
        administer_cyrus_imapd()
    elif local_server_type == "dovecot-imap":
        administer_dovecot_imapd()

def get_imap_settings():
    return {
            "imap_config_dir": get_cyrus_config_base(),
            "imap_spool_dir": get_cyrus_spool_base(),
            "imap_sieve_dir": get_cyrus_sieve_base(),
            "imap_socket_dir": get_cyrus_socket_base(),
            "ldap_servers": conf.get('ldap', 'ldap_uri'),
            "ldap_host": get_host_from_url(conf.get('ldap', 'ldap_uri')),
            "ldap_base": conf.get('ldap', 'base_dn'),
            "ldap_bind_dn": conf.get('ldap', 'service_bind_dn'),
            "ldap_password": conf.get('ldap', 'service_bind_pw'),
            "ldap_user_filter": conf.get('ldap', 'kolab_user_filter'),
            "ldap_filter": '(|'
                            '(&(|(uid=%s)(uid=cyrus-murder))(uid=%%U))'
                            '(&(|(uid=%%U)(mail=%%U@%%d)(mail=%%U@%%r))(objectclass=kolabinetorgperson))'
                            ')' % conf.get('cyrus-imap', 'admin_login'),
            "ldap_user_attribute": conf.get('cyrus-sasl', 'result_attribute'),
            "ldap_group_base": conf.get('ldap', 'base_dn'),
            "ldap_group_filter": "(&(cn=%u)(objectclass=ldapsubentry)(objectclass=nsroledefinition))",
            "ldap_group_scope": "one",
            "ldap_member_base": conf.get('ldap','user_base_dn'),
            "ldap_member_method": "attribute",
            "ldap_member_attribute": "nsrole",
            "admins": conf.get('cyrus-imap', 'admin_login'),
            "postuser": "shared",
            "dovecot_mail_uid": conf.get('dovecot-imap', 'mail_uid') or 'vmail',
            "dovecot_mail_gid": conf.get('dovecot-imap', 'mail_gid') or 'vmail',
            "dovecot_mail_location": conf.get('dovecot-imap', 'mail_location') or (
                'mbox:/var/mail/%s/%%u' % (conf.get('dovecot-imap', 'mail_uid') or 'vmail')
                ),
        }

def configure_cyrus_imapd(imapd_settings):
    matching_config = True

    for template_basename, output_file, settings in [
        ('imapd.conf.tpl', '/etc/imapd.conf', [imapd_settings]),
        ('cyrus.conf.tpl', '/etc/cyrus.conf', [imapd_settings])
        ]:

        template_file = get_template_path(template_basename)

        # Instantiate the template unless only checking is being performed.

        if template_file is not None:
            matching_config = instantiate_template(template_file, output_file, settings, check_only=conf.check_only) and matching_config
        else:
            log.error(_("Could not write out Cyrus IMAP configuration file %s") % output_file)
            sys.exit(1)

    return matching_config

def configure_dovecot_imapd(imapd_settings):
    matching_config = True

    # See: http://wiki2.dovecot.org/AuthDatabase/LDAP/AuthBinds
    # See: http://wiki2.dovecot.org/Dict
    # See: http://hg.dovecot.org/dovecot-metadata-plugin/file/tip/README

    for filename, substitutions in [
    	("/etc/dovecot/conf.d/10-auth.conf", [
            ('^!include auth-system.conf.ext', '#!include auth-system.conf.ext'),
            ('^#*!include auth-ldap.conf.ext', '!include auth-ldap.conf.ext'),
            ]),
        ("/etc/dovecot/dovecot-ldap.conf.ext", [
            ('^#*hosts =.*?$', 'hosts = %(ldap_host)s' % imapd_settings),
            ('^#*dn =.*?$', 'dn = %(ldap_bind_dn)s' % imapd_settings),
            ('^#*dnpass =.*?$', 'dnpass = %(ldap_password)s' % imapd_settings),
            ('^#*base =.*?$', 'base = %(ldap_base)s' % imapd_settings),
            ('^#*auth_bind =.*?$', 'auth_bind = yes'),
            ('^#*auth_bind_userdn =.*?$', 'auth_bind_userdn = uid=%%u,%(ldap_member_base)s' % imapd_settings),
            ('^#*user_filter =.*?$', 'user_filter = (&%(ldap_user_filter)s(uid=%%u))' % imapd_settings),
            ]),
        ("/etc/dovecot/dovecot.conf", [
            ("dict {.*?}", "dict {\n  metadata = file:/var/lib/dovecot/shared-metadata\n}")
            ]),
        ("/etc/dovecot/conf.d/10-master.conf", [
            ("unix_listener dict {.*?}", "unix_listener dict {\n    mode = 0600\n    user = %(dovecot_mail_uid)s\n  }" % imapd_settings)
            ]),
        ("/etc/dovecot/conf.d/10-mail.conf", [
            ("^#*mail_plugins =.*?$", "mail_plugins = metadata"),
            ("^#*mail_uid =.*?$", "mail_uid = %(dovecot_mail_uid)s" % imapd_settings),
            ("^#*mail_gid =.*?$", "mail_gid = %(dovecot_mail_gid)s" % imapd_settings),
            ("^#*mail_location =.*?$", "mail_location = %(dovecot_mail_location)s" % imapd_settings)
            ]),
        ("/etc/dovecot/conf.d/20-imap.conf", [
            ("#*mail_plugins =.*?$", "mail_plugins = $mail_plugins imap_metadata imap_annotatemore")
            ]),
        ("/etc/dovecot/conf.d/90-plugin.conf", [
            ("plugin {\n  (?!metadata_dict = proxy::metadata)", "plugin {\n  metadata_dict = proxy::metadata\n")
            ]),
        ]:

        s = readfile(filename)
        original = s

        for pattern, substitution in substitutions:
            s = re.sub(pattern, substitution, s, flags=re.DOTALL | re.MULTILINE)

        matching_config = matching_config and original == s

        if not matching_config and not conf.check_only:
            writefile(filename, s)

    return matching_config

def administer_cyrus_imapd():
    set_service_default('kolab-saslauthd', 'START', 'yes')

    if not (
        control_service('saslauthd', 'stop') and
        control_service('kolab-saslauthd', 'restart') and
        control_service('cyrus-imapd', 'restart')
        ):

        log.error(_("Could not start the cyrus-imapd and kolab-saslauthd services."))

    if not (
        configure_service('saslauthd', False) and
        configure_service('kolab-saslauthd', True) and
        configure_service('cyrus-imapd', True)
        ):

        log.error(_("Could not configure to start on boot, the " + \
                "cyrus-imapd and kolab-saslauthd services."))

def administer_dovecot_imapd():
    set_service_default('dovecot', 'START', 'yes')

    if not control_service('dovecot', 'restart'):
        log.error(_("Could not start the dovecot service."))

    if not configure_service('dovecot', True):
        log.error(_("Could not configure to start on boot, the " + \
                "dovecot service."))

# Data used above.

annotations = """\
/vendor/kolab/activesync,mailbox,string,backend,value.priv,r
/vendor/kolab/color,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/displayname,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/folder-test,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/folder-type,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/incidences-for,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/pxfb-readable-for,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/uniqueid,mailbox,string,backend,value.shared value.priv,a
/vendor/kolab/h-share-attr-desc,mailbox,string,backend,value.shared value.priv,a
/vendor/horde/share-params,mailbox,string,backend,value.shared value.priv,a
/vendor/x-toltec/test,mailbox,string,backend,value.shared value.priv,a
"""