No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

1414 líneas
55 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 itertools
  17. import logging
  18. import os.path
  19. import re
  20. from textwrap import indent
  21. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
  22. import attr
  23. import yaml
  24. from netaddr import AddrFormatError, IPNetwork, IPSet
  25. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  26. from synapse.util.module_loader import load_module
  27. from synapse.util.stringutils import parse_and_validate_server_name
  28. from ._base import Config, ConfigError
  29. logger = logging.Logger(__name__)
  30. # by default, we attempt to listen on both '::' *and* '0.0.0.0' because some OSes
  31. # (Windows, macOS, other BSD/Linux where net.ipv6.bindv6only is set) will only listen
  32. # on IPv6 when '::' is set.
  33. #
  34. # We later check for errors when binding to 0.0.0.0 and ignore them if :: is also in
  35. # in the list.
  36. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
  37. def _6to4(network: IPNetwork) -> IPNetwork:
  38. """Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056."""
  39. # 6to4 networks consist of:
  40. # * 2002 as the first 16 bits
  41. # * The first IPv4 address in the network hex-encoded as the next 32 bits
  42. # * The new prefix length needs to include the bits from the 2002 prefix.
  43. hex_network = hex(network.first)[2:]
  44. hex_network = ("0" * (8 - len(hex_network))) + hex_network
  45. return IPNetwork(
  46. "2002:%s:%s::/%d"
  47. % (
  48. hex_network[:4],
  49. hex_network[4:],
  50. 16 + network.prefixlen,
  51. )
  52. )
  53. def generate_ip_set(
  54. ip_addresses: Optional[Iterable[str]],
  55. extra_addresses: Optional[Iterable[str]] = None,
  56. config_path: Optional[Iterable[str]] = None,
  57. ) -> IPSet:
  58. """
  59. Generate an IPSet from a list of IP addresses or CIDRs.
  60. Additionally, for each IPv4 network in the list of IP addresses, also
  61. includes the corresponding IPv6 networks.
  62. This includes:
  63. * IPv4-Compatible IPv6 Address (see RFC 4291, section 2.5.5.1)
  64. * IPv4-Mapped IPv6 Address (see RFC 4291, section 2.5.5.2)
  65. * 6to4 Address (see RFC 3056, section 2)
  66. Args:
  67. ip_addresses: An iterable of IP addresses or CIDRs.
  68. extra_addresses: An iterable of IP addresses or CIDRs.
  69. config_path: The path in the configuration for error messages.
  70. Returns:
  71. A new IP set.
  72. """
  73. result = IPSet()
  74. for ip in itertools.chain(ip_addresses or (), extra_addresses or ()):
  75. try:
  76. network = IPNetwork(ip)
  77. except AddrFormatError as e:
  78. raise ConfigError(
  79. "Invalid IP range provided: %s." % (ip,), config_path
  80. ) from e
  81. result.add(network)
  82. # It is possible that these already exist in the set, but that's OK.
  83. if ":" not in str(network):
  84. result.add(IPNetwork(network).ipv6(ipv4_compatible=True))
  85. result.add(IPNetwork(network).ipv6(ipv4_compatible=False))
  86. result.add(_6to4(network))
  87. return result
  88. # IP ranges that are considered private / unroutable / don't make sense.
  89. DEFAULT_IP_RANGE_BLACKLIST = [
  90. # Localhost
  91. "127.0.0.0/8",
  92. # Private networks.
  93. "10.0.0.0/8",
  94. "172.16.0.0/12",
  95. "192.168.0.0/16",
  96. # Carrier grade NAT.
  97. "100.64.0.0/10",
  98. # Address registry.
  99. "192.0.0.0/24",
  100. # Link-local networks.
  101. "169.254.0.0/16",
  102. # Formerly used for 6to4 relay.
  103. "192.88.99.0/24",
  104. # Testing networks.
  105. "198.18.0.0/15",
  106. "192.0.2.0/24",
  107. "198.51.100.0/24",
  108. "203.0.113.0/24",
  109. # Multicast.
  110. "224.0.0.0/4",
  111. # Localhost
  112. "::1/128",
  113. # Link-local addresses.
  114. "fe80::/10",
  115. # Unique local addresses.
  116. "fc00::/7",
  117. # Testing networks.
  118. "2001:db8::/32",
  119. # Multicast.
  120. "ff00::/8",
  121. # Site-local addresses
  122. "fec0::/10",
  123. ]
  124. DEFAULT_ROOM_VERSION = "6"
  125. ROOM_COMPLEXITY_TOO_GREAT = (
  126. "Your homeserver is unable to join rooms this large or complex. "
  127. "Please speak to your server administrator, or upgrade your instance "
  128. "to join this room."
  129. )
  130. METRICS_PORT_WARNING = """\
  131. The metrics_port configuration option is deprecated in Synapse 0.31 in favour of
  132. a listener. Please see
  133. https://matrix-org.github.io/synapse/latest/metrics-howto.html
  134. on how to configure the new listener.
  135. --------------------------------------------------------------------------------"""
  136. KNOWN_LISTENER_TYPES = {
  137. "http",
  138. "metrics",
  139. "manhole",
  140. "replication",
  141. }
  142. KNOWN_RESOURCES = {
  143. "client",
  144. "consent",
  145. "federation",
  146. "keys",
  147. "media",
  148. "metrics",
  149. "openid",
  150. "replication",
  151. "static",
  152. "webclient",
  153. }
  154. @attr.s(frozen=True)
  155. class HttpResourceConfig:
  156. names = attr.ib(
  157. type=List[str],
  158. factory=list,
  159. validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)), # type: ignore
  160. )
  161. compress = attr.ib(
  162. type=bool,
  163. default=False,
  164. validator=attr.validators.optional(attr.validators.instance_of(bool)), # type: ignore[arg-type]
  165. )
  166. @attr.s(frozen=True)
  167. class HttpListenerConfig:
  168. """Object describing the http-specific parts of the config of a listener"""
  169. x_forwarded = attr.ib(type=bool, default=False)
  170. resources = attr.ib(type=List[HttpResourceConfig], factory=list)
  171. additional_resources = attr.ib(type=Dict[str, dict], factory=dict)
  172. tag = attr.ib(type=str, default=None)
  173. @attr.s(frozen=True)
  174. class ListenerConfig:
  175. """Object describing the configuration of a single listener."""
  176. port = attr.ib(type=int, validator=attr.validators.instance_of(int))
  177. bind_addresses = attr.ib(type=List[str])
  178. type = attr.ib(type=str, validator=attr.validators.in_(KNOWN_LISTENER_TYPES))
  179. tls = attr.ib(type=bool, default=False)
  180. # http_options is only populated if type=http
  181. http_options = attr.ib(type=Optional[HttpListenerConfig], default=None)
  182. class ServerConfig(Config):
  183. section = "server"
  184. def read_config(self, config, **kwargs):
  185. self.server_name = config["server_name"]
  186. self.server_context = config.get("server_context", None)
  187. try:
  188. parse_and_validate_server_name(self.server_name)
  189. except ValueError as e:
  190. raise ConfigError(str(e))
  191. self.pid_file = self.abspath(config.get("pid_file"))
  192. self.web_client_location = config.get("web_client_location", None)
  193. self.soft_file_limit = config.get("soft_file_limit", 0)
  194. self.daemonize = config.get("daemonize")
  195. self.print_pidfile = config.get("print_pidfile")
  196. self.user_agent_suffix = config.get("user_agent_suffix")
  197. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  198. self.public_baseurl = config.get("public_baseurl")
  199. if self.public_baseurl is not None:
  200. if self.public_baseurl[-1] != "/":
  201. self.public_baseurl += "/"
  202. # Whether to enable user presence.
  203. presence_config = config.get("presence") or {}
  204. self.use_presence = presence_config.get("enabled")
  205. if self.use_presence is None:
  206. self.use_presence = config.get("use_presence", True)
  207. # Custom presence router module
  208. # This is the legacy way of configuring it (the config should now be put in the modules section)
  209. self.presence_router_module_class = None
  210. self.presence_router_config = None
  211. presence_router_config = presence_config.get("presence_router")
  212. if presence_router_config:
  213. (
  214. self.presence_router_module_class,
  215. self.presence_router_config,
  216. ) = load_module(presence_router_config, ("presence", "presence_router"))
  217. # Whether to update the user directory or not. This should be set to
  218. # false only if we are updating the user directory in a worker
  219. self.update_user_directory = config.get("update_user_directory", True)
  220. # whether to enable the media repository endpoints. This should be set
  221. # to false if the media repository is running as a separate endpoint;
  222. # doing so ensures that we will not run cache cleanup jobs on the
  223. # master, potentially causing inconsistency.
  224. self.enable_media_repo = config.get("enable_media_repo", True)
  225. # Whether to require authentication to retrieve profile data (avatars,
  226. # display names) of other users through the client API.
  227. self.require_auth_for_profile_requests = config.get(
  228. "require_auth_for_profile_requests", False
  229. )
  230. # Whether to require sharing a room with a user to retrieve their
  231. # profile data
  232. self.limit_profile_requests_to_users_who_share_rooms = config.get(
  233. "limit_profile_requests_to_users_who_share_rooms",
  234. False,
  235. )
  236. # Whether to retrieve and display profile data for a user when they
  237. # are invited to a room
  238. self.include_profile_data_on_invite = config.get(
  239. "include_profile_data_on_invite", True
  240. )
  241. if "restrict_public_rooms_to_local_users" in config and (
  242. "allow_public_rooms_without_auth" in config
  243. or "allow_public_rooms_over_federation" in config
  244. ):
  245. raise ConfigError(
  246. "Can't use 'restrict_public_rooms_to_local_users' if"
  247. " 'allow_public_rooms_without_auth' and/or"
  248. " 'allow_public_rooms_over_federation' is set."
  249. )
  250. # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This
  251. # flag is now obsolete but we need to check it for backward-compatibility.
  252. if config.get("restrict_public_rooms_to_local_users", False):
  253. self.allow_public_rooms_without_auth = False
  254. self.allow_public_rooms_over_federation = False
  255. else:
  256. # If set to 'true', removes the need for authentication to access the server's
  257. # public rooms directory through the client API, meaning that anyone can
  258. # query the room directory. Defaults to 'false'.
  259. self.allow_public_rooms_without_auth = config.get(
  260. "allow_public_rooms_without_auth", False
  261. )
  262. # If set to 'true', allows any other homeserver to fetch the server's public
  263. # rooms directory via federation. Defaults to 'false'.
  264. self.allow_public_rooms_over_federation = config.get(
  265. "allow_public_rooms_over_federation", False
  266. )
  267. default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION)
  268. # Ensure room version is a str
  269. default_room_version = str(default_room_version)
  270. if default_room_version not in KNOWN_ROOM_VERSIONS:
  271. raise ConfigError(
  272. "Unknown default_room_version: %s, known room versions: %s"
  273. % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys()))
  274. )
  275. # Get the actual room version object rather than just the identifier
  276. self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version]
  277. # whether to enable search. If disabled, new entries will not be inserted
  278. # into the search tables and they will not be indexed. Users will receive
  279. # errors when attempting to search for messages.
  280. self.enable_search = config.get("enable_search", True)
  281. self.filter_timeline_limit = config.get("filter_timeline_limit", 100)
  282. # Whether we should block invites sent to users on this server
  283. # (other than those sent by local server admins)
  284. self.block_non_admin_invites = config.get("block_non_admin_invites", False)
  285. # Whether to enable experimental MSC1849 (aka relations) support
  286. self.experimental_msc1849_support_enabled = config.get(
  287. "experimental_msc1849_support_enabled", True
  288. )
  289. # Options to control access by tracking MAU
  290. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  291. self.max_mau_value = 0
  292. if self.limit_usage_by_mau:
  293. self.max_mau_value = config.get("max_mau_value", 0)
  294. self.mau_stats_only = config.get("mau_stats_only", False)
  295. self.mau_limits_reserved_threepids = config.get(
  296. "mau_limit_reserved_threepids", []
  297. )
  298. self.mau_trial_days = config.get("mau_trial_days", 0)
  299. self.mau_limit_alerting = config.get("mau_limit_alerting", True)
  300. # How long to keep redacted events in the database in unredacted form
  301. # before redacting them.
  302. redaction_retention_period = config.get("redaction_retention_period", "7d")
  303. if redaction_retention_period is not None:
  304. self.redaction_retention_period = self.parse_duration(
  305. redaction_retention_period
  306. )
  307. else:
  308. self.redaction_retention_period = None
  309. # How long to keep entries in the `users_ips` table.
  310. user_ips_max_age = config.get("user_ips_max_age", "28d")
  311. if user_ips_max_age is not None:
  312. self.user_ips_max_age = self.parse_duration(user_ips_max_age)
  313. else:
  314. self.user_ips_max_age = None
  315. # Options to disable HS
  316. self.hs_disabled = config.get("hs_disabled", False)
  317. self.hs_disabled_message = config.get("hs_disabled_message", "")
  318. # Admin uri to direct users at should their instance become blocked
  319. # due to resource constraints
  320. self.admin_contact = config.get("admin_contact", None)
  321. ip_range_blacklist = config.get(
  322. "ip_range_blacklist", DEFAULT_IP_RANGE_BLACKLIST
  323. )
  324. # Attempt to create an IPSet from the given ranges
  325. # Always blacklist 0.0.0.0, ::
  326. self.ip_range_blacklist = generate_ip_set(
  327. ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",)
  328. )
  329. self.ip_range_whitelist = generate_ip_set(
  330. config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",)
  331. )
  332. # The federation_ip_range_blacklist is used for backwards-compatibility
  333. # and only applies to federation and identity servers.
  334. if "federation_ip_range_blacklist" in config:
  335. # Always blacklist 0.0.0.0, ::
  336. self.federation_ip_range_blacklist = generate_ip_set(
  337. config["federation_ip_range_blacklist"],
  338. ["0.0.0.0", "::"],
  339. config_path=("federation_ip_range_blacklist",),
  340. )
  341. # 'federation_ip_range_whitelist' was never a supported configuration option.
  342. self.federation_ip_range_whitelist = None
  343. else:
  344. # No backwards-compatiblity requrired, as federation_ip_range_blacklist
  345. # is not given. Default to ip_range_blacklist and ip_range_whitelist.
  346. self.federation_ip_range_blacklist = self.ip_range_blacklist
  347. self.federation_ip_range_whitelist = self.ip_range_whitelist
  348. # (undocumented) option for torturing the worker-mode replication a bit,
  349. # for testing. The value defines the number of milliseconds to pause before
  350. # sending out any replication updates.
  351. self.replication_torture_level = config.get("replication_torture_level")
  352. # Whether to require a user to be in the room to add an alias to it.
  353. # Defaults to True.
  354. self.require_membership_for_aliases = config.get(
  355. "require_membership_for_aliases", True
  356. )
  357. # Whether to allow per-room membership profiles through the send of membership
  358. # events with profile information that differ from the target's global profile.
  359. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True)
  360. retention_config = config.get("retention")
  361. if retention_config is None:
  362. retention_config = {}
  363. self.retention_enabled = retention_config.get("enabled", False)
  364. retention_default_policy = retention_config.get("default_policy")
  365. if retention_default_policy is not None:
  366. self.retention_default_min_lifetime = retention_default_policy.get(
  367. "min_lifetime"
  368. )
  369. if self.retention_default_min_lifetime is not None:
  370. self.retention_default_min_lifetime = self.parse_duration(
  371. self.retention_default_min_lifetime
  372. )
  373. self.retention_default_max_lifetime = retention_default_policy.get(
  374. "max_lifetime"
  375. )
  376. if self.retention_default_max_lifetime is not None:
  377. self.retention_default_max_lifetime = self.parse_duration(
  378. self.retention_default_max_lifetime
  379. )
  380. if (
  381. self.retention_default_min_lifetime is not None
  382. and self.retention_default_max_lifetime is not None
  383. and (
  384. self.retention_default_min_lifetime
  385. > self.retention_default_max_lifetime
  386. )
  387. ):
  388. raise ConfigError(
  389. "The default retention policy's 'min_lifetime' can not be greater"
  390. " than its 'max_lifetime'"
  391. )
  392. else:
  393. self.retention_default_min_lifetime = None
  394. self.retention_default_max_lifetime = None
  395. if self.retention_enabled:
  396. logger.info(
  397. "Message retention policies support enabled with the following default"
  398. " policy: min_lifetime = %s ; max_lifetime = %s",
  399. self.retention_default_min_lifetime,
  400. self.retention_default_max_lifetime,
  401. )
  402. self.retention_allowed_lifetime_min = retention_config.get(
  403. "allowed_lifetime_min"
  404. )
  405. if self.retention_allowed_lifetime_min is not None:
  406. self.retention_allowed_lifetime_min = self.parse_duration(
  407. self.retention_allowed_lifetime_min
  408. )
  409. self.retention_allowed_lifetime_max = retention_config.get(
  410. "allowed_lifetime_max"
  411. )
  412. if self.retention_allowed_lifetime_max is not None:
  413. self.retention_allowed_lifetime_max = self.parse_duration(
  414. self.retention_allowed_lifetime_max
  415. )
  416. if (
  417. self.retention_allowed_lifetime_min is not None
  418. and self.retention_allowed_lifetime_max is not None
  419. and self.retention_allowed_lifetime_min
  420. > self.retention_allowed_lifetime_max
  421. ):
  422. raise ConfigError(
  423. "Invalid retention policy limits: 'allowed_lifetime_min' can not be"
  424. " greater than 'allowed_lifetime_max'"
  425. )
  426. self.retention_purge_jobs: List[Dict[str, Optional[int]]] = []
  427. for purge_job_config in retention_config.get("purge_jobs", []):
  428. interval_config = purge_job_config.get("interval")
  429. if interval_config is None:
  430. raise ConfigError(
  431. "A retention policy's purge jobs configuration must have the"
  432. " 'interval' key set."
  433. )
  434. interval = self.parse_duration(interval_config)
  435. shortest_max_lifetime = purge_job_config.get("shortest_max_lifetime")
  436. if shortest_max_lifetime is not None:
  437. shortest_max_lifetime = self.parse_duration(shortest_max_lifetime)
  438. longest_max_lifetime = purge_job_config.get("longest_max_lifetime")
  439. if longest_max_lifetime is not None:
  440. longest_max_lifetime = self.parse_duration(longest_max_lifetime)
  441. if (
  442. shortest_max_lifetime is not None
  443. and longest_max_lifetime is not None
  444. and shortest_max_lifetime > longest_max_lifetime
  445. ):
  446. raise ConfigError(
  447. "A retention policy's purge jobs configuration's"
  448. " 'shortest_max_lifetime' value can not be greater than its"
  449. " 'longest_max_lifetime' value."
  450. )
  451. self.retention_purge_jobs.append(
  452. {
  453. "interval": interval,
  454. "shortest_max_lifetime": shortest_max_lifetime,
  455. "longest_max_lifetime": longest_max_lifetime,
  456. }
  457. )
  458. if not self.retention_purge_jobs:
  459. self.retention_purge_jobs = [
  460. {
  461. "interval": self.parse_duration("1d"),
  462. "shortest_max_lifetime": None,
  463. "longest_max_lifetime": None,
  464. }
  465. ]
  466. self.listeners = [parse_listener_def(x) for x in config.get("listeners", [])]
  467. # no_tls is not really supported any more, but let's grandfather it in
  468. # here.
  469. if config.get("no_tls", False):
  470. l2 = []
  471. for listener in self.listeners:
  472. if listener.tls:
  473. logger.info(
  474. "Ignoring TLS-enabled listener on port %i due to no_tls",
  475. listener.port,
  476. )
  477. else:
  478. l2.append(listener)
  479. self.listeners = l2
  480. if not self.web_client_location:
  481. _warn_if_webclient_configured(self.listeners)
  482. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  483. self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None))
  484. @attr.s
  485. class LimitRemoteRoomsConfig:
  486. enabled = attr.ib(
  487. validator=attr.validators.instance_of(bool), default=False
  488. )
  489. complexity = attr.ib(
  490. validator=attr.validators.instance_of(
  491. (float, int) # type: ignore[arg-type] # noqa
  492. ),
  493. default=1.0,
  494. )
  495. complexity_error = attr.ib(
  496. validator=attr.validators.instance_of(str),
  497. default=ROOM_COMPLEXITY_TOO_GREAT,
  498. )
  499. admins_can_join = attr.ib(
  500. validator=attr.validators.instance_of(bool), default=False
  501. )
  502. self.limit_remote_rooms = LimitRemoteRoomsConfig(
  503. **(config.get("limit_remote_rooms") or {})
  504. )
  505. bind_port = config.get("bind_port")
  506. if bind_port:
  507. if config.get("no_tls", False):
  508. raise ConfigError("no_tls is incompatible with bind_port")
  509. self.listeners = []
  510. bind_host = config.get("bind_host", "")
  511. gzip_responses = config.get("gzip_responses", True)
  512. http_options = HttpListenerConfig(
  513. resources=[
  514. HttpResourceConfig(names=["client"], compress=gzip_responses),
  515. HttpResourceConfig(names=["federation"]),
  516. ],
  517. )
  518. self.listeners.append(
  519. ListenerConfig(
  520. port=bind_port,
  521. bind_addresses=[bind_host],
  522. tls=True,
  523. type="http",
  524. http_options=http_options,
  525. )
  526. )
  527. unsecure_port = config.get("unsecure_port", bind_port - 400)
  528. if unsecure_port:
  529. self.listeners.append(
  530. ListenerConfig(
  531. port=unsecure_port,
  532. bind_addresses=[bind_host],
  533. tls=False,
  534. type="http",
  535. http_options=http_options,
  536. )
  537. )
  538. manhole = config.get("manhole")
  539. if manhole:
  540. self.listeners.append(
  541. ListenerConfig(
  542. port=manhole,
  543. bind_addresses=["127.0.0.1"],
  544. type="manhole",
  545. )
  546. )
  547. metrics_port = config.get("metrics_port")
  548. if metrics_port:
  549. logger.warning(METRICS_PORT_WARNING)
  550. self.listeners.append(
  551. ListenerConfig(
  552. port=metrics_port,
  553. bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")],
  554. type="http",
  555. http_options=HttpListenerConfig(
  556. resources=[HttpResourceConfig(names=["metrics"])]
  557. ),
  558. )
  559. )
  560. self.cleanup_extremities_with_dummy_events = config.get(
  561. "cleanup_extremities_with_dummy_events", True
  562. )
  563. # The number of forward extremities in a room needed to send a dummy event.
  564. self.dummy_events_threshold = config.get("dummy_events_threshold", 10)
  565. self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False)
  566. # Inhibits the /requestToken endpoints from returning an error that might leak
  567. # information about whether an e-mail address is in use or not on this
  568. # homeserver, and instead return a 200 with a fake sid if this kind of error is
  569. # met, without sending anything.
  570. # This is a compromise between sending an email, which could be a spam vector,
  571. # and letting the client know which email address is bound to an account and
  572. # which one isn't.
  573. self.request_token_inhibit_3pid_errors = config.get(
  574. "request_token_inhibit_3pid_errors",
  575. False,
  576. )
  577. # List of users trialing the new experimental default push rules. This setting is
  578. # not included in the sample configuration file on purpose as it's a temporary
  579. # hack, so that some users can trial the new defaults without impacting every
  580. # user on the homeserver.
  581. users_new_default_push_rules: list = (
  582. config.get("users_new_default_push_rules") or []
  583. )
  584. if not isinstance(users_new_default_push_rules, list):
  585. raise ConfigError("'users_new_default_push_rules' must be a list")
  586. # Turn the list into a set to improve lookup speed.
  587. self.users_new_default_push_rules: set = set(users_new_default_push_rules)
  588. # Whitelist of domain names that given next_link parameters must have
  589. next_link_domain_whitelist: Optional[List[str]] = config.get(
  590. "next_link_domain_whitelist"
  591. )
  592. self.next_link_domain_whitelist: Optional[Set[str]] = None
  593. if next_link_domain_whitelist is not None:
  594. if not isinstance(next_link_domain_whitelist, list):
  595. raise ConfigError("'next_link_domain_whitelist' must be a list")
  596. # Turn the list into a set to improve lookup speed.
  597. self.next_link_domain_whitelist = set(next_link_domain_whitelist)
  598. def has_tls_listener(self) -> bool:
  599. return any(listener.tls for listener in self.listeners)
  600. def generate_config_section(
  601. self, server_name, data_dir_path, open_private_ports, listeners, **kwargs
  602. ):
  603. ip_range_blacklist = "\n".join(
  604. " # - '%s'" % ip for ip in DEFAULT_IP_RANGE_BLACKLIST
  605. )
  606. _, bind_port = parse_and_validate_server_name(server_name)
  607. if bind_port is not None:
  608. unsecure_port = bind_port - 400
  609. else:
  610. bind_port = 8448
  611. unsecure_port = 8008
  612. pid_file = os.path.join(data_dir_path, "homeserver.pid")
  613. # Bring DEFAULT_ROOM_VERSION into the local-scope for use in the
  614. # default config string
  615. default_room_version = DEFAULT_ROOM_VERSION
  616. secure_listeners = []
  617. unsecure_listeners = []
  618. private_addresses = ["::1", "127.0.0.1"]
  619. if listeners:
  620. for listener in listeners:
  621. if listener["tls"]:
  622. secure_listeners.append(listener)
  623. else:
  624. # If we don't want open ports we need to bind the listeners
  625. # to some address other than 0.0.0.0. Here we chose to use
  626. # localhost.
  627. # If the addresses are already bound we won't overwrite them
  628. # however.
  629. if not open_private_ports:
  630. listener.setdefault("bind_addresses", private_addresses)
  631. unsecure_listeners.append(listener)
  632. secure_http_bindings = indent(
  633. yaml.dump(secure_listeners), " " * 10
  634. ).lstrip()
  635. unsecure_http_bindings = indent(
  636. yaml.dump(unsecure_listeners), " " * 10
  637. ).lstrip()
  638. if not unsecure_listeners:
  639. unsecure_http_bindings = (
  640. """- port: %(unsecure_port)s
  641. tls: false
  642. type: http
  643. x_forwarded: true"""
  644. % locals()
  645. )
  646. if not open_private_ports:
  647. unsecure_http_bindings += (
  648. "\n bind_addresses: ['::1', '127.0.0.1']"
  649. )
  650. unsecure_http_bindings += """
  651. resources:
  652. - names: [client, federation]
  653. compress: false"""
  654. if listeners:
  655. # comment out this block
  656. unsecure_http_bindings = "#" + re.sub(
  657. "\n {10}",
  658. lambda match: match.group(0) + "#",
  659. unsecure_http_bindings,
  660. )
  661. if not secure_listeners:
  662. secure_http_bindings = (
  663. """#- port: %(bind_port)s
  664. # type: http
  665. # tls: true
  666. # resources:
  667. # - names: [client, federation]"""
  668. % locals()
  669. )
  670. return (
  671. """\
  672. ## Server ##
  673. # The public-facing domain of the server
  674. #
  675. # The server_name name will appear at the end of usernames and room addresses
  676. # created on this server. For example if the server_name was example.com,
  677. # usernames on this server would be in the format @user:example.com
  678. #
  679. # In most cases you should avoid using a matrix specific subdomain such as
  680. # matrix.example.com or synapse.example.com as the server_name for the same
  681. # reasons you wouldn't use user@email.example.com as your email address.
  682. # See https://matrix-org.github.io/synapse/latest/delegate.html
  683. # for information on how to host Synapse on a subdomain while preserving
  684. # a clean server_name.
  685. #
  686. # The server_name cannot be changed later so it is important to
  687. # configure this correctly before you start Synapse. It should be all
  688. # lowercase and may contain an explicit port.
  689. # Examples: matrix.org, localhost:8080
  690. #
  691. server_name: "%(server_name)s"
  692. # When running as a daemon, the file to store the pid in
  693. #
  694. pid_file: %(pid_file)s
  695. # The absolute URL to the web client which /_matrix/client will redirect
  696. # to if 'webclient' is configured under the 'listeners' configuration.
  697. #
  698. # This option can be also set to the filesystem path to the web client
  699. # which will be served at /_matrix/client/ if 'webclient' is configured
  700. # under the 'listeners' configuration, however this is a security risk:
  701. # https://github.com/matrix-org/synapse#security-note
  702. #
  703. #web_client_location: https://riot.example.com/
  704. # The public-facing base URL that clients use to access this Homeserver (not
  705. # including _matrix/...). This is the same URL a user might enter into the
  706. # 'Custom Homeserver URL' field on their client. If you use Synapse with a
  707. # reverse proxy, this should be the URL to reach Synapse via the proxy.
  708. # Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  709. # 'listeners' below).
  710. #
  711. #public_baseurl: https://example.com/
  712. # Set the soft limit on the number of file descriptors synapse can use
  713. # Zero is used to indicate synapse should set the soft limit to the
  714. # hard limit.
  715. #
  716. #soft_file_limit: 0
  717. # Presence tracking allows users to see the state (e.g online/offline)
  718. # of other local and remote users.
  719. #
  720. presence:
  721. # Uncomment to disable presence tracking on this homeserver. This option
  722. # replaces the previous top-level 'use_presence' option.
  723. #
  724. #enabled: false
  725. # Whether to require authentication to retrieve profile data (avatars,
  726. # display names) of other users through the client API. Defaults to
  727. # 'false'. Note that profile data is also available via the federation
  728. # API, unless allow_profile_lookup_over_federation is set to false.
  729. #
  730. #require_auth_for_profile_requests: true
  731. # Uncomment to require a user to share a room with another user in order
  732. # to retrieve their profile information. Only checked on Client-Server
  733. # requests. Profile requests from other servers should be checked by the
  734. # requesting server. Defaults to 'false'.
  735. #
  736. #limit_profile_requests_to_users_who_share_rooms: true
  737. # Uncomment to prevent a user's profile data from being retrieved and
  738. # displayed in a room until they have joined it. By default, a user's
  739. # profile data is included in an invite event, regardless of the values
  740. # of the above two settings, and whether or not the users share a server.
  741. # Defaults to 'true'.
  742. #
  743. #include_profile_data_on_invite: false
  744. # If set to 'true', removes the need for authentication to access the server's
  745. # public rooms directory through the client API, meaning that anyone can
  746. # query the room directory. Defaults to 'false'.
  747. #
  748. #allow_public_rooms_without_auth: true
  749. # If set to 'true', allows any other homeserver to fetch the server's public
  750. # rooms directory via federation. Defaults to 'false'.
  751. #
  752. #allow_public_rooms_over_federation: true
  753. # The default room version for newly created rooms.
  754. #
  755. # Known room versions are listed here:
  756. # https://matrix.org/docs/spec/#complete-list-of-room-versions
  757. #
  758. # For example, for room version 1, default_room_version should be set
  759. # to "1".
  760. #
  761. #default_room_version: "%(default_room_version)s"
  762. # The GC threshold parameters to pass to `gc.set_threshold`, if defined
  763. #
  764. #gc_thresholds: [700, 10, 10]
  765. # The minimum time in seconds between each GC for a generation, regardless of
  766. # the GC thresholds. This ensures that we don't do GC too frequently.
  767. #
  768. # A value of `[1s, 10s, 30s]` indicates that a second must pass between consecutive
  769. # generation 0 GCs, etc.
  770. #
  771. # Defaults to `[1s, 10s, 30s]`.
  772. #
  773. #gc_min_interval: [0.5s, 30s, 1m]
  774. # Set the limit on the returned events in the timeline in the get
  775. # and sync operations. The default value is 100. -1 means no upper limit.
  776. #
  777. # Uncomment the following to increase the limit to 5000.
  778. #
  779. #filter_timeline_limit: 5000
  780. # Whether room invites to users on this server should be blocked
  781. # (except those sent by local server admins). The default is False.
  782. #
  783. #block_non_admin_invites: true
  784. # Room searching
  785. #
  786. # If disabled, new messages will not be indexed for searching and users
  787. # will receive errors when searching for messages. Defaults to enabled.
  788. #
  789. #enable_search: false
  790. # Prevent outgoing requests from being sent to the following blacklisted IP address
  791. # CIDR ranges. If this option is not specified then it defaults to private IP
  792. # address ranges (see the example below).
  793. #
  794. # The blacklist applies to the outbound requests for federation, identity servers,
  795. # push servers, and for checking key validity for third-party invite events.
  796. #
  797. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  798. # listed here, since they correspond to unroutable addresses.)
  799. #
  800. # This option replaces federation_ip_range_blacklist in Synapse v1.25.0.
  801. #
  802. # Note: The value is ignored when an HTTP proxy is in use
  803. #
  804. #ip_range_blacklist:
  805. %(ip_range_blacklist)s
  806. # List of IP address CIDR ranges that should be allowed for federation,
  807. # identity servers, push servers, and for checking key validity for
  808. # third-party invite events. This is useful for specifying exceptions to
  809. # wide-ranging blacklisted target IP ranges - e.g. for communication with
  810. # a push server only visible in your network.
  811. #
  812. # This whitelist overrides ip_range_blacklist and defaults to an empty
  813. # list.
  814. #
  815. #ip_range_whitelist:
  816. # - '192.168.1.1'
  817. # List of ports that Synapse should listen on, their purpose and their
  818. # configuration.
  819. #
  820. # Options for each listener include:
  821. #
  822. # port: the TCP port to bind to
  823. #
  824. # bind_addresses: a list of local addresses to listen on. The default is
  825. # 'all local interfaces'.
  826. #
  827. # type: the type of listener. Normally 'http', but other valid options are:
  828. # 'manhole' (see https://matrix-org.github.io/synapse/latest/manhole.html),
  829. # 'metrics' (see https://matrix-org.github.io/synapse/latest/metrics-howto.html),
  830. # 'replication' (see https://matrix-org.github.io/synapse/latest/workers.html).
  831. #
  832. # tls: set to true to enable TLS for this listener. Will use the TLS
  833. # key/cert specified in tls_private_key_path / tls_certificate_path.
  834. #
  835. # x_forwarded: Only valid for an 'http' listener. Set to true to use the
  836. # X-Forwarded-For header as the client IP. Useful when Synapse is
  837. # behind a reverse-proxy.
  838. #
  839. # resources: Only valid for an 'http' listener. A list of resources to host
  840. # on this port. Options for each resource are:
  841. #
  842. # names: a list of names of HTTP resources. See below for a list of
  843. # valid resource names.
  844. #
  845. # compress: set to true to enable HTTP compression for this resource.
  846. #
  847. # additional_resources: Only valid for an 'http' listener. A map of
  848. # additional endpoints which should be loaded via dynamic modules.
  849. #
  850. # Valid resource names are:
  851. #
  852. # client: the client-server API (/_matrix/client), and the synapse admin
  853. # API (/_synapse/admin). Also implies 'media' and 'static'.
  854. #
  855. # consent: user consent forms (/_matrix/consent).
  856. # See https://matrix-org.github.io/synapse/latest/consent_tracking.html.
  857. #
  858. # federation: the server-server API (/_matrix/federation). Also implies
  859. # 'media', 'keys', 'openid'
  860. #
  861. # keys: the key discovery API (/_matrix/keys).
  862. #
  863. # media: the media API (/_matrix/media).
  864. #
  865. # metrics: the metrics interface.
  866. # See https://matrix-org.github.io/synapse/latest/metrics-howto.html.
  867. #
  868. # openid: OpenID authentication.
  869. #
  870. # replication: the HTTP replication API (/_synapse/replication).
  871. # See https://matrix-org.github.io/synapse/latest/workers.html.
  872. #
  873. # static: static resources under synapse/static (/_matrix/static). (Mostly
  874. # useful for 'fallback authentication'.)
  875. #
  876. # webclient: A web client. Requires web_client_location to be set.
  877. #
  878. listeners:
  879. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  880. #
  881. # Disabled by default. To enable it, uncomment the following. (Note that you
  882. # will also need to give Synapse a TLS key and certificate: see the TLS section
  883. # below.)
  884. #
  885. %(secure_http_bindings)s
  886. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  887. # that unwraps TLS.
  888. #
  889. # If you plan to use a reverse proxy, please see
  890. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  891. #
  892. %(unsecure_http_bindings)s
  893. # example additional_resources:
  894. #
  895. #additional_resources:
  896. # "/_matrix/my/custom/endpoint":
  897. # module: my_module.CustomRequestHandler
  898. # config: {}
  899. # Turn on the twisted ssh manhole service on localhost on the given
  900. # port.
  901. #
  902. #- port: 9000
  903. # bind_addresses: ['::1', '127.0.0.1']
  904. # type: manhole
  905. # Forward extremities can build up in a room due to networking delays between
  906. # homeservers. Once this happens in a large room, calculation of the state of
  907. # that room can become quite expensive. To mitigate this, once the number of
  908. # forward extremities reaches a given threshold, Synapse will send an
  909. # org.matrix.dummy_event event, which will reduce the forward extremities
  910. # in the room.
  911. #
  912. # This setting defines the threshold (i.e. number of forward extremities in the
  913. # room) at which dummy events are sent. The default value is 10.
  914. #
  915. #dummy_events_threshold: 5
  916. ## Homeserver blocking ##
  917. # How to reach the server admin, used in ResourceLimitError
  918. #
  919. #admin_contact: 'mailto:admin@server.com'
  920. # Global blocking
  921. #
  922. #hs_disabled: false
  923. #hs_disabled_message: 'Human readable reason for why the HS is blocked'
  924. # Monthly Active User Blocking
  925. #
  926. # Used in cases where the admin or server owner wants to limit to the
  927. # number of monthly active users.
  928. #
  929. # 'limit_usage_by_mau' disables/enables monthly active user blocking. When
  930. # enabled and a limit is reached the server returns a 'ResourceLimitError'
  931. # with error type Codes.RESOURCE_LIMIT_EXCEEDED
  932. #
  933. # 'max_mau_value' is the hard limit of monthly active users above which
  934. # the server will start blocking user actions.
  935. #
  936. # 'mau_trial_days' is a means to add a grace period for active users. It
  937. # means that users must be active for this number of days before they
  938. # can be considered active and guards against the case where lots of users
  939. # sign up in a short space of time never to return after their initial
  940. # session.
  941. #
  942. # 'mau_limit_alerting' is a means of limiting client side alerting
  943. # should the mau limit be reached. This is useful for small instances
  944. # where the admin has 5 mau seats (say) for 5 specific people and no
  945. # interest increasing the mau limit further. Defaults to True, which
  946. # means that alerting is enabled
  947. #
  948. #limit_usage_by_mau: false
  949. #max_mau_value: 50
  950. #mau_trial_days: 2
  951. #mau_limit_alerting: false
  952. # If enabled, the metrics for the number of monthly active users will
  953. # be populated, however no one will be limited. If limit_usage_by_mau
  954. # is true, this is implied to be true.
  955. #
  956. #mau_stats_only: false
  957. # Sometimes the server admin will want to ensure certain accounts are
  958. # never blocked by mau checking. These accounts are specified here.
  959. #
  960. #mau_limit_reserved_threepids:
  961. # - medium: 'email'
  962. # address: 'reserved_user@example.com'
  963. # Used by phonehome stats to group together related servers.
  964. #server_context: context
  965. # Resource-constrained homeserver settings
  966. #
  967. # When this is enabled, the room "complexity" will be checked before a user
  968. # joins a new remote room. If it is above the complexity limit, the server will
  969. # disallow joining, or will instantly leave.
  970. #
  971. # Room complexity is an arbitrary measure based on factors such as the number of
  972. # users in the room.
  973. #
  974. limit_remote_rooms:
  975. # Uncomment to enable room complexity checking.
  976. #
  977. #enabled: true
  978. # the limit above which rooms cannot be joined. The default is 1.0.
  979. #
  980. #complexity: 0.5
  981. # override the error which is returned when the room is too complex.
  982. #
  983. #complexity_error: "This room is too complex."
  984. # allow server admins to join complex rooms. Default is false.
  985. #
  986. #admins_can_join: true
  987. # Whether to require a user to be in the room to add an alias to it.
  988. # Defaults to 'true'.
  989. #
  990. #require_membership_for_aliases: false
  991. # Whether to allow per-room membership profiles through the send of membership
  992. # events with profile information that differ from the target's global profile.
  993. # Defaults to 'true'.
  994. #
  995. #allow_per_room_profiles: false
  996. # How long to keep redacted events in unredacted form in the database. After
  997. # this period redacted events get replaced with their redacted form in the DB.
  998. #
  999. # Defaults to `7d`. Set to `null` to disable.
  1000. #
  1001. #redaction_retention_period: 28d
  1002. # How long to track users' last seen time and IPs in the database.
  1003. #
  1004. # Defaults to `28d`. Set to `null` to disable clearing out of old rows.
  1005. #
  1006. #user_ips_max_age: 14d
  1007. # Message retention policy at the server level.
  1008. #
  1009. # Room admins and mods can define a retention period for their rooms using the
  1010. # 'm.room.retention' state event, and server admins can cap this period by setting
  1011. # the 'allowed_lifetime_min' and 'allowed_lifetime_max' config options.
  1012. #
  1013. # If this feature is enabled, Synapse will regularly look for and purge events
  1014. # which are older than the room's maximum retention period. Synapse will also
  1015. # filter events received over federation so that events that should have been
  1016. # purged are ignored and not stored again.
  1017. #
  1018. retention:
  1019. # The message retention policies feature is disabled by default. Uncomment the
  1020. # following line to enable it.
  1021. #
  1022. #enabled: true
  1023. # Default retention policy. If set, Synapse will apply it to rooms that lack the
  1024. # 'm.room.retention' state event. Currently, the value of 'min_lifetime' doesn't
  1025. # matter much because Synapse doesn't take it into account yet.
  1026. #
  1027. #default_policy:
  1028. # min_lifetime: 1d
  1029. # max_lifetime: 1y
  1030. # Retention policy limits. If set, and the state of a room contains a
  1031. # 'm.room.retention' event in its state which contains a 'min_lifetime' or a
  1032. # 'max_lifetime' that's out of these bounds, Synapse will cap the room's policy
  1033. # to these limits when running purge jobs.
  1034. #
  1035. #allowed_lifetime_min: 1d
  1036. #allowed_lifetime_max: 1y
  1037. # Server admins can define the settings of the background jobs purging the
  1038. # events which lifetime has expired under the 'purge_jobs' section.
  1039. #
  1040. # If no configuration is provided, a single job will be set up to delete expired
  1041. # events in every room daily.
  1042. #
  1043. # Each job's configuration defines which range of message lifetimes the job
  1044. # takes care of. For example, if 'shortest_max_lifetime' is '2d' and
  1045. # 'longest_max_lifetime' is '3d', the job will handle purging expired events in
  1046. # rooms whose state defines a 'max_lifetime' that's both higher than 2 days, and
  1047. # lower than or equal to 3 days. Both the minimum and the maximum value of a
  1048. # range are optional, e.g. a job with no 'shortest_max_lifetime' and a
  1049. # 'longest_max_lifetime' of '3d' will handle every room with a retention policy
  1050. # which 'max_lifetime' is lower than or equal to three days.
  1051. #
  1052. # The rationale for this per-job configuration is that some rooms might have a
  1053. # retention policy with a low 'max_lifetime', where history needs to be purged
  1054. # of outdated messages on a more frequent basis than for the rest of the rooms
  1055. # (e.g. every 12h), but not want that purge to be performed by a job that's
  1056. # iterating over every room it knows, which could be heavy on the server.
  1057. #
  1058. # If any purge job is configured, it is strongly recommended to have at least
  1059. # a single job with neither 'shortest_max_lifetime' nor 'longest_max_lifetime'
  1060. # set, or one job without 'shortest_max_lifetime' and one job without
  1061. # 'longest_max_lifetime' set. Otherwise some rooms might be ignored, even if
  1062. # 'allowed_lifetime_min' and 'allowed_lifetime_max' are set, because capping a
  1063. # room's policy to these values is done after the policies are retrieved from
  1064. # Synapse's database (which is done using the range specified in a purge job's
  1065. # configuration).
  1066. #
  1067. #purge_jobs:
  1068. # - longest_max_lifetime: 3d
  1069. # interval: 12h
  1070. # - shortest_max_lifetime: 3d
  1071. # interval: 1d
  1072. # Inhibits the /requestToken endpoints from returning an error that might leak
  1073. # information about whether an e-mail address is in use or not on this
  1074. # homeserver.
  1075. # Note that for some endpoints the error situation is the e-mail already being
  1076. # used, and for others the error is entering the e-mail being unused.
  1077. # If this option is enabled, instead of returning an error, these endpoints will
  1078. # act as if no error happened and return a fake session ID ('sid') to clients.
  1079. #
  1080. #request_token_inhibit_3pid_errors: true
  1081. # A list of domains that the domain portion of 'next_link' parameters
  1082. # must match.
  1083. #
  1084. # This parameter is optionally provided by clients while requesting
  1085. # validation of an email or phone number, and maps to a link that
  1086. # users will be automatically redirected to after validation
  1087. # succeeds. Clients can make use this parameter to aid the validation
  1088. # process.
  1089. #
  1090. # The whitelist is applied whether the homeserver or an
  1091. # identity server is handling validation.
  1092. #
  1093. # The default value is no whitelist functionality; all domains are
  1094. # allowed. Setting this value to an empty list will instead disallow
  1095. # all domains.
  1096. #
  1097. #next_link_domain_whitelist: ["matrix.org"]
  1098. """
  1099. % locals()
  1100. )
  1101. def read_arguments(self, args):
  1102. if args.manhole is not None:
  1103. self.manhole = args.manhole
  1104. if args.daemonize is not None:
  1105. self.daemonize = args.daemonize
  1106. if args.print_pidfile is not None:
  1107. self.print_pidfile = args.print_pidfile
  1108. @staticmethod
  1109. def add_arguments(parser):
  1110. server_group = parser.add_argument_group("server")
  1111. server_group.add_argument(
  1112. "-D",
  1113. "--daemonize",
  1114. action="store_true",
  1115. default=None,
  1116. help="Daemonize the homeserver",
  1117. )
  1118. server_group.add_argument(
  1119. "--print-pidfile",
  1120. action="store_true",
  1121. default=None,
  1122. help="Print the path to the pidfile just before daemonizing",
  1123. )
  1124. server_group.add_argument(
  1125. "--manhole",
  1126. metavar="PORT",
  1127. dest="manhole",
  1128. type=int,
  1129. help="Turn on the twisted telnet manhole service on the given port.",
  1130. )
  1131. def read_gc_intervals(self, durations) -> Optional[Tuple[float, float, float]]:
  1132. """Reads the three durations for the GC min interval option, returning seconds."""
  1133. if durations is None:
  1134. return None
  1135. try:
  1136. if len(durations) != 3:
  1137. raise ValueError()
  1138. return (
  1139. self.parse_duration(durations[0]) / 1000,
  1140. self.parse_duration(durations[1]) / 1000,
  1141. self.parse_duration(durations[2]) / 1000,
  1142. )
  1143. except Exception:
  1144. raise ConfigError(
  1145. "Value of `gc_min_interval` must be a list of three durations if set"
  1146. )
  1147. def is_threepid_reserved(reserved_threepids, threepid):
  1148. """Check the threepid against the reserved threepid config
  1149. Args:
  1150. reserved_threepids([dict]) - list of reserved threepids
  1151. threepid(dict) - The threepid to test for
  1152. Returns:
  1153. boolean Is the threepid undertest reserved_user
  1154. """
  1155. for tp in reserved_threepids:
  1156. if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]:
  1157. return True
  1158. return False
  1159. def read_gc_thresholds(thresholds):
  1160. """Reads the three integer thresholds for garbage collection. Ensures that
  1161. the thresholds are integers if thresholds are supplied.
  1162. """
  1163. if thresholds is None:
  1164. return None
  1165. try:
  1166. assert len(thresholds) == 3
  1167. return (int(thresholds[0]), int(thresholds[1]), int(thresholds[2]))
  1168. except Exception:
  1169. raise ConfigError(
  1170. "Value of `gc_threshold` must be a list of three integers if set"
  1171. )
  1172. def parse_listener_def(listener: Any) -> ListenerConfig:
  1173. """parse a listener config from the config file"""
  1174. listener_type = listener["type"]
  1175. port = listener.get("port")
  1176. if not isinstance(port, int):
  1177. raise ConfigError("Listener configuration is lacking a valid 'port' option")
  1178. tls = listener.get("tls", False)
  1179. bind_addresses = listener.get("bind_addresses", [])
  1180. bind_address = listener.get("bind_address")
  1181. # if bind_address was specified, add it to the list of addresses
  1182. if bind_address:
  1183. bind_addresses.append(bind_address)
  1184. # if we still have an empty list of addresses, use the default list
  1185. if not bind_addresses:
  1186. if listener_type == "metrics":
  1187. # the metrics listener doesn't support IPv6
  1188. bind_addresses.append("0.0.0.0")
  1189. else:
  1190. bind_addresses.extend(DEFAULT_BIND_ADDRESSES)
  1191. http_config = None
  1192. if listener_type == "http":
  1193. http_config = HttpListenerConfig(
  1194. x_forwarded=listener.get("x_forwarded", False),
  1195. resources=[
  1196. HttpResourceConfig(**res) for res in listener.get("resources", [])
  1197. ],
  1198. additional_resources=listener.get("additional_resources", {}),
  1199. tag=listener.get("tag"),
  1200. )
  1201. return ListenerConfig(port, bind_addresses, listener_type, tls, http_config)
  1202. NO_MORE_WEB_CLIENT_WARNING = """
  1203. Synapse no longer includes a web client. To enable a web client, configure
  1204. web_client_location. To remove this warning, remove 'webclient' from the 'listeners'
  1205. configuration.
  1206. """
  1207. def _warn_if_webclient_configured(listeners: Iterable[ListenerConfig]) -> None:
  1208. for listener in listeners:
  1209. if not listener.http_options:
  1210. continue
  1211. for res in listener.http_options.resources:
  1212. for name in res.names:
  1213. if name == "webclient":
  1214. logger.warning(NO_MORE_WEB_CLIENT_WARNING)
  1215. return