Jump to content

Recommended Posts

Posted (edited)

AutoIt's WebSocket story usually stops at "a client that can dial out". This one does both
directions, ships no binary, and does not call WinHTTP COM, curl, PowerShell or .NET.

You get a WebSocket endpoint inside an AutoIt script, and an AutoIt script that dials a real
wss:// server - with TLS verification that actually verifies - in about fifteen lines of code.


WHAT IS IN THE PACKAGE

WebSocket.au3        the only include you write. It orders the four layers, contains no function.
wsk.au3              layer 1 - Winsock 2, non-blocking sockets, connect race, address walk
tls.au3              layer 2 - Schannel TLS records, client side and server side
wsp.au3              layer 3 - the websocket.dll protocol component: framing, close handshake
ws.au3               layer 4 - the caller API: _WS_Startup, _WS_Connect, _WS_Send, _WS_Call,
                     _WS_Pump, _WS_WaitMessage, _WS_Listen, _WS_Accept, _WS_UpgradeHead,
                     _WS_UpgradeAnswer, _WS_Close

examples/            four programs, all run before release
 

210 documented public functions, every one of them with : syntax, parameters,
return values, @error codes, and a Remarks line that says what was measured.


WHY IT IS WORTH A LOOK

- Nothing to install and nothing to trust. No DLL is shipped, no download, no third-party binary.
  The layers name only DLLs that are already in Windows (ws2_32, secur32, bcrypt and the WebSocket
  component websocket.dll). If your security review forbids shipping binaries, this passes.
- Client AND server. Host an endpoint from a script: a browser page, a phone app, a Python or Node
  service can connect TO AutoIt, not only the other way round.
- Verified against other implementations, not only against itself. The TLS layer was tested against
  Python's ssl stack and against public echo services. That is the only interesting test, because it
  is where the other side is not your code.
- TLS verification is real. An untrusted chain is refused before the upgrade, and the peer name is
  checked. You can opt out with a flag, and the flag is loud about it.
- Layered on purpose. 95 % of scripts will only ever call layer 4. If you need your own socket, your
  own TLS records or your own frame handling, layers 1 to 3 are usable on their own and are the same  code the top layer uses.

- Errors are named, not mysterious. A failure tells you the step, the Winsock or HRESULT code, and a
  text. A refused connection and a refused handshake are two different answers.
- 32-bit and 64-bit, same behaviour, both tested. No admin rights.


REQUIREMENTS

AutoIt 3.3.16.1 and Windows 8 or later (that is the floor stated by the library, the WebSocket
component does not exist before it; everything here was measured on Windows 10 19045). Nothing else.


INSTALL

Extract the archive next to your script. Five files make the UDF run - the umbrella and its four
layers - and none of them is generated at run time. Then:

  #include "WebSocket\WebSocket.au3"


THE WHOLE CLIENT, IN ONE PROGRAM

#include "..\WebSocket.au3"

If Not _WS_Startup() Then Exit 1

Local $h = _WS_Connect("ws://127.0.0.1:8181/chat")
If $h < 0 Then
    ConsoleWrite("step " & @error & "/" & @extended & " :: " & _WS_ErrorText(-1) & @CRLF)
    ConsoleWrite("addresses: " & _WS_LastWalk() & @CRLF)
    _WS_Cleanup()
    Exit 1
EndIf

Local $b = _WS_Call($h, "hello", 8000)
If @error Then
    ConsoleWrite("round trip failed: " & _WS_ErrorText($h) & @CRLF)
Else
    ConsoleWrite("answer: " & BinaryToString($b, 8) & @CRLF)
EndIf

_WS_Close($h, 1000, "done", 2000)
_WS_Cleanup()

_WS_Connect takes a URL and does the address race, the TLS handshake if the scheme is wss, and the
HTTP upgrade. _WS_Call sends one message and waits for the answer. If it fails, @error is the step
and @extended the system code, and _WS_ErrorText() plus _WS_LastWalk() tell you what happened
without a debugger.


THE WHOLE SERVER, IN ONE PROGRAM

#include "..\WebSocket.au3"

