server.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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. import logging
  18. import os.path
  19. import re
  20. from textwrap import indent
  21. import attr
  22. import yaml
  23. from netaddr import IPSet
  24. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  25. from synapse.http.endpoint import parse_and_validate_server_name
  26. from synapse.python_dependencies import DependencyException, check_requirements
  27. from ._base import Config, ConfigError
  28. logger = logging.Logger(__name__)
  29. # by default, we attempt to listen on both '::' *and* '0.0.0.0' because some OSes
  30. # (Windows, macOS, other BSD/Linux where net.ipv6.bindv6only is set) will only listen
  31. # on IPv6 when '::' is set.
  32. #
  33. # We later check for errors when binding to 0.0.0.0 and ignore them if :: is also in
  34. # in the list.
  35. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
  36. DEFAULT_ROOM_VERSION = "4"
  37. ROOM_COMPLEXITY_TOO_GREAT = (
  38. "Your homeserver is unable to join rooms this large or complex. "
  39. "Please speak to your server administrator, or upgrade your instance "
  40. "to join this room."
  41. )
  42. class ServerConfig(Config):
  43. def read_config(self, config, **kwargs):
  44. self.server_name = config["server_name"]
  45. self.server_context = config.get("server_context", None)
  46. try:
  47. parse_and_validate_server_name(self.server_name)
  48. except ValueError as e:
  49. raise ConfigError(str(e))
  50. self.pid_file = self.abspath(config.get("pid_file"))
  51. self.web_client_location = config.get("web_client_location", None)
  52. self.soft_file_limit = config.get("soft_file_limit", 0)
  53. self.daemonize = config.get("daemonize")
  54. self.print_pidfile = config.get("print_pidfile")
  55. self.user_agent_suffix = config.get("user_agent_suffix")
  56. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  57. self.public_baseurl = config.get("public_baseurl")
  58. # Whether to send federation traffic out in this process. This only
  59. # applies to some federation traffic, and so shouldn't be used to
  60. # "disable" federation
  61. self.send_federation = config.get("send_federation", True)
  62. # Whether to enable user presence.
  63. self.use_presence = config.get("use_presence", True)
  64. # Whether to update the user directory or not. This should be set to
  65. # false only if we are updating the user directory in a worker
  66. self.update_user_directory = config.get("update_user_directory", True)
  67. # whether to enable the media repository endpoints. This should be set
  68. # to false if the media repository is running as a separate endpoint;
  69. # doing so ensures that we will not run cache cleanup jobs on the
  70. # master, potentially causing inconsistency.
  71. self.enable_media_repo = config.get("enable_media_repo", True)
  72. # Whether to require authentication to retrieve profile data (avatars,
  73. # display names) of other users through the client API.
  74. self.require_auth_for_profile_requests = config.get(
  75. "require_auth_for_profile_requests", False
  76. )
  77. if "restrict_public_rooms_to_local_users" in config and (
  78. "allow_public_rooms_without_auth" in config
  79. or "allow_public_rooms_over_federation" in config
  80. ):
  81. raise ConfigError(
  82. "Can't use 'restrict_public_rooms_to_local_users' if"
  83. " 'allow_public_rooms_without_auth' and/or"
  84. " 'allow_public_rooms_over_federation' is set."
  85. )
  86. # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This
  87. # flag is now obsolete but we need to check it for backward-compatibility.
  88. if config.get("restrict_public_rooms_to_local_users", False):
  89. self.allow_public_rooms_without_auth = False
  90. self.allow_public_rooms_over_federation = False
  91. else:
  92. # If set to 'False', requires authentication to access the server's public
  93. # rooms directory through the client API. Defaults to 'True'.
  94. self.allow_public_rooms_without_auth = config.get(
  95. "allow_public_rooms_without_auth", True
  96. )
  97. # If set to 'False', forbids any other homeserver to fetch the server's public
  98. # rooms directory via federation. Defaults to 'True'.
  99. self.allow_public_rooms_over_federation = config.get(
  100. "allow_public_rooms_over_federation", True
  101. )
  102. default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION)
  103. # Ensure room version is a str
  104. default_room_version = str(default_room_version)
  105. if default_room_version not in KNOWN_ROOM_VERSIONS:
  106. raise ConfigError(
  107. "Unknown default_room_version: %s, known room versions: %s"
  108. % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys()))
  109. )
  110. # Get the actual room version object rather than just the identifier
  111. self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version]
  112. # whether to enable search. If disabled, new entries will not be inserted
  113. # into the search tables and they will not be indexed. Users will receive
  114. # errors when attempting to search for messages.
  115. self.enable_search = config.get("enable_search", True)
  116. self.filter_timeline_limit = config.get("filter_timeline_limit", -1)
  117. # Whether we should block invites sent to users on this server
  118. # (other than those sent by local server admins)
  119. self.block_non_admin_invites = config.get("block_non_admin_invites", False)
  120. # Whether to enable experimental MSC1849 (aka relations) support
  121. self.experimental_msc1849_support_enabled = config.get(
  122. "experimental_msc1849_support_enabled", True
  123. )
  124. # Options to control access by tracking MAU
  125. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  126. self.max_mau_value = 0
  127. if self.limit_usage_by_mau:
  128. self.max_mau_value = config.get("max_mau_value", 0)
  129. self.mau_stats_only = config.get("mau_stats_only", False)
  130. self.mau_limits_reserved_threepids = config.get(
  131. "mau_limit_reserved_threepids", []
  132. )
  133. self.mau_trial_days = config.get("mau_trial_days", 0)
  134. # How long to keep redacted events in the database in unredacted form
  135. # before redacting them.
  136. redaction_retention_period = config.get("redaction_retention_period", "7d")
  137. if redaction_retention_period is not None:
  138. self.redaction_retention_period = self.parse_duration(
  139. redaction_retention_period
  140. )
  141. else:
  142. self.redaction_retention_period = None
  143. # Options to disable HS
  144. self.hs_disabled = config.get("hs_disabled", False)
  145. self.hs_disabled_message = config.get("hs_disabled_message", "")
  146. self.hs_disabled_limit_type = config.get("hs_disabled_limit_type", "")
  147. # Admin uri to direct users at should their instance become blocked
  148. # due to resource constraints
  149. self.admin_contact = config.get("admin_contact", None)
  150. # FIXME: federation_domain_whitelist needs sytests
  151. self.federation_domain_whitelist = None
  152. federation_domain_whitelist = config.get("federation_domain_whitelist", None)
  153. if federation_domain_whitelist is not None:
  154. # turn the whitelist into a hash for speed of lookup
  155. self.federation_domain_whitelist = {}
  156. for domain in federation_domain_whitelist:
  157. self.federation_domain_whitelist[domain] = True
  158. self.federation_ip_range_blacklist = config.get(
  159. "federation_ip_range_blacklist", []
  160. )
  161. # Attempt to create an IPSet from the given ranges
  162. try:
  163. self.federation_ip_range_blacklist = IPSet(
  164. self.federation_ip_range_blacklist
  165. )
  166. # Always blacklist 0.0.0.0, ::
  167. self.federation_ip_range_blacklist.update(["0.0.0.0", "::"])
  168. except Exception as e:
  169. raise ConfigError(
  170. "Invalid range(s) provided in " "federation_ip_range_blacklist: %s" % e
  171. )
  172. if self.public_baseurl is not None:
  173. if self.public_baseurl[-1] != "/":
  174. self.public_baseurl += "/"
  175. self.start_pushers = config.get("start_pushers", True)
  176. # (undocumented) option for torturing the worker-mode replication a bit,
  177. # for testing. The value defines the number of milliseconds to pause before
  178. # sending out any replication updates.
  179. self.replication_torture_level = config.get("replication_torture_level")
  180. # Whether to require a user to be in the room to add an alias to it.
  181. # Defaults to True.
  182. self.require_membership_for_aliases = config.get(
  183. "require_membership_for_aliases", True
  184. )
  185. # Whether to allow per-room membership profiles through the send of membership
  186. # events with profile information that differ from the target's global profile.
  187. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True)
  188. self.listeners = []
  189. for listener in config.get("listeners", []):
  190. if not isinstance(listener.get("port", None), int):
  191. raise ConfigError(
  192. "Listener configuration is lacking a valid 'port' option"
  193. )
  194. if listener.setdefault("tls", False):
  195. # no_tls is not really supported any more, but let's grandfather it in
  196. # here.
  197. if config.get("no_tls", False):
  198. logger.info(
  199. "Ignoring TLS-enabled listener on port %i due to no_tls"
  200. )
  201. continue
  202. bind_address = listener.pop("bind_address", None)
  203. bind_addresses = listener.setdefault("bind_addresses", [])
  204. # if bind_address was specified, add it to the list of addresses
  205. if bind_address:
  206. bind_addresses.append(bind_address)
  207. # if we still have an empty list of addresses, use the default list
  208. if not bind_addresses:
  209. if listener["type"] == "metrics":
  210. # the metrics listener doesn't support IPv6
  211. bind_addresses.append("0.0.0.0")
  212. else:
  213. bind_addresses.extend(DEFAULT_BIND_ADDRESSES)
  214. self.listeners.append(listener)
  215. if not self.web_client_location:
  216. _warn_if_webclient_configured(self.listeners)
  217. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  218. @attr.s
  219. class LimitRemoteRoomsConfig(object):
  220. enabled = attr.ib(
  221. validator=attr.validators.instance_of(bool), default=False
  222. )
  223. complexity = attr.ib(
  224. validator=attr.validators.instance_of((int, float)), default=1.0
  225. )
  226. complexity_error = attr.ib(
  227. validator=attr.validators.instance_of(str),
  228. default=ROOM_COMPLEXITY_TOO_GREAT,
  229. )
  230. self.limit_remote_rooms = LimitRemoteRoomsConfig(
  231. **config.get("limit_remote_rooms", {})
  232. )
  233. bind_port = config.get("bind_port")
  234. if bind_port:
  235. if config.get("no_tls", False):
  236. raise ConfigError("no_tls is incompatible with bind_port")
  237. self.listeners = []
  238. bind_host = config.get("bind_host", "")
  239. gzip_responses = config.get("gzip_responses", True)
  240. self.listeners.append(
  241. {
  242. "port": bind_port,
  243. "bind_addresses": [bind_host],
  244. "tls": True,
  245. "type": "http",
  246. "resources": [
  247. {"names": ["client"], "compress": gzip_responses},
  248. {"names": ["federation"], "compress": False},
  249. ],
  250. }
  251. )
  252. unsecure_port = config.get("unsecure_port", bind_port - 400)
  253. if unsecure_port:
  254. self.listeners.append(
  255. {
  256. "port": unsecure_port,
  257. "bind_addresses": [bind_host],
  258. "tls": False,
  259. "type": "http",
  260. "resources": [
  261. {"names": ["client"], "compress": gzip_responses},
  262. {"names": ["federation"], "compress": False},
  263. ],
  264. }
  265. )
  266. manhole = config.get("manhole")
  267. if manhole:
  268. self.listeners.append(
  269. {
  270. "port": manhole,
  271. "bind_addresses": ["127.0.0.1"],
  272. "type": "manhole",
  273. "tls": False,
  274. }
  275. )
  276. metrics_port = config.get("metrics_port")
  277. if metrics_port:
  278. logger.warn(
  279. (
  280. "The metrics_port configuration option is deprecated in Synapse 0.31 "
  281. "in favour of a listener. Please see "
  282. "http://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.md"
  283. " on how to configure the new listener."
  284. )
  285. )
  286. self.listeners.append(
  287. {
  288. "port": metrics_port,
  289. "bind_addresses": [config.get("metrics_bind_host", "127.0.0.1")],
  290. "tls": False,
  291. "type": "http",
  292. "resources": [{"names": ["metrics"], "compress": False}],
  293. }
  294. )
  295. _check_resource_config(self.listeners)
  296. # An experimental option to try and periodically clean up extremities
  297. # by sending dummy events.
  298. self.cleanup_extremities_with_dummy_events = config.get(
  299. "cleanup_extremities_with_dummy_events", False
  300. )
  301. def has_tls_listener(self):
  302. return any(l["tls"] for l in self.listeners)
  303. def generate_config_section(
  304. self, server_name, data_dir_path, open_private_ports, listeners, **kwargs
  305. ):
  306. _, bind_port = parse_and_validate_server_name(server_name)
  307. if bind_port is not None:
  308. unsecure_port = bind_port - 400
  309. else:
  310. bind_port = 8448
  311. unsecure_port = 8008
  312. pid_file = os.path.join(data_dir_path, "homeserver.pid")
  313. # Bring DEFAULT_ROOM_VERSION into the local-scope for use in the
  314. # default config string
  315. default_room_version = DEFAULT_ROOM_VERSION
  316. secure_listeners = []
  317. unsecure_listeners = []
  318. private_addresses = ["::1", "127.0.0.1"]
  319. if listeners:
  320. for listener in listeners:
  321. if listener["tls"]:
  322. secure_listeners.append(listener)
  323. else:
  324. # If we don't want open ports we need to bind the listeners
  325. # to some address other than 0.0.0.0. Here we chose to use
  326. # localhost.
  327. # If the addresses are already bound we won't overwrite them
  328. # however.
  329. if not open_private_ports:
  330. listener.setdefault("bind_addresses", private_addresses)
  331. unsecure_listeners.append(listener)
  332. secure_http_bindings = indent(
  333. yaml.dump(secure_listeners), " " * 10
  334. ).lstrip()
  335. unsecure_http_bindings = indent(
  336. yaml.dump(unsecure_listeners), " " * 10
  337. ).lstrip()
  338. if not unsecure_listeners:
  339. unsecure_http_bindings = (
  340. """- port: %(unsecure_port)s
  341. tls: false
  342. type: http
  343. x_forwarded: true"""
  344. % locals()
  345. )
  346. if not open_private_ports:
  347. unsecure_http_bindings += (
  348. "\n bind_addresses: ['::1', '127.0.0.1']"
  349. )
  350. unsecure_http_bindings += """
  351. resources:
  352. - names: [client, federation]
  353. compress: false"""
  354. if listeners:
  355. # comment out this block
  356. unsecure_http_bindings = "#" + re.sub(
  357. "\n {10}",
  358. lambda match: match.group(0) + "#",
  359. unsecure_http_bindings,
  360. )
  361. if not secure_listeners:
  362. secure_http_bindings = (
  363. """#- port: %(bind_port)s
  364. # type: http
  365. # tls: true
  366. # resources:
  367. # - names: [client, federation]"""
  368. % locals()
  369. )
  370. return (
  371. """\
  372. ## Server ##
  373. # The domain name of the server, with optional explicit port.
  374. # This is used by remote servers to connect to this server,
  375. # e.g. matrix.org, localhost:8080, etc.
  376. # This is also the last part of your UserID.
  377. #
  378. server_name: "%(server_name)s"
  379. # When running as a daemon, the file to store the pid in
  380. #
  381. pid_file: %(pid_file)s
  382. # The path to the web client which will be served at /_matrix/client/
  383. # if 'webclient' is configured under the 'listeners' configuration.
  384. #
  385. #web_client_location: "/path/to/web/root"
  386. # The public-facing base URL that clients use to access this HS
  387. # (not including _matrix/...). This is the same URL a user would
  388. # enter into the 'custom HS URL' field on their client. If you
  389. # use synapse with a reverse proxy, this should be the URL to reach
  390. # synapse via the proxy.
  391. #
  392. #public_baseurl: https://example.com/
  393. # Set the soft limit on the number of file descriptors synapse can use
  394. # Zero is used to indicate synapse should set the soft limit to the
  395. # hard limit.
  396. #
  397. #soft_file_limit: 0
  398. # Set to false to disable presence tracking on this homeserver.
  399. #
  400. #use_presence: false
  401. # Whether to require authentication to retrieve profile data (avatars,
  402. # display names) of other users through the client API. Defaults to
  403. # 'false'. Note that profile data is also available via the federation
  404. # API, so this setting is of limited value if federation is enabled on
  405. # the server.
  406. #
  407. #require_auth_for_profile_requests: true
  408. # If set to 'false', requires authentication to access the server's public rooms
  409. # directory through the client API. Defaults to 'true'.
  410. #
  411. #allow_public_rooms_without_auth: false
  412. # If set to 'false', forbids any other homeserver to fetch the server's public
  413. # rooms directory via federation. Defaults to 'true'.
  414. #
  415. #allow_public_rooms_over_federation: false
  416. # The default room version for newly created rooms.
  417. #
  418. # Known room versions are listed here:
  419. # https://matrix.org/docs/spec/#complete-list-of-room-versions
  420. #
  421. # For example, for room version 1, default_room_version should be set
  422. # to "1".
  423. #
  424. #default_room_version: "%(default_room_version)s"
  425. # The GC threshold parameters to pass to `gc.set_threshold`, if defined
  426. #
  427. #gc_thresholds: [700, 10, 10]
  428. # Set the limit on the returned events in the timeline in the get
  429. # and sync operations. The default value is -1, means no upper limit.
  430. #
  431. #filter_timeline_limit: 5000
  432. # Whether room invites to users on this server should be blocked
  433. # (except those sent by local server admins). The default is False.
  434. #
  435. #block_non_admin_invites: True
  436. # Room searching
  437. #
  438. # If disabled, new messages will not be indexed for searching and users
  439. # will receive errors when searching for messages. Defaults to enabled.
  440. #
  441. #enable_search: false
  442. # Restrict federation to the following whitelist of domains.
  443. # N.B. we recommend also firewalling your federation listener to limit
  444. # inbound federation traffic as early as possible, rather than relying
  445. # purely on this application-layer restriction. If not specified, the
  446. # default is to whitelist everything.
  447. #
  448. #federation_domain_whitelist:
  449. # - lon.example.com
  450. # - nyc.example.com
  451. # - syd.example.com
  452. # Prevent federation requests from being sent to the following
  453. # blacklist IP address CIDR ranges. If this option is not specified, or
  454. # specified with an empty list, no ip range blacklist will be enforced.
  455. #
  456. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  457. # listed here, since they correspond to unroutable addresses.)
  458. #
  459. federation_ip_range_blacklist:
  460. - '127.0.0.0/8'
  461. - '10.0.0.0/8'
  462. - '172.16.0.0/12'
  463. - '192.168.0.0/16'
  464. - '100.64.0.0/10'
  465. - '169.254.0.0/16'
  466. - '::1/128'
  467. - 'fe80::/64'
  468. - 'fc00::/7'
  469. # List of ports that Synapse should listen on, their purpose and their
  470. # configuration.
  471. #
  472. # Options for each listener include:
  473. #
  474. # port: the TCP port to bind to
  475. #
  476. # bind_addresses: a list of local addresses to listen on. The default is
  477. # 'all local interfaces'.
  478. #
  479. # type: the type of listener. Normally 'http', but other valid options are:
  480. # 'manhole' (see docs/manhole.md),
  481. # 'metrics' (see docs/metrics-howto.md),
  482. # 'replication' (see docs/workers.md).
  483. #
  484. # tls: set to true to enable TLS for this listener. Will use the TLS
  485. # key/cert specified in tls_private_key_path / tls_certificate_path.
  486. #
  487. # x_forwarded: Only valid for an 'http' listener. Set to true to use the
  488. # X-Forwarded-For header as the client IP. Useful when Synapse is
  489. # behind a reverse-proxy.
  490. #
  491. # resources: Only valid for an 'http' listener. A list of resources to host
  492. # on this port. Options for each resource are:
  493. #
  494. # names: a list of names of HTTP resources. See below for a list of
  495. # valid resource names.
  496. #
  497. # compress: set to true to enable HTTP comression for this resource.
  498. #
  499. # additional_resources: Only valid for an 'http' listener. A map of
  500. # additional endpoints which should be loaded via dynamic modules.
  501. #
  502. # Valid resource names are:
  503. #
  504. # client: the client-server API (/_matrix/client), and the synapse admin
  505. # API (/_synapse/admin). Also implies 'media' and 'static'.
  506. #
  507. # consent: user consent forms (/_matrix/consent). See
  508. # docs/consent_tracking.md.
  509. #
  510. # federation: the server-server API (/_matrix/federation). Also implies
  511. # 'media', 'keys', 'openid'
  512. #
  513. # keys: the key discovery API (/_matrix/keys).
  514. #
  515. # media: the media API (/_matrix/media).
  516. #
  517. # metrics: the metrics interface. See docs/metrics-howto.md.
  518. #
  519. # openid: OpenID authentication.
  520. #
  521. # replication: the HTTP replication API (/_synapse/replication). See
  522. # docs/workers.md.
  523. #
  524. # static: static resources under synapse/static (/_matrix/static). (Mostly
  525. # useful for 'fallback authentication'.)
  526. #
  527. # webclient: A web client. Requires web_client_location to be set.
  528. #
  529. listeners:
  530. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  531. #
  532. # Disabled by default. To enable it, uncomment the following. (Note that you
  533. # will also need to give Synapse a TLS key and certificate: see the TLS section
  534. # below.)
  535. #
  536. %(secure_http_bindings)s
  537. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  538. # that unwraps TLS.
  539. #
  540. # If you plan to use a reverse proxy, please see
  541. # https://github.com/matrix-org/synapse/blob/master/docs/reverse_proxy.md.
  542. #
  543. %(unsecure_http_bindings)s
  544. # example additional_resources:
  545. #
  546. #additional_resources:
  547. # "/_matrix/my/custom/endpoint":
  548. # module: my_module.CustomRequestHandler
  549. # config: {}
  550. # Turn on the twisted ssh manhole service on localhost on the given
  551. # port.
  552. #
  553. #- port: 9000
  554. # bind_addresses: ['::1', '127.0.0.1']
  555. # type: manhole
  556. ## Homeserver blocking ##
  557. # How to reach the server admin, used in ResourceLimitError
  558. #
  559. #admin_contact: 'mailto:admin@server.com'
  560. # Global blocking
  561. #
  562. #hs_disabled: False
  563. #hs_disabled_message: 'Human readable reason for why the HS is blocked'
  564. #hs_disabled_limit_type: 'error code(str), to help clients decode reason'
  565. # Monthly Active User Blocking
  566. #
  567. # Used in cases where the admin or server owner wants to limit to the
  568. # number of monthly active users.
  569. #
  570. # 'limit_usage_by_mau' disables/enables monthly active user blocking. When
  571. # anabled and a limit is reached the server returns a 'ResourceLimitError'
  572. # with error type Codes.RESOURCE_LIMIT_EXCEEDED
  573. #
  574. # 'max_mau_value' is the hard limit of monthly active users above which
  575. # the server will start blocking user actions.
  576. #
  577. # 'mau_trial_days' is a means to add a grace period for active users. It
  578. # means that users must be active for this number of days before they
  579. # can be considered active and guards against the case where lots of users
  580. # sign up in a short space of time never to return after their initial
  581. # session.
  582. #
  583. #limit_usage_by_mau: False
  584. #max_mau_value: 50
  585. #mau_trial_days: 2
  586. # If enabled, the metrics for the number of monthly active users will
  587. # be populated, however no one will be limited. If limit_usage_by_mau
  588. # is true, this is implied to be true.
  589. #
  590. #mau_stats_only: False
  591. # Sometimes the server admin will want to ensure certain accounts are
  592. # never blocked by mau checking. These accounts are specified here.
  593. #
  594. #mau_limit_reserved_threepids:
  595. # - medium: 'email'
  596. # address: 'reserved_user@example.com'
  597. # Used by phonehome stats to group together related servers.
  598. #server_context: context
  599. # Resource-constrained Homeserver Settings
  600. #
  601. # If limit_remote_rooms.enabled is True, the room complexity will be
  602. # checked before a user joins a new remote room. If it is above
  603. # limit_remote_rooms.complexity, it will disallow joining or
  604. # instantly leave.
  605. #
  606. # limit_remote_rooms.complexity_error can be set to customise the text
  607. # displayed to the user when a room above the complexity threshold has
  608. # its join cancelled.
  609. #
  610. # Uncomment the below lines to enable:
  611. #limit_remote_rooms:
  612. # enabled: True
  613. # complexity: 1.0
  614. # complexity_error: "This room is too complex."
  615. # Whether to require a user to be in the room to add an alias to it.
  616. # Defaults to 'true'.
  617. #
  618. #require_membership_for_aliases: false
  619. # Whether to allow per-room membership profiles through the send of membership
  620. # events with profile information that differ from the target's global profile.
  621. # Defaults to 'true'.
  622. #
  623. #allow_per_room_profiles: false
  624. # How long to keep redacted events in unredacted form in the database. After
  625. # this period redacted events get replaced with their redacted form in the DB.
  626. #
  627. # Defaults to `7d`. Set to `null` to disable.
  628. #
  629. redaction_retention_period: 7d
  630. """
  631. % locals()
  632. )
  633. def read_arguments(self, args):
  634. if args.manhole is not None:
  635. self.manhole = args.manhole
  636. if args.daemonize is not None:
  637. self.daemonize = args.daemonize
  638. if args.print_pidfile is not None:
  639. self.print_pidfile = args.print_pidfile
  640. @staticmethod
  641. def add_arguments(parser):
  642. server_group = parser.add_argument_group("server")
  643. server_group.add_argument(
  644. "-D",
  645. "--daemonize",
  646. action="store_true",
  647. default=None,
  648. help="Daemonize the home server",
  649. )
  650. server_group.add_argument(
  651. "--print-pidfile",
  652. action="store_true",
  653. default=None,
  654. help="Print the path to the pidfile just" " before daemonizing",
  655. )
  656. server_group.add_argument(
  657. "--manhole",
  658. metavar="PORT",
  659. dest="manhole",
  660. type=int,
  661. help="Turn on the twisted telnet manhole" " service on the given port.",
  662. )
  663. def is_threepid_reserved(reserved_threepids, threepid):
  664. """Check the threepid against the reserved threepid config
  665. Args:
  666. reserved_threepids([dict]) - list of reserved threepids
  667. threepid(dict) - The threepid to test for
  668. Returns:
  669. boolean Is the threepid undertest reserved_user
  670. """
  671. for tp in reserved_threepids:
  672. if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]:
  673. return True
  674. return False
  675. def read_gc_thresholds(thresholds):
  676. """Reads the three integer thresholds for garbage collection. Ensures that
  677. the thresholds are integers if thresholds are supplied.
  678. """
  679. if thresholds is None:
  680. return None
  681. try:
  682. assert len(thresholds) == 3
  683. return (int(thresholds[0]), int(thresholds[1]), int(thresholds[2]))
  684. except Exception:
  685. raise ConfigError(
  686. "Value of `gc_threshold` must be a list of three integers if set"
  687. )
  688. NO_MORE_WEB_CLIENT_WARNING = """
  689. Synapse no longer includes a web client. To enable a web client, configure
  690. web_client_location. To remove this warning, remove 'webclient' from the 'listeners'
  691. configuration.
  692. """
  693. def _warn_if_webclient_configured(listeners):
  694. for listener in listeners:
  695. for res in listener.get("resources", []):
  696. for name in res.get("names", []):
  697. if name == "webclient":
  698. logger.warning(NO_MORE_WEB_CLIENT_WARNING)
  699. return
  700. KNOWN_RESOURCES = (
  701. "client",
  702. "consent",
  703. "federation",
  704. "keys",
  705. "media",
  706. "metrics",
  707. "openid",
  708. "replication",
  709. "static",
  710. "webclient",
  711. )
  712. def _check_resource_config(listeners):
  713. resource_names = set(
  714. res_name
  715. for listener in listeners
  716. for res in listener.get("resources", [])
  717. for res_name in res.get("names", [])
  718. )
  719. for resource in resource_names:
  720. if resource not in KNOWN_RESOURCES:
  721. raise ConfigError("Unknown listener resource '%s'" % (resource,))
  722. if resource == "consent":
  723. try:
  724. check_requirements("resources.consent")
  725. except DependencyException as e:
  726. raise ConfigError(e.message)