[CalendarServer-changes] [1273] CalendarServer/trunk
source_changes at macosforge.org
source_changes at macosforge.org
Mon Feb 26 20:17:54 PST 2007
Revision: 1273
http://trac.macosforge.org/projects/calendarserver/changeset/1273
Author: dreid at apple.com
Date: 2007-02-26 20:17:54 -0800 (Mon, 26 Feb 2007)
Log Message:
-----------
Revert all made by me today.
Modified Paths:
--------------
CalendarServer/trunk/bin/caladmin
CalendarServer/trunk/twistedcaldav/config.py
CalendarServer/trunk/twistedcaldav/directory/aggregate.py
CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py
CalendarServer/trunk/twistedcaldav/directory/directory.py
CalendarServer/trunk/twistedcaldav/directory/sqldb.py
CalendarServer/trunk/twistedcaldav/directory/sudo.py
CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py
CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py
CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py
CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py
CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py
CalendarServer/trunk/twistedcaldav/directory/xmlfile.py
CalendarServer/trunk/twistedcaldav/tap.py
CalendarServer/trunk/twistedcaldav/test/test_config.py
Modified: CalendarServer/trunk/bin/caladmin
===================================================================
--- CalendarServer/trunk/bin/caladmin 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/bin/caladmin 2007-02-27 04:17:54 UTC (rev 1273)
@@ -22,7 +22,7 @@
#PYTHONPATH
if __name__ == '__main__':
- if 'PYTHONPATH' in globals():
+ if PYTHONPATH in globals():
sys.path.insert(0, PYTHONPATH)
from twistedcaldav.admin.script import run
Modified: CalendarServer/trunk/twistedcaldav/config.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/config.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/config.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -17,7 +17,6 @@
##
import os
-import copy
from twistedcaldav.py.plistlib import readPlist
@@ -142,38 +141,15 @@
},
}
-
class Config (object):
def __init__(self, defaults):
- self._defaults = defaults
- self._data = copy.deepcopy(defaults)
- self._configFile = None
+ self.update(defaults)
def update(self, items):
- self._data.update(items)
+ items = items.iteritems()
+ for key, value in items:
+ setattr(self, key, value)
- def updateDefaults(self, items):
- self._defaults.update(items)
- self.update(items)
-
- def __getattr__(self, attr):
- if attr in self._data:
- return self._data[attr]
-
- raise AttributeError(attr)
-
- def reload(self):
- self._data = copy.deepcopy(self._defaults)
- self.loadConfig(self._configFile)
-
- def loadConfig(self, configFile):
- self._configFile = configFile
-
- if configFile and os.path.exists(configFile):
- plist = readPlist(configFile)
- self.update(plist)
-
-
class ConfigurationError (RuntimeError):
"""
Invalid server configuration.
@@ -182,4 +158,6 @@
config = Config(defaultConfig)
def parseConfig(configFile):
- config.loadConfig(configFile)
+ if os.path.exists(configFile):
+ plist = readPlist(configFile)
+ config.update(plist)
Modified: CalendarServer/trunk/twistedcaldav/directory/aggregate.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/aggregate.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/aggregate.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -27,13 +27,12 @@
]
from twisted.cred.error import UnauthorizedLogin
-from twisted.application.service import MultiService, IService
from twistedcaldav.directory.idirectory import IDirectoryService
from twistedcaldav.directory.directory import DirectoryService, DirectoryError
from twistedcaldav.directory.directory import UnknownRecordTypeError
-class AggregateDirectoryService(DirectoryService, MultiService):
+class AggregateDirectoryService(DirectoryService):
"""
L{IDirectoryService} implementation which aggregates multiple directory services.
"""
@@ -41,39 +40,35 @@
def __init__(self, services):
DirectoryService.__init__(self)
- MultiService.__init__(self)
- self.realmName = None
- self._recordTypes = {}
+ realmName = None
+ recordTypes = {}
for service in services:
- IService(service).setServiceParent(self)
-
- def startService(self):
- super(AggregateDirectoryService, self).startService()
-
- for service in self.services:
service = IDirectoryService(service)
- if service.realmName != self.realmName:
- assert self.realmName is None or service.realmName is None, (
+ if service.realmName != realmName:
+ assert realmName is None, (
"Aggregated directory services must have the same realm name: %r != %r"
- % (service.realmName, self.realmName)
+ % (service.realmName, realmName)
)
- self.realmName = service.realmName
+ realmName = service.realmName
if not hasattr(service, "recordTypePrefix"):
service.recordTypePrefix = ""
prefix = service.recordTypePrefix
for recordType in (prefix + r for r in service.recordTypes()):
- if recordType in self._recordTypes:
+ if recordType in recordTypes:
raise DuplicateRecordTypeError(
"%r is in multiple services: %s, %s"
- % (recordType, self._recordTypes[recordType], service)
+ % (recordType, recordTypes[recordType], service)
)
- self._recordTypes[recordType] = service
+ recordTypes[recordType] = service
+ self.realmName = realmName
+ self._recordTypes = recordTypes
+
def __repr__(self):
return "<%s (%s): %r>" % (self.__class__.__name__, self.realmName, self._recordTypes)
@@ -138,7 +133,7 @@
if user:
return self.serviceForRecordType(
type).requestAvatarId(credentials)
-
+
raise UnauthorizedLogin("No such user: %s" % (
credentials.credentials.username,))
Modified: CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -53,11 +53,14 @@
def __repr__(self):
return "<%s %r: %r>" % (self.__class__.__name__, self.realmName, self.node)
- def __init__(self, node="/Search", requireComputerRecord=True):
+ def __init__(self, node="/Search", requireComputerRecord=True, dosetup=True):
"""
@param node: an OpenDirectory node name to bind to.
@param requireComputerRecord: C{True} if the directory schema is to be used to determine
which calendar users are enabled.
+ @param dosetup: if C{True} then the directory records are initialized,
+ if C{False} they are not.
+ This should only be set to C{False} when doing unit tests.
"""
try:
directory = opendirectory.odInit(node)
@@ -73,16 +76,16 @@
self._records = {}
self._delayedCalls = set()
- def startService(self):
- if self.requireComputerRecord:
- try:
- self._lookupVHostRecord()
- except Exception, e:
- log.err("Unable to locate virtual host record: %s" % (e,))
- raise
+ if dosetup:
+ if self.requireComputerRecord:
+ try:
+ self._lookupVHostRecord()
+ except Exception, e:
+ log.err("Unable to locate virtual host record: %s" % (e,))
+ raise
- for recordType in self.recordTypes():
- self.recordsForType(recordType)
+ for recordType in self.recordTypes():
+ self.recordsForType(recordType)
def __cmp__(self, other):
if not isinstance(other, DirectoryRecord):
@@ -112,7 +115,7 @@
"There is no virtual hostname configured for the server for use with Open Directory (node=%s)"
% (self.realmName,)
)
-
+
# Find a record in /Computers with an ENetAddress attribute value equal to the MAC address
# and return some useful attributes.
attrs = [
@@ -133,7 +136,7 @@
self._parseComputersRecords(records, vhostname)
def _parseComputersRecords(self, records, vhostname):
-
+
# Must have some results
if len(records) == 0:
raise OpenDirectoryInitError(
@@ -144,12 +147,12 @@
# Now find a single record that actually matches the hostname
found = False
for recordname, record in records.iteritems():
-
+
# Must have XMLPlist value
plist = record.get(dsattributes.kDS1AttrXMLPlist, None)
if not plist:
continue
-
+
if not self._parseXMLPlist(vhostname, recordname, plist, record[dsattributes.kDS1AttrGeneratedUID]):
continue
elif found:
@@ -159,13 +162,13 @@
)
else:
found = True
-
+
if not found:
raise OpenDirectoryInitError(
"Open Directory (node=%s) no /Computers records with an enabled and valid calendar service were found matching virtual hostname: %s"
% (self.realmName, vhostname,)
)
-
+
def _parseXMLPlist(self, vhostname, recordname, plist, recordguid):
# Parse the plist and look for our special entry
plist = readPlistFromString(plist)
@@ -177,7 +180,7 @@
% (self.realmName, recordname)
)
return False
-
+
# Iterate over each vhost and find one that is a calendar service
hostguid = None
for key, value in vhosts.iteritems():
@@ -187,7 +190,7 @@
if type == "calendar":
hostguid = key
break
-
+
if not hostguid:
log.msg(
"Open Directory (node=%s) /Computers/%s record does not have a "
@@ -195,7 +198,7 @@
% (self.realmName, recordname)
)
return False
-
+
# Get host name
hostname = vhosts[hostguid].get("hostname", None)
if not hostname:
@@ -212,7 +215,7 @@
% (self.realmName, recordname, hostname, vhostname)
)
return False
-
+
# Get host details and create host templates
hostdetails = vhosts[hostguid].get("hostDetails", None)
if not hostdetails:
@@ -226,7 +229,7 @@
for key, value in hostdetails.iteritems():
if key in ("http", "https"):
hostvariants.append((key, hostname, value["port"]))
-
+
# Look at the service data
serviceInfos = vhosts[hostguid].get("serviceInfo", None)
if not serviceInfos or not serviceInfos.has_key("calendar"):
@@ -237,7 +240,7 @@
)
return False
serviceInfo = serviceInfos["calendar"]
-
+
# Check that this service is enabled
enabled = serviceInfo.get("enabled", True)
if not enabled:
@@ -250,23 +253,23 @@
# Create the string we will use to match users with accounts on this server
self.servicetag = "%s:%s:calendar" % (recordguid, hostguid)
-
+
self.computerRecordName = recordname
-
+
return True
-
+
def _getCalendarUserAddresses(self, recordType, recordName, record):
"""
Extract specific attributes from the directory record for use as calendar user address.
-
+
@param recordName: a C{str} containing the record name being operated on.
@param record: a C{dict} containing the attributes retrieved from the directory.
@return: a C{set} of C{str} for each expanded calendar user address.
"""
-
+
# Now get the addresses
result = set()
-
+
# Add each email address as a mailto URI
emails = record.get(dsattributes.kDSNAttrEMailAddress)
if emails is not None:
@@ -274,7 +277,7 @@
emails = [emails]
for email in emails:
result.add("mailto:%s" % (email,))
-
+
return result
def recordTypes(self):
@@ -313,7 +316,7 @@
elif recordType == DirectoryService.recordType_locations:
listRecordType = dsattributes.kDSStdRecordTypeResources
query = dsquery.match(dsattributes.kDSNAttrResourceType, "1", dsattributes.eDSExact)
-
+
elif recordType == DirectoryService.recordType_resources:
listRecordType = dsattributes.kDSStdRecordTypeResources
query = dsquery.expression(dsquery.expression.OR, (
@@ -323,7 +326,7 @@
dsquery.match(dsattributes.kDSNAttrResourceType, "4", dsattributes.eDSExact),
dsquery.match(dsattributes.kDSNAttrResourceType, "5", dsattributes.eDSExact),
))
-
+
else:
raise UnknownRecordTypeError("Unknown Open Directory record type: %s"
% (recordType,))
@@ -334,7 +337,7 @@
query = dsquery.expression(dsquery.expression.AND, (cprecord, query))
else:
query = cprecord
-
+
records = {}
try:
Modified: CalendarServer/trunk/twistedcaldav/directory/directory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/directory.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/directory.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -33,7 +33,6 @@
from zope.interface import implements
from twisted.python import log
-from twisted.application.service import Service
from twisted.cred.error import UnauthorizedLogin
from twisted.cred.checkers import ICredentialsChecker
from twisted.web2.dav.auth import IPrincipalCredentials
@@ -46,7 +45,7 @@
from twistedcaldav.directory.idirectory import IDirectoryService, IDirectoryRecord
from twistedcaldav.directory.util import uuidFromName
-class DirectoryService(object, Service):
+class DirectoryService(object):
implements(IDirectoryService, ICredentialsChecker)
##
@@ -59,7 +58,7 @@
recordType_groups = "groups"
recordType_locations = "locations"
recordType_resources = "resources"
-
+
def _generatedGUID(self):
if not hasattr(self, "_guid"):
realmName = self.realmName
@@ -99,7 +98,7 @@
raise UnauthorizedLogin("No such user: %s" % (user,))
# Handle Kerberos as a separate behavior
- if NegotiateCredentials and isinstance(credentials.credentials,
+ if NegotiateCredentials and isinstance(credentials.credentials,
NegotiateCredentials):
# If we get here with Kerberos, then authentication has already succeeded
return (
@@ -113,7 +112,7 @@
credentials.authzPrincipal.principalURL(),
)
else:
- raise UnauthorizedLogin("Incorrect credentials for %s" % (user,))
+ raise UnauthorizedLogin("Incorrect credentials for %s" % (user,))
def recordTypes(self):
raise NotImplementedError("Subclass must implement recordTypes()")
Modified: CalendarServer/trunk/twistedcaldav/directory/sqldb.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/sqldb.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/sqldb.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -65,7 +65,7 @@
def loadFromXML(self, xmlFile):
parser = XMLAccountsParser(xmlFile)
-
+
# Totally wipe existing DB and start from scratch
if os.path.exists(self.dbpath):
os.remove(self.dbpath)
@@ -95,13 +95,13 @@
):
# See if we have members
members = self.members(shortName)
-
+
# See if we are a member of any groups
groups = self.groups(shortName)
-
+
# Get calendar user addresses
calendarUserAddresses = self.calendarUserAddresses(shortName)
-
+
yield shortName, guid, password, name, members, groups, calendarUserAddresses
def getRecord(self, recordType, shortName):
@@ -117,18 +117,18 @@
break
else:
return None
-
+
# See if we have members
members = self.members(shortName)
-
+
# See if we are a member of any groups
groups = self.groups(shortName)
-
+
# Get calendar user addresses
calendarUserAddresses = self.calendarUserAddresses(shortName)
-
+
return shortName, guid, password, name, members, groups, calendarUserAddresses
-
+
def members(self, shortName):
members = set()
for member in self._db_execute(
@@ -179,7 +179,7 @@
values (:1, :2, :3, :4, :5)
""", recordType, shortName, guid, password, name
)
-
+
# Check for members
for memberRecordType, memberShortName in record.members:
self._db_execute(
@@ -188,7 +188,7 @@
values (:1, :2, :3)
""", shortName, memberRecordType, memberShortName
)
-
+
# CUAddress
for cuaddr in record.calendarUserAddresses:
self._db_execute(
@@ -197,7 +197,7 @@
values (:1, :2)
""", cuaddr, shortName
)
-
+
def _delete_from_db(self, shortName):
"""
Deletes the specified entry from all dbs.
@@ -208,13 +208,13 @@
self._db_execute("delete from GROUPS where SHORT_NAME = :1", shortName)
self._db_execute("delete from GROUPS where MEMBER_SHORT_NAME = :1", shortName)
self._db_execute("delete from ADDRESSES where SHORT_NAME = :1", shortName)
-
+
def _db_type(self):
"""
@return: the collection type assigned to this index.
"""
return SQLDirectoryManager.dbType
-
+
def _db_init_data_tables(self, q):
"""
Initialise the underlying database tables.
@@ -280,14 +280,10 @@
if type(dbParentPath) is str:
dbParentPath = FilePath(dbParentPath)
-
- self.xmlFile = xmlFile
-
+
self.manager = SQLDirectoryManager(dbParentPath.path)
-
- def startService(self):
- if self.xmlFile:
- self.manager.loadFromXML(self.xmlFile)
+ if xmlFile:
+ self.manager.loadFromXML(xmlFile)
self.realmName = self.manager.getRealm()
def recordTypes(self):
Modified: CalendarServer/trunk/twistedcaldav/directory/sudo.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/sudo.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/sudo.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -27,13 +27,13 @@
from twisted.python.filepath import FilePath
-from twisted.cred.credentials import (IUsernamePassword,
+from twisted.cred.credentials import (IUsernamePassword,
IUsernameHashedPassword)
from twisted.cred.error import UnauthorizedLogin
from twistedcaldav.py.plistlib import readPlist
-from twistedcaldav.directory.directory import (DirectoryService,
+from twistedcaldav.directory.directory import (DirectoryService,
DirectoryRecord,
UnknownRecordTypeError)
@@ -58,11 +58,9 @@
if isinstance(plistFile, (unicode, str)):
plistFile = FilePath(plistFile)
-
+
self.plistFile = plistFile
self._fileInfo = None
-
- def startService(self):
self._accounts()
def _accounts(self):
@@ -104,12 +102,12 @@
# implementation because you shouldn't have a principal object for a
# disabled directory principal.
sudouser = self.recordWithShortName(
- SudoDirectoryService.recordType_sudoers,
+ SudoDirectoryService.recordType_sudoers,
credentials.credentials.username)
if sudouser is None:
raise UnauthorizedLogin("No such user: %s" % (sudouser,))
-
+
if sudouser.verifyCredentials(credentials.credentials):
return (
credentials.authnPrincipal.principalURL(),
@@ -117,7 +115,7 @@
)
else:
raise UnauthorizedLogin(
- "Incorrect credentials for %s" % (sudouser,))
+ "Incorrect credentials for %s" % (sudouser,))
class SudoDirectoryRecord(DirectoryRecord):
@@ -141,5 +139,5 @@
return credentials.checkPassword(self.password)
elif IUsernameHashedPassword.providedBy(credentials):
return credentials.checkPassword(self.password)
-
+
return super(SudoDirectoryRecord, self).verifyCredentials(credentials)
Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -73,7 +73,4 @@
xmlService = XMLDirectoryService(xmlFile)
xmlService.recordTypePrefix = xml_prefix
- aggregate = AggregateDirectoryService((apacheService, xmlService))
- aggregate.startService()
-
- return aggregate
+ return AggregateDirectoryService((apacheService, xmlService))
Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -21,7 +21,6 @@
except ImportError:
pass
else:
- from twisted.internet.task import Clock
from twistedcaldav.directory.directory import DirectoryService
import twistedcaldav.directory.test.util
@@ -51,7 +50,7 @@
def setUp(self):
super(OpenDirectory, self).setUp()
- self._service = OpenDirectoryService(node="/Search")
+ self._service = OpenDirectoryService(node="/Search", dosetup=False)
def tearDown(self):
for call in self._service._delayedCalls:
Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -30,7 +30,7 @@
"""
Test Open Directory service schema.
"""
-
+
plist_nomacosxserver_key = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
@@ -186,7 +186,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostname</key>
@@ -301,7 +301,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostname</key>
@@ -425,7 +425,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostDetails</key>
@@ -544,7 +544,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostname</key>
@@ -647,7 +647,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostname</key>
@@ -769,7 +769,7 @@
</dict>
</dict>
</dict>
-
+
<key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
<dict>
<key>hostname</key>
@@ -825,10 +825,10 @@
def test_plist_errors(self):
def _doParse(plist, title):
- service = OpenDirectoryService(node="/Search")
+ service = OpenDirectoryService(node="/Search", dosetup=False)
if service._parseXMLPlist("calendar.apple.com", "recordit", plist, "GUIDIFY"):
self.fail(msg="Plist parse should have failed: %s" % (title,))
-
+
plists = (
(PlistParse.plist_nomacosxserver_key, "nomacosxserver_key"),
(PlistParse.plist_nocalendarservice, "nocalendarservice"),
@@ -841,7 +841,7 @@
_doParse(plist, title)
def test_goodplist(self):
- service = OpenDirectoryService(node="/Search")
+ service = OpenDirectoryService(node="/Search", dosetup=False)
if not service._parseXMLPlist("calendar.apple.com", "recordit", PlistParse.plist_good, "GUIDIFY"):
self.fail(msg="Plist parse should not have failed")
else:
@@ -850,15 +850,15 @@
def test_expandcuaddrs(self):
def _doTest(recordName, record, result, title):
- service = OpenDirectoryService(node="/Search")
+ service = OpenDirectoryService(node="/Search", dosetup=False)
if not service._parseXMLPlist("calendar.apple.com", recordName, PlistParse.plist_good, "GUIDIFY"):
self.fail(msg="Plist parse should not have failed: %s" % (recordName,))
else:
expanded = service._getCalendarUserAddresses(DirectoryService.recordType_users, recordName, record)
-
+
# Verify that we extracted the proper items
self.assertEqual(expanded, result, msg=title % (expanded, result,))
-
+
data = (
(
"user01",
@@ -892,7 +892,7 @@
"User with no email addresses, %s != %s",
),
)
-
+
for recordName, record, result, title in data:
_doTest(recordName, record, result, title)
@@ -916,13 +916,13 @@
def test_odrecords_error(self):
def _doParseRecords(recordlist, title):
- service = OpenDirectoryService(node="/Search")
+ service = OpenDirectoryService(node="/Search", dosetup=False)
try:
service._parseComputersRecords(recordlist, "calendar.apple.com")
self.fail(msg="Record parse should have failed: %s" % (title,))
except OpenDirectoryInitError:
pass
-
+
records = (
({}, "no records found"),
({
@@ -939,12 +939,12 @@
def test_odrecords_good(self):
def _doParseRecords(recordlist, title):
- service = OpenDirectoryService(node="/Search")
+ service = OpenDirectoryService(node="/Search", dosetup=False)
try:
service._parseComputersRecords(recordlist, "calendar.apple.com")
except OpenDirectoryInitError, ex:
self.fail(msg="Record parse should not have failed: \"%s\" with error: %s" % (title, ex))
-
+
records = (
({
ODRecordsParse.record_good[0] : ODRecordsParse.record_good[1],
Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -37,9 +37,7 @@
Test SQL directory implementation.
"""
def service(self):
- service = SQLDirectoryService(os.getcwd(), self.xmlFile())
- service.startService()
- return service
+ return SQLDirectoryService(os.getcwd(), self.xmlFile())
def test_verifyCredentials_digest(self):
super(SQLDB, self).test_verifyCredentials_digest()
@@ -51,6 +49,5 @@
# Then get an instance without using the XML file
service = SQLDirectoryService(os.getcwd(), None)
- service.startService()
self.assertEquals(service.realmName, "Test")
Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -86,9 +86,7 @@
Test XML file based directory implementation.
"""
def service(self):
- service = XMLDirectoryService(self.xmlFile())
- service.startService()
- return service
+ return XMLDirectoryService(self.xmlFile())
def test_changedXML(self):
self.xmlFile().open("w").write(
Modified: CalendarServer/trunk/twistedcaldav/directory/xmlfile.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/xmlfile.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/directory/xmlfile.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -50,8 +50,6 @@
self.xmlFile = xmlFile
self._fileInfo = None
-
- def startService(self):
self._accounts()
def recordTypes(self):
Modified: CalendarServer/trunk/twistedcaldav/tap.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/tap.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/tap.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -65,97 +65,8 @@
self.logObserver = logObserver
service.MultiService.__init__(self)
- def verifyFiles(self):
- # Verify that document root actually exists
- self.checkDirectory(
- config.DocumentRoot,
- "Document root",
- access=os.R_OK or os.W_OK,
- permissions=0750,
- uname=config.UserName,
- gname=config.GroupName
- )
-
- # Verify that ssl certs exist if needed
- if config.SSLPort:
- self.checkFile(
- config.SSLPrivateKey,
- "SSL Private key",
- access=os.R_OK,
- permissions=0640
- )
- self.checkFile(
- config.SSLCertificate,
- "SSL Public key",
- access=os.R_OK,
- permissions=0644
- )
-
- def checkDirectory(self, dirpath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
- if not os.path.exists(dirpath):
- raise ConfigurationError("%s does not exist: %s" % (description, dirpath,))
- elif not os.path.isdir(dirpath):
- raise ConfigurationError("%s is not a directory: %s" % (description, dirpath,))
- elif access and not os.access(dirpath, access):
- raise ConfigurationError("Insufficient permissions for server on %s directory: %s" % (description, dirpath,))
- self.securityCheck(dirpath, description, fail=fail, permissions=permissions, uname=uname, gname=gname)
-
- def checkFile(self, filepath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
- if not os.path.exists(filepath):
- raise ConfigurationError("%s does not exist: %s" % (description, filepath,))
- elif not os.path.isfile(filepath):
- raise ConfigurationError("%s is not a file: %s" % (description, filepath,))
- elif access and not os.access(filepath, access):
- raise ConfigurationError("Insufficient permissions for server on %s directory: %s" % (description, filepath,))
- self.securityCheck(filepath, description, fail=fail, permissions=permissions, uname=uname, gname=gname)
-
- def securityCheck(self, path, description, fail=False, permissions=None, uname=None, gname=None):
- def raiseOrPrint(txt):
- if fail:
- raise ConfigurationError(txt)
- else:
- print "WARNING: %s" % (txt,)
-
- pathstat = os.stat(path)
- if permissions:
- if stat.S_IMODE(pathstat[stat.ST_MODE]) != permissions:
- raiseOrPrint("The permisions on %s directory %s are 0%03o and do not match expected permissions: 0%03o"
- % (description, path, stat.S_IMODE(pathstat[stat.ST_MODE]), permissions))
- if uname:
- import pwd
- try:
- pathuname = pwd.getpwuid(pathstat[stat.ST_UID])[0]
- if pathuname != uname:
- raiseOrPrint("The owner of %s directory %s is %s and does not match the expected owner: %s"
- % (description, path, pathuname, uname))
- except KeyError:
- raiseOrPrint("The owner of %s directory %s is unknown (%s) and does not match the expected owner: %s"
- % (description, path, pathstat[stat.ST_UID], uname))
-
- if gname:
- import grp
- try:
- pathgname = grp.getgrgid(pathstat[stat.ST_GID])[0]
- if pathgname != gname:
- raiseOrPrint("The group of %s directory %s is %s and does not match the expected group: %s"
- % (description, path, pathgname, gname))
- except KeyError:
- raiseOrPrint("The group of %s directory %s is unknown (%s) and does not match the expected group: %s"
- % (description, path, pathstat[stat.ST_GID], gname))
-
- def startService(self):
- self.verifyFiles()
-
- service.MultiService.startService(self)
-
def privilegedStartService(self):
service.MultiService.privilegedStartService(self)
-
- # Check current umask and warn if changed
- oldmask = os.umask(0027)
- if oldmask != 0027:
- print "WARNING: changing umask from: 0%03o to 0%03o" % (oldmask, 0027,)
-
self.logObserver.start()
def stopService(self):
@@ -177,9 +88,9 @@
def opt_option(self, option):
"""
- Set an option to override a value in the config file. True, False, int,
+ Set an option to override a value in the config file. True, False, int,
and float options are supported, as well as comma seperated lists. Only
- one option may be given for each --option flag, however multiple
+ one option may be given for each --option flag, however multiple
--option flags may be specified.
"""
@@ -192,13 +103,13 @@
elif isinstance(defaultConfig[key], (int, float, long)):
value = type(defaultConfig[key])(value)
-
+
elif isinstance(defaultConfig[key], (list, tuple)):
value = value.split(',')
elif isinstance(defaultConfig[key], dict):
raise UsageError("Dict options not supported on the command line")
-
+
elif value == 'None':
value = None
@@ -219,7 +130,7 @@
uid, gid = None, None
if self.parent['uid'] or self.parent['gid']:
- uid, gid = getid(self.parent['uid'],
+ uid, gid = getid(self.parent['uid'],
self.parent['gid'])
if uid:
@@ -239,6 +150,30 @@
self.parent['logfile'] = config.ErrorLogFile
self.parent['pidfile'] = config.PIDFile
+ # Verify that document root actually exists
+ self.checkDirectory(
+ config.DocumentRoot,
+ "Document root",
+ access=os.R_OK or os.W_OK,
+ permissions=0750,
+ uname=config.UserName,
+ gname=config.GroupName
+ )
+
+ # Verify that ssl certs exist if needed
+ if config.SSLPort:
+ self.checkFile(
+ config.SSLPrivateKey,
+ "SSL Private key",
+ access=os.R_OK,
+ permissions=0640
+ )
+ self.checkFile(
+ config.SSLCertificate,
+ "SSL Public key",
+ access=os.R_OK,
+ permissions=0644
+ )
#
# Nuke the file log observer's time format.
@@ -246,10 +181,65 @@
if not config.ErrorLogFile and config.ProcessType == 'Slave':
log.FileLogObserver.timeFormat = ''
+
+ # Check current umask and warn if changed
+ oldmask = os.umask(0027)
+ if oldmask != 0027:
+ print "WARNING: changing umask from: 0%03o to 0%03o" % (oldmask, 0027,)
+
+ def checkDirectory(self, dirpath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
+ if not os.path.exists(dirpath):
+ raise ConfigurationError("%s does not exist: %s" % (description, dirpath,))
+ elif not os.path.isdir(dirpath):
+ raise ConfigurationError("%s is not a directory: %s" % (description, dirpath,))
+ elif access and not os.access(dirpath, access):
+ raise ConfigurationError("Insufficient permissions for server on %s directory: %s" % (description, dirpath,))
+ self.securityCheck(dirpath, description, fail=fail, permissions=permissions, uname=uname, gname=gname)
+
+ def checkFile(self, filepath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
+ if not os.path.exists(filepath):
+ raise ConfigurationError("%s does not exist: %s" % (description, filepath,))
+ elif not os.path.isfile(filepath):
+ raise ConfigurationError("%s is not a file: %s" % (description, filepath,))
+ elif access and not os.access(filepath, access):
+ raise ConfigurationError("Insufficient permissions for server on %s directory: %s" % (description, filepath,))
+ self.securityCheck(filepath, description, fail=fail, permissions=permissions, uname=uname, gname=gname)
+ def securityCheck(self, path, description, fail=False, permissions=None, uname=None, gname=None):
+ def raiseOrPrint(txt):
+ if fail:
+ raise ConfigurationError(txt)
+ else:
+ print "WARNING: %s" % (txt,)
+ pathstat = os.stat(path)
+ if permissions:
+ if stat.S_IMODE(pathstat[stat.ST_MODE]) != permissions:
+ raiseOrPrint("The permisions on %s directory %s are 0%03o and do not match expected permissions: 0%03o"
+ % (description, path, stat.S_IMODE(pathstat[stat.ST_MODE]), permissions))
+ if uname:
+ import pwd
+ try:
+ pathuname = pwd.getpwuid(pathstat[stat.ST_UID])[0]
+ if pathuname != uname:
+ raiseOrPrint("The owner of %s directory %s is %s and does not match the expected owner: %s"
+ % (description, path, pathuname, uname))
+ except KeyError:
+ raiseOrPrint("The owner of %s directory %s is unknown (%s) and does not match the expected owner: %s"
+ % (description, path, pathstat[stat.ST_UID], uname))
+
+ if gname:
+ import grp
+ try:
+ pathgname = grp.getgrgid(pathstat[stat.ST_GID])[0]
+ if pathgname != gname:
+ raiseOrPrint("The group of %s directory %s is %s and does not match the expected group: %s"
+ % (description, path, pathgname, gname))
+ except KeyError:
+ raiseOrPrint("The group of %s directory %s is unknown (%s) and does not match the expected group: %s"
+ % (description, path, pathstat[stat.ST_GID], gname))
+
-
class CalDAVServiceMaker(object):
implements(IPlugin, service.IServiceMaker)
@@ -272,12 +262,12 @@
# Setup the Directory
#
directories = []
-
+
directoryClass = namedClass(config.DirectoryService['type'])
-
+
log.msg("Configuring directory service of type: %s"
% (config.DirectoryService['type'],))
-
+
baseDirectory = directoryClass(**config.DirectoryService['params'])
directories.append(baseDirectory)
@@ -287,8 +277,9 @@
if config.SudoersFile and os.path.exists(config.SudoersFile):
log.msg("Configuring SudoDirectoryService with file: %s"
% (config.SudoersFile,))
-
+
sudoDirectory = SudoDirectoryService(config.SudoersFile)
+ sudoDirectory.realmName = baseDirectory.realmName
CalDAVResource.sudoDirectory = sudoDirectory
directories.append(sudoDirectory)
@@ -307,7 +298,7 @@
#
log.msg("Setting up document root at: %s" % (config.DocumentRoot,))
-
+
log.msg("Setting up principal collection: %r" % (self.principalResourceClass,))
principalCollection = self.principalResourceClass(
@@ -323,11 +314,11 @@
directory,
'/calendars/'
)
-
+
log.msg("Setting up root resource: %r" % (self.rootResourceClass,))
-
+
root = self.rootResourceClass(
- config.DocumentRoot,
+ config.DocumentRoot,
principalCollections=(principalCollection,)
)
@@ -344,12 +335,12 @@
davxml.Grant(davxml.Privilege(davxml.Read())),
),
]
-
+
log.msg("Setting up AdminPrincipals")
for principal in config.AdminPrincipals:
log.msg("Added %s as admin principal" % (principal,))
-
+
rootACEs.append(
davxml.ACE(
davxml.Principal(davxml.HRef(principal)),
@@ -381,10 +372,10 @@
scheme = scheme.lower()
credFactory = None
-
+
if schemeConfig['Enabled']:
log.msg("Setting up scheme: %s" % (scheme,))
-
+
if scheme == 'kerberos':
if not NegotiateCredentialFactory:
log.msg("Kerberos support not available")
@@ -423,7 +414,7 @@
#
# Configure the service
- #
+ #
log.msg("Setting up service")
@@ -433,11 +424,9 @@
config.AccessLogFile,))
logObserver = RotatingFileAccessLoggingObserver(config.AccessLogFile)
-
+
service = CalDAVService(logObserver)
- directory.setServiceParent(service)
-
if not config.BindAddresses:
config.BindAddresses = [""]
@@ -459,20 +448,20 @@
for port in config.BindHTTPPorts:
log.msg("Adding server at %s:%s" % (bindAddress, port))
-
+
httpService = internet.TCPServer(int(port), channel, interface=bindAddress)
httpService.setServiceParent(service)
for port in config.BindSSLPorts:
log.msg("Adding SSL server at %s:%s" % (bindAddress, port))
-
+
httpsService = internet.SSLServer(
int(port), channel,
DefaultOpenSSLContextFactory(config.SSLPrivateKey, config.SSLCertificate),
interface=bindAddress
)
httpsService.setServiceParent(service)
-
+
return service
makeService_Combined = makeService_Combined
Modified: CalendarServer/trunk/twistedcaldav/test/test_config.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/test/test_config.py 2007-02-27 02:14:25 UTC (rev 1272)
+++ CalendarServer/trunk/twistedcaldav/test/test_config.py 2007-02-27 04:17:54 UTC (rev 1273)
@@ -18,8 +18,6 @@
from twisted.trial import unittest
-from twistedcaldav.py.plistlib import writePlist
-
from twistedcaldav.config import config, defaultConfig, parseConfig
testConfig = """<?xml version="1.0" encoding="UTF-8"?>
@@ -28,8 +26,6 @@
<dict>
<key>Verbose</key>
<true/>
- <key>HTTPPort</key>
- <integer>8008</integer>
</dict>
</plist>
"""
@@ -42,7 +38,8 @@
def testDefaults(self):
for key, value in defaultConfig.iteritems():
- self.assertEquals(getattr(config, key), value)
+ self.failUnless(key in config.__dict__)
+ self.assertEquals(config.__dict__[key], value)
def testParseConfig(self):
self.assertEquals(config.Verbose, False)
@@ -50,7 +47,7 @@
parseConfig(self.testConfig)
self.assertEquals(config.Verbose, True)
-
+
def testScoping(self):
def getVerbose():
self.assertEquals(config.Verbose, True)
@@ -62,53 +59,3 @@
self.assertEquals(config.Verbose, True)
getVerbose()
-
- def testReloading(self):
- self.assertEquals(config.HTTPPort, None)
-
- parseConfig(self.testConfig)
-
- self.assertEquals(config.HTTPPort, 8008)
-
- writePlist({}, self.testConfig)
-
- config.reload()
-
- self.assertEquals(config.HTTPPort, None)
-
- def testUpdateAndReload(self):
- self.assertEquals(config.HTTPPort, None)
-
- parseConfig(self.testConfig)
-
- self.assertEquals(config.HTTPPort, 8008)
-
- config.update({'HTTPPort': 80})
-
- self.assertEquals(config.HTTPPort, 80)
-
- config.reload()
-
- self.assertEquals(config.HTTPPort, 8008)
-
- def testUpdating(self):
- self.assertEquals(config.SSLPort, None)
-
- config.update({'SSLPort': 8443})
-
- self.assertEquals(config.SSLPort, 8443)
-
- def testUpdateDefaults(self):
- self.assertEquals(config.SSLPort, None)
-
- parseConfig(self.testConfig)
-
- config.updateDefaults({'SSLPort': 8009})
-
- self.assertEquals(config.SSLPort, 8009)
-
- config.reload()
-
- self.assertEquals(config.SSLPort, 8009)
-
- config.updateDefaults({'SSLPort': None})
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20070226/881a3e12/attachment.html
More information about the calendarserver-changes
mailing list