This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
util.py
1743 lines (1422 loc) · 58.1 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: calendarserver.tap.test.test_caldav -*-
##
# Copyright (c) 2005-2016 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# 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 "AS IS" 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.
##
"""
Utilities for assembling the service and resource hierarchy.
"""
__all__ = [
"FakeRequest",
"getDBPool",
"getRootResource",
"getSSLPassphrase",
"MemoryLimitService",
"AlertPoster",
"preFlightChecks",
]
from calendarserver.accesslog import DirectoryLogWrapperResource
from calendarserver.provision.root import RootResource
from calendarserver.push.applepush import APNSubscriptionResource
from calendarserver.push.notifier import NotifierFactory
from calendarserver.push.util import getAPNTopicFromConfig
from calendarserver.tools import diagnose
from calendarserver.tools.util import checkDirectory
from calendarserver.webadmin.delegation import WebAdminResource
from calendarserver.webcal.resource import WebCalendarResource
from socket import fromfd, AF_UNIX, SOCK_STREAM, socketpair
from subprocess import Popen, PIPE
from twext.enterprise.adbapi2 import ConnectionPool, ConnectionPoolConnection
from twext.enterprise.adbapi2 import ConnectionPoolClient
from twext.enterprise.ienterprise import POSTGRES_DIALECT, ORACLE_DIALECT, DatabaseType
from twext.internet.ssl import ChainingOpenSSLContextFactory
from twext.python.filepath import CachingFilePath
from twext.python.filepath import CachingFilePath as FilePath
from twext.python.log import Logger
from twext.who.checker import HTTPDigestCredentialChecker
from twext.who.checker import UsernamePasswordCredentialChecker
from twisted.application.service import Service
from twisted.cred.error import UnauthorizedLogin
from twisted.cred.portal import Portal
from twisted.internet import reactor as _reactor
from twisted.internet.defer import inlineCallbacks, returnValue, Deferred, succeed
from twisted.internet.reactor import addSystemEventTrigger
from twisted.internet.protocol import Factory
from twisted.internet.tcp import Connection
from twisted.protocols import amp
from twisted.python.procutils import which
from twisted.python.usage import UsageError
from twistedcaldav.bind import doBind
from twistedcaldav.cache import CacheStoreNotifierFactory
from twistedcaldav.config import ConfigurationError
from twistedcaldav.controlapi import ControlAPIResource
from twistedcaldav.directory.addressbook import DirectoryAddressBookHomeProvisioningResource
from twistedcaldav.directory.calendar import DirectoryCalendarHomeProvisioningResource
from twistedcaldav.directory.digest import QopDigestCredentialFactory
from twistedcaldav.directory.principal import DirectoryPrincipalProvisioningResource
from twistedcaldav.directorybackedaddressbook import DirectoryBackedAddressBookResource
from twistedcaldav.resource import AuthenticationWrapper
from twistedcaldav.serverinfo import ServerInfoResource
from twistedcaldav.simpleresource import SimpleResource, SimpleRedirectResource, \
SimpleUnavailableResource
from twistedcaldav.stdconfig import config
from twistedcaldav.timezones import TimezoneCache
from twistedcaldav.timezoneservice import TimezoneServiceResource
from twistedcaldav.timezonestdservice import TimezoneStdServiceResource
from txdav.base.datastore.dbapiclient import DBAPIConnector
from txdav.base.datastore.subpostgres import PostgresService
from txdav.caldav.datastore.scheduling.ischedule.dkim import DKIMUtils, DomainKeyResource
from txdav.caldav.datastore.scheduling.ischedule.localservers import buildServersDB
from txdav.caldav.datastore.scheduling.ischedule.resource import IScheduleInboxResource
from txdav.common.datastore.podding.resource import ConduitResource
from txdav.common.datastore.sql import current_sql_schema
from txdav.common.datastore.upgrade.sql.upgrade import NotAllowedToUpgrade
from txdav.dps.client import DirectoryService as DirectoryProxyClientService
from txdav.who.cache import CachingDirectoryService
from txdav.who.util import directoryFromConfig
from txweb2.auth.basic import BasicCredentialFactory
from txweb2.auth.tls import TLSCredentialsFactory, TLSCredentials
from txweb2.dav import auth
from txweb2.dav.auth import IPrincipalCredentials
from txweb2.dav.util import joinURL
from txweb2.http_headers import Headers
from txweb2.resource import Resource
from txweb2.static import File as FileResource
from plistlib import readPlist
from urllib import quote
import OpenSSL
import errno
import os
import psutil
import sys
import time
try:
from twistedcaldav.authkerb import NegotiateCredentialFactory
NegotiateCredentialFactory # pacify pyflakes
except ImportError:
NegotiateCredentialFactory = None
log = Logger()
def pgServiceFromConfig(config, subServiceFactory, uid=None, gid=None):
"""
Construct a L{PostgresService} from a given configuration and subservice.
@param config: the configuration to derive postgres configuration
parameters from.
@param subServiceFactory: A factory for the service to start once the
L{PostgresService} has been initialized.
@param uid: The user-ID to run the PostgreSQL server as.
@param gid: The group-ID to run the PostgreSQL server as.
@return: a service which can start postgres.
@rtype: L{PostgresService}
"""
dbRoot = CachingFilePath(config.DatabaseRoot)
# Construct a PostgresService exactly as the parent would, so that we
# can establish connection information.
return PostgresService(
dbRoot, subServiceFactory, current_sql_schema,
databaseName=config.Postgres.DatabaseName,
clusterName=config.Postgres.ClusterName,
logFile=config.Postgres.LogFile,
logDirectory=config.LogRoot if config.Postgres.LogRotation else "",
socketDir=config.Postgres.SocketDirectory,
socketName=config.Postgres.SocketName,
listenAddresses=config.Postgres.ListenAddresses,
txnTimeoutSeconds=config.Postgres.TxnTimeoutSeconds,
sharedBuffers=config.Postgres.SharedBuffers,
maxConnections=config.Postgres.MaxConnections,
options=config.Postgres.Options,
uid=uid, gid=gid,
spawnedDBUser=config.SpawnedDBUser,
pgCtl=config.Postgres.Ctl,
initDB=config.Postgres.Init,
)
class ConnectionWithPeer(Connection):
connected = True
def getPeer(self):
return "<peer: %r %r>" % (self.socket.fileno(), id(self))
def getHost(self):
return "<host: %r %r>" % (self.socket.fileno(), id(self))
def transactionFactoryFromFD(dbampfd, dbtype):
"""
Create a transaction factory from an inherited file descriptor, such as one
created by L{ConnectionDispenser}.
"""
skt = fromfd(dbampfd, AF_UNIX, SOCK_STREAM)
os.close(dbampfd)
protocol = ConnectionPoolClient(dbtype=dbtype)
transport = ConnectionWithPeer(skt, protocol)
protocol.makeConnection(transport)
transport.startReading()
return protocol.newTransaction
class ConnectionDispenser(object):
"""
A L{ConnectionDispenser} can dispense already-connected file descriptors,
for use with subprocess spawning.
"""
# Very long term FIXME: this mechanism should ideally be eliminated, by
# making all subprocesses have a single stdio AMP connection that
# multiplexes between multiple protocols.
def __init__(self, connectionPool):
self.pool = connectionPool
def dispense(self):
"""
Dispense a socket object, already connected to a server, for a client
in a subprocess.
"""
# FIXME: these sockets need to be re-dispensed when the process is
# respawned, and they currently won't be.
c, s = socketpair(AF_UNIX, SOCK_STREAM)
protocol = ConnectionPoolConnection(self.pool)
transport = ConnectionWithPeer(s, protocol)
protocol.makeConnection(transport)
transport.startReading()
return c
def storeFromConfigWithoutDPS(config, txnFactory):
store = storeFromConfig(config, txnFactory, None)
directory = directoryFromConfig(config, store)
# if config.DirectoryProxy.InProcessCachingSeconds:
# directory = CachingDirectoryService(
# directory,
# expireSeconds=config.DirectoryProxy.InProcessCachingSeconds
# )
store.setDirectoryService(directory)
return store
def storeFromConfigWithDPSClient(config, txnFactory):
store = storeFromConfig(config, txnFactory, None)
directory = DirectoryProxyClientService(config.DirectoryRealmName)
if config.Servers.Enabled:
directory.setServersDB(buildServersDB(config.Servers.MaxClients))
if config.DirectoryProxy.InProcessCachingSeconds:
directory = CachingDirectoryService(
directory,
expireSeconds=config.DirectoryProxy.InProcessCachingSeconds
)
store.setDirectoryService(directory)
return store
def storeFromConfigWithDPSServer(config, txnFactory):
store = storeFromConfig(config, txnFactory, None)
directory = directoryFromConfig(config, store)
# if config.DirectoryProxy.InSidecarCachingSeconds:
# directory = CachingDirectoryService(
# directory,
# expireSeconds=config.DirectoryProxy.InSidecarCachingSeconds
# )
store.setDirectoryService(directory)
return store
def storeFromConfig(config, txnFactory, directoryService):
"""
Produce an L{IDataStore} from the given configuration, transaction factory,
and notifier factory.
If the transaction factory is C{None}, we will create a filesystem
store. Otherwise, a SQL store, using that connection information.
"""
#
# Configure NotifierFactory
#
notifierFactories = {}
if config.Notifications.Enabled:
notifierFactories["push"] = NotifierFactory(config.ServerHostName, config.Notifications.CoalesceSeconds)
if config.EnableResponseCache and config.Memcached.Pools.Default.ClientEnabled:
notifierFactories["cache"] = CacheStoreNotifierFactory()
quota = config.UserQuota
if quota == 0:
quota = None
if txnFactory is not None:
if config.EnableSSL or config.BehindTLSProxy:
uri = "https://{config.ServerHostName}:{config.SSLPort}".format(config=config)
else:
uri = "https://{config.ServerHostName}:{config.HTTPPort}".format(config=config)
attachments_uri = uri + "/calendars/__uids__/%(home)s/dropbox/%(dropbox_id)s/%(name)s"
from txdav.common.datastore.sql import CommonDataStore as CommonSQLDataStore
store = CommonSQLDataStore(
txnFactory, notifierFactories,
directoryService,
FilePath(config.AttachmentsRoot), attachments_uri,
config.EnableCalDAV, config.EnableCardDAV,
config.EnableManagedAttachments,
quota=quota,
logLabels=config.LogDatabase.LabelsInSQL,
logStats=config.LogDatabase.Statistics,
logStatsLogFile=config.LogDatabase.StatisticsLogFile,
logSQL=config.LogDatabase.SQLStatements,
logTransactionWaits=config.LogDatabase.TransactionWaitSeconds,
timeoutTransactions=config.TransactionTimeoutSeconds,
cacheQueries=config.QueryCaching.Enabled,
cachePool=config.QueryCaching.MemcachedPool,
cacheExpireSeconds=config.QueryCaching.ExpireSeconds
)
else:
from txdav.common.datastore.file import CommonDataStore as CommonFileDataStore
store = CommonFileDataStore(
FilePath(config.DocumentRoot),
notifierFactories, directoryService,
config.EnableCalDAV, config.EnableCardDAV,
quota=quota
)
# FIXME: NotifierFactories need a reference to the store in order
# to get a txn in order to possibly create a Work item
for notifierFactory in notifierFactories.values():
notifierFactory.store = store
return store
# MOVE2WHO -- should we move this class somewhere else?
class PrincipalCredentialChecker(object):
credentialInterfaces = (IPrincipalCredentials,)
@inlineCallbacks
def requestAvatarId(self, credentials):
credentials = IPrincipalCredentials(credentials)
if credentials.authnPrincipal is None:
raise UnauthorizedLogin(
"No such user: {user}".format(
user=credentials.credentials.username
)
)
# See if record is enabledForLogin
if not credentials.authnPrincipal.record.isLoginEnabled():
raise UnauthorizedLogin(
"User not allowed to log in: {user}".format(
user=credentials.credentials.username
)
)
# Handle Kerberos as a separate behavior
try:
from twistedcaldav.authkerb import NegotiateCredentials
except ImportError:
NegotiateCredentials = None
if NegotiateCredentials and isinstance(credentials.credentials, NegotiateCredentials):
# If we get here with Kerberos, then authentication has already succeeded
returnValue(
(
credentials.authnPrincipal,
credentials.authzPrincipal,
)
)
# Handle TLS Client Certificate
elif isinstance(credentials.credentials, TLSCredentials):
# If we get here with TLS, then authentication (certificate verification) has already succeeded
returnValue(
(
credentials.authnPrincipal,
credentials.authzPrincipal,
)
)
else:
if (yield credentials.authnPrincipal.record.verifyCredentials(credentials.credentials)):
returnValue(
(
credentials.authnPrincipal,
credentials.authzPrincipal,
)
)
else:
raise UnauthorizedLogin(
"Incorrect credentials for user: {user}".format(
user=credentials.credentials.username
)
)
def getRootResource(config, newStore, resources=None):
"""
Set up directory service and resource hierarchy based on config.
Return root resource.
Additional resources can be added to the hierarchy by passing a list of
tuples containing: path, resource class, __init__ args list, and optional
authentication schemes list ("basic", "digest").
If the store is specified, then it has already been constructed, so use it.
Otherwise build one with L{storeFromConfig}.
"""
if newStore is None:
raise RuntimeError("Internal error, 'newStore' must be specified.")
if resources is None:
resources = []
# FIXME: this is only here to workaround circular imports
doBind()
#
# Default resource classes
#
rootResourceClass = RootResource
calendarResourceClass = DirectoryCalendarHomeProvisioningResource
iScheduleResourceClass = IScheduleInboxResource
conduitResourceClass = ConduitResource
timezoneServiceResourceClass = TimezoneServiceResource
timezoneStdServiceResourceClass = TimezoneStdServiceResource
webCalendarResourceClass = WebCalendarResource
webAdminResourceClass = WebAdminResource
addressBookResourceClass = DirectoryAddressBookHomeProvisioningResource
directoryBackedAddressBookResourceClass = DirectoryBackedAddressBookResource
apnSubscriptionResourceClass = APNSubscriptionResource
serverInfoResourceClass = ServerInfoResource
principalResourceClass = DirectoryPrincipalProvisioningResource
controlResourceClass = ControlAPIResource
directory = newStore.directoryService()
principalCollection = principalResourceClass("/principals/", directory)
#
# Configure the Site and Wrappers
#
wireEncryptedCredentialFactories = []
wireUnencryptedCredentialFactories = []
portal = Portal(auth.DavRealm())
portal.registerChecker(UsernamePasswordCredentialChecker(directory))
portal.registerChecker(HTTPDigestCredentialChecker(directory))
portal.registerChecker(PrincipalCredentialChecker())
realm = directory.realmName.encode("utf-8") or ""
log.info("Configuring authentication for realm: {realm}", realm=realm)
for scheme, schemeConfig in config.Authentication.iteritems():
scheme = scheme.lower()
credFactory = None
if schemeConfig["Enabled"]:
log.info("Setting up scheme: {scheme}", scheme=scheme)
if scheme == "kerberos":
if not NegotiateCredentialFactory:
log.info("Kerberos support not available")
continue
try:
principal = schemeConfig["ServicePrincipal"]
if not principal:
credFactory = NegotiateCredentialFactory(
serviceType="HTTP",
hostname=config.ServerHostName,
)
else:
credFactory = NegotiateCredentialFactory(
principal=principal,
)
except ValueError:
log.info("Could not start Kerberos")
continue
elif scheme == "digest":
credFactory = QopDigestCredentialFactory(
schemeConfig["Algorithm"],
schemeConfig["Qop"],
realm,
)
elif scheme == "basic":
credFactory = BasicCredentialFactory(realm)
elif scheme == TLSCredentialsFactory.scheme:
credFactory = TLSCredentialsFactory(realm)
elif scheme == "wiki":
pass
else:
log.error("Unknown scheme: {scheme}", scheme=scheme)
if credFactory:
wireEncryptedCredentialFactories.append(credFactory)
if schemeConfig.get("AllowedOverWireUnencrypted", False):
wireUnencryptedCredentialFactories.append(credFactory)
#
# Setup Resource hierarchy
#
log.info("Setting up document root at: {root}", root=config.DocumentRoot)
if config.EnableCalDAV:
log.info("Setting up calendar collection: {cls}", cls=calendarResourceClass)
calendarCollection = calendarResourceClass(
directory,
"/calendars/",
newStore,
)
principalCollection.calendarCollection = calendarCollection
if config.EnableCardDAV:
log.info("Setting up address book collection: {cls}", cls=addressBookResourceClass)
addressBookCollection = addressBookResourceClass(
directory,
"/addressbooks/",
newStore,
)
principalCollection.addressBookCollection = addressBookCollection
if config.DirectoryAddressBook.Enabled and config.EnableSearchAddressBook:
log.info(
"Setting up directory address book: {cls}",
cls=directoryBackedAddressBookResourceClass)
directoryBackedAddressBookCollection = directoryBackedAddressBookResourceClass(
principalCollections=(principalCollection,),
principalDirectory=directory,
uri=joinURL("/", config.DirectoryAddressBook.name, "/")
)
if _reactor._started:
directoryBackedAddressBookCollection.provisionDirectory()
else:
addSystemEventTrigger("after", "startup", directoryBackedAddressBookCollection.provisionDirectory)
else:
# remove /directory from previous runs that may have created it
directoryPath = os.path.join(config.DocumentRoot, config.DirectoryAddressBook.name)
try:
FilePath(directoryPath).remove()
log.info("Deleted: {path}", path=directoryPath)
except (OSError, IOError), e:
if e.errno != errno.ENOENT:
log.error("Could not delete: {path} : {error}", path=directoryPath, error=e)
if config.MigrationOnly:
unavailable = SimpleUnavailableResource((principalCollection,))
else:
unavailable = None
log.info("Setting up root resource: {cls}", cls=rootResourceClass)
root = rootResourceClass(
config.DocumentRoot,
principalCollections=(principalCollection,),
)
root.putChild("principals", principalCollection if unavailable is None else unavailable)
if config.EnableCalDAV:
root.putChild("calendars", calendarCollection if unavailable is None else unavailable)
if config.EnableCardDAV:
root.putChild('addressbooks', addressBookCollection if unavailable is None else unavailable)
if config.DirectoryAddressBook.Enabled and config.EnableSearchAddressBook:
root.putChild(config.DirectoryAddressBook.name, directoryBackedAddressBookCollection if unavailable is None else unavailable)
# /.well-known
if config.EnableWellKnown:
log.info("Setting up .well-known collection resource")
wellKnownResource = SimpleResource(
principalCollections=(principalCollection,),
isdir=True,
defaultACL=SimpleResource.allReadACL
)
root.putChild(".well-known", wellKnownResource)
for enabled, wellknown_name, redirected_to in (
(config.EnableCalDAV, "caldav", "/principals/",),
(config.EnableCardDAV, "carddav", "/principals/",),
(config.TimezoneService.Enabled, "timezone", config.TimezoneService.URI,),
(config.Scheduling.iSchedule.Enabled, "ischedule", "/ischedule"),
):
if enabled:
if config.EnableSSL or config.BehindTLSProxy:
scheme = "https"
port = config.SSLPort
else:
scheme = "http"
port = config.HTTPPort
wellKnownResource.putChild(
wellknown_name,
SimpleRedirectResource(
principalCollections=(principalCollection,),
isdir=False,
defaultACL=SimpleResource.allReadACL,
scheme=scheme, port=port, path=redirected_to)
)
for alias in config.Aliases:
url = alias.get("url", None)
path = alias.get("path", None)
if not url or not path or url[0] != "/":
log.error("Invalid alias: URL: {url} Path: {path}", url=url, path=path)
continue
urlbits = url[1:].split("/")
parent = root
for urlpiece in urlbits[:-1]:
child = parent.getChild(urlpiece)
if child is None:
child = Resource()
parent.putChild(urlpiece, child)
parent = child
if parent.getChild(urlbits[-1]) is not None:
log.error("Invalid alias: URL: {url} Path: {path} already exists", url=url, path=path)
continue
resource = FileResource(path)
parent.putChild(urlbits[-1], resource)
log.info("Added alias {url} -> {path}", url=url, path=path)
# Need timezone cache before setting up any timezone service
log.info("Setting up Timezone Cache")
TimezoneCache.create()
# Timezone service is optional
if config.EnableTimezoneService:
log.info(
"Setting up time zone service resource: {cls}",
cls=timezoneServiceResourceClass)
timezoneService = timezoneServiceResourceClass(
root,
)
root.putChild("timezones", timezoneService)
# Standard Timezone service is optional
if config.TimezoneService.Enabled:
log.info(
"Setting up standard time zone service resource: {cls}",
cls=timezoneStdServiceResourceClass)
timezoneStdService = timezoneStdServiceResourceClass(
root,
)
root.putChild("stdtimezones", timezoneStdService)
# TODO: we only want the master to do this
if _reactor._started:
_reactor.callLater(0, timezoneStdService.onStartup)
else:
addSystemEventTrigger("after", "startup", timezoneStdService.onStartup)
#
# iSchedule/cross-pod service for podding
#
if config.Servers.Enabled:
log.info("Setting up iSchedule podding inbox resource: {cls}", cls=iScheduleResourceClass)
ischedule = iScheduleResourceClass(
root,
newStore,
podding=True
)
root.putChild(config.Servers.InboxName, ischedule if unavailable is None else unavailable)
log.info("Setting up podding conduit resource: {cls}", cls=conduitResourceClass)
conduit = conduitResourceClass(
root,
newStore,
)
root.putChild(config.Servers.ConduitName, conduit)
#
# iSchedule service (not used for podding)
#
if config.Scheduling.iSchedule.Enabled:
log.info("Setting up iSchedule inbox resource: {cls}", cls=iScheduleResourceClass)
ischedule = iScheduleResourceClass(
root,
newStore,
)
root.putChild("ischedule", ischedule if unavailable is None else unavailable)
# Do DomainKey resources
DKIMUtils.validConfiguration(config)
if config.Scheduling.iSchedule.DKIM.Enabled:
log.info("Setting up domainkey resource: {res}", res=DomainKeyResource)
domain = config.Scheduling.iSchedule.DKIM.Domain if config.Scheduling.iSchedule.DKIM.Domain else config.ServerHostName
dk = DomainKeyResource(
domain,
config.Scheduling.iSchedule.DKIM.KeySelector,
config.Scheduling.iSchedule.DKIM.PublicKeyFile,
)
wellKnownResource.putChild("domainkey", dk)
#
# WebCal
#
if config.WebCalendarRoot:
log.info(
"Setting up WebCalendar resource: {res}",
res=config.WebCalendarRoot)
webCalendar = webCalendarResourceClass(
config.WebCalendarRoot,
principalCollections=(principalCollection,),
)
root.putChild("webcal", webCalendar if unavailable is None else unavailable)
#
# WebAdmin
#
if config.EnableWebAdmin:
log.info("Setting up WebAdmin resource")
webAdmin = webAdminResourceClass(
config.WebCalendarRoot,
root,
directory,
newStore,
principalCollections=(principalCollection,),
)
root.putChild("admin", webAdmin)
#
# Control API
#
if config.EnableControlAPI:
log.info("Setting up Control API resource")
controlAPI = controlResourceClass(
root,
directory,
newStore,
principalCollections=(principalCollection,),
)
root.putChild("control", controlAPI)
#
# Apple Push Notification Subscriptions
#
apnConfig = config.Notifications.Services.APNS
if apnConfig.Enabled:
log.info(
"Setting up APNS resource at /{url}",
url=apnConfig["SubscriptionURL"])
apnResource = apnSubscriptionResourceClass(root, newStore)
root.putChild(apnConfig["SubscriptionURL"], apnResource)
# Server info document
if config.EnableServerInfo:
log.info(
"Setting up server-info resource: {cls}",
cls=serverInfoResourceClass)
serverInfo = serverInfoResourceClass(
root,
)
root.putChild("server-info", serverInfo)
#
# Configure ancillary data
#
# MOVE2WHO
log.info("Configuring authentication wrapper")
overrides = {}
if resources:
for path, cls, args, schemes in resources:
# putChild doesn't want "/" starting the path
root.putChild(path, cls(root, newStore, *args))
# overrides requires "/" prepended
path = "/" + path
overrides[path] = []
for scheme in schemes:
if scheme == "basic":
overrides[path].append(BasicCredentialFactory(realm))
elif scheme == "digest":
schemeConfig = config.Authentication.Digest
overrides[path].append(QopDigestCredentialFactory(
schemeConfig["Algorithm"],
schemeConfig["Qop"],
realm,
))
log.info(
"Overriding {path} with {cls} ({schemes})",
path=path, cls=cls, schemes=schemes)
authWrapper = AuthenticationWrapper(
root,
portal,
wireEncryptedCredentialFactories,
wireUnencryptedCredentialFactories,
(auth.IPrincipal,),
overrides=overrides
)
logWrapper = DirectoryLogWrapperResource(
authWrapper,
directory,
)
# FIXME: Storing a reference to the root resource on the store
# until scheduling no longer needs resource objects
newStore.rootResource = root
return logWrapper
def getDBPool(config):
"""
Inspect configuration to determine what database connection pool
to set up.
return: (L{ConnectionPool}, transactionFactory)
"""
if config.DBType == 'oracle':
dialect = ORACLE_DIALECT
paramstyle = 'numeric'
else:
dialect = POSTGRES_DIALECT
paramstyle = 'pyformat'
pool = None
if config.DBAMPFD:
txnFactory = transactionFactoryFromFD(
int(config.DBAMPFD), DatabaseType(dialect, paramstyle, config.DBFeatures)
)
elif not config.UseDatabase:
txnFactory = None
elif not config.SharedConnectionPool:
if config.DBType == '':
# get a PostgresService to tell us what the local connection
# info is, but *don't* start it (that would start one postgres
# master per slave, resulting in all kinds of mayhem...)
connectionFactory = pgServiceFromConfig(config, None).produceConnection
else:
connectionFactory = DBAPIConnector.connectorFor(config.DBType, **config.DatabaseConnection).connect
pool = ConnectionPool(connectionFactory, dbtype=DatabaseType(dialect, paramstyle, config.DBFeatures),
maxConnections=config.MaxDBConnectionsPerPool)
txnFactory = pool.connection
else:
raise UsageError(
"trying to use DB in slave, but no connection info from parent"
)
return (pool, txnFactory)
class FakeRequest(object):
def __init__(self, rootResource, method, path, uri='/', transaction=None):
self.rootResource = rootResource
self.method = method
self.path = path
self.uri = uri
self._resourcesByURL = {}
self._urlsByResource = {}
self.headers = Headers()
if transaction is not None:
self._newStoreTransaction = transaction
@inlineCallbacks
def _getChild(self, resource, segments):
if not segments:
returnValue(resource)
child, remaining = (yield resource.locateChild(self, segments))
returnValue((yield self._getChild(child, remaining)))
@inlineCallbacks
def locateResource(self, url):
url = url.strip("/")
segments = url.split("/")
resource = (yield self._getChild(self.rootResource, segments))
if resource:
self._rememberResource(resource, url)
returnValue(resource)
@inlineCallbacks
def locateChildResource(self, parent, childName):
if parent is None or childName is None:
returnValue(None)
parentURL = self.urlForResource(parent)
if not parentURL.endswith("/"):
parentURL += "/"
url = parentURL + quote(childName)
segment = childName
resource = (yield self._getChild(parent, [segment]))
if resource:
self._rememberResource(resource, url)
returnValue(resource)
def _rememberResource(self, resource, url):
self._resourcesByURL[url] = resource
self._urlsByResource[resource] = url
return resource
def _forgetResource(self, resource, url):
if url in self._resourcesByURL:
del self._resourcesByURL[url]
if resource in self._urlsByResource:
del self._urlsByResource[resource]
def urlForResource(self, resource):
url = self._urlsByResource.get(resource, None)
if url is None:
class NoURLForResourceError(RuntimeError):
pass
raise NoURLForResourceError(resource)
return url
def addResponseFilter(self, *args, **kwds):
pass
def memoryForPID(pid, residentOnly=True):
"""
Return the amount of memory in use for the given process. If residentOnly is True,
then RSS is returned; if False, then virtual memory is returned.
@param pid: process id
@type pid: C{int}
@param residentOnly: Whether only resident memory should be included
@type residentOnly: C{boolean}
@return: Memory used by process in bytes
@rtype: C{int}
"""
memoryInfo = psutil.Process(pid).memory_info()
return memoryInfo.rss if residentOnly else memoryInfo.vms
class MemoryLimitService(Service, object):
"""
A service which when paired with a DelayedStartupProcessMonitor will periodically
examine the memory usage of the monitored processes and stop any which exceed
a configured limit. Memcached processes are ignored.
"""
def __init__(self, processMonitor, intervalSeconds, limitBytes, residentOnly, reactor=None):
"""
@param processMonitor: the DelayedStartupProcessMonitor
@param intervalSeconds: how often to check
@type intervalSeconds: C{int}
@param limitBytes: any monitored process over this limit is stopped
@type limitBytes: C{int}
@param residentOnly: whether only resident memory should be included
@type residentOnly: C{boolean}
@param reactor: for testing
"""
self._processMonitor = processMonitor
self._seconds = intervalSeconds
self._bytes = limitBytes
self._residentOnly = residentOnly
self._delayedCall = None
if reactor is None:
from twisted.internet import reactor
self._reactor = reactor
# Unit tests can swap out _memoryForPID
self._memoryForPID = memoryForPID
def startService(self):
"""
Start scheduling the memory checks
"""
super(MemoryLimitService, self).startService()
self._delayedCall = self._reactor.callLater(self._seconds, self.checkMemory)
def stopService(self):
"""
Stop checking memory
"""
super(MemoryLimitService, self).stopService()
if self._delayedCall is not None and self._delayedCall.active():
self._delayedCall.cancel()
self._delayedCall = None
def checkMemory(self):
"""
Stop any processes monitored by our paired processMonitor whose resident
memory exceeds our configured limitBytes. Reschedule intervalSeconds in