summaryrefslogtreecommitdiffstats
path: root/pykolab/imap/cyrus.py
blob: 09271fadc0434b0d5be26b236d95e7e9b04d954d (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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# -*- coding: utf-8 -*-
# Copyright 2010-2013 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 cyruslib
import sys
import time

from urlparse import urlparse

import pykolab

from pykolab import constants
from pykolab.imap import IMAP
from pykolab.translate import _

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


class Cyrus(cyruslib.CYRUS):
    """
        Abstraction class for some common actions to do exclusively in Cyrus.

        For example, the following functions require the commands to be
        executed against the backend server if a murder is being used.

        - Setting quota
        - Renaming the top-level mailbox
        - Setting annotations

    """

    setquota = cyruslib.CYRUS.sq

    def __init__(self, uri):
        """
            Initialize this class, but do not connect yet.
        """
        port = None

        result = urlparse(uri)

        if hasattr(result, 'hostname'):
            scheme = result.scheme
            hostname = result.hostname
            port = result.port
        else:
            scheme = uri.split(':')[0]
            (hostname, port) = uri.split('/')[2].split(':')

        if not port:
            if scheme == 'imap':
                port = 143
            else:
                port = 993

        self.server = hostname

        self.uri = "%s://%s:%s" % (scheme, hostname, port)

        while 1:
            try:
                cyruslib.CYRUS.__init__(self, self.uri)
                break
            except cyruslib.CYRUSError:
                log.warning(
                        _("Could not connect to Cyrus IMAP server %r") % (
                                self.uri
                            )
                    )

                time.sleep(10)

        if conf.debuglevel > 8:
            self.VERBOSE = True
            self.m.debug = 5

        # Initialize our variables
        self.separator = self.SEP

        # Placeholder for known mailboxes on known servers
        self.mbox = {}

    def __del__(self):
        pass

    def connect(self, uri):
        """
            Dummy connect function that checks if the server that we want to
            connect to is actually the server we are connected to.

            Uses pykolab.imap.IMAP.connect() in the background.
        """
        port = None

        result = urlparse(uri)

        if hasattr(result, 'hostname'):
            scheme = result.scheme
            hostname = result.hostname
            port = result.port
        else:
            scheme = uri.split(':')[0]
            (hostname, port) = uri.split('/')[2].split(':')

        if not port:
            if scheme == 'imap':
                port = 143
            else:
                port = 993

        if hostname == self.server:
            return

        imap = IMAP()
        imap.connect(uri=uri)

        if not self.SEP == self.separator:
            self.separator = self.SEP

    def login(self, *args, **kw):
        """
            Login to the Cyrus IMAP server through cyruslib.CYRUS, but set our
            hierarchy separator.
        """
        cyruslib.CYRUS.login(self, *args, **kw)
        self.separator = self.SEP
        try:
            self._id()
        except Exception, errmsg:
            pass

        log.debug(
                _("Continuing with separator: %r") % (self.separator),
                level=8
            )

        self.murder = False

        for capability in self.m.capabilities:
            if capability.startswith("MUPDATE="):
                log.debug(
                        _("Detected we are running in a Murder topology"),
                        level=8
                    )

                self.murder = True

        if not self.murder:
            log.debug(
                    _("This system is not part of a murder topology"),
                    level=8
                )

    def find_mailfolder_server(self, mailfolder):
        annotations = {}

        _mailfolder = self.parse_mailfolder(mailfolder)

        prefix = _mailfolder['path_parts'].pop(0)
        mbox = _mailfolder['path_parts'].pop(0)
        if _mailfolder['domain'] is not None:
            mailfolder = "%s%s%s@%s" % (
                    prefix,
                    self.separator,
                    mbox,
                    _mailfolder['domain']
                )

        # TODO: Workaround for undelete
        if len(self.lm(mailfolder)) < 1:
            return self.server

        # TODO: Murder capabilities may have been suppressed using Cyrus IMAP
        # configuration.
        if not self.murder:
            return self.server

        log.debug(
                _("Checking actual backend server for folder %s " +
                    "through annotations") % (
                        mailfolder
                    ),
                level=8
            )

        if self.mbox.has_key(mailfolder):
            log.debug(
                    _(
                            "Possibly reproducing the find " +
                            "mailfolder server answer from " +
                            "previously detected and stored " +
                            "annotation value: %r"
                        ) % (
                                self.mbox[mailfolder]
                            ),
                    level=8
                )

            if not self.mbox[mailfolder] == self.server:
                return self.mbox[mailfolder]

        max_tries = 20
        num_try = 0

        ann_path = "/vendor/cmu/cyrus-imapd/server"
        s_ann_path = "/shared%s" % (ann_path)

        while 1:
            num_try += 1
            annotations = self._getannotation(
                    mailfolder,
                    ann_path
                )

            if annotations.has_key(mailfolder):
                if annotations[mailfolder].has_key(s_ann_path):
                    break

            if max_tries <= num_try:
                log.error(
                        _("Could not get the annotations after %s tries.") % (
                                num_try
                            )
                    )

                annotations = {
                        mailfolder: {
                                s_ann_path: self.server
                            }
                    }

                break

            log.warning(
                    _("No annotations for %s: %r") % (
                            mailfolder,
                            annotations
                        )
                )

            time.sleep(1)

        server = annotations[mailfolder][s_ann_path]
        self.mbox[mailfolder] = server

        log.debug(
                _("Server for INBOX folder %s is %s") % (
                        mailfolder,
                        server
                    ),
                level=8
            )

        return server

    def folder_utf7(self, folder):
        from pykolab import imap_utf7
        return imap_utf7.encode(folder)

    def folder_utf8(self, folder):
        from pykolab import imap_utf7
        return imap_utf7.decode(folder)

    def _id(self, identity=None):
        if identity is None:
            identity = '("name" "Python/Kolab" "version" "%s")' % (constants.__version__)

        typ, dat = self.m._simple_command('ID', identity)
        res, dat = self.m._untagged_response(typ, dat, 'ID')

    def _setquota(self, mailfolder, quota):
        """
            Login to the actual backend server.
        """
        server = self.find_mailfolder_server(mailfolder)
        self.connect(self.uri.replace(self.server, server))

        log.debug(
                _("Setting quota for folder %s to %s") % (
                        mailfolder,
                        quota
                    ),
                level=8
            )

        try:
            self.m.setquota(mailfolder, quota)
        except:
            log.error(
                    _("Could not set quota for mailfolder %s") % (
                            mailfolder
                        )
                )

    def _rename(self, from_mailfolder, to_mailfolder, partition=None):
        """
            Login to the actual backend server, then rename.
        """
        server = self.find_mailfolder_server(from_mailfolder)
        self.connect(self.uri.replace(self.server, server))

        if partition is not None:
            log.debug(
                    _("Moving INBOX folder %s to %s on partition %s") % (
                            from_mailfolder,
                            to_mailfolder,
                            partition
                        ),
                    level=8
                )

        else:
            log.debug(
                    _("Moving INBOX folder %s to %s") % (
                            from_mailfolder,
                            to_mailfolder
                        ),
                    level=8
                )

        self.m.rename(
                self.folder_utf7(from_mailfolder),
                self.folder_utf7(to_mailfolder),
                partition
            )

    def _getannotation(self, *args, **kw):
        return self.getannotation(*args, **kw)

    def _setannotation(self, mailfolder, annotation, value, shared=False):
        """
            Login to the actual backend server, then set annotation.
        """
        try:
            server = self.find_mailfolder_server(mailfolder)
        except:
            server = self.server

        log.debug(
                _("Setting annotation %s on folder %s") % (
                        annotation,
                        mailfolder
                    ),
                level=8
            )

        try:
            self.setannotation(mailfolder, annotation, value, shared)
        except cyruslib.CYRUSError, errmsg:
            log.error(
                    _("Could not set annotation %r on mail folder %r: %r") % (
                            annotation,
                            mailfolder,
                            errmsg
                        )
                )

    def _xfer(self, mailfolder, current_server, new_server):
        self.connect(self.uri.replace(self.server, current_server))
        log.debug(
                _("Transferring folder %s from %s to %s") % (
                        mailfolder,
                        current_server,
                        new_server
                    ),
                level=8
            )

        self.xfer(mailfolder, new_server)

    def undelete_mailfolder(
                self,
                mailfolder,
                to_mailfolder=None,
                recursive=True
            ):
        """
            Login to the actual backend server, then "undelete" the mailfolder.

            'mailfolder' may be a string representing either of the following
            two options;

            - the fully qualified pathof the deleted folder in its current
              location, such as, for a deleted INBOX folder originally known as
              "user/userid[@domain]";

                "DELETED/user/userid/hex[@domain]"

            - the original folder name, such as;

                "user/userid[@domain]"

            'to_mailfolder' may be the target folder to "undelete" the deleted
            folder to. If not specified, the original folder name is used.
        """
        # Placeholder for folders we have recovered already.
        target_folders = []

        mailfolder = self.parse_mailfolder(mailfolder)

        undelete_folders = self._find_deleted_folder(mailfolder)

        if to_mailfolder is not None:
            target_mbox = self.parse_mailfolder(to_mailfolder)
        else:
            target_mbox = mailfolder

        for undelete_folder in undelete_folders:
            undelete_mbox = self.parse_mailfolder(undelete_folder)

            prefix = undelete_mbox['path_parts'].pop(0)
            mbox = undelete_mbox['path_parts'].pop(0)

            if to_mailfolder is None:
                target_folder = self.separator.join([prefix, mbox])
            else:
                target_folder = self.separator.join(target_mbox['path_parts'])

            if to_mailfolder is not None:
                target_folder = "%s%s%s" % (
                        target_folder,
                        self.separator,
                        mbox
                    )

            if not len(undelete_mbox['path_parts']) == 0:
                target_folder = "%s%s%s" % (
                        target_folder,
                        self.separator,
                        self.separator.join(undelete_mbox['path_parts'])
                    )

            if target_folder in target_folders:
                target_folder = "%s%s%s" % (
                        target_folder,
                        self.separator,
                        undelete_mbox['hex_timestamp']
                    )

            target_folders.append(target_folder)

            if target_mbox['domain'] is not None:
                target_folder = "%s@%s" % (
                        target_folder,
                        target_mbox['domain']
                    )

            log.info(
                    _("Undeleting %s to %s") % (
                            undelete_folder,
                            target_folder
                        )
                )

            target_server = self.find_mailfolder_server(target_folder)
            source_server = self.find_mailfolder_server(undelete_folder)

            if hasattr(conf, 'dry_run') and not conf.dry_run:
                undelete_folder = self.folder_utf7(undelete_folder)
                target_folder = self.folder_utf7(target_folder)

                if not target_server == source_server:
                    self.xfer(undelete_folder, target_server)

                self.rename(undelete_folder, target_folder)
            else:
                if not target_server == source_server:
                    print >> sys.stdout, \
                        _("Would have transferred %s from %s to %s") % (
                                undelete_folder,
                                source_server,
                                target_server
                            )

                print >> sys.stdout, \
                    _("Would have renamed %s to %s") % (
                            undelete_folder,
                            target_folder
                        )

    def parse_mailfolder(self, mailfolder):
        """
            Parse a mailfolder name to it's parts.

            Takes a fully qualified mailfolder or mailfolder sub-folder.
        """
        mbox = {
                'domain': None
            }

        if len(mailfolder.split('/')) > 1:
            self.separator = '/'

        # Split off the virtual domain identifier, if any
        if len(mailfolder.split('@')) > 1:
            mbox['domain'] = mailfolder.split('@')[1]
            mbox['path_parts'] = mailfolder.split('@')[0].split(self.separator)
        else:
            mbox['path_parts'] = mailfolder.split(self.separator)

        # See if the path that has been specified is the current location for
        # the deleted folder, or the original location, we have to find the
        # deleted folder for.
        if not mbox['path_parts'][0] in ['user', 'shared']:
            deleted_prefix = mbox['path_parts'].pop(0)
            # See if the hexadecimal timestamp is actually hexadecimal.
            # This prevents "DELETED/user/userid/Sent", but not
            # "DELETED/user/userid/FFFFFF" from being specified.
            try:
                hexstamp = mbox['path_parts'][(len(mbox['path_parts'])-1)]
                epoch = int(hexstamp, 16)
                try:
                    timestamp = time.asctime(time.gmtime(epoch))
                except:
                    return None
            except:
                return None

            # Verify that the input for the deleted folder is actually a
            # deleted folder.
            verify_folder_search = "%(dp)s%(sep)s%(mailfolder)s" % {
                    'dp': deleted_prefix,
                    'sep': self.separator,
                    'mailfolder': self.separator.join(mbox['path_parts'])
                }

            if mbox['domain'] is not None:
                verify_folder_search = "%s@%s" % (
                        verify_folder_search,
                        mbox['domain']
                    )

            if ' ' in verify_folder_search:
                folders = self.lm(
                        '"%s"' % self.folder_utf7(verify_folder_search)
                    )

            else:
                folders = self.lm(self.folder_utf7(verify_folder_search))

            # NOTE: Case also covered is valid hexadecimal folders; won't be
            # the actual check as intended, but doesn't give you anyone else's
            # data unless... See the following:
            #
            # TODO: Case not covered is usernames that are hexadecimal.
            #
            # We could probably attempt to convert the int(hex) into a
            # time.gmtime(), but it still would not cover all cases.
            #

            # If no folders were found... well... then there you go.
            if len(folders) < 1:
                return None

            # Pop off the hex timestamp, which turned out to be valid
            mbox['hex_timestamp'] = mbox['path_parts'].pop()

        return mbox

    def _find_deleted_folder(self, mbox):
        """
            Give me the parts that are in an original mailfolder name and I'll
            find the deleted folder name.

            TODO: It finds virtdomain folders for non-virtdomain searches.
        """
        deleted_folder_search = "%(deleted_prefix)s%(separator)s" + \
            "%(mailfolder)s%(separator)s*" % {
                # TODO: The prefix used is configurable
                'deleted_prefix': "DELETED",
                'mailfolder': self.separator.join(mbox['path_parts']),
                'separator': self.separator,
            }

        if mbox['domain'] is not None:
            deleted_folder_search = "%s@%s" % (
                    deleted_folder_search,
                    mbox['domain']
                )

        folders = self.lm(self.folder_utf7(deleted_folder_search))

        # The folders we have found at this stage include virtdomain folders.
        #
        # For example, having searched for user/userid, it will also find
        # user/userid@example.org
        #

        # Here, we explicitly remove any virtdomain folders.
        if mbox['domain'] is None:
            _folders = []
            for folder in folders:
                if len(folder.split('@')) < 2:
                    _folders.append(folder)

            folders = _folders

        return [self.folder_utf8(x) for x in folders]