"""
ldapurl - handling of LDAP URLs as described in RFC 4516
See http://www.python-ldap.org/ for details.
\$Id: ldapurl.py,v 1.43 2009/08/16 18:45:31 stroeder Exp $
Python compability note:
This module only works with Python 2.0+ since
1. string methods are used instead of module string and
2. list comprehensions are used.
"""
__version__ = '2.3.10'
__all__ = [
# constants
'SEARCH_SCOPE','SEARCH_SCOPE_STR',
'LDAP_SCOPE_BASE','LDAP_SCOPE_ONELEVEL','LDAP_SCOPE_SUBTREE',
# functions
'isLDAPUrl',
# classes
'LDAPUrlExtension','LDAPUrlExtensions','LDAPUrl'
]
import UserDict
from urllib import quote,unquote
LDAP_SCOPE_BASE = 0
LDAP_SCOPE_ONELEVEL = 1
LDAP_SCOPE_SUBTREE = 2
SEARCH_SCOPE_STR = {None:'',0:'base',1:'one',2:'sub'}
SEARCH_SCOPE = {
'':None,
# the search scope strings defined in RFC2255
'base':LDAP_SCOPE_BASE,
'one':LDAP_SCOPE_ONELEVEL,
'sub':LDAP_SCOPE_SUBTREE,
}
# Some widely used types
StringType = type('')
TupleType=type(())
def isLDAPUrl(s):
"""
Returns 1 if s is a LDAP URL, 0 else
"""
s_lower = s.lower()
return \
s_lower.startswith('ldap://') or \
s_lower.startswith('ldaps://') or \
s_lower.startswith('ldapi://')
def ldapUrlEscape(s):
"""Returns URL encoding of string s"""
return quote(s).replace(',','%2C').replace('/','%2F')
class LDAPUrlExtension:
"""
Class for parsing and unparsing LDAP URL extensions
as described in RFC 4516.
Usable class attributes:
critical
Boolean integer marking the extension as critical
extype
Type of extension
exvalue
Value of extension
"""
def __init__(self,extensionStr=None,critical=0,extype=None,exvalue=None):
self.critical = critical
self.extype = extype
self.exvalue = exvalue
if extensionStr:
self._parse(extensionStr)
def _parse(self,extension):
extension = extension.strip()
if not extension:
# Don't parse empty strings
self.extype,self.exvalue = None,None
return
self.critical = extension[0]=='!'
if extension[0]=='!':
extension = extension[1:].strip()
try:
self.extype,self.exvalue = extension.split('=',1)
except ValueError:
# No value, just the extype
self.extype,self.exvalue = extension,None
else:
self.exvalue = unquote(self.exvalue.strip())
self.extype = self.extype.strip()
def unparse(self):
if self.exvalue is None:
return '%s%s' % ('!'*(self.critical>0),self.extype)
else:
return '%s%s=%s' % (
'!'*(self.critical>0),
self.extype,quote(self.exvalue or '')
)
def __str__(self):
return self.unparse()
def __repr__(self):
return '<%s.%s instance at %s: %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self)),
self.__dict__
)
def __eq__(self,other):
return \
(self.critical==other.critical) and \
(self.extype==other.extype) and \
(self.exvalue==other.exvalue)
def __ne__(self,other):
return not self.__eq__(other)
class LDAPUrlExtensions(UserDict.UserDict):
"""
Models a collection of LDAP URL extensions as
dictionary type
"""
def __init__(self,default=None):
UserDict.UserDict.__init__(self)
for k,v in (default or {}).items():
self[k]=v
def __setitem__(self,name,value):
"""
value
Either LDAPUrlExtension instance, (critical,exvalue)
or string'ed exvalue
"""
assert isinstance(value,LDAPUrlExtension)
assert name==value.extype
self.data[name] = value
def values(self):
return [
self[k]
for k in self.keys()
]
def __str__(self):
return ','.join(map(str,self.values()))
def __repr__(self):
return '<%s.%s instance at %s: %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self)),
self.data
)
def __eq__(self,other):
assert isinstance(other,self.__class__),TypeError(
"other has to be instance of %s" % (self.__class__)
)
return self.data==other.data
def parse(self,extListStr):
for extension_str in extListStr.strip().split(','):
if extension_str:
e = LDAPUrlExtension(extension_str)
self[e.extype] = e
def unparse(self):
return ','.join([ v.unparse() for v in self.values() ])
class LDAPUrl:
"""
Class for parsing and unparsing LDAP URLs
as described in RFC 4516.
Usable class attributes:
urlscheme
URL scheme (either ldap, ldaps or ldapi)
hostport
LDAP host (default '')
dn
String holding distinguished name (default '')
attrs
list of attribute types (default None)
scope
integer search scope for ldap-module
filterstr
String representation of LDAP Search Filters
(see RFC 2254)
extensions
Dictionary used as extensions store
who
Maps automagically to bindname LDAP URL extension
cred
Maps automagically to X-BINDPW LDAP URL extension
"""
attr2extype = {'who':'bindname','cred':'X-BINDPW'}
def __init__(
self,
ldapUrl=None,
urlscheme='ldap',
hostport='',dn='',attrs=None,scope=None,filterstr=None,
extensions=None,
who=None,cred=None
):
self.urlscheme=urlscheme
self.hostport=hostport
self.dn=dn
self.attrs=attrs
self.scope=scope
self.filterstr=filterstr
self.extensions=(extensions or LDAPUrlExtensions({}))
if ldapUrl!=None:
self._parse(ldapUrl)
if who!=None:
self.who = who
if cred!=None:
self.cred = cred
def __eq__(self,other):
return \
self.urlscheme==other.urlscheme and \
self.hostport==other.hostport and \
self.dn==other.dn and \
self.attrs==other.attrs and \
self.scope==other.scope and \
self.filterstr==other.filterstr and \
self.extensions==other.extensions
def __ne__(self,other):
return not self.__eq__(other)
def _parse(self,ldap_url):
"""
parse a LDAP URL and set the class attributes
urlscheme,host,dn,attrs,scope,filterstr,extensions
"""
if not isLDAPUrl(ldap_url):
raise ValueError,'Parameter ldap_url does not seem to be a LDAP URL.'
scheme,rest = ldap_url.split('://',1)
self.urlscheme = scheme.strip()
if not self.urlscheme in ['ldap','ldaps','ldapi']:
raise ValueError,'LDAP URL contains unsupported URL scheme %s.' % (self.urlscheme)
slash_pos = rest.find('/')
qemark_pos = rest.find('?')
if (slash_pos==-1) and (qemark_pos==-1):
# No / and ? found at all
self.hostport = unquote(rest)
self.dn = ''
return
else:
if slash_pos!=-1 and (qemark_pos==-1 or (slash_pos