If Not _WS_Startup() Then Exit 1
Local $hl = _WS_Listen(8181)                       ; 127.0.0.1, plain ws://
If $hl < 0 Then
    ConsoleWrite("cannot listen: " & _WS_ErrorText(-1) & @CRLF)
    _WS_Cleanup()
    Exit 1
EndIf
ConsoleWrite("listening on " & _WS_ListenPort($hl) & @CRLF)

While 1
    Local $h = _WS_Accept($hl)                     ; -1 = nobody is dialing now
    If $h < 0 Then
        Sleep(10)                                  ; _WS_Accept never waits, so the loop must
        ContinueLoop
    EndIf
    If _WS_UpgradeHead($h, 4000) < 0 Then          ; the request head first
        _WS_CloseRefused($h, "400 Bad Request", 2000)
        ContinueLoop
    EndIf
    ConsoleWrite("path=" & _WS_Path($h) & " origin=" & _WS_RequestHeader($h, "Origin") & @CRLF)
    If _WS_UpgradeAnswer($h, "", "", 4000) < 0 Then    ; accept, no subprotocol
        _WS_CloseHandle($h)
        ContinueLoop
    EndIf
    Local $b = _WS_WaitMessage($h, 8000)
    If @error = 0 Then _WS_Send($h, BinaryToString($b, 8))
    _WS_Flush($h, 3000)
    _WS_Close($h, 1000, "", 2000)
WEnd

Two calls instead of one, on purpose: _WS_UpgradeHead reads what the peer actually asked - path,
Origin, offered subprotocols - and only then do you decide to accept, pick a subprotocol, or refuse
with a real HTTP status. A server that cannot see the request head before saying yes cannot check
an Origin, and that is a security hole, not a convenience.

examples/example_server.au3 and examples/example_client.au3 are the same pair with TLS, Origin
checking, subprotocol selection and several messages in flight. Both printed programs above ship in
the archive as examples/hello_server.au3 and examples/hello_client.au3.


DOCUMENTATION

The attached WebSocket_Quick_Start.pdf is 11 pages: install, the client, the server, the pump,
wss and certificates, error reading, a chapter on what a browser is allowed to do with this, and a
chapter of copy-paste recipes. Read chapter 02 and 05 and you can write anything in the UDF.


WHAT IT IS FOR

- A script that needs a live feed: prices, telemetry, a chat room, a job queue, a device console.
- Replacing a polling HTTP API with a pushed one, on a machine where you cannot install anything.
- Letting a web page, a phone or another language talk TO an AutoIt script that keeps running.
- A bridge: AutoIt still owns the desktop, the GUI and the legacy app, and a browser UI drives it.


KNOWN LIMITATIONS

Everything below is measured. Each item says what actually happens, so you are not left debugging
something that was merely undocumented.

1. Ping cannot be initiated. The Windows WebSocket component answers WebSocketSend with a PING_PONG
   buffer by E_INVALIDARG (0x80070057) and schedules no network action at all. _Wsp_Ping() exists so
   that you get a named failure instead of a false success. Inbound pings are fine: the component
   answers them with a pong on its own, proved against a third-party client that received our pong
   although we never wrote one. Do keepalive at application level - one data frame answered by the
   peer is a round trip you can actually time, and that is what _WS_Call() is for.

2. Close codes 1005 and 1006 are never put on the wire, and out-of-range values are not refused
   either: both cases are replaced by 1000 before the answer leaves. That is RFC behaviour for those
   two codes, but it means the code alone cannot tell you "no status frame arrived" from "closed
   abnormally". The field that does tell you those apart is fromPeer= in _WS_CloseInfo($h): a real
   close frame sets it to 1 and carries its code and reason (measured in the suite: code=1000,
   code=1001 reason=[moving away]), while a peer that drops the socket leaves code=0 fromPeer=0.
   A close is also never queued behind data: it surfaces through the type returned by the pump call
   that saw it.

