websocket(n)

πŸ“¦
version 2.0 Β· 2 versions
, in fedora 43, fedora 44, nixos 26.05, nixpkgs unstable

πŸ’– websocket(n) β€” websocket client and server πŸ’–

okay so bestie, welcome to the websocket page, this is part 1 of 3 so like, buckle up πŸŽ€


✨ NAME ✨

websocket β€” Tcl implementation of the websocket protocol πŸ¦‹


✨ SYNOPSIS ✨

package require Tcl 8.6 9

package require http 2.7

package require logger

package require sha1

package require base64

package require websocket ?1.6?

::websocket::open url handler ?options?

::websocket::send sock type ?msg? ?final?

::websocket::server sock

::websocket::live sock path cb ?proto?

::websocket::test srvSock cliSock path ?hdrs? ?qry?

::websocket::upgrade sock

::websocket::takeover sock handler ?server?

::websocket::conninfo sock what

::websocket::find ?host? ?port?

::websocket::configure sock args

::websocket::loglevel ?loglvl?

::websocket::close sock ?code? ?reason?

✨ DESCRIPTION ✨

NOTE: THIS DOCUMENTATION IS WORK IN PROGRESS... πŸ‘€

The websocket library is a pure Tcl implementation of the WebSocket specification, and it covers the needs of both clients and servers, like it's giving versatility fr fr πŸ’…

Websockets provide a way to upgrade a regular HTTP connection into a long-lived and continuous binary or text communication between the client and the server. So no more awkward reconnecting every five seconds, it's giving main character energy ✨

The library offers a high-level interface to receive and send data as specified in RFC 6455 (v. 13 of the protocol), relieving callers from all necessary protocol framing and reassembly. It implements the ping facility specified by the standard, together with levers to control it. Pings are server-driven and ensure the liveness of the connection across home (NAT) networks. 🫢

The library also has a number of introspection facilities to inquire about the current state of the connection, and to receive notifications of incoming pings, if necessary. And finally, the library contains a number of helper procedures to facilitate the upgrading handshaking in existing web servers. 🌸


🧚 the central one: takeover

Central to the library is the procedure websocket::takeover, which will take over a regular socket and treat it as a WebSocket, thus performing all necessary protocol framing, packetisation and reassembly in servers and clients. πŸ’…

The procedure also takes a handler, a command that will be called back each time a (possibly reassembled) packet from the remote end is ready for delivery at the original caller.

While exported by the package, the command websocket::takeover is seldom called in applications, since the package provides other commands that are specifically tuned for the needs of clients and servers. So like, it's iconic but you probably won't be texting it directly, iykyk 😌


🌈 clients, bestie

Typically, clients will open a connection to a remote server by providing a WebSocket URL (ws: or wss: schemes) and the handler described above to the command websocket::open.

The opening procedure is a wrapper around the latest http::geturl implementations: it arranges to keep the socket created within the http library opened for reuse, but confiscates it from its (internal) map of known sockets for its own use. lowkey feral but okay πŸ’€


πŸ‘‘ servers, also bestie

Servers will start by registering themselves through the command ::websocket::server and a number of handlers for paths using the command ::websocket::live.

Then for each incoming client connection, they should test the incoming request to detect if it is an upgrade request using ::websocket::test and perform the final handshake to place the socket connection under the control of the websocket library and its central procedure using ::websocket::upgrade. ✨


πŸ”₯ everything else

Apart from these main commands, the package provides a number of commands for introspection and basic operations on the websockets that it has under its control. πŸ¦‹

As WebSockets connections are long-lived, most remaining communication with the library will be by way of callbacks, i.e. commands that are triggered whenever important events within the library have occur, but mostly whenever data has been received on a WebSocket. No cap, it's a callback kind of lifestyle. πŸ’–


✨ CALLBACKS ✨

