您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

1034 行
38 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, StrSequence
  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[StrSequence] = 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_BLOCKLIST = [
  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 TCPListenerConfig:
  182. """Object describing the configuration of a single TCP listener."""
  183. port: int = attr.ib(validator=attr.validators.instance_of(int))
  184. bind_addresses: List[str] = attr.ib(validator=attr.validators.instance_of(List))
  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. def get_site_tag(self) -> str:
  190. """Retrieves http_options.tag if it exists, otherwise the port number."""
  191. if self.http_options and self.http_options.tag is not None:
  192. return self.http_options.tag
  193. else:
  194. return str(self.port)
  195. def is_tls(self) -> bool:
  196. return self.tls
  197. @attr.s(slots=True, frozen=True, auto_attribs=True)
  198. class UnixListenerConfig:
  199. """Object describing the configuration of a single Unix socket listener."""
  200. # Note: unix sockets can not be tls encrypted, so HAVE to be behind a tls-handling
  201. # reverse proxy
  202. path: str = attr.ib()
  203. # A default(0o666) for this is set in parse_listener_def() below
  204. mode: int
  205. type: str = attr.ib(validator=attr.validators.in_(KNOWN_LISTENER_TYPES))
  206. # http_options is only populated if type=http
  207. http_options: Optional[HttpListenerConfig] = None
  208. def get_site_tag(self) -> str:
  209. return "unix"
  210. def is_tls(self) -> bool:
  211. """Unix sockets can't have TLS"""
  212. return False
  213. ListenerConfig = Union[TCPListenerConfig, UnixListenerConfig]
  214. @attr.s(slots=True, frozen=True, auto_attribs=True)
  215. class ManholeConfig:
  216. """Object describing the configuration of the manhole"""
  217. username: str = attr.ib(validator=attr.validators.instance_of(str))
  218. password: str = attr.ib(validator=attr.validators.instance_of(str))
  219. priv_key: Optional[Key]
  220. pub_key: Optional[Key]
  221. @attr.s(frozen=True)
  222. class LimitRemoteRoomsConfig:
  223. enabled: bool = attr.ib(validator=attr.validators.instance_of(bool), default=False)
  224. complexity: Union[float, int] = attr.ib(
  225. validator=attr.validators.instance_of((float, int)), # noqa
  226. default=1.0,
  227. )
  228. complexity_error: str = attr.ib(
  229. validator=attr.validators.instance_of(str),
  230. default=ROOM_COMPLEXITY_TOO_GREAT,
  231. )
  232. admins_can_join: bool = attr.ib(
  233. validator=attr.validators.instance_of(bool), default=False
  234. )
  235. class ServerConfig(Config):
  236. section = "server"
  237. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  238. self.server_name = config["server_name"]
  239. self.server_context = config.get("server_context", None)
  240. try:
  241. parse_and_validate_server_name(self.server_name)
  242. except ValueError as e:
  243. raise ConfigError(str(e))
  244. self.pid_file = self.abspath(config.get("pid_file"))
  245. self.soft_file_limit = config.get("soft_file_limit", 0)
  246. self.daemonize = bool(config.get("daemonize"))
  247. self.print_pidfile = bool(config.get("print_pidfile"))
  248. self.user_agent_suffix = config.get("user_agent_suffix")
  249. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  250. self.serve_server_wellknown = config.get("serve_server_wellknown", False)
  251. # Whether we should serve a "client well-known":
  252. # (a) at .well-known/matrix/client on our client HTTP listener
  253. # (b) in the response to /login
  254. #
  255. # ... which together help ensure that clients use our public_baseurl instead of
  256. # whatever they were told by the user.
  257. #
  258. # For the sake of backwards compatibility with existing installations, this is
  259. # True if public_baseurl is specified explicitly, and otherwise False. (The
  260. # reasoning here is that we have no way of knowing that the default
  261. # public_baseurl is actually correct for existing installations - many things
  262. # will not work correctly, but that's (probably?) better than sending clients
  263. # to a completely broken URL.
  264. self.serve_client_wellknown = False
  265. public_baseurl = config.get("public_baseurl")
  266. if public_baseurl is None:
  267. public_baseurl = f"https://{self.server_name}/"
  268. logger.info("Using default public_baseurl %s", public_baseurl)
  269. else:
  270. self.serve_client_wellknown = True
  271. if public_baseurl[-1] != "/":
  272. public_baseurl += "/"
  273. self.public_baseurl = public_baseurl
  274. # check that public_baseurl is valid
  275. try:
  276. splits = urllib.parse.urlsplit(self.public_baseurl)
  277. except Exception as e:
  278. raise ConfigError(f"Unable to parse URL: {e}", ("public_baseurl",))
  279. if splits.scheme not in ("https", "http"):
  280. raise ConfigError(
  281. f"Invalid scheme '{splits.scheme}': only https and http are supported"
  282. )
  283. if splits.query or splits.fragment:
  284. raise ConfigError(
  285. "public_baseurl cannot contain query parameters or a #-fragment"
  286. )
  287. self.extra_well_known_client_content = config.get(
  288. "extra_well_known_client_content", {}
  289. )
  290. if not isinstance(self.extra_well_known_client_content, dict):
  291. raise ConfigError(
  292. "extra_well_known_content must be a dictionary of key-value pairs"
  293. )
  294. if "m.homeserver" in self.extra_well_known_client_content:
  295. raise ConfigError(
  296. "m.homeserver is not supported in extra_well_known_content, "
  297. "use public_baseurl in base config instead."
  298. )
  299. if "m.identity_server" in self.extra_well_known_client_content:
  300. raise ConfigError(
  301. "m.identity_server is not supported in extra_well_known_content, "
  302. "use default_identity_server in base config instead."
  303. )
  304. # Whether to enable user presence.
  305. presence_config = config.get("presence") or {}
  306. presence_enabled = presence_config.get("enabled")
  307. if presence_enabled is None:
  308. presence_enabled = config.get("use_presence", True)
  309. # Whether presence is enabled *at all*.
  310. self.presence_enabled = bool(presence_enabled)
  311. # Whether to internally track presence, requires that presence is enabled,
  312. self.track_presence = self.presence_enabled and presence_enabled != "untracked"
  313. # Custom presence router module
  314. # This is the legacy way of configuring it (the config should now be put in the modules section)
  315. self.presence_router_module_class = None
  316. self.presence_router_config = None
  317. presence_router_config = presence_config.get("presence_router")
  318. if presence_router_config:
  319. (
  320. self.presence_router_module_class,
  321. self.presence_router_config,
  322. ) = load_module(presence_router_config, ("presence", "presence_router"))
  323. # whether to enable the media repository endpoints. This should be set
  324. # to false if the media repository is running as a separate endpoint;
  325. # doing so ensures that we will not run cache cleanup jobs on the
  326. # master, potentially causing inconsistency.
  327. self.enable_media_repo = config.get("enable_media_repo", True)
  328. # Whether to require authentication to retrieve profile data (avatars,
  329. # display names) of other users through the client API.
  330. self.require_auth_for_profile_requests = config.get(
  331. "require_auth_for_profile_requests", False
  332. )
  333. # Whether to require sharing a room with a user to retrieve their
  334. # profile data
  335. self.limit_profile_requests_to_users_who_share_rooms = config.get(
  336. "limit_profile_requests_to_users_who_share_rooms",
  337. False,
  338. )
  339. # Whether to retrieve and display profile data for a user when they
  340. # are invited to a room
  341. self.include_profile_data_on_invite = config.get(
  342. "include_profile_data_on_invite", True
  343. )
  344. if "restrict_public_rooms_to_local_users" in config and (
  345. "allow_public_rooms_without_auth" in config
  346. or "allow_public_rooms_over_federation" in config
  347. ):
  348. raise ConfigError(
  349. "Can't use 'restrict_public_rooms_to_local_users' if"
  350. " 'allow_public_rooms_without_auth' and/or"
  351. " 'allow_public_rooms_over_federation' is set."
  352. )
  353. # Check if the legacy "restrict_public_rooms_to_local_users" flag is set. This
  354. # flag is now obsolete but we need to check it for backward-compatibility.
  355. if config.get("restrict_public_rooms_to_local_users", False):
  356. self.allow_public_rooms_without_auth = False
  357. self.allow_public_rooms_over_federation = False
  358. else:
  359. # If set to 'true', removes the need for authentication to access the server's
  360. # public rooms directory through the client API, meaning that anyone can
  361. # query the room directory. Defaults to 'false'.
  362. self.allow_public_rooms_without_auth = config.get(
  363. "allow_public_rooms_without_auth", False
  364. )
  365. # If set to 'true', allows any other homeserver to fetch the server's public
  366. # rooms directory via federation. Defaults to 'false'.
  367. self.allow_public_rooms_over_federation = config.get(
  368. "allow_public_rooms_over_federation", False
  369. )
  370. default_room_version = config.get("default_room_version", DEFAULT_ROOM_VERSION)
  371. # Ensure room version is a str
  372. default_room_version = str(default_room_version)
  373. if default_room_version not in KNOWN_ROOM_VERSIONS:
  374. raise ConfigError(
  375. "Unknown default_room_version: %s, known room versions: %s"
  376. % (default_room_version, list(KNOWN_ROOM_VERSIONS.keys()))
  377. )
  378. # Get the actual room version object rather than just the identifier
  379. self.default_room_version = KNOWN_ROOM_VERSIONS[default_room_version]
  380. # whether to enable search. If disabled, new entries will not be inserted
  381. # into the search tables and they will not be indexed. Users will receive
  382. # errors when attempting to search for messages.
  383. self.enable_search = config.get("enable_search", True)
  384. self.filter_timeline_limit = config.get("filter_timeline_limit", 100)
  385. # Whether we should block invites sent to users on this server
  386. # (other than those sent by local server admins)
  387. self.block_non_admin_invites = config.get("block_non_admin_invites", False)
  388. # Options to control access by tracking MAU
  389. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  390. self.max_mau_value = 0
  391. if self.limit_usage_by_mau:
  392. self.max_mau_value = config.get("max_mau_value", 0)
  393. self.mau_stats_only = config.get("mau_stats_only", False)
  394. self.mau_limits_reserved_threepids = config.get(
  395. "mau_limit_reserved_threepids", []
  396. )
  397. self.mau_trial_days = config.get("mau_trial_days", 0)
  398. self.mau_appservice_trial_days = config.get("mau_appservice_trial_days", {})
  399. self.mau_limit_alerting = config.get("mau_limit_alerting", True)
  400. # How long to keep redacted events in the database in unredacted form
  401. # before redacting them.
  402. redaction_retention_period = config.get("redaction_retention_period", "7d")
  403. if redaction_retention_period is not None:
  404. self.redaction_retention_period: Optional[int] = self.parse_duration(
  405. redaction_retention_period
  406. )
  407. else:
  408. self.redaction_retention_period = None
  409. # How long to keep locally forgotten rooms before purging them from the DB.
  410. forgotten_room_retention_period = config.get(
  411. "forgotten_room_retention_period", None
  412. )
  413. if forgotten_room_retention_period is not None:
  414. self.forgotten_room_retention_period: Optional[int] = self.parse_duration(
  415. forgotten_room_retention_period
  416. )
  417. else:
  418. self.forgotten_room_retention_period = None
  419. # How long to keep entries in the `users_ips` table.
  420. user_ips_max_age = config.get("user_ips_max_age", "28d")
  421. if user_ips_max_age is not None:
  422. self.user_ips_max_age: Optional[int] = self.parse_duration(user_ips_max_age)
  423. else:
  424. self.user_ips_max_age = None
  425. # Options to disable HS
  426. self.hs_disabled = config.get("hs_disabled", False)
  427. self.hs_disabled_message = config.get("hs_disabled_message", "")
  428. # Admin uri to direct users at should their instance become blocked
  429. # due to resource constraints
  430. self.admin_contact = config.get("admin_contact", None)
  431. ip_range_blocklist = config.get(
  432. "ip_range_blacklist", DEFAULT_IP_RANGE_BLOCKLIST
  433. )
  434. # Attempt to create an IPSet from the given ranges
  435. # Always block 0.0.0.0, ::
  436. self.ip_range_blocklist = generate_ip_set(
  437. ip_range_blocklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",)
  438. )
  439. self.ip_range_allowlist = generate_ip_set(
  440. config.get("ip_range_whitelist", ()), config_path=("ip_range_whitelist",)
  441. )
  442. # The federation_ip_range_blacklist is used for backwards-compatibility
  443. # and only applies to federation and identity servers.
  444. if "federation_ip_range_blacklist" in config:
  445. # Always block 0.0.0.0, ::
  446. self.federation_ip_range_blocklist = generate_ip_set(
  447. config["federation_ip_range_blacklist"],
  448. ["0.0.0.0", "::"],
  449. config_path=("federation_ip_range_blacklist",),
  450. )
  451. # 'federation_ip_range_whitelist' was never a supported configuration option.
  452. self.federation_ip_range_allowlist = None
  453. else:
  454. # No backwards-compatiblity requrired, as federation_ip_range_blacklist
  455. # is not given. Default to ip_range_blacklist and ip_range_whitelist.
  456. self.federation_ip_range_blocklist = self.ip_range_blocklist
  457. self.federation_ip_range_allowlist = self.ip_range_allowlist
  458. # (undocumented) option for torturing the worker-mode replication a bit,
  459. # for testing. The value defines the number of milliseconds to pause before
  460. # sending out any replication updates.
  461. self.replication_torture_level = config.get("replication_torture_level")
  462. # Whether to require a user to be in the room to add an alias to it.
  463. # Defaults to True.
  464. self.require_membership_for_aliases = config.get(
  465. "require_membership_for_aliases", True
  466. )
  467. # Whether to allow per-room membership profiles through the send of membership
  468. # events with profile information that differ from the target's global profile.
  469. self.allow_per_room_profiles = config.get("allow_per_room_profiles", True)
  470. # The maximum size an avatar can have, in bytes.
  471. self.max_avatar_size = config.get("max_avatar_size")
  472. if self.max_avatar_size is not None:
  473. self.max_avatar_size = self.parse_size(self.max_avatar_size)
  474. # The MIME types allowed for an avatar.
  475. self.allowed_avatar_mimetypes = config.get("allowed_avatar_mimetypes")
  476. if self.allowed_avatar_mimetypes and not isinstance(
  477. self.allowed_avatar_mimetypes,
  478. list,
  479. ):
  480. raise ConfigError("allowed_avatar_mimetypes must be a list")
  481. listeners = config.get("listeners", [])
  482. if not isinstance(listeners, list):
  483. raise ConfigError("Expected a list", ("listeners",))
  484. self.listeners = [parse_listener_def(i, x) for i, x in enumerate(listeners)]
  485. # no_tls is not really supported anymore, but let's grandfather it in here.
  486. if config.get("no_tls", False):
  487. l2 = []
  488. for listener in self.listeners:
  489. if isinstance(listener, TCPListenerConfig) and listener.tls:
  490. # Use isinstance() as the assertion this *has* a listener.port
  491. logger.info(
  492. "Ignoring TLS-enabled listener on port %i due to no_tls",
  493. listener.port,
  494. )
  495. else:
  496. l2.append(listener)
  497. self.listeners = l2
  498. self.web_client_location = config.get("web_client_location", None)
  499. # Non-HTTP(S) web client location is not supported.
  500. if self.web_client_location and not (
  501. self.web_client_location.startswith("http://")
  502. or self.web_client_location.startswith("https://")
  503. ):
  504. raise ConfigError("web_client_location must point to a HTTP(S) URL.")
  505. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  506. self.gc_seconds = self.read_gc_intervals(config.get("gc_min_interval", None))
  507. self.limit_remote_rooms = LimitRemoteRoomsConfig(
  508. **(config.get("limit_remote_rooms") or {})
  509. )
  510. bind_port = config.get("bind_port")
  511. if bind_port:
  512. if config.get("no_tls", False):
  513. raise ConfigError("no_tls is incompatible with bind_port")
  514. self.listeners = []
  515. bind_host = config.get("bind_host", "")
  516. gzip_responses = config.get("gzip_responses", True)
  517. http_options = HttpListenerConfig(
  518. resources=[
  519. HttpResourceConfig(names=["client"], compress=gzip_responses),
  520. HttpResourceConfig(names=["federation"]),
  521. ],
  522. )
  523. self.listeners.append(
  524. TCPListenerConfig(
  525. port=bind_port,
  526. bind_addresses=[bind_host],
  527. tls=True,
  528. type="http",
  529. http_options=http_options,
  530. )
  531. )
  532. unsecure_port = config.get("unsecure_port", bind_port - 400)
  533. if unsecure_port:
  534. self.listeners.append(
  535. TCPListenerConfig(
  536. port=unsecure_port,
  537. bind_addresses=[bind_host],
  538. tls=False,
  539. type="http",
  540. http_options=http_options,
  541. )
  542. )
  543. manhole = config.get("manhole")
  544. if manhole:
  545. self.listeners.append(
  546. TCPListenerConfig(
  547. port=manhole,
  548. bind_addresses=["127.0.0.1"],
  549. type="manhole",
  550. )
  551. )
  552. manhole_settings = config.get("manhole_settings") or {}
  553. validate_config(
  554. _MANHOLE_SETTINGS_SCHEMA, manhole_settings, ("manhole_settings",)
  555. )
  556. manhole_username = manhole_settings.get("username", "matrix")
  557. manhole_password = manhole_settings.get("password", "rabbithole")
  558. manhole_priv_key_path = manhole_settings.get("ssh_priv_key_path")
  559. manhole_pub_key_path = manhole_settings.get("ssh_pub_key_path")
  560. manhole_priv_key = None
  561. if manhole_priv_key_path is not None:
  562. try:
  563. manhole_priv_key = Key.fromFile(manhole_priv_key_path)
  564. except Exception as e:
  565. raise ConfigError(
  566. f"Failed to read manhole private key file {manhole_priv_key_path}"
  567. ) from e
  568. manhole_pub_key = None
  569. if manhole_pub_key_path is not None:
  570. try:
  571. manhole_pub_key = Key.fromFile(manhole_pub_key_path)
  572. except Exception as e:
  573. raise ConfigError(
  574. f"Failed to read manhole public key file {manhole_pub_key_path}"
  575. ) from e
  576. self.manhole_settings = ManholeConfig(
  577. username=manhole_username,
  578. password=manhole_password,
  579. priv_key=manhole_priv_key,
  580. pub_key=manhole_pub_key,
  581. )
  582. metrics_port = config.get("metrics_port")
  583. if metrics_port:
  584. logger.warning(METRICS_PORT_WARNING)
  585. self.listeners.append(
  586. TCPListenerConfig(
  587. port=metrics_port,
  588. bind_addresses=[config.get("metrics_bind_host", "127.0.0.1")],
  589. type="http",
  590. http_options=HttpListenerConfig(
  591. resources=[HttpResourceConfig(names=["metrics"])]
  592. ),
  593. )
  594. )
  595. self.cleanup_extremities_with_dummy_events = config.get(
  596. "cleanup_extremities_with_dummy_events", True
  597. )
  598. # The number of forward extremities in a room needed to send a dummy event.
  599. self.dummy_events_threshold = config.get("dummy_events_threshold", 10)
  600. self.enable_ephemeral_messages = config.get("enable_ephemeral_messages", False)
  601. # Inhibits the /requestToken endpoints from returning an error that might leak
  602. # information about whether an e-mail address is in use or not on this
  603. # homeserver, and instead return a 200 with a fake sid if this kind of error is
  604. # met, without sending anything.
  605. # This is a compromise between sending an email, which could be a spam vector,
  606. # and letting the client know which email address is bound to an account and
  607. # which one isn't.
  608. self.request_token_inhibit_3pid_errors = config.get(
  609. "request_token_inhibit_3pid_errors",
  610. False,
  611. )
  612. # Whitelist of domain names that given next_link parameters must have
  613. next_link_domain_whitelist: Optional[List[str]] = config.get(
  614. "next_link_domain_whitelist"
  615. )
  616. self.next_link_domain_whitelist: Optional[Set[str]] = None
  617. if next_link_domain_whitelist is not None:
  618. if not isinstance(next_link_domain_whitelist, list):
  619. raise ConfigError("'next_link_domain_whitelist' must be a list")
  620. # Turn the list into a set to improve lookup speed.
  621. self.next_link_domain_whitelist = set(next_link_domain_whitelist)
  622. templates_config = config.get("templates") or {}
  623. if not isinstance(templates_config, dict):
  624. raise ConfigError("The 'templates' section must be a dictionary")
  625. self.custom_template_directory: Optional[str] = templates_config.get(
  626. "custom_template_directory"
  627. )
  628. if self.custom_template_directory is not None and not isinstance(
  629. self.custom_template_directory, str
  630. ):
  631. raise ConfigError("'custom_template_directory' must be a string")
  632. self.use_account_validity_in_account_status: bool = (
  633. config.get("use_account_validity_in_account_status") or False
  634. )
  635. self.rooms_to_exclude_from_sync: List[str] = (
  636. config.get("exclude_rooms_from_sync") or []
  637. )
  638. delete_stale_devices_after: Optional[str] = (
  639. config.get("delete_stale_devices_after") or None
  640. )
  641. if delete_stale_devices_after is not None:
  642. self.delete_stale_devices_after: Optional[int] = self.parse_duration(
  643. delete_stale_devices_after
  644. )
  645. else:
  646. self.delete_stale_devices_after = None
  647. def has_tls_listener(self) -> bool:
  648. return any(listener.is_tls() for listener in self.listeners)
  649. def generate_config_section(
  650. self,
  651. config_dir_path: str,
  652. data_dir_path: str,
  653. server_name: str,
  654. open_private_ports: bool,
  655. listeners: Optional[List[dict]],
  656. **kwargs: Any,
  657. ) -> str:
  658. _, bind_port = parse_and_validate_server_name(server_name)
  659. if bind_port is not None:
  660. unsecure_port = bind_port - 400
  661. else:
  662. bind_port = 8448
  663. unsecure_port = 8008
  664. pid_file = os.path.join(data_dir_path, "homeserver.pid")
  665. secure_listeners = []
  666. unsecure_listeners = []
  667. private_addresses = ["::1", "127.0.0.1"]
  668. if listeners:
  669. for listener in listeners:
  670. if listener["tls"]:
  671. secure_listeners.append(listener)
  672. else:
  673. # If we don't want open ports we need to bind the listeners
  674. # to some address other than 0.0.0.0. Here we chose to use
  675. # localhost.
  676. # If the addresses are already bound we won't overwrite them
  677. # however.
  678. if not open_private_ports:
  679. listener.setdefault("bind_addresses", private_addresses)
  680. unsecure_listeners.append(listener)
  681. secure_http_bindings = indent(
  682. yaml.dump(secure_listeners), " " * 10
  683. ).lstrip()
  684. unsecure_http_bindings = indent(
  685. yaml.dump(unsecure_listeners), " " * 10
  686. ).lstrip()
  687. if not unsecure_listeners:
  688. unsecure_http_bindings = (
  689. """- port: %(unsecure_port)s
  690. tls: false
  691. type: http
  692. x_forwarded: true"""
  693. % locals()
  694. )
  695. if not open_private_ports:
  696. unsecure_http_bindings += (
  697. "\n bind_addresses: ['::1', '127.0.0.1']"
  698. )
  699. unsecure_http_bindings += """
  700. resources:
  701. - names: [client, federation]
  702. compress: false"""
  703. if listeners:
  704. unsecure_http_bindings = ""
  705. if not secure_listeners:
  706. secure_http_bindings = ""
  707. return (
  708. """\
  709. server_name: "%(server_name)s"
  710. pid_file: %(pid_file)s
  711. listeners:
  712. %(secure_http_bindings)s
  713. %(unsecure_http_bindings)s
  714. """
  715. % locals()
  716. )
  717. def read_arguments(self, args: argparse.Namespace) -> None:
  718. if args.manhole is not None:
  719. self.manhole = args.manhole
  720. if args.daemonize is not None:
  721. self.daemonize = args.daemonize
  722. if args.print_pidfile is not None:
  723. self.print_pidfile = args.print_pidfile
  724. @staticmethod
  725. def add_arguments(parser: argparse.ArgumentParser) -> None:
  726. server_group = parser.add_argument_group("server")
  727. server_group.add_argument(
  728. "-D",
  729. "--daemonize",
  730. action="store_true",
  731. default=None,
  732. help="Daemonize the homeserver",
  733. )
  734. server_group.add_argument(
  735. "--print-pidfile",
  736. action="store_true",
  737. default=None,
  738. help="Print the path to the pidfile just before daemonizing",
  739. )
  740. server_group.add_argument(
  741. "--manhole",
  742. metavar="PORT",
  743. dest="manhole",
  744. type=int,
  745. help="Turn on the twisted telnet manhole service on the given port.",
  746. )
  747. def read_gc_intervals(self, durations: Any) -> Optional[Tuple[float, float, float]]:
  748. """Reads the three durations for the GC min interval option, returning seconds."""
  749. if durations is None:
  750. return None
  751. try:
  752. if len(durations) != 3:
  753. raise ValueError()
  754. return (
  755. self.parse_duration(durations[0]) / 1000,
  756. self.parse_duration(durations[1]) / 1000,
  757. self.parse_duration(durations[2]) / 1000,
  758. )
  759. except Exception:
  760. raise ConfigError(
  761. "Value of `gc_min_interval` must be a list of three durations if set"
  762. )
  763. def is_threepid_reserved(
  764. reserved_threepids: List[JsonDict], threepid: JsonDict
  765. ) -> bool:
  766. """Check the threepid against the reserved threepid config
  767. Args:
  768. reserved_threepids: List of reserved threepids
  769. threepid: The threepid to test for
  770. Returns:
  771. Is the threepid undertest reserved_user
  772. """
  773. for tp in reserved_threepids:
  774. if threepid["medium"] == tp["medium"] and threepid["address"] == tp["address"]:
  775. return True
  776. return False
  777. def read_gc_thresholds(
  778. thresholds: Optional[List[Any]],
  779. ) -> Optional[Tuple[int, int, int]]:
  780. """Reads the three integer thresholds for garbage collection. Ensures that
  781. the thresholds are integers if thresholds are supplied.
  782. """
  783. if thresholds is None:
  784. return None
  785. try:
  786. assert len(thresholds) == 3
  787. return int(thresholds[0]), int(thresholds[1]), int(thresholds[2])
  788. except Exception:
  789. raise ConfigError(
  790. "Value of `gc_threshold` must be a list of three integers if set"
  791. )
  792. def parse_listener_def(num: int, listener: Any) -> ListenerConfig:
  793. """parse a listener config from the config file"""
  794. if not isinstance(listener, dict):
  795. raise ConfigError("Expected a dictionary", ("listeners", str(num)))
  796. listener_type = listener["type"]
  797. # Raise a helpful error if direct TCP replication is still configured.
  798. if listener_type == "replication":
  799. raise ConfigError(DIRECT_TCP_ERROR, ("listeners", str(num), "type"))
  800. port = listener.get("port")
  801. socket_path = listener.get("path")
  802. # Either a port or a path should be declared at a minimum. Using both would be bad.
  803. if port is not None and not isinstance(port, int):
  804. raise ConfigError("Listener configuration is lacking a valid 'port' option")
  805. if socket_path is not None and not isinstance(socket_path, str):
  806. raise ConfigError("Listener configuration is lacking a valid 'path' option")
  807. if port and socket_path:
  808. raise ConfigError(
  809. "Can not have both a UNIX socket and an IP/port declared for the same "
  810. "resource!"
  811. )
  812. if port is None and socket_path is None:
  813. raise ConfigError(
  814. "Must have either a UNIX socket or an IP/port declared for a given "
  815. "resource!"
  816. )
  817. tls = listener.get("tls", False)
  818. http_config = None
  819. if listener_type == "http":
  820. try:
  821. resources = [
  822. HttpResourceConfig(**res) for res in listener.get("resources", [])
  823. ]
  824. except ValueError as e:
  825. raise ConfigError("Unknown listener resource") from e
  826. # For a unix socket, default x_forwarded to True, as this is the only way of
  827. # getting a client IP.
  828. # Note: a reverse proxy is required anyway, as there is no way of exposing a
  829. # unix socket to the internet.
  830. http_config = HttpListenerConfig(
  831. x_forwarded=listener.get("x_forwarded", (True if socket_path else False)),
  832. resources=resources,
  833. additional_resources=listener.get("additional_resources", {}),
  834. tag=listener.get("tag"),
  835. request_id_header=listener.get("request_id_header"),
  836. experimental_cors_msc3886=listener.get("experimental_cors_msc3886", False),
  837. )
  838. if socket_path:
  839. # TODO: Add in path validation, like if the directory exists and is writable?
  840. # Set a default for the permission, in case it's left out
  841. socket_mode = listener.get("mode", 0o666)
  842. return UnixListenerConfig(socket_path, socket_mode, listener_type, http_config)
  843. else:
  844. assert port is not None
  845. bind_addresses = listener.get("bind_addresses", [])
  846. bind_address = listener.get("bind_address")
  847. # if bind_address was specified, add it to the list of addresses
  848. if bind_address:
  849. bind_addresses.append(bind_address)
  850. # if we still have an empty list of addresses, use the default list
  851. if not bind_addresses:
  852. if listener_type == "metrics":
  853. # the metrics listener doesn't support IPv6
  854. bind_addresses.append("0.0.0.0")
  855. else:
  856. bind_addresses.extend(DEFAULT_BIND_ADDRESSES)
  857. return TCPListenerConfig(port, bind_addresses, listener_type, tls, http_config)
  858. _MANHOLE_SETTINGS_SCHEMA = {
  859. "type": "object",
  860. "properties": {
  861. "username": {"type": "string"},
  862. "password": {"type": "string"},
  863. "ssh_priv_key_path": {"type": "string"},
  864. "ssh_pub_key_path": {"type": "string"},
  865. },
  866. }