Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

641 Zeilen
21 KiB

  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. import os
  24. from twisted.mail.smtp import sendmail
  25. from synapse.api.auth import Auth
  26. from synapse.api.filtering import Filtering
  27. from synapse.api.ratelimiting import Ratelimiter
  28. from synapse.appservice.api import ApplicationServiceApi
  29. from synapse.appservice.scheduler import ApplicationServiceScheduler
  30. from synapse.config.homeserver import HomeServerConfig
  31. from synapse.crypto import context_factory
  32. from synapse.crypto.context_factory import RegularPolicyForHTTPS
  33. from synapse.crypto.keyring import Keyring
  34. from synapse.events.builder import EventBuilderFactory
  35. from synapse.events.spamcheck import SpamChecker
  36. from synapse.events.third_party_rules import ThirdPartyEventRules
  37. from synapse.events.utils import EventClientSerializer
  38. from synapse.federation.federation_client import FederationClient
  39. from synapse.federation.federation_server import (
  40. FederationHandlerRegistry,
  41. FederationServer,
  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, GroupsServerWorkerHandler
  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.cas_handler import CasHandler
  54. from synapse.handlers.deactivate_account import DeactivateAccountHandler
  55. from synapse.handlers.device import DeviceHandler, DeviceWorkerHandler
  56. from synapse.handlers.devicemessage import DeviceMessageHandler
  57. from synapse.handlers.e2e_keys import E2eKeysHandler
  58. from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
  59. from synapse.handlers.events import EventHandler, EventStreamHandler
  60. from synapse.handlers.groups_local import GroupsLocalHandler, GroupsLocalWorkerHandler
  61. from synapse.handlers.initial_sync import InitialSyncHandler
  62. from synapse.handlers.message import EventCreationHandler, MessageHandler
  63. from synapse.handlers.pagination import PaginationHandler
  64. from synapse.handlers.password_policy import PasswordPolicyHandler
  65. from synapse.handlers.presence import PresenceHandler
  66. from synapse.handlers.profile import BaseProfileHandler, MasterProfileHandler
  67. from synapse.handlers.read_marker import ReadMarkerHandler
  68. from synapse.handlers.receipts import ReceiptsHandler
  69. from synapse.handlers.register import RegistrationHandler
  70. from synapse.handlers.room import (
  71. RoomContextHandler,
  72. RoomCreationHandler,
  73. RoomShutdownHandler,
  74. )
  75. from synapse.handlers.room_list import RoomListHandler
  76. from synapse.handlers.room_member import RoomMemberMasterHandler
  77. from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
  78. from synapse.handlers.set_password import SetPasswordHandler
  79. from synapse.handlers.stats import StatsHandler
  80. from synapse.handlers.sync import SyncHandler
  81. from synapse.handlers.typing import FollowerTypingHandler, TypingWriterHandler
  82. from synapse.handlers.user_directory import UserDirectoryHandler
  83. from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
  84. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  85. from synapse.notifier import Notifier
  86. from synapse.push.action_generator import ActionGenerator
  87. from synapse.push.pusherpool import PusherPool
  88. from synapse.replication.tcp.client import ReplicationDataHandler
  89. from synapse.replication.tcp.handler import ReplicationCommandHandler
  90. from synapse.replication.tcp.resource import ReplicationStreamer
  91. from synapse.replication.tcp.streams import STREAMS_MAP
  92. from synapse.rest.media.v1.media_repository import (
  93. MediaRepository,
  94. MediaRepositoryResource,
  95. )
  96. from synapse.secrets import Secrets
  97. from synapse.server_notices.server_notices_manager import ServerNoticesManager
  98. from synapse.server_notices.server_notices_sender import ServerNoticesSender
  99. from synapse.server_notices.worker_server_notices_sender import (
  100. WorkerServerNoticesSender,
  101. )
  102. from synapse.state import StateHandler, StateResolutionHandler
  103. from synapse.storage import Databases, DataStore, Storage
  104. from synapse.streams.events import EventSources
  105. from synapse.util import Clock
  106. from synapse.util.distributor import Distributor
  107. from synapse.util.stringutils import random_string
  108. logger = logging.getLogger(__name__)
  109. class HomeServer(object):
  110. """A basic homeserver object without lazy component builders.
  111. This will need all of the components it requires to either be passed as
  112. constructor arguments, or the relevant methods overriding to create them.
  113. Typically this would only be used for unit tests.
  114. For every dependency in the DEPENDENCIES list below, this class creates one
  115. method,
  116. def get_DEPENDENCY(self)
  117. which returns the value of that dependency. If no value has yet been set
  118. nor was provided to the constructor, it will attempt to call a lazy builder
  119. method called
  120. def build_DEPENDENCY(self)
  121. which must be implemented by the subclass. This code may call any of the
  122. required "get" methods on the instance to obtain the sub-dependencies that
  123. one requires.
  124. Attributes:
  125. config (synapse.config.homeserver.HomeserverConfig):
  126. _listening_services (list[twisted.internet.tcp.Port]): TCP ports that
  127. we are listening on to provide HTTP services.
  128. """
  129. __metaclass__ = abc.ABCMeta
  130. DEPENDENCIES = [
  131. "http_client",
  132. "federation_client",
  133. "federation_server",
  134. "handlers",
  135. "auth",
  136. "room_creation_handler",
  137. "room_shutdown_handler",
  138. "state_handler",
  139. "state_resolution_handler",
  140. "presence_handler",
  141. "sync_handler",
  142. "typing_handler",
  143. "room_list_handler",
  144. "acme_handler",
  145. "auth_handler",
  146. "device_handler",
  147. "stats_handler",
  148. "e2e_keys_handler",
  149. "e2e_room_keys_handler",
  150. "event_handler",
  151. "event_stream_handler",
  152. "initial_sync_handler",
  153. "application_service_api",
  154. "application_service_scheduler",
  155. "application_service_handler",
  156. "device_message_handler",
  157. "profile_handler",
  158. "event_creation_handler",
  159. "deactivate_account_handler",
  160. "set_password_handler",
  161. "notifier",
  162. "event_sources",
  163. "keyring",
  164. "pusherpool",
  165. "event_builder_factory",
  166. "filtering",
  167. "http_client_context_factory",
  168. "simple_http_client",
  169. "proxied_http_client",
  170. "media_repository",
  171. "media_repository_resource",
  172. "federation_transport_client",
  173. "federation_sender",
  174. "receipts_handler",
  175. "macaroon_generator",
  176. "tcp_replication",
  177. "read_marker_handler",
  178. "action_generator",
  179. "user_directory_handler",
  180. "groups_local_handler",
  181. "groups_server_handler",
  182. "groups_attestation_signing",
  183. "groups_attestation_renewer",
  184. "secrets",
  185. "spam_checker",
  186. "third_party_event_rules",
  187. "room_member_handler",
  188. "federation_registry",
  189. "server_notices_manager",
  190. "server_notices_sender",
  191. "message_handler",
  192. "pagination_handler",
  193. "room_context_handler",
  194. "sendmail",
  195. "registration_handler",
  196. "account_validity_handler",
  197. "cas_handler",
  198. "saml_handler",
  199. "oidc_handler",
  200. "event_client_serializer",
  201. "password_policy_handler",
  202. "storage",
  203. "replication_streamer",
  204. "replication_data_handler",
  205. "replication_streams",
  206. ]
  207. REQUIRED_ON_MASTER_STARTUP = ["user_directory_handler", "stats_handler"]
  208. # This is overridden in derived application classes
  209. # (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
  210. # instantiated during setup() for future return by get_datastore()
  211. DATASTORE_CLASS = abc.abstractproperty()
  212. def __init__(self, hostname: str, config: HomeServerConfig, reactor=None, **kwargs):
  213. """
  214. Args:
  215. hostname : The hostname for the server.
  216. config: The full config for the homeserver.
  217. """
  218. if not reactor:
  219. from twisted.internet import reactor
  220. self._reactor = reactor
  221. self.hostname = hostname
  222. # the key we use to sign events and requests
  223. self.signing_key = config.key.signing_key[0]
  224. self.config = config
  225. self._building = {}
  226. self._listening_services = []
  227. self.start_time = None
  228. self._instance_id = random_string(5)
  229. self._instance_name = config.worker_name or "master"
  230. self.clock = Clock(reactor)
  231. self.distributor = Distributor()
  232. self.registration_ratelimiter = Ratelimiter(
  233. clock=self.clock,
  234. rate_hz=config.rc_registration.per_second,
  235. burst_count=config.rc_registration.burst_count,
  236. )
  237. self.datastores = None
  238. # Other kwargs are explicit dependencies
  239. for depname in kwargs:
  240. setattr(self, depname, kwargs[depname])
  241. def get_instance_id(self):
  242. """A unique ID for this synapse process instance.
  243. This is used to distinguish running instances in worker-based
  244. deployments.
  245. """
  246. return self._instance_id
  247. def get_instance_name(self) -> str:
  248. """A unique name for this synapse process.
  249. Used to identify the process over replication and in config. Does not
  250. change over restarts.
  251. """
  252. return self._instance_name
  253. def setup(self):
  254. logger.info("Setting up.")
  255. self.start_time = int(self.get_clock().time())
  256. self.datastores = Databases(self.DATASTORE_CLASS, self)
  257. logger.info("Finished setting up.")
  258. def setup_master(self):
  259. """
  260. Some handlers have side effects on instantiation (like registering
  261. background updates). This function causes them to be fetched, and
  262. therefore instantiated, to run those side effects.
  263. """
  264. for i in self.REQUIRED_ON_MASTER_STARTUP:
  265. getattr(self, "get_" + i)()
  266. def get_reactor(self):
  267. """
  268. Fetch the Twisted reactor in use by this HomeServer.
  269. """
  270. return self._reactor
  271. def get_ip_from_request(self, request):
  272. # X-Forwarded-For is handled by our custom request type.
  273. return request.getClientIP()
  274. def is_mine(self, domain_specific_string):
  275. return domain_specific_string.domain == self.hostname
  276. def is_mine_id(self, string):
  277. return string.split(":", 1)[1] == self.hostname
  278. def get_clock(self):
  279. return self.clock
  280. def get_datastore(self) -> DataStore:
  281. return self.datastores.main
  282. def get_datastores(self):
  283. return self.datastores
  284. def get_config(self):
  285. return self.config
  286. def get_distributor(self):
  287. return self.distributor
  288. def get_registration_ratelimiter(self) -> Ratelimiter:
  289. return self.registration_ratelimiter
  290. def build_federation_client(self):
  291. return FederationClient(self)
  292. def build_federation_server(self):
  293. return FederationServer(self)
  294. def build_handlers(self):
  295. return Handlers(self)
  296. def build_notifier(self):
  297. return Notifier(self)
  298. def build_auth(self):
  299. return Auth(self)
  300. def build_http_client_context_factory(self):
  301. return (
  302. InsecureInterceptableContextFactory()
  303. if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
  304. else RegularPolicyForHTTPS()
  305. )
  306. def build_simple_http_client(self):
  307. return SimpleHttpClient(self)
  308. def build_proxied_http_client(self):
  309. return SimpleHttpClient(
  310. self,
  311. http_proxy=os.getenvb(b"http_proxy"),
  312. https_proxy=os.getenvb(b"HTTPS_PROXY"),
  313. )
  314. def build_room_creation_handler(self):
  315. return RoomCreationHandler(self)
  316. def build_room_shutdown_handler(self):
  317. return RoomShutdownHandler(self)
  318. def build_sendmail(self):
  319. return sendmail
  320. def build_state_handler(self):
  321. return StateHandler(self)
  322. def build_state_resolution_handler(self):
  323. return StateResolutionHandler(self)
  324. def build_presence_handler(self):
  325. return PresenceHandler(self)
  326. def build_typing_handler(self):
  327. if self.config.worker.writers.typing == self.get_instance_name():
  328. return TypingWriterHandler(self)
  329. else:
  330. return FollowerTypingHandler(self)
  331. def build_sync_handler(self):
  332. return SyncHandler(self)
  333. def build_room_list_handler(self):
  334. return RoomListHandler(self)
  335. def build_auth_handler(self):
  336. return AuthHandler(self)
  337. def build_macaroon_generator(self):
  338. return MacaroonGenerator(self)
  339. def build_device_handler(self):
  340. if self.config.worker_app:
  341. return DeviceWorkerHandler(self)
  342. else:
  343. return DeviceHandler(self)
  344. def build_device_message_handler(self):
  345. return DeviceMessageHandler(self)
  346. def build_e2e_keys_handler(self):
  347. return E2eKeysHandler(self)
  348. def build_e2e_room_keys_handler(self):
  349. return E2eRoomKeysHandler(self)
  350. def build_acme_handler(self):
  351. return AcmeHandler(self)
  352. def build_application_service_api(self):
  353. return ApplicationServiceApi(self)
  354. def build_application_service_scheduler(self):
  355. return ApplicationServiceScheduler(self)
  356. def build_application_service_handler(self):
  357. return ApplicationServicesHandler(self)
  358. def build_event_handler(self):
  359. return EventHandler(self)
  360. def build_event_stream_handler(self):
  361. return EventStreamHandler(self)
  362. def build_initial_sync_handler(self):
  363. return InitialSyncHandler(self)
  364. def build_profile_handler(self):
  365. if self.config.worker_app:
  366. return BaseProfileHandler(self)
  367. else:
  368. return MasterProfileHandler(self)
  369. def build_event_creation_handler(self):
  370. return EventCreationHandler(self)
  371. def build_deactivate_account_handler(self):
  372. return DeactivateAccountHandler(self)
  373. def build_set_password_handler(self):
  374. return SetPasswordHandler(self)
  375. def build_event_sources(self):
  376. return EventSources(self)
  377. def build_keyring(self):
  378. return Keyring(self)
  379. def build_event_builder_factory(self):
  380. return EventBuilderFactory(self)
  381. def build_filtering(self):
  382. return Filtering(self)
  383. def build_pusherpool(self):
  384. return PusherPool(self)
  385. def build_http_client(self):
  386. tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
  387. self.config
  388. )
  389. return MatrixFederationHttpClient(self, tls_client_options_factory)
  390. def build_media_repository_resource(self):
  391. # build the media repo resource. This indirects through the HomeServer
  392. # to ensure that we only have a single instance of
  393. return MediaRepositoryResource(self)
  394. def build_media_repository(self):
  395. return MediaRepository(self)
  396. def build_federation_transport_client(self):
  397. return TransportLayerClient(self)
  398. def build_federation_sender(self):
  399. if self.should_send_federation():
  400. return FederationSender(self)
  401. elif not self.config.worker_app:
  402. return FederationRemoteSendQueue(self)
  403. else:
  404. raise Exception("Workers cannot send federation traffic")
  405. def build_receipts_handler(self):
  406. return ReceiptsHandler(self)
  407. def build_read_marker_handler(self):
  408. return ReadMarkerHandler(self)
  409. def build_tcp_replication(self):
  410. return ReplicationCommandHandler(self)
  411. def build_action_generator(self):
  412. return ActionGenerator(self)
  413. def build_user_directory_handler(self):
  414. return UserDirectoryHandler(self)
  415. def build_groups_local_handler(self):
  416. if self.config.worker_app:
  417. return GroupsLocalWorkerHandler(self)
  418. else:
  419. return GroupsLocalHandler(self)
  420. def build_groups_server_handler(self):
  421. if self.config.worker_app:
  422. return GroupsServerWorkerHandler(self)
  423. else:
  424. return GroupsServerHandler(self)
  425. def build_groups_attestation_signing(self):
  426. return GroupAttestationSigning(self)
  427. def build_groups_attestation_renewer(self):
  428. return GroupAttestionRenewer(self)
  429. def build_secrets(self):
  430. return Secrets()
  431. def build_stats_handler(self):
  432. return StatsHandler(self)
  433. def build_spam_checker(self):
  434. return SpamChecker(self)
  435. def build_third_party_event_rules(self):
  436. return ThirdPartyEventRules(self)
  437. def build_room_member_handler(self):
  438. if self.config.worker_app:
  439. return RoomMemberWorkerHandler(self)
  440. return RoomMemberMasterHandler(self)
  441. def build_federation_registry(self):
  442. return FederationHandlerRegistry(self)
  443. def build_server_notices_manager(self):
  444. if self.config.worker_app:
  445. raise Exception("Workers cannot send server notices")
  446. return ServerNoticesManager(self)
  447. def build_server_notices_sender(self):
  448. if self.config.worker_app:
  449. return WorkerServerNoticesSender(self)
  450. return ServerNoticesSender(self)
  451. def build_message_handler(self):
  452. return MessageHandler(self)
  453. def build_pagination_handler(self):
  454. return PaginationHandler(self)
  455. def build_room_context_handler(self):
  456. return RoomContextHandler(self)
  457. def build_registration_handler(self):
  458. return RegistrationHandler(self)
  459. def build_account_validity_handler(self):
  460. return AccountValidityHandler(self)
  461. def build_cas_handler(self):
  462. return CasHandler(self)
  463. def build_saml_handler(self):
  464. from synapse.handlers.saml_handler import SamlHandler
  465. return SamlHandler(self)
  466. def build_oidc_handler(self):
  467. from synapse.handlers.oidc_handler import OidcHandler
  468. return OidcHandler(self)
  469. def build_event_client_serializer(self):
  470. return EventClientSerializer(self)
  471. def build_password_policy_handler(self):
  472. return PasswordPolicyHandler(self)
  473. def build_storage(self) -> Storage:
  474. return Storage(self, self.datastores)
  475. def build_replication_streamer(self) -> ReplicationStreamer:
  476. return ReplicationStreamer(self)
  477. def build_replication_data_handler(self):
  478. return ReplicationDataHandler(self)
  479. def build_replication_streams(self):
  480. return {stream.NAME: stream(self) for stream in STREAMS_MAP.values()}
  481. def remove_pusher(self, app_id, push_key, user_id):
  482. return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
  483. def should_send_federation(self):
  484. "Should this server be sending federation traffic directly?"
  485. return self.config.send_federation and (
  486. not self.config.worker_app
  487. or self.config.worker_app == "synapse.app.federation_sender"
  488. )
  489. def _make_dependency_method(depname):
  490. def _get(hs):
  491. try:
  492. return getattr(hs, depname)
  493. except AttributeError:
  494. pass
  495. try:
  496. builder = getattr(hs, "build_%s" % (depname))
  497. except AttributeError:
  498. raise NotImplementedError(
  499. "%s has no %s nor a builder for it" % (type(hs).__name__, depname)
  500. )
  501. # Prevent cyclic dependencies from deadlocking
  502. if depname in hs._building:
  503. raise ValueError("Cyclic dependency while building %s" % (depname,))
  504. hs._building[depname] = 1
  505. try:
  506. dep = builder()
  507. setattr(hs, depname, dep)
  508. finally:
  509. del hs._building[depname]
  510. return dep
  511. setattr(HomeServer, "get_%s" % (depname), _get)
  512. # Build magic accessors for every dependency
  513. for depname in HomeServer.DEPENDENCIES:
  514. _make_dependency_method(depname)