3 # Copyright (C) 2008-2013 W. Trevor King
4 # Copyright (C) 2012-2013 Wade Berrier
5 # Copyright (C) 2012 Niels de Vos
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.
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.
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/>.
20 "LDAP address searches for Mutt"
22 import codecs as _codecs
23 import ConfigParser as _configparser
24 import hashlib as _hashlib
26 import locale as _locale
27 import logging as _logging
28 import os.path as _os_path
29 import pickle as _pickle
34 import ldap.sasl as _ldap_sasl
36 _xdg_import_error = None
38 import xdg.BaseDirectory as _xdg_basedirectory
39 except ImportError as _xdg_import_error:
40 _xdg_basedirectory = None
46 LOG = _logging.getLogger('mutt-ldap')
47 LOG.addHandler(_logging.StreamHandler())
48 LOG.setLevel(_logging.ERROR)
51 class Config (_configparser.SafeConfigParser):
53 config_paths = self._get_config_paths()
54 LOG.info(u'load configuration from {0}'.format(config_paths))
55 read_config_paths = self.read(config_paths)
56 self._setup_defaults()
57 LOG.info(u'loaded configuration from {0}'.format(read_config_paths))
59 def get_connection_class(self):
60 if self.getboolean('cache', 'enable'):
61 return CachedLDAPConnection
65 def _setup_defaults(self):
66 "Setup dynamic default values"
67 self._setup_encoding_defaults()
68 self._setup_cache_defaults()
70 def _setup_encoding_defaults(self):
71 default_encoding = _locale.getpreferredencoding(do_setlocale=True)
72 for key in ['output-encoding', 'argv-encoding']:
75 self.get('system', key, raw=True) or default_encoding)
77 # HACK: convert sys.std{out,err} to Unicode (not needed in Python 3)
78 output_encoding = self.get('system', 'output-encoding')
79 _sys.stdout = _codecs.getwriter(output_encoding)(_sys.stdout)
80 _sys.stderr = _codecs.getwriter(output_encoding)(_sys.stderr)
82 # HACK: convert sys.argv to Unicode (not needed in Python 3)
83 argv_encoding = self.get('system', 'argv-encoding')
84 _sys.argv = [unicode(arg, argv_encoding) for arg in _sys.argv]
86 def _setup_cache_defaults(self):
87 if not self.get('cache', 'path'):
88 self.set('cache', 'path', self._get_cache_path())
89 if not self.get('cache', 'fields'):
90 # setup a reasonable default
91 fields = ['mail', 'cn', 'displayName'] # used by format_entry()
92 optional_column = self.get('results', 'optional-column')
94 fields.append(optional_column)
95 self.set('cache', 'fields', ' '.join(fields))
97 def _get_config_paths(self):
98 "Get configuration file paths"
99 if _xdg_basedirectory:
100 paths = list(reversed(list(
101 _xdg_basedirectory.load_config_paths(''))))
102 if not paths: # setup something for a useful log message
103 paths.append(_xdg_basedirectory.save_config_path(''))
105 self._log_xdg_import_error()
106 paths = [_os_path.expanduser(_os_path.join('~', '.config'))]
107 return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths]
109 def _get_cache_path(self):
110 "Get the cache file path"
111 if _xdg_basedirectory:
112 path = _xdg_basedirectory.save_cache_path('')
114 self._log_xdg_import_error()
115 path = _os_path.expanduser(_os_path.join('~', '.cache'))
116 return _os_path.join(path, 'mutt-ldap.json')
118 def _log_xdg_import_error(self):
119 global _xdg_import_error
120 if _xdg_import_error:
121 LOG.warning(u'could not import xdg.BaseDirectory '
122 u'or lacking necessary support')
123 LOG.warning(_xdg_import_error)
124 _xdg_import_error = None
128 CONFIG.add_section('connection')
129 CONFIG.set('connection', 'server', 'domaincontroller.yourdomain.com')
130 CONFIG.set('connection', 'port', '389') # set to 636 for default over SSL
131 CONFIG.set('connection', 'ssl', 'no')
132 CONFIG.set('connection', 'starttls', 'no')
133 CONFIG.set('connection', 'basedn', 'ou=x co.,dc=example,dc=net')
134 CONFIG.add_section('auth')
135 CONFIG.set('auth', 'user', '')
136 CONFIG.set('auth', 'password', '')
137 CONFIG.set('auth', 'gssapi', 'no')
138 CONFIG.add_section('query')
139 CONFIG.set('query', 'filter', '') # only match entries according to this filter
140 CONFIG.set('query', 'search-fields', 'cn displayName uid mail') # fields to wildcard search
141 CONFIG.add_section('results')
142 CONFIG.set('results', 'optional-column', '') # mutt can display one optional column
143 CONFIG.add_section('cache')
144 CONFIG.set('cache', 'enable', 'yes') # enable caching by default
145 CONFIG.set('cache', 'path', '') # cache results here, defaults to XDG
146 CONFIG.set('cache', 'fields', '') # fields to cache (if empty, setup in the main block)
147 CONFIG.set('cache', 'longevity-days', '14') # Days before cache entries are invalidated
148 CONFIG.add_section('system')
149 # HACK: Python 2.x support, see http://bugs.python.org/issue13329#msg147475
150 CONFIG.set('system', 'output-encoding', '') # match .muttrc's $charset
151 # HACK: Python 2.x support, see http://bugs.python.org/issue2128
152 CONFIG.set('system', 'argv-encoding', '')
155 class LDAPConnection (object):
156 """Wrap an LDAP connection supporting the 'with' statement
158 See PEP 343 for details.
160 def __init__(self, config=None):
164 self.connection = None
170 def __exit__(self, type, value, traceback):
174 if self.connection is not None:
175 raise RuntimeError('already connected to the LDAP server')
177 if self.config.getboolean('connection', 'ssl'):
179 url = '{0}://{1}:{2}'.format(
181 self.config.get('connection', 'server'),
182 self.config.get('connection', 'port'))
183 LOG.info(u'connect to LDAP server at {0}'.format(url))
184 self.connection = _ldap.initialize(url)
185 if (self.config.getboolean('connection', 'starttls') and
187 self.connection.start_tls_s()
188 if self.config.getboolean('auth', 'gssapi'):
189 sasl = _ldap_sasl.gssapi()
190 self.connection.sasl_interactive_bind_s('', sasl)
192 self.connection.bind(
193 self.config.get('auth', 'user'),
194 self.config.get('auth', 'password'),
198 if self.connection is None:
199 raise RuntimeError('not connected to an LDAP server')
200 LOG.info(u'unbind from LDAP server')
201 self.connection.unbind()
202 self.connection = None
204 def search(self, query):
205 if self.connection is None:
206 raise RuntimeError('connect to the LDAP server before searching')
210 fields = self.config.get('query', 'search-fields').split()
211 filterstr = u'(|{0})'.format(
212 u' '.join([u'({0}=*{1}{2})'.format(field, query, post) for
214 query_filter = self.config.get('query', 'filter')
216 filterstr = u'(&({0}){1})'.format(query_filter, filterstr)
217 LOG.info(u'search for {0}'.format(filterstr))
218 msg_id = self.connection.search(
219 self.config.get('connection', 'basedn'),
221 filterstr.encode('utf-8'))
223 while res_type != _ldap.RES_SEARCH_RESULT:
225 res_type, res_data = self.connection.result(
226 msg_id, all=False, timeout=0)
227 except _ldap.ADMINLIMIT_EXCEEDED as e:
228 LOG.warn(u'could not handle query results: {0}'.format(e))
231 # use `yield from res_data` in Python >= 3.3, see PEP 380
232 for entry in res_data:
236 class CachedLDAPConnection (LDAPConnection):
237 _cache_version = '{0}.0'.format(__version__)
240 # delay LDAP connection until we actually need it
245 super(CachedLDAPConnection, self).unbind()
249 def search(self, query):
250 cache_hit, entries = self._cache_lookup(query=query)
252 LOG.info(u'return cached entries for {0}'.format(query))
253 # use `yield from res_data` in Python >= 3.3, see PEP 380
254 for entry in entries:
257 if self.connection is None:
258 super(CachedLDAPConnection, self).connect()
260 keys = self.config.get('cache', 'fields').split()
261 for entry in super(CachedLDAPConnection, self).search(query=query):
263 # use dict comprehensions in Python >= 2.7, see PEP 274
265 [(key, data[key]) for key in keys if key in data])
266 entries.append((cn, cached_data))
268 self._cache_store(query=query, entries=entries)
270 def _load_cache(self):
271 path = _os_path.expanduser(self.config.get('cache', 'path'))
272 LOG.info(u'load cache from {0}'.format(path))
275 data = _json.load(open(path, 'rb'))
276 except IOError as e: # probably "No such file"
277 LOG.warn(u'error reading cache: {0}'.format(e))
278 except (ValueError, KeyError) as e: # probably a corrupt cache file
279 LOG.warn(u'error parsing cache: {0}'.format(e))
281 version = data.get('version', None)
282 if version == self._cache_version:
283 self._cache = data.get('queries', {})
285 LOG.debug(u'drop outdated local cache {0} != {1}'.format(
286 version, self._cache_version))
289 def _save_cache(self):
290 path = _os_path.expanduser(self.config.get('cache', 'path'))
291 LOG.info(u'save cache to {0}'.format(path))
293 'queries': self._cache,
294 'version': self._cache_version,
296 with open(path, 'wb') as f:
297 _json.dump(data, f, indent=2, separators=(',', ': '))
298 f.write('\n'.encode('utf-8'))
300 def _cache_store(self, query, entries):
301 self._cache[self._cache_key(query=query)] = {
303 'time': _time.time(),
306 def _cache_lookup(self, query):
307 data = self._cache.get(self._cache_key(query=query), None)
310 return (True, data['entries'])
312 def _cache_key(self, query):
313 return str((self._config_id(), query))
315 def _config_id(self):
316 """Return a unique ID representing the current configuration
318 config_string = _pickle.dumps(self.config)
319 return _hashlib.sha1(config_string).hexdigest()
321 def _cull_cache(self):
322 cull_days = self.config.getint('cache', 'longevity-days')
323 day_seconds = 24*60*60
324 expire = _time.time() - cull_days * day_seconds
325 for key in list(self._cache.keys()): # cull the cache
326 if self._cache[key]['time'] < expire:
327 LOG.debug('cull entry from cache: {0}'.format(key))
331 def _decode_query_data(obj):
332 if isinstance(obj, unicode): # e.g. cached JSON data
334 return unicode(obj, 'utf-8')
336 def format_columns(address, data):
337 yield _decode_query_data(address)
338 yield _decode_query_data(data.get('displayName', data['cn'])[-1])
339 optional_column = CONFIG.get('results', 'optional-column')
340 if optional_column in data:
341 yield _decode_query_data(data[optional_column][-1])
343 def format_entry(entry):
346 for m in data['mail']:
347 # http://www.mutt.org/doc/manual/manual-4.html#ss4.5
348 # Describes the format mutt expects: address\tname
349 yield u'\t'.join(format_columns(m, data))
352 if __name__ == '__main__':
355 if len(_sys.argv) < 2:
356 LOG.error(u'{0}: no search string given'.format(_sys.argv[0]))
359 query = u' '.join(_sys.argv[1:])
361 connection_class = CONFIG.get_connection_class()
363 with connection_class() as connection:
364 entries = connection.search(query=query)
365 for entry in entries:
366 addresses.extend(format_entry(entry))
367 print(u'{0} addresses found:'.format(len(addresses)))
368 print(u'\n'.join(addresses))