server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. # This file provides some classes for setting up (partially-populated)
  18. # homeservers; either as a full homeserver as a real application, or a small
  19. # partial one for unit test mocking.
  20. # Imports required for the default HomeServer() implementation
  21. import abc
  22. import logging
  23. from twisted.enterprise import adbapi
  24. from twisted.mail.smtp import sendmail
  25. from twisted.web.client import BrowserLikePolicyForHTTPS
  26. from synapse.api.auth import Auth
  27. from synapse.api.filtering import Filtering
  28. from synapse.api.ratelimiting import Ratelimiter
  29. from synapse.appservice.api import ApplicationServiceApi
  30. from synapse.appservice.scheduler import ApplicationServiceScheduler
  31. from synapse.crypto import context_factory
  32. from synapse.crypto.keyring import Keyring
  33. from synapse.events.builder import EventBuilderFactory
  34. from synapse.events.spamcheck import SpamChecker
  35. from synapse.events.third_party_rules import ThirdPartyEventRules
  36. from synapse.events.utils import EventClientSerializer
  37. from synapse.federation.federation_client import FederationClient
  38. from synapse.federation.federation_server import (
  39. FederationHandlerRegistry,
  40. FederationServer,
  41. ReplicationFederationHandlerRegistry,
  42. )
  43. from synapse.federation.send_queue import FederationRemoteSendQueue
  44. from synapse.federation.sender import FederationSender
  45. from synapse.federation.transport.client import TransportLayerClient
  46. from synapse.groups.attestations import GroupAttestationSigning, GroupAttestionRenewer
  47. from synapse.groups.groups_server import GroupsServerHandler
  48. from synapse.handlers import Handlers
  49. from synapse.handlers.account_validity import AccountValidityHandler
  50. from synapse.handlers.acme import AcmeHandler
  51. from synapse.handlers.appservice import ApplicationServicesHandler
  52. from synapse.handlers.auth import AuthHandler, MacaroonGenerator
  53. from synapse.handlers.deactivate_account import DeactivateAccountHandler
  54. from synapse.handlers.device import DeviceHandler, DeviceWorkerHandler
  55. from synapse.handlers.devicemessage import DeviceMessageHandler
  56. from synapse.handlers.e2e_keys import E2eKeysHandler
  57. from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
  58. from synapse.handlers.events import EventHandler, EventStreamHandler
  59. from synapse.handlers.groups_local import GroupsLocalHandler
  60. from synapse.handlers.initial_sync import InitialSyncHandler
  61. from synapse.handlers.message import EventCreationHandler, MessageHandler
  62. from synapse.handlers.pagination import PaginationHandler
  63. from synapse.handlers.presence import PresenceHandler
  64. from synapse.handlers.profile import BaseProfileHandler, MasterProfileHandler
  65. from synapse.handlers.read_marker import ReadMarkerHandler
  66. from synapse.handlers.receipts import ReceiptsHandler
  67. from synapse.handlers.register import RegistrationHandler
  68. from synapse.handlers.room import RoomContextHandler, RoomCreationHandler
  69. from synapse.handlers.room_list import RoomListHandler
  70. from synapse.handlers.room_member import RoomMemberMasterHandler
  71. from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
  72. from synapse.handlers.set_password import SetPasswordHandler
  73. from synapse.handlers.stats import StatsHandler
  74. from synapse.handlers.sync import SyncHandler
  75. from synapse.handlers.typing import TypingHandler
  76. from synapse.handlers.user_directory import UserDirectoryHandler
  77. from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
  78. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  79. from synapse.notifier import Notifier
  80. from synapse.push.action_generator import ActionGenerator
  81. from synapse.push.pusherpool import PusherPool
  82. from synapse.rest.media.v1.media_repository import (
  83. MediaRepository,
  84. MediaRepositoryResource,
  85. )
  86. from synapse.secrets import Secrets
  87. from synapse.server_notices.server_notices_manager import ServerNoticesManager
  88. from synapse.server_notices.server_notices_sender import ServerNoticesSender
  89. from synapse.server_notices.worker_server_notices_sender import (
  90. WorkerServerNoticesSender,
  91. )
  92. from synapse.state import StateHandler, StateResolutionHandler
  93. from synapse.streams.events import EventSources
  94. from synapse.util import Clock
  95. from synapse.util.distributor import Distributor
  96. logger = logging.getLogger(__name__)
  97. class HomeServer(object):
  98. """A basic homeserver object without lazy component builders.
  99. This will need all of the components it requires to either be passed as
  100. constructor arguments, or the relevant methods overriding to create them.
  101. Typically this would only be used for unit tests.
  102. For every dependency in the DEPENDENCIES list below, this class creates one
  103. method,
  104. def get_DEPENDENCY(self)
  105. which returns the value of that dependency. If no value has yet been set
  106. nor was provided to the constructor, it will attempt to call a lazy builder
  107. method called
  108. def build_DEPENDENCY(self)
  109. which must be implemented by the subclass. This code may call any of the
  110. required "get" methods on the instance to obtain the sub-dependencies that
  111. one requires.
  112. Attributes:
  113. config (synapse.config.homeserver.HomeserverConfig):
  114. _listening_services (list[twisted.internet.tcp.Port]): TCP ports that
  115. we are listening on to provide HTTP services.
  116. """
  117. __metaclass__ = abc.ABCMeta
  118. DEPENDENCIES = [
  119. "http_client",
  120. "db_pool",
  121. "federation_client",
  122. "federation_server",
  123. "handlers",
  124. "auth",
  125. "room_creation_handler",
  126. "state_handler",
  127. "state_resolution_handler",
  128. "presence_handler",
  129. "sync_handler",
  130. "typing_handler",
  131. "room_list_handler",
  132. "acme_handler",
  133. "auth_handler",
  134. "device_handler",
  135. "stats_handler",
  136. "e2e_keys_handler",
  137. "e2e_room_keys_handler",
  138. "event_handler",
  139. "event_stream_handler",
  140. "initial_sync_handler",
  141. "application_service_api",
  142. "application_service_scheduler",
  143. "application_service_handler",
  144. "device_message_handler",
  145. "profile_handler",
  146. "event_creation_handler",
  147. "deactivate_account_handler",
  148. "set_password_handler",
  149. "notifier",
  150. "event_sources",
  151. "keyring",
  152. "pusherpool",
  153. "event_builder_factory",
  154. "filtering",
  155. "http_client_context_factory",
  156. "simple_http_client",
  157. "media_repository",
  158. "media_repository_resource",
  159. "federation_transport_client",
  160. "federation_sender",
  161. "receipts_handler",
  162. "macaroon_generator",
  163. "tcp_replication",
  164. "read_marker_handler",
  165. "action_generator",
  166. "user_directory_handler",
  167. "groups_local_handler",
  168. "groups_server_handler",
  169. "groups_attestation_signing",
  170. "groups_attestation_renewer",
  171. "secrets",
  172. "spam_checker",
  173. "third_party_event_rules",
  174. "room_member_handler",
  175. "federation_registry",
  176. "server_notices_manager",
  177. "server_notices_sender",
  178. "message_handler",
  179. "pagination_handler",
  180. "room_context_handler",
  181. "sendmail",
  182. "registration_handler",
  183. "account_validity_handler",
  184. "saml_handler",
  185. "event_client_serializer",
  186. ]
  187. REQUIRED_ON_MASTER_STARTUP = ["user_directory_handler", "stats_handler"]
  188. # This is overridden in derived application classes
  189. # (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
  190. # instantiated during setup() for future return by get_datastore()
  191. DATASTORE_CLASS = abc.abstractproperty()
  192. def __init__(self, hostname, reactor=None, **kwargs):
  193. """
  194. Args:
  195. hostname : The hostname for the server.
  196. """
  197. if not reactor:
  198. from twisted.internet import reactor
  199. self._reactor = reactor
  200. self.hostname = hostname
  201. self._building = {}
  202. self._listening_services = []
  203. self.clock = Clock(reactor)
  204. self.distributor = Distributor()
  205. self.ratelimiter = Ratelimiter()
  206. self.admin_redaction_ratelimiter = Ratelimiter()
  207. self.registration_ratelimiter = Ratelimiter()
  208. self.datastore = None
  209. # Other kwargs are explicit dependencies
  210. for depname in kwargs:
  211. setattr(self, depname, kwargs[depname])
  212. def setup(self):
  213. logger.info("Setting up.")
  214. with self.get_db_conn() as conn:
  215. self.datastore = self.DATASTORE_CLASS(conn, self)
  216. conn.commit()
  217. logger.info("Finished setting up.")
  218. def setup_master(self):
  219. """
  220. Some handlers have side effects on instantiation (like registering
  221. background updates). This function causes them to be fetched, and
  222. therefore instantiated, to run those side effects.
  223. """
  224. for i in self.REQUIRED_ON_MASTER_STARTUP:
  225. getattr(self, "get_" + i)()
  226. def get_reactor(self):
  227. """
  228. Fetch the Twisted reactor in use by this HomeServer.
  229. """
  230. return self._reactor
  231. def get_ip_from_request(self, request):
  232. # X-Forwarded-For is handled by our custom request type.
  233. return request.getClientIP()
  234. def is_mine(self, domain_specific_string):
  235. return domain_specific_string.domain == self.hostname
  236. def is_mine_id(self, string):
  237. return string.split(":", 1)[1] == self.hostname
  238. def get_clock(self):
  239. return self.clock
  240. def get_datastore(self):
  241. return self.datastore
  242. def get_config(self):
  243. return self.config
  244. def get_distributor(self):
  245. return self.distributor
  246. def get_ratelimiter(self):
  247. return self.ratelimiter
  248. def get_registration_ratelimiter(self):
  249. return self.registration_ratelimiter
  250. def get_admin_redaction_ratelimiter(self):
  251. return self.admin_redaction_ratelimiter
  252. def build_federation_client(self):
  253. return FederationClient(self)
  254. def build_federation_server(self):
  255. return FederationServer(self)
  256. def build_handlers(self):
  257. return Handlers(self)
  258. def build_notifier(self):
  259. return Notifier(self)
  260. def build_auth(self):
  261. return Auth(self)
  262. def build_http_client_context_factory(self):
  263. return (
  264. InsecureInterceptableContextFactory()
  265. if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
  266. else BrowserLikePolicyForHTTPS()
  267. )
  268. def build_simple_http_client(self):
  269. return SimpleHttpClient(self)
  270. def build_room_creation_handler(self):
  271. return RoomCreationHandler(self)
  272. def build_sendmail(self):
  273. return sendmail
  274. def build_state_handler(self):
  275. return StateHandler(self)
  276. def build_state_resolution_handler(self):
  277. return StateResolutionHandler(self)
  278. def build_presence_handler(self):
  279. return PresenceHandler(self)
  280. def build_typing_handler(self):
  281. return TypingHandler(self)
  282. def build_sync_handler(self):
  283. return SyncHandler(self)
  284. def build_room_list_handler(self):
  285. return RoomListHandler(self)
  286. def build_auth_handler(self):
  287. return AuthHandler(self)
  288. def build_macaroon_generator(self):
  289. return MacaroonGenerator(self)
  290. def build_device_handler(self):
  291. if self.config.worker_app:
  292. return DeviceWorkerHandler(self)
  293. else:
  294. return DeviceHandler(self)
  295. def build_device_message_handler(self):
  296. return DeviceMessageHandler(self)
  297. def build_e2e_keys_handler(self):
  298. return E2eKeysHandler(self)
  299. def build_e2e_room_keys_handler(self):
  300. return E2eRoomKeysHandler(self)
  301. def build_acme_handler(self):
  302. return AcmeHandler(self)
  303. def build_application_service_api(self):
  304. return ApplicationServiceApi(self)
  305. def build_application_service_scheduler(self):
  306. return ApplicationServiceScheduler(self)
  307. def build_application_service_handler(self):
  308. return ApplicationServicesHandler(self)
  309. def build_event_handler(self):
  310. return EventHandler(self)
  311. def build_event_stream_handler(self):
  312. return EventStreamHandler(self)
  313. def build_initial_sync_handler(self):
  314. return InitialSyncHandler(self)
  315. def build_profile_handler(self):
  316. if self.config.worker_app:
  317. return BaseProfileHandler(self)
  318. else:
  319. return MasterProfileHandler(self)
  320. def build_event_creation_handler(self):
  321. return EventCreationHandler(self)
  322. def build_deactivate_account_handler(self):
  323. return DeactivateAccountHandler(self)
  324. def build_set_password_handler(self):
  325. return SetPasswordHandler(self)
  326. def build_event_sources(self):
  327. return EventSources(self)
  328. def build_keyring(self):
  329. return Keyring(self)
  330. def build_event_builder_factory(self):
  331. return EventBuilderFactory(self)
  332. def build_filtering(self):
  333. return Filtering(self)
  334. def build_pusherpool(self):
  335. return PusherPool(self)
  336. def build_http_client(self):
  337. tls_client_options_factory = context_factory.ClientTLSOptionsFactory(
  338. self.config
  339. )
  340. return MatrixFederationHttpClient(self, tls_client_options_factory)
  341. def build_db_pool(self):
  342. name = self.db_config["name"]
  343. return adbapi.ConnectionPool(
  344. name, cp_reactor=self.get_reactor(), **self.db_config.get("args", {})
  345. )
  346. def get_db_conn(self, run_new_connection=True):
  347. """Makes a new connection to the database, skipping the db pool
  348. Returns:
  349. Connection: a connection object implementing the PEP-249 spec
  350. """
  351. # Any param beginning with cp_ is a parameter for adbapi, and should
  352. # not be passed to the database engine.
  353. db_params = {
  354. k: v
  355. for k, v in self.db_config.get("args", {}).items()
  356. if not k.startswith("cp_")
  357. }
  358. db_conn = self.database_engine.module.connect(**db_params)
  359. if run_new_connection:
  360. self.database_engine.on_new_connection(db_conn)
  361. return db_conn
  362. def build_media_repository_resource(self):
  363. # build the media repo resource. This indirects through the HomeServer
  364. # to ensure that we only have a single instance of
  365. return MediaRepositoryResource(self)
  366. def build_media_repository(self):
  367. return MediaRepository(self)
  368. def build_federation_transport_client(self):
  369. return TransportLayerClient(self)
  370. def build_federation_sender(self):
  371. if self.should_send_federation():
  372. return FederationSender(self)
  373. elif not self.config.worker_app:
  374. return FederationRemoteSendQueue(self)
  375. else:
  376. raise Exception("Workers cannot send federation traffic")
  377. def build_receipts_handler(self):
  378. return ReceiptsHandler(self)
  379. def build_read_marker_handler(self):
  380. return ReadMarkerHandler(self)
  381. def build_tcp_replication(self):
  382. raise NotImplementedError()
  383. def build_action_generator(self):
  384. return ActionGenerator(self)
  385. def build_user_directory_handler(self):
  386. return UserDirectoryHandler(self)
  387. def build_groups_local_handler(self):
  388. return GroupsLocalHandler(self)
  389. def build_groups_server_handler(self):
  390. return GroupsServerHandler(self)
  391. def build_groups_attestation_signing(self):
  392. return GroupAttestationSigning(self)
  393. def build_groups_attestation_renewer(self):
  394. return GroupAttestionRenewer(self)
  395. def build_secrets(self):
  396. return Secrets()
  397. def build_stats_handler(self):
  398. return StatsHandler(self)
  399. def build_spam_checker(self):
  400. return SpamChecker(self)
  401. def build_third_party_event_rules(self):
  402. return ThirdPartyEventRules(self)
  403. def build_room_member_handler(self):
  404. if self.config.worker_app:
  405. return RoomMemberWorkerHandler(self)
  406. return RoomMemberMasterHandler(self)
  407. def build_federation_registry(self):
  408. if self.config.worker_app:
  409. return ReplicationFederationHandlerRegistry(self)
  410. else:
  411. return FederationHandlerRegistry()
  412. def build_server_notices_manager(self):
  413. if self.config.worker_app:
  414. raise Exception("Workers cannot send server notices")
  415. return ServerNoticesManager(self)
  416. def build_server_notices_sender(self):
  417. if self.config.worker_app:
  418. return WorkerServerNoticesSender(self)
  419. return ServerNoticesSender(self)
  420. def build_message_handler(self):
  421. return MessageHandler(self)
  422. def build_pagination_handler(self):
  423. return PaginationHandler(self)
  424. def build_room_context_handler(self):
  425. return RoomContextHandler(self)
  426. def build_registration_handler(self):
  427. return RegistrationHandler(self)
  428. def build_account_validity_handler(self):
  429. return AccountValidityHandler(self)
  430. def build_saml_handler(self):
  431. from synapse.handlers.saml_handler import SamlHandler
  432. return SamlHandler(self)
  433. def build_event_client_serializer(self):
  434. return EventClientSerializer(self)
  435. def remove_pusher(self, app_id, push_key, user_id):
  436. return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
  437. def should_send_federation(self):
  438. "Should this server be sending federation traffic directly?"
  439. return self.config.send_federation and (
  440. not self.config.worker_app
  441. or self.config.worker_app == "synapse.app.federation_sender"
  442. )
  443. def _make_dependency_method(depname):
  444. def _get(hs):
  445. try:
  446. return getattr(hs, depname)
  447. except AttributeError:
  448. pass
  449. try:
  450. builder = getattr(hs, "build_%s" % (depname))
  451. except AttributeError:
  452. builder = None
  453. if builder:
  454. # Prevent cyclic dependencies from deadlocking
  455. if depname in hs._building:
  456. raise ValueError("Cyclic dependency while building %s" % (depname,))
  457. hs._building[depname] = 1
  458. dep = builder()
  459. setattr(hs, depname, dep)
  460. del hs._building[depname]
  461. return dep
  462. raise NotImplementedError(
  463. "%s has no %s nor a builder for it" % (type(hs).__name__, depname)
  464. )
  465. setattr(HomeServer, "get_%s" % (depname), _get)
  466. # Build magic accessors for every dependency
  467. for depname in HomeServer.DEPENDENCIES:
  468. _make_dependency_method(depname)