A number of commands of the library take a handler command as an argument, a command which will be called back upon reception of data, but also upon important events within the library or events resulting from control messages sent by the remote end.

For each callback being performed, the following arguments will be appended: πŸ‘‡

  • sock β€” the identifier of the WebSocket, as returned for example by ::websocket::open
  • type β€” a textual type describing the event or message content, can be one of the following:
    • text β€” complete text message ✨
    • binary β€” complete binary message πŸ“
    • ping β€” incoming ping message πŸ“
    • pong β€” response to incoming ping message πŸ“
    • connect β€” notification of successful connection to server πŸŽ€
    • disconnect β€” disconnection from remote end 😭
    • close β€” pending closure of connection πŸ™ˆ
    • timeout β€” notification of connection timeout πŸ’€
    • error β€” notification of error condition 🚨
  • msg β€” will contain the data of the message, whenever this is relevant, i.e. when the type is text, binary, ping or pong and whenever there is data available.

okay that's the whole first chunk, stay tuned because there is MORE πŸ‘‘

πŸ’… API πŸ’…

okay bestie this is the good part, this is where the actual commands live 🫢


::websocket::open url handler ?options?

Client side, opening time, let's gooo. This is the one you use in clients to open a WebSocket to a remote websocket-enabled HTTP server. The url you pass has to start with ws: or wss: β€” those are literally the WebSockets counterpart of http: and https:, no cap. The handler is a command that gets called back on data reception or whenever important events occur during the life of the websocket (the whole callback situation is described back in the Callbacks section, go peek if you skipped it πŸ™ˆ).

::websocket::open will return a socket, and that socket is doing double duty: it's both the identifier of the websocket and of the physical low-level socket to the server. You can feed it into a bunch of other commands for introspection or for controlling the behaviour of the library. Under the hood it's basically a wrapper around ::http::geturl, so it offers mostly the same set of dash-led options as ::http::geturl does. What I'm listing below are the options that differ from ::http::geturl and which are specific to the WebSocket library:

  • -headers β€” supported ✨ just know that a number of headers get automatically added internally in the library so it can handshake the upgrading of the socket from a regular HTTP socket to a WebSocket with the server.
  • -validate β€” not supported, it just has no real point for WebSockets.
  • -handler β€” used internally by the websocket library, so you cannot use it, sorry bestie πŸ™ˆ
  • -command β€” also used internally by the websocket library, also cannot be used.
  • -protocol β€” this one specifies a list of application protocols to handshake with the server. These protocols might help the server triggering application specific features πŸ‘‘. Heads up though: the http::geturl option -protocol is used internally by the websocket library and cannot be used.
  • -timeout β€” supported, but it's implemented as part of the library so that a number of finalising cleanups can happen.

::websocket::send sock type ?msg? ?final?

Send a fragment or a control message to the remote end of the WebSocket identified by sock. The type of the message can either be an integer according to the specification, or β€” preferably πŸ’… β€” one of these case insensitive strings: "text", "binary" or "ping". The content of the message to send lives in msg, and message fragmentation is made possible by setting the argument final to non-true, knowing that the type of each fragment has then to be the same. The command returns the number of bytes that were effectively sent, or -1 on errors. Serious errors β€” like when sock does not identify a known WebSocket, or when the connection is not stable yet β€” will generate errors that must be catched. fr fr, wrap that in a catch.


::websocket::server sock

This one registers the (accept) socket sock as the identifier fo an HTTP server that is capable of doing WebSockets. Paths onto which this server will listen for incoming connections should be declared using ::websocket::live. πŸ¦‹


::websocket::live sock path cb ?proto?

This procedure registers callbacks that will be performed on a WebSocket compliant server registered with ::websocket::server whenever a client connects to a matching path and protocol. So: sock is the listening socket of the websocket compliant server declared using ::websocket::server. path is a glob-style path to match in client request, whenever this will occur. cb is the command to callback (see Callbacks). And proto is a glob-style protocol name matcher. πŸŽ€


