summaryrefslogtreecommitdiff
path: root/pykolab/cli/__init__.py
blob: 6a13c14e0a00d412d2f4f83a0467b286ed7dc261 (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
# -*- coding: utf-8 -*-
# Copyright 2010-2011 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; version 3 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

import ldap
import ldif
import logging
import traceback
import shutil
import sys
import time

from ldap.modlist import addModlist

import pykolab
import pykolab.plugins

from pykolab import utils
from pykolab import conf
from pykolab.constants import *
from pykolab.translate import _

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

auth = pykolab.auth
imap = pykolab.imap

class Cli(object):
    def __init__(self):
        domain_group = conf.add_cli_parser_option_group(_("CLI Options"))

        domain_group.add_option(    '--review',
                                    dest    = "review",
                                    action  = "store_true",
                                    default = False,
                                    help    = _("Review LDIF before committed"))

        conf.finalize_conf()

        try:
            action = conf.cli_args.pop(0)
        except IndexError, e:
            self.no_command()

        action_function = action.replace('-','_')
        action_components = action.split('-')

        if hasattr(self, "action_%s" %(action)):
            exec("self.action_%s()" %(action))
        elif hasattr(self, "action_%s" %(action_function)):
            log.info(_("TODO: self.check_%s()") %(action_function))
            exec("self.action_%s()" %(action_function))
        else:
            try:
                action_domain = action_components.pop()
                action_action = action_components.pop()
                exec("from pykolab.cli import action_%s" %(action_domain))
                if hasattr("action_%s" %(action_domain), "%s" %(action_action)):
                    exec("result = action_%s.%s(%r)" %(action_domain,action_action,conf.cli_args))
            except IndexError, e:
                self.no_command()
            except ImportError, e:
                pass

            self.print_usage()

    def no_command(self):
        print >> sys.stderr, _("No command given, see --help for details")
        sys.exit(1)

    ##
    ## Alias (shorthand) commands
    ##

    def action_cm(self):
        """
            Alias for action_create_mailbox
        """

        self.action_create_mailbox()

    def action_dm(self):
        """
            Alias for action_delete_mailbox
        """

        self.action_delete_mailbox()

    def action_lm(self):
        """
            Alias for action_list_mailbox
        """

        self.action_list_mailbox()

    ##
    ## Actual commands
    ##

    def action_add_domain(self):
        log.info(_("TODO: Figure out where the domain should actually be added."))

        domainname = conf.cli_args.pop(0)

        log.info(_("Adding domain %s") %(domainname))

        # The dn of our new entry/object
        log.info(_("TODO: Make the format for a new domain configurable."))
        dn = "associateddomain=%s,cn=kolab,cn=config" %(domainname)

        # A dict to help build the "body" of the object
        log.info(_("TODO: Make what a domain looks like configurable."))
        attrs = {}
        attrs['objectclass'] = [
                'top',
                'domainrelatedobject',
                'organization',
                'inetdomain'
            ]
        attrs['associatedDomain'] = ['%s' %(domainname)]
        domainname_components = domainname.split('.')
        attrs['inetDomainBaseDN'] = ['dc=%s,dc=%s' %(domainname_components[0],domainname_components[1])]

        log.info(_("TODO: Prompt for organization name/description. For now, use domain name."))
        attrs['o'] = ['%s' %(domainname)]

        go_ahead = True

        if conf.cli_keywords.review:
            ldif_writer = ldif.LDIFWriter(sys.stdout)
            ldif_writer.unparse(dn,attrs)
            if not utils.ask_confirmation(_("Please ACK or NACK the above LDIF:"), default="y", all_inclusive_no=True):
                go_ahead = False

        if go_ahead:
            # Convert our dict to nice syntax for the add-function using modlist-module
            _ldif = addModlist(attrs)

            # Now build an ldap connection and execute the motherf.
            ldap_con = ldap.initialize(conf.get('ldap', 'uri'))
            ldap_con.bind_s(conf.get('ldap', 'bind_dn'), conf.get('ldap', 'bind_pw'))

            # The try/except should actually be in check_add_domain
            try:
                # Do the actual synchronous add-operation to the ldapserver
                ldap_con.add_s(dn,_ldif)
            except ldap.ALREADY_EXISTS, e:
                log.error(_("Domain %s already exists.") %(domainname))

            # Its nice to the server to disconnect and free resources when done
            ldap_con.unbind_s()

    def action_add_group(self):
        print >> sys.stderr, _("Not yet implemented.")
        sys.exit(1)

    def action_add_user(self):
        print >> sys.stderr, _("Not yet implemented.")
        sys.exit(1)

    def action_create_mailbox(self):
        mailbox = conf.cli_args.pop(0)

        imap.connect()
        imap.cm(mailbox)

    def action_delete_domain(self):
        domainname = conf.cli_args.pop(0)

        log.info(_("Deleting domain %s") %(domainname))

        dn = "associateddomain=%s,cn=kolab,cn=config" %(domainname)

        ldap_con = ldap.initialize(conf.get('ldap', 'uri'))
        ldap_con.bind_s(conf.get('ldap', 'bind_dn'), conf.get('ldap', 'bind_pw'))

        # The try/except should actually be in check_del_domain()
        try:
            # Do the actual synchronous add-operation to the ldapserver
            ldap_con.delete_s(dn)
        except ldap.NO_SUCH_OBJECT, e:
            log.error(_("No domain %s exists.") %(domainname))

        # Its nice to the server to disconnect and free resources when done
        ldap_con.unbind_s()

    def action_delete_group(self):
        print >> sys.stderr, _("Not yet implemented.")
        sys.exit(1)

    def action_delete_mailbox(self):
        """
            Delete mailbox
        """

        target_folder = None

        try:
            delete_folder = conf.cli_args.pop(0)
        except IndexError, e:
            print >> sys.stderr, _("No mailbox specified")
            sys.exit(1)

        imap.connect()
        imap.dm(delete_folder)

    def action_delete_user(self):
        print >> sys.stderr, _("Not yet implemented.")
        sys.exit(1)

    def action_export_mailbox(self):
        import os
        import subprocess

        user = conf.cli_args.pop(0)

        # TODO: /etc/imapd.conf is not the definitive location for the
        # imapd.conf configuration file.
        partition_proc = subprocess.Popen(['grep', '^partition', '/etc/imapd.conf'], stdout=subprocess.PIPE)

        partitions = [x.split(':')[1].strip() for x in partition_proc.communicate()[0].split('\n') if len(x.split(':')) > 1]

        # TODO: ctl_mboxlist is not necessarily in this location.
        ctl_mboxlist_args = [ '/usr/lib/cyrus-imapd/ctl_mboxlist', '-d' ]
        ctl_mboxlist = subprocess.Popen(ctl_mboxlist_args, stdout=subprocess.PIPE)

        mboxlist_proc = subprocess.Popen(['grep', '-E', '\s*%s\s*.*i.*p.*' %(user)], stdin=ctl_mboxlist.stdout, stdout=subprocess.PIPE)
        ctl_mboxlist.stdout.close()

        mboxlist_output = mboxlist_proc.communicate()[0]

        directories = []

        for mbox_internal in mboxlist_output.split('\n'):
            if len(mbox_internal.split('\t')[0].split('!')) > 1:
                domain = mbox_internal.split('\t')[0].split('!')[0]
                mailbox = '/'.join(mbox_internal.split('\t')[0].split('!')[1].split('.')[1:])

                zipper_args = [
                        'zip',
                        '-r',
                        '%s.zip' %(user)
                    ]

                for partition in partitions:
                    if os.path.isdir('%s/domain/%s/%s/%s/user/%s/' %(partition,domain[0],domain,user[0],mailbox)):
                        directories.append('%s/domain/%s/%s/%s/user/%s/' %(partition,domain[0],domain,user[0],mailbox))
                    else:
                        log.debug(_('%s/domain/%s/%s/%s/user/%s/ is not a directory') %(partition,domain[0],domain,user[0],mailbox), level=5)

        zipper_output = subprocess.Popen(zipper_args + directories, stdout=subprocess.PIPE).communicate()[0]
        print >> sys.stderr, _("ZIP file at %s.zip") %(user)

    def action_list_deleted(self):
        """
            List deleted mailboxes
        """
        imap.connect()
        folders = imap.lm("DELETED/*")
        print "Deleted folders:"
        for folder in folders:
            print folder

    def action_list_domains(self):
        auth.connect()

        # Create the authentication object.
        # TODO: Binds with superuser credentials!
        domains = auth.list_domains()

        # TODO: Take a hint in --quiet, and otherwise print out a nice table
        # with headers and such.
        for domain,domain_aliases in domains:
            print _("Primary domain: %s - Secondary domain(s): %s") %(domain, ', '.join(domain_aliases))

    def action_list_mailbox(self):
        """
            List a mailbox
        """
        try:
            searches = [ conf.cli_args.pop(0) ]
        except IndexError, e:
            #searches = [ 'DELETED/*', 'shared/*', 'user/*' ]
            searches = [ '' ]

        imap.connect()

        folders = []

        for search in searches:
            folders.extend(imap.lm(search))

        for folder in folders:
            print folder

    def action_sync(self):
        log.debug(_("Listing domains..."), level=5)
        start_time = time.time()
        domains = auth.list_domains()
        end_time = time.time()
        log.debug(_("Found %d domains in %d seconds") %(len(domains),(end_time-start_time)), level=8)

        all_folders = []

        for primary_domain,secondary_domains in domains:
            #print "Running for domain %s" %(primary_domain)
            auth.connect(primary_domain)
            start_time = time.time()
            auth.synchronize(primary_domain, secondary_domains)
            end_time = time.time()

            log.info(_("Synchronizing users for %s took %d seconds")
                    %(primary_domain, (end_time-start_time))
                )

    def action_undelete_mailbox(self):
        """
            Undelete mailbox
        """

        target_folder = None

        undelete_folder = conf.cli_args.pop(0)
        if len(conf.cli_args) > 0:
            target_folder = conf.cli_args.pop(0)

        imap.connect()
        imap.undelete(undelete_folder, target_folder)

    def run(self):
        pass

    def print_usage(self):
        print >> sys.stderr, _("Actions") + ":"
        print >> sys.stderr, "add-domain <domainname>"
        print >> sys.stderr, "list-domains"