CachedLDAPConnection: Add support for cache.longevity-days
[mutt-ldap.git] / mutt-ldap.py
1 #!/usr/bin/env python2
2 #
3 # Copyright (C) 2008-2013  W. Trevor King
4 # Copyright (C) 2012-2013  Wade Berrier
5 # Copyright (C) 2012       Niels de Vos
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 """LDAP address searches for Mutt.
21
22 Add :file:`mutt-ldap.py` to your ``PATH`` and add the following line
23 to your :file:`.muttrc`::
24
25   set query_command = "mutt-ldap.py '%s'"
26
27 Search for addresses with `^t`, optionally after typing part of the
28 name.  Configure your connection by creating :file:`~/.mutt-ldap.rc`
29 contaning something like::
30
31   [connection]
32   server = myserver.example.net
33   basedn = ou=people,dc=example,dc=net
34
35 See the `CONFIG` options for other available settings.
36 """
37
38 import ConfigParser as _configparser
39 import hashlib as _hashlib
40 import os.path as _os_path
41 import pickle as _pickle
42 import time as _time
43
44 import ldap as _ldap
45 import ldap.sasl as _ldap_sasl
46
47
48 CONFIG = _configparser.SafeConfigParser()
49 CONFIG.add_section('connection')
50 CONFIG.set('connection', 'server', 'domaincontroller.yourdomain.com')
51 CONFIG.set('connection', 'port', '389')  # set to 636 for default over SSL
52 CONFIG.set('connection', 'ssl', 'no')
53 CONFIG.set('connection', 'starttls', 'no')
54 CONFIG.set('connection', 'basedn', 'ou=x co.,dc=example,dc=net')
55 CONFIG.add_section('auth')
56 CONFIG.set('auth', 'user', '')
57 CONFIG.set('auth', 'password', '')
58 CONFIG.set('auth', 'gssapi', 'no')
59 CONFIG.add_section('query')
60 CONFIG.set('query', 'filter', '') # only match entries according to this filter
61 CONFIG.set('query', 'search-fields', 'cn displayName uid mail') # fields to wildcard search
62 CONFIG.add_section('results')
63 CONFIG.set('results', 'optional-column', '') # mutt can display one optional column
64 CONFIG.add_section('cache')
65 CONFIG.set('cache', 'enable', 'yes') # enable caching by default
66 CONFIG.set('cache', 'path', '~/.mutt-ldap.cache') # cache results here
67 CONFIG.set('cache', 'fields', '')  # fields to cache (if empty, setup in the main block)
68 CONFIG.set('cache', 'longevity-days', '14') # TODO: cache results for 14 days by default
69 CONFIG.add_section('system')
70 # HACK: Python 2.x support, see http://bugs.python.org/issue2128
71 CONFIG.set('system', 'argv-encoding', 'utf-8')
72
73 CONFIG.read(_os_path.expanduser('~/.mutt-ldap.rc'))
74
75
76 class LDAPConnection (object):
77     """Wrap an LDAP connection supporting the 'with' statement
78
79     See PEP 343 for details.
80     """
81     def __init__(self, config=None):
82         if config is None:
83             config = CONFIG
84         self.config = config
85         self.connection = None
86
87     def __enter__(self):
88         self.connect()
89         return self
90
91     def __exit__(self, type, value, traceback):
92         self.unbind()
93
94     def connect(self):
95         if self.connection is not None:
96             raise RuntimeError('already connected to the LDAP server')
97         protocol = 'ldap'
98         if self.config.getboolean('connection', 'ssl'):
99             protocol = 'ldaps'
100         url = '{0}://{1}:{2}'.format(
101             protocol,
102             self.config.get('connection', 'server'),
103             self.config.get('connection', 'port'))
104         self.connection = _ldap.initialize(url)
105         if (self.config.getboolean('connection', 'starttls') and
106                 protocol == 'ldap'):
107             self.connection.start_tls_s()
108         if self.config.getboolean('auth', 'gssapi'):
109             sasl = _ldap_sasl.gssapi()
110             self.connection.sasl_interactive_bind_s('', sasl)
111         else:
112             self.connection.bind(
113                 self.config.get('auth', 'user'),
114                 self.config.get('auth', 'password'),
115                 _ldap.AUTH_SIMPLE)
116
117     def unbind(self):
118         if self.connection is None:
119             raise RuntimeError('not connected to an LDAP server')
120         self.connection.unbind()
121         self.connection = None
122
123     def search(self, query):
124         if self.connection is None:
125             raise RuntimeError('connect to the LDAP server before searching')
126         post = u''
127         if query:
128             post = u'*'
129         fields = self.config.get('query', 'search-fields').split()
130         filterstr = u'(|{0})'.format(
131             u' '.join([u'({0}=*{1}{2})'.format(field, query, post) for
132                        field in fields]))
133         query_filter = self.config.get('query', 'filter')
134         if query_filter:
135             filterstr = u'(&({0}){1})'.format(query_filter, filterstr)
136         msg_id = self.connection.search(
137             self.config.get('connection', 'basedn'),
138             _ldap.SCOPE_SUBTREE,
139             filterstr.encode('utf-8'))
140         res_type = None
141         while res_type != _ldap.RES_SEARCH_RESULT:
142             try:
143                 res_type, res_data = self.connection.result(
144                     msg_id, all=False, timeout=0)
145             except _ldap.ADMINLIMIT_EXCEEDED:
146                 #print "Partial results"
147                 break
148             if res_data:
149                 # use `yield from res_data` in Python >= 3.3, see PEP 380
150                 for entry in res_data:
151                     yield entry
152
153
154 class CachedLDAPConnection (LDAPConnection):
155     def connect(self):
156         self._load_cache()
157         super(CachedLDAPConnection, self).connect()
158
159     def unbind(self):
160         super(CachedLDAPConnection, self).unbind()
161         self._save_cache()
162
163     def search(self, query):
164         cache_hit, entries = self._cache_lookup(query=query)
165         if cache_hit:
166             # use `yield from res_data` in Python >= 3.3, see PEP 380
167             for entry in entries:
168                 yield entry
169         else:
170             entries = []
171             keys = self.config.get('cache', 'fields').split()
172             for entry in super(CachedLDAPConnection, self).search(query=query):
173                 cn,data = entry
174                 # use dict comprehensions in Python >= 2.7, see PEP 274
175                 cached_data = dict(
176                     [(key, data[key]) for key in keys if key in data])
177                 entries.append((cn, cached_data))
178                 yield entry
179             self._cache_store(query=query, entries=entries)
180
181     def _load_cache(self):
182         path = _os_path.expanduser(self.config.get('cache', 'path'))
183         try:
184             self._cache = _pickle.load(open(path, 'rb'))
185         except IOError:  # probably "No such file"
186             self._cache = {}
187         except (ValueError, KeyError):  # probably a corrupt cache file
188             self._cache = {}
189         self._cull_cache()
190
191     def _save_cache(self):
192         path = _os_path.expanduser(self.config.get('cache', 'path'))
193         _pickle.dump(self._cache, open(path, 'wb'))
194
195     def _cache_store(self, query, entries):
196         self._cache[self._cache_key(query=query)] = {
197             'entries': entries,
198             'time': _time.time(),
199             }
200
201     def _cache_lookup(self, query):
202         data = self._cache.get(self._cache_key(query=query), None)
203         if data is None:
204             return (False, data)
205         return (True, data['entries'])
206
207     def _cache_key(self, query):
208         return (self._config_id(), query)
209
210     def _config_id(self):
211         """Return a unique ID representing the current configuration
212         """
213         config_string = _pickle.dumps(self.config)
214         return _hashlib.sha1(config_string).hexdigest()
215
216     def _cull_cache(self):
217         cull_days = self.config.getint('cache', 'longevity-days')
218         day_seconds = 24*60*60
219         expire = _time.time() - cull_days * day_seconds
220         for key in list(self._cache.keys()):  # cull the cache
221             if self._cache[key]['time'] < expire:
222                 self._cache.pop(key)
223
224
225 def format_columns(address, data):
226     yield unicode(address, 'utf-8')
227     yield unicode(data.get('displayName', data['cn'])[-1], 'utf-8')
228     optional_column = CONFIG.get('results', 'optional-column')
229     if optional_column in data:
230         yield unicode(data[optional_column][-1], 'utf-8')
231
232 def format_entry(entry):
233     cn,data = entry
234     if 'mail' in data:
235         for m in data['mail']:
236             # http://www.mutt.org/doc/manual/manual-4.html#ss4.5
237             # Describes the format mutt expects: address\tname
238             yield u'\t'.join(format_columns(m, data))
239
240
241 if __name__ == '__main__':
242     import sys
243
244     # HACK: convert sys.argv to Unicode (not needed in Python 3)
245     argv_encoding = CONFIG.get('system', 'argv-encoding')
246     sys.argv = [unicode(arg, argv_encoding) for arg in sys.argv]
247
248     if len(sys.argv) < 2:
249         sys.stderr.write(u'{0}: no search string given\n'.format(sys.argv[0]))
250         sys.exit(1)
251
252     query = u' '.join(sys.argv[1:])
253
254     if CONFIG.getboolean('cache', 'enable'):
255         connection_class = CachedLDAPConnection
256         if not CONFIG.get('cache', 'fields'):
257             # setup a reasonable default
258             fields = ['mail', 'cn', 'displayName']  # used by format_entry()
259             optional_column = CONFIG.get('results', 'optional-column')
260             if optional_column:
261                 fields.append(optional_column)
262             CONFIG.set('cache', 'fields', ' '.join(fields))
263     else:
264         connection_class = LDAPConnection
265
266     addresses = []
267     with connection_class() as connection:
268         entries = connection.search(query=query)
269         for entry in entries:
270             addresses.extend(format_entry(entry))
271     print(u'{0} addresses found:'.format(len(addresses)))
272     print(u'\n'.join(addresses))