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.
 
 
 
 
 
 

1405 lines
54 KiB

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