This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
caldav.py
2374 lines (1933 loc) · 84 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-2013 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.
##
from __future__ import print_function
__all__ = [
"CalDAVService",
"CalDAVOptions",
"CalDAVServiceMaker",
]
import os
import signal
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 os import getuid, getgid
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.util import uidFromString, gidFromString
from twisted.plugin import IPlugin
from twisted.internet.defer import gatherResults, Deferred, inlineCallbacks, succeed
from twisted.internet.process import ProcessExitedAlready
from twisted.internet.protocol import Protocol, Factory
from twisted.internet.protocol import ProcessProtocol
from twisted.internet.endpoints import UNIXClientEndpoint, TCP4ClientEndpoint
from twisted.application.internet import TCPServer, UNIXServer
from twisted.application.service import MultiService, IServiceMaker
from twisted.application.service import Service
from twisted.protocols.amp import AMP
from twext.web2.server import Site
from twext.python.log import Logger, LogLevel, replaceTwistedLoggers
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 twext.enterprise.ienterprise import POSTGRES_DIALECT
from twext.enterprise.ienterprise import ORACLE_DIALECT
from twext.enterprise.adbapi2 import ConnectionPool
from twext.enterprise.queue import WorkerFactory as QueueWorkerFactory
from twext.enterprise.queue import PeerConnectionPool
from txdav.common.datastore.sql_tables import schema
from txdav.common.datastore.upgrade.sql.upgrade import (
UpgradeDatabaseSchemaStep, UpgradeDatabaseAddressBookDataStep,
UpgradeDatabaseCalendarDataStep, UpgradeDatabaseOtherStep,
UpgradeAcquireLockStep, UpgradeReleaseLockStep
)
from txdav.common.datastore.upgrade.migrate import UpgradeToDatabaseStep
from txdav.caldav.datastore.scheduling.imip.inbound import MailRetriever
from txdav.caldav.datastore.scheduling.imip.inbound import scheduleNextMailPoll
from twistedcaldav.config import config, ConfigurationError
from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
from twistedcaldav.directory import calendaruserproxy
from twistedcaldav.directory.directory import GroupMembershipCacheUpdater
from twistedcaldav.localization import processLocalizationFiles
from twistedcaldav import memcachepool
from twistedcaldav.upgrade import UpgradeFileSystemFormatStep, PostDBImportStep
from twistedcaldav.directory.directory import scheduleNextGroupCachingUpdate
try:
from twistedcaldav.authkerb import NegotiateCredentialFactory
NegotiateCredentialFactory # pacify pyflakes
except ImportError:
NegotiateCredentialFactory = None
from calendarserver.tap.util import pgServiceFromConfig, getDBPool, MemoryLimitService
from calendarserver.tap.util import checkDirectories
from calendarserver.tap.util import Stepper
from calendarserver.tap.util import ConnectionDispenser
from calendarserver.tap.util import getRootResource
from calendarserver.tap.util import storeFromConfig
from calendarserver.tap.util import pgConnectorFromConfig
from calendarserver.tap.util import oracleConnectorFromConfig
from calendarserver.controlsocket import ControlSocket
from calendarserver.controlsocket import ControlSocketConnectingService
from calendarserver.accesslog import AMPCommonAccessLoggingObserver
from calendarserver.accesslog import AMPLoggingFactory
from calendarserver.accesslog import RotatingFileAccessLoggingObserver
from calendarserver.push.notifier import PushDistributor
from calendarserver.push.amppush import AMPPushMaster, AMPPushForwarder
from calendarserver.push.applepush import ApplePushNotifierService
from calendarserver.tools.agent import makeAgentService
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()
from twext.web2.server import VERSION as TWISTED_VERSION
TWISTED_VERSION = "CalendarServer/%s %s" % (
version.replace(" ", ""), TWISTED_VERSION,
)
log = Logger()
# Control socket message-routing constants.
_LOG_ROUTE = "log"
_QUEUE_ROUTE = "queue"
_CONTROL_SERVICE_NAME = "control"
def getid(uid, gid):
if uid is not None:
uid = uidFromString(uid)
if gid is not None:
gid = gidFromString(gid)
return (uid, gid)
def conflictBetweenIPv4AndIPv6():
"""
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
This is a temporary workaround until maybe Twisted starts setting
C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets.
@return: C{True} if listening on IPv4 conflicts with listening on IPv6.
"""
s4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
try:
s4.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s4.bind(("", 0))
s4.listen(1)
usedport = s4.getsockname()[1]
try:
s6.bind(("::", usedport))
except socket.error:
return True
else:
return False
finally:
s4.close()
s6.close()
def _computeEnvVars(parent):
"""
Compute environment variables to be propagated to child processes.
"""
result = {}
requiredVars = [
"PATH",
"PYTHONPATH",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
]
optionalVars = [
"PYTHONHASHSEED",
"KRB5_KTNAME",
"ORACLE_HOME",
"VERSIONER_PYTHON_PREFER_32_BIT",
]
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.getStats()
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, object):
""" Registers a rotating file logger for error logging, if
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):
# The ConnectionService is a MultiService which bundles all the connection
# services together for the purposes of being able to stop them and wait
# for all of their connections to close before shutting down.
connectionServiceName = "ConnectionService"
def __init__(self, logObserver):
self.logObserver = logObserver # accesslog observer
MultiService.__init__(self)
def privilegedStartService(self):
MultiService.privilegedStartService(self)
self.logObserver.start()
@inlineCallbacks
def stopService(self):
"""
Wait for outstanding requests to finish
@return: a Deferred which fires when all outstanding requests are complete
"""
connectionService = self.getServiceNamed(self.connectionServiceName)
# Note: removeService() also calls stopService()
yield self.removeService(connectionService)
# At this point, all outstanding requests have been responded to
yield super(CalDAVService, self).stopService()
self.logObserver.stop()
class CalDAVOptions (Options):
log = Logger()
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 separated 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):
try:
self.loadConfiguration()
self.checkConfiguration()
except ConfigurationError, e:
print("Invalid configuration: %s" % (e,))
sys.exit(1)
def loadConfiguration(self):
if not os.path.exists(self["config"]):
raise ConfigurationError("Config file %s not found. Exiting."
% (self["config"],))
print("Reading configuration from file: %s" % (self["config"],))
config.load(self["config"])
config.updateDefaults(self.overrides)
def checkDirectories(self, config):
checkDirectories(config)
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 config.ProcessType not in ["Agent", "Utility"]:
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
self.checkDirectories(config)
#
# 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))
self.parent['umask'] = 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)
"""
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)
class WorkSchedulingService(Service):
"""
A Service to kick off the initial scheduling of periodic work items.
"""
log = Logger()
def __init__(self, store, doImip, doGroupCaching):
"""
@param store: the Store to use for enqueuing work
@param doImip: whether to schedule imip polling
@type doImip: boolean
@param doGroupCaching: whether to schedule group caching
@type doImip: boolean
"""
self.store = store
self.doImip = doImip
self.doGroupCaching = doGroupCaching
@inlineCallbacks
def startService(self):
# Note: the "seconds in the future" args are being set to the LogID
# numbers to spread them out. This is only needed until
# ultimatelyPerform( ) handles groups correctly. Once that is fixed
# these can be set to zero seconds in the future.
if self.doImip:
yield scheduleNextMailPoll(self.store, int(config.LogID) if config.LogID else 5)
if self.doGroupCaching:
yield scheduleNextGroupCachingUpdate(self.store, int(config.LogID) if config.LogID else 5)
class ReExecService(MultiService):
"""
A MultiService which catches SIGHUP and re-exec's the process.
"""
log = Logger()
def __init__(self, pidfilePath, reactor=None):
"""
@param pidFilePath: Absolute path to the pidfile which will need to be
removed
@type pidFilePath: C{str}
"""
self.pidfilePath = pidfilePath
if reactor is None:
from twisted.internet import reactor
self.reactor = reactor
MultiService.__init__(self)
def reExec(self):
"""
Removes pidfile, registers an exec to happen after shutdown, then
stops the reactor.
"""
self.log.warn("SIGHUP received - restarting")
try:
self.log.info("Removing pidfile: %s" % (self.pidfilePath,))
os.remove(self.pidfilePath)
except OSError:
pass
self.reactor.addSystemEventTrigger("after", "shutdown", os.execv,
sys.executable, [sys.executable] + sys.argv)
self.reactor.stop()
def sighupHandler(self, num, frame):
self.reactor.callFromThread(self.reExec)
def startService(self):
self.previousHandler = signal.signal(signal.SIGHUP, self.sighupHandler)
MultiService.startService(self)
def stopService(self):
signal.signal(signal.SIGHUP, self.previousHandler)
MultiService.stopService(self)
class PreProcessingService(Service):
"""
A Service responsible for running any work that needs to be finished prior
to the main service starting. Once that work is done, it instantiates the
main service and adds it to the Service hierarchy (specifically to its
parent). If the final work step does not return a Failure, that is an
indication the store is ready and it is passed to the main service.
Otherwise, None is passed to the main service in place of a store. This
is mostly useful in the case of command line utilities that need to do
something different if the store is not available (e.g. utilities that
aren't allowed to upgrade the database).
"""
def __init__(self, serviceCreator, connectionPool, store, logObserver,
reactor=None):
"""
@param serviceCreator: callable which will be passed the connection
pool, store, and log observer, and should return a Service
@param connectionPool: connection pool to pass to serviceCreator
@param store: the store object being processed
@param logObserver: log observer to pass to serviceCreator
"""
self.serviceCreator = serviceCreator
self.connectionPool = connectionPool
self.store = store
self.logObserver = logObserver
self.stepper = Stepper()
if reactor is None:
from twisted.internet import reactor
self.reactor = reactor
def stepWithResult(self, result):
"""
The final "step"; if we get here we know our store is ready, so
we create the main service and pass in the store.
"""
service = self.serviceCreator(self.connectionPool, self.store,
self.logObserver)
if self.parent is not None:
self.reactor.callLater(0, service.setServiceParent, self.parent)
return succeed(None)
def stepWithFailure(self, failure):
"""
The final "step", but if we get here we know our store is not ready,
so we create the main service and pass in a None for the store.
"""
try:
service = self.serviceCreator(self.connectionPool, None,
self.logObserver)
if self.parent is not None:
self.reactor.callLater(0, service.setServiceParent, self.parent)
except StoreNotAvailable:
self.reactor.stop()
return succeed(None)
def addStep(self, step):
"""
Hand the step to our Stepper
@param step: an object implementing stepWithResult( )
"""
self.stepper.addStep(step)
return self
def startService(self):
"""
Add ourself as the final step, and then tell the coordinator to start
working on each step one at a time.
"""
self.addStep(self)
self.stepper.start()
class PostUpgradeStopRequested(Exception):
"""
Raised when we've been asked to stop just after upgrade has completed.
"""
class StoreNotAvailable(Exception):
"""
Raised when we want to give up because the store is not available
"""
class QuitAfterUpgradeStep(object):
def __init__(self, triggerFile, reactor=None):
self.triggerFile = triggerFile
if reactor is None:
from twisted.internet import reactor
self.reactor = reactor
def removeTriggerFile(self):
try:
os.remove(self.triggerFile)
except OSError:
pass
def stepWithResult(self, result):
if os.path.exists(self.triggerFile):
self.removeTriggerFile()
self.reactor.stop()
raise PostUpgradeStopRequested()
else:
return succeed(result)
def stepWithFailure(self, failure):
if os.path.exists(self.triggerFile):
self.removeTriggerFile()
self.reactor.stop()
raise PostUpgradeStopRequested()
else:
return failure
class CalDAVServiceMaker (object):
log = Logger()
implements(IPlugin, IServiceMaker)
tapname = "caldav"
description = "Calendar and Contacts Server"
options = CalDAVOptions
def makeService(self, options):
"""
Create the top-level service.
"""
replaceTwistedLoggers()
self.log.info("%s %s starting %s process..." % (self.description, version, config.ProcessType))
try:
from setproctitle import setproctitle
except ImportError:
pass
else:
execName = os.path.basename(sys.argv[0])
if config.LogID:
logID = " #%s" % (config.LogID,)
else:
logID = ""
if config.ProcessType is not "Utility":
execName = ""
setproctitle("CalendarServer %s [%s%s] %s" % (version, config.ProcessType, logID, execName))
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"):
# Process localization string files
processLocalizationFiles(config.Localization)
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)
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, txnFactory = getDBPool(config)
store = storeFromConfig(config, txnFactory)
logObserver = AMPCommonAccessLoggingObserver()
result = self.requestProcessingService(options, store, logObserver)
directory = store.directoryService()
if pool is not None:
pool.setServiceParent(result)
if config.ControlSocket:
id = config.ControlSocket
self.log.info("Control via AF_UNIX: %s" % (id,))
endpointFactory = lambda reactor: UNIXClientEndpoint(
reactor, id)
else:
id = int(config.ControlPort)
self.log.info("Control via AF_INET: %d" % (id,))
endpointFactory = lambda reactor: TCP4ClientEndpoint(
reactor, "127.0.0.1", id)
controlSocketClient = ControlSocket()
class LogClient(AMP):
def startReceivingBoxes(self, sender):
super(LogClient, self).startReceivingBoxes(sender)
logObserver.addClient(self)
f = Factory()
f.protocol = LogClient
controlSocketClient.addFactory(_LOG_ROUTE, f)
from txdav.common.datastore.sql import CommonDataStore as SQLStore
if isinstance(store, SQLStore):
def queueMasterAvailable(connectionFromMaster):
store.queuer = store.queuer.transferProposalCallbacks(connectionFromMaster)
queueFactory = QueueWorkerFactory(store.newTransaction, schema,
queueMasterAvailable)
controlSocketClient.addFactory(_QUEUE_ROUTE, queueFactory)
controlClient = ControlSocketConnectingService(
endpointFactory, controlSocketClient
)
controlClient.setServiceParent(result)
# Optionally set up push notifications
pushDistributor = None
if config.Notifications.Enabled:
observers = []
if config.Notifications.Services.APNS.Enabled:
pushSubService = ApplePushNotifierService.makeService(
config.Notifications.Services.APNS, store)
observers.append(pushSubService)
pushSubService.setServiceParent(result)
if config.Notifications.Services.AMP.Enabled:
pushSubService = AMPPushForwarder(controlSocketClient)
observers.append(pushSubService)
if observers:
pushDistributor = PushDistributor(observers)
# Optionally set up mail retrieval
if config.Scheduling.iMIP.Enabled:
mailRetriever = MailRetriever(store, directory,
config.Scheduling.iMIP.Receiving)
mailRetriever.setServiceParent(result)
else:
mailRetriever = None
# Optionally set up group cacher
if config.GroupCaching.Enabled:
groupCacher = GroupMembershipCacheUpdater(
calendaruserproxy.ProxyDBService,
directory,
config.GroupCaching.UpdateSeconds,
config.GroupCaching.ExpireSeconds,
namespace=config.GroupCaching.MemcachedPool,
useExternalProxies=config.GroupCaching.UseExternalProxies
)
else:
groupCacher = None
def decorateTransaction(txn):
txn._pushDistributor = pushDistributor
txn._rootResource = result.rootResource
txn._mailRetriever = mailRetriever
txn._groupCacher = groupCacher
store.callWithNewTransactions(decorateTransaction)
# Optionally enable Manhole access
if config.Manhole.Enabled:
try:
from twisted.conch.manhole_tap import makeService as manholeMakeService
portString = "tcp:%d:interface=127.0.0.1" % (config.Manhole.StartingPortNumber + int(config.LogID) + 1,)
manholeService = manholeMakeService({
"sshPort" : None,
"telnetPort" : portString,
"namespace" : {
"config" : config,
"service" : result,
"store" : store,
"directory" : directory,
},
"passwd" : config.Manhole.PasswordFilePath,
})
manholeService.setServiceParent(result)
# Using print(because logging isn't ready at this point)
print("Manhole access enabled: %s" % (portString,))
except ImportError:
print("Manhole access could not enabled because manhole_tap could not be imported")
return result
def requestProcessingService(self, options, store, logObserver):
"""
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 = log.publisher.levels.logLevelForNamespace(None)
log.publisher.levels.setLogLevelForNamespace(None, LogLevel.info)
# Note: 'additional' was used for IMIP reply resource, and perhaps
# we can remove this
additional = []
#
# Configure the service
#
self.log.info("Setting up service")
self.log.info("Configuring access log observer: %s" % (logObserver,))
service = CalDAVService(logObserver)
rootResource = getRootResource(config, store, additional)
service.rootResource = rootResource
underlyingSite = Site(rootResource)
# Need to cache SSL port info here so we can access it in a Request to
# deal with the possibility of being behind an SSL decoder
underlyingSite.EnableSSL = config.EnableSSL
underlyingSite.SSLPort = config.SSLPort
underlyingSite.BindSSLPorts = config.BindSSLPorts
requestFactory = underlyingSite
if config.EnableSSL and config.RedirectHTTPToHTTPS:
self.log.info("Redirecting to HTTPS port %s" % (config.SSLPort,))
def requestFactory(*args, **kw):
return SSLRedirectRequest(site=underlyingSite, *args, **kw)
# Add the Strict-Transport-Security header to all secured requests
# if enabled.
if config.StrictTransportSecuritySeconds:
previousRequestFactory = requestFactory
def requestFactory(*args, **kw):
request = previousRequestFactory(*args, **kw)
def responseFilter(ignored, response):
ignored, secure = request.chanRequest.getHostInfo()
if secure:
response.headers.addRawHeader("Strict-Transport-Security",
"max-age={max_age:d}"
.format(max_age=config.StrictTransportSecuritySeconds))
return response
request.addResponseFilter(responseFilter)
return request
httpFactory = LimitingHTTPFactory(
requestFactory,
maxRequests=config.MaxRequests,
maxAccepts=config.MaxAccepts,
betweenRequestsTimeOut=config.IdleConnectionTimeOut,
vary=True,
)
def updateFactory(configDict, reloading=False):
httpFactory.maxRequests = configDict.MaxRequests
httpFactory.maxAccepts = configDict.MaxAccepts
config.addPostUpdateHooks((updateFactory,))
# Bundle the various connection services within a single MultiService
# that can be stopped before the others for graceful shutdown.
connectionService = MultiService()
connectionService.setName(CalDAVService.connectionServiceName)
connectionService.setServiceParent(service)
# Service to schedule initial work
WorkSchedulingService(
store,
config.Scheduling.iMIP.Enabled,
(config.GroupCaching.Enabled and config.GroupCaching.EnableUpdater)
).setServiceParent(service)
# For calendarserver.tap.test.test_caldav.BaseServiceMakerTests.getSite():