server.py 53 KB

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