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.
 
 
 
 
 
 

956 lines
35 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 urllib.parse
  19. from textwrap import indent
  20. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
  21. import attr
  22. import yaml
  23. from netaddr import AddrFormatError, IPNetwork, IPSet
  24. from twisted.conch.ssh.keys import Key
  25. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  26. from synapse.types import JsonDict
  27. from synapse.util.module_loader import load_module
  28. from synapse.util.stringutils import parse_and_validate_server_name
  29. from ._base import Config, ConfigError
  30. from ._util import validate_config
  31. logger = logging.Logger(__name__)
  32. DIRECT_TCP_ERROR = """
  33. Using direct TCP replication for workers is no longer supported.
  34. Please see https://matrix-org.github.io/synapse/latest/upgrade.html#direct-tcp-replication-is-no-longer-supported-migrate-to-redis
  35. """
  36. # by default, we attempt to listen on both '::' *and* '0.0.0.0' because some OSes
  37. # (Windows, macOS, other BSD/Linux where net.ipv6.bindv6only is set) will only listen
  38. # on IPv6 when '::' is set.
  39. #
  40. # We later check for errors when binding to 0.0.0.0 and ignore them if :: is also in
  41. # in the list.
  42. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"]
  43. def _6to4(network: IPNetwork) -> IPNetwork:
  44. """Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056."""
  45. # 6to4 networks consist of:
  46. # * 2002 as the first 16 bits
  47. # * The first IPv4 address in the network hex-encoded as the next 32 bits
  48. # * The new prefix length needs to include the bits from the 2002 prefix.
  49. hex_network = hex(network.first)[2:]
  50. hex_network = ("0" * (8 - len(hex_network))) + hex_network
  51. return IPNetwork(
  52. "2002:%s:%s::/%d"
  53. % (
  54. hex_network[:4],
  55. hex_network[4:],
  56. 16 + network.prefixlen,
  57. )
  58. )
  59. def generate_ip_set(
  60. ip_addresses: Optional[Iterable[str]],
  61. extra_addresses: Optional[Iterable[str]] = None,
  62. config_path: Optional[Iterable[str]] = None,
  63. ) -> IPSet:
  64. """
  65. Generate an IPSet from a list of IP addresses or CIDRs.
  66. Additionally, for each IPv4 network in the list of IP addresses, also
  67. includes the corresponding IPv6 networks.
  68. This includes:
  69. * IPv4-Compatible IPv6 Address (see RFC 4291, section 2.5.5.1)
  70. * IPv4-Mapped IPv6 Address (see RFC 4291, section 2.5.5.2)
  71. * 6to4 Address (see RFC 3056, section 2)
  72. Args:
  73. ip_addresses: An iterable of IP addresses or CIDRs.
  74. extra_addresses: An iterable of IP addresses or CIDRs.
  75. config_path: The path in the configuration for error messages.
  76. Returns:
  77. A new IP set.
  78. """
  79. result = IPSet()
  80. for ip in itertools.chain(ip_addresses or (), extra_addresses or ()):
  81. try:
  82. network = IPNetwork(ip)
  83. except AddrFormatError as e:
  84. raise ConfigError(
  85. "Invalid IP range provided: %s." % (ip,), config_path
  86. ) from e
  87. result.add(network)
  88. # It is possible that these already exist in the set, but that's OK.
  89. if ":" not in str(network):
  90. result.add(IPNetwork(network).ipv6(ipv4_compatible=True))
  91. result.add(IPNetwork(network).ipv6(ipv4_compatible=False))
  92. result.add(_6to4(network))
  93. return result
  94. # IP ranges that are considered private / unroutable / don't make sense.
  95. DEFAULT_IP_RANGE_BLACKLIST = [
  96. # Localhost
  97. "127.0.0.0/8",
  98. # Private networks.
  99. "10.0.0.0/8",
  100. "172.16.0.0/12",
  101. "192.168.0.0/16",
  102. # Carrier grade NAT.
  103. "100.64.0.0/10",
  104. # Address registry.
  105. "192.0.0.0/24",
  106. # Link-local networks.
  107. "169.254.0.0/16",
  108. # Formerly used for 6to4 relay.
  109. "192.88.99.0/24",
  110. # Testing networks.
  111. "198.18.0.0/15",
  112. "192.0.2.0/24",
  113. "198.51.100.0/24",
  114. "203.0.113.0/24",
  115. # Multicast.
  116. "224.0.0.0/4",
  117. # Localhost
  118. "::1/128",
  119. # Link-local addresses.
  120. "fe80::/10",
  121. # Unique local addresses.
  122. "fc00::/7",
  123. # Testing networks.
  124. "2001:db8::/32",
  125. # Multicast.
  126. "ff00::/8",
  127. # Site-local addresses
  128. "fec0::/10",
  129. ]
  130. DEFAULT_ROOM_VERSION = "10"
  131. ROOM_COMPLEXITY_TOO_GREAT = (
  132. "Your homeserver is unable to join rooms this large or complex. "
  133. "Please speak to your server administrator, or upgrade your instance "
  134. "to join this room."
  135. )
  136. METRICS_PORT_WARNING = """\
  137. The metrics_port configuration option is deprecated in Synapse 0.31 in favour of
  138. a listener. Please see
  139. https://matrix-org.github.io/synapse/latest/metrics-howto.html
  140. on how to configure the new listener.
  141. --------------------------------------------------------------------------------"""
  142. KNOWN_LISTENER_TYPES = {
  143. "http",
  144. "metrics",
  145. "manhole",
  146. }
  147. KNOWN_RESOURCES = {
  148. "client",
  149. "consent",
  150. "federation",
  151. "health",
  152. "keys",
  153. "media",
  154. "metrics",
  155. "openid",
  156. "replication",
  157. "static",
  158. }
  159. @attr.s(frozen=True)
  160. class HttpResourceConfig:
  161. names: List[str] = attr.ib(
  162. factory=list,
  163. validator=attr.validators.deep_iterable(attr.validators.in_(KNOWN_RESOURCES)),
  164. )
  165. compress: bool = attr.ib(
  166. default=False,
  167. validator=attr.validators.optional(attr.validators.instance_of(bool)), # type: ignore[arg-type]
  168. )
  169. @attr.s(slots=True, frozen=True, auto_attribs=True)
  170. class HttpListenerConfig:
  171. """Object describing the http-specific parts of the config of a listener"""
  172. x_forwarded: bool = False
  173. resources: List[HttpResourceConfig] = attr.Factory(list)
  174. additional_resources: Dict[str, dict] = attr.Factory(dict)
  175. tag: Optional[str] = None
  176. request_id_header: Optional[str] = None
  177. # If true, the listener will return CORS response headers compatible with MSC3886:
  178. # https://github.com/matrix-org/matrix-spec-proposals/pull/3886
  179. experimental_cors_msc3886: bool = False
  180. @attr.s(slots=True, frozen=True, auto_attribs=True)
  181. class ListenerConfig:
  182. """Object describing the configuration of a single listener."""
  183. port: int = attr.ib(validator=attr.validators.instance_of(int))
  184. bind_addresses: List[str]
  185. type: str = attr.ib(validator=attr.validators.in_(KNOWN_LISTENER_TYPES))
  186. tls: bool = False
  187. # http_options is only populated if type=http
  188. http_options: Optional[HttpListenerConfig] = None
  189. @attr.s(slots=True, frozen=True, auto_attribs=True)
  190. class ManholeConfig:
  191. """Object describing the configuration of the manhole"""
  192. username: str = attr.ib(validator=attr.validators.instance_of(str))
  193. password: str = attr.ib(validator=attr.validators.instance_of(str))
  194. priv_key: Optional[Key]
  195. pub_key: Optional[Key]
  196. @attr.s(frozen=True)
  197. class LimitRemoteRoomsConfig:
  198. enabled: bool = attr.ib(validator=attr.validators.instance_of(bool), default=False)
  199. complexity: Union[float, int] = attr.ib(
  200. validator=attr.validators.instance_of((float, int)), # noqa
  201. default=1.0,
  202. )
  203. complexity_error: str = attr.ib(
  204. validator=attr.validators.instance_of(str),
  205. default=ROOM_COMPLEXITY_TOO_GREAT,
  206. )
  207. admins_can_join: bool = attr.ib(
  208. validator=attr.validators.instance_of(bool), default=False
  209. )
  210. class ServerConfig(Config):
  211. section = "server"
  212. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  213. self.server_name = config["server_name"]
  214. self.server_context = config.get("server_context", None)
  215. try:
  216. parse_and_validate_server_name(self.server_name)
  217. except ValueError as e:
  218. raise ConfigError(str(e))
  219. self.pid_file = self.abspath(config.get("pid_file"))
  220. self.soft_file_limit = config.get("soft_file_limit", 0)
  221. self.daemonize = bool(config.get("daemonize"))
  222. self.print_pidfile = bool(config.get("print_pidfile"))
  223. self.user_agent_suffix = config.get("user_agent_suffix")
  224. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  225. self.serve_server_wellknown = config.get("serve_server_wellknown", False)
  226. # Whether we should serve a "client well-known":
  227. # (a) at .well-known/matrix/client on our client HTTP listener
  228. # (b) in the response to /login
  229. #
  230. # ... which together help ensure that clients use our public_baseurl instead of
  231. # whatever they were told by the user.
  232. #
  233. # For the sake of backwards compatibility with existing installations, this is
  234. # True if public_baseurl is specified explicitly, and otherwise False. (The
  235. # reasoning here is that we have no way of knowing that the default
  236. # public_baseurl is actually correct for existing installations - many things
  237. # will not work correctly, but that's (probably?) better than sending clients
  238. # to a completely broken URL.
  239. self.serve_client_wellknown = False
  240. public_baseurl = config.get("public_baseurl")
  241. if public_baseurl is None:
  242. public_baseurl = f"https://{self.server_name}/"
  243. logger.info("Using default public_baseurl %s", public_baseurl)
  244. else:
  245. self.serve_client_wellknown = True
  246. if public_baseurl[-1] != "/":
  247. public_baseurl += "/"
  248. self.public_baseurl = public_baseurl
  249. # check that public_baseurl is valid
  250. try:
  251. splits = urllib.parse.urlsplit(self.public_baseurl)
  252. except Exception as e:
  253. raise ConfigError(f"Unable to parse URL: {e}", ("public_baseurl",))
  254. if splits.scheme not in ("https", "http"):
  255. raise ConfigError(
  256. f"Invalid scheme '{splits.scheme}': only https and http are supported"
  257. )
  258. if splits.query or splits.fragment:
  259. raise ConfigError(
  260. "public_baseurl cannot contain query parameters or a #-fragment"
  261. )
  262. self.extra_well_known_client_content = config.get(
  263. "extra_well_known_client_content", {}
  264. )
  265. if not isinstance(self.extra_well_known_client_content, dict):
  266. raise ConfigError(
  267. "extra_well_known_content must be a dictionary of key-value pairs"
  268. )
  269. if "m.homeserver" in self.extra_well_known_client_content:
  270. raise ConfigError(
  271. "m.homeserver is not supported in extra_well_known_content, "
  272. "use public_baseurl in base config instead."
  273. )
  274. if "m.identity_server" in self.extra_well_known_client_content:
  275. raise ConfigError(
  276. "m.identity_server is not supported in extra_well_known_content, "
  277. "use default_identity_server in base config instead."
  278. )
  279. # Whether to enable user presence.
  280. presence_config = config.get("presence") or {}
  281. self.use_presence = presence_config.get("enabled")
  282. if self.use_presence is None:
  283. self.use_presence = config.get("use_presence", True)
  284. # Custom presence router module
  285. # This is the legacy way of configuring it (the config should now be put in the modules section)
  286. self.presence_router_module_class = None
  287. self.presence_router_config = None
  288. presence_router_config = presence_config.get("presence_router")
  289. if presence_router_config:
  290. (
  291. self.presence_router_module_class,
  292. self.presence_router_config,
  293. ) = load_module(presence_router_config, ("presence", "presence_router"))
  294. # whether to enable the media repository endpoints. This should be set
  295. # to false if the media repository is running as a separate endpoint;
  296. # doing so ensures that we will not run cache cleanup jobs on the
  297. # master, potentially causing inconsistency.
  298. self.enable_media_repo = config.get("enable_media_repo", True)
  299. # Whether to require authentication to retrieve profile data (avatars,
  300. # display names) of other users through the client API.
  301. self.require_auth_for_profile_requests = config.get(
  302. "require_auth_for_profile_requests", False
  303. )
  304. # Whether to require sharing a room with a user to retrieve their
  305. # profile data
  306. self.limit_profile_requests_to_users_who_share_rooms = config.get(
  307. "limit_profile_requests_to_users_who_share_rooms",
  308. False,
  309. )
  310. # Whether to retrieve and display profile data for a user when they
  311. # are invited to a room
  312. self.include_profile_data_on_invite = config.get(
  313. "include_profile_data_on_invite", True
  314. )
  315. if "restrict_public_rooms_to_local_users" in config and (
  316. "allow_public_rooms_without_auth" in config
  317. or "allow_public_rooms_over_federation" in config
  318. ):
  319. raise ConfigError(
  320. "Can't use 'restrict_public_rooms_to_local_users' if"
  321. " 'allow_public_rooms_without_auth' and/or"
  322. " 'allow_public_rooms_over_federation' is set."
  323. )
  324. # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This
  325. # flag is now obsolete but we need to check it for backward-compatibility.
  326. if config.get("restrict_public_rooms_to_local_users", False):
  327. self.allow_public_rooms_without_auth = False
  328. self.allow_public_rooms_over_federation = False
  329. else:
  330. # If set to 'true', removes the need for authentication to access the server's
  331. # public rooms directory through the client API, meaning that anyone can
  332. # query the room directory. Defaults to 'false'.
  333. self.allow_public_rooms_without_auth = config.get(
  334. "allow_public_rooms_without_auth", False
  335. )
  336. # If set to 'true', allows any other homeserver to fetch the server's public
  337. # rooms directory via federation. Defaults to 'false'.
  338. self.allow_public_rooms_over_federation = config.get(
  339. "allow_public_rooms_over_federation", False
  340. )
  341. default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION)
  342. # Ensure room version is a str
  343. default_room_version = str(default_room_version)
  344. if default_room_version not in KNOWN_ROOM_VERSIONS:
  345. raise ConfigError(
  346. "Unknown default_room_version: %s, known room versions: %s"
  347. % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys()))
  348. )
  349. # Get the actual room version object rather than just the identifier
  350. self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version]
  351. # whether to enable search. If disabled, new entries will not be inserted
  352. # into the search tables and they will not be indexed. Users will receive
  353. # errors when attempting to search for messages.
  354. self.enable_search = config.get("enable_search", True)
  355. self.filter_timeline_limit = config.get("filter_timeline_limit", 100)
  356. # Whether we should block invites sent to users on this server
  357. # (other than those sent by local server admins)
  358. self.block_non_admin_invites = config.get("block_non_admin_invites", False)
  359. # Options to control access by tracking MAU
  360. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  361. self.max_mau_value = 0
  362. if self.limit_usage_by_mau:
  363. self.max_mau_value = config.get("max_mau_value", 0)
  364. self.mau_stats_only = config.get("mau_stats_only", False)
  365. self.mau_limits_reserved_threepids = config.get(
  366. "mau_limit_reserved_threepids", []
  367. )
  368. self.mau_trial_days = config.get("mau_trial_days", 0)
  369. self.mau_appservice_trial_days = config.get("mau_appservice_trial_days", {})
  370. self.mau_limit_alerting = config.get("mau_limit_alerting", True)
  371. # How long to keep redacted events in the database in unredacted form
  372. # before redacting them.
  373. redaction_retention_period = config.get("redaction_retention_period", "7d")
  374. if redaction_retention_period is not None:
  375. self.redaction_retention_period: Optional[int] = self.parse_duration(
  376. redaction_retention_period
  377. )
  378. else:
  379. self.redaction_retention_period = None
  380. # How long to keep entries in the `users_ips` table.
  381. user_ips_max_age = config.get("user_ips_max_age", "28d")
  382. if user_ips_max_age is not None:
  383. self.user_ips_max_age: Optional[int] = self.parse_duration(user_ips_max_age)
  384. else:
  385. self.user_ips_max_age = None
  386. # Options to disable HS
  387. self.hs_disabled = config.get("hs_disabled", False)
  388. self.hs_disabled_message = config.get("hs_disabled_message", "")
  389. # Admin uri to direct users at should their instance become blocked
  390. # due to resource constraints
  391. self.admin_contact = config.get("admin_contact", None)
  392. ip_range_blacklist = config.get(
  393. "ip_range_blacklist", DEFAULT_IP_RANGE_BLACKLIST
  394. )
  395. # Attempt to create an IPSet from the given ranges
  396. # Always blacklist 0.0.0.0, ::
  397. self.ip_range_blacklist = generate_ip_set(
  398. ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",)
  399. )
  400. self.ip_range_whitelist = generate_ip_set(
  401. config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",)
  402. )
  403. # The federation_ip_range_blacklist is used for backwards-compatibility
  404. # and only applies to federation and identity servers.
  405. if "federation_ip_range_blacklist" in config:
  406. # Always blacklist 0.0.0.0, ::
  407. self.federation_ip_range_blacklist = generate_ip_set(
  408. config["federation_ip_range_blacklist"],
  409. ["0.0.0.0", "::"],
  410. config_path=("federation_ip_range_blacklist",),
  411. )
  412. # 'federation_ip_range_whitelist' was never a supported configuration option.
  413. self.federation_ip_range_whitelist = None
  414. else:
  415. # No backwards-compatiblity requrired, as federation_ip_range_blacklist
  416. # is not given. Default to ip_range_blacklist and ip_range_whitelist.
  417. self.federation_ip_range_blacklist = self.ip_range_blacklist
  418. self.federation_ip_range_whitelist = self.ip_range_whitelist
  419. # (undocumented) option for torturing the worker-mode replication a bit,
  420. # for testing. The value defines the number of milliseconds to pause before
  421. # sending out any replication updates.
  422. self.replication_torture_level = config.get("replication_torture_level")
  423. # Whether to require a user to be in the room to add an alias to it.
  424. # Defaults to True.
  425. self.require_membership_for_aliases = config.get(
  426. "require_membership_for_aliases", True
  427. )
  428. # Whether to allow per-room membership profiles through the send of membership
  429. # events with profile information that differ from the target's global profile.
  430. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True)
  431. # The maximum size an avatar can have, in bytes.
  432. self.max_avatar_size = config.get("max_avatar_size")
  433. if self.max_avatar_size is not None:
  434. self.max_avatar_size = self.parse_size(self.max_avatar_size)
  435. # The MIME types allowed for an avatar.
  436. self.allowed_avatar_mimetypes = config.get("allowed_avatar_mimetypes")
  437. if self.allowed_avatar_mimetypes and not isinstance(
  438. self.allowed_avatar_mimetypes,
  439. list,
  440. ):
  441. raise ConfigError("allowed_avatar_mimetypes must be a list")
  442. listeners = config.get("listeners", [])
  443. if not isinstance(listeners, list):
  444. raise ConfigError("Expected a list", ("listeners",))
  445. self.listeners = [parse_listener_def(i, x) for i, x in enumerate(listeners)]
  446. # no_tls is not really supported any more, but let's grandfather it in
  447. # here.
  448. if config.get("no_tls", False):
  449. l2 = []
  450. for listener in self.listeners:
  451. if listener.tls:
  452. logger.info(
  453. "Ignoring TLS-enabled listener on port %i due to no_tls",
  454. listener.port,
  455. )
  456. else:
  457. l2.append(listener)
  458. self.listeners = l2
  459. self.web_client_location = config.get("web_client_location", None)
  460. # Non-HTTP(S) web client location is not supported.
  461. if self.web_client_location and not (
  462. self.web_client_location.startswith("http://")
  463. or self.web_client_location.startswith("https://")
  464. ):
  465. raise ConfigError("web_client_location must point to a HTTP(S) URL.")
  466. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  467. self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None))
  468. self.limit_remote_rooms = LimitRemoteRoomsConfig(
  469. **(config.get("limit_remote_rooms") or {})
  470. )
  471. bind_port = config.get("bind_port")
  472. if bind_port:
  473. if config.get("no_tls", False):
  474. raise ConfigError("no_tls is incompatible with bind_port")
  475. self.listeners = []
  476. bind_host = config.get("bind_host", "")
  477. gzip_responses = config.get("gzip_responses", True)
  478. http_options = HttpListenerConfig(
  479. resources=[
  480. HttpResourceConfig(names=["client"], compress=gzip_responses),
  481. HttpResourceConfig(names=["federation"]),
  482. ],
  483. )
  484. self.listeners.append(
  485. ListenerConfig(
  486. port=bind_port,
  487. bind_addresses=[bind_host],
  488. tls=True,
  489. type="http",
  490. http_options=http_options,
  491. )
  492. )
  493. unsecure_port = config.get("unsecure_port", bind_port - 400)
  494. if unsecure_port:
  495. self.listeners.append(
  496. ListenerConfig(
  497. port=unsecure_port,
  498. bind_addresses=[bind_host],
  499. tls=False,
  500. type="http",
  501. http_options=http_options,
  502. )
  503. )
  504. manhole = config.get("manhole")
  505. if manhole:
  506. self.listeners.append(
  507. ListenerConfig(
  508. port=manhole,
  509. bind_addresses=["127.0.0.1"],
  510. type="manhole",
  511. )
  512. )
  513. manhole_settings = config.get("manhole_settings") or {}
  514. validate_config(
  515. _MANHOLE_SETTINGS_SCHEMA, manhole_settings, ("manhole_settings",)
  516. )
  517. manhole_username = manhole_settings.get("username", "matrix")
  518. manhole_password = manhole_settings.get("password", "rabbithole")
  519. manhole_priv_key_path = manhole_settings.get("ssh_priv_key_path")
  520. manhole_pub_key_path = manhole_settings.get("ssh_pub_key_path")
  521. manhole_priv_key = None
  522. if manhole_priv_key_path is not None:
  523. try:
  524. manhole_priv_key = Key.fromFile(manhole_priv_key_path)
  525. except Exception as e:
  526. raise ConfigError(
  527. f"Failed to read manhole private key file {manhole_priv_key_path}"
  528. ) from e
  529. manhole_pub_key = None
  530. if manhole_pub_key_path is not None:
  531. try:
  532. manhole_pub_key = Key.fromFile(manhole_pub_key_path)
  533. except Exception as e:
  534. raise ConfigError(
  535. f"Failed to read manhole public key file {manhole_pub_key_path}"
  536. ) from e
  537. self.manhole_settings = ManholeConfig(
  538. username=manhole_username,
  539. password=manhole_password,
  540. priv_key=manhole_priv_key,
  541. pub_key=manhole_pub_key,
  542. )
  543. metrics_port = config.get("metrics_port")
  544. if metrics_port:
  545. logger.warning(METRICS_PORT_WARNING)
  546. self.listeners.append(
  547. ListenerConfig(
  548. port=metrics_port,
  549. bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")],
  550. type="http",
  551. http_options=HttpListenerConfig(
  552. resources=[HttpResourceConfig(names=["metrics"])]
  553. ),
  554. )
  555. )
  556. self.cleanup_extremities_with_dummy_events = config.get(
  557. "cleanup_extremities_with_dummy_events", True
  558. )
  559. # The number of forward extremities in a room needed to send a dummy event.
  560. self.dummy_events_threshold = config.get("dummy_events_threshold", 10)
  561. self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False)
  562. # Inhibits the /requestToken endpoints from returning an error that might leak
  563. # information about whether an e-mail address is in use or not on this
  564. # homeserver, and instead return a 200 with a fake sid if this kind of error is
  565. # met, without sending anything.
  566. # This is a compromise between sending an email, which could be a spam vector,
  567. # and letting the client know which email address is bound to an account and
  568. # which one isn't.
  569. self.request_token_inhibit_3pid_errors = config.get(
  570. "request_token_inhibit_3pid_errors",
  571. False,
  572. )
  573. # Whitelist of domain names that given next_link parameters must have
  574. next_link_domain_whitelist: Optional[List[str]] = config.get(
  575. "next_link_domain_whitelist"
  576. )
  577. self.next_link_domain_whitelist: Optional[Set[str]] = None
  578. if next_link_domain_whitelist is not None:
  579. if not isinstance(next_link_domain_whitelist, list):
  580. raise ConfigError("'next_link_domain_whitelist' must be a list")
  581. # Turn the list into a set to improve lookup speed.
  582. self.next_link_domain_whitelist = set(next_link_domain_whitelist)
  583. templates_config = config.get("templates") or {}
  584. if not isinstance(templates_config, dict):
  585. raise ConfigError("The 'templates' section must be a dictionary")
  586. self.custom_template_directory: Optional[str] = templates_config.get(
  587. "custom_template_directory"
  588. )
  589. if self.custom_template_directory is not None and not isinstance(
  590. self.custom_template_directory, str
  591. ):
  592. raise ConfigError("'custom_template_directory' must be a string")
  593. self.use_account_validity_in_account_status: bool = (
  594. config.get("use_account_validity_in_account_status") or False
  595. )
  596. self.rooms_to_exclude_from_sync: List[str] = (
  597. config.get("exclude_rooms_from_sync") or []
  598. )
  599. delete_stale_devices_after: Optional[str] = (
  600. config.get("delete_stale_devices_after") or None
  601. )
  602. if delete_stale_devices_after is not None:
  603. self.delete_stale_devices_after: Optional[int] = self.parse_duration(
  604. delete_stale_devices_after
  605. )
  606. else:
  607. self.delete_stale_devices_after = None
  608. def has_tls_listener(self) -> bool:
  609. return any(listener.tls for listener in self.listeners)
  610. def generate_config_section(
  611. self,
  612. config_dir_path: str,
  613. data_dir_path: str,
  614. server_name: str,
  615. open_private_ports: bool,
  616. listeners: Optional[List[dict]],
  617. **kwargs: Any,
  618. ) -> str:
  619. _, bind_port = parse_and_validate_server_name(server_name)
  620. if bind_port is not None:
  621. unsecure_port = bind_port - 400
  622. else:
  623. bind_port = 8448
  624. unsecure_port = 8008
  625. pid_file = os.path.join(data_dir_path, "homeserver.pid")
  626. secure_listeners = []
  627. unsecure_listeners = []
  628. private_addresses = ["::1", "127.0.0.1"]
  629. if listeners:
  630. for listener in listeners:
  631. if listener["tls"]:
  632. secure_listeners.append(listener)
  633. else:
  634. # If we don't want open ports we need to bind the listeners
  635. # to some address other than 0.0.0.0. Here we chose to use
  636. # localhost.
  637. # If the addresses are already bound we won't overwrite them
  638. # however.
  639. if not open_private_ports:
  640. listener.setdefault("bind_addresses", private_addresses)
  641. unsecure_listeners.append(listener)
  642. secure_http_bindings = indent(
  643. yaml.dump(secure_listeners), " " * 10
  644. ).lstrip()
  645. unsecure_http_bindings = indent(
  646. yaml.dump(unsecure_listeners), " " * 10
  647. ).lstrip()
  648. if not unsecure_listeners:
  649. unsecure_http_bindings = (
  650. """- port: %(unsecure_port)s
  651. tls: false
  652. type: http
  653. x_forwarded: true"""
  654. % locals()
  655. )
  656. if not open_private_ports:
  657. unsecure_http_bindings += (
  658. "\n bind_addresses: ['::1', '127.0.0.1']"
  659. )
  660. unsecure_http_bindings += """
  661. resources:
  662. - names: [client, federation]
  663. compress: false"""
  664. if listeners:
  665. unsecure_http_bindings = ""
  666. if not secure_listeners:
  667. secure_http_bindings = ""
  668. return (
  669. """\
  670. server_name: "%(server_name)s"
  671. pid_file: %(pid_file)s
  672. listeners:
  673. %(secure_http_bindings)s
  674. %(unsecure_http_bindings)s
  675. """
  676. % locals()
  677. )
  678. def read_arguments(self, args: argparse.Namespace) -> None:
  679. if args.manhole is not None:
  680. self.manhole = args.manhole
  681. if args.daemonize is not None:
  682. self.daemonize = args.daemonize
  683. if args.print_pidfile is not None:
  684. self.print_pidfile = args.print_pidfile
  685. @staticmethod
  686. def add_arguments(parser: argparse.ArgumentParser) -> None:
  687. server_group = parser.add_argument_group("server")
  688. server_group.add_argument(
  689. "-D",
  690. "--daemonize",
  691. action="store_true",
  692. default=None,
  693. help="Daemonize the homeserver",
  694. )
  695. server_group.add_argument(
  696. "--print-pidfile",
  697. action="store_true",
  698. default=None,
  699. help="Print the path to the pidfile just before daemonizing",
  700. )
  701. server_group.add_argument(
  702. "--manhole",
  703. metavar="PORT",
  704. dest="manhole",
  705. type=int,
  706. help="Turn on the twisted telnet manhole service on the given port.",
  707. )
  708. def read_gc_intervals(self, durations: Any) -> Optional[Tuple[float, float, float]]:
  709. """Reads the three durations for the GC min interval option, returning seconds."""
  710. if durations is None:
  711. return None
  712. try:
  713. if len(durations) != 3:
  714. raise ValueError()
  715. return (
  716. self.parse_duration(durations[0]) / 1000,
  717. self.parse_duration(durations[1]) / 1000,
  718. self.parse_duration(durations[2]) / 1000,
  719. )
  720. except Exception:
  721. raise ConfigError(
  722. "Value of `gc_min_interval` must be a list of three durations if set"
  723. )
  724. def is_threepid_reserved(
  725. reserved_threepids: List[JsonDict], threepid: JsonDict
  726. ) -> bool:
  727. """Check the threepid against the reserved threepid config
  728. Args:
  729. reserved_threepids: List of reserved threepids
  730. threepid: The threepid to test for
  731. Returns:
  732. Is the threepid undertest reserved_user
  733. """
  734. for tp in reserved_threepids:
  735. if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]:
  736. return True
  737. return False
  738. def read_gc_thresholds(
  739. thresholds: Optional[List[Any]],
  740. ) -> Optional[Tuple[int, int, int]]:
  741. """Reads the three integer thresholds for garbage collection. Ensures that
  742. the thresholds are integers if thresholds are supplied.
  743. """
  744. if thresholds is None:
  745. return None
  746. try:
  747. assert len(thresholds) == 3
  748. return int(thresholds[0]), int(thresholds[1]), int(thresholds[2])
  749. except Exception:
  750. raise ConfigError(
  751. "Value of `gc_threshold` must be a list of three integers if set"
  752. )
  753. def parse_listener_def(num: int, listener: Any) -> ListenerConfig:
  754. """parse a listener config from the config file"""
  755. if not isinstance(listener, dict):
  756. raise ConfigError("Expected a dictionary", ("listeners", str(num)))
  757. listener_type = listener["type"]
  758. # Raise a helpful error if direct TCP replication is still configured.
  759. if listener_type == "replication":
  760. raise ConfigError(DIRECT_TCP_ERROR, ("listeners", str(num), "type"))
  761. port = listener.get("port")
  762. if type(port) is not int:
  763. raise ConfigError("Listener configuration is lacking a valid 'port' option")
  764. tls = listener.get("tls", False)
  765. bind_addresses = listener.get("bind_addresses", [])
  766. bind_address = listener.get("bind_address")
  767. # if bind_address was specified, add it to the list of addresses
  768. if bind_address:
  769. bind_addresses.append(bind_address)
  770. # if we still have an empty list of addresses, use the default list
  771. if not bind_addresses:
  772. if listener_type == "metrics":
  773. # the metrics listener doesn't support IPv6
  774. bind_addresses.append("0.0.0.0")
  775. else:
  776. bind_addresses.extend(DEFAULT_BIND_ADDRESSES)
  777. http_config = None
  778. if listener_type == "http":
  779. try:
  780. resources = [
  781. HttpResourceConfig(**res) for res in listener.get("resources", [])
  782. ]
  783. except ValueError as e:
  784. raise ConfigError("Unknown listener resource") from e
  785. http_config = HttpListenerConfig(
  786. x_forwarded=listener.get("x_forwarded", False),
  787. resources=resources,
  788. additional_resources=listener.get("additional_resources", {}),
  789. tag=listener.get("tag"),
  790. request_id_header=listener.get("request_id_header"),
  791. experimental_cors_msc3886=listener.get("experimental_cors_msc3886", False),
  792. )
  793. return ListenerConfig(port, bind_addresses, listener_type, tls, http_config)
  794. _MANHOLE_SETTINGS_SCHEMA = {
  795. "type": "object",
  796. "properties": {
  797. "username": {"type": "string"},
  798. "password": {"type": "string"},
  799. "ssh_priv_key_path": {"type": "string"},
  800. "ssh_pub_key_path": {"type": "string"},
  801. },
  802. }