server.py 53 KB

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