You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

703 lines
24 KiB

  1. # Copyright 2017 New Vector Ltd
  2. # Copyright 2019-2021 The Matrix.org Foundation C.I.C
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import atexit
  16. import gc
  17. import logging
  18. import os
  19. import signal
  20. import socket
  21. import sys
  22. import traceback
  23. import warnings
  24. from typing import (
  25. TYPE_CHECKING,
  26. Any,
  27. Awaitable,
  28. Callable,
  29. Collection,
  30. Dict,
  31. Iterable,
  32. List,
  33. NoReturn,
  34. Optional,
  35. Tuple,
  36. cast,
  37. )
  38. from cryptography.utils import CryptographyDeprecationWarning
  39. from typing_extensions import ParamSpec
  40. import twisted
  41. from twisted.internet import defer, error, reactor as _reactor
  42. from twisted.internet.interfaces import IOpenSSLContextFactory, IReactorSSL, IReactorTCP
  43. from twisted.internet.protocol import ServerFactory
  44. from twisted.internet.tcp import Port
  45. from twisted.logger import LoggingFile, LogLevel
  46. from twisted.protocols.tls import TLSMemoryBIOFactory
  47. from twisted.python.threadpool import ThreadPool
  48. from twisted.web.resource import Resource
  49. import synapse.util.caches
  50. from synapse.api.constants import MAX_PDU_SIZE
  51. from synapse.app import check_bind_error
  52. from synapse.app.phone_stats_home import start_phone_stats_home
  53. from synapse.config import ConfigError
  54. from synapse.config._base import format_config_error
  55. from synapse.config.homeserver import HomeServerConfig
  56. from synapse.config.server import ListenerConfig, ManholeConfig
  57. from synapse.crypto import context_factory
  58. from synapse.events.presence_router import load_legacy_presence_router
  59. from synapse.events.spamcheck import load_legacy_spam_checkers
  60. from synapse.events.third_party_rules import load_legacy_third_party_event_rules
  61. from synapse.handlers.auth import load_legacy_password_auth_providers
  62. from synapse.http.site import SynapseSite
  63. from synapse.logging.context import PreserveLoggingContext
  64. from synapse.logging.opentracing import init_tracer
  65. from synapse.metrics import install_gc_manager, register_threadpool
  66. from synapse.metrics.background_process_metrics import wrap_as_background_process
  67. from synapse.metrics.jemalloc import setup_jemalloc_stats
  68. from synapse.types import ISynapseReactor
  69. from synapse.util import SYNAPSE_VERSION
  70. from synapse.util.caches.lrucache import setup_expire_lru_cache_entries
  71. from synapse.util.daemonize import daemonize_process
  72. from synapse.util.gai_resolver import GAIResolver
  73. from synapse.util.rlimit import change_resource_limit
  74. if TYPE_CHECKING:
  75. from synapse.server import HomeServer
  76. # Twisted injects the global reactor to make it easier to import, this confuses
  77. # mypy which thinks it is a module. Tell it that it a more proper type.
  78. reactor = cast(ISynapseReactor, _reactor)
  79. logger = logging.getLogger(__name__)
  80. # list of tuples of function, args list, kwargs dict
  81. _sighup_callbacks: List[
  82. Tuple[Callable[..., None], Tuple[object, ...], Dict[str, object]]
  83. ] = []
  84. P = ParamSpec("P")
  85. def register_sighup(func: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None:
  86. """
  87. Register a function to be called when a SIGHUP occurs.
  88. Args:
  89. func: Function to be called when sent a SIGHUP signal.
  90. *args, **kwargs: args and kwargs to be passed to the target function.
  91. """
  92. _sighup_callbacks.append((func, args, kwargs))
  93. def start_worker_reactor(
  94. appname: str,
  95. config: HomeServerConfig,
  96. # Use a lambda to avoid binding to a given reactor at import time.
  97. # (needed when synapse.app.complement_fork_starter is being used)
  98. run_command: Callable[[], None] = lambda: reactor.run(),
  99. ) -> None:
  100. """Run the reactor in the main process
  101. Daemonizes if necessary, and then configures some resources, before starting
  102. the reactor. Pulls configuration from the 'worker' settings in 'config'.
  103. Args:
  104. appname: application name which will be sent to syslog
  105. config: config object
  106. run_command: callable that actually runs the reactor
  107. """
  108. logger = logging.getLogger(config.worker.worker_app)
  109. start_reactor(
  110. appname,
  111. soft_file_limit=config.server.soft_file_limit,
  112. gc_thresholds=config.server.gc_thresholds,
  113. pid_file=config.worker.worker_pid_file,
  114. daemonize=config.worker.worker_daemonize,
  115. print_pidfile=config.server.print_pidfile,
  116. logger=logger,
  117. run_command=run_command,
  118. )
  119. def start_reactor(
  120. appname: str,
  121. soft_file_limit: int,
  122. gc_thresholds: Optional[Tuple[int, int, int]],
  123. pid_file: Optional[str],
  124. daemonize: bool,
  125. print_pidfile: bool,
  126. logger: logging.Logger,
  127. # Use a lambda to avoid binding to a given reactor at import time.
  128. # (needed when synapse.app.complement_fork_starter is being used)
  129. run_command: Callable[[], None] = lambda: reactor.run(),
  130. ) -> None:
  131. """Run the reactor in the main process
  132. Daemonizes if necessary, and then configures some resources, before starting
  133. the reactor
  134. Args:
  135. appname: application name which will be sent to syslog
  136. soft_file_limit:
  137. gc_thresholds:
  138. pid_file: name of pid file to write to if daemonize is True
  139. daemonize: true to run the reactor in a background process
  140. print_pidfile: whether to print the pid file, if daemonize is True
  141. logger: logger instance to pass to Daemonize
  142. run_command: callable that actually runs the reactor
  143. """
  144. def run() -> None:
  145. logger.info("Running")
  146. setup_jemalloc_stats()
  147. change_resource_limit(soft_file_limit)
  148. if gc_thresholds:
  149. gc.set_threshold(*gc_thresholds)
  150. install_gc_manager()
  151. run_command()
  152. # make sure that we run the reactor with the sentinel log context,
  153. # otherwise other PreserveLoggingContext instances will get confused
  154. # and complain when they see the logcontext arbitrarily swapping
  155. # between the sentinel and `run` logcontexts.
  156. #
  157. # We also need to drop the logcontext before forking if we're daemonizing,
  158. # otherwise the cputime metrics get confused about the per-thread resource usage
  159. # appearing to go backwards.
  160. with PreserveLoggingContext():
  161. if daemonize:
  162. assert pid_file is not None
  163. if print_pidfile:
  164. print(pid_file)
  165. daemonize_process(pid_file, logger)
  166. run()
  167. def quit_with_error(error_string: str) -> NoReturn:
  168. message_lines = error_string.split("\n")
  169. line_length = min(max(len(line) for line in message_lines), 80) + 2
  170. sys.stderr.write("*" * line_length + "\n")
  171. for line in message_lines:
  172. sys.stderr.write(" %s\n" % (line.rstrip(),))
  173. sys.stderr.write("*" * line_length + "\n")
  174. sys.exit(1)
  175. def handle_startup_exception(e: Exception) -> NoReturn:
  176. # Exceptions that occur between setting up the logging and forking or starting
  177. # the reactor are written to the logs, followed by a summary to stderr.
  178. logger.exception("Exception during startup")
  179. quit_with_error(
  180. f"Error during initialisation:\n {e}\nThere may be more information in the logs."
  181. )
  182. def redirect_stdio_to_logs() -> None:
  183. streams = [("stdout", LogLevel.info), ("stderr", LogLevel.error)]
  184. for stream, level in streams:
  185. oldStream = getattr(sys, stream)
  186. loggingFile = LoggingFile(
  187. logger=twisted.logger.Logger(namespace=stream),
  188. level=level,
  189. encoding=getattr(oldStream, "encoding", None),
  190. )
  191. setattr(sys, stream, loggingFile)
  192. print("Redirected stdout/stderr to logs")
  193. def register_start(
  194. cb: Callable[P, Awaitable], *args: P.args, **kwargs: P.kwargs
  195. ) -> None:
  196. """Register a callback with the reactor, to be called once it is running
  197. This can be used to initialise parts of the system which require an asynchronous
  198. setup.
  199. Any exception raised by the callback will be printed and logged, and the process
  200. will exit.
  201. """
  202. async def wrapper() -> None:
  203. try:
  204. await cb(*args, **kwargs)
  205. except Exception:
  206. # previously, we used Failure().printTraceback() here, in the hope that
  207. # would give better tracebacks than traceback.print_exc(). However, that
  208. # doesn't handle chained exceptions (with a __cause__ or __context__) well,
  209. # and I *think* the need for Failure() is reduced now that we mostly use
  210. # async/await.
  211. # Write the exception to both the logs *and* the unredirected stderr,
  212. # because people tend to get confused if it only goes to one or the other.
  213. #
  214. # One problem with this is that if people are using a logging config that
  215. # logs to the console (as is common eg under docker), they will get two
  216. # copies of the exception. We could maybe try to detect that, but it's
  217. # probably a cost we can bear.
  218. logger.fatal("Error during startup", exc_info=True)
  219. print("Error during startup:", file=sys.__stderr__)
  220. traceback.print_exc(file=sys.__stderr__)
  221. # it's no use calling sys.exit here, since that just raises a SystemExit
  222. # exception which is then caught by the reactor, and everything carries
  223. # on as normal.
  224. os._exit(1)
  225. reactor.callWhenRunning(lambda: defer.ensureDeferred(wrapper()))
  226. def listen_metrics(bind_addresses: Iterable[str], port: int) -> None:
  227. """
  228. Start Prometheus metrics server.
  229. """
  230. from prometheus_client import start_http_server as start_http_server_prometheus
  231. from synapse.metrics import RegistryProxy
  232. for host in bind_addresses:
  233. logger.info("Starting metrics listener on %s:%d", host, port)
  234. _set_prometheus_client_use_created_metrics(False)
  235. start_http_server_prometheus(port, addr=host, registry=RegistryProxy)
  236. def _set_prometheus_client_use_created_metrics(new_value: bool) -> None:
  237. """
  238. Sets whether prometheus_client should expose `_created`-suffixed metrics for
  239. all gauges, histograms and summaries.
  240. There is no programmatic way to disable this without poking at internals;
  241. the proper way is to use an environment variable which prometheus_client
  242. loads at import time.
  243. The motivation for disabling these `_created` metrics is that they're
  244. a waste of space as they're not useful but they take up space in Prometheus.
  245. """
  246. import prometheus_client.metrics
  247. if hasattr(prometheus_client.metrics, "_use_created"):
  248. prometheus_client.metrics._use_created = new_value
  249. else:
  250. logger.error(
  251. "Can't disable `_created` metrics in prometheus_client (brittle hack broken?)"
  252. )
  253. def listen_manhole(
  254. bind_addresses: Collection[str],
  255. port: int,
  256. manhole_settings: ManholeConfig,
  257. manhole_globals: dict,
  258. ) -> None:
  259. # twisted.conch.manhole 21.1.0 uses "int_from_bytes", which produces a confusing
  260. # warning. It's fixed by https://github.com/twisted/twisted/pull/1522), so
  261. # suppress the warning for now.
  262. warnings.filterwarnings(
  263. action="ignore",
  264. category=CryptographyDeprecationWarning,
  265. message="int_from_bytes is deprecated",
  266. )
  267. from synapse.util.manhole import manhole
  268. listen_tcp(
  269. bind_addresses,
  270. port,
  271. manhole(settings=manhole_settings, globals=manhole_globals),
  272. )
  273. def listen_tcp(
  274. bind_addresses: Collection[str],
  275. port: int,
  276. factory: ServerFactory,
  277. reactor: IReactorTCP = reactor,
  278. backlog: int = 50,
  279. ) -> List[Port]:
  280. """
  281. Create a TCP socket for a port and several addresses
  282. Returns:
  283. list of twisted.internet.tcp.Port listening for TCP connections
  284. """
  285. r = []
  286. for address in bind_addresses:
  287. try:
  288. r.append(reactor.listenTCP(port, factory, backlog, address))
  289. except error.CannotListenError as e:
  290. check_bind_error(e, address, bind_addresses)
  291. # IReactorTCP returns an object implementing IListeningPort from listenTCP,
  292. # but we know it will be a Port instance.
  293. return r # type: ignore[return-value]
  294. def listen_http(
  295. listener_config: ListenerConfig,
  296. root_resource: Resource,
  297. version_string: str,
  298. max_request_body_size: int,
  299. context_factory: Optional[IOpenSSLContextFactory],
  300. reactor: ISynapseReactor = reactor,
  301. ) -> List[Port]:
  302. port = listener_config.port
  303. bind_addresses = listener_config.bind_addresses
  304. tls = listener_config.tls
  305. assert listener_config.http_options is not None
  306. site_tag = listener_config.http_options.tag
  307. if site_tag is None:
  308. site_tag = str(port)
  309. site = SynapseSite(
  310. "synapse.access.%s.%s" % ("https" if tls else "http", site_tag),
  311. site_tag,
  312. listener_config,
  313. root_resource,
  314. version_string,
  315. max_request_body_size=max_request_body_size,
  316. reactor=reactor,
  317. )
  318. if tls:
  319. # refresh_certificate should have been called before this.
  320. assert context_factory is not None
  321. ports = listen_ssl(
  322. bind_addresses,
  323. port,
  324. site,
  325. context_factory,
  326. reactor=reactor,
  327. )
  328. logger.info("Synapse now listening on TCP port %d (TLS)", port)
  329. else:
  330. ports = listen_tcp(
  331. bind_addresses,
  332. port,
  333. site,
  334. reactor=reactor,
  335. )
  336. logger.info("Synapse now listening on TCP port %d", port)
  337. return ports
  338. def listen_ssl(
  339. bind_addresses: Collection[str],
  340. port: int,
  341. factory: ServerFactory,
  342. context_factory: IOpenSSLContextFactory,
  343. reactor: IReactorSSL = reactor,
  344. backlog: int = 50,
  345. ) -> List[Port]:
  346. """
  347. Create an TLS-over-TCP socket for a port and several addresses
  348. Returns:
  349. list of twisted.internet.tcp.Port listening for TLS connections
  350. """
  351. r = []
  352. for address in bind_addresses:
  353. try:
  354. r.append(
  355. reactor.listenSSL(port, factory, context_factory, backlog, address)
  356. )
  357. except error.CannotListenError as e:
  358. check_bind_error(e, address, bind_addresses)
  359. # IReactorSSL incorrectly declares that an int is returned from listenSSL,
  360. # it actually returns an object implementing IListeningPort, but we know it
  361. # will be a Port instance.
  362. return r # type: ignore[return-value]
  363. def refresh_certificate(hs: "HomeServer") -> None:
  364. """
  365. Refresh the TLS certificates that Synapse is using by re-reading them from
  366. disk and updating the TLS context factories to use them.
  367. """
  368. if not hs.config.server.has_tls_listener():
  369. return
  370. hs.config.tls.read_certificate_from_disk()
  371. hs.tls_server_context_factory = context_factory.ServerContextFactory(hs.config)
  372. if hs._listening_services:
  373. logger.info("Updating context factories...")
  374. for i in hs._listening_services:
  375. # When you listenSSL, it doesn't make an SSL port but a TCP one with
  376. # a TLS wrapping factory around the factory you actually want to get
  377. # requests. This factory attribute is public but missing from
  378. # Twisted's documentation.
  379. if isinstance(i.factory, TLSMemoryBIOFactory):
  380. addr = i.getHost()
  381. logger.info(
  382. "Replacing TLS context factory on [%s]:%i", addr.host, addr.port
  383. )
  384. # We want to replace TLS factories with a new one, with the new
  385. # TLS configuration. We do this by reaching in and pulling out
  386. # the wrappedFactory, and then re-wrapping it.
  387. i.factory = TLSMemoryBIOFactory(
  388. hs.tls_server_context_factory, False, i.factory.wrappedFactory
  389. )
  390. logger.info("Context factories updated.")
  391. async def start(hs: "HomeServer") -> None:
  392. """
  393. Start a Synapse server or worker.
  394. Should be called once the reactor is running.
  395. Will start the main HTTP listeners and do some other startup tasks, and then
  396. notify systemd.
  397. Args:
  398. hs: homeserver instance
  399. """
  400. reactor = hs.get_reactor()
  401. # We want to use a separate thread pool for the resolver so that large
  402. # numbers of DNS requests don't starve out other users of the threadpool.
  403. resolver_threadpool = ThreadPool(name="gai_resolver")
  404. resolver_threadpool.start()
  405. reactor.addSystemEventTrigger("during", "shutdown", resolver_threadpool.stop)
  406. reactor.installNameResolver(
  407. GAIResolver(reactor, getThreadPool=lambda: resolver_threadpool)
  408. )
  409. # Register the threadpools with our metrics.
  410. register_threadpool("default", reactor.getThreadPool())
  411. register_threadpool("gai_resolver", resolver_threadpool)
  412. # Set up the SIGHUP machinery.
  413. if hasattr(signal, "SIGHUP"):
  414. @wrap_as_background_process("sighup")
  415. async def handle_sighup(*args: Any, **kwargs: Any) -> None:
  416. # Tell systemd our state, if we're using it. This will silently fail if
  417. # we're not using systemd.
  418. sdnotify(b"RELOADING=1")
  419. for i, args, kwargs in _sighup_callbacks:
  420. i(*args, **kwargs)
  421. sdnotify(b"READY=1")
  422. # We defer running the sighup handlers until next reactor tick. This
  423. # is so that we're in a sane state, e.g. flushing the logs may fail
  424. # if the sighup happens in the middle of writing a log entry.
  425. def run_sighup(*args: Any, **kwargs: Any) -> None:
  426. # `callFromThread` should be "signal safe" as well as thread
  427. # safe.
  428. reactor.callFromThread(handle_sighup, *args, **kwargs)
  429. signal.signal(signal.SIGHUP, run_sighup)
  430. register_sighup(refresh_certificate, hs)
  431. register_sighup(reload_cache_config, hs.config)
  432. # Apply the cache config.
  433. hs.config.caches.resize_all_caches()
  434. # Load the certificate from disk.
  435. refresh_certificate(hs)
  436. # Start the tracer
  437. init_tracer(hs) # noqa
  438. # Instantiate the modules so they can register their web resources to the module API
  439. # before we start the listeners.
  440. module_api = hs.get_module_api()
  441. for module, config in hs.config.modules.loaded_modules:
  442. m = module(config, module_api)
  443. logger.info("Loaded module %s", m)
  444. load_legacy_spam_checkers(hs)
  445. load_legacy_third_party_event_rules(hs)
  446. load_legacy_presence_router(hs)
  447. load_legacy_password_auth_providers(hs)
  448. # If we've configured an expiry time for caches, start the background job now.
  449. setup_expire_lru_cache_entries(hs)
  450. # It is now safe to start your Synapse.
  451. hs.start_listening()
  452. hs.get_datastores().main.db_pool.start_profiling()
  453. hs.get_pusherpool().start()
  454. # Log when we start the shut down process.
  455. hs.get_reactor().addSystemEventTrigger(
  456. "before", "shutdown", logger.info, "Shutting down..."
  457. )
  458. setup_sentry(hs)
  459. setup_sdnotify(hs)
  460. # If background tasks are running on the main process or this is the worker in
  461. # charge of them, start collecting the phone home stats and shared usage metrics.
  462. if hs.config.worker.run_background_tasks:
  463. await hs.get_common_usage_metrics_manager().setup()
  464. start_phone_stats_home(hs)
  465. # We now freeze all allocated objects in the hopes that (almost)
  466. # everything currently allocated are things that will be used for the
  467. # rest of time. Doing so means less work each GC (hopefully).
  468. #
  469. # PyPy does not (yet?) implement gc.freeze()
  470. if hasattr(gc, "freeze"):
  471. gc.collect()
  472. gc.freeze()
  473. # Speed up shutdowns by freezing all allocated objects. This moves everything
  474. # into the permanent generation and excludes them from the final GC.
  475. atexit.register(gc.freeze)
  476. def reload_cache_config(config: HomeServerConfig) -> None:
  477. """Reload cache config from disk and immediately apply it.resize caches accordingly.
  478. If the config is invalid, a `ConfigError` is logged and no changes are made.
  479. Otherwise, this:
  480. - replaces the `caches` section on the given `config` object,
  481. - resizes all caches according to the new cache factors, and
  482. Note that the following cache config keys are read, but not applied:
  483. - event_cache_size: used to set a max_size and _original_max_size on
  484. EventsWorkerStore._get_event_cache when it is created. We'd have to update
  485. the _original_max_size (and maybe
  486. - sync_response_cache_duration: would have to update the timeout_sec attribute on
  487. HomeServer -> SyncHandler -> ResponseCache.
  488. - track_memory_usage. This affects synapse.util.caches.TRACK_MEMORY_USAGE which
  489. influences Synapse's self-reported metrics.
  490. Also, the HTTPConnectionPool in SimpleHTTPClient sets its maxPersistentPerHost
  491. parameter based on the global_factor. This won't be applied on a config reload.
  492. """
  493. try:
  494. previous_cache_config = config.reload_config_section("caches")
  495. except ConfigError as e:
  496. logger.warning("Failed to reload cache config")
  497. for f in format_config_error(e):
  498. logger.warning(f)
  499. else:
  500. logger.debug(
  501. "New cache config. Was:\n %s\nNow:\n %s",
  502. previous_cache_config.__dict__,
  503. config.caches.__dict__,
  504. )
  505. synapse.util.caches.TRACK_MEMORY_USAGE = config.caches.track_memory_usage
  506. config.caches.resize_all_caches()
  507. def setup_sentry(hs: "HomeServer") -> None:
  508. """Enable sentry integration, if enabled in configuration"""
  509. if not hs.config.metrics.sentry_enabled:
  510. return
  511. import sentry_sdk
  512. sentry_sdk.init(
  513. dsn=hs.config.metrics.sentry_dsn,
  514. release=SYNAPSE_VERSION,
  515. )
  516. # We set some default tags that give some context to this instance
  517. with sentry_sdk.configure_scope() as scope:
  518. scope.set_tag("matrix_server_name", hs.config.server.server_name)
  519. app = (
  520. hs.config.worker.worker_app
  521. if hs.config.worker.worker_app
  522. else "synapse.app.homeserver"
  523. )
  524. name = hs.get_instance_name()
  525. scope.set_tag("worker_app", app)
  526. scope.set_tag("worker_name", name)
  527. def setup_sdnotify(hs: "HomeServer") -> None:
  528. """Adds process state hooks to tell systemd what we are up to."""
  529. # Tell systemd our state, if we're using it. This will silently fail if
  530. # we're not using systemd.
  531. sdnotify(b"READY=1\nMAINPID=%i" % (os.getpid(),))
  532. hs.get_reactor().addSystemEventTrigger(
  533. "before", "shutdown", sdnotify, b"STOPPING=1"
  534. )
  535. sdnotify_sockaddr = os.getenv("NOTIFY_SOCKET")
  536. def sdnotify(state: bytes) -> None:
  537. """
  538. Send a notification to systemd, if the NOTIFY_SOCKET env var is set.
  539. This function is based on the sdnotify python package, but since it's only a few
  540. lines of code, it's easier to duplicate it here than to add a dependency on a
  541. package which many OSes don't include as a matter of principle.
  542. Args:
  543. state: notification to send
  544. """
  545. if not isinstance(state, bytes):
  546. raise TypeError("sdnotify should be called with a bytes")
  547. if not sdnotify_sockaddr:
  548. return
  549. addr = sdnotify_sockaddr
  550. if addr[0] == "@":
  551. addr = "\0" + addr[1:]
  552. try:
  553. with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock:
  554. sock.connect(addr)
  555. sock.sendall(state)
  556. except Exception as e:
  557. # this is a bit surprising, since we don't expect to have a NOTIFY_SOCKET
  558. # unless systemd is expecting us to notify it.
  559. logger.warning("Unable to send notification to systemd: %s", e)
  560. def max_request_body_size(config: HomeServerConfig) -> int:
  561. """Get a suitable maximum size for incoming HTTP requests"""
  562. # Other than media uploads, the biggest request we expect to see is a fully-loaded
  563. # /federation/v1/send request.
  564. #
  565. # The main thing in such a request is up to 50 PDUs, and up to 100 EDUs. PDUs are
  566. # limited to 65536 bytes (possibly slightly more if the sender didn't use canonical
  567. # json encoding); there is no specced limit to EDUs (see
  568. # https://github.com/matrix-org/matrix-doc/issues/3121).
  569. #
  570. # in short, we somewhat arbitrarily limit requests to 200 * 64K (about 12.5M)
  571. #
  572. max_request_size = 200 * MAX_PDU_SIZE
  573. # if we have a media repo enabled, we may need to allow larger uploads than that
  574. if config.media.can_load_media_repo:
  575. max_request_size = max(max_request_size, config.media.max_upload_size)
  576. return max_request_size