![]() |
The TeXmacs server | ![]() |
A server is an ordinary TeXmacs process with server mode enabled. The relevant command line options are parsed in
Texmacs/Texmacs/texmacs.cpp
:
Enable server mode (set_server). At the end of the initialization, server_start is called provided that server_can_start succeeds. The latter refuses to start when GnuTLS is available, the preference "tls-server" is on and no certificate is present.
Override the preference "server port" (default 6561).
Run without graphical interface. In headless mode, TeXmacs normally quits after the command line has been processed, but not in server mode.
Call server-reset-preferences resp. server-reset-admin-password when the server starts. The new administrator password is written to the server log (and shown in an auxiliary buffer when a graphical interface is present).
Remove the directory $TEXMACS_HOME_PATH/server with all accounts, files and the server database.
Client side option: skip the verification of server certificates (useful for headless clients which cannot ask the user to trust a self-signed certificate).
A typical invocation on a machine without display is therefore
texmacs -headless -server -port 6561 |
The environment variable TEXMACS_SERVER_CERT_DIR (default $TEXMACS_HOME_PATH/server) indicates where the certificate cert.pem and the private key key.pem are stored. SIGPIPE is ignored so that a client which aborts its connection does not kill the server.
In a graphical session, the server is started from the menu Remote\(\rightarrow\)Start server, which calls server-safe-start (
server/server-menu.scm
). If TLS is supported and on but no certificate exists, the user is first offered to create a self-signed certificate (open-certificate-warning in
server-widgets.scm
, which ends up in the glue function generate-self-signed-certificate). The server menu also allows to stop and restart the server and to reset the administrator password or the preferences. See also the user documentation Starting and configuring the server and TLS certificates.
After the listening socket has been created, server-create-default-admin-account creates an account admin with a random password of 20 characters if no user exists yet. The password is written to the log with level warning; the administrator is expected to change it immediately.
All server data are stored below $TEXMACS_HOME_PATH/server:
The server database, returned by (global-database) (
database/db-base.scm
) and installed by tm-service as the current database of each service (server-database). It contains one entry per user, file, directory, file version list, live document, chat room, chat message, message and notification.
An association list from user identifiers to (pseudo name credentials email admin?), cached in the table server-users. User entries also exist in the database (with type "user"); the user identifier is currently the pseudo itself (see server-set-user-info).
Accounts waiting for email confirmation and pending credential reset codes.
Templates of the emails sent to users and the license document shown to new users. The email templates are copied from progs/server/server-email-*.txt on first use.
The contents of remote files, live documents and messages. See the remote file system.
The database layer is described in the Scheme modules of
progs/database/
. The points which matter for the server are:
The C++ class database_rep (
Plugins/Database/database.hpp
) stores lines (id, attr, val, created, expires) and never forgets anything unless history is disabled: removing a field or an entry only sets an expiration time. Queries take a time argument, so the state of the database at any past moment can be reconstructed. In Scheme, the time is the global variable db-time, which is :now by default and can be changed with with-time (:always means: at any time). The macro with-time-stamp makes db-create-entry add a "date" field.
Access rights are ordinary fields: "owner", "readable" and "writable" contain lists of user identifiers, where the special value "all" denotes everybody. (db-allow? id uid attr) (
database/db-users.scm
) checks whether uid (or a group it belongs to, see db-expand-user) appears in the field, and owners are allowed everything. (with-user uid …) sets db-current-user, which the wrappers of db-get-field, db-set-field, etc. take into account; (with-user #t …) bypasses the checks. Services usually test db-allow? explicitly.
A client authenticates with a pseudo and a password after the connection (legacy or TLS) has been established; the transport layer itself is anonymous. On the client, a credential is a list such as (tls-password p) or (legacy-password p); the kind determines the transport used by client-login-then. Passwords are sent in clear inside the encrypted channel.
On the server, credentials are stored in a hidden form (password encoding salt hash …), produced by server-hide-credentials and checked by server-password-correct? in
server/server-authentication.scm
. The supported encodings are listed by server-supported-password-encodings:
PBKDF2 with HMAC-SHA256 computed by GnuTLS (glue function hash-password-pbkdf2).
Crypt-style hashes computed by running openssl passwd -6 resp. -5 as an external process (not available on Windows).
No hashing (used for backward compatibility).
The preference "server password encoding" selects the encoding of new passwords (by default the first supported one, i.e. pbkdf2 when GnuTLS is present). When the preference "server password update" is on, server-password-update rehashes a password with the preferred encoding (and a fresh salt if the old one had the wrong length) at the next successful login.
If "server require strong passwords" is on (the default), new passwords must pass server-strong-password?: at least 10 characters, with a lower case letter, an upper case letter, a digit and a symbol.
The service remote-login (
server/server-base.scm
) finds the user with server-find-user, verifies the password with server-password-authentified? and, on success, calls server-login-uid, which records the login time and address, resets the failure counter and stores the association between the connection and the user in server-logged-table (in both directions). Later services retrieve the user with (server-get-user envelope), which returns #f for anonymous connections. The answers are strings: "ready", "pending" (account awaiting confirmation), "user not found", or an error message.
Brute force attacks are limited by server-can-login-uid?: after "server failed login limit" (default 3) failures, logins are refused until "server failed login delay" seconds (default 3600) have elapsed since the last failure. Accounts can also be suspended (server-suspend-user) or marked as deleted.
On the client, client-login-home (
client-widgets.scm
) performs the complete sequence: connect and log in (client-login-then), register the connection with add-active-connection, send the protocol version, fetch the account information, record the account in the client database (user-database "remote") (client-notify-account), open the remote home directory and pull pending notifications. Passwords may be stored in the TeXmacs wallet; the tmfs load handler of remote files uses wallet-get to log in automatically when a document on a server without active connection is opened.
new-account is only allowed if "server service new-account" is on (default off), or when called by an administrator. If "server account confirmation delay" is non negative, the account is first stored as a pending user and an email with a random six digit code is sent using the shell command in "server mail command" (server-send-email; the placeholders $USER_PSEUDO, $USER_NAME, $USER_EMAIL, $USER_CODE and $FILE_NAME are substituted). The service confirm-pending-account turns the pending user into a real one.
remote-reset-credentials (allowed if "server service reset-credentials" is on) emails a one-time code, and remote-login-code logs in with this code.
remote-set-account changes the name, email or credentials of the current user; administrators may pass another user.
remote-delete-account deletes an account after the checks in the macro with-verify-delete-rights: non administrators may only delete themselves and only if "server service delete-account" is on; the admin account cannot be deleted. server-remove-user marks the user as deleted, executes the deletion plan (server-execute-deletion-plan: resources owned by the user which were not shared through chat messages are removed, shared ones are kept), removes the user from all access lists (server-scrub-participations) and deletes its notifications. The service remote-deletion-plan lets the client display this plan beforehand.
Users with the admin flag may read and modify the server preferences remotely (remote-admin-preferences, remote-set-preferences, remote-admin-preferences-form; see
client/client-remote-config.scm
), list the accounts (remote-get-accounts) and evaluate arbitrary Scheme expressions on the server with remote-eval. The latter is equivalent to shell access to the server account and should be kept in mind when granting administrator rights. Each preference guarding a service is a string "on" or "off" declared with define-preferences; see Server preferences for the user level description. Anonymous clients may retrieve the preferences listed in server-all-preferences together with the license through remote-public-preferences, unless disabled by the corresponding "server public: …" preference.
(server-log-write level message) accepts the syslog levels emergency, alert, critical, error, warning, notice, info and debug. In headless mode it calls the glue function server-log-write-int, which uses syslog on Unix (
Plugins/Unix/unix_server_log.cpp
), os_log on macOS (subsystem org.texmacs.logging), and the corresponding modules for Windows; when standard output is a terminal the messages are printed instead. With a graphical interface, the messages go to the debug console channels server-error, server-warning and server-debug.
Chat rooms (
server/server-chat.scm
) are database entries of type "chat-room"; messages are entries of type "chat-message" with fields "action", "from", "to" (the room), "message" and a time stamp. Documents sent to a room (action "send") are stored in the repository as separate entries of type "message", whereas the action "share" stores the URL of the shared resource together with its identifier in "resource-id", so that the link can still be resolved after renaming (resolve-resource-id). Each user has a private room mail-pseudo, which is the mail box.
The server caches the messages of each room in chat-room-messages and remembers which connections have the room open in chat-room-present. When a message is posted (remote-send-message, remote-send), chat-room-notify appends it to the cache and pushes it to all present clients with the call-back chat-room-receive. Messages to a mail box also create a notification: a database entry of type "notification" owned by the recipient, pushed immediately with client-push-notifications if the recipient is logged in, and otherwise retrieved at the next login with remote-pending-notifications. Clients acknowledge notifications with remote-ack-notifications, which deletes them on the server. See also Messages and chat rooms and Shared resources.
Documents with many large images or graphics are expensive to transmit again and again. Since protocol version 1, the server replaces such subtrees by references into a content addressed cache.
The C++ side (Data/Tree/tree_cache.*) maintains, for each host name, a directory $TEXMACS_HOME_PATH/system/tmp/tree_cache/host of serialized trees indexed by a 64-bit hash of the tree (tree_hash), with a least recently used eviction policy (disk_lru, by default at most 1024 entries in memory and 500 MB on disk). tree_cache::update traverses a tree and replaces each subtree for which should_cache holds (images with embedded raw data and graphics) by a cache-ref tree containing the hash and the original label (for images also the width and height arguments of the image and its size in pixels, so that the client can lay out the document before the image arrives).
On the server, the host name is server-tree-cache-host ("localhost"). remote-file-load and remote-chat-room-open send cached documents to clients for which server-can-handle-cache? holds (preference "server service tree-cache" on and client protocol version at least 1). The service remote-get-cache-ref returns the tree for a hash. A janitor (tree-cache-janitor-all) is run every twelve hours, as soon as the processor has been idle for 30 seconds (delayed with the :on-cpu-idle keyword).
The client (fetch-missing-cache-refs in
client/client-tmfs.scm
) uses its own cache with the server name as host, requests the missing hashes one by one and substitutes the cache-ref trees in the buffer as they arrive, without marking the buffer as modified.
server/server-backup.scm
implements optional periodic snapshots of $TEXMACS_HOME_PATH/server with rsync. When "server service backup" is on and "server backup destination" is set, server-backup-register schedules server-backup-run every "server backup interval" hours (again using :on-cpu-idle). Each run creates a directory named after the current date and time in the destination and calls rsync -a --partial --link-dest=previous, so that unchanged files are hard links into the previous snapshot. server-backup-prune then keeps the newest snapshot per hour, day, month and year up to the counts given by the "server backup keep …" preferences. The comments in the module explain why running rsync on a live server is considered safe (the database is flushed in the idle cycle, file contents are write-once and users.scm is atomically rewritten).
The following points should be kept in mind when deploying a server or modifying the code. Some of them are known limitations of the current implementation.
Transport. Use TLS. In legacy mode the key exchange is done with an unauthenticated RSA key, so it offers no protection against an active attacker. With TLS, the server still accepts anonymous Diffie–Hellman by default ("tls-server authentication anonymous"), and the client does not check that the certificate matches the host name (see the comment near gnutls_session_set_verify_cert in
gnutls.cpp
); when the certificate cannot be verified, the user is asked whether to trust it (trust-certificate-interactive). Disabling anonymous authentication on the server and distributing the server certificate to clients gives the strongest guarantees currently available.
Parsing. Messages are parsed with the Scheme reader and the packet length is not bounded, so a malicious peer can make the server allocate large amounts of memory. Only symbols registered with tm-service can be invoked, but services receive arbitrary S-expressions as arguments and must validate them.
Access control. Every service must check the user and the rights itself. Several services accept anonymous connections: database reads use the pseudo-user "all" when nobody is logged in, remote-search-user can search all user entries (a TODO in the code), and live-exists? does not require a login. Live documents and chat rooms are created readable and writable by "all". The client side permission handler for remote files always answers #t (a FIXME in
client-tmfs.scm
); the server is the only line of defence.
Secrets. Account confirmation and reset codes are six digit numbers produced by the Scheme random function. The helper password-correct-sha512? prints the password being verified with display*, which ends up on the standard output of the server. The administrator password generated at first start is written to the log.
Administrators. remote-eval evaluates arbitrary code and the "server mail command" preference is executed by the shell, so an administrator account is equivalent to a shell account on the server machine.