<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[12149] twext/trunk/twext/who/opendirectory</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/12149">12149</a></dd>
<dt>Author</dt> <dd>wsanchez@apple.com</dd>
<dt>Date</dt> <dd>2013-12-19 11:46:53 -0800 (Thu, 19 Dec 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>Make submodules private.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextwhoopendirectory__init__py">twext/trunk/twext/who/opendirectory/__init__.py</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#twexttrunktwextwhoopendirectory_odframeworkpy">twext/trunk/twext/who/opendirectory/_odframework.py</a></li>
<li><a href="#twexttrunktwextwhoopendirectory_servicepy">twext/trunk/twext/who/opendirectory/_service.py</a></li>
</ul>

<h3>Removed Paths</h3>
<ul>
<li><a href="#twexttrunktwextwhoopendirectoryodframeworkpy">twext/trunk/twext/who/opendirectory/odframework.py</a></li>
<li><a href="#twexttrunktwextwhoopendirectoryservicepy">twext/trunk/twext/who/opendirectory/service.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="twexttrunktwextwhoopendirectory__init__py"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/who/opendirectory/__init__.py (12148 => 12149)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/__init__.py        2013-12-19 19:43:30 UTC (rev 12148)
+++ twext/trunk/twext/who/opendirectory/__init__.py        2013-12-19 19:46:53 UTC (rev 12149)
</span><span class="lines">@@ -28,7 +28,7 @@
</span><span class="cx"> ]
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-from .service import (
</del><ins>+from ._service import (
</ins><span class="cx">     OpenDirectoryError, OpenDirectoryConnectionError, OpenDirectoryQueryError,
</span><span class="cx">     OpenDirectoryDataError,
</span><span class="cx">     DirectoryService, DirectoryRecord,
</span></span></pre></div>
<a id="twexttrunktwextwhoopendirectory_odframeworkpyfromrev12148twexttrunktwextwhoopendirectoryodframeworkpy"></a>
<div class="copfile"><h4>Copied: twext/trunk/twext/who/opendirectory/_odframework.py (from rev 12148, twext/trunk/twext/who/opendirectory/odframework.py) (0 => 12149)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/_odframework.py                                (rev 0)
+++ twext/trunk/twext/who/opendirectory/_odframework.py        2013-12-19 19:46:53 UTC (rev 12149)
</span><span class="lines">@@ -0,0 +1,30 @@
</span><ins>+##
+# Copyright (c) 2010-2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+&quot;&quot;&quot;
+OpenDirectory.framework
+&quot;&quot;&quot;
+
+import objc as _objc
+
+__bundle__ = _objc.initFrameworkWrapper(
+    &quot;OpenDirectory&quot;,
+    frameworkIdentifier=&quot;com.apple.OpenDirectory&quot;,
+    frameworkPath=_objc.pathForFramework(
+        &quot;/System/Library/Frameworks/OpenDirectory.framework&quot;
+    ),
+    globals=globals()
+)
</ins></span></pre></div>
<a id="twexttrunktwextwhoopendirectory_servicepyfromrev12148twexttrunktwextwhoopendirectoryservicepy"></a>
<div class="copfile"><h4>Copied: twext/trunk/twext/who/opendirectory/_service.py (from rev 12148, twext/trunk/twext/who/opendirectory/service.py) (0 => 12149)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/_service.py                                (rev 0)
+++ twext/trunk/twext/who/opendirectory/_service.py        2013-12-19 19:46:53 UTC (rev 12149)
</span><span class="lines">@@ -0,0 +1,716 @@
</span><ins>+# -*- test-case-name: twext.who.opendirectory.test.test_service -*-
+##
+# Copyright (c) 2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from __future__ import print_function
+
+&quot;&quot;&quot;
+OpenDirectory directory service implementation.
+&quot;&quot;&quot;
+
+from zope.interface import implements
+
+from twisted.python.constants import (
+    Names, NamedConstant, Values, ValueConstant,
+)
+from twisted.internet.defer import succeed, fail
+from twisted.cred.checkers import ICredentialsChecker
+from twisted.cred.credentials import (
+    IUsernamePassword, IUsernameHashedPassword, DigestedCredentials,
+)
+from twisted.cred.error import UnauthorizedLogin
+# from twisted.web.guard import DigestCredentialFactory
+
+from twext.python.log import Logger
+
+from ..idirectory import (
+    DirectoryServiceError, QueryNotSupportedError,
+    FieldName as BaseFieldName, RecordType as BaseRecordType,
+)
+from ..directory import (
+    DirectoryService as BaseDirectoryService,
+    DirectoryRecord as BaseDirectoryRecord,
+)
+from ..expression import (
+    CompoundExpression, Operand, MatchExpression, MatchType, MatchFlags,
+)
+from ..util import iterFlags, ConstantsContainer
+
+from ._odframework import ODSession, ODNode, ODQuery
+
+
+
+#
+# Exceptions
+#
+
+class OpenDirectoryError(DirectoryServiceError):
+    &quot;&quot;&quot;
+    OpenDirectory error.
+    &quot;&quot;&quot;
+
+    def __init__(self, message, odError):
+        super(OpenDirectoryError, self).__init__(message)
+        self.odError = odError
+
+
+
+class OpenDirectoryConnectionError(OpenDirectoryError):
+    &quot;&quot;&quot;
+    OpenDirectory connection error.
+    &quot;&quot;&quot;
+
+
+
+class OpenDirectoryQueryError(OpenDirectoryError):
+    &quot;&quot;&quot;
+    OpenDirectory query error.
+    &quot;&quot;&quot;
+
+
+class OpenDirectoryDataError(OpenDirectoryError):
+    &quot;&quot;&quot;
+    OpenDirectory data error.
+    &quot;&quot;&quot;
+
+
+
+#
+# Constants
+#
+
+class FieldName(Names):
+    searchPath = NamedConstant()
+    searchPath.description = &quot;search path&quot;
+    searchPath.multiValue = False
+
+    metaNodeLocation = NamedConstant()
+    metaNodeLocation.description = &quot;source OD node&quot;
+    metaNodeLocation.multiValue = False
+
+    metaRecordName = NamedConstant()
+    metaRecordName.description = &quot;meta record name&quot;
+    metaRecordName.multiValue = False
+
+
+
+#
+# OD Constants
+#
+
+class ODSearchPath(Values):
+    local = ValueConstant(&quot;/Local/Default&quot;)
+    search = ValueConstant(&quot;/Search&quot;)
+
+
+
+class ODRecordType(Values):
+    user = ValueConstant(&quot;dsRecTypeStandard:Users&quot;)
+    user.recordType = BaseRecordType.user
+
+    group = ValueConstant(&quot;dsRecTypeStandard:Groups&quot;)
+    group.recordType = BaseRecordType.group
+
+
+    @classmethod
+    def fromRecordType(cls, recordType):
+        if not hasattr(cls, &quot;_recordTypeByRecordType&quot;):
+            cls._recordTypeByRecordType = dict((
+                (recordType.recordType, recordType)
+                for recordType in cls.iterconstants()
+            ))
+
+        return cls._recordTypeByRecordType.get(recordType, None)
+
+
+
+class ODAttribute(Values):
+    searchPath = ValueConstant(&quot;dsAttrTypeStandard:SearchPath&quot;)
+    searchPath.fieldName = FieldName.searchPath
+
+    recordType = ValueConstant(&quot;dsAttrTypeStandard:RecordType&quot;)
+    recordType.fieldName = BaseFieldName.recordType
+
+    uid = ValueConstant(&quot;dsAttrTypeStandard:GeneratedUID&quot;)
+    uid.fieldName = BaseFieldName.uid
+
+    guid = ValueConstant(&quot;dsAttrTypeStandard:GeneratedUID&quot;)
+    guid.fieldName = BaseFieldName.guid
+
+    shortName = ValueConstant(&quot;dsAttrTypeStandard:RecordName&quot;)
+    shortName.fieldName = BaseFieldName.shortNames
+
+    fullName = ValueConstant(&quot;dsAttrTypeStandard:RealName&quot;)
+    fullName.fieldName = BaseFieldName.fullNames
+
+    emailAddress = ValueConstant(&quot;dsAttrTypeStandard:EMailAddress&quot;)
+    emailAddress.fieldName = BaseFieldName.emailAddresses
+
+    metaNodeLocation = ValueConstant(
+        &quot;dsAttrTypeStandard:AppleMetaNodeLocation&quot;
+    )
+    metaNodeLocation.fieldName = FieldName.metaNodeLocation
+
+    metaRecordName = ValueConstant(&quot;dsAttrTypeStandard:AppleMetaRecordName&quot;)
+    metaRecordName.fieldName = FieldName.metaRecordName
+
+
+    @classmethod
+    def fromFieldName(cls, fieldName):
+        if not hasattr(cls, &quot;_attributesByFieldName&quot;):
+            cls._attributesByFieldName = dict((
+                (attribute.fieldName, attribute)
+                for attribute in cls.iterconstants()
+                if hasattr(attribute, &quot;fieldName&quot;)
+            ))
+
+        return cls._attributesByFieldName.get(fieldName, None)
+
+
+
+class ODMatchType(Values):
+    equals = ValueConstant(0x2001)
+    equals.matchType = MatchType.equals
+
+    startsWith = ValueConstant(0x2002)
+    startsWith.matchType = MatchType.startsWith
+
+    endsWith = ValueConstant(0x2003)
+    endsWith.matchType = MatchType.endsWith
+
+    contains = ValueConstant(0x2004)
+    contains.matchType = MatchType.contains
+
+    lessThan = ValueConstant(0x2005)
+    lessThan.matchType = MatchType.lessThan
+
+    greaterThan = ValueConstant(0x2006)
+    greaterThan.matchType = MatchType.greaterThan
+
+    lessThanOrEqualTo = ValueConstant(0x2007)
+    lessThanOrEqualTo.matchType = MatchType.lessThanOrEqualTo
+
+    greaterThanOrEqualTo = ValueConstant(0x2008)
+    greaterThanOrEqualTo.matchType = MatchType.greaterThanOrEqualTo
+
+    compound = ValueConstant(0x210B)
+    compound.matchType = MatchType.compound
+
+
+    @classmethod
+    def fromMatchType(cls, matchType):
+        if not hasattr(cls, &quot;_matchTypeByMatchType&quot;):
+            cls._matchTypeByMatchType = dict((
+                (matchType.matchType, matchType)
+                for matchType in cls.iterconstants()
+            ))
+
+        return cls._matchTypeByMatchType.get(matchType, None)
+
+
+
+class ODMatchFlags(Values):
+    caseInsensitive = ValueConstant(0x100)
+
+
+
+#
+# Directory Service
+#
+
+class DirectoryService(BaseDirectoryService):
+    &quot;&quot;&quot;
+    OpenDirectory directory service.
+    &quot;&quot;&quot;
+
+    implements(ICredentialsChecker)
+    credentialInterfaces = (IUsernamePassword, IUsernameHashedPassword)
+
+    log = Logger()
+
+    recordType = ConstantsContainer((
+        BaseRecordType.user, BaseRecordType.group,
+    ))
+
+    fieldName = ConstantsContainer((BaseDirectoryService.fieldName, FieldName))
+
+
+
+    def __init__(self, nodeName=ODSearchPath.search.value):
+        &quot;&quot;&quot;
+        @param nodeName: the OpenDirectory node to query against.
+        @type nodeName: bytes
+        &quot;&quot;&quot;
+        self._nodeName = nodeName
+
+
+    @property
+    def nodeName(self):
+        return self._nodeName
+
+
+    @property
+    def realmName(self):
+        return &quot;OpenDirectory Node {self.nodeName!r}&quot;.format(self=self)
+
+
+    @property
+    def session(self):
+        &quot;&quot;&quot;
+        Get the underlying directory session.
+        &quot;&quot;&quot;
+        self._connect()
+        return self._session
+
+
+    @property
+    def node(self):
+        &quot;&quot;&quot;
+        Get the underlying (network) directory node.
+        &quot;&quot;&quot;
+        self._connect()
+        return self._node
+
+
+    # @property
+    # def localNode(self):
+    #     &quot;&quot;&quot;
+    #     Get the local node from the search path (if any), so that we can
+    #     handle it specially.
+    #     &quot;&quot;&quot;
+    #     if not hasattr(self, &quot;_localNode&quot;):
+    #         if self.nodeName == ODSearchPath.search.value:
+    #             result = getNodeAttributes(
+    #                 self.node, ODSearchPath.search.value,
+    #                 (ODAttribute.searchPath.value,)
+    #             )
+    #             if (
+    #                 ODSearchPath.local.value in
+    #                 result[ODAttribute.searchPath.value]
+    #             ):
+    #                 try:
+    #                     self._localNode = odInit(ODSearchPath.local.value)
+    #                 except ODError, e:
+    #                     self.log.error(
+    #                         &quot;Failed to open local node: {error}}&quot;,
+    #                         error=e,
+    #                     )
+    #                     raise OpenDirectoryError(e)
+    #             else:
+    #                 self._localNode = None
+
+    #         elif self.nodeName == ODSearchPath.local.value:
+    #             self._localNode = self.node
+
+    #         else:
+    #             self._localNode = None
+
+    #     return self._localNode
+
+
+    def _connect(self):
+        &quot;&quot;&quot;
+        Connect to the directory server.
+
+        @raises: L{OpenDirectoryConnectionError} if unable to connect.
+        &quot;&quot;&quot;
+        if not hasattr(self, &quot;_session&quot;):
+            session = ODSession.defaultSession()
+
+            node, error = ODNode.nodeWithSession_name_error_(
+                session, self.nodeName, None
+            )
+
+            if error:
+                self.log.error(
+                    &quot;Error while trying to connect to OpenDirectory node &quot;
+                    &quot;{source.nodeName!r}: {error}&quot;,
+                    error=error
+                )
+                raise OpenDirectoryConnectionError(error)
+
+            self._session = session
+            self._node = node
+
+
+    def _queryStringFromExpression(self, expression):
+        &quot;&quot;&quot;
+        Converts either a MatchExpression or a CompoundExpression into a native
+        OpenDirectory query string.
+
+        @param expression: The expression
+        @type expression: Either L{MatchExpression} or L{CompoundExpression}
+
+        @return: A native OpenDirectory query string
+        @rtype: C{unicode}
+        &quot;&quot;&quot;
+
+        if isinstance(expression, MatchExpression):
+            matchType = ODMatchType.fromMatchType(expression.matchType)
+            if matchType is None:
+                raise QueryNotSupportedError(
+                    &quot;Unknown match type: {0}&quot;.format(matchType)
+                )
+            odAttr = ODAttribute.fromFieldName(expression.fieldName).value
+            queryString = {
+                ODMatchType.equals.value: u&quot;({attr}={value})&quot;,
+                ODMatchType.startsWith.value: u&quot;({attr}={value}*)&quot;,
+                ODMatchType.endsWith.value: u&quot;({attr}=*{value})&quot;,
+                ODMatchType.contains.value: u&quot;({attr}=*{value}*)&quot;,
+                ODMatchType.lessThan.value: u&quot;({attr}&lt;{value})&quot;,
+                ODMatchType.greaterThan.value: u&quot;({attr}&gt;{value})&quot;,
+            }.get(matchType.value, u&quot;({attr}=*{value}*)&quot;).format(
+                attr=odAttr,
+                value=expression.fieldValue
+            )
+
+        elif isinstance(expression, CompoundExpression):
+            queryString = u&quot;&quot;
+            operand = u&quot;&amp;&quot; if expression.operand is Operand.AND else u&quot;|&quot;
+            if len(expression.expressions) &gt; 1:
+                queryString += u&quot;(&quot;
+                queryString += operand
+            for subExpression in expression.expressions:
+                queryString += self._queryStringFromExpression(subExpression)
+            if len(expression.expressions) &gt; 1:
+                queryString += u&quot;)&quot;
+
+        return queryString
+
+
+    def _queryFromCompoundExpression(self, expression):
+        &quot;&quot;&quot;
+        Form an OpenDirectory query from a compound expression.
+
+        @param expression: The compound expression.
+        @type expression: L{CompoundExpression}
+
+        @return: A native OpenDirectory query.
+        @rtype: L{ODQuery}
+        &quot;&quot;&quot;
+
+        queryString = self._queryStringFromExpression(expression)
+
+        recordTypes = [t.value for t in ODRecordType.iterconstants()]
+        attributes = [a.value for a in ODAttribute.iterconstants()]
+        maxResults = 0
+
+        query, error = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
+            self.node,
+            recordTypes,
+            None,
+            ODMatchType.compound.value,
+            queryString,
+            attributes,
+            maxResults,
+            None
+        )
+
+        if error:
+            self.log.error(
+                &quot;Error while forming OpenDirectory query: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(error)
+
+        return query
+
+
+
+    def _queryFromMatchExpression(self, expression):
+        &quot;&quot;&quot;
+        Form an OpenDirectory query from a match expression.
+
+        @param expression: The match expression.
+        @type expression: L{MatchExpression}
+
+        @return: A native OpenDirectory query.
+        @rtype: L{ODQuery}
+        &quot;&quot;&quot;
+        if not isinstance(expression, MatchExpression):
+            raise TypeError(expression)
+
+        matchType = ODMatchType.fromMatchType(expression.matchType)
+        if matchType is None:
+            raise QueryNotSupportedError(
+                &quot;Unknown match type: {0}&quot;.format(matchType)
+            )
+
+        if MatchFlags.caseInsensitive in iterFlags(expression.flags):
+            caseInsensitive = 0x100
+        else:
+            caseInsensitive = 0x0
+
+        if expression.fieldName is self.fieldName.recordType:
+            raise NotImplementedError()
+
+        else:
+            recordTypes = [t.value for t in ODRecordType.iterconstants()]
+            attributes = [a.value for a in ODAttribute.iterconstants()]
+            maxResults = 0
+
+        query, error = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
+            self.node,
+            recordTypes,
+            ODAttribute.fromFieldName(expression.fieldName).value,
+            matchType.value | caseInsensitive,
+            expression.fieldValue,
+            attributes,
+            maxResults,
+            None
+        )
+
+        if error:
+            self.log.error(
+                &quot;Error while forming OpenDirectory query: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(error)
+
+        return query
+
+
+    def _recordsFromQuery(self, query):
+        &quot;&quot;&quot;
+        Executes a query and generates directory records from it.
+
+        @param query: A query.
+        @type query: L{ODQuery}
+
+        @return: The records produced by executing the query.
+        @rtype: iterable of L{DirectoryRecord}
+        &quot;&quot;&quot;
+
+        odRecords, error = query.resultsAllowingPartial_error_(False, None)
+
+        if error:
+            self.log.error(
+                &quot;Error while executing OpenDirectory query: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(error)
+
+        for odRecord in odRecords:
+            yield DirectoryRecord(self, odRecord)
+
+
+
+    def recordsFromExpression(self, expression):
+        &quot;&quot;&quot;
+        @param expression: an expression to apply
+        @type expression: L{MatchExpression} or L{CompoundExpression}
+
+        @return: The matching records.
+        @rtype: deferred iterable of L{IDirectoryRecord}s
+
+        @raises: L{QueryNotSupportedError} if the expression is not
+            supported by this directory service.
+        &quot;&quot;&quot;
+
+        try:
+            if isinstance(expression, CompoundExpression):
+                query = self._queryFromCompoundExpression(expression)
+                return succeed(self._recordsFromQuery(query))
+
+            elif isinstance(expression, MatchExpression):
+                query = self._queryFromMatchExpression(expression)
+                return succeed(self._recordsFromQuery(query))
+
+        except QueryNotSupportedError:
+            pass
+
+        return BaseDirectoryService.recordsFromExpression(
+            self, expression
+        )
+
+
+    def _getUserRecord(self, username):
+        &quot;&quot;&quot;
+        Fetch the OD record for a given user.
+
+        @return: ODRecord, or None
+        &quot;&quot;&quot;
+        record, error = self.node.recordWithRecordType_name_attributes_error_(
+            ODRecordType.user.value, username, None, None
+        )
+        if error:
+            self.log.error(
+                &quot;Error while executing OpenDirectory query: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryQueryError(&quot;Could not look up user&quot;, error)
+
+        return record
+
+
+    def requestAvatarId(self, credentials):
+        &quot;&quot;&quot;
+        Authenticate the credentials against OpenDirectory and return the
+        corresponding directory record.
+
+        @param: credentials: The credentials to authenticate.
+        @type: credentials: L{ICredentials}
+
+        @return: The directory record for the given credentials.
+        @rtype: deferred L{DirectoryRecord}
+
+        @raises: L{UnauthorizedLogin} if the credentials are not valid.
+        &quot;&quot;&quot;
+
+        odRecord = self._getUserRecord(credentials.username)
+
+        if odRecord is None:
+            return fail(UnauthorizedLogin(&quot;No such user&quot;))
+
+        if IUsernamePassword.providedBy(credentials):
+            result, error = odRecord.verifyPassword_error_(
+                credentials.password, None
+            )
+
+            if error:
+                return fail(UnauthorizedLogin(error))
+
+            if result:
+                return succeed(DirectoryRecord(self, odRecord))
+
+        elif isinstance(credentials, DigestedCredentials):
+            try:
+                credentials.fields.setdefault(&quot;algorithm&quot;, &quot;md5&quot;)
+                challenge = (
+                    'Digest realm=&quot;{realm}&quot;, nonce=&quot;{nonce}&quot;, '
+                    'algorithm={algorithm}'
+                    .format(**credentials.fields)
+                )
+                response = credentials.fields[&quot;response&quot;]
+
+            except KeyError as e:
+                self.log.error(
+                    &quot;Error authenticating against OpenDirectory: &quot;
+                    &quot;missing digest response field {field!r} in &quot;
+                    &quot;{credentials.fields!r}&quot;,
+                    field=e.args[0], credentials=credentials
+                )
+                return fail(UnauthorizedLogin(&quot;Invalid digest challenge&quot;))
+
+            result, m1, m2, error = odRecord.verifyExtendedWithAuthenticationType_authenticationItems_continueItems_context_error_(
+                &quot;dsAuthMethodStandard:dsAuthNodeDIGEST-MD5&quot;,
+                [
+                    credentials.username,
+                    challenge,
+                    response,
+                    credentials.method,
+                ],
+                None, None, None
+            )
+
+            if error:
+                return fail(UnauthorizedLogin(error))
+
+            if result:
+                return succeed(DirectoryRecord(self, odRecord))
+
+        else:
+            return fail(UnauthorizedLogin(
+                &quot;Unknown credentials type: {0}&quot;.format(type(credentials))
+            ))
+
+        return fail(UnauthorizedLogin(&quot;Unknown authorization failure&quot;))
+
+
+
+# class CustomDigestCredentialFactory(DigestCredentialFactory):
+#     &quot;&quot;&quot;
+#     DigestCredentialFactory without qop, to interop with OD.
+#     &quot;&quot;&quot;
+
+#     def getChallenge(self, address):
+#         result = DigestCredentialFactory.getChallenge(self, address)
+#         del result[&quot;qop&quot;]
+#         return result
+
+
+
+class DirectoryRecord(BaseDirectoryRecord):
+    &quot;&quot;&quot;
+    OpenDirectory directory record.
+    &quot;&quot;&quot;
+
+    log = Logger()
+
+    # GUID is a required attribute for OD records.
+    requiredFields = BaseDirectoryRecord.requiredFields + (BaseFieldName.guid,)
+
+
+    def __init__(self, service, odRecord):
+        details, error = odRecord.recordDetailsForAttributes_error_(None, None)
+
+        if error:
+            self.log.error(
+                &quot;Error while reading OpenDirectory record: {error}&quot;,
+                error=error
+            )
+            raise OpenDirectoryDataError(error)
+
+        fields = {}
+        for name, values in details.iteritems():
+            if name == ODAttribute.metaRecordName.value:
+                # We get this field even though we did not ask for it...
+                continue
+
+            try:
+                attribute = ODAttribute.lookupByValue(name)
+            except ValueError:
+                self.log.debug(
+                    &quot;Unexpected OpenDirectory record attribute: {attribute}&quot;,
+                    attribute=name
+                )
+                continue
+            fieldName = attribute.fieldName
+
+            if type(values) is bytes:
+                values = (unicode(values),)
+            else:
+                values = [unicode(v) for v in values]
+
+            if BaseFieldName.isMultiValue(fieldName):
+                fields[fieldName] = values
+            else:
+                assert len(values) == 1
+
+                if fieldName is service.fieldName.recordType:
+                    fields[fieldName] = ODRecordType.lookupByValue(
+                        values[0]
+                    ).recordType
+                else:
+                    fields[fieldName] = values[0]
+
+        # Make sure that uid and guid are both set and equal
+        uid = fields.get(service.fieldName.uid, None)
+        guid = fields.get(service.fieldName.guid, None)
+
+        if uid is not None and guid is not None:
+            if uid != guid:
+                raise ValueError(
+                    &quot;uid and guid must be equal ({uid} != {guid})&quot;
+                    .format(uid=uid, guid=guid)
+                )
+        elif uid is None:
+            fields[service.fieldName.uid] = guid
+        elif guid is None:
+            fields[service.fieldName.guid] = uid
+
+        super(DirectoryRecord, self).__init__(service, fields)
+        self._odRecord = odRecord
</ins></span></pre></div>
<a id="twexttrunktwextwhoopendirectoryodframeworkpy"></a>
<div class="delfile"><h4>Deleted: twext/trunk/twext/who/opendirectory/odframework.py (12148 => 12149)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/odframework.py        2013-12-19 19:43:30 UTC (rev 12148)
+++ twext/trunk/twext/who/opendirectory/odframework.py        2013-12-19 19:46:53 UTC (rev 12149)
</span><span class="lines">@@ -1,30 +0,0 @@
</span><del>-##
-# Copyright (c) 2010-2013 Apple Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-##
-
-&quot;&quot;&quot;
-OpenDirectory.framework
-&quot;&quot;&quot;
-
-import objc as _objc
-
-__bundle__ = _objc.initFrameworkWrapper(
-    &quot;OpenDirectory&quot;,
-    frameworkIdentifier=&quot;com.apple.OpenDirectory&quot;,
-    frameworkPath=_objc.pathForFramework(
-        &quot;/System/Library/Frameworks/OpenDirectory.framework&quot;
-    ),
-    globals=globals()
-)
</del></span></pre></div>
<a id="twexttrunktwextwhoopendirectoryservicepy"></a>
<div class="delfile"><h4>Deleted: twext/trunk/twext/who/opendirectory/service.py (12148 => 12149)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/who/opendirectory/service.py        2013-12-19 19:43:30 UTC (rev 12148)
+++ twext/trunk/twext/who/opendirectory/service.py        2013-12-19 19:46:53 UTC (rev 12149)
</span><span class="lines">@@ -1,716 +0,0 @@
</span><del>-# -*- test-case-name: twext.who.opendirectory.test.test_service -*-
-##
-# Copyright (c) 2013 Apple Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-##
-
-from __future__ import print_function
-
-&quot;&quot;&quot;
-OpenDirectory directory service implementation.
-&quot;&quot;&quot;
-
-from odframework import ODSession, ODNode, ODQuery
-
-from zope.interface import implements
-
-from twisted.python.constants import (
-    Names, NamedConstant, Values, ValueConstant,
-)
-from twisted.internet.defer import succeed, fail
-from twisted.cred.checkers import ICredentialsChecker
-from twisted.cred.credentials import (
-    IUsernamePassword, IUsernameHashedPassword, DigestedCredentials,
-)
-from twisted.cred.error import UnauthorizedLogin
-# from twisted.web.guard import DigestCredentialFactory
-
-from twext.python.log import Logger
-
-from ..idirectory import (
-    DirectoryServiceError, QueryNotSupportedError,
-    FieldName as BaseFieldName, RecordType as BaseRecordType,
-)
-from ..directory import (
-    DirectoryService as BaseDirectoryService,
-    DirectoryRecord as BaseDirectoryRecord,
-)
-from ..expression import (
-    CompoundExpression, Operand, MatchExpression, MatchType, MatchFlags,
-)
-from ..util import iterFlags, ConstantsContainer
-
-
-
-#
-# Exceptions
-#
-
-class OpenDirectoryError(DirectoryServiceError):
-    &quot;&quot;&quot;
-    OpenDirectory error.
-    &quot;&quot;&quot;
-
-    def __init__(self, message, odError):
-        super(OpenDirectoryError, self).__init__(message)
-        self.odError = odError
-
-
-
-class OpenDirectoryConnectionError(OpenDirectoryError):
-    &quot;&quot;&quot;
-    OpenDirectory connection error.
-    &quot;&quot;&quot;
-
-
-
-class OpenDirectoryQueryError(OpenDirectoryError):
-    &quot;&quot;&quot;
-    OpenDirectory query error.
-    &quot;&quot;&quot;
-
-
-class OpenDirectoryDataError(OpenDirectoryError):
-    &quot;&quot;&quot;
-    OpenDirectory data error.
-    &quot;&quot;&quot;
-
-
-
-#
-# Constants
-#
-
-class FieldName(Names):
-    searchPath = NamedConstant()
-    searchPath.description = &quot;search path&quot;
-    searchPath.multiValue = False
-
-    metaNodeLocation = NamedConstant()
-    metaNodeLocation.description = &quot;source OD node&quot;
-    metaNodeLocation.multiValue = False
-
-    metaRecordName = NamedConstant()
-    metaRecordName.description = &quot;meta record name&quot;
-    metaRecordName.multiValue = False
-
-
-
-#
-# OD Constants
-#
-
-class ODSearchPath(Values):
-    local = ValueConstant(&quot;/Local/Default&quot;)
-    search = ValueConstant(&quot;/Search&quot;)
-
-
-
-class ODRecordType(Values):
-    user = ValueConstant(&quot;dsRecTypeStandard:Users&quot;)
-    user.recordType = BaseRecordType.user
-
-    group = ValueConstant(&quot;dsRecTypeStandard:Groups&quot;)
-    group.recordType = BaseRecordType.group
-
-
-    @classmethod
-    def fromRecordType(cls, recordType):
-        if not hasattr(cls, &quot;_recordTypeByRecordType&quot;):
-            cls._recordTypeByRecordType = dict((
-                (recordType.recordType, recordType)
-                for recordType in cls.iterconstants()
-            ))
-
-        return cls._recordTypeByRecordType.get(recordType, None)
-
-
-
-class ODAttribute(Values):
-    searchPath = ValueConstant(&quot;dsAttrTypeStandard:SearchPath&quot;)
-    searchPath.fieldName = FieldName.searchPath
-
-    recordType = ValueConstant(&quot;dsAttrTypeStandard:RecordType&quot;)
-    recordType.fieldName = BaseFieldName.recordType
-
-    uid = ValueConstant(&quot;dsAttrTypeStandard:GeneratedUID&quot;)
-    uid.fieldName = BaseFieldName.uid
-
-    guid = ValueConstant(&quot;dsAttrTypeStandard:GeneratedUID&quot;)
-    guid.fieldName = BaseFieldName.guid
-
-    shortName = ValueConstant(&quot;dsAttrTypeStandard:RecordName&quot;)
-    shortName.fieldName = BaseFieldName.shortNames
-
-    fullName = ValueConstant(&quot;dsAttrTypeStandard:RealName&quot;)
-    fullName.fieldName = BaseFieldName.fullNames
-
-    emailAddress = ValueConstant(&quot;dsAttrTypeStandard:EMailAddress&quot;)
-    emailAddress.fieldName = BaseFieldName.emailAddresses
-
-    metaNodeLocation = ValueConstant(
-        &quot;dsAttrTypeStandard:AppleMetaNodeLocation&quot;
-    )
-    metaNodeLocation.fieldName = FieldName.metaNodeLocation
-
-    metaRecordName = ValueConstant(&quot;dsAttrTypeStandard:AppleMetaRecordName&quot;)
-    metaRecordName.fieldName = FieldName.metaRecordName
-
-
-    @classmethod
-    def fromFieldName(cls, fieldName):
-        if not hasattr(cls, &quot;_attributesByFieldName&quot;):
-            cls._attributesByFieldName = dict((
-                (attribute.fieldName, attribute)
-                for attribute in cls.iterconstants()
-                if hasattr(attribute, &quot;fieldName&quot;)
-            ))
-
-        return cls._attributesByFieldName.get(fieldName, None)
-
-
-
-class ODMatchType(Values):
-    equals = ValueConstant(0x2001)
-    equals.matchType = MatchType.equals
-
-    startsWith = ValueConstant(0x2002)
-    startsWith.matchType = MatchType.startsWith
-
-    endsWith = ValueConstant(0x2003)
-    endsWith.matchType = MatchType.endsWith
-
-    contains = ValueConstant(0x2004)
-    contains.matchType = MatchType.contains
-
-    lessThan = ValueConstant(0x2005)
-    lessThan.matchType = MatchType.lessThan
-
-    greaterThan = ValueConstant(0x2006)
-    greaterThan.matchType = MatchType.greaterThan
-
-    lessThanOrEqualTo = ValueConstant(0x2007)
-    lessThanOrEqualTo.matchType = MatchType.lessThanOrEqualTo
-
-    greaterThanOrEqualTo = ValueConstant(0x2008)
-    greaterThanOrEqualTo.matchType = MatchType.greaterThanOrEqualTo
-
-    compound = ValueConstant(0x210B)
-    compound.matchType = MatchType.compound
-
-
-    @classmethod
-    def fromMatchType(cls, matchType):
-        if not hasattr(cls, &quot;_matchTypeByMatchType&quot;):
-            cls._matchTypeByMatchType = dict((
-                (matchType.matchType, matchType)
-                for matchType in cls.iterconstants()
-            ))
-
-        return cls._matchTypeByMatchType.get(matchType, None)
-
-
-
-class ODMatchFlags(Values):
-    caseInsensitive = ValueConstant(0x100)
-
-
-
-#
-# Directory Service
-#
-
-class DirectoryService(BaseDirectoryService):
-    &quot;&quot;&quot;
-    OpenDirectory directory service.
-    &quot;&quot;&quot;
-
-    implements(ICredentialsChecker)
-    credentialInterfaces = (IUsernamePassword, IUsernameHashedPassword)
-
-    log = Logger()
-
-    recordType = ConstantsContainer((
-        BaseRecordType.user, BaseRecordType.group,
-    ))
-
-    fieldName = ConstantsContainer((BaseDirectoryService.fieldName, FieldName))
-
-
-
-    def __init__(self, nodeName=ODSearchPath.search.value):
-        &quot;&quot;&quot;
-        @param nodeName: the OpenDirectory node to query against.
-        @type nodeName: bytes
-        &quot;&quot;&quot;
-        self._nodeName = nodeName
-
-
-    @property
-    def nodeName(self):
-        return self._nodeName
-
-
-    @property
-    def realmName(self):
-        return &quot;OpenDirectory Node {self.nodeName!r}&quot;.format(self=self)
-
-
-    @property
-    def session(self):
-        &quot;&quot;&quot;
-        Get the underlying directory session.
-        &quot;&quot;&quot;
-        self._connect()
-        return self._session
-
-
-    @property
-    def node(self):
-        &quot;&quot;&quot;
-        Get the underlying (network) directory node.
-        &quot;&quot;&quot;
-        self._connect()
-        return self._node
-
-
-    # @property
-    # def localNode(self):
-    #     &quot;&quot;&quot;
-    #     Get the local node from the search path (if any), so that we can
-    #     handle it specially.
-    #     &quot;&quot;&quot;
-    #     if not hasattr(self, &quot;_localNode&quot;):
-    #         if self.nodeName == ODSearchPath.search.value:
-    #             result = getNodeAttributes(
-    #                 self.node, ODSearchPath.search.value,
-    #                 (ODAttribute.searchPath.value,)
-    #             )
-    #             if (
-    #                 ODSearchPath.local.value in
-    #                 result[ODAttribute.searchPath.value]
-    #             ):
-    #                 try:
-    #                     self._localNode = odInit(ODSearchPath.local.value)
-    #                 except ODError, e:
-    #                     self.log.error(
-    #                         &quot;Failed to open local node: {error}}&quot;,
-    #                         error=e,
-    #                     )
-    #                     raise OpenDirectoryError(e)
-    #             else:
-    #                 self._localNode = None
-
-    #         elif self.nodeName == ODSearchPath.local.value:
-    #             self._localNode = self.node
-
-    #         else:
-    #             self._localNode = None
-
-    #     return self._localNode
-
-
-    def _connect(self):
-        &quot;&quot;&quot;
-        Connect to the directory server.
-
-        @raises: L{OpenDirectoryConnectionError} if unable to connect.
-        &quot;&quot;&quot;
-        if not hasattr(self, &quot;_session&quot;):
-            session = ODSession.defaultSession()
-
-            node, error = ODNode.nodeWithSession_name_error_(
-                session, self.nodeName, None
-            )
-
-            if error:
-                self.log.error(
-                    &quot;Error while trying to connect to OpenDirectory node &quot;
-                    &quot;{source.nodeName!r}: {error}&quot;,
-                    error=error
-                )
-                raise OpenDirectoryConnectionError(error)
-
-            self._session = session
-            self._node = node
-
-
-    def _queryStringFromExpression(self, expression):
-        &quot;&quot;&quot;
-        Converts either a MatchExpression or a CompoundExpression into a native
-        OpenDirectory query string.
-
-        @param expression: The expression
-        @type expression: Either L{MatchExpression} or L{CompoundExpression}
-
-        @return: A native OpenDirectory query string
-        @rtype: C{unicode}
-        &quot;&quot;&quot;
-
-        if isinstance(expression, MatchExpression):
-            matchType = ODMatchType.fromMatchType(expression.matchType)
-            if matchType is None:
-                raise QueryNotSupportedError(
-                    &quot;Unknown match type: {0}&quot;.format(matchType)
-                )
-            odAttr = ODAttribute.fromFieldName(expression.fieldName).value
-            queryString = {
-                ODMatchType.equals.value: u&quot;({attr}={value})&quot;,
-                ODMatchType.startsWith.value: u&quot;({attr}={value}*)&quot;,
-                ODMatchType.endsWith.value: u&quot;({attr}=*{value})&quot;,
-                ODMatchType.contains.value: u&quot;({attr}=*{value}*)&quot;,
-                ODMatchType.lessThan.value: u&quot;({attr}&lt;{value})&quot;,
-                ODMatchType.greaterThan.value: u&quot;({attr}&gt;{value})&quot;,
-            }.get(matchType.value, u&quot;({attr}=*{value}*)&quot;).format(
-                attr=odAttr,
-                value=expression.fieldValue
-            )
-
-        elif isinstance(expression, CompoundExpression):
-            queryString = u&quot;&quot;
-            operand = u&quot;&amp;&quot; if expression.operand is Operand.AND else u&quot;|&quot;
-            if len(expression.expressions) &gt; 1:
-                queryString += u&quot;(&quot;
-                queryString += operand
-            for subExpression in expression.expressions:
-                queryString += self._queryStringFromExpression(subExpression)
-            if len(expression.expressions) &gt; 1:
-                queryString += u&quot;)&quot;
-
-        return queryString
-
-
-    def _queryFromCompoundExpression(self, expression):
-        &quot;&quot;&quot;
-        Form an OpenDirectory query from a compound expression.
-
-        @param expression: The compound expression.
-        @type expression: L{CompoundExpression}
-
-        @return: A native OpenDirectory query.
-        @rtype: L{ODQuery}
-        &quot;&quot;&quot;
-
-        queryString = self._queryStringFromExpression(expression)
-
-        recordTypes = [t.value for t in ODRecordType.iterconstants()]
-        attributes = [a.value for a in ODAttribute.iterconstants()]
-        maxResults = 0
-
-        query, error = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
-            self.node,
-            recordTypes,
-            None,
-            ODMatchType.compound.value,
-            queryString,
-            attributes,
-            maxResults,
-            None
-        )
-
-        if error:
-            self.log.error(
-                &quot;Error while forming OpenDirectory query: {error}&quot;,
-                error=error
-            )
-            raise OpenDirectoryQueryError(error)
-
-        return query
-
-
-
-    def _queryFromMatchExpression(self, expression):
-        &quot;&quot;&quot;
-        Form an OpenDirectory query from a match expression.
-
-        @param expression: The match expression.
-        @type expression: L{MatchExpression}
-
-        @return: A native OpenDirectory query.
-        @rtype: L{ODQuery}
-        &quot;&quot;&quot;
-        if not isinstance(expression, MatchExpression):
-            raise TypeError(expression)
-
-        matchType = ODMatchType.fromMatchType(expression.matchType)
-        if matchType is None:
-            raise QueryNotSupportedError(
-                &quot;Unknown match type: {0}&quot;.format(matchType)
-            )
-
-        if MatchFlags.caseInsensitive in iterFlags(expression.flags):
-            caseInsensitive = 0x100
-        else:
-            caseInsensitive = 0x0
-
-        if expression.fieldName is self.fieldName.recordType:
-            raise NotImplementedError()
-
-        else:
-            recordTypes = [t.value for t in ODRecordType.iterconstants()]
-            attributes = [a.value for a in ODAttribute.iterconstants()]
-            maxResults = 0
-
-        query, error = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
-            self.node,
-            recordTypes,
-            ODAttribute.fromFieldName(expression.fieldName).value,
-            matchType.value | caseInsensitive,
-            expression.fieldValue,
-            attributes,
-            maxResults,
-            None
-        )
-
-        if error:
-            self.log.error(
-                &quot;Error while forming OpenDirectory query: {error}&quot;,
-                error=error
-            )
-            raise OpenDirectoryQueryError(error)
-
-        return query
-
-
-    def _recordsFromQuery(self, query):
-        &quot;&quot;&quot;
-        Executes a query and generates directory records from it.
-
-        @param query: A query.
-        @type query: L{ODQuery}
-
-        @return: The records produced by executing the query.
-        @rtype: iterable of L{DirectoryRecord}
-        &quot;&quot;&quot;
-
-        odRecords, error = query.resultsAllowingPartial_error_(False, None)
-
-        if error:
-            self.log.error(
-                &quot;Error while executing OpenDirectory query: {error}&quot;,
-                error=error
-            )
-            raise OpenDirectoryQueryError(error)
-
-        for odRecord in odRecords:
-            yield DirectoryRecord(self, odRecord)
-
-
-
-    def recordsFromExpression(self, expression):
-        &quot;&quot;&quot;
-        @param expression: an expression to apply
-        @type expression: L{MatchExpression} or L{CompoundExpression}
-
-        @return: The matching records.
-        @rtype: deferred iterable of L{IDirectoryRecord}s
-
-        @raises: L{QueryNotSupportedError} if the expression is not
-            supported by this directory service.
-        &quot;&quot;&quot;
-
-        try:
-            if isinstance(expression, CompoundExpression):
-                query = self._queryFromCompoundExpression(expression)
-                return succeed(self._recordsFromQuery(query))
-
-            elif isinstance(expression, MatchExpression):
-                query = self._queryFromMatchExpression(expression)
-                return succeed(self._recordsFromQuery(query))
-
-        except QueryNotSupportedError:
-            pass
-
-        return BaseDirectoryService.recordsFromExpression(
-            self, expression
-        )
-
-
-    def _getUserRecord(self, username):
-        &quot;&quot;&quot;
-        Fetch the OD record for a given user.
-
-        @return: ODRecord, or None
-        &quot;&quot;&quot;
-        record, error = self.node.recordWithRecordType_name_attributes_error_(
-            ODRecordType.user.value, username, None, None
-        )
-        if error:
-            self.log.error(
-                &quot;Error while executing OpenDirectory query: {error}&quot;,
-                error=error
-            )
-            raise OpenDirectoryQueryError(&quot;Could not look up user&quot;, error)
-
-        return record
-
-
-    def requestAvatarId(self, credentials):
-        &quot;&quot;&quot;
-        Authenticate the credentials against OpenDirectory and return the
-        corresponding directory record.
-
-        @param: credentials: The credentials to authenticate.
-        @type: credentials: L{ICredentials}
-
-        @return: The directory record for the given credentials.
-        @rtype: deferred L{DirectoryRecord}
-
-        @raises: L{UnauthorizedLogin} if the credentials are not valid.
-        &quot;&quot;&quot;
-
-        odRecord = self._getUserRecord(credentials.username)
-
-        if odRecord is None:
-            return fail(UnauthorizedLogin(&quot;No such user&quot;))
-
-        if IUsernamePassword.providedBy(credentials):
-            result, error = odRecord.verifyPassword_error_(
-                credentials.password, None
-            )
-
-            if error:
-                return fail(UnauthorizedLogin(error))
-
-            if result:
-                return succeed(DirectoryRecord(self, odRecord))
-
-        elif isinstance(credentials, DigestedCredentials):
-            try:
-                credentials.fields.setdefault(&quot;algorithm&quot;, &quot;md5&quot;)
-                challenge = (
-                    'Digest realm=&quot;{realm}&quot;, nonce=&quot;{nonce}&quot;, '
-                    'algorithm={algorithm}'
-                    .format(**credentials.fields)
-                )
-                response = credentials.fields[&quot;response&quot;]
-
-            except KeyError as e:
-                self.log.error(
-                    &quot;Error authenticating against OpenDirectory: &quot;
-                    &quot;missing digest response field {field!r} in &quot;
-                    &quot;{credentials.fields!r}&quot;,
-                    field=e.args[0], credentials=credentials
-                )
-                return fail(UnauthorizedLogin(&quot;Invalid digest challenge&quot;))
-
-            result, m1, m2, error = odRecord.verifyExtendedWithAuthenticationType_authenticationItems_continueItems_context_error_(
-                &quot;dsAuthMethodStandard:dsAuthNodeDIGEST-MD5&quot;,
-                [
-                    credentials.username,
-                    challenge,
-                    response,
-                    credentials.method,
-                ],
-                None, None, None
-            )
-
-            if error:
-                return fail(UnauthorizedLogin(error))
-
-            if result:
-                return succeed(DirectoryRecord(self, odRecord))
-
-        else:
-            return fail(UnauthorizedLogin(
-                &quot;Unknown credentials type: {0}&quot;.format(type(credentials))
-            ))
-
-        return fail(UnauthorizedLogin(&quot;Unknown authorization failure&quot;))
-
-
-
-# class CustomDigestCredentialFactory(DigestCredentialFactory):
-#     &quot;&quot;&quot;
-#     DigestCredentialFactory without qop, to interop with OD.
-#     &quot;&quot;&quot;
-
-#     def getChallenge(self, address):
-#         result = DigestCredentialFactory.getChallenge(self, address)
-#         del result[&quot;qop&quot;]
-#         return result
-
-
-
-class DirectoryRecord(BaseDirectoryRecord):
-    &quot;&quot;&quot;
-    OpenDirectory directory record.
-    &quot;&quot;&quot;
-
-    log = Logger()
-
-    # GUID is a required attribute for OD records.
-    requiredFields = BaseDirectoryRecord.requiredFields + (BaseFieldName.guid,)
-
-
-    def __init__(self, service, odRecord):
-        details, error = odRecord.recordDetailsForAttributes_error_(None, None)
-
-        if error:
-            self.log.error(
-                &quot;Error while reading OpenDirectory record: {error}&quot;,
-                error=error
-            )
-            raise OpenDirectoryDataError(error)
-
-        fields = {}
-        for name, values in details.iteritems():
-            if name == ODAttribute.metaRecordName.value:
-                # We get this field even though we did not ask for it...
-                continue
-
-            try:
-                attribute = ODAttribute.lookupByValue(name)
-            except ValueError:
-                self.log.debug(
-                    &quot;Unexpected OpenDirectory record attribute: {attribute}&quot;,
-                    attribute=name
-                )
-                continue
-            fieldName = attribute.fieldName
-
-            if type(values) is bytes:
-                values = (unicode(values),)
-            else:
-                values = [unicode(v) for v in values]
-
-            if BaseFieldName.isMultiValue(fieldName):
-                fields[fieldName] = values
-            else:
-                assert len(values) == 1
-
-                if fieldName is service.fieldName.recordType:
-                    fields[fieldName] = ODRecordType.lookupByValue(
-                        values[0]
-                    ).recordType
-                else:
-                    fields[fieldName] = values[0]
-
-        # Make sure that uid and guid are both set and equal
-        uid = fields.get(service.fieldName.uid, None)
-        guid = fields.get(service.fieldName.guid, None)
-
-        if uid is not None and guid is not None:
-            if uid != guid:
-                raise ValueError(
-                    &quot;uid and guid must be equal ({uid} != {guid})&quot;
-                    .format(uid=uid, guid=guid)
-                )
-        elif uid is None:
-            fields[service.fieldName.uid] = guid
-        elif guid is None:
-            fields[service.fieldName.guid] = uid
-
-        super(DirectoryRecord, self).__init__(service, fields)
-        self._odRecord = odRecord
</del></span></pre>
</div>
</div>

</body>
</html>