::websocket::test srvSock cliSock path ?hdrs? ?qry?

This procedure will test if the connection from an incoming client on socket cliSock and on the path path is the opening of a WebSocket stream within a known server srvSock. Important vibe check: the incoming request is not upgraded at once β€” instead a (temporary) context for the incoming connection is created. That's on purpose, because it lets server code perform a number of actions, if necessary, before the WebSocket stream connection goes live. The text is made by analysing the content of the headers hdrs, which should contain a dictionary list of the HTTP headers of the incoming client connection. The command will return 1 if this is an incoming WebSocket upgrade request and 0 otherwise. 🫢


::websocket::upgrade sock

Upgrade the socket sock that had been deemed by ::websocket::test to be a WebSocket connection request to a true WebSocket as recognised by this library. As a result, the necessary connection handshake will be sent to the client, and the command will arrange for relevant callbacks to be made during the life of the WebSocket, notably using the specifications described by ::websocket::live. glow up complete ✨


::websocket::takeover sock handler ?server?

Take over the existing opened socket sock to implement sending and receiving WebSocket framing on top of the socket. The procedure arranges for handler to be called back whenever messages, control messages or other important internal events are received or occured. server defaults to 0 and can be set to 1 (or a boolean that evaluates to true) to specify that this is a WebSocket within a server. Apart from specificities in the protocol, servers should ping their clients at regular intervals in order to keep the connection opened at all time ⏰. When server is set to true, the library will arrange to send these pings automatically. iconic, honestly.


::websocket::conninfo sock what

Provides callers with some introspection facilities in order to get some semi-internal information about an existing websocket connection. Depending on the value of the what argument, the procedure returns the following piece of information:

  • peername β€” Name (preferred) or IP of remote end.
  • sockname or name β€” Name or IP of local end.
  • closed β€” 1 if the connection is closed, 0 otherwise
  • client β€” 1 if the connection is a client websocket, 0 otherwise
  • server β€” 1 if the connection is a server websocket, 0 otherwise
  • type β€” server if the connection is a server websocket, client otherwise.
  • handler β€” The handler command associated to the websocket
  • state β€” The state of the websocket, which can be one of:
    • CONNECTING β€” Connection to remote end is in progress.
    • CONNECTED β€” Connection is connected to remote end.
    • CLOSED β€” Connection is closed.

::websocket::find ?host? ?port?

Look among existing websocket connections for the ones that match the hostname and port number filters passed as parameters. This lookup takes the remote end into account, and the host argument is matched both against the hostname (whenever available) and the IP address of the remote end. Both the host and port arguments are glob-style string matching filters and default to *, i.e. will match any host and/or port number. 🌈


::websocket::configure sock args

This command takes a number of dash-led options (and their values) to configure the behaviour of an existing websocket connection. The recognised options are the following (they can be shortened to the lowest common denominator):

  • -keepalive β€” is the number of seconds between each keepalive pings being sent along the connection. A zero or negative number will effectively turn off the feature. In servers, -keepalive defaults to 30 seconds, and in clients, no pings are initiated.
  • -ping β€” is the text that is used during the automated pings. This text defaults to the empty string, leading to an empty ping.

::websocket::loglevel ?loglvl?

Set or query the log level of the library, which defaults to error. Logging is built on top of the logger module, and the library makes use of the following levels: debug, info, notice, warn and error. When called with no argument, this procedure will simply return the current log level. Otherwise loglvl should contain the desired log level. πŸ’œ


::websocket::close sock ?code? ?reason?

