homeserver.py 17 KB

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