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

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