server.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import os.path
  18. from synapse.http.endpoint import parse_and_validate_server_name
  19. from synapse.python_dependencies import DependencyException, check_requirements
  20. from ._base import Config, ConfigError
  21. logger = logging.Logger(__name__)
  22. class ServerConfig(Config):
  23. def read_config(self, config):
  24. self.server_name = config["server_name"]
  25. try:
  26. parse_and_validate_server_name(self.server_name)
  27. except ValueError as e:
  28. raise ConfigError(str(e))
  29. self.pid_file = self.abspath(config.get("pid_file"))
  30. self.web_client_location = config.get("web_client_location", None)
  31. self.soft_file_limit = config["soft_file_limit"]
  32. self.daemonize = config.get("daemonize")
  33. self.print_pidfile = config.get("print_pidfile")
  34. self.user_agent_suffix = config.get("user_agent_suffix")
  35. self.use_frozen_dicts = config.get("use_frozen_dicts", False)
  36. self.public_baseurl = config.get("public_baseurl")
  37. self.cpu_affinity = config.get("cpu_affinity")
  38. # Whether to send federation traffic out in this process. This only
  39. # applies to some federation traffic, and so shouldn't be used to
  40. # "disable" federation
  41. self.send_federation = config.get("send_federation", True)
  42. # Whether to enable user presence.
  43. self.use_presence = config.get("use_presence", True)
  44. # Whether to update the user directory or not. This should be set to
  45. # false only if we are updating the user directory in a worker
  46. self.update_user_directory = config.get("update_user_directory", True)
  47. # whether to enable the media repository endpoints. This should be set
  48. # to false if the media repository is running as a separate endpoint;
  49. # doing so ensures that we will not run cache cleanup jobs on the
  50. # master, potentially causing inconsistency.
  51. self.enable_media_repo = config.get("enable_media_repo", True)
  52. # whether to enable search. If disabled, new entries will not be inserted
  53. # into the search tables and they will not be indexed. Users will receive
  54. # errors when attempting to search for messages.
  55. self.enable_search = config.get("enable_search", True)
  56. self.filter_timeline_limit = config.get("filter_timeline_limit", -1)
  57. # Whether we should block invites sent to users on this server
  58. # (other than those sent by local server admins)
  59. self.block_non_admin_invites = config.get(
  60. "block_non_admin_invites", False,
  61. )
  62. # Options to control access by tracking MAU
  63. self.limit_usage_by_mau = config.get("limit_usage_by_mau", False)
  64. self.max_mau_value = 0
  65. if self.limit_usage_by_mau:
  66. self.max_mau_value = config.get(
  67. "max_mau_value", 0,
  68. )
  69. self.mau_stats_only = config.get("mau_stats_only", False)
  70. self.mau_limits_reserved_threepids = config.get(
  71. "mau_limit_reserved_threepids", []
  72. )
  73. self.mau_trial_days = config.get(
  74. "mau_trial_days", 0,
  75. )
  76. # Options to disable HS
  77. self.hs_disabled = config.get("hs_disabled", False)
  78. self.hs_disabled_message = config.get("hs_disabled_message", "")
  79. self.hs_disabled_limit_type = config.get("hs_disabled_limit_type", "")
  80. # Admin uri to direct users at should their instance become blocked
  81. # due to resource constraints
  82. self.admin_contact = config.get("admin_contact", None)
  83. # FIXME: federation_domain_whitelist needs sytests
  84. self.federation_domain_whitelist = None
  85. federation_domain_whitelist = config.get(
  86. "federation_domain_whitelist", None
  87. )
  88. # turn the whitelist into a hash for speed of lookup
  89. if federation_domain_whitelist is not None:
  90. self.federation_domain_whitelist = {}
  91. for domain in federation_domain_whitelist:
  92. self.federation_domain_whitelist[domain] = True
  93. if self.public_baseurl is not None:
  94. if self.public_baseurl[-1] != '/':
  95. self.public_baseurl += '/'
  96. self.start_pushers = config.get("start_pushers", True)
  97. self.listeners = config.get("listeners", [])
  98. for listener in self.listeners:
  99. bind_address = listener.pop("bind_address", None)
  100. bind_addresses = listener.setdefault("bind_addresses", [])
  101. if bind_address:
  102. bind_addresses.append(bind_address)
  103. elif not bind_addresses:
  104. bind_addresses.append('')
  105. if not self.web_client_location:
  106. _warn_if_webclient_configured(self.listeners)
  107. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  108. bind_port = config.get("bind_port")
  109. if bind_port:
  110. self.listeners = []
  111. bind_host = config.get("bind_host", "")
  112. gzip_responses = config.get("gzip_responses", True)
  113. self.listeners.append({
  114. "port": bind_port,
  115. "bind_addresses": [bind_host],
  116. "tls": True,
  117. "type": "http",
  118. "resources": [
  119. {
  120. "names": ["client"],
  121. "compress": gzip_responses,
  122. },
  123. {
  124. "names": ["federation"],
  125. "compress": False,
  126. }
  127. ]
  128. })
  129. unsecure_port = config.get("unsecure_port", bind_port - 400)
  130. if unsecure_port:
  131. self.listeners.append({
  132. "port": unsecure_port,
  133. "bind_addresses": [bind_host],
  134. "tls": False,
  135. "type": "http",
  136. "resources": [
  137. {
  138. "names": ["client"],
  139. "compress": gzip_responses,
  140. },
  141. {
  142. "names": ["federation"],
  143. "compress": False,
  144. }
  145. ]
  146. })
  147. manhole = config.get("manhole")
  148. if manhole:
  149. self.listeners.append({
  150. "port": manhole,
  151. "bind_addresses": ["127.0.0.1"],
  152. "type": "manhole",
  153. })
  154. metrics_port = config.get("metrics_port")
  155. if metrics_port:
  156. logger.warn(
  157. ("The metrics_port configuration option is deprecated in Synapse 0.31 "
  158. "in favour of a listener. Please see "
  159. "http://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.rst"
  160. " on how to configure the new listener."))
  161. self.listeners.append({
  162. "port": metrics_port,
  163. "bind_addresses": [config.get("metrics_bind_host", "127.0.0.1")],
  164. "tls": False,
  165. "type": "http",
  166. "resources": [
  167. {
  168. "names": ["metrics"],
  169. "compress": False,
  170. },
  171. ]
  172. })
  173. _check_resource_config(self.listeners)
  174. def default_config(self, server_name, data_dir_path, **kwargs):
  175. _, bind_port = parse_and_validate_server_name(server_name)
  176. if bind_port is not None:
  177. unsecure_port = bind_port - 400
  178. else:
  179. bind_port = 8448
  180. unsecure_port = 8008
  181. pid_file = os.path.join(data_dir_path, "homeserver.pid")
  182. return """\
  183. ## Server ##
  184. # The domain name of the server, with optional explicit port.
  185. # This is used by remote servers to connect to this server,
  186. # e.g. matrix.org, localhost:8080, etc.
  187. # This is also the last part of your UserID.
  188. server_name: "%(server_name)s"
  189. # When running as a daemon, the file to store the pid in
  190. pid_file: %(pid_file)s
  191. # CPU affinity mask. Setting this restricts the CPUs on which the
  192. # process will be scheduled. It is represented as a bitmask, with the
  193. # lowest order bit corresponding to the first logical CPU and the
  194. # highest order bit corresponding to the last logical CPU. Not all CPUs
  195. # may exist on a given system but a mask may specify more CPUs than are
  196. # present.
  197. #
  198. # For example:
  199. # 0x00000001 is processor #0,
  200. # 0x00000003 is processors #0 and #1,
  201. # 0xFFFFFFFF is all processors (#0 through #31).
  202. #
  203. # Pinning a Python process to a single CPU is desirable, because Python
  204. # is inherently single-threaded due to the GIL, and can suffer a
  205. # 30-40%% slowdown due to cache blow-out and thread context switching
  206. # if the scheduler happens to schedule the underlying threads across
  207. # different cores. See
  208. # https://www.mirantis.com/blog/improve-performance-python-programs-restricting-single-cpu/.
  209. #
  210. # This setting requires the affinity package to be installed!
  211. #
  212. # cpu_affinity: 0xFFFFFFFF
  213. # The path to the web client which will be served at /_matrix/client/
  214. # if 'webclient' is configured under the 'listeners' configuration.
  215. #
  216. # web_client_location: "/path/to/web/root"
  217. # The public-facing base URL for the client API (not including _matrix/...)
  218. # public_baseurl: https://example.com:8448/
  219. # Set the soft limit on the number of file descriptors synapse can use
  220. # Zero is used to indicate synapse should set the soft limit to the
  221. # hard limit.
  222. soft_file_limit: 0
  223. # Set to false to disable presence tracking on this homeserver.
  224. use_presence: true
  225. # The GC threshold parameters to pass to `gc.set_threshold`, if defined
  226. # gc_thresholds: [700, 10, 10]
  227. # Set the limit on the returned events in the timeline in the get
  228. # and sync operations. The default value is -1, means no upper limit.
  229. # filter_timeline_limit: 5000
  230. # Whether room invites to users on this server should be blocked
  231. # (except those sent by local server admins). The default is False.
  232. # block_non_admin_invites: True
  233. # Restrict federation to the following whitelist of domains.
  234. # N.B. we recommend also firewalling your federation listener to limit
  235. # inbound federation traffic as early as possible, rather than relying
  236. # purely on this application-layer restriction. If not specified, the
  237. # default is to whitelist everything.
  238. #
  239. # federation_domain_whitelist:
  240. # - lon.example.com
  241. # - nyc.example.com
  242. # - syd.example.com
  243. # List of ports that Synapse should listen on, their purpose and their
  244. # configuration.
  245. listeners:
  246. # Main HTTPS listener
  247. # For when matrix traffic is sent directly to synapse.
  248. -
  249. # The port to listen for HTTPS requests on.
  250. port: %(bind_port)s
  251. # Local addresses to listen on.
  252. # On Linux and Mac OS, `::` will listen on all IPv4 and IPv6
  253. # addresses by default. For most other OSes, this will only listen
  254. # on IPv6.
  255. bind_addresses:
  256. - '::'
  257. - '0.0.0.0'
  258. # This is a 'http' listener, allows us to specify 'resources'.
  259. type: http
  260. tls: true
  261. # Use the X-Forwarded-For (XFF) header as the client IP and not the
  262. # actual client IP.
  263. x_forwarded: false
  264. # List of HTTP resources to serve on this listener.
  265. resources:
  266. -
  267. # List of resources to host on this listener.
  268. names:
  269. - client # The client-server APIs, both v1 and v2
  270. # - webclient # A web client. Requires web_client_location to be set.
  271. # Should synapse compress HTTP responses to clients that support it?
  272. # This should be disabled if running synapse behind a load balancer
  273. # that can do automatic compression.
  274. compress: true
  275. - names: [federation] # Federation APIs
  276. compress: false
  277. # optional list of additional endpoints which can be loaded via
  278. # dynamic modules
  279. # additional_resources:
  280. # "/_matrix/my/custom/endpoint":
  281. # module: my_module.CustomRequestHandler
  282. # config: {}
  283. # Unsecure HTTP listener,
  284. # For when matrix traffic passes through loadbalancer that unwraps TLS.
  285. - port: %(unsecure_port)s
  286. tls: false
  287. bind_addresses: ['::', '0.0.0.0']
  288. type: http
  289. x_forwarded: false
  290. resources:
  291. - names: [client]
  292. compress: true
  293. - names: [federation]
  294. compress: false
  295. # Turn on the twisted ssh manhole service on localhost on the given
  296. # port.
  297. # - port: 9000
  298. # bind_addresses: ['::1', '127.0.0.1']
  299. # type: manhole
  300. # Homeserver blocking
  301. #
  302. # How to reach the server admin, used in ResourceLimitError
  303. # admin_contact: 'mailto:admin@server.com'
  304. #
  305. # Global block config
  306. #
  307. # hs_disabled: False
  308. # hs_disabled_message: 'Human readable reason for why the HS is blocked'
  309. # hs_disabled_limit_type: 'error code(str), to help clients decode reason'
  310. #
  311. # Monthly Active User Blocking
  312. #
  313. # Enables monthly active user checking
  314. # limit_usage_by_mau: False
  315. # max_mau_value: 50
  316. # mau_trial_days: 2
  317. #
  318. # If enabled, the metrics for the number of monthly active users will
  319. # be populated, however no one will be limited. If limit_usage_by_mau
  320. # is true, this is implied to be true.
  321. # mau_stats_only: False
  322. #
  323. # Sometimes the server admin will want to ensure certain accounts are
  324. # never blocked by mau checking. These accounts are specified here.
  325. #
  326. # mau_limit_reserved_threepids:
  327. # - medium: 'email'
  328. # address: 'reserved_user@example.com'
  329. #
  330. # Room searching
  331. #
  332. # If disabled, new messages will not be indexed for searching and users
  333. # will receive errors when searching for messages. Defaults to enabled.
  334. # enable_search: true
  335. """ % locals()
  336. def read_arguments(self, args):
  337. if args.manhole is not None:
  338. self.manhole = args.manhole
  339. if args.daemonize is not None:
  340. self.daemonize = args.daemonize
  341. if args.print_pidfile is not None:
  342. self.print_pidfile = args.print_pidfile
  343. def add_arguments(self, parser):
  344. server_group = parser.add_argument_group("server")
  345. server_group.add_argument("-D", "--daemonize", action='store_true',
  346. default=None,
  347. help="Daemonize the home server")
  348. server_group.add_argument("--print-pidfile", action='store_true',
  349. default=None,
  350. help="Print the path to the pidfile just"
  351. " before daemonizing")
  352. server_group.add_argument("--manhole", metavar="PORT", dest="manhole",
  353. type=int,
  354. help="Turn on the twisted telnet manhole"
  355. " service on the given port.")
  356. def is_threepid_reserved(config, threepid):
  357. """Check the threepid against the reserved threepid config
  358. Args:
  359. config(ServerConfig) - to access server config attributes
  360. threepid(dict) - The threepid to test for
  361. Returns:
  362. boolean Is the threepid undertest reserved_user
  363. """
  364. for tp in config.mau_limits_reserved_threepids:
  365. if (threepid['medium'] == tp['medium']
  366. and threepid['address'] == tp['address']):
  367. return True
  368. return False
  369. def read_gc_thresholds(thresholds):
  370. """Reads the three integer thresholds for garbage collection. Ensures that
  371. the thresholds are integers if thresholds are supplied.
  372. """
  373. if thresholds is None:
  374. return None
  375. try:
  376. assert len(thresholds) == 3
  377. return (
  378. int(thresholds[0]), int(thresholds[1]), int(thresholds[2]),
  379. )
  380. except Exception:
  381. raise ConfigError(
  382. "Value of `gc_threshold` must be a list of three integers if set"
  383. )
  384. NO_MORE_WEB_CLIENT_WARNING = """
  385. Synapse no longer includes a web client. To enable a web client, configure
  386. web_client_location. To remove this warning, remove 'webclient' from the 'listeners'
  387. configuration.
  388. """
  389. def _warn_if_webclient_configured(listeners):
  390. for listener in listeners:
  391. for res in listener.get("resources", []):
  392. for name in res.get("names", []):
  393. if name == 'webclient':
  394. logger.warning(NO_MORE_WEB_CLIENT_WARNING)
  395. return
  396. KNOWN_RESOURCES = (
  397. 'client',
  398. 'consent',
  399. 'federation',
  400. 'keys',
  401. 'media',
  402. 'metrics',
  403. 'replication',
  404. 'static',
  405. 'webclient',
  406. )
  407. def _check_resource_config(listeners):
  408. resource_names = set(
  409. res_name
  410. for listener in listeners
  411. for res in listener.get("resources", [])
  412. for res_name in res.get("names", [])
  413. )
  414. for resource in resource_names:
  415. if resource not in KNOWN_RESOURCES:
  416. raise ConfigError(
  417. "Unknown listener resource '%s'" % (resource, )
  418. )
  419. if resource == "consent":
  420. try:
  421. check_requirements('resources.consent')
  422. except DependencyException as e:
  423. raise ConfigError(e.message)