server.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. from synapse.http.endpoint import parse_and_validate_server_name
  18. from ._base import Config, ConfigError
  19. logger = logging.Logger(__name__)
  20. class ServerConfig(Config):
  21. def read_config(self, config):
  22. self.server_name = config["server_name"]
  23. try:
  24. parse_and_validate_server_name(self.server_name)
  25. except ValueError as e:
  26. raise ConfigError(str(e))
  27. self.pid_file = self.abspath(config.get("pid_file"))
  28. self.web_client = config["web_client"]
  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. self.gc_thresholds = read_gc_thresholds(config.get("gc_thresholds", None))
  105. bind_port = config.get("bind_port")
  106. if bind_port:
  107. self.listeners = []
  108. bind_host = config.get("bind_host", "")
  109. gzip_responses = config.get("gzip_responses", True)
  110. names = ["client", "webclient"] if self.web_client else ["client"]
  111. self.listeners.append({
  112. "port": bind_port,
  113. "bind_addresses": [bind_host],
  114. "tls": True,
  115. "type": "http",
  116. "resources": [
  117. {
  118. "names": names,
  119. "compress": gzip_responses,
  120. },
  121. {
  122. "names": ["federation"],
  123. "compress": False,
  124. }
  125. ]
  126. })
  127. unsecure_port = config.get("unsecure_port", bind_port - 400)
  128. if unsecure_port:
  129. self.listeners.append({
  130. "port": unsecure_port,
  131. "bind_addresses": [bind_host],
  132. "tls": False,
  133. "type": "http",
  134. "resources": [
  135. {
  136. "names": names,
  137. "compress": gzip_responses,
  138. },
  139. {
  140. "names": ["federation"],
  141. "compress": False,
  142. }
  143. ]
  144. })
  145. manhole = config.get("manhole")
  146. if manhole:
  147. self.listeners.append({
  148. "port": manhole,
  149. "bind_addresses": ["127.0.0.1"],
  150. "type": "manhole",
  151. })
  152. metrics_port = config.get("metrics_port")
  153. if metrics_port:
  154. logger.warn(
  155. ("The metrics_port configuration option is deprecated in Synapse 0.31 "
  156. "in favour of a listener. Please see "
  157. "http://github.com/matrix-org/synapse/blob/master/docs/metrics-howto.rst"
  158. " on how to configure the new listener."))
  159. self.listeners.append({
  160. "port": metrics_port,
  161. "bind_addresses": [config.get("metrics_bind_host", "127.0.0.1")],
  162. "tls": False,
  163. "type": "http",
  164. "resources": [
  165. {
  166. "names": ["metrics"],
  167. "compress": False,
  168. },
  169. ]
  170. })
  171. def default_config(self, server_name, **kwargs):
  172. _, bind_port = parse_and_validate_server_name(server_name)
  173. if bind_port is not None:
  174. unsecure_port = bind_port - 400
  175. else:
  176. bind_port = 8448
  177. unsecure_port = 8008
  178. pid_file = self.abspath("homeserver.pid")
  179. return """\
  180. ## Server ##
  181. # The domain name of the server, with optional explicit port.
  182. # This is used by remote servers to connect to this server,
  183. # e.g. matrix.org, localhost:8080, etc.
  184. # This is also the last part of your UserID.
  185. server_name: "%(server_name)s"
  186. # When running as a daemon, the file to store the pid in
  187. pid_file: %(pid_file)s
  188. # CPU affinity mask. Setting this restricts the CPUs on which the
  189. # process will be scheduled. It is represented as a bitmask, with the
  190. # lowest order bit corresponding to the first logical CPU and the
  191. # highest order bit corresponding to the last logical CPU. Not all CPUs
  192. # may exist on a given system but a mask may specify more CPUs than are
  193. # present.
  194. #
  195. # For example:
  196. # 0x00000001 is processor #0,
  197. # 0x00000003 is processors #0 and #1,
  198. # 0xFFFFFFFF is all processors (#0 through #31).
  199. #
  200. # Pinning a Python process to a single CPU is desirable, because Python
  201. # is inherently single-threaded due to the GIL, and can suffer a
  202. # 30-40%% slowdown due to cache blow-out and thread context switching
  203. # if the scheduler happens to schedule the underlying threads across
  204. # different cores. See
  205. # https://www.mirantis.com/blog/improve-performance-python-programs-restricting-single-cpu/.
  206. #
  207. # This setting requires the affinity package to be installed!
  208. #
  209. # cpu_affinity: 0xFFFFFFFF
  210. # Whether to serve a web client from the HTTP/HTTPS root resource.
  211. web_client: True
  212. # The root directory to server for the above web client.
  213. # If left undefined, synapse will serve the matrix-angular-sdk web client.
  214. # Make sure matrix-angular-sdk is installed with pip if web_client is True
  215. # and web_client_location is undefined
  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 # The bundled webclient.
  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, webclient]
  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. )