GNU TeXmacsUser manualReferenceAboutEnglish
Transport and message protocol

1.Overview

Communication between a client and a server goes through three layers:

  1. A byte stream over a TCP socket, optionally wrapped in a TLS session (GnuTLS) or, in “legacy” mode, encrypted with a symmetric key exchanged through OpenSSL.

  2. A packet layer which splits the stream into messages. Each packet is a decimal length, a newline and the payload.

  3. A Scheme layer in which each payload is the printed form of a list (serial command), where command is itself an S-expression naming a service on the server or a call-back on the client, followed by its arguments.

All requests are asynchronous: the sender registers a continuation and an error handler under the serial number of the message, and the receiver eventually answers with a special result or error command which carries the same serial number.

2.Sockets and contacts (C++)

2.1.The socket classes

The socket code lives in

Plugins/Qt/QTMSockets.cpp

(with a copy in

Plugins/Qt6/

). It defines two Qt objects:

socket_server_rep

The listening socket of a server. Its start method binds a non blocking socket on the configured port (all interfaces, IPv4 or IPv6 depending on getaddrinfo), listens with a backlog of 1024 and installs a QSocketNotifier. When the notifier fires, the slot connection accepts the connection, records the peer address in address_from_id, creates a contact (see below), wraps it in a socket_link_rep and calls the Scheme function server-add with the socket number. After a successful start, start also calls server-create-default-admin-account.

socket_link_rep

One end of a connection; it derives from both QObject and tm_link_rep (

System/Link/tm_link.hpp

). Incoming data is accumulated in input_buffer by the slot data_set_ready (reads of at most 16384 bytes), outgoing data is queued in output_buffer and flushed by ready_to_send. For a client side link, a successful start calls client-add; when a link stops it calls server-logout-client and server-remove (server side) or client-remove (client side), so that the Scheme layer can clean up its tables.

A contact (

System/Link/tm_contact.hpp

) abstracts the transport underneath the socket: tm_contact_rep has virtual methods start, stop, send, receive, alive, active and last_error. There are two families:

2.2.The C++ interface

The functions exported to Scheme are declared in

System/Link/client_server.hpp

and implemented in

texmacs_server.cpp

and

texmacs_client.cpp

. The glue is declared in

Scheme/Glue/build-glue-basic.scm

. Sockets are identified on both sides by their integer file descriptor; this integer is what the Scheme code calls a client (on the server) or a server (on the client).

(server-start), (server-stop), (server-started?)
(control the listening socket)

server-start loads the modules (server server-base), (server server-tmfs), (server server-menu), (server server-live) and (server server-backup), optionally resets the server preferences or the administrator password (command line options -reset-server-preferences and -reset-admin-password), and starts a socket_server_rep on get_server_port (): the value given by -port, or else the preference "server port" (default 6561). (server-port-in-use) returns the port of the running server, or 0.

(server-read client), (server-write client s)
(packet input/output on the server)

server-read returns the next complete packet received from client, or the empty string if no complete packet is available. server-write sends s as one packet. (server-client-address client) returns the peer address recorded when the connection was accepted.

(tls-client-start host port credentials), (legacy-client-start host port)
(open a connection to a server)

Connect to a server and return the socket number, or a negative error code. The error codes are TM_NET_* constants in

client_server.hpp

; (server-define-error-codes) defines the corresponding Scheme variables tm_net_success, tm_net_invalid_port, tm_net_no_gnutls, tm_net_connection_failed, etc. The credentials of tls-client-start are a list of lists of strings; the client code always passes '((anonymous)). The Scheme wrappers tls-anonymous-client-start and legacy-anonymous-client-start in

client/client-authentication.scm

are what the rest of the code uses; the legacy wrapper immediately calls (enter-secure-mode server).

(client-read server), (client-write server s), (client-stop server)
(packet input/output on the client)

The client side counterparts of server-read and server-write; client-stop closes the connection. (client-protocol-version) returns the constant TM_PROTOCOL_VERSION of

texmacs_client.cpp

(currently 1, the version which introduced the tree cache).

2.3.Packets and legacy encryption

Packets are produced and parsed by tm_link_rep::write_packet, complete_packet and read_packet in

System/Link/tm_link.cpp

. A packet is the decimal length of the payload, a newline, and the payload itself:

44
(3 (remote-file-load "localhost/~joe/a.tm"))

