This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
caldav.py
1815 lines (1483 loc) · 62.8 KB
/
caldav.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-2010 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.
##
__all__ = [
"CalDAVService",
"CalDAVOptions",
"CalDAVServiceMaker",
]
import os
import socket
import stat
import sys
from time import time
from subprocess import Popen, PIPE
from pwd import getpwuid, getpwnam
from grp import getgrnam
import OpenSSL
from OpenSSL.SSL import Error as SSLError
from zope.interface import implements
from twisted.python.log import FileLogObserver, ILogObserver
from twisted.python.logfile import LogFile
from twisted.python.usage import Options, UsageError
from twisted.python.reflect import namedClass
from twisted.plugin import IPlugin
from twisted.internet.defer import gatherResults, Deferred
from twisted.internet import reactor as _reactor
from twisted.internet.reactor import addSystemEventTrigger
from twisted.internet.process import ProcessExitedAlready
from twisted.internet.protocol import Protocol, Factory
from twisted.internet.protocol import ProcessProtocol
from twisted.application.internet import TCPServer, UNIXServer
from twisted.application.service import MultiService, IServiceMaker
from twisted.application.service import Service
import twext
from twext.web2.server import Site
from twext.python.log import Logger, LoggingMixIn
from twext.python.log import logLevelForNamespace, setLogLevelForNamespace
from twext.python.filepath import CachingFilePath
from twext.internet.ssl import ChainingOpenSSLContextFactory
from twext.internet.tcp import MaxAcceptTCPServer, MaxAcceptSSLServer
from twext.web2.channel.http import LimitingHTTPFactory, SSLRedirectRequest
from twext.web2.metafd import ConnectionLimiter, ReportingHTTPService
from txdav.common.datastore.util import UpgradeToDatabaseService
from twistedcaldav.config import ConfigurationError
from twistedcaldav.config import config
from twistedcaldav.directory import calendaruserproxy
from twistedcaldav.directory.calendaruserproxyloader import XMLCalendarUserProxyLoader
from twistedcaldav.localization import processLocalizationFiles
from twistedcaldav.mail import IMIPReplyInboxResource
from twistedcaldav import memcachepool
from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
from twistedcaldav.upgrade import UpgradeFileSystemFormatService
from calendarserver.tap.util import pgServiceFromConfig
from twext.enterprise.ienterprise import POSTGRES_DIALECT
from twext.enterprise.ienterprise import ORACLE_DIALECT
from twext.enterprise.adbapi2 import ConnectionPool
from twext.enterprise.adbapi2 import ConnectionPoolConnection
try:
from twistedcaldav.authkerb import NegotiateCredentialFactory
NegotiateCredentialFactory # pacify pyflakes
except ImportError:
NegotiateCredentialFactory = None
from calendarserver.accesslog import AMPCommonAccessLoggingObserver
from calendarserver.accesslog import AMPLoggingFactory
from calendarserver.accesslog import RotatingFileAccessLoggingObserver
from calendarserver.tap.util import getRootResource, computeProcessCount
from calendarserver.tap.util import ConnectionWithPeer
from calendarserver.tap.util import storeFromConfig
from calendarserver.tap.util import transactionFactoryFromFD
from calendarserver.tap.util import pgConnectorFromConfig
from calendarserver.tap.util import oracleConnectorFromConfig
from calendarserver.tools.util import checkDirectory
try:
from calendarserver.version import version
version
except ImportError:
from twisted.python.modules import getModule
sys.path.insert(
0, getModule(__name__).pathEntry.filePath.child("support").path)
from version import version as getVersion
version = "%s (%s*)" % getVersion()
twext.web2.server.VERSION = "CalendarServer/%s %s" % (
version.replace(" ", ""), twext.web2.server.VERSION,
)
log = Logger()
from twisted.python.util import uidFromString, gidFromString
def getid(uid, gid):
if uid is not None:
uid = uidFromString(uid)
if gid is not None:
gid = gidFromString(gid)
return (uid, gid)
def _computeEnvVars(parent):
"""
Compute environment variables to be propagated to child processes.
"""
result = {}
requiredVars = [
"PATH",
"PYTHONPATH",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
]
optionalVars = [
"KRB5_KTNAME",
"ORACLE_HOME",
]
for varname in requiredVars:
result[varname] = parent.get(varname, "")
for varname in optionalVars:
if varname in parent:
result[varname] = parent[varname]
return result
PARENT_ENVIRONMENT = _computeEnvVars(os.environ)
class CalDAVStatisticsProtocol (Protocol):
def connectionMade(self):
stats = self.factory.logger.observer.getGlobalHits()
self.transport.write("%s\r\n" % (stats,))
self.transport.loseConnection()
class CalDAVStatisticsServer (Factory):
protocol = CalDAVStatisticsProtocol
def __init__(self, logObserver):
self.logger = logObserver
class ErrorLoggingMultiService(MultiService):
""" Registers a rotating file logger for error logging, iff
config.ErrorLogEnabled is True. """
def setServiceParent(self, app):
MultiService.setServiceParent(self, app)
if config.ErrorLogEnabled:
errorLogFile = LogFile.fromFullPath(
config.ErrorLogFile,
rotateLength=config.ErrorLogRotateMB * 1024 * 1024,
maxRotatedFiles=config.ErrorLogMaxRotatedFiles
)
errorLogObserver = FileLogObserver(errorLogFile).emit
# Registering ILogObserver with the Application object
# gets our observer picked up within AppLogger.start( )
app.setComponent(ILogObserver, errorLogObserver)
class CalDAVService (ErrorLoggingMultiService):
def __init__(self, logObserver):
self.logObserver = logObserver # accesslog observer
MultiService.__init__(self)
def privilegedStartService(self):
MultiService.privilegedStartService(self)
self.logObserver.start()
def stopService(self):
d = MultiService.stopService(self)
self.logObserver.stop()
return d
class CalDAVOptions (Options, LoggingMixIn):
optParameters = [[
"config", "f", DEFAULT_CONFIG_FILE, "Path to configuration file."
]]
zsh_actions = {"config" : "_files -g '*.plist'"}
def __init__(self, *args, **kwargs):
super(CalDAVOptions, self).__init__(*args, **kwargs)
self.overrides = {}
@staticmethod
def coerceOption(configDict, key, value):
"""
Coerce the given C{val} to type of C{configDict[key]}
"""
if key in configDict:
if isinstance(configDict[key], bool):
value = value == "True"
elif isinstance(configDict[key], (int, float, long)):
value = type(configDict[key])(value)
elif isinstance(configDict[key], (list, tuple)):
value = value.split(",")
elif isinstance(configDict[key], dict):
raise UsageError(
"Dict options not supported on the command line"
)
elif value == "None":
value = None
return value
@classmethod
def setOverride(cls, configDict, path, value, overrideDict):
"""
Set the value at path in configDict
"""
key = path[0]
if len(path) == 1:
overrideDict[key] = cls.coerceOption(configDict, key, value)
return
if key in configDict:
if not isinstance(configDict[key], dict):
raise UsageError(
"Found intermediate path element that is not a dictionary"
)
if key not in overrideDict:
overrideDict[key] = {}
cls.setOverride(
configDict[key], path[1:],
value, overrideDict[key]
)
def opt_option(self, option):
"""
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
--option flags may be specified.
"""
if "=" in option:
path, value = option.split("=")
self.setOverride(
DEFAULT_CONFIG,
path.split("/"),
value,
self.overrides
)
else:
self.opt_option("%s=True" % (option,))
opt_o = opt_option
def postOptions(self):
self.loadConfiguration()
self.checkConfiguration()
def loadConfiguration(self):
if not os.path.exists(self["config"]):
print "Config file %s not found. Exiting." % (self["config"],)
sys.exit(1)
print "Reading configuration from file: %s" % (self["config"],)
try:
config.load(self["config"])
except ConfigurationError, e:
print "Invalid configuration: %s" % (e,)
sys.exit(1)
config.updateDefaults(self.overrides)
def checkDirectory(self, dirpath, description, access=None, create=None):
checkDirectory(dirpath, description, access=access, create=create)
def checkConfiguration(self):
# Having CalDAV *and* CardDAV both disabled is an illegal configuration
# for a running server (but is fine for command-line utilities)
if not config.EnableCalDAV and not config.EnableCardDAV:
print "Neither EnableCalDAV nor EnableCardDAV are set to True."
sys.exit(1)
uid, gid = None, None
if self.parent["uid"] or self.parent["gid"]:
uid, gid = getid(self.parent["uid"], self.parent["gid"])
def gottaBeRoot():
if os.getuid() != 0:
username = getpwuid(os.getuid()).pw_name
raise UsageError("Only root can drop privileges. You are: %r"
% (username,))
if uid and uid != os.getuid():
gottaBeRoot()
if gid and gid != os.getgid():
gottaBeRoot()
self.parent["pidfile"] = config.PIDFile
#
# Verify that server root actually exists
#
self.checkDirectory(
config.ServerRoot,
"Server root",
# Require write access because one might not allow editing on /
access=os.W_OK,
)
#
# Verify that other root paths are OK
#
if config.DocumentRoot.startswith(config.ServerRoot + os.sep):
self.checkDirectory(
config.DocumentRoot,
"Document root",
# Don't require write access because one might not allow editing on /
access=os.R_OK,
create=(0750, config.UserName, config.GroupName),
)
if config.DataRoot.startswith(config.ServerRoot + os.sep):
self.checkDirectory(
config.DataRoot,
"Data root",
access=os.W_OK,
create=(0750, config.UserName, config.GroupName),
)
if config.ConfigRoot.startswith(config.ServerRoot + os.sep):
self.checkDirectory(
config.ConfigRoot,
"Config root",
access=os.W_OK,
create=(0750, config.UserName, config.GroupName),
)
if config.LogRoot.startswith(config.ServerRoot + os.sep):
self.checkDirectory(
config.LogRoot,
"Log root",
access=os.W_OK,
create=(0750, config.UserName, config.GroupName),
)
# Always create RunRoot (for pid files, socket files) if it does not exist
self.checkDirectory(
config.RunRoot,
"Run root",
access=os.W_OK,
create=(0770, config.UserName, config.GroupName),
)
#
# Nuke the file log observer's time format.
#
if not config.ErrorLogFile and config.ProcessType == "Slave":
FileLogObserver.timeFormat = ""
# Check current umask and warn if changed
oldmask = os.umask(config.umask)
if oldmask != config.umask:
self.log_info("WARNING: changing umask from: 0%03o to 0%03o"
% (oldmask, config.umask))
class GroupOwnedUNIXServer(UNIXServer, object):
"""
A L{GroupOwnedUNIXServer} is a L{UNIXServer} which changes the group
ownership of its socket immediately after binding its port.
@ivar gid: the group ID which should own the socket after it is bound.
"""
def __init__(self, gid, *args, **kw):
super(GroupOwnedUNIXServer, self).__init__(*args, **kw)
self.gid = gid
def privilegedStartService(self):
"""
Bind the UNIX socket and then change its group.
"""
super(GroupOwnedUNIXServer, self).privilegedStartService()
# Unfortunately, there's no public way to access this. -glyph
fileName = self._port.port
os.chown(fileName, os.getuid(), self.gid)
class SlaveSpawnerService(Service):
"""
Service to add all Python subprocesses that need to do work to a
L{DelayedStartupProcessMonitor}:
- regular slave processes (CalDAV workers)
- task sidecar
- notifier
- mail gateway
"""
def __init__(self, maker, monitor, dispenser, dispatcher, configPath,
inheritFDs=None, inheritSSLFDs=None):
self.maker = maker
self.monitor = monitor
self.dispenser = dispenser
self.dispatcher = dispatcher
self.configPath = configPath
self.inheritFDs = inheritFDs
self.inheritSSLFDs = inheritSSLFDs
def startService(self):
for slaveNumber in xrange(0, config.MultiProcess.ProcessCount):
if config.UseMetaFD:
extraArgs = dict(metaSocket=self.dispatcher.addSocket())
else:
extraArgs = dict(inheritFDs=self.inheritFDs,
inheritSSLFDs=self.inheritSSLFDs)
if self.dispenser is not None:
extraArgs.update(ampSQLDispenser=self.dispenser)
process = TwistdSlaveProcess(
sys.argv[0], self.maker.tapname, self.configPath, slaveNumber,
config.BindAddresses, **extraArgs
)
self.monitor.addProcessObject(process, PARENT_ENVIRONMENT)
if (
config.Notifications.Enabled and
config.Notifications.InternalNotificationHost == "localhost"
):
self.maker.log_info("Adding notification service")
notificationsArgv = [
sys.executable,
sys.argv[0],
]
if config.UserName:
notificationsArgv.extend(("-u", config.UserName))
if config.GroupName:
notificationsArgv.extend(("-g", config.GroupName))
notificationsArgv.extend((
"--reactor=%s" % (config.Twisted.reactor,),
"-n", self.maker.notifierTapName,
"-f", self.configPath,
))
self.monitor.addProcess("notifications", notificationsArgv,
env=PARENT_ENVIRONMENT)
if (
config.Scheduling.iMIP.Enabled and
config.Scheduling.iMIP.MailGatewayServer == "localhost"
):
self.maker.log_info("Adding mail gateway service")
mailGatewayArgv = [
sys.executable,
sys.argv[0],
]
if config.UserName:
mailGatewayArgv.extend(("-u", config.UserName))
if config.GroupName:
mailGatewayArgv.extend(("-g", config.GroupName))
mailGatewayArgv.extend((
"--reactor=%s" % (config.Twisted.reactor,),
"-n", self.maker.mailGatewayTapName,
"-f", self.configPath,
))
self.monitor.addProcess("mailgateway", mailGatewayArgv,
env=PARENT_ENVIRONMENT)
self.maker.log_info("Adding task service")
taskArgv = [
sys.executable,
sys.argv[0],
]
if config.UserName:
taskArgv.extend(("-u", config.UserName))
if config.GroupName:
taskArgv.extend(("-g", config.GroupName))
taskArgv.extend((
"--reactor=%s" % (config.Twisted.reactor,),
"-n", "caldav_task",
"-f", self.configPath,
))
self.monitor.addProcess(
"caldav_task", taskArgv, env=PARENT_ENVIRONMENT
)
class CalDAVServiceMaker (LoggingMixIn):
implements(IPlugin, IServiceMaker)
tapname = "caldav"
description = "Darwin Calendar Server"
options = CalDAVOptions
#
# Default tap names
#
mailGatewayTapName = "caldav_mailgateway"
notifierTapName = "caldav_notifier"
def makeService(self, options):
"""
Create the top-level service.
"""
self.log_info("%s %s starting %s process..." % (self.description, version, config.ProcessType))
serviceMethod = getattr(self, "makeService_%s" % (config.ProcessType,), None)
if not serviceMethod:
raise UsageError(
"Unknown server type %s. "
"Please choose: Slave, Single or Combined"
% (config.ProcessType,)
)
else:
#
# Configure Memcached Client Pool
#
memcachepool.installPools(
config.Memcached.Pools,
config.Memcached.MaxClients,
)
if config.ProcessType in ('Combined', 'Single'):
# Memcached is not needed for the "master" process
if config.ProcessType in ('Combined',):
config.Memcached.Pools.Default.ClientEnabled = False
# Note: if the master process ever needs access to memcached
# we'll either have to start memcached prior to the
# updateProxyDB call below, or disable memcached
# client config only while updateProxyDB is running.
# Process localization string files
processLocalizationFiles(config.Localization)
# Make sure proxies get initialized
if config.ProxyLoadFromFile:
def _doProxyUpdate():
proxydbClass = namedClass(config.ProxyDBService.type)
calendaruserproxy.ProxyDBService = proxydbClass(**config.ProxyDBService.params)
loader = XMLCalendarUserProxyLoader(config.ProxyLoadFromFile)
return loader.updateProxyDB()
addSystemEventTrigger("after", "startup", _doProxyUpdate)
try:
service = serviceMethod(options)
except ConfigurationError, e:
sys.stderr.write("Configuration error: %s\n" % (e,))
sys.exit(1)
#
# Note: if there is a stopped process in the same session
# as the calendar server and the calendar server is the
# group leader then when twistd forks to drop privileges a
# SIGHUP may be sent by the kernel, which can cause the
# process to exit. This SIGHUP should be, at a minimum,
# ignored.
#
def location(frame):
if frame is None:
return "Unknown"
else:
return "%s: %s" % (frame.f_code.co_name, frame.f_lineno)
import signal
def sighup_handler(num, frame):
self.log_info("SIGHUP recieved at %s" % (location(frame),))
# Reload the config file
try:
config.reload()
except ConfigurationError, e:
self.log_error("Invalid configuration: {0}".format(e))
# If combined service send signal to all caldavd children
if hasattr(service, "processMonitor"):
service.processMonitor.signalAll(signal.SIGHUP, "caldav")
# FIXME: There is no memcachepool.getCachePool
# Also, better option is probably to add a hook to
# the config object instead of doing things here.
#self.log_info("Suggesting new max clients for memcache.")
#memcachepool.getCachePool().suggestMaxClients(
# config.Memcached.MaxClients
#)
signal.signal(signal.SIGHUP, sighup_handler)
return service
def createContextFactory(self):
"""
Create an SSL context factory for use with any SSL socket talking to
this server.
"""
return ChainingOpenSSLContextFactory(
config.SSLPrivateKey,
config.SSLCertificate,
certificateChainFile=config.SSLAuthorityChain,
passwdCallback=getSSLPassphrase,
sslmethod=getattr(OpenSSL.SSL, config.SSLMethod),
ciphers=config.SSLCiphers.strip()
)
def makeService_Slave(self, options):
"""
Create a "slave" service, a subprocess of a service created with
L{makeService_Combined}, which does the work of actually handling
CalDAV and CardDAV requests.
"""
pool = None
if config.DBAMPFD:
txnFactory = transactionFactoryFromFD(int(config.DBAMPFD))
elif not config.UseDatabase:
txnFactory = None
elif not config.SharedConnectionPool:
dialect = POSTGRES_DIALECT
paramstyle = 'pyformat'
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
elif config.DBType == 'postgres':
connectionFactory = pgConnectorFromConfig(config)
elif config.DBType == 'oracle':
dialect = ORACLE_DIALECT
paramstyle = 'numeric'
connectionFactory = oracleConnectorFromConfig(config)
else:
raise UsageError("unknown DB type: %r" % (config.DBType,))
pool = ConnectionPool(connectionFactory, dialect=dialect,
paramstyle=paramstyle)
txnFactory = pool.connection
else:
raise UsageError(
"trying to use DB in slave, but no connection info from parent"
)
store = storeFromConfig(config, txnFactory)
result = self.requestProcessingService(options, store)
if pool is not None:
pool.setServiceParent(result)
return result
def requestProcessingService(self, options, store):
"""
Make a service that will actually process HTTP requests.
This may be a 'Slave' service, which runs as a worker subprocess of the
'Combined' configuration, or a 'Single' service, which is a stand-alone
process that answers CalDAV/CardDAV requests by itself.
"""
#
# Change default log level to "info" as its useful to have
# that during startup
#
oldLogLevel = logLevelForNamespace(None)
setLogLevelForNamespace(None, "info")
additional = []
if config.Scheduling.iMIP.Enabled:
additional.append(("inbox", IMIPReplyInboxResource, [], "digest"))
#
# Configure the service
#
self.log_info("Setting up service")
if config.ProcessType == "Slave":
if config.ControlSocket:
mode = "AF_UNIX"
id = config.ControlSocket
self.log_info("Logging via AF_UNIX: %s" % (id,))
else:
mode = "AF_INET"
id = int(config.ControlPort)
self.log_info("Logging via AF_INET: %d" % (id,))
logObserver = AMPCommonAccessLoggingObserver(mode, id)
elif config.ProcessType == "Single":
# Make sure no old socket files are lying around.
self.deleteStaleSocketFiles()
logObserver = RotatingFileAccessLoggingObserver(
config.AccessLogFile,
)
self.log_info("Configuring access log observer: %s" % (logObserver,))
service = CalDAVService(logObserver)
rootResource = getRootResource(config, store, additional)
underlyingSite = Site(rootResource)
requestFactory = underlyingSite
if config.RedirectHTTPToHTTPS:
self.log_info("Redirecting to HTTPS port %s" % (config.SSLPort,))
def requestFactory(*args, **kw):
return SSLRedirectRequest(site=underlyingSite, *args, **kw)
httpFactory = LimitingHTTPFactory(
requestFactory,
maxRequests=config.MaxRequests,
maxAccepts=config.MaxAccepts,
betweenRequestsTimeOut=config.IdleConnectionTimeOut,
vary=True,
)
def updateFactory(configDict):
httpFactory.maxRequests = configDict.MaxRequests
httpFactory.maxAccepts = configDict.MaxAccepts
config.addPostUpdateHooks((updateFactory,))
if config.InheritFDs or config.InheritSSLFDs:
# Inherit sockets to call accept() on them individually.
if config.EnableSSL:
for fdAsStr in config.InheritSSLFDs:
try:
contextFactory = self.createContextFactory()
except SSLError, e:
log.error("Unable to set up SSL context factory: %s" % (e,))
else:
MaxAcceptSSLServer(
int(fdAsStr), httpFactory,
contextFactory,
backlog=config.ListenBacklog,
inherit=True
).setServiceParent(service)
for fdAsStr in config.InheritFDs:
MaxAcceptTCPServer(
int(fdAsStr), httpFactory,
backlog=config.ListenBacklog,
inherit=True
).setServiceParent(service)
elif config.MetaFD:
# Inherit a single socket to receive accept()ed connections via
# recvmsg() and SCM_RIGHTS.
try:
contextFactory = self.createContextFactory()
except SSLError, e:
self.log_error("Unable to set up SSL context factory: %s" % (e,))
# None is okay as a context factory for ReportingHTTPService as
# long as we will never receive a file descriptor with the
# 'SSL' tag on it, since that's the only time it's used.
contextFactory = None
ReportingHTTPService(
requestFactory, int(config.MetaFD), contextFactory
).setServiceParent(service)
else: # Not inheriting, therefore we open our own:
for bindAddress in self._allBindAddresses():
self._validatePortConfig()
if config.EnableSSL:
for port in config.BindSSLPorts:
self.log_info("Adding SSL server at %s:%s"
% (bindAddress, port))
try:
contextFactory = self.createContextFactory()
except SSLError, e:
self.log_error("Unable to set up SSL context factory: %s"
% (e,))
self.log_error("Disabling SSL port: %s" % (port,))
else:
httpsService = MaxAcceptSSLServer(
int(port), httpFactory,
contextFactory, interface=bindAddress,
backlog=config.ListenBacklog,
inherit=False
)
httpsService.setServiceParent(service)
for port in config.BindHTTPPorts:
MaxAcceptTCPServer(
int(port), httpFactory,
interface=bindAddress,
backlog=config.ListenBacklog,
inherit=False
).setServiceParent(service)
# Change log level back to what it was before
setLogLevelForNamespace(None, oldLogLevel)
return service
def _validatePortConfig(self):
"""
If BindHTTPPorts is specified, HTTPPort must also be specified to
indicate which is the preferred port (the one to be used in URL
generation, etc). If only HTTPPort is specified, BindHTTPPorts should
be set to a list containing only that port number. Similarly for
BindSSLPorts/SSLPort.
@raise UsageError: if configuration is not valid.
"""
if config.BindHTTPPorts:
if config.HTTPPort == 0:
raise UsageError(
"HTTPPort required if BindHTTPPorts is not empty"
)
elif config.HTTPPort != 0:
config.BindHTTPPorts = [config.HTTPPort]
if config.BindSSLPorts:
if config.SSLPort == 0:
raise UsageError(
"SSLPort required if BindSSLPorts is not empty"
)
elif config.SSLPort != 0:
config.BindSSLPorts = [config.SSLPort]
def _allBindAddresses(self):
"""
An empty array for the config value of BindAddresses should be
equivalent a BindAddresses with a single empty string, meaning "bind
everything".
"""
if not config.BindAddresses:
config.BindAddresses = [""]
return config.BindAddresses
def makeService_Single(self, options):
"""
Create a service to be used in a single-process, stand-alone
configuration.
"""
def slaveSvcCreator(pool, store):
return self.requestProcessingService(options, store)
return self.storageService(slaveSvcCreator)
def makeService_Utility(self, options):
"""
Create a service to be used in a command-line utility
Specify the actual utility service class in config.UtilityServiceClass.
When created, that service will have access to the storage facilities.
"""
def toolServiceCreator(pool, store):
return config.UtilityServiceClass(store)
return self.storageService(toolServiceCreator)
def storageService(self, createMainService, uid=None, gid=None):
"""
If necessary, create a service to be started used for storage; for
example, starting a database backend. This service will then start the
main service.
This has the effect of delaying any child process spawning or
standalone port-binding until the backing for the selected data store
implementation is ready to process requests.
@param createMainService: This is the service that will be doing the main
work of the current process. If the configured storage mode does
not require any particular setup, then this may return the
C{mainService} argument.
@type mainService: C{callable} that takes C{(connectionPool, store)}
and returns L{IService}
@param uid: the user ID to run the backend as, if this process is
running as root (also the uid to chown Attachments to).
@type uid: C{int}
@param gid: the user ID to run the backend as, if this process is
running as root (also the gid to chown Attachments to).
@type gid: C{int}
@return: the appropriate a service to start.
@rtype: L{IService}
"""
if config.UseDatabase:
if os.getuid() == 0: # Only override if root
overrideUID = uid
overrideGID = gid
else:
overrideUID = None
overrideGID = None
if config.DBType == '':
# Spawn our own database as an inferior process, then connect
# to it.
pgserv = pgServiceFromConfig(
config,
self.subServiceFactoryFactory(createMainService,
uid=overrideUID, gid=overrideGID),
uid=overrideUID, gid=overrideGID
)
return pgserv
elif config.DBType == 'postgres':
# Connect to a postgres database that is already running.
return self.subServiceFactoryFactory(createMainService,
uid=overrideUID, gid=overrideGID)(
pgConnectorFromConfig(config))
elif config.DBType == 'oracle':
# Connect to an Oracle database that is already running.
return self.subServiceFactoryFactory(createMainService,
uid=overrideUID, gid=overrideGID,
dialect=ORACLE_DIALECT, paramstyle='numeric')(
oracleConnectorFromConfig(config))
else:
raise UsageError("Unknown database type %r" (config.DBType,))
else:
store = storeFromConfig(config, None)
return createMainService(None, store)
def subServiceFactoryFactory(self, createMainService, uid=None, gid=None,
dialect=POSTGRES_DIALECT,
paramstyle='pyformat'):
def subServiceFactory(connectionFactory):
ms = MultiService()
cp = ConnectionPool(connectionFactory, dialect=dialect,
paramstyle=paramstyle)
cp.setServiceParent(ms)
store = storeFromConfig(config, cp.connection)
mainService = createMainService(cp, store)
upgradeSvc = UpgradeFileSystemFormatService(config,
UpgradeToDatabaseService.wrapService(
CachingFilePath(config.DocumentRoot), mainService,
store, uid=uid, gid=gid
)
)
upgradeSvc.setServiceParent(ms)
return ms
return subServiceFactory
def makeService_Combined(self, options):
"""
Create a master service to coordinate a multi-process configuration,
spawning subprocesses that use L{makeService_Slave} to perform work.
"""
s = ErrorLoggingMultiService()