server.py 51 KB

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