In legacy mode (when TLS is not used), the client calls tm_link_rep::secure_client right after connecting: it sends the byte ! followed by a packet with its RSA public key. The server recognizes the leading ! in read_packet, generates a random secret with secret_generate, sends it back encrypted with the public key (secure_server), and from then on both sides encrypt each payload with secret_encode/secret_decode. These functions run the external openssl program through temporary files (

Plugins/Openssl/openssl.cpp

). The server itself warns that this mode is weak; it is kept for backward compatibility and for builds without GnuTLS.

3.Serialization and dispatching (Scheme)

3.1.Messages

The Scheme side is symmetric; the server part lives in

server/server-base.scm

, the client part in

client/client-base.scm

. A message is sent with

(tm-define (server-send client cmd)
  (server-write client (object->string* (list server-serial cmd)))
  (set! server-serial (+ server-serial 1)))

and similarly client-send with client-serial. The function object->string* (

kernel/library/base.scm

) prints lists, numbers, strings and symbols with object->string and converts trees to Scheme trees first; any other object is transmitted as #f. Hence arguments of services must be built out of lists, strings, numbers, symbols and booleans. Documents are usually transmitted either as Scheme trees or as strings in the TeXmacs file format (see for instance remote-file-load). The receiver parses the payload with string->object, i.e. with the Scheme reader.

The serial counters are global per process, not per connection; the continuation tables therefore store the connection together with the continuation, and a result is only accepted if it comes from the connection to which the request was sent.

3.2.Polling

The socket notifiers fill the input buffers, but the Scheme layer reads them by polling. When a connection is established, server-add (or client-add) marks it active and starts a delayed loop which repeatedly calls server-read (resp. client-read). The pause between two polls starts at 1 ms, grows by a factor 1.01 after each empty poll up to 2500 ms, and is reset to 1 ms whenever a message is received:

