server.py 18 KB

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