Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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