3. TLS 1.3 was never observed, in either direction, on this machine. Measured on 2026-11-17 with
   certificate verification ON ($fIgnoreRoot = False, so Windows validated the chain and the host name
   each time): ws.postman-echo.com, echo.websocket.org and echo-websocket.fly.dev all settled on
   TLS 1.2 (protocol 0x00000800, ECDHE-RSA-AES256-GCM-SHA384 or AES128-GCM), at both 32-bit and 64-bit,
   open 596 to 2 885 ms, echo answered every time. The version reporter in tls.au3 has a TLS 1.3
   branch and it has never fired - not against those public servers, and not against a local peer that
   offers 1.3. That is the floor of the operating system, not of the UDF: Schannel added TLS 1.3 in
   Windows 11 and Windows Server 2022, and this suite ran on Windows 10 19045. If you run it on
   Windows 11 and get a TLS 1.3 session, tell me - the record format differs and I have not been able
   to test it.

4. You drive the pump. No timer, no Adlib, no thread inside the UDF: messages move when you call
   _WS_Pump($h) or _WS_WaitMessage($h, $iTimeoutMs). In a GUI script that normally means one pump call
   per GUIGetMsg() turn, and a bare GUIGetMsg loop turns about 60 times a second, so that is the
   delivery ceiling. Two consequences: never call a sending function from inside _Wsp_PumpOnce (the
   send re-enters the pump and wipes the shared structures mid-read - that one segfaulted during
   development), and a peer that stops answering costs you at most the budget you passed.

5. Fixed ceilings per process, all compile-time constants: 8 concurrent connections ($g_iWspSlots) and
   8 listeners ($g_iWsListeners). Both show up in the logs, as cap=8 and on every listener line. The
   receive cap is 4 MiB per message by default ($iMaxMsg, the same figure IIS documents for
   receiveBufferLimit) and is settable per listen or per connect; the TLS record buffer is 65536 +
   32768 bytes per slot. What is measured about overflow: a delivery queue that fills is counted in
   dropped= and surfaces as the pump's @error 3, with the dropped count in @extended - bounded memory
   plus a loud failure, never silent buffering.

6. No extensions. The UDF never offers and never selects one: permessage-deflate appears nowhere in the
   sources. Every session in the suite produced a plain 101 with no extension selected. A peer that
   explicitly offered an extension has not been exercised, so do not read more into this line than
   that.

7. No reconnection, no HTTP body, no routing. It is a transport layer. After a closed connection you
   call _WS_Connect again yourself. The server answers the upgrade handshake and then speaks frames
   only: the 101 is written by the Windows component, the 405 to a non-GET request is written by this
   UDF (_WS_Upgrade checks _WS_Method), and neither answer carries a body. Both refusals are measured:
   method refused:

c4s0 ANSWER refused step 2/S_OK :: Origin refused [http://evil.example] allow=[http://good.example]
SUMMARY c4s0 messages=0 bytes=0 errors=0 why=answer step 2

8. Trust is Windows' own.
Verification goes through the Schannel chain policy, so a self-signed certificate is refused
before the upgrade unless you pass the ignore-root flag. Measured both ways: with
$fIgnoreRoot = False, a connect to a name whose chain ends in an untrusted root fails at the
policy step with 0x800B0109, and the verdict text is returned by _WS_ErrorText($h); with the
flag set, the same session opens and the log says approved. The flag does not weaken the host
name check. The certificate used by the TLS examples is a test certificate and is deliberately
not trusted. Use a real certificate; do not ship the flag.

9. Scope of testing.
AutoIt 3.3.16.1, both interpreters, one Windows 10 machine (19045), against our own server,
against Python's ssl and websocket stacks (OpenSSL 3.0.15, websockets 17.2), and against the
three public echo servers named in item 3. The guard gate replays 19 suites at both bitnesses -
38 runs - and the last recorded run finished with 38 zero return codes, with the failure
counters read inside the logs and not just the exit codes. Nothing was run on Windows Server
SKUs or behind a proxy, and no TLS 1.3 session was ever observed.

 

VERSION AND LICENCE

1.0.0, MIT licence (see LICENSE in the archive).
If you hit something, post the bitness, the step and the two codes: the return value, @error
(step) and @extended (system code), plus the output of _WS_ErrorText($h) and, for a failed
connect, _WS_LastWalk(). Those four lines are enough for me to reproduce almost anything.

 

WebSocket.zip

 

WebSocket_Quick_Start.pdf

 

Edited by Numeric1
From 0 and 1 to the stars, it all starts with binary, Numeric1
 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...