(tm-define (server-add client)
  (ahash-set! server-client-active? client #t)
  (with wait 1
    (delayed
      (:while (ahash-ref server-client-active? client))
      (:pause ((lambda () (inexact->exact (round wait)))))
      (:do (set! wait (min (* 1.01 wait) 2500)))
      (with msg (server-read client)
        (when (!= msg "")
          (with (msg-id msg-cmd) (string->object msg)
            (server-eval (list client msg-id) msg-cmd)
            (set! wait 1)))))))

Consequently, after a long idle period the latency of a request may reach a few seconds. At most one message is handled per poll.

3.3.Envelopes and dispatching

Each incoming message is evaluated in an envelope, the list (connection serial). On the server, server-eval looks up the head symbol of the command in service-dispatch-table and applies the registered function to the envelope and the arguments. Unknown commands are answered with an error (invalid command '…'); in particular, a client can only invoke functions which were explicitly declared as services. Services are declared with the macro tm-service:

(tm-define-macro (tm-service proto . body)
  …
  ‘(begin
     (tm-define (,(symbol-append 'service- fun) envelope ,@args)
       (with-database (server-database)
         (catch #t
                (lambda () ,@body)
                (lambda (key . err-args)
                  … (server-error envelope msg)))))
     (ahash-set! service-dispatch-table
                 ',fun ,(symbol-append 'service- fun))))

So (tm-service (remote-logout) …) defines a function service-remote-logout, evaluates its body with the global server database as current database, catches all errors (they are logged with server-log-write and sent back as an error) and registers the function under the symbol remote-logout. The variable envelope is bound inside the body.

The client uses the analogous macro tm-call-back, the table call-back-dispatch-table and the evaluator client-eval. Note that tm-call-back defines a function with the name of the call-back itself (not prefixed), and that client call-backs do not install a database.

3.4.Answers and continuations

The value returned by a service body is ignored. A service must explicitly answer with

(server-return envelope value), (server-error envelope message)
(answer a request)

These send (client-remote-result serial value), resp. (client-remote-error serial message), back to the client, where serial is taken from the envelope. On the client, client-return and client-error send server-remote-result and server-remote-error in the same way.

A service which never answers leaves the continuation of the client pending forever; there is no time-out at the Scheme level. Requests are sent with

(client-remote-eval server cmd cont [err-handler])
(asynchronous request to a server)

Send cmd to server, and call cont on the result, or err-handler (default std-client-error, which displays the message) on an error. The variant client-remote-eval* uses the same function for both cases. The helpers client-remote-then and client-remote-then-cb implement the common convention of

client-base.scm

that a list is a successful result and a string an error message.

(server-remote-eval client cmd cont [err-handler])
(request from the server to a client)

The server may also send requests to clients, for instance to push chat messages (chat-room-receive), notifications (client-push-notifications), live modifications (live-modify) or to announce that an account was deleted (client-account-deleted). The client answers through its call-backs.

The results are received by the service server-remote-result and the call-back client-remote-result (and their error variants), which look up the continuation under the serial number, check that the answer comes from the right connection, remove the entry and call the continuation. Thanks to this mechanism, client code is written in continuation passing style; for instance, the login dialog first calls client-login-then, then client-protocol-version-then, then fetches the account information, each step in the continuation of the previous one (see client-login-home in

client/client-widgets.scm

).

3.5.Debugging

With the debug flag remote switched on ((debug-set "remote" #t)), both evaluators print every incoming message. Socket level traces are printed when the C++ debug flags for sockets and input/output are on (DEBUG_SOCKETS, DEBUG_IO). The flag live traces live editing.

4.Protocol version

After login, clients send (remote-protocol-version n) with (client-protocol-version). The server stores the number per user in server-client-version (reset to 0 at each login), and services may test it with (client-version>=? uid n). Version 1 means that the client understands cache-ref trees (see the tree cache in the TeXmacs server); a server therefore never sends such trees to older clients. When the wire format evolves, increase TM_PROTOCOL_VERSION and guard the new behaviour with client-version>=?.

5.List of services

The following table lists the services currently declared with tm-service, grouped by module (all under

progs/server/

).

server-base.scm

remote-login, remote-login-code, remote-logout, remote-logged?, remote-protocol-version, new-account, confirm-pending-account, remote-reset-credentials, remote-get-account, remote-set-account, remote-get-accounts, remote-deletion-plan, remote-delete-account, remote-public-preferences, remote-admin-preferences, remote-admin-preferences-form, remote-set-preferences, server-license, remote-eval, and the internal server-remote-result, server-remote-error.

server-tmfs.scm

remote-identifier, remote-get-versions, remote-file-create, remote-file-load, remote-file-save, remote-file-remove, remote-dir-create, remote-dir-load, remote-dir-remove.

server-db.scm

remote-get-field, remote-set-field, remote-get-attributes, remote-get-entry, remote-set-entry, remote-create-entry, remote-search, remote-search-user, remote-get-user-pseudo, remote-get-user-name.

server-sync.scm
,
server-db-sync.scm

remote-sync-list, remote-upload, remote-download, remote-remove-several, remote-db-changes, remote-db-sync.

server-live.scm

live-open, live-modify, live-exists?, remote-list-live.

server-chat.scm

remote-chat-room-create, remote-list-chat-rooms, remote-chat-room-open, remote-chat-room-messages-reset, remote-mail-open, remote-shared, remote-send-message.

Others

remote-pending-notifications, remote-ack-notifications (

server-notifications.scm

) and remote-get-cache-ref (

server-cache.scm

).

The client call-backs are client-remote-result, client-remote-error, client-account-deleted, local-eval (disabled: its body is guarded by (when #f …)), chat-room-receive, client-push-notifications and live-modify.

6.How to add a new service

Adding a request type requires a service on the server and, usually, a small wrapper on the client.

  1. Declare the service in a server module. Check the user with server-get-user, check the access rights with db-allow?, and always answer with server-return or server-error:

    (tm-service (remote-word-count rname)
      (with-remote-context rname
        (let* ((uid (server-get-user envelope))
               (r (server-file-load uid rname)))
          (if (== (car r) :error)
              (server-error envelope (cadr r))
              (server-return envelope
                             (string-length (cadr r)))))))
  2. Make sure that the module is loaded by the server. The modules loaded by server_start are server-base, server-tmfs, server-menu, server-live and server-backup; server-menu in turn uses server-widgets, server-db, server-sync and server-chat. Either add your module to the :use list of one of them or load it from server_start.

  3. On the client, wrap the request in a function written in continuation passing style:

    (tm-define (remote-word-count server u cont)
      (client-remote-eval server ‘(remote-word-count ,u) cont
        (lambda (err) (set-message err "word count"))))
  4. If the server needs to push data to clients, declare a call-back with tm-call-back in a client module which is loaded whenever a connection exists (for instance a module used by

    client-base.scm

    or

    client-tmfs.scm

    ), and send it with server-remote-eval. The call-back must answer with client-return or client-error if the server supplied a meaningful continuation.

  5. If the new service changes the meaning of existing messages, increase TM_PROTOCOL_VERSION and test client-version>=? on the server.

  6. If the service can be disabled by the administrator, add a preference named "server service …" with define-preferences in

    server-authentication.scm

    (or in your module) and test it in the service body, as done for instance in remote-pending-notifications. Preferences whose name starts with "server" are automatically exposed to remote administrators by server-admin-preferences.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".