Gracefully close a websocket that was directly or indirectly passed to ::websocket::takeover. The procedure will optionally send the code and describing reason as part of the closure handshake. Good defaults are provided, so that reasons for a number of known codes will be sent back. Only the first 125 characters of a reason string will be kept and sent as part of the handshake. The known codes are:

  • 1000 β€” Normal closure (the default code when none provided).
  • 1001 β€” Endpoint going away
  • 1002 β€” Protocol Error
  • 1003 β€” Received incompatible data type
  • 1006 β€” Abnormal closure
  • 1007 β€” Received data not consistent with type
  • 1008 β€” Policy violation
  • 1009 β€” Received message too big
  • 1010 β€” Missing extension
  • 1011 β€” Unexpected condition
  • 1015 β€” TLS handshake error

not me realising there's still more of this page coming 😭 stay tuned bestie, we're not done yet πŸ’…

🎬 EXAMPLES ✨

okay bestie here's a whole lil client script, she's cute, she works 🫢

This example is a client that opens a websocket connection to an echo service, waits 400ms so we know the connection is actually, truly established, and then sends one single textual message that the echo service should bounce right back at us. πŸ’Œ

Real talk though: a real-life example would probably use the connect callback to know when the connection to the remote server has been established, and would only send data at that moment. This one's just out here vibing with a timer. Then, finally, the script closes the connection. periodt.

package require websocket
::websocket::loglevel debug
proc handler { sock type msg } {
    switch -glob -nocase -- $type {
  co* {
      puts "Connected on $sock"
  }
  te* {
      puts "RECEIVED: $msg"
  }
  cl* -
  dis* {
  }
    }

}
proc test { sock } {
    puts "[::websocket::conninfo $sock type] from [::websocket::conninfo $sock sockname] to [::websocket::conninfo $sock peername]"

    ::websocket::send $sock text "Testing, testing..."
    after 2000 ::websocket::close $sock
}
set sock [::websocket::open ws://ws.ifelse.io/ handler]
after 400 test $sock
vwait forever

and if you want the other side of the story?? Example code for a websocket server is provided in the Tcllib directory "examples/websocket". go look, it's giving main character energy 🧚


πŸ” TLS SECURITY CONSIDERATIONS πŸ”

bestie this part is important, so like, pay attention πŸ’…

This package uses the TLS package to handle the security for https urls and other socket connections.

Policy decisions β€” like the set of protocols to support and which ciphers to use β€” are not the responsibility of TLS, and honestly not of this package either. Nope. Those decisions belong to whichever application is using the package, and they're likely influenced by the set of servers that application is gonna talk to as well. iykyk.

For example: in light of the recent POODLE attack [http://googleonlinesecurity.blogspot.co.uk/2014/10/this-poodle-bites-exploiting-ssl-30.html] discovered by Google, many servers will disable support for the SSLv3 protocol. To handle that change, the applications using TLS must be patched β€” not this package, and not TLS itself. And such a patch may be as simple as generally activating tls1 support, as shown in the example below. πŸ’–

package require tls
tls::init -tls1 1 ;# forcibly activate support for the TLS1 protocol

... your own application code ...

πŸ› BUGS, IDEAS, FEEDBACK πŸ’Œ

ngl, this document and the package it describes will undoubtedly contain bugs and other problems. it's giving humbling. 😭

Please report such in the category websocket of the Tcllib Trackers [http://core.tcl.tk/tcllib/reportlist]. And please also report any ideas for enhancements you may have for either the package and/or the documentation. we wanna hear it fr fr 🫢

When proposing code changes, please provide unified diffs, i.e the output of diff -u.

Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. don't skip this step bestie, it's lowkey the whole vibe 🌸

πŸ‘€ SEE ALSO

  • http

πŸ”‘ KEYWORDS

http, internet, net, rfc 6455 ✨


πŸ—‚οΈ CATEGORY

Networking 🌈


and that's the whole page, we did it!! πŸŽ€ this one came from tcllib, version 1.6, and it's websocket(n) β€” the date field up there is being all mysterious and blank, but the version is right there and she's iconic. slay, go build something, bye bestie πŸ’œπŸ¦‹

πŸ“¦ where this page comes from