Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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