conduwuit

a very cool, featureful fork of Conduit

What is Matrix?

Matrix is an open network for secure and decentralized communication. Users from every Matrix homeserver can chat with users from all other Matrix servers. You can even use bridges (also called Matrix Appservices) to communicate with users outside of Matrix, like a community on Discord.

What is the goal?

An efficient Matrix homeserver that's easy to set up and just works. You can install it on a mini-computer like the Raspberry Pi to host Matrix for your family, friends or company.

Can I try it out?

An official conduwuit server ran by me is available at transfem.dev (element.transfem.dev / cinny.transfem.dev)

transfem.dev is a public homeserver that can be used, it is not a "test only homeserver". This means there are rules, so please read the rules: https://transfem.dev/homeserver_rules.txt

transfem.dev is also listed at servers.joinmatrix.org

What is the current status?

conduwuit is a hard fork of Conduit which is in beta, meaning you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.

What's different about your fork than upstream Conduit?

See the differences page

How can I deploy my own?

If you want to connect an appservice to conduwuit, take a look at the appservices documentation.

How can I contribute?

See the contributor's guide

Contact

If you run into any question, feel free to

Original repo and Matrix room picture was from bran (<3). Current banner image and logo is directly from this cohost post.

Is it conduwuit or Conduwuit?

Both, but I prefer conduwuit.

Mirrors of conduwuit

Note: This list may not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the conduwuit Matrix room and ask any pre-usage questions.

list of features, bug fixes, etc that conduwuit does that Conduit does not

Outgoing typing indicators, outgoing read receipts, and outgoing presence!

