You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

502 lines
18 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2019 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import os
  18. import sys
  19. from typing import Iterable, Iterator
  20. from twisted.internet import reactor
  21. from twisted.web.resource import EncodingResourceWrapper, IResource
  22. from twisted.web.server import GzipEncoderFactory
  23. from twisted.web.static import File
  24. import synapse
  25. import synapse.config.logger
  26. from synapse import events
  27. from synapse.api.urls import (
  28. FEDERATION_PREFIX,
  29. LEGACY_MEDIA_PREFIX,
  30. MEDIA_PREFIX,
  31. SERVER_KEY_V2_PREFIX,
  32. STATIC_PREFIX,
  33. WEB_CLIENT_PREFIX,
  34. )
  35. from synapse.app import _base
  36. from synapse.app._base import listen_ssl, listen_tcp, quit_with_error, register_start
  37. from synapse.config._base import ConfigError
  38. from synapse.config.emailconfig import ThreepidBehaviour
  39. from synapse.config.homeserver import HomeServerConfig
  40. from synapse.config.server import ListenerConfig
  41. from synapse.federation.transport.server import TransportLayerServer
  42. from synapse.http.additional_resource import AdditionalResource
  43. from synapse.http.server import (
  44. OptionsResource,
  45. RootOptionsRedirectResource,
  46. RootRedirect,
  47. StaticResource,
  48. )
  49. from synapse.http.site import SynapseSite
  50. from synapse.logging.context import LoggingContext
  51. from synapse.metrics import METRICS_PREFIX, MetricsResource, RegistryProxy
  52. from synapse.python_dependencies import check_requirements
  53. from synapse.replication.http import REPLICATION_PREFIX, ReplicationRestResource
  54. from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
  55. from synapse.rest import ClientRestResource
  56. from synapse.rest.admin import AdminRestResource
  57. from synapse.rest.health import HealthResource
  58. from synapse.rest.key.v2 import KeyApiV2Resource
  59. from synapse.rest.synapse.client import build_synapse_client_resource_tree
  60. from synapse.rest.well_known import WellKnownResource
  61. from synapse.server import HomeServer
  62. from synapse.storage import DataStore
  63. from synapse.storage.engines import IncorrectDatabaseSetup
  64. from synapse.storage.prepare_database import UpgradeDatabaseException
  65. from synapse.util.httpresourcetree import create_resource_tree
  66. from synapse.util.module_loader import load_module
  67. from synapse.util.versionstring import get_version_string
  68. logger = logging.getLogger("synapse.app.homeserver")
  69. def gz_wrap(r):
  70. return EncodingResourceWrapper(r, [GzipEncoderFactory()])
  71. class SynapseHomeServer(HomeServer):
  72. DATASTORE_CLASS = DataStore
  73. def _listener_http(self, config: HomeServerConfig, listener_config: ListenerConfig):
  74. port = listener_config.port
  75. bind_addresses = listener_config.bind_addresses
  76. tls = listener_config.tls
  77. site_tag = listener_config.http_options.tag
  78. if site_tag is None:
  79. site_tag = str(port)
  80. # We always include a health resource.
  81. resources = {"/health": HealthResource()}
  82. for res in listener_config.http_options.resources:
  83. for name in res.names:
  84. if name == "openid" and "federation" in res.names:
  85. # Skip loading openid resource if federation is defined
  86. # since federation resource will include openid
  87. continue
  88. resources.update(self._configure_named_resource(name, res.compress))
  89. additional_resources = listener_config.http_options.additional_resources
  90. logger.debug("Configuring additional resources: %r", additional_resources)
  91. module_api = self.get_module_api()
  92. for path, resmodule in additional_resources.items():
  93. handler_cls, config = load_module(
  94. resmodule,
  95. ("listeners", site_tag, "additional_resources", "<%s>" % (path,)),
  96. )
  97. handler = handler_cls(config, module_api)
  98. if IResource.providedBy(handler):
  99. resource = handler
  100. elif hasattr(handler, "handle_request"):
  101. resource = AdditionalResource(self, handler.handle_request)
  102. else:
  103. raise ConfigError(
  104. "additional_resource %s does not implement a known interface"
  105. % (resmodule["module"],)
  106. )
  107. resources[path] = resource
  108. # try to find something useful to redirect '/' to
  109. if WEB_CLIENT_PREFIX in resources:
  110. root_resource = RootOptionsRedirectResource(WEB_CLIENT_PREFIX)
  111. elif STATIC_PREFIX in resources:
  112. root_resource = RootOptionsRedirectResource(STATIC_PREFIX)
  113. else:
  114. root_resource = OptionsResource()
  115. root_resource = create_resource_tree(resources, root_resource)
  116. if tls:
  117. ports = listen_ssl(
  118. bind_addresses,
  119. port,
  120. SynapseSite(
  121. "synapse.access.https.%s" % (site_tag,),
  122. site_tag,
  123. listener_config,
  124. root_resource,
  125. self.version_string,
  126. ),
  127. self.tls_server_context_factory,
  128. reactor=self.get_reactor(),
  129. )
  130. logger.info("Synapse now listening on TCP port %d (TLS)", port)
  131. else:
  132. ports = listen_tcp(
  133. bind_addresses,
  134. port,
  135. SynapseSite(
  136. "synapse.access.http.%s" % (site_tag,),
  137. site_tag,
  138. listener_config,
  139. root_resource,
  140. self.version_string,
  141. ),
  142. reactor=self.get_reactor(),
  143. )
  144. logger.info("Synapse now listening on TCP port %d", port)
  145. return ports
  146. def _configure_named_resource(self, name, compress=False):
  147. """Build a resource map for a named resource
  148. Args:
  149. name (str): named resource: one of "client", "federation", etc
  150. compress (bool): whether to enable gzip compression for this
  151. resource
  152. Returns:
  153. dict[str, Resource]: map from path to HTTP resource
  154. """
  155. resources = {}
  156. if name == "client":
  157. client_resource = ClientRestResource(self)
  158. if compress:
  159. client_resource = gz_wrap(client_resource)
  160. resources.update(
  161. {
  162. "/_matrix/client/api/v1": client_resource,
  163. "/_matrix/client/r0": client_resource,
  164. "/_matrix/client/unstable": client_resource,
  165. "/_matrix/client/v2_alpha": client_resource,
  166. "/_matrix/client/versions": client_resource,
  167. "/.well-known/matrix/client": WellKnownResource(self),
  168. "/_synapse/admin": AdminRestResource(self),
  169. **build_synapse_client_resource_tree(self),
  170. }
  171. )
  172. if self.get_config().threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  173. from synapse.rest.synapse.client.password_reset import (
  174. PasswordResetSubmitTokenResource,
  175. )
  176. resources[
  177. "/_synapse/client/password_reset/email/submit_token"
  178. ] = PasswordResetSubmitTokenResource(self)
  179. if name == "consent":
  180. from synapse.rest.consent.consent_resource import ConsentResource
  181. consent_resource = ConsentResource(self)
  182. if compress:
  183. consent_resource = gz_wrap(consent_resource)
  184. resources.update({"/_matrix/consent": consent_resource})
  185. if name == "federation":
  186. resources.update({FEDERATION_PREFIX: TransportLayerServer(self)})
  187. if name == "openid":
  188. resources.update(
  189. {
  190. FEDERATION_PREFIX: TransportLayerServer(
  191. self, servlet_groups=["openid"]
  192. )
  193. }
  194. )
  195. if name in ["static", "client"]:
  196. resources.update(
  197. {
  198. STATIC_PREFIX: StaticResource(
  199. os.path.join(os.path.dirname(synapse.__file__), "static")
  200. )
  201. }
  202. )
  203. if name in ["media", "federation", "client"]:
  204. if self.get_config().enable_media_repo:
  205. media_repo = self.get_media_repository_resource()
  206. resources.update(
  207. {MEDIA_PREFIX: media_repo, LEGACY_MEDIA_PREFIX: media_repo}
  208. )
  209. elif name == "media":
  210. raise ConfigError(
  211. "'media' resource conflicts with enable_media_repo=False"
  212. )
  213. if name in ["keys", "federation"]:
  214. resources[SERVER_KEY_V2_PREFIX] = KeyApiV2Resource(self)
  215. if name == "webclient":
  216. webclient_loc = self.get_config().web_client_location
  217. if webclient_loc is None:
  218. logger.warning(
  219. "Not enabling webclient resource, as web_client_location is unset."
  220. )
  221. elif webclient_loc.startswith("http://") or webclient_loc.startswith(
  222. "https://"
  223. ):
  224. resources[WEB_CLIENT_PREFIX] = RootRedirect(webclient_loc)
  225. else:
  226. logger.warning(
  227. "Running webclient on the same domain is not recommended: "
  228. "https://github.com/matrix-org/synapse#security-note - "
  229. "after you move webclient to different host you can set "
  230. "web_client_location to its full URL to enable redirection."
  231. )
  232. # GZip is disabled here due to
  233. # https://twistedmatrix.com/trac/ticket/7678
  234. resources[WEB_CLIENT_PREFIX] = File(webclient_loc)
  235. if name == "metrics" and self.get_config().enable_metrics:
  236. resources[METRICS_PREFIX] = MetricsResource(RegistryProxy)
  237. if name == "replication":
  238. resources[REPLICATION_PREFIX] = ReplicationRestResource(self)
  239. return resources
  240. def start_listening(self, listeners: Iterable[ListenerConfig]):
  241. config = self.get_config()
  242. if config.redis_enabled:
  243. # If redis is enabled we connect via the replication command handler
  244. # in the same way as the workers (since we're effectively a client
  245. # rather than a server).
  246. self.get_tcp_replication().start_replication(self)
  247. for listener in listeners:
  248. if listener.type == "http":
  249. self._listening_services.extend(self._listener_http(config, listener))
  250. elif listener.type == "manhole":
  251. _base.listen_manhole(
  252. listener.bind_addresses, listener.port, manhole_globals={"hs": self}
  253. )
  254. elif listener.type == "replication":
  255. services = listen_tcp(
  256. listener.bind_addresses,
  257. listener.port,
  258. ReplicationStreamProtocolFactory(self),
  259. )
  260. for s in services:
  261. reactor.addSystemEventTrigger("before", "shutdown", s.stopListening)
  262. elif listener.type == "metrics":
  263. if not self.get_config().enable_metrics:
  264. logger.warning(
  265. (
  266. "Metrics listener configured, but "
  267. "enable_metrics is not True!"
  268. )
  269. )
  270. else:
  271. _base.listen_metrics(listener.bind_addresses, listener.port)
  272. else:
  273. # this shouldn't happen, as the listener type should have been checked
  274. # during parsing
  275. logger.warning("Unrecognized listener type: %s", listener.type)
  276. def setup(config_options):
  277. """
  278. Args:
  279. config_options_options: The options passed to Synapse. Usually
  280. `sys.argv[1:]`.
  281. Returns:
  282. HomeServer
  283. """
  284. try:
  285. config = HomeServerConfig.load_or_generate_config(
  286. "Synapse Homeserver", config_options
  287. )
  288. except ConfigError as e:
  289. sys.stderr.write("\n")
  290. for f in format_config_error(e):
  291. sys.stderr.write(f)
  292. sys.stderr.write("\n")
  293. sys.exit(1)
  294. if not config:
  295. # If a config isn't returned, and an exception isn't raised, we're just
  296. # generating config files and shouldn't try to continue.
  297. sys.exit(0)
  298. events.USE_FROZEN_DICTS = config.use_frozen_dicts
  299. hs = SynapseHomeServer(
  300. config.server_name,
  301. config=config,
  302. version_string="Synapse/" + get_version_string(synapse),
  303. )
  304. synapse.config.logger.setup_logging(hs, config, use_worker_options=False)
  305. logger.info("Setting up server")
  306. try:
  307. hs.setup()
  308. except IncorrectDatabaseSetup as e:
  309. quit_with_error(str(e))
  310. except UpgradeDatabaseException as e:
  311. quit_with_error("Failed to upgrade database: %s" % (e,))
  312. async def do_acme() -> bool:
  313. """
  314. Reprovision an ACME certificate, if it's required.
  315. Returns:
  316. Whether the cert has been updated.
  317. """
  318. acme = hs.get_acme_handler()
  319. # Check how long the certificate is active for.
  320. cert_days_remaining = hs.config.is_disk_cert_valid(allow_self_signed=False)
  321. # We want to reprovision if cert_days_remaining is None (meaning no
  322. # certificate exists), or the days remaining number it returns
  323. # is less than our re-registration threshold.
  324. provision = False
  325. if (
  326. cert_days_remaining is None
  327. or cert_days_remaining < hs.config.acme_reprovision_threshold
  328. ):
  329. provision = True
  330. if provision:
  331. await acme.provision_certificate()
  332. return provision
  333. async def reprovision_acme():
  334. """
  335. Provision a certificate from ACME, if required, and reload the TLS
  336. certificate if it's renewed.
  337. """
  338. reprovisioned = await do_acme()
  339. if reprovisioned:
  340. _base.refresh_certificate(hs)
  341. async def start():
  342. # Run the ACME provisioning code, if it's enabled.
  343. if hs.config.acme_enabled:
  344. acme = hs.get_acme_handler()
  345. # Start up the webservices which we will respond to ACME
  346. # challenges with, and then provision.
  347. await acme.start_listening()
  348. await do_acme()
  349. # Check if it needs to be reprovisioned every day.
  350. hs.get_clock().looping_call(reprovision_acme, 24 * 60 * 60 * 1000)
  351. # Load the OIDC provider metadatas, if OIDC is enabled.
  352. if hs.config.oidc_enabled:
  353. oidc = hs.get_oidc_handler()
  354. # Loading the provider metadata also ensures the provider config is valid.
  355. await oidc.load_metadata()
  356. await _base.start(hs, config.listeners)
  357. hs.get_datastore().db_pool.updates.start_doing_background_updates()
  358. register_start(start)
  359. return hs
  360. def format_config_error(e: ConfigError) -> Iterator[str]:
  361. """
  362. Formats a config error neatly
  363. The idea is to format the immediate error, plus the "causes" of those errors,
  364. hopefully in a way that makes sense to the user. For example:
  365. Error in configuration at 'oidc_config.user_mapping_provider.config.display_name_template':
  366. Failed to parse config for module 'JinjaOidcMappingProvider':
  367. invalid jinja template:
  368. unexpected end of template, expected 'end of print statement'.
  369. Args:
  370. e: the error to be formatted
  371. Returns: An iterator which yields string fragments to be formatted
  372. """
  373. yield "Error in configuration"
  374. if e.path:
  375. yield " at '%s'" % (".".join(e.path),)
  376. yield ":\n %s" % (e.msg,)
  377. e = e.__cause__
  378. indent = 1
  379. while e:
  380. indent += 1
  381. yield ":\n%s%s" % (" " * indent, str(e))
  382. e = e.__cause__
  383. def run(hs):
  384. PROFILE_SYNAPSE = False
  385. if PROFILE_SYNAPSE:
  386. def profile(func):
  387. from cProfile import Profile
  388. from threading import current_thread
  389. def profiled(*args, **kargs):
  390. profile = Profile()
  391. profile.enable()
  392. func(*args, **kargs)
  393. profile.disable()
  394. ident = current_thread().ident
  395. profile.dump_stats(
  396. "/tmp/%s.%s.%i.pstat" % (hs.hostname, func.__name__, ident)
  397. )
  398. return profiled
  399. from twisted.python.threadpool import ThreadPool
  400. ThreadPool._worker = profile(ThreadPool._worker)
  401. reactor.run = profile(reactor.run)
  402. _base.start_reactor(
  403. "synapse-homeserver",
  404. soft_file_limit=hs.config.soft_file_limit,
  405. gc_thresholds=hs.config.gc_thresholds,
  406. pid_file=hs.config.pid_file,
  407. daemonize=hs.config.daemonize,
  408. print_pidfile=hs.config.print_pidfile,
  409. logger=logger,
  410. )
  411. def main():
  412. with LoggingContext("main"):
  413. # check base requirements
  414. check_requirements()
  415. hs = setup(sys.argv[1:])
  416. run(hs)
  417. if __name__ == "__main__":
  418. main()