Performance

  • Concurrency support for individual homeserver key fetching for faster remote room joins and room joins that will error less frequently
  • Send Cache-Control response header with immutable and 1 year cache length for all media requests (download and thumbnail) to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
  • Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request)
  • Eliminate all usage of the thread-blocking getaddrinfo(3) call upon DNS queries, significantly improving federation latency/ping and cache DNS results (NXDOMAINs, successful queries, etc) using hickory-dns / hickory-resolver
  • Enable HTTP/2 support on all requests
  • Vastly improve RocksDB default settings to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage or buggy filesystems.
  • Implement database flush and cleanup conduwuit operations when using RocksDB
  • Implement RocksDB write buffer corking and coalescing in database write-heavy areas
  • Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
  • Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults which also help huge with performance via reusing connections and retrying where needed
  • Properly get and use the amount of parallelism / tokio workers
  • Implement building conduwuit with jemalloc (which extends to the RocksDB jemalloc feature for maximum gains) or hardened_malloc light variant, and io_uring support, and produce CI builds with jemalloc and io_uring by default for performance (Nix doesn't seem to build hardened_malloc-rs properly)
  • Add support for caching DNS results with hickory-dns / hickory-resolver in conduwuit (not a replacement for a proper resolver cache, but still far better than nothing), also properly falls back on TCP for UDP errors or if a SRV response is too large
  • Add config option for using DNS over TCP, and config option for controlling A/AAAA record lookup strategy (e.g. don't query AAAA records if you don't have IPv6 connectivity)
  • Overall significant database, Client-Server, and federation performance and latency improvements (check out the ping room leaderboards if you don't believe me :>)
  • Add config options for RocksDB compression and bottommost compression, including choosing the algorithm and compression level
  • Use loole MPSC channels instead of tokio MPSC channels for huge performance boosts in sending channels (mainly relevant for federation) and presence channels
  • Use tracing/log's release_max_level_info feature to improve performance, build speeds, binary size, and CPU usage in release builds by avoid compiling debug/trace log level macros that users will generally never use (can be disabled with a build-time feature flag)
  • Remove some unnecessary checks on EDU handling for incoming transactions, effectively speeding them up
  • Simplify, dedupe, etc huge chunks of the codebase, including some that were unnecessary overhead, binary bloats, or preventing compiler/linker optimisations
  • Implement zero-copy RocksDB database accessors, substantially improving performance caused by unnecessary memory allocations

General Fixes/Features

  • Add legacy Element client hack fixing password changes and deactivations on legacy Element Android/iOS due to usage of an unspecced user field for UIAA
  • Raise and improve all the various request timeouts making some things like room joins and client bugs error less or none at all than they should, and make them all user configurable
  • Add missing reason field to user ban events (/ban)
  • Safer and cleaner shutdowns across incoming/outgoing requests (graceful shutdown) and the database
  • Stop sending make_join requests on room joins if 15 servers respond with M_UNSUPPORTED_ROOM_VERSION or M_INVALID_ROOM_VERSION
  • Stop sending make_join requests if 50 servers cannot provide make_join for us
  • Respect most client parameters for /media/ requests (allow_redirect still needs work)
  • Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
  • Make CONDUIT_CONFIG optional, relevant for container users that configure only by environment variables and no longer need to set CONDUIT_CONFIG to an empty string.
  • Allow HEAD and PATCH (MSC4138) HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
  • Fix using conduwuit with flake-compat on NixOS
  • Resolve and remove some "features" from upstream that result in concurrency hazards, exponential backoff issues, or arbitrary performance limiters
  • Find more servers for outbound federation /hierarchy requests instead of just the room ID server name
  • Support for suggesting servers to join through at /_matrix/client/v3/directory/room/{roomAlias}
  • Support for suggesting servers to join through us at /_matrix/federation/v1/query/directory
  • Misc edge-case search fixes (e.g. potentially missing some events)
  • Misc /sync fixes (e.g. returning unnecessary data or incorrect/invalid responses)
  • Add replaces_state and prev_sender in unsigned for state event changes which primarily makes Element's "See history" button on a state event functional
  • Fix Conduit not allowing incoming federation requests for various world readable rooms
  • Fix Conduit not respecting the client-requested file name on media requests
  • Prevent sending junk / non-membership events to /send_join and /send_leave endpoints
  • Only allow the requested membership type on /send_join and /send_leave endpoints (e.g. don't allow leave memberships on join endpoints)
  • Prevent state key impersonation on /send_join and /send_leave endpoints
  • Validate X-Matrix origin and request body "origin" field on incoming transactions
  • Add GET /_matrix/client/v1/register/m.login.registration_token/validity endpoint
  • Explicitly define support for sliding sync at /_matrix/client/versions (org.matrix.msc3575)
  • Fix seeing empty status messages on user presences

Moderation

  • (Also see Admin Room for all the admin commands pertaining to moderation, there's a lot!)
  • Add support for room banning/blocking by ID using admin command
  • Add support for serving support well-known from [global.well_known] (MSC1929) (/.well-known/matrix/support)
  • Config option to forbid publishing rooms to the room directory (lockdown_public_room_directory) except for admins
  • Admin commands to delete room aliases and unpublish rooms from our room directory
  • For all /report requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
  • Support blocking servers from downloading remote media from, returning a 404
  • Don't allow m.call.invite events to be sent in public rooms (prevents calling the entire room)
  • On new public room creations, only allow moderators to send m.call.invite, org.matrix.msc3401.call, and org.matrix.msc3401.call.member events to prevent unprivileged users from calling the entire room
  • Add support for a "global ACLs" feature (forbidden_remote_server_names) that blocks inbound remote room invites, room joins by room ID on server name, room joins by room alias on server name, incoming federated joins, and incoming federated room directory requests. This is very helpful for blocking servers that are purely toxic/bad and serve no value in allowing our users to suffer from things like room invite spam or such. Please note that this is not a substitute for room ACLs.
  • Add support for a config option to forbid our local users from sending federated room directory requests for (forbidden_remote_room_directory_server_names). Similar to above, useful for blocking servers that help prevent our users from wandering into bad areas of Matrix via room directories of those malicious servers.
  • Add config option for auto remediating/deactivating local non-admin users who attempt to join bad/forbidden rooms (auto_deactivate_banned_room_attempts)
  • Deactivating users will remove their profile picture, blurhash, display name, and leave all rooms by default just like Synapse and for additional privacy
  • Reject some EDUs from ACL'd users such as read receipts and typing indicators

Privacy/Security

  • Add config option for device name federation with a privacy-friendly default (disabled)
  • Add config option for requiring authentication to the /publicRooms endpoint (room directory) with a default enabled for privacy
  • Add config option for federating /publicRooms endpoint (room directory) to other servers with a default disabled for privacy
  • Uses proper argon2 crate by RustCrypto instead of questionable rust-argon2 crate
  • Generate passwords with 25 characters instead of 15
  • Config option ip_range_denylist to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security (note: this is not a guaranteed protection, and you should be using a firewall with zones if you want guaranteed protection as doing this on the application level is prone to bypasses).
  • Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
  • Config option to disable incoming and/or outgoing remote read receipts
  • Config option to disable incoming and/or outgoing remote typing indicators
  • Config option to disable incoming, outgoing, and/or local presence and for timing out remote users
  • Sanitise file names for the Content-Disposition header for all media requests (thumbnails, downloads, uploads)
  • Media repository on handling Content-Disposition and Content-Type is fully spec compliant and secured
  • Send secure default HTTP headers such as a strong restrictive CSP (see MSC4149), deny iframes, disable X-XSS-Protection, disable interest cohort in Permission-Policy, etc to mitigate any potential attack surface such as from untrusted media

Administration/Logging

  • Commandline argument to specify the path to a config file instead of relying on CONDUIT_CONFIG
  • Revamped admin room infrastructure and commands
  • Substantially clean up, improve, and fix logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, proper error propagation, etc)
  • Configurable RocksDB logging (LOG files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
  • Explicit startup error if your configuration allows open registration without a token or such like Synapse with a way to bypass it if needed
  • Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations, with a conduwuit default of "🏳️‍⚧️"
  • Implement config option to auto join rooms upon registration
  • Warn on unknown config options specified
  • Add /_conduwuit/server_version route to return the version of conduwuit without relying on the federation API /_matrix/federation/v1/version
  • Add /_conduwuit/local_user_count route to return the amount of registered active local users on your homeserver if federation is enabled
  • Add configurable RocksDB recovery modes to aid in recovering corrupted RocksDB databases
  • Support config options via CONDUWUIT_ prefix and accessing non-global struct config options with the __ split (e.g. CONDUWUIT_WELL_KNOWN__SERVER)
  • Add support for listening on multiple TCP ports and multiple addresses
  • Opt-in Sentry.io telemetry and metrics, mainly used for crash reporting
  • Log the client IP on various requests such as registrations, banned room join attempts, logins, deactivations, federation transactions, etc
  • Fix Conduit dropping some remote server federation response errors

Maintenance/Stability

  • GitLab CI ported to GitHub Actions
  • Add support for the Matrix spec compliance test suite Complement via the Nix flake and various other fixes for it
  • Implement running and diff'ing Complement results in CI and error if any mismatch occurs to prevent large cases of conduwuit regressions
  • Repo is (officially) mirrored to GitHub, GitLab, git.gay, git.girlcock.ceo, sourcehut, and Codeberg (see README.md for their links)
  • Docker container images published to GitLab Container Registry, GitHub Container Registry, and Dockerhub
  • Extensively revamp the example config to be extremely helpful and useful to both new users and power users
  • Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
  • Add a lot of other clippy and rustc lints and a rustfmt.toml file
  • Repo uses Renovate, Trivy, and keeps ALL dependencies as up to date as possible
  • Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) and other unnecessary code or overhead
  • webp support for images
  • Add cargo audit support to CI
  • Add documentation lints via lychee and markdownlint-cli to CI
  • CI tests for all sorts of feature matrixes (jemalloc, non-defaullt, all features, etc)
  • Add static and dynamic linking smoke tests in CI to prevent any potential linking regressions for Complement, static binaries, Nix devshells, etc
  • Add timestamp by commit date when building OCI images for keeping image build reproducibility and still have a meaningful "last modified date" for OCI image
  • Add timestamp by commit date via SOURCE_DATE_EPOCH for Debian packages
  • Startup check if conduwuit running in a container and is listening on 127.0.0.1 (generally containers are using NAT networking and 0.0.0.0 is the intended listening address)
  • Add a panic catcher layer to return panic messages in HTTP responses if a panic occurs
  • Add full compatibility support for SHA256 media file names instead of base64 file names to overcome filesystem file name length limitations (OS error file name too long) while still retaining upstream database compatibility
  • Remove SQLite support due to being very poor performance, difficult to maintain against RocksDB, and is a blocker to significantly improved database code

Admin Room

  • Add support for a console CLI interface that can issue admin commands and output them in your terminal
  • Add support for an admin-user-only commandline admin room interface that can be issued in any room with the \\!admin or \!admin prefix and returns the response as yourself in the same room
  • Add admin commands for uptime, server startup, server shutdown, and server restart
  • Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
  • Add command to dynamically change conduwuit's tracing log level filter on the fly
  • Add admin command to fetch a server's /.well-known/matrix/support file
  • Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes)
  • Implement RocksDB online backups, listing RocksDB backups, and listing database file counts all via admin commands
  • Add various database visibility commands such as being able to query the getters and iterators used in conduwuit, a very helpful online debugging utility
  • Forbid the admin room from being made public or world readable history
  • Add !admin as a way to call the admin bot
  • Extend clear cache admin command to support clearing more caches such as DNS and TLS name overrides
  • Admin debug command to send a federation request/ping to a server's /_matrix/federation/v1/version endpoint and measures the latency it took
  • Add admin command to bulk delete media via a codeblock list of MXC URLs.
  • Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
  • Add admin command to list all the rooms a local user is joined in
  • Add admin command to list joined members in a room
  • Add admin command to view the room topic of a room
  • Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room, a --force flag to ignore errors, and support for reading last modified time instead of creation time for filesystems that don't support file created metadata
  • Add admin command to return a room's full/complete state
  • Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline as backfill
  • Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
  • Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature
  • Add admin commands to output jemalloc memory stats and memory usage
  • Add admin command to get rooms a remote user shares with us
  • Add debug admin commands to get the earliest and latest PDU in a room
  • Add debug admin command to echo a message
  • Add admin command to insert rooms tags for a user, most useful for inserting the m.server_notice tag on your admin room to make it "persistent" in the "System Alerts" section of Element
  • Add experimental admin debug command for Dendrite's AdminDownloadState (/admin/downloadState/{serverName}/{roomID}) admin API endpoint to download and use a remote server's room state in the room
  • Disable URL previews by default in the admin room due to various command outputs having "URLs" in them that clients may needlessly render/request
  • Extend memory usage admin server command to support showing memory allocator stats such as jemalloc's
  • Add admin debug command to see memory allocator's full extended debug statistics such as jemalloc's

Misc

  • Add guest support for accessing TURN servers via turn_allow_guests like Synapse
  • Support for creating rooms with custom room IDs like Maunium Synapse (room_id request body field to /createRoom)
  • Query parameter ?format=event|content for returning either the room state event's content (default) for the full room state event on /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}] requests (see https://github.com/matrix-org/matrix-spec/issues/1047)
  • Send a User-Agent on all of our requests
  • Send avatar_url on invite room membership events/changes
  • Support sending well_known response to client login responses if using config option [well_known.client]
  • Implement include_state search criteria support for /search requests (response now can include room states)
  • Declare various missing Matrix versions and features at /_matrix/client/versions
  • Implement legacy Matrix /v1/ media endpoints that some clients and servers may still call
  • Config option to change Conduit's behaviour of homeserver key fetching (query_trusted_key_servers_first). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa which may help in joining certain rooms.
  • Implement unstable MSC2666 support for querying mutual rooms with a user
  • Implement unstable MSC3266 room summary API support
  • Implement unstable MSC4125 support for specifying servers to join via on federated invites
  • Make conduwuit build and be functional under Nix + macOS
  • Log out all sessions after unsetting the emergency password
  • Assume well-knowns are broken if they exceed past 12288 characters.
  • Add support for listening on both HTTP and HTTPS if using direct TLS with conduwuit for usecases such as Complement
  • Add config option for disabling RocksDB Direct IO if needed
  • Add various documentation on maintaining conduwuit, using RocksDB online backups, some troubleshooting, using admin commands, moderation documentation, etc
  • (Developers): Add support for hot reloadable/"live" modular development
  • (Developers): Add support for tokio-console
  • (Developers): Add support for tracing flame graphs
  • No cryptocurrency donations allowed, conduwuit is fully maintained by independent queer maintainers, and with a strong priority on inclusitivity and comfort for protected groups 🏳️‍⚧️
  • Add a community Code of Conduct for all conduwuit community spaces, primarily the Matrix space

Configuration

This chapter describes various ways to configure conduwuit.

Basics

Conduwuit uses a config file for the majority of the settings. Please refer to the example config file for all of those settings. The config file to use can either be specified on the command line when running conduwuit by specifying the -c, --config flag. Alternatively, you can use the environment variable CONDUWUIT_CONFIG to specify the config file to used.

Environment variables

All of the settings that are found in the config file can be specified by using environment variables. The environment variable names should be all caps and prefixed with CONDUWUIT_. For example, if the setting you are changing is max_request_size, then the environment variable to set is CONDUWUIT_MAX_REQUEST_SIZE.

Example configuration

Example configuration
# =============================================================================
#  This is the official example config for conduwuit.
#  If you use it for your server, you will need to adjust it to your own needs.
#  At the very least, change the server_name field!
#
#  This documentation can also be found at https://conduwuit.puppyirl.gay/configuration.html
# =============================================================================

[global]

# The server_name is the pretty name of this server. It is used as a suffix for user
# and room ids. Examples: matrix.org, conduit.rs

# The Conduit server needs all /_matrix/ requests to be reachable at
# https://your.server.name/ on port 443 (client-server) and 8448 (federation).

# If that's not possible for you, you can create /.well-known files to redirect
# requests (delegation). See
# https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient
# and
# https://spec.matrix.org/v1.9/server-server-api/#getwell-knownmatrixserver
# for more information

# YOU NEED TO EDIT THIS
#server_name = "your.server.name"

# Servers listed here will be used to gather public keys of other servers (notary trusted key servers).
#
# The default behaviour for conduwuit is to attempt to query trusted key servers before querying the individual servers.
# This is done for performance reasons, but if you would like to query individual servers before the notary servers
# configured below, set to
#
# (Currently, conduwuit doesn't support batched key requests, so this list should only contain Synapse servers)
# Defaults to `matrix.org`
# trusted_servers = ["matrix.org"]

# Sentry.io crash/panic reporting, performance monitoring/metrics, etc. This is NOT enabled by default.
# conduwuit's default Sentry reporting endpoint is o4506996327251968.ingest.us.sentry.io
#
# Defaults to *false*
#sentry = false

# Sentry reporting URL if a custom one is desired
#
# Defaults to conduwuit's default Sentry endpoint: "https://fe2eb4536aa04949e28eff3128d64757@o4506996327251968.ingest.us.sentry.io/4506996334657536"
#sentry_endpoint = ""

# Report your Conduwuit server_name in Sentry.io crash reports and metrics
#
# Defaults to false
#sentry_send_server_name = false

# Performance monitoring/tracing sample rate for Sentry.io
#
# Note that too high values may impact performance, and can be disabled by setting it to 0.0 (0%)
# This value is read as a percentage to Sentry, represented as a decimal
#
# Defaults to 15% of traces (0.15)
#sentry_traces_sample_rate = 0.15

# Whether to attach a stacktrace to Sentry reports.
#sentry_attach_stacktrace = false

# Send panics to sentry. This is true by default, but sentry has to be enabled.
#sentry_send_panic = true

# Send errors to sentry. This is true by default, but sentry has to be enabled. This option is
# only effective in release-mode; forced to false in debug-mode.
#sentry_send_error = true


### Database configuration

# This is the only directory where conduwuit will save its data, including media.
# Note: this was previously "/var/lib/matrix-conduit"
database_path = "/var/lib/conduwuit"

# Database backend: Only rocksdb is supported.
database_backend = "rocksdb"


### Network

# The port(s) conduwuit will be running on. You need to set up a reverse proxy such as
# Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be
# forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this.
# To listen on multiple ports, specify a vector e.g. [8080, 8448]
#
# default if unspecified is 8008
port = 6167

# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
# localhost (127.0.0.1 / ::1). If you are using Docker or a container NAT networking setup, you
# likely need this to be 0.0.0.0.
# To listen multiple addresses, specify a vector e.g. ["127.0.0.1", "::1"]
#
# default if unspecified is both IPv4 and IPv6 localhost: ["127.0.0.1", "::1"]
address = "127.0.0.1"

# Max request size for file uploads
max_request_size = 20_000_000 # in bytes

# Uncomment unix_socket_path to listen on a UNIX socket at the specified path.
# If listening on a UNIX socket, you must remove/comment the 'address' key if defined and add your
# reverse proxy to the 'conduwuit' group, unless world RW permissions are specified with unix_socket_perms (666 minimum).
#unix_socket_path = "/run/conduwuit/conduwuit.sock"
#unix_socket_perms = 660

# Set this to true for conduwuit to compress HTTP response bodies using zstd.
# This option does nothing if conduwuit was not built with `zstd_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
zstd_compression = false

# Set this to true for conduwuit to compress HTTP response bodies using gzip.
# This option does nothing if conduwuit was not built with `gzip_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
gzip_compression = false

# Set this to true for conduwuit to compress HTTP response bodies using brotli.
# This option does nothing if conduwuit was not built with `brotli_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
brotli_compression = false

# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to.
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
#
# To disable, set this to be an empty vector (`[]`).
# Please be aware that this is *not* a guarantee. You should be using a firewall with zones as doing this on the application layer may have bypasses.
#
# Currently this does not account for proxies in use like Synapse does.
ip_range_denylist = [
    "127.0.0.0/8",
    "10.0.0.0/8",
    "172.16.0.0/12",
    "192.168.0.0/16",
    "100.64.0.0/10",
    "192.0.0.0/24",
    "169.254.0.0/16",
    "192.88.99.0/24",
    "198.18.0.0/15",
    "192.0.2.0/24",
    "198.51.100.0/24",
    "203.0.113.0/24",
    "224.0.0.0/4",
    "::1/128",
    "fe80::/10",
    "fc00::/7",
    "2001:db8::/32",
    "ff00::/8",
    "fec0::/10",
]


### Moderation / Privacy / Security

# Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically.
# Defaults to false
allow_guest_registration = false

# Set to true to log guest registrations in the admin room.
# Defaults to false as it may be noisy or unnecessary.
log_guest_registrations = false

# Set to true to allow guest registrations/users to auto join any rooms specified in `auto_join_rooms`
# Defaults to false
allow_guests_auto_join_rooms = false

# Vector list of servers that conduwuit will refuse to download remote media from.
# No default.
# prevent_media_downloads_from = ["example.com", "example.local"]

# Enables registration. If set to false, no users can register on this
# server.
# If set to true without a token configured, users can register with no form of 2nd-
# step only if you set
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` to
# true in your config. If you would like
# registration only via token reg, please configure the `registration_token` key.
allow_registration = false
# Please note that an open registration homeserver with no second-step verification
# is highly prone to abuse and potential defederation by homeservers, including
# matrix.org.

# A static registration token that new users will have to provide when creating
# an account. If unset and `allow_registration` is true, registration is open
# without any condition. YOU NEED TO EDIT THIS.
registration_token = "change this token for something specific to your server"

# controls whether federation is allowed or not
# defaults to true
# allow_federation = true

# controls whether users are allowed to create rooms.
# appservices and admins are always allowed to create rooms
# defaults to true
# allow_room_creation = true

# controls whether non-admin local users are forbidden from sending room invites (local and remote),
# and if non-admin users can receive remote room invites. admins are always allowed to send and receive all room invites.
# defaults to false
# block_non_admin_invites = false

# Allows admins to enter commands in rooms other than #admins by prefixing with \!admin. The reply
# will be publicly visible to the room, originating from the sender.
# defaults to true
#admin_escape_commands = true

# List of forbidden username patterns/strings. Values in this list are matched as *contains*.
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
# have a forbidden username.
# No default.
# forbidden_usernames = []

# List of forbidden room aliases and room IDs as patterns/strings. Values in this list are matched as *contains*.
# This is checked upon room alias creation, custom room ID creation if used, and startup as warnings if any room aliases
# in your database have a forbidden room alias/ID.
# No default.
# forbidden_alias_names = []

# List of forbidden server names that we will block all client room joins, incoming federated room directory requests, incoming federated invites for, and incoming federated joins. This check is applied on the room ID, room alias, sender server name, and sender user's server name.
# Basically "global" ACLs. For our user (client) checks, admin users are allowed.
# No default.
# forbidden_remote_server_names = []

# List of forbidden server names that we will block all outgoing federated room directory requests for. Useful for preventing our users from wandering into bad servers or spaces.
# No default.
# forbidden_remote_room_directory_server_names = []

# Set this to true to allow your server's public room directory to be federated.
# Set this to false to protect against /publicRooms spiders, but will forbid external users
# from viewing your server's public room directory. If federation is disabled entirely
# (`allow_federation`), this is inherently false.
allow_public_room_directory_over_federation = false

# Set this to true to allow your server's public room directory to be queried without client
# authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders.
allow_public_room_directory_without_auth = false

# Set this to true to lock down your server's public room directory and only allow admins to publish rooms to the room directory.
# Unpublishing is still allowed by all users with this enabled.
#
# Defaults to false
lockdown_public_room_directory = false

# Set this to true to allow federating device display names / allow external users to see your device display name.
# If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled.
allow_device_name_federation = false

# Vector list of domains allowed to send requests to for URL previews. Defaults to none.
# Note: this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com" and "http://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_contains_allowlist = []

# Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_explicit_allowlist = []

# Vector list of URLs allowed to send requests to for URL previews. Defaults to none.
# Note that this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com/", "https://google.com/url?q=https://mymaliciousdomainexample.com", and "https://mymaliciousdomainexample.com/hi/google.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_url_contains_allowlist = []

# Vector list of explicit domains not allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# The denylist is checked first before allowlist. Setting this to "*" will not do anything.
url_preview_domain_explicit_denylist = []

# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 384KB (384_000 bytes)
url_preview_max_spider_size = 384_000

# Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false.
# Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched.
# Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain.
url_preview_check_root_domain = false

# Config option to allow or disallow incoming federation requests that obtain the profiles
# of our local users from `/_matrix/federation/v1/query/profile`
#
# This is inherently false if `allow_federation` is disabled
#
# Defaults to true
allow_profile_lookup_federation_requests = true

# Config option to automatically deactivate the account of any user who attempts to join a:
# - banned room
# - forbidden room alias
# - room alias or ID with a forbidden server name
#
# This may be useful if all your banned lists consist of toxic rooms or servers that no good faith user would ever attempt to join, and
# to automatically remediate the problem without any admin user intervention.
#
# This will also make the user leave all rooms. Federation (e.g. remote room invites) are ignored here.
#
# Defaults to false as rooms can be banned for non-moderation-related reasons
#auto_deactivate_banned_room_attempts = false


### Misc

# max log level for conduwuit. allows debug, info, warn, or error
# see also: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
# **Caveat**:
# For release builds, the tracing crate is configured to only implement levels higher than error to avoid unnecessary overhead in the compiled binary from trace macros.
# For debug builds, this restriction is not applied.
#
# Defaults to "info"
#log = "info"

# controls whether encrypted rooms and events are allowed (default true)
#allow_encryption = false

# if enabled, conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable`
# for any new announcements made. Despite the name, this is not an update check
# endpoint, it is simply an announcement check endpoint.
# Defaults to false.
#allow_check_for_updates = false

# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 3 - 5, and 11.
# Defaults to true.
#allow_unstable_room_versions = true

# Option to control adding arbitrary text to the end of the user's displayname upon registration with a space before the text.
# This was the lightning bolt emoji option, just replaced with support for adding your own custom text or emojis.
# To disable, set this to "" (an empty string)
# Defaults to "🏳️‍⚧️" (trans pride flag)
#new_user_displayname_suffix = "🏳️‍⚧️"

# Option to control whether conduwuit will query your list of trusted notary key servers (`trusted_servers`) for
# remote homeserver signing keys it doesn't know *first*, or query the individual servers first before falling back to the trusted
# key servers.
#
# The former/default behaviour makes federated/remote rooms joins generally faster because we're querying a single (or list of) server
# that we know works, is reasonably fast, and is reliable for just about all the homeserver signing keys in the room. Querying individual
# servers may take longer depending on the general infrastructure of everyone in there, how many dead servers there are, etc.
#
# However, this does create an increased reliance on one single or multiple large entities as `trusted_servers` should generally
# contain long-term and large servers who know a very large number of homeservers.
#
# If you don't know what any of this means, leave this and `trusted_servers` alone to their defaults.
#
# Defaults to true as this is the fastest option for federation.
#query_trusted_key_servers_first = true

# List/vector of room **IDs** that conduwuit will make newly registered users join.
# The room IDs specified must be rooms that you have joined at least once on the server, and must be public.
#
# No default.
#auto_join_rooms = []

# Retry failed and incomplete messages to remote servers immediately upon startup. This is called bursting.
# If this is disabled, said messages may not be delivered until more messages are queued for that server.
# Do not change this option unless server resources are extremely limited or the scale of the server's
# deployment is huge. Do not disable this unless you know what you are doing.
#startup_netburst = true

# Limit the startup netburst to the most recent (default: 50) messages queued for each remote server. All older
# messages are dropped and not reattempted. The `startup_netburst` option must be enabled for this value to have
# any effect. Do not change this value unless you know what you are doing. Set this value to -1 to reattempt
# every message without trimming the queues; this may consume significant disk. Set this value to 0 to drop all
# messages without any attempt at redelivery.
#startup_netburst_keep = 50

# If the 'perf_measurements' feature is enabled, enables collecting folded stack trace profile of tracing spans using
# tracing_flame. The resulting profile can be visualized with inferno[1], speedscope[2], or a number of other tools.
# [1]: https://github.com/jonhoo/inferno
# [2]: www.speedscope.app
# tracing_flame = false

# If 'tracing_flame' is enabled, sets a filter for which events will be included in the profile.
# Supported syntax is documented at https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
# tracing_flame_filter = "trace,h2=off"

# If 'tracing_flame' is enabled, set the path to write the generated profile.
# tracing_flame_output_path = "./tracing.folded"

# Enable the tokio-console. This option is only relevant to developers.
# See: docs/development.md#debugging-with-tokio-console for more information.
#tokio_console = false

# Enable backward-compatibility with Conduit's media directory by creating symlinks of media. This
# option is only necessary if you plan on using Conduit again. Otherwise setting this to false
# reduces filesystem clutter and overhead for managing these symlinks in the directory.
#
# Enabled by default.
#media_compat_file_link = true

# Checks consistency of the media directory at startup:
# 1. When `media_compat_file_link` is enbled, this check will upgrade media when switching back
#    and forth between Conduit and Conduwuit. Both options must be enabled to handle this.
# 2. When media is deleted from the directory, this check will also delete its database entry.
#
# If none of these checks apply to your use cases, and your media directory is significantly large
# setting this to false may reduce startup time.
#
# Enabled by default.
#media_startup_check = true

# OpenID token expiration/TTL in seconds
#
# These are the OpenID tokens that are primarily used for Matrix account integrations, *not* OIDC/OpenID Connect/etc
#
# Defaults to 3600 (1 hour)
#openid_token_ttl = 3600

# Emergency password feature. This password set here will let you login to the server service account (e.g. `@conduit`)
# and let you run admin commands, invite yourself to the admin room, etc.
#
# no default.
#emergency_password = ""


### Generic database options

# Set this to any float value to multiply conduwuit's in-memory LRU caches with.
# May be useful if you have significant memory to spare to increase performance.
#
# This was previously called `conduit_cache_capacity_modifier`
#
# Defaults to 1.0.
#cache_capacity_modifier = 1.0

# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 256.0
#db_cache_capacity_mb = 256.0


### RocksDB options

# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
#
# It is worth noting that by default, conduwuit will use RocksDB with Direct IO enabled. *Generally* speaking this improves performance as it bypasses buffered I/O (system page cache).
# However there is a potential chance that Direct IO may cause issues with database operations if your setup is uncommon. This has been observed with FUSE filesystems, and possibly ZFS filesystem.
# RocksDB generally deals/corrects these issues but it cannot account for all setups.
# If you experience any weird RocksDB issues, try enabling this option as it turns off Direct IO and feel free to report in the conduwuit Matrix room if this option fixes your DB issues.
# See https://github.com/facebook/rocksdb/wiki/Direct-IO for more information.
#
# Defaults to false
#rocksdb_optimize_for_spinning_disks = false

# Enables direct-io to increase database performance. This is enabled by default. Set this option to false if the
# database resides on a filesystem which does not support direct-io.
#rocksdb_direct_io = true

# RocksDB log level. This is not the same as conduwuit's log level. This is the log level for the RocksDB engine/library
# which show up in your database folder/path as `LOG` files. Defaults to error. conduwuit will typically log RocksDB errors as normal.
#rocksdb_log_level = "error"

# Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB.
#rocksdb_max_log_file_size = 4194304

# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0

# Amount of threads that RocksDB will use for parallelism on database operatons such as cleanup, sync, flush, compaction, etc. Set to 0 to use all your logical threads.
#
# Defaults to your CPU logical thread count.
#rocksdb_parallelism_threads = 0

# Enables idle IO priority for compaction thread. This prevents any unexpected lag in the server's operation and
# is usually a good idea. Enabled by default.
#rocksdb_compaction_ioprio_idle = true

# Enables idle CPU priority for compaction thread. This is not enabled by default to prevent compaction from
# falling too far behind on busy systems.
#rocksdb_compaction_prio_idle = false

# Maximum number of LOG files RocksDB will keep. This must *not* be set to 0. It must be at least 1.
# Defaults to 3 as these are not very useful.
#rocksdb_max_log_files = 3

# Type of RocksDB database compression to use.
# Available options are "zstd", "zlib", "bz2", "lz4", or "none"
# It is best to use ZSTD as an overall good balance between speed/performance, storage, IO amplification, and CPU usage.
# For more performance but less compression (more storage used) and less CPU usage, use LZ4.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# "none" will disable compression.
#
# Defaults to "zstd"
#rocksdb_compression_algo = "zstd"

# Level of compression the specified compression algorithm for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
#rocksdb_compression_level = 32767

# Level of compression the specified compression algorithm for the bottommost level/data for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
# Since this is the bottommost level (generally old and least used data), it may be desirable to have a very
# high compression level here as it's lesss likely for this data to be used. Research your chosen compression algorithm.
#
#rocksdb_bottommost_compression_level = 32767

# Whether to enable RocksDB "bottommost_compression".
# At the expense of more CPU usage, this will further compress the database to reduce more storage.
# It is recommended to use ZSTD compression with this for best compression results.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# Defaults to false as this uses more CPU when compressing.
#rocksdb_bottommost_compression = false

# Database recovery mode (for RocksDB WAL corruption)
#
# Use this option when the server reports corruption and refuses to start. Set mode 2 (PointInTime)
# to cleanly recover from this corruption. The server will continue from the last good state,
# several seconds or minutes prior to the crash. Clients may have to run "clear-cache & reload" to
# account for the rollback. Upon success, you may reset the mode back to default and restart again.
# Please note in some cases the corruption error may not be cleared for at least 30 minutes of
# operation in PointInTime mode.
#
# As a very last ditch effort, if PointInTime does not fix or resolve anything, you can try mode
# 3 (SkipAnyCorruptedRecord) but this will leave the server in a potentially inconsistent state.
#
# The default mode 1 (TolerateCorruptedTailRecords) will automatically drop the last entry in the
# database if corrupted during shutdown, but nothing more. It is extraordinarily unlikely this will
# desynchronize clients. To disable any form of silent rollback set mode 0 (AbsoluteConsistency).
#
# The options are:
# 0 = AbsoluteConsistency
# 1 = TolerateCorruptedTailRecords (default)
# 2 = PointInTime (use me if trying to recover)
# 3 = SkipAnyCorruptedRecord (you now voided your Conduwuit warranty)
#
# See https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes for more information
#
# Defaults to 1 (TolerateCorruptedTailRecords)
#rocksdb_recovery_mode = 1


### Domain Name Resolution and Caching

# Maximum entries stored in DNS memory-cache. The size of an entry may vary so please take care if
# raising this value excessively. Only decrease this when using an external DNS cache. Please note
# that systemd does *not* count as an external cache, even when configured to do so.
#dns_cache_entries = 32768

# Minimum time-to-live in seconds for entries in the DNS cache. The default may appear high to most
# administrators; this is by design. Only decrease this if you are using an external DNS cache.
#dns_min_ttl = 10800

# Minimum time-to-live in seconds for NXDOMAIN entries in the DNS cache. This value is critical for
# the server to federate efficiently. NXDOMAIN's are assumed to not be returning to the federation
# and aggressively cached rather than constantly rechecked.
#
# Defaults to 3 days as these are *very rarely* false negatives.
#dns_min_ttl_nxdomain = 259200

# The number of seconds to wait for a reply to a DNS query. Please note that recursive queries can
# take up to several seconds for some domains, so this value should not be too low.
#dns_timeout = 10

# Number of retries after a timeout.
#dns_attempts = 10

# Fallback to TCP on DNS errors. Set this to false if unsupported by nameserver.
#dns_tcp_fallback = true

# Enable to query all nameservers until the domain is found. Referred to as "trust_negative_responses" in hickory_resolver.
# This can avoid useless DNS queries if the first nameserver responds with NXDOMAIN or an empty NOERROR response.
#
# The default is to query one nameserver and stop (false).
#query_all_nameservers = true

# Enables using *only* TCP for querying your specified nameservers instead of UDP.
#
# You very likely do *not* want this. hickory-resolver already falls back to TCP on UDP errors.
# Defaults to false
#query_over_tcp_only = false

# DNS A/AAAA record lookup strategy
#
# Takes a number of one of the following options:
# 1 - Ipv4Only (Only query for A records, no AAAA/IPv6)
# 2 - Ipv6Only (Only query for AAAA records, no A/IPv4)
# 3 - Ipv4AndIpv6 (Query for A and AAAA records in parallel, uses whatever returns a successful response first)
# 4 - Ipv6thenIpv4 (Query for AAAA record, if that fails then query the A record)
# 5 - Ipv4thenIpv6 (Query for A record, if that fails then query the AAAA record)
#
# If you don't have IPv6 networking, then for better performance it may be suitable to set this to Ipv4Only (1) as
# you will never ever use the AAAA record contents even if the AAAA record is successful instead of the A record.
#
# Defaults to 5 - Ipv4ThenIpv6 as this is the most compatible and IPv4 networking is currently the most prevalent.
#ip_lookup_strategy = 5


### Request Timeouts, Connection Timeouts, and Connection Pooling

## Request Timeouts are HTTP response timeouts
## Connection Timeouts are TCP connection timeouts
##
## Connection Pooling Timeouts are timeouts for keeping an open idle connection alive.
## Connection pooling and keepalive is very useful for federation or other places where for performance reasons,
## we want to keep connections open that we will re-use frequently due to TCP and TLS 1.3 overhead/expensiveness.
##
## Generally these defaults are the best, but if you find a reason to need to change these they are here.

# Default/base connection timeout.
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 10 seconds
#request_conn_timeout = 10

# Default/base request timeout. The time waiting to receive more data from another server.
# This is used only by URL previews, update/news, and misc endpoint checks
#
# Defaults to 35 seconds
#request_timeout = 35

# Default/base request total timeout. The time limit for a whole request. This is set very high to not
# cancel healthy requests while serving as a backstop.
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 320 seconds
#request_total_timeout = 320

# Default/base idle connection pool timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 5 seconds
#request_idle_timeout = 5

# Default/base max idle connections per host
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 1 as generally the same open connection can be re-used
#request_idle_per_host = 1

# Federation well-known resolution connection timeout
#
# Defaults to 6 seconds
#well_known_conn_timeout = 6

# Federation HTTP well-known resolution request timeout
#
# Defaults to 10 seconds
#well_known_timeout = 10

# Federation client request timeout
# You most definitely want this to be high to account for extremely large room joins, slow homeservers, your own resources etc.
#
# Defaults to 300 seconds
#federation_timeout = 300

# Federation client idle connection pool timeout
#
# Defaults to 25 seconds
#federation_idle_timeout = 25

# Federation client max idle connections per host
#
# Defaults to 1 as generally the same open connection can be re-used
#federation_idle_per_host = 1

# Federation sender request timeout
# The time it takes for the remote server to process sent transactions can take a while.
#
# Defaults to 180 seconds
#sender_timeout = 180

# Federation sender idle connection pool timeout
#
# Defaults to 180 seconds
#sender_idle_timeout = 180

# Federation sender transaction retry backoff limit
#
# Defaults to 86400 seconds
#sender_retry_backoff_limit = 86400

# Appservice URL request connection timeout
#
# Defaults to 35 seconds as generally appservices are hosted within the same network
#appservice_timeout = 35

# Appservice URL idle connection pool timeout
#
# Defaults to 300 seconds
#appservice_idle_timeout = 300

# Notification gateway pusher idle connection pool timeout
#
# Defaults to 15 seconds
#pusher_idle_timeout = 15


### Presence / Typing Indicators / Read Receipts

# Config option to control local (your server only) presence updates/requests. Defaults to true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, this MUST be enabled.
#
#allow_local_presence = true

# Config option to control incoming federated presence updates/requests. Defaults to true.
# This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
#
#allow_incoming_presence = true

# Config option to control outgoing presence updates/requests. Defaults to true.
# This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, you MUST enable `allow_local_presence` as well.
#
#allow_outgoing_presence = true

# Config option to enable the presence idle timer for remote users. Disabling is offered as an optimization for
# servers participating in many large rooms or when resources are limited. Disabling it may cause incorrect
# presence states (i.e. stuck online) to be seen for some remote users. Defaults to true.
#presence_timeout_remote_users = true

# Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes.
#presence_idle_timeout_s = 300

# Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes.
#presence_offline_timeout_s = 1800

# Config option to control whether we should receive remote incoming read receipts.
# Defaults to true.
#allow_incoming_read_receipts = true

# Config option to control whether we should send read receipts to remote servers.
# Defaults to true.
#allow_outgoing_read_receipts = true

# Config option to control outgoing typing updates to federation. Defaults to true.
#allow_outgoing_typing = true

# Config option to control incoming typing updates from federation. Defaults to true.
#allow_incoming_typing = true

# Config option to control maximum time federation user can indicate typing.
#typing_federation_timeout_s = 30

# Config option to control minimum time local client can indicate typing. This does not override
# a client's request to stop typing. It only enforces a minimum value in case of no stop request.
#typing_client_timeout_min_s = 15

# Config option to control maximum time local client can indicate typing.
#typing_client_timeout_max_s = 45


### TURN / VoIP

# vector list of TURN URIs/servers to use
#
# No default
#turn_uris = ["turn:example.turn.uri?transport=udp", "turn:example.turn.uri?transport=tcp"]

# TURN secret to use for generating the HMAC-SHA1 hash apart of username and password generation
#
# this is more secure, but if needed you can use traditional username/password below.
#
# no default
#turn_secret = ""

# TURN username to provide the client
#
# no default
#turn_username = ""

# TURN password to provide the client
#
# no default
#turn_password = ""

# TURN TTL
#
# Default is 86400 seconds
#turn_ttl = 86400

# allow guests/unauthenticated users to access TURN credentials
#
# this is the equivalent of Synapse's `turn_allow_guests` config option. this allows
# any unauthenticated user to call `/_matrix/client/v3/voip/turnServer`.
#
# defaults to false
#turn_allow_guests = false


# Other options not in [global]:
#
#
# Enables running conduwuit with direct TLS support
# It is strongly recommended you use a reverse proxy instead. This is primarily relevant for test suites like complement that require a private CA setup.
# [global.tls]
# certs = "/path/to/my/certificate.crt"
# key = "/path/to/my/private_key.key"
#
# Whether to listen and allow for HTTP and HTTPS connections (insecure!)
# This config option is only available if conduwuit was built with `axum_dual_protocol` feature (not default feature)
# Defaults to false
#dual_protocol = false


# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#
#[global.well_known]
#server = "matrix.example.com:443"
#client = "https://matrix.example.com"
#
# A single contact and/or support page for /.well-known/matrix/support
# All options here are strings. Currently only supports 1 single contact.
# No default.
#
#support_page = ""
#support_role = ""
#support_email = ""
#support_mxid = ""

Debian systemd unit file

Debian systemd unit file
[Unit]
Description=conduwuit Matrix homeserver
Documentation=https://conduwuit.puppyirl.gay/
After=network-online.target

[Service]
DynamicUser=yes
User=conduwuit
Group=conduwuit
Type=notify

Environment="CONDUWUIT_CONFIG=/etc/conduwuit/conduwuit.toml"

ExecStart=/usr/sbin/conduwuit

ReadWritePaths=/var/lib/conduwuit /etc/conduwuit

AmbientCapabilities=
CapabilityBoundingSet=

DevicePolicy=closed
LockPersonality=yes
MemoryDenyWriteExecute=yes
NoNewPrivileges=yes
ProcSubset=pid
ProtectClock=yes
ProtectControlGroups=yes
ProtectHome=yes
ProtectHostname=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectProc=invisible
ProtectSystem=strict
PrivateDevices=yes
PrivateMounts=yes
PrivateTmp=yes
PrivateUsers=yes
PrivateIPC=yes
RemoveIPC=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service @resources
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
SystemCallErrorNumber=EPERM
#StateDirectory=conduwuit

RuntimeDirectory=conduwuit
RuntimeDirectoryMode=0750

Restart=on-failure
RestartSec=5

TimeoutStopSec=2m
TimeoutStartSec=2m

StartLimitInterval=1m
StartLimitBurst=5

[Install]
WantedBy=multi-user.target

Arch Linux systemd unit file

Arch Linux systemd unit file
[Unit]
Description=conduwuit Matrix homeserver
After=network.target
Documentation=https://conduwuit.puppyirl.gay/
RequiresMountsFor=/var/lib/private/conduwuit

[Service]
DynamicUser=yes
Type=notify

AmbientCapabilities=
CapabilityBoundingSet=

DevicePolicy=closed
LockPersonality=yes
MemoryDenyWriteExecute=yes
NoNewPrivileges=yes
ProcSubset=pid
ProtectClock=yes
ProtectControlGroups=yes
ProtectHome=yes
ProtectHostname=yes
ProtectKernelLogs=yes
ProtectKernelModules=yes
ProtectKernelTunables=yes
ProtectProc=invisible
ProtectSystem=strict
PrivateDevices=yes
PrivateMounts=yes
PrivateTmp=yes
PrivateUsers=yes
PrivateIPC=yes
RemoveIPC=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service @resources
SystemCallFilter=~@clock @debug @module @mount @reboot @swap @cpu-emulation @obsolete @timer @chown @setuid @privileged @keyring @ipc
SystemCallErrorNumber=EPERM
StateDirectory=conduwuit

RuntimeDirectory=conduwuit
RuntimeDirectoryMode=0750

Environment="CONDUWUIT_CONFIG=/etc/conduwuit/conduwuit.toml"
BindPaths=/var/lib/private/conduwuit:/var/lib/matrix-conduit
BindPaths=/var/lib/private/conduwuit:/var/lib/private/matrix-conduit

ExecStart=/usr/bin/conduwuit
Restart=on-failure
RestartSec=5

TimeoutStopSec=4m
TimeoutStartSec=4m

StartLimitInterval=1m
StartLimitBurst=5

[Install]
WantedBy=multi-user.target

Deploying

This chapter describes various ways to deploy conduwuit.

Generic deployment documentation

Getting help

If you run into any problems while setting up conduwuit, ask us in #conduwuit:puppygock.gay or open an issue on GitHub.

Installing conduwuit

You may simply download the binary that fits your machine. Run uname -m to see what you need.

Prebuilt binaries can be downloaded from the latest tagged release here.

The latest tagged release also includes the Debian packages.

Alternatively, you may compile the binary yourself. We recommend using Lix to build conduwuit as this has the most guaranteed reproducibiltiy and easiest to get a build environment and output going.

Otherwise, follow standard Rust project build guides (installing git and cloning the repo, getting the Rust toolchain via rustup, installing LLVM toolchain + libclang, installing liburing for io_uring and RocksDB, etc).

Adding a conduwuit user

While conduwuit can run as any user it is better to use dedicated users for different services. This also allows you to make sure that the file permissions are correctly set up.

In Debian or Fedora/RHEL, you can use this command to create a conduwuit user:

sudo adduser --system conduwuit --group --disabled-login --no-create-home

For distros without adduser:

sudo useradd -r --shell /usr/bin/nologin --no-create-home conduwuit

Forwarding ports in the firewall or the router

conduwuit uses the ports 443 and 8448 both of which need to be open in the firewall.

If conduwuit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.

Setting up a systemd service

The systemd unit for conduwuit can be found here. You may need to change the ExecStart= path to where you placed the conduwuit binary.

Creating the conduwuit configuration file

Now we need to create the conduwuit's config file in /etc/conduwuit/conduwuit.toml. The example config can be found at conduwuit-example.toml.Please take a moment to read it. You need to change at least the server name.

RocksDB is the only supported database backend.

Setting the correct file permissions

If you are using a dedicated user for conduwuit, you will need to allow it to read the config. To do that you can run this:

sudo chown -R root:root /etc/conduwuit
sudo chmod -R 755 /etc/conduwuit

If you use the default database path you also need to run this:

sudo mkdir -p /var/lib/conduwuit/
sudo chown -R conduwuit:conduwuit /var/lib/conduwuit/
sudo chmod 700 /var/lib/conduwuit/

Setting up the Reverse Proxy

Refer to the documentation or various guides online of your chosen reverse proxy software. A Caddy example will be provided as this is the recommended reverse proxy for new users and is very trivial to use (handles TLS, reverse proxy headers, etc transparently with proper defaults).

Lighttpd is not supported as it seems to mess with the X-Matrix Authorization header, making federation non-functional. If using Apache, you need to use nocanon to prevent this.

Caddy

Create /etc/caddy/conf.d/conduwuit_caddyfile and enter this (substitute for your server name).

your.server.name, your.server.name:8448 {
        # TCP
        reverse_proxy 127.0.0.1:6167

        # UNIX socket
        #reverse_proxy unix//run/conduwuit/conduwuit.sock
}

That's it! Just start and enable the service and you're set.

sudo systemctl enable --now caddy

You're done

Now you can start conduwuit with:

sudo systemctl start conduwuit

Set it to start automatically when your system boots with:

sudo systemctl enable conduwuit

How do I know it works?

You can open a Matrix client, enter your homeserver and try to register.

You can also use these commands as a quick health check (replace your.server.name).

$ curl https://your.server.name/_conduwuit/server_version

# If using port 8448
$ curl https://your.server.name:8448/_conduwuit/server_version
  • To check if your server can talk with other homeservers, you can use the Matrix Federation Tester. If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.

What's next?

Audio/Video calls

For Audio/Video call functionality see the TURN Guide.

Appservices

If you want to set up an appservice, take a look at the Appservice Guide.

conduwuit for NixOS

conduwuit can be acquired by Lix from various places:

  • The flake.nix at the root of the repo
  • The default.nix at the root of the repo
  • From conduwuit's binary cache

A binary cache for conduwuit that the CI/CD publishes to is available at the following places (both are the same just different names):

https://attic.kennel.juneis.dog/conduit
conduit:eEKoUwlQGDdYmAI/Q/0slVlegqh/QmAvQd7HBSm21Wk=

https://attic.kennel.juneis.dog/conduwuit
conduwuit:BbycGUgTISsltcmH0qNjFR9dbrQNYgdIAcmViSGoVTE=

The binary caches have been recreated recently due to attic issues. The old public keys were:

conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=

conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=

If specifying a URL in your flake, please use the GitHub remote: github:girlbossceo/conduwuit

The flake.nix and default.nix do not (currently) provide a NixOS module, so (for now) services.matrix-conduit from Nixpkgs should be used to configure conduwuit.

If you want to run the latest code, you should get conduwuit from the flake.nix or default.nix and set services.matrix-conduit.package appropriately.

conduwuit for Docker

Docker

To run conduwuit with Docker you can either build the image yourself or pull it from a registry.

Use a registry

OCI images for conduwuit are available in the registries listed below.

RegistryImageSizeNotes
GitHub Registryghcr.io/girlbossceo/conduwuit:latestImage SizeStable tagged image.
GitLab Registryregistry.gitlab.com/conduwuit/conduwuit:latestImage SizeStable tagged image.
Docker Hubdocker.io/girlbossceo/conduwuit:latestImage SizeStable tagged image.
GitHub Registryghcr.io/girlbossceo/conduwuit:mainImage SizeStable main branch.
GitLab Registryregistry.gitlab.com/conduwuit/conduwuit:mainImage SizeStable main branch.
Docker Hubdocker.io/girlbossceo/conduwuit:mainImage SizeStable main branch.

Use

docker image pull <link>

to pull it to your machine.

Run

When you have the image you can simply run it with

docker run -d -p 8448:6167 \
  -v db:/var/lib/conduwuit/ \
  -e CONDUWUIT_SERVER_NAME="your.server.name" \
  -e CONDUWUIT_DATABASE_BACKEND="rocksdb" \
  -e CONDUWUIT_ALLOW_REGISTRATION=false \
  --name conduit <link>

or you can use docker compose.

The -d flag lets the container run in detached mode. You may supply an optional conduwuit.toml config file, the example config can be found here. You can pass in different env vars to change config values on the fly. You can even configure conduwuit completely by using env vars. For an overview of possible values, please take a look at the docker-compose.yml file.

If you just want to test conduwuit for a short time, you can use the --rm flag, which will clean up everything related to your container after you stop it.

Docker-compose

If the docker run command is not for you or your setup, you can also use one of the provided docker-compose files.

Depending on your proxy setup, you can use one of the following files;

When picking the traefik-related compose file, rename it so it matches docker-compose.yml, and rename the override file to docker-compose.override.yml. Edit the latter with the values you want for your server.

When picking the caddy-docker-proxy compose file, it's important to first create the caddy network before spinning up the containers:

docker network create caddy

After that, you can rename it so it matches docker-compose.yml and spin up the containers!

Additional info about deploying conduwuit can be found here.

Build

To build the conduwuit image with docker-compose, you first need to open and modify the docker-compose.yml file. There you need to comment the image: option and uncomment the build: option. Then call docker compose with:

docker compose up

This will also start the container right afterwards, so if want it to run in detached mode, you also should use the -d flag.

Run

If you already have built the image or want to use one from the registries, you can just start the container and everything else in the compose file in detached mode with:

docker compose up -d

Note: Don't forget to modify and adjust the compose file to your needs.

Use Traefik as Proxy

As a container user, you probably know about Traefik. It is a easy to use reverse proxy for making containerized app and services available through the web. With the two provided files, docker-compose.for-traefik.yml (or docker-compose.with-traefik.yml) and docker-compose.override.yml, it is equally easy to deploy and use conduwuit, with a little caveat. If you already took a look at the files, then you should have seen the well-known service, and that is the little caveat. Traefik is simply a proxy and loadbalancer and is not able to serve any kind of content, but for conduwuit to federate, we need to either expose ports 443 and 8448 or serve two endpoints .well-known/matrix/client and .well-known/matrix/server.

With the service well-known we use a single nginx container that will serve those two files.

Voice communication

See the TURN page.

conduwuit for Arch Linux

Currently conduwuit is only on the Arch User Repository (AUR).

The conduwuit AUR packages are community maintained and are not maintained by conduwuit development team, but the AUR package maintainers are in the Matrix room. Please attempt to verify your AUR package's PKGBUILD file looks fine before asking for support.

conduwuit for Debian

Information about downloading and deploying the Debian package. This may also be referenced for other apt-based distros such as Ubuntu.

Installation

It is recommended to see the generic deployment guide for further information if needed as usage of the Debian package is generally related.

Configuration

When installed, the example config is placed at /etc/conduwuit/conduwuit.toml as the default config. At the minimum, you will need to change your server_name here.

You can tweak more detailed settings by uncommenting and setting the config options in /etc/conduwuit/conduwuit.toml.

Running

The package uses the conduwuit.service systemd unit file to start and stop conduwuit. The binary is installed at /usr/sbin/conduwuit.

This package assumes by default that conduwuit will be placed behind a reverse proxy. The default config options apply (listening on localhost and TCP port 6167). Matrix federation requires a valid domain name and TLS, so you will need to set up TLS certificates and renewal for it to work properly if you intend to federate.

Consult various online documentation and guides on setting up a reverse proxy and TLS. Caddy is documented at the generic deployment guide as it's the easiest and most user friendly.

Setting up TURN/STURN

In order to make or receive calls, a TURN server is required. conduwuit suggests using Coturn for this purpose, which is also available as a Docker image.

Configuration

Create a configuration file called coturn.conf containing:

use-auth-secret
static-auth-secret=<a secret key>
realm=<your server domain>

A common way to generate a suitable alphanumeric secret key is by using pwgen -s 64 1.

These same values need to be set in conduwuit. See the example config in the TURN section for configuring these and restart conduwuit after.

Run

Run the Coturn image using

docker run -d --network=host -v $(pwd)/coturn.conf:/etc/coturn/turnserver.conf coturn/coturn

or docker-compose. For the latter, paste the following section into a file called docker-compose.yml and run docker compose up -d in the same directory.

version: 3
services:
    turn:
      container_name: coturn-server
      image: docker.io/coturn/coturn
      restart: unless-stopped
      network_mode: "host"
      volumes:
        - ./coturn.conf:/etc/coturn/turnserver.conf

To understand why the host networking mode is used and explore alternative configuration options, please visit Coturn's Docker documentation.

For security recommendations see Synapse's Coturn documentation.

Setting up Appservices

Getting help

If you run into any problems while setting up an Appservice: ask us in #conduwuit:puppygock.gay or open an issue on GitHub.

Set up the appservice - general instructions

Follow whatever instructions are given by the appservice. This usually includes downloading, changing its config (setting domain, homeserver url, port etc.) and later starting it.

At some point the appservice guide should ask you to add a registration yaml file to the homeserver. In Synapse you would do this by adding the path to the homeserver.yaml, but in conduwuit you can do this from within Matrix:

First, go into the #admins room of your homeserver. The first person that registered on the homeserver automatically joins it. Then send a message into the room like this:

!admin appservices register
```
paste
the
contents
of
the
yaml
registration
here
```

You can confirm it worked by sending a message like this: !admin appservices list

The server bot should answer with Appservices (1): your-bridge

Then you are done. conduwuit will send messages to the appservices and the appservice can send requests to the homeserver. You don't need to restart conduwuit, but if it doesn't work, restarting while the appservice is running could help.

Appservice-specific instructions

Remove an appservice

To remove an appservice go to your admin room and execute

!admin appservices unregister <name>

where <name> one of the output of appservices list.

Maintaining your conduwuit setup

Moderation

conduwuit has moderation through admin room commands. "binary commands" (medium priority) and an admin API (low priority) is planned. Some moderation-related config options are available in the example config such as "global ACLs" and blocking media requests to certain servers. See the example config for the moderation config options under the "Moderation / Privacy / Security" section.

conduwuit has moderation admin commands for:

  • managing room aliases (!admin rooms alias)
  • managing room directory (!admin rooms directory)
  • managing room banning/blocking and user removal (!admin rooms moderation)
  • managing user accounts (!admin users)
  • fetching /.well-known/matrix/support from servers (!admin federation)
  • blocking incoming federation for certain rooms (not the same as room banning) (!admin federation)
  • deleting media (see the media section)

Any commands with -list in them will require a codeblock in the message with each object being newline delimited. An example of doing this is:

!admin rooms moderation ban-list-of-rooms
```
!roomid1:server.name
!roomid2:server.name
!roomid3:server.name
```

Database

If using RocksDB, there's very little you need to do. Compaction is ran automatically based on various defined thresholds tuned for conduwuit to be high performance with the least I/O amplifcation or overhead. Manually running compaction is not recommended, or compaction via a timer. RocksDB is built with io_uring support via liburing for async read I/O.

Some RocksDB settings can be adjusted such as the compression method chosen. See the RocksDB section in the example config. btrfs users may benefit from disabling compression on RocksDB if CoW is in use.

RocksDB troubleshooting can be found in the RocksDB section of troubleshooting.

Backups

Currently only RocksDB supports online backups. If you'd like to backup your database online without any downtime, see the !admin server command for the backup commands and the database_backup_path config options in the example config. Please note that the format of the database backup is not the exact same. This is unfortunately a bad design choice by Facebook as we are using the database backup engine API from RocksDB, however the data is still there and can still be joined together.

To restore a backup from an online RocksDB backup:

  • shutdown conduwuit
  • create a new directory for merging together the data
  • in the online backup created, copy all .sst files in $DATABASE_BACKUP_PATH/shared_checksum to your new directory
  • trim all the strings so instead of ######_sxxxxxxxxx.sst, it reads ######.sst. A way of doing this with sed and bash is for file in *.sst; do mv "$file" "$(echo "$file" | sed 's/_s.*/.sst/')"; done
  • copy all the files in $DATABASE_BACKUP_PATH/1 (or the latest backup number if you have multiple) to your new directory
  • set your database_path config option to your new directory, or replace your old one with the new one you crafted
  • start up conduwuit again and it should open as normal

If you'd like to do an offline backup, shutdown conduwuit and copy your database_path directory elsewhere. This can be restored with no modifications needed.

Backing up media is also just copying the media/ directory from your database directory.

Media

Media still needs various work, however conduwuit implements media deletion via:

  • MXC URI or Event ID (unencrypted and attempts to find the MXC URI in the event)
  • Delete list of MXC URIs
  • Delete remote media in the past N seconds/minutes via filesystem metadata on the file created time (btime) or file modified time (mtime)

See the !admin media command for further information. All media in conduwuit is stored at $DATABASE_DIR/media. This will be configurable soon.

If you are finding yourself needing extensive granular control over media, we recommend looking into Matrix Media Repo. conduwuit intends to implement various utilities for media, but MMR is dedicated to extensive media management.

Built-in S3 support is also planned, but for now using a "S3 filesystem" on media/ works. conduwuit also sends a Cache-Control header of 1 year and immutable for all media requests (download and thumbnail) to reduce unnecessary media requests from browsers, reduce bandwidth usage, and reduce load.

Troubleshooting conduwuit

Docker users ⚠️

Docker is extremely UX unfriendly. Because of this, a ton of issues or support is actually Docker support, not conduwuit support. We also cannot document the ever-growing list of Docker issues here.

If you intend on asking for support and you are using Docker, PLEASE triple validate your issues are NOT because you have a misconfiguration in your Docker setup.

If there are things like Compose file issues or Dockerhub image issues, those can still be mentioned as long as they're something we can fix.

Rocksdb / database issues

Direct IO

Some filesystems may not like RocksDB using Direct IO. Direct IO is for non-buffered I/O which improves conduwuit performance, but at least FUSE is a filesystem potentially known to not like this. See the example config for disabling it if needed. Issues from Direct IO on unsupported filesystems are usually shown as startup errors.

Database corruption

If your database is corrupted and is failing to start (e.g. checksum mismatch), it may be recoverable but careful steps must be taken, and there is no guarantee it may be recoverable.

The first thing that can be done is launching conduwuit with the rocksdb_repair config option set to true. This will tell RocksDB to attempt to repair itself at launch. If this does not work, disable the option and continue reading.

RocksDB has the following recovery modes:

  • TolerateCorruptedTailRecords
  • AbsoluteConsistency
  • PointInTime
  • SkipAnyCorruptedRecord

By default, conduwuit uses TolerateCorruptedTailRecords as generally these may be due to bad federation and we can re-fetch the correct data over federation. The RocksDB default is PointInTime which will attempt to restore a "snapshot" of the data when it was last known to be good. This data can be either a few seconds old, or multiple minutes prior. PointInTime may not be suitable for default usage due to clients and servers possibly not being able to handle sudden "backwards time travels", and AbsoluteConsistency may be too strict.

AbsoluteConsistency will fail to start the database if any sign of corruption is detected. SkipAnyCorruptedRecord will skip all forms of corruption unless it forbids the database from opening (e.g. too severe). Usage of SkipAnyCorruptedRecord voids any support as this may cause more damage and/or leave your database in a permanently inconsistent state, but it may do something if PointInTime does not work as a last ditch effort.

With this in mind:

  • First start conduwuit with the PointInTime recovery method. See the example config for how to do this using rocksdb_recovery_mode
  • If your database successfully opens, clients are recommended to clear their client cache to account for the rollback
  • Leave your conduwuit running in PointInTime for at least 30-60 minutes so as much possible corruption is restored
  • If all goes will, you should be able to restore back to using TolerateCorruptedTailRecords and you have successfully recovered your database

Media

Debugging

Note that users should not really be debugging things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. Various debug commands can be found in !admin debug.

Debug/Trace log level

conduwuit builds without debug or trace log levels by default for at least performance reasons. This may change in the future and/or binaries providing such configurations may be provided. If you need to access debug/trace log levels, you will need to build without the release_max_log_level feature.

Changing log level dynamically

conduwuit supports changing the tracing log environment filter on-the-fly using the admin command !admin debug change-log-level. This accepts a string without quotes the same format as the log config option.

Pinging servers

conduwuit can ping other servers using !admin debug ping. This takes a server name and goes through the server discovery process and queries /_matrix/federation/v1/version. Errors are outputted.

Allocator memory stats

When using jemalloc with jemallocator's stats feature, you can see conduwuit's jemalloc memory stats by using !admin debug memory-stats

Development

Information about developing the project. If you are only interested in using it, you can safely ignore this section. If you plan on contributing, see the contributor's guide.

Debugging with tokio-console

tokio-console can be a useful tool for debugging and profiling. To make a tokio-console-enabled build of conduwuit, enable the tokio_console feature, disable the default release_max_log_level feature, and set the --cfg tokio_unstable flag to enable experimental tokio APIs. A build might look like this:

RUSTFLAGS="--cfg tokio_unstable" cargo build \
    --release \
    --no-default-features \
    --features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console

Contributing guide

This page is for about contributing to conduwuit. The development page may be of interest for you as well.

If you would like to work on an issue that is not assigned, preferably ask in the Matrix room first at #conduwuit:puppygock.gay, and comment on it.

Linting and Formatting

It is mandatory all your changes satisfy the lints (clippy, rustc, rustdoc, etc) and your code is formatted via the nightly cargo fmt. A lot of the rustfmt.toml features depend on nightly toolchain. It would be ideal if they weren't nightly-exclusive features, but they currently still are. CI's rustfmt uses nightly.

If you need to allow a lint, please make sure it's either obvious as to why (e.g. clippy saying redundant clone but it's actually required) or it has a comment saying why. Do not write inefficient code for the sake of satisfying lints. If a lint is wrong and provides a more inefficient solution or suggestion, allow the lint and mention that in a comment.

Running CI tests locally

conduwuit's CI for tests, linting, formatting, audit, etc use engage. engage can be installed from nixpkgs or cargo install engage. conduwuit's Nix flake devshell has the nixpkgs engage with direnv. Use engage --help for more usage details.

To test, format, lint, etc that CI would do, install engage, allow the .envrc file using direnv allow, and run engage.

All of the tasks are defined at the engage.toml file. You can view all of them neatly by running engage list

If you would like to run only a specific engage task group, use just:

  • engage just <group>
  • Example: engage just lints

If you would like to run a specific engage task in a specific group, use just <GROUP> [TASK]: engage just lints cargo-fmt

The following binaries are used in engage.toml:

Matrix tests

CI runs Complement, but currently does not fail if results from the checked-in results differ with the new results. If your changes are done to fix Matrix tests, note that in your pull request. If more Complement tests start failing from your changes, please review the logs (they are uploaded as artifacts) and determine if they're intended or not.

If you'd like to run Complement locally using Nix, see the testing page.

Sytest support will come soon.

Writing documentation

conduwuit's website uses mdbook and deployed via CI using GitHub Pages in the documentation.yml workflow file with Nix's mdbook in the devshell. All documentation is in the docs/ directory at the top level. The compiled mdbook website is also uploaded as an artifact.

To build the documentation using Nix, run: bin/nix-build-and-cache just .#book

The output of the mdbook generation is in result/. mdbooks can be opened in your browser from the individual HTML files without any web server needed.

Inclusivity and Diversity

All MUST code and write with inclusivity and diversity in mind. See the following page by Google on writing inclusive code and documentation.

This EXPLICITLY forbids usage of terms like "blacklist"/"whitelist" and "master"/"slave", forbids gender-specific words and phrases, forbids ableist language like "sanity-check", "cripple", or "insane", and forbids culture-specific language (e.g. US-only holidays or cultures).

No exceptions are allowed. Dependencies that may use these terms are allowed but do not replicate the name in your functions or variables.

In addition to language, write and code with the user experience in mind. This is software that intends to be used by everyone, so make it easy and comfortable for everyone to use. 🏳️‍⚧️

Variable, comment, function, etc standards

Rust's default style and standards with regards to function names, variable names, comments, etc applies here.

Creating pull requests

Please try to keep contributions to the GitHub. While the mirrors of conduwuit allow for pull/merge requests, there is no guarantee I will see them in a timely manner. Additionally, please mark WIP or unfinished or incomplete PRs as drafts. This prevents me from having to ping once in a while to double check the status of it, especially when the CI completed successfully and everything so it looks done.

If you open a pull request on one of the mirrors, it is your responsibility to inform me about its existence. In the future I may try to solve this with more repo bots in the conduwuit Matrix room. There is no mailing list or email-patch support on the sr.ht mirror, but if you'd like to email me a git patch you can do so at strawberry@puppygock.gay.

Direct all PRs/MRs to the main branch.

By sending a pull request or patch, you are agreeing that your changes are allowed to be licenced under the Apache-2.0 licence and all of your conduct is in line with the Contributor's Covenant.

Testing

Complement

Have a look at Complement's repository for an explanation of what it is.

To test against Complement, with Lix and direnv installed and set up, you can:

  • Run ./bin/complement "$COMPLEMENT_SRC" ./path/to/logs.jsonl ./path/to/results.jsonl to build a Complement image, run the tests, and output the logs and results to the specified paths. This will also output the OCI image at result
  • Run nix build .#complement from the root of the repository to just build a Complement OCI image outputted to result (it's a .tar.gz file)
  • Or download the latest Complement OCI image from the CI workflow artifacts output from the commit/revision you want to test (e.g. from main) here

Hot Reloading ("Live" Development)

Summary

When developing in debug-builds with the nightly toolchain, conduwuit is modular using dynamic libraries and various parts of the application are hot-reloadable while the server is running: http api handlers, admin commands, services, database, etc. These are all split up into individual workspace crates as seen in the src/ directory. Changes to sourcecode in a crate rebuild that crate and subsequent crates depending on it. Reloading then occurs for the changed crates.

Release builds still produce static binaries which are unaffected. Rust's soundness guarantees are in full force. Thus you cannot hot-reload release binaries.

Requirements

Currently, this development setup only works on x86_64 and aarch64 Linux glibc. musl explicitly does not support hot reloadable libraries, and does not implement dlclose. macOS does not fully support our usage of RTLD_GLOBAL possibly due to some thread-local issues. This Rust issue may be of relevance, specifically this comment. It may be possible to get it working on only very modern macOS versions such as at least Sonoma, as currently loading dylibs is supported, but not unloading them in our setup, and the cited comment mentions an Apple WWDC confirming there have been TLS changes to somewhat make this possible.

As mentioned above this requires the nightly toolchain. This is due to reliance on various Cargo.toml features that are only available on nightly, most specifically RUSTFLAGS in Cargo.toml. Some of the implementation could also be simpler based on other various nightly features. We hope lots of nightly features start making it out of nightly sooner as there have been dozens of very helpful features that have been stuck in nightly ("unstable") for at least 5+ years that would make this simpler. We encourage greater community consensus to move these features into stability.

This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C library, macOS, and likely other host architectures are not supported (if other architectures work, feel free to let us know and/or make a PR updating this). This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you happen to have linker issues it's recommended to try using mold or gold linkers, and please let us know in the conduwuit Matrix room the linker error and what linker solved this issue so we can figure out a solution. Ideally there should be minimal friction to using this, and in the future a build script (build.rs) may be suitable to making this easier to use if the capabilities allow us.

Usage

As of 19 May 2024, the instructions for using this are:

  1. Have patience. Don't hesitate to join the conduwuit Matrix room to receive help using this. As indicated by the various rustflags used and some of the interesting issues linked at the bottom, this is definitely not something the Rust ecosystem or toolchain is used to doing.

  2. Install the nightly toolchain using rustup. You may need to use rustup override set nightly in your local conduwuit directory, or use cargo +nightly for all actions.

  3. Uncomment cargo-features at the top level / root Cargo.toml

  4. Scroll down to the # Developer profile section and uncomment ALL the rustflags for each dev profile and their respective packages.

  5. In each workspace crate's Cargo.toml (everything under src/* AND deps/rust-rocksdb/Cargo.toml), uncomment the dylib crate type under [lib].

  6. Due to this rpath issue, you must export the LD_LIBRARY_PATH environment variable to your nightly Rust toolchain library directory. If using rustup (hopefully), use this: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/

  7. Start the server. You can use cargo +nightly run for this along with the standard.

  8. Make some changes where you need to.

  9. In a separate terminal window in the same directory (or using a terminal multiplexer like tmux), run the build Cargo command cargo +nightly build. Cargo should only rebuild what was changed / what's necessary, so it should not be rebuilding all the crates.

  10. In your conduwuit server terminal, hit/send CTRL+C signal. This will tell conduwuit to find which libraries need to be reloaded, and reloads them as necessary.

  11. If there were no errors, it will tell you it successfully reloaded # modules, and your changes should now be visible. Repeat 7 - 9 as needed.

To shutdown conduwuit in this setup, hit/send CTRL+\. Normal builds still shutdown with CTRL+C as usual.

Steps 1 - 5 are the initial first-time steps for using this. To remove the hot reload setup, revert/comment all the Cargo.toml changes.

As mentioned in the requirements section, if you happen to have some linker issues, try using the -fuse-ld= rustflag and specify mold or gold in all the rustflags definitions in the top level Cargo.toml, and please let us know in the conduwuit Matrix room the problem. mold can be installed typically through your distro, and gold is provided by the binutils package.

It's possible a helper script can be made to do all of this, or most preferably a specially made build script (build.rs). cargo watch support will be implemented soon which will eliminate the need to manually run cargo build all together.

Addendum

Conduit was inherited as a single crate without modularity or reloading in its design. Reasonable partitioning and abstraction allowed a split into several crates, though many circular dependencies had to be corrected. The resulting crates now form a directed graph as depicted in figures below. The interfacing between these crates is still extremely broad which is not mitigable.

Initially hot_lib_reload was investigated but found appropriate for a project designed with modularity through limited interfaces, not a large and complex existing codebase. Instead a bespoke solution built directly on libloading satisfied our constraints. This required relatively minimal modifications and zero maintenance burden compared to what would be required otherwise. The technical difference lies with relocation processing: we leverage global bindings (RTLD_GLOBAL) in a very intentional way. Most libraries and off-the-shelf module systems (such as hot_lib_reload) restrict themselves to local bindings (RTLD_LOCAL). This allows them to release software to multiple platforms with much greater consistency, but at the cost of burdening applications to explicitly manage these bindings. In our case with an optional feature for developers, we shrug any such requirement to enjoy the cost/benefit on platforms where global relocations are properly cooperative.

To make use of RTLD_GLOBAL the application has to be oriented as a directed acyclic graph. The primary rule is simple and illustrated in the figure below: no crate is allowed to call a function or use a variable from a crate below it.

conduwuit's dynamic library setup diagram - created by Jason Volk

When a symbol is referenced between crates they become bound: crates cannot be unloaded until their calling crates are first unloaded. Thus we start the reloading process from the crate which has no callers. There is a small problem though: the first crate is called by the base executable itself! This is solved by using an RTLD_LOCAL binding for just one link between the main executable and the first crate, freeing the executable from all modules as no global binding ever occurs between them.

conduwuit's reload and load order diagram - created by Jason Volk

Proper resource management is essential for reliable reloading to occur. This is a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is remarkably low, generally stemming from poor patterns and practices. Unfortunately static analysis doesn't enforce reload-safety programmatically (though it could one day), for now hazards can be avoided by knowing a few basic do's and dont's:

  1. Understand that code is memory. Just like one is forbidden from referencing free'd memory, one must not transfer control to free'd code. Exposure to this is primarily from two things:
  • Callbacks, which this project makes very little use of.
  • Async tasks, which are addressed below.
  1. Tie all resources to a scope or object lifetime with greatest possible symmetry (locality). For our purposes this applies to code resources, which means async blocks and tokio tasks.
  • Never spawn a task without receiving and storing its JoinHandle.
  • Always wait on join handles before leaving a scope or in another cleanup function called by an owning scope.
  1. Know any minor specific quirks documented in code or here:
  • Don't use tokio::spawn, instead use our Handle in core/server.rs, which is reachable in most of the codebase via services() or other state. This is due to some bugs or assumptions made in tokio, as it happens in unsafe {} blocks, which are mitigated by circumventing some thread-local variables. Using runtime handles is good practice in any case.

The initial implementation PR is available here.

conduwuit Community Code of Conduct

Welcome to the conduwuit community! We’re excited to have you here. conduwuit is a hard-fork of the Conduit homeserver, aimed at making Matrix more accessible and inclusive for everyone.

This space is dedicated to fostering a positive, supportive, and inclusive environment for everyone. This Code of Conduct applies to all conduwuit spaces, including any further community rooms that reference this CoC. Here are our guidelines to help maintain the welcoming atmosphere that sets conduwuit apart.

For the foundational rules, please refer to the Matrix.org Code of Conduct and the Contributor's Covenant. Below are additional guidelines specific to the conduwuit community.

Our Values and Guidelines

  1. Respect and Inclusivity: We are committed to maintaining a community where everyone feels safe and respected. Discrimination, harassment, or hate speech of any kind will not be tolerated. Recognise that each community member experiences the world differently based on their past experiences, background, and identity. Share your own experiences and be open to learning about others' diverse perspectives.

  2. Positivity and Constructiveness: Engage in constructive discussions and support each other. If you feel angry, negative, or aggressive, take a break until you can participate in a positive and constructive manner. Process intense feelings with a friend or in a private setting before engaging in community conversations to help maintain a supportive and focused environment.

  3. Clarity and Understanding: Our community includes neurodivergent individuals and those who may not appreciate sarcasm or subtlety. Communicate clearly and kindly, avoiding sarcasm and ensuring your messages are easily understood by all. Additionally, avoid putting the burden of education on marginalized groups by doing your own research before asking for explanations.

  4. Be Open to Inclusivity: Actively engage in conversations about making our community more inclusive. Report discriminatory behavior to the moderators and be open to constructive feedback that aims to improve our community. Understand that discussing discrimination and negative experiences can be emotionally taxing, so focus on the message rather than critiquing the tone used.

  5. Commit to Inclusivity: Building an inclusive community requires time, energy, and resources. Recognise that addressing discrimination and bias is an ongoing process that necessitates commitment and action from all community members.

Matrix Community

This Code of Conduct applies to the entire conduwuit Matrix Space and its rooms, including:

#conduwuit:puppygock.gay

This room is for support and discussions about conduwuit. Ask questions, share insights, and help each other out.

#conduwuit-offtopic:girlboss.ceo

For off-topic community conversations about any subject. While this room allows for a wide range of topics, the same CoC applies. Keep discussions respectful and inclusive, and avoid divisive subjects like country/world politics. General topics, such as world events, are welcome as long as they follow the CoC.

#conduwuit-dev:puppygock.gay

This room is dedicated to discussing active development of conduwuit. Posting requires an elevated power level, which can be requested in one of the other rooms. Use this space to collaborate and innovate.

Enforcement

We have a zero-tolerance policy for violations of this Code of Conduct. If someone’s behavior makes you uncomfortable, please report it to the moderators. Actions we may take include:

  1. Warning: A warning given directly in the room or via a private message from the moderators, identifying the violation and requesting corrective action.
  2. Temporary Mute: Temporary restriction from participating in discussions for a specified period to allow for reflection and cooling off.
  3. Kick or Ban: Egregious behavior may result in an immediate kick or ban to protect other community members. Bans are considered permanent and will only be reversed in exceptional circumstances after proven good behavior.

Please highlight issues directly in rooms when possible, but if you don't feel comfortable doing that, then please send a DM to one of the moderators directly.

Together, let’s build a community where everyone feels valued and respected.

  • The conduwuit Moderation Team