diff --git a/.gitignore b/.gitignore index 01c0e0c..141a699 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,10 @@ build/ # Python bytecode from tests/ and wiretest/ __pycache__/ +build-*/ + +# --datalink sc: the device's certificates and private key (--sc-cert-dir, +# default ./certs) and the CARI request/response zips. Never commit them. +certs/ +*-cari-request.zip +*-cari-response.zip diff --git a/CHANGELOG.md b/CHANGELOG.md index 12d33ff..b7524b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,72 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.3.0] - 2026-10-28 -_No changes yet._ +Built on CAS BACnet Stack 6.x (`d9f39406`, 6.0.23). One executable now runs on any +one of four BACnet data links, chosen at start-up with `--datalink`. The default, +`ipv4`, is the same device as 1.2.0. + +### Added + +- **`--datalink ipv4|ipv6|mstp|sc`**, with each data link's own options. Every + option is checked, and an option for a data link other than the chosen one is + an error rather than silently ignored. `--help` lists them all. +- **One Network Port object per data link**, only the active one's: 1 "Vermilion" + (BACnet/IP), 2 "Cerulean" (BACnet/IPv6), 3 "Amber" (MS/TP), 4 "Teal" (BACnet/SC). +- **BACnet/IPv6** (`--datalink ipv6`, `--port`, `--interface`). Network Port 2 + serves the host's IPv6 address, prefix length, default gateway, DNS server and + link speed, and the stack serves the VMAC. The start-up I-Am and Who-Is go to the + multicast group FF02::BAC0. `tests/ipv6_probe.py` checks it from outside. +- **MS/TP** (`--datalink mstp`, `--mstp-port`, `--mstp-baud`, `--mstp-mac`, + `--mstp-max-master`, `--mstp-max-info-frames`) on a USB-to-RS-485 adapter. The + CAS BACnet Stack runs the MS/TP state machines; the example only moves bytes on + and off the serial port. Network Port 3's Max_Master and Max_Info_Frames are + writable as pending changes. The start-up I-Am and Who-Is wait until the station + has joined the token ring. The `m` key prints the MS/TP counters. The Device's + Max_APDU_Length_Accepted is 480 on MS/TP. +- **BACnet/SC node** (`--datalink sc`, `--sc-hub`, `--sc-failover-hub`, + `--sc-cert-dir`, `--import-cari`), built when libwebsockets, OpenSSL and zlib are + found (`-D BBC_SC=OFF` leaves it out). The certificates follow the B-SCHUB + example's CARI flow: the first start writes a certificate request and stops, and + `--import-cari` installs the Certificate Authority's response, printing each CA's + SHA-256 fingerprint to check out of band. Files 2-5 expose the certificates over + BACnet; ReinitializeDevice ACTIVATE_CHANGES installs new ones only if the device + could still connect with them, and the Network Port Command GENERATE_CSR_FILE + makes a new key and request. `tools/sign_cari_request.py` signs a request with a + test CA. +- ReinitializeDevice ACTIVATE_CHANGES on every data link, and the Network Port + Command DISCARD_CHANGES. +- A start-up warning while `DCC_PASSWORD` is empty: any BACnet client can then + silence or restart the device, and on BACnet/SC replace its certificates. +- `common/`: `SimpleUDP6` (a BACnet/IPv6 socket) and `SimpleSerial` (a serial port + for MS/TP), see `common/CHANGELOG.md`. + +### Changed + +- Reading the peer device (DS-RP-A, DS-RPM-A) runs on `ipv4` and `ipv6` only: on + MS/TP and BACnet/SC the CAS BACnet Stack does not hand the application the + answers. See `TODO.md`. +- The Notification Class recipient is preset on `ipv4` only; on the other data + links a client writes Recipient_List. +- `--deviceName` sets the name in the BACnet/SC certificate request as well. + +### Fixed + +- **Linux: BACnet/SC is built with the distribution's libwebsockets.** CMake now + finds Ubuntu's `LibwebsocketsConfig.cmake` as well as `libwebsockets-config.cmake`, + and the hub connector builds against libwebsockets 4.0 (Ubuntu 22.04), which + lacks `LWS_PROTOCOL_LIST_TERM`. +- `tools/sign_cari_request.py` says it needs `cryptography` 42 or later. + +### Known limitations + +- MS/TP was run on a live bus at 38400 baud only. 76800 baud is refused on Linux, + where termios has no such rate. +- The BACnet/SC failover hub, the certificate procedures over BACnet and writing + Max_Master / Max_Info_Frames have not been exercised against this example. +- As a BACnet/IPv6 BBMD this example would not pass its peers' broadcasts on: it + gives the stack no destination address. ## [1.2.0] - 2026-10-27 diff --git a/CMakeLists.txt b/CMakeLists.txt index ca56d94..e058111 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,15 +10,45 @@ # STATIC and DLL modes - see its CMakeLists.txt - but they need a prebuilt library # and this example does not use them.) # +# ONE executable, four data links: BACnet/IP (default), BACnet/IPv6, MS/TP and +# BACnet/SC, chosen at run time with --datalink. The stack's default (full) build +# already compiles all four. BACnet/IP, BACnet/IPv6 and MS/TP need nothing but the +# operating system. BACnet/SC also needs libwebsockets, OpenSSL and zlib (the +# WebSocket/TLS connection to the hub, and the certificate tools); they are found +# through vcpkg (VCPKG_ROOT) or the system. Without them the example still builds, +# and --datalink sc says how to rebuild with them. -D BBC_SC=OFF leaves them out on +# purpose. +# # Build: # cmake -B build -S . # cmake --build build --config Release --parallel # Run (from the example folder): -# ./build/BACnetExampleBBC (Linux/macOS) -# .\build\Release\BACnetExampleBBC.exe (Windows) +# ./build/BACnetExampleBBC [--datalink ipv4|ipv6|mstp|sc] (Linux/macOS) +# .\build\Release\BACnetExampleBBC.exe [--datalink ipv4|ipv6|mstp|sc] (Windows) # ============================================================================= cmake_minimum_required(VERSION 3.15) + +# --- BACnet/SC (optional) -------------------------------------------------------- +# ON (the default) means "build BACnet/SC if its libraries can be found". It is +# not an error when they cannot: the example is then built without it. +option(BBC_SC "Build the BACnet/SC data link (needs libwebsockets, OpenSSL and zlib)" ON) + +# vcpkg toolchain auto-detection - only when BACnet/SC is wanted, and only if the +# caller did not choose a toolchain. Must happen BEFORE project(). With VCPKG_ROOT +# set (Visual Studio bundles a vcpkg), vcpkg.json's libraries are installed into +# the build folder at configure time. A machine without vcpkg skips all of this. +if(BBC_SC AND NOT DEFINED CMAKE_TOOLCHAIN_FILE AND DEFINED ENV{VCPKG_ROOT} + AND EXISTS "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" + CACHE STRING "Vcpkg toolchain file") + # On Windows, the static triplet: libwebsockets/OpenSSL linked into the one + # executable, against the static C runtime (see CMAKE_MSVC_RUNTIME_LIBRARY below). + if(WIN32 AND NOT DEFINED VCPKG_TARGET_TRIPLET) + set(VCPKG_TARGET_TRIPLET "x64-windows-static" CACHE STRING "Vcpkg target triplet") + endif() +endif() + project(BACnetProfileExample_CPP_B_BC CXX C) @@ -57,25 +87,95 @@ if(NOT EXISTS "${CAS_STACK_DIR}/adapters/cpp/CMakeLists.txt") "Or pass -D CAS_STACK_DIR=/path/to/cas-bacnet-stack to use a stack elsewhere.") endif() +# --- BACnet/SC libraries --------------------------------------------------------- +set(BBC_SC_FOUND OFF) +if(BBC_SC) + # vcpkg installs libwebsocketsConfig.cmake; Debian and Ubuntu install + # LibwebsocketsConfig.cmake, and Linux file names are case-sensitive. + find_package(libwebsockets CONFIG QUIET NAMES libwebsockets Libwebsockets) + find_package(OpenSSL QUIET) + find_package(ZLIB QUIET) + find_package(Threads QUIET) + if(libwebsockets_FOUND AND OpenSSL_FOUND AND ZLIB_FOUND AND Threads_FOUND) + set(BBC_SC_FOUND ON) + else() + message(STATUS "B-BC: BACnet/SC is NOT built - libwebsockets, OpenSSL or zlib was not found " + "(set VCPKG_ROOT, or install them). The other data links are built.") + endif() +endif() +if(BBC_SC_FOUND) + message(STATUS "B-BC: BACnet/SC is built (libwebsockets, OpenSSL, zlib found)") +endif() + +# --- MSVC runtime library (must match across the whole link) ---------------- +# vcpkg's x64-windows-static triplet builds libwebsockets/OpenSSL against the +# static CRT (/MT). When this build links them, compile the stack and this example +# the same way - set BEFORE add_subdirectory(adapter) so the stack's own SOURCE-mode +# compile picks it up - or the link fails with LNK2038 MD-vs-MT mismatches. +if(MSVC AND BBC_SC_FOUND AND VCPKG_TARGET_TRIPLET MATCHES "-static$") + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +# Compile each target's files in parallel with MSVC too (/MP): the stack is ~600 +# files. Before add_subdirectory() so the stack's target gets it. +if(MSVC) + add_compile_options(/MP) +endif() + # --- The CAS BACnet Stack, via its CMake adapter target --------------------- # CAS_BACNET_STACK_LINK is the adapter's own cache variable (SOURCE/STATIC/DLL, # default SOURCE, which is what this example builds with). To override it, set it # BEFORE add_subdirectory() so the adapter target picks it up. See # submodules/cas-bacnet-stack/adapters/cpp/CMakeLists.txt for what each mode does. +# The stack is built with its default options (source/CIBuildSettingsDefaults.h): +# every object type and every data link - BACnet/IP, BACnet/IPv6, MS/TP, BACnet/SC. add_subdirectory("${CAS_STACK_DIR}/adapters/cpp" cas-bacnet-stack-adapter) # --- The shared example helper ---------------------------------------------- set(COMMON_SOURCES "${EXAMPLES_COMMON_DIR}/CASExampleHelper.cpp" - "${EXAMPLES_COMMON_DIR}/SimpleUDP.cpp") + "${EXAMPLES_COMMON_DIR}/SimpleUDP.cpp" # BACnet/IP (--datalink ipv4) + "${EXAMPLES_COMMON_DIR}/SimpleUDP6.cpp" # BACnet/IPv6 (--datalink ipv6) + "${EXAMPLES_COMMON_DIR}/SimpleSerial.cpp") # MS/TP (--datalink mstp) -# --- The executable --------------------------------------------------------- -add_executable(BACnetExampleBBC +# --- This example's own sources --------------------------------------------- +set(EXAMPLE_SOURCES main.cpp - ${COMMON_SOURCES}) + command_line.cpp # --datalink and every other option, --help + ipv6/LocalIPv6Address.cpp # the host's IPv6 address for the IPv6 Network Port + mstp/MstpDataLink.cpp) # the stack's MS/TP byte callbacks on a serial port + +# BACnet/SC: the hub connection (libwebsockets client) and the certificate files +# (CARI request/response, the certificate File objects) - see sc/README.md. +set(SC_SOURCES + sc/ScNode.cpp + sc/ScHubConnector.cpp + sc/KeyPassword.cpp + sc/cari.cpp + sc/cert_layout.cpp + sc/cert_tool.cpp + sc/cert_store.cpp) + +# --- The executable --------------------------------------------------------- +if(BBC_SC_FOUND) + add_executable(BACnetExampleBBC ${EXAMPLE_SOURCES} ${COMMON_SOURCES} ${SC_SOURCES}) + target_compile_definitions(BACnetExampleBBC PRIVATE BBC_WITH_SC) + # The libwebsockets package names its target "websockets" (static) or + # "websockets_shared" (some Linux distributions ship only that one). + if(TARGET websockets) + set(BBC_WEBSOCKETS_TARGET websockets) + else() + set(BBC_WEBSOCKETS_TARGET websockets_shared) + endif() + target_link_libraries(BACnetExampleBBC PRIVATE + ${BBC_WEBSOCKETS_TARGET} OpenSSL::SSL OpenSSL::Crypto ZLIB::ZLIB Threads::Threads) +else() + add_executable(BACnetExampleBBC ${EXAMPLE_SOURCES} ${COMMON_SOURCES}) +endif() target_include_directories(BACnetExampleBBC PRIVATE - "${EXAMPLES_COMMON_DIR}") + "${EXAMPLES_COMMON_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}") target_link_libraries(BACnetExampleBBC PRIVATE CASBACnetStack::Adapter) @@ -88,11 +188,16 @@ if(MSVC) else() set(EXAMPLE_WARNINGS "-Wall;-Wextra") endif() -set_source_files_properties(main.cpp ${COMMON_SOURCES} +set_source_files_properties(${EXAMPLE_SOURCES} ${COMMON_SOURCES} ${SC_SOURCES} PROPERTIES COMPILE_OPTIONS "${EXAMPLE_WARNINGS}") -# --- Platform sockets ------------------------------------------------------- -# ws2_32 = Winsock (UDP); iphlpapi = GetAdaptersInfo (local broadcast address). +# --- Platform libraries ----------------------------------------------------- +# ws2_32 = Winsock (UDP); iphlpapi = GetAdaptersInfo / GetAdaptersAddresses (the +# local IPv4 and IPv6 addresses); winmm = timeBeginPeriod (1 ms sleeps for MS/TP). +# dbghelp is needed by libuv, which a static libwebsockets pulls in (BACnet/SC). if(WIN32) - target_link_libraries(BACnetExampleBBC PRIVATE ws2_32 iphlpapi) + target_link_libraries(BACnetExampleBBC PRIVATE ws2_32 iphlpapi winmm) + if(BBC_SC_FOUND) + target_link_libraries(BACnetExampleBBC PRIVATE dbghelp) + endif() endif() diff --git a/README.md b/README.md index 2bdb1eb..19dec05 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,12 @@ silent** - see [The scenario](#the-scenario). Around that it carries the rest of the profile: commandable outputs, DeviceCommunicationControl, intrinsic alarming with a writable event-recipient list, time synchronisation, ReinitializeDevice, Backup and Restore, and trending (Trend Log, Trend Log -Multiple, and ReadRange). It listens on **BACnet/IP (UDP 47808)** and claims -only B-BC. +Multiple, and ReadRange). It claims only B-BC. + +**One executable, four data links**, chosen when you start it: +`--datalink ipv4` (BACnet/IP on UDP 47808, the default), `ipv6` (BACnet/IPv6), +`mstp` (MS/TP on an RS-485 adapter) or `sc` (a BACnet/SC node connecting to a +hub). Only one runs at a time - see [Data links](#data-links). **[Download a prebuilt binary](https://github.com/chipkin/BACnetProfileExample-B-BC-CPP/releases)** (Windows and Linux x64) - or build it yourself, see [Build](#build) below. @@ -21,8 +25,8 @@ only B-BC. - **[docs/PICS.md](docs/PICS.md)** - the Protocol Implementation Conformance Statement: every object, every property, and who answers it. -> **Versions:** this document describes **example v1.2.0**, built and verified -> against **CAS BACnet Stack 6.0.23** (`6.x` @ `69b6249f`), at +> **Versions:** this document describes **example v1.3.0**, built and verified +> against **CAS BACnet Stack 6.0.23** (`6.x` @ `d9f39406`), at > **Protocol_Revision 30**, with the vendored `common/` helper at **v3.5.0**. > Running the example prints all three - if what it prints disagrees with this > line, trust the program and check `CHANGELOG.md`. @@ -113,10 +117,14 @@ Binary Output 1 "Fuchsia" (active / inactive; WRITABLE, commandable Multi-state Output 1 "Indigo" (state 1..3; WRITABLE, commandable) Analog Value 1 "Diamond" (REAL, read from peer 389002's Analog Input 1; OutOfRange alarm; Reliability) Notification Class 1 "Crimson" (routes Diamond's alarms; Recipient_List WRITABLE) -Network Port 1 "Vermilion" (BACnet/IP - required) +Network Port 1 "Vermilion" (BACnet/IP, --datalink ipv4 - the default) + or Network Port 2 "Cerulean" (BACnet/IPv6, --datalink ipv6) + or Network Port 3 "Amber" (MS/TP, --datalink mstp) + or Network Port 4 "Teal" (BACnet/SC, --datalink sc) Schedule 1 "Saffron" (drives Chartreuse locally AND a remote peer - SCHED-E-B) Calendar 1 "Cream" (stack-held Date_List, WRITABLE; drives Saffron's exception) File 1 "Ivory" (backup/restore payload - DM-BR-B) +File 2..5 (--datalink sc only: the BACnet/SC certificates) Trend Log 1 "Lilac" (polls Bronze) Trend Log Multiple 1 "Magenta" (polls Bronze/Diamond/Chartreuse) ``` @@ -162,8 +170,8 @@ Trend Log Multiple 1 "Magenta" (polls Bronze/Diamond/Chartreuse) | (Un)ConfirmedEventNotification | Sends alarm/event notifications for Diamond to Crimson's recipients (AE-N-I-B). | | AcknowledgeAlarm | Accepts an acknowledgement for Diamond's alarm (AE-ACK-B). | | GetEventInformation | Reports active events (AE-INFO-B). | -| DeviceCommunicationControl | Accepts `disable-initiation` / `enable`, optionally password-gated (DM-DCC-B). | -| ReinitializeDevice | Accepts COLDSTART/WARMSTART plus the five backup/restore states (DM-RD-B / DM-BR-B). | +| DeviceCommunicationControl | Accepts `disable-initiation` / `enable`, optionally password-gated (DM-DCC-B). No password by default (`DCC_PASSWORD` in `main.cpp`); the device warns at start-up while it is empty. | +| ReinitializeDevice | Accepts COLDSTART/WARMSTART plus the five backup/restore states (DM-RD-B / DM-BR-B), and ACTIVATE_CHANGES (pending Network Port writes; on `--datalink sc`, newly written certificates). | | TimeSynchronization / UTCTimeSynchronization | Accepts a time sync request (DM-TS-B / DM-UTC-B). | | AtomicReadFile / AtomicWriteFile | Reads and writes File 1 "Ivory" (DM-BR-B). | | ReadRange | Retrieves `Log_Buffer` from a Trend Log / Trend Log Multiple (T-ATR-B). A plain ReadProperty of `Log_Buffer` is rejected. | @@ -181,10 +189,11 @@ Trend Log Multiple 1 "Magenta" (polls Bronze/Diamond/Chartreuse) | Multi-state Output | 1 | Indigo | | Analog Value | 1 | Diamond | | Notification Class | 1 | Crimson | -| Network Port | 1 | Vermilion | +| Network Port | 1, 2, 3 or 4 | Vermilion (BACnet/IP), Cerulean (BACnet/IPv6), Amber (MS/TP) or Teal (BACnet/SC) - the active data link's only | | Schedule | 1 | Saffron | | Calendar | 1 | Cream | | File | 1 | Ivory | +| File | 2, 3, 4, 5 | `--datalink sc` only: Operational certificate, Issuer certificate 1 and 2, Certificate signing request | | Trend Log | 1 | Lilac | | Trend Log Multiple | 1 | Magenta | @@ -213,7 +222,16 @@ gates. This is a **self-contained** project. It ships: - `main.cpp` - the example device. -- `common/` - the shared helper (UDP, callbacks, CLI, keyboard) vendored in. +- `command_line.cpp` - `--datalink` and every other option, and `--help`. +- `ipv6/` - the host's IPv6 address for the IPv6 Network Port, and + [ipv6/README.md](ipv6/README.md). +- `mstp/` - the stack's MS/TP engine on a serial port (`MstpDataLink`). +- `sc/` - the BACnet/SC node: the hub connection (libwebsockets), the + certificate files and the CARI request/response. +- `common/` - the shared helper (UDP, IPv6 UDP, serial port, callbacks, + keyboard) vendored in. +- `tools/sign_cari_request.py` - a TEST Certificate Authority step for trying + BACnet/SC on a bench. - `CMakeLists.txt` - the build, the same on Windows, Linux, and macOS. - `docs/PICS.md` - the conformance statement. - `tests/` - the Wire Tests (see [Wire Tests](#wire-tests)), and `wiretest/`, the @@ -263,6 +281,32 @@ first - the build needs the stack submodule. If your CAS BACnet Stack lives somewhere other than the bundled submodule, point CMake at it: `cmake -B build -S . -D CAS_STACK_DIR=/path/to/cas-bacnet-stack`. +BACnet/IP, BACnet/IPv6 and MS/TP need nothing else. BACnet/SC is optional: +see the next section. + +### Building with BACnet/SC + +BACnet/SC needs three libraries: **libwebsockets** (the TLS WebSocket to the +hub), **OpenSSL** and **zlib** (the certificate tools). CMake looks for them +and builds `--datalink sc` when it finds all three; when it does not, it says +so and builds the other three data links, and `--datalink sc` then tells you +how to rebuild. The configure step prints which one happened: + +``` +-- B-BC: BACnet/SC is built (libwebsockets, OpenSSL, zlib found) +``` + +- **Windows** - with vcpkg. Visual Studio ships one: run the same two commands + from a *Developer PowerShell for VS* (which sets `VCPKG_ROOT`), and CMake + installs [`vcpkg.json`](vcpkg.json)'s libraries into the build folder on the + first configure (a few minutes, once). They are linked statically + (`x64-windows-static`), so the executable needs no DLLs. +- **Linux** - `sudo apt install libwebsockets-dev libssl-dev zlib1g-dev`, then + the same two commands. + +`-D BBC_SC=OFF` leaves BACnet/SC out on purpose, even when the libraries are +there. + ## Run ```bash @@ -276,21 +320,25 @@ CMake at it: `cmake -B build -S . -D CAS_STACK_DIR=/path/to/cas-bacnet-stack`. Expected output: ``` -BACnet B-BC (Building Controller) Example - C++ v1.2.0 +BACnet B-BC (Building Controller) Example - C++ v1.3.0 CAS BACnet Stack version: 6.0.23.0 Common helper (common/) version: 3.5.0 +FYI: Data link: BACnet/IP (Network Port 1). Run with --help for the others. FYI: Listening for BACnet/IP on UDP port 47808 (Network Port 1). -TX 21 bytes to 192.168.3.255:47808 (broadcast) (Network Port 1) +TX 21 bytes to 192.168.3.255:47808 (broadcast) (Network Port 1) - Unconfirmed: I-Am +TX 8 bytes to 192.168.3.255:47808 (broadcast) (Network Port 1) - Unconfirmed: Who-Is FYI: Device 389005 ("Chipkin Example B-BC") ready. Vendor ID 389. Press 'h' for help. ``` -The `TX` line is the start-up I-Am the device broadcasts to announce itself, to +The `TX` lines are the start-up I-Am the device broadcasts to announce itself, and +its Who-Is, to the **local subnet broadcast** address (computed from the Network Port's interface). As clients talk to the device you'll see `RX ... bytes from ...` and `TX ... bytes to ...` lines showing the traffic. The device listens on UDP **47808** (BACnet/IP). Allow that port through your -firewall. To use a different port, pass `--port` (see below). +firewall. To use a different port, pass `--port` (see below). For the other +data links see [Data links](#data-links). > **A few red `Error:` lines at start-up are expected and are not your bug** - > it is the stack's own debug logging of the device hearing its own broadcast @@ -302,13 +350,27 @@ firewall. To use a different port, pass `--port` (see below). | Option | Default | Meaning | |--------|---------|---------| -| `--port ` | `47808` | UDP port to listen on (BACnet/IP). | +| `--datalink ` | `ipv4` | `ipv4` (BACnet/IP), `ipv6` (BACnet/IPv6), `mstp` (MS/TP) or `sc` (BACnet/SC). | | `--deviceID ` | `389005` | The device's BACnet instance number (BACnet requires this to be configurable). | | `--deviceName ` | `Chipkin Example B-BC` | The Device object's `Object_Name`, 1..255 bytes, no control characters. It must be unique across the BACnet internetwork, so give every unit its own (BACnet requires it to be configurable, like the instance). An invalid value prints a warning and keeps the default. | -| `--xml` | off | Print every received and sent BACnet message as an indented XML block instead of a one-line summary (very verbose; for protocol debugging). | -| `--help`, `-h` | - | Show usage and exit. | +| `--port ` | `47808` | `ipv4`, `ipv6`: the UDP port. | +| `--interface ` | every interface | `ipv6`: join the multicast group on this interface only, and take the IPv6 address from it. | +| `--mstp-port ` | (required) | `mstp`: the RS-485 adapter's serial port - `COM3`, `/dev/ttyUSB0`. | +| `--mstp-baud ` | `38400` | `mstp`: 9600, 19200, 38400, 57600, 76800 or 115200 (76800 only on Windows, or where termios has `B76800`). | +| `--mstp-mac ` | `1` | `mstp`: this station's address, 0..127, unique on the segment. | +| `--mstp-max-master ` | `127` | `mstp`: the highest station address polled for a new master. | +| `--mstp-max-info-frames ` | `1` | `mstp`: frames sent per token. | +| `--sc-hub ` | (required) | `sc`: the primary hub, `wss://host:port`, at most 255 characters. | +| `--sc-failover-hub ` | none | `sc`: the failover hub. | +| `--sc-cert-dir ` | `./certs` | `sc`: this device's certificates and private key. | +| `--import-cari ` | - | `sc`: install a Certificate Authority's CARI response into `--sc-cert-dir`, then exit. | +| `--xml` | off | Print every frame as XML instead of one line. | +| `--help`, `-h` | - | Show usage (every option) and exit. | | `--version` | - | Print the example, stack, and `common/` helper versions, then exit. | +An option for a data link that is not the one chosen (say `--mstp-baud` with +`--datalink ipv4`) is an error, not silently ignored. + ### Interactive commands While the example runs, these keys are available: @@ -320,6 +382,137 @@ While the example runs, these keys are available: | up arrow | Increase Analog Input 1 (`Bronze`) by 1.1. | | down arrow | Decrease Analog Input 1 (`Bronze`) by 1.1. | | `s` | Add a Weekly_Schedule transition for Schedule 1 (`Saffron`) right now, so it can be observed without waiting for the wall clock. | +| `m` | `--datalink mstp`: print the MS/TP counters (frames, tokens, errors, whether the station is in the token ring). | + +## Data links + +The device runs on **one data link at a time**, chosen with `--datalink`. +Everything above it - the objects, the services, the alarms, the schedule - +is the same on all four. Each data link has its **own** Network Port object +instance, and the device has only the active one's: a client that remembers +"Network Port 1 is the BACnet/IP port" never finds an MS/TP port there after +a restart. + +| `--datalink` | Network Port | Network_Type | Address the device uses | +|---|---|---|---| +| `ipv4` (default) | 1 "Vermilion" | ipv4 (5) | the host's IPv4 address and `--port` | +| `ipv6` | 2 "Cerulean" | ipv6 (9) | the host's IPv6 address and `--port`; the 3-octet VMAC is the device instance | +| `mstp` | 3 "Amber" | mstp (2) | `--mstp-mac` on the RS-485 segment | +| `sc` | 4 "Teal" | secure-connect (11) | a 6-octet VMAC the stack picks; every message goes through the hub | + +Reading the peer device (section 2e, DS-RP-A / DS-RPM-A) works on `ipv4` and +`ipv6` only: its replies are decoded on the UDP receive path, which MS/TP +and BACnet/SC do not go through here (see [TODO.md](TODO.md)). The rest of +the profile is the same on every data link. + +### BACnet/IP (`--datalink ipv4`) + +The default, and unchanged from earlier versions: `BACnetExampleBBC` alone is +the same device as before 1.2.0. + +### BACnet/IPv6 (`--datalink ipv6`) + +```bash +BACnetExampleBBC --datalink ipv6 # multicast group on every interface +BACnetExampleBBC --datalink ipv6 --interface 12 # one interface (ipconfig: the %12) +``` + +Network Port 2 reports the interface's address (`IPv6_Address`, a global one +when there is one; on Windows never a temporary or deprecated one - give +`--interface` when the host has virtual adapters such as Hyper-V or WSL), `IPv6_Prefix_Length`, `IPv6_Default_Gateway`, +`IPv6_DNS_Server` and `BACnet_IPv6_UDP_Port`; broadcasts go to the multicast +group FF02::BAC0 - the start-up I-Am and Who-Is too, as Original-Broadcast-NPDUs. +The example configures no BBMD or foreign-device registration; a client can, through +Network Port 2, but as a BBMD it would not pass its peers' broadcasts on. +[ipv6/README.md](ipv6/README.md) has the details and `tests/ipv6_probe.py`, a +BACnet/IPv6 client in plain Python to check it from outside. + +### MS/TP (`--datalink mstp`) + +```bash +BACnetExampleBBC --datalink mstp --mstp-port COM3 --mstp-baud 38400 --mstp-mac 12 +BACnetExampleBBC --datalink mstp --mstp-port /dev/ttyUSB0 --mstp-mac 12 +``` + +The stack runs MS/TP itself - the token, Poll For Master, the frame timers - +and the example only moves bytes between it and the serial port +([`mstp/MstpDataLink.cpp`](mstp/MstpDataLink.cpp), on +[`common/SimpleSerial`](common/SimpleSerial.h)). A USB-to-RS-485 adapter that +switches its driver itself is all the hardware it needs. + +- Every station on the segment must use the **same baud rate**, and a **MAC + address no other station uses**. The device reports both on Network Port 3 + (`Link_Speed`, `MAC_Address`) with `Max_Master` and `Max_Info_Frames`. + `Max_Master` and `Max_Info_Frames` are writable; like every Network Port + setting the write is *pending* until ReinitializeDevice `ACTIVATE_CHANGES`. +- The start-up I-Am and Who-Is go out once the station has joined the token + ring. The Who-Is is global, so devices behind an MS/TP to BACnet/IP router + answer too. +- The `m` key prints the engine's counters. They are also printed when the + station joins or leaves the token ring, a minute after it joins, and every + 10 s while it has not found the ring. Frames received but no token + usually means a wrong baud rate; nothing received at all, wiring (swap A/B). +- The largest APDU on MS/TP is 480 octets, so the Device's + `Max_APDU_Length_Accepted` reads 480 in this mode. +- On Linux, 76800 baud needs a serial driver and C library that define + `B76800`; where they do not, `--mstp-baud 76800` is refused at start-up + and `--help` leaves it out. +- The RS-485 driver is not switched by the example: USB-to-RS-485 adapters + switch it themselves. An adapter that needs RTS to enable its driver needs + a `TransmitEnable` callback (`BACnetStack_RegisterCallbackMSTPTransmitEnable` + in the stack's header) that this example does not register. +- A write is "sent" when the serial driver says so. For a USB adapter that is + when the USB transfer completes, which can be slightly before the last stop + bit leaves the adapter (see [TODO.md](TODO.md)). + +### BACnet/SC (`--datalink sc`) + +The device is a BACnet/SC **node**: it opens a TLS WebSocket to a **hub** +(`--sc-hub`, and optionally `--sc-failover-hub`) and every message goes +through it. It needs a certificate signed by a Certificate Authority the hub +trusts, which it gets the way the B-SCHUB example's hub does - a CARI +request and response (135-2024 Annex AA.2): + +1. **First start** - no certificate yet. The device makes a private key and a + certificate signing request, writes `certs/node-cari-request.zip`, prints + what to do next and stops: + + ```bash + BACnetExampleBBC --datalink sc --sc-hub wss://192.168.1.20:4443 + ``` + +2. **Sign it** - send the zip to your Certificate Authority (the Chipkin + BACnet SC Certificate Authority, BACnet International's BACCARI, or your + own). To try it on a bench, `tools/sign_cari_request.py` plays a TEST CA + with the B-SCHUB example's demo CA (its key is public - test networks + only): + + ```bash + python tools/sign_cari_request.py certs/node-cari-request.zip \ + --ca-cert ../BACnetProfileExample-B-SCHUB-CPP/certs/ca/ca-cert.pem \ + --ca-key ../BACnetProfileExample-B-SCHUB-CPP/certs/ca/ca-key.pem \ + --out node-cari-response.zip + ``` + +3. **Import the response**, then start again: + + ```bash + BACnetExampleBBC --datalink sc --import-cari node-cari-response.zip + BACnetExampleBBC --datalink sc --sc-hub wss://192.168.1.20:4443 + ``` + +Network Port 4 then reports the connection: `SC_Primary_Hub_Connection_Status` +reads `connected` once the hub has accepted the device, and the I-Am and +Who-Is go out through the hub. The certificates are also File objects 2 to 5 +(the operational certificate, two issuer certificates and the signing +request), so a client can replace them over BACnet: AtomicWriteFile the new +certificate, then ReinitializeDevice `ACTIVATE_CHANGES` - the example checks +the new set before using it and refuses one that would leave it unable to +connect. Network Port Command `GENERATE_CSR_FILE` makes a new key and request. + +Keep `--sc-cert-dir` private: it holds the device's private key. The hub's +host name is not checked against its certificate (an IP-addressed hub on a +bench rarely has one that matches), but its certificate chain is. ## Verify diff --git a/TODO.md b/TODO.md index 68292eb..414b4a5 100644 --- a/TODO.md +++ b/TODO.md @@ -1,18 +1,127 @@ # TODO - known gaps (each checked against the pinned stack source and/or the wire, not assumed) -Stack pin: `69b6249f` (`6.x`, 2026-10-25, reports 6.0.23). Re-checked 2026-10-26 when the pin -moved from `4238a39f`: clean build (0 warnings), every Wire Test passes, segmentation both. -Before that, `4238a39f` (2026-10-23) was re-checked 2026-10-24 when the pin moved from -`64b2cfac5`: clean build (0 warnings), every Wire Test passes, every listed property -reads, segmentation both. Before that, `64b2cfac5` (2026-10-15) moved it from `00aa2d0e` -(`issues/runbook`, 6.0.22), when the stack-held Calendars this example needed (#1758) reached `6.x`. - -This example is **Profile-functional** (series `docs/GLOSSARY.md`) since 1.1.0 (this file is current at release 1.2.0): the Wire +Stack pin: `d9f39406` (`6.x`, 2026-10-28, reports 6.0.23) since 1.3.0, the promotion that +carries the BACnet/IPv6 data link, its client broadcasts (#4636) and the MS/TP engine. Before it: +`632165847` (`issues/runbook`) on the `ipv6` branch, `69b6249f` for release 1.2.0, and +`64b2cfac5` (`6.x`, 2026-10-15). + +This example is **Profile-functional** (series `docs/GLOSSARY.md`) since 1.1.0 (this file is current at release 1.3.0): the Wire Tests prove it reading a peer (DS-RP-A, DS-RPM-A), acting on the reading, writing the peer (DS-WP-A, SCHED-E-B) and handling the peer going silent. No `[KNOWN GAP]` - nothing in this example's Profile Function is blocked by the stack at this pin. What is left is this example's own scope (bottom of this file). +## 1.3.0 - the four data links (`--datalink`) + +### Stack gaps found while adding them (not filed - recorded here) + +- **No way to see a reply's value on MS/TP or BACnet/SC.** Section 2e reads the peer by + decoding the ReadProperty-ACK in the receive callback, because the stack has no hook that + hands the application a confirmed-service ACK. On BACnet/IP and BACnet/IPv6 the whole + datagram passes through that callback; on MS/TP the stack's byte-mode engine does the + framing, so the application never sees the APDU, and on BACnet/SC it arrives inside the + hub's WebSocket frame. So DS-RP-A / DS-RPM-A run on `ipv4` and `ipv6` only. A hook that + delivers a ReadProperty / ReadPropertyMultiple ACK (decoded, or as APDU octets) would make + section 2e data-link independent. +- **`BACNET_NETWORK_PORT_DEFAULT` is no help with several data links.** With more than one + data link compiled in (the default full build), the default port instance does not name + the MS/TP port; this example always names its Network Port instance explicitly. +- **`docs/property-profile-reference.md` is no longer in the stack checkout** at `b79d4b5bb` + or `632165847` + (it became generated output). The series' `tools/gen-objects-properties.py` reads it from + the submodule, so `docs/PICS.md` was regenerated against the copy at `64b2cfac5` (the + previous pin, in the B-SCHUB example's submodule). The generic Network Port and File rows + it uses did not change. +- **"Unsupported datatype for callbacks" for Network Port 1's Command_Validation_Result.** At + `d9f39406` the stack prints this line when a client reads the property on `ipv4`; the read + itself succeeds and the discovery Wire Test passes. Log noise only; not filed yet. + +### Checked at `d9f39406` (release 1.3.0, 2026-10-28) + +- **Windows 11** (Visual Studio 2026, vcpkg, BACnet/SC built): all ten Wire Test scripts pass + (`python tests/run_wire_tests.py`); `tests/ipv6_probe.py` 14/14; MS/TP on COM3 as MAC 12 + (`--deviceID 389105`), six reads through the router; BACnet/SC 10/10 against the B-SCHUB + hub on the same PC (enrolment, then Who-Is, Object_Name, Application_Software_Version 1.3.0, + Network Port 4 name, Network_Type 11 and Reliability through the hub), twice. +- **Linux** (Ubuntu 22.04 in WSL2, g++ 11, distribution libwebsockets 4.0.20): all Wire Tests + pass; `tests/ipv6_probe.py` 14/14 on `eth0`; BACnet/SC 10/10 against the same hub on the + Windows host, across the WSL NAT. Two build fixes came out of it (CHANGELOG 1.3.0, Fixed): + Ubuntu's `LibwebsocketsConfig.cmake` file name, and `LWS_PROTOCOL_LIST_TERM`, which + libwebsockets 4.0 does not define. `tools/sign_cari_request.py` needs `cryptography` 42 or + later; Ubuntu 22.04's package is older (`pip install "cryptography>=42"`). +- Issues #15, #16 and #18 of this repository (UUID / date-time log lines, unreadable + properties) no longer reproduce at this pin: no such lines, every property reads. +- **BACnet/SC first connection.** In some earlier runs the same day (Windows, with libwebsockets + logging raised) the first connection attempt ended "Closed before conn" and the retry + connected about a minute later; once, context creation itself took 51 s. Not reproduced in + the four runs above, where the device connected at once. If a device is slow to reach its + hub on Windows, look here first. + +### Checked, and how (Windows 11, 2026-10-28, on the `ipv6` branch before the merge) + +- `ipv4` (the default): `python tests/run_wire_tests.py` - ALL WIRE TESTS PASSED. +- `ipv6`: `python tests/ipv6_probe.py --target fe80::...%10 --multicast --interface 10` - + 14/14, including Network Port 2 Network_Type 9, MAC_Address = the VMAC, the UDP port, the + 16-octet IPv6_Address, and the multicast Address-Resolution. By hand: IPv6_Prefix_Length 64, + IPv6_Default_Gateway, IPv6_DNS_Server (the host's, as `ipconfig /all` lists it), + BACnet_IPv6_Multicast_Address FF02::BAC0 port 47808, APDU_Length 1476, Device + Max_APDU_Length_Accepted 1476. At `632165847`, a capture on the Ethernet interface (tshark) + showed the start-up I-Am and Who-Is leave as Original-Broadcast-NPDUs (BVLC 82 02, source + VMAC 05EF8D) to [FF02::BAC0]:47808. + +### Resolved during 1.2.0 + +- **No application broadcast on BACnet/IPv6** (found at `b79d4b5bb`): `BACnetStack_SendIAm` / + `SendWhoIs` refused a call with no connection string, and with one the IPv6 data link sent a + unicast, so the example could not announce itself on `--datalink ipv6`. Fixed by + cas-bacnet-stack #4636 (`632165847`): with `broadcast` true and any 18-octet connection + string the message goes out as an Original-Broadcast-NPDU, handed to the host with no + connection string. +- `sc`: against the B-SCHUB example's hub on this PC (`wss://127.0.0.1:4443/`). First start + made `certs/node-cari-request.zip`; `tools/sign_cari_request.py` signed it with B-SCHUB's + demo CA; `--import-cari` installed it; the device connected and sent I-Am / Who-Is. Read + through the hub with B-SCHUB's Python BACnet/SC client: Network Port 4 "Teal", Network_Type + 11, SC_Primary_Hub_URI, SC_Primary_Hub_Connection_Status connection-state 1 (connected) with + its connect timestamp, SC_Hub_Connector_State 1 (connected to primary), the certificate File + references 2 / 3, 4 / 5, and Files 2-5 (name, type, size, Read_Only, Modification_Date). +- `mstp`: on a USB-to-RS-485 adapter (CP210x, COM3) wired to a live segment with an MS/TP + to BACnet/IP router. A passive listen first found the segment at 38400 baud with stations + 0 and 10 passing the token; the example ran as MAC 12 (`--deviceID 389105`: station 10 + already answers as device 389005). It joined the ring; one minute later its counters read + 2466 frames heard (1086 for it), 1917 sent, 0 dropped, 0 octets lost, last frame a Token + from 10 to 12. From BACnet/IP, a global Who-Is to the subnet broadcast came back as an + I-Am from 389105 via router 192.168.3.107, SNET 5, SADR 0C; ReadProperty through the + router (DNET 5, DADR 0C) read Object_Name, Max_APDU_Length_Accepted 480, + Application_Software_Version 1.2.0, and Network Port 3: "Amber", Network_Type 2, + MAC_Address 0C, Max_Master 127, Max_Info_Frames 1, Link_Speed 38400.0, APDU_Length 480. + Only 38400 was run on the wire (the segment's rate); the router was not reconfigured. + +### Not checked yet + +- macOS: nothing was built or run there. On Linux, MS/TP through `common/SimpleSerial` was built + but not run on a bus (WSL has no serial adapter attached). +- 76800 baud on Linux: termios has no `B76800` on most systems, so `SimpleSerial` refuses it + there; a `termios2` / `BOTHER` custom rate would be needed. +- A USB serial adapter reports a write as done when the USB transfer completes, a little + before the adapter's UART has sent the last octet. Not measured; if a station misses + replies at high baud rates, look here first. +- The BACnet/SC certificate procedures over BACnet (AtomicWriteFile to Files 2-4, then + ReinitializeDevice ACTIVATE_CHANGES; Network Port Command GENERATE_CSR_FILE): the code is + the B-SCHUB example's `CertStore`, but not exercised against this example. +- The BACnet/SC failover hub. +- Writing the MS/TP port's Max_Master / Max_Info_Frames and activating them. +- MS/TP at baud rates other than 38400 on the wire (the others are accepted by `--mstp-baud` + and opened by `SimpleSerial`, but no segment ran at them). +- Writing File_Size of the BACnet/SC certificate Files 2-4 over BACnet: the Set callback + handles it (truncate / extend before an AtomicWriteFile), but whether the stack lets a + client write it was not tried, so `docs/objects.json` lists no writable File property. + +### Pending in the series + +- `common/` gained `SimpleUDP6` and `SimpleSerial` (`common/CHANGELOG.md`, [Unreleased]). + `COMMON_VERSION` is not bumped and the series is not re-synced yet: do both when this + branch is merged (`tools/sync-common.sh`). + ## Resolved in 1.1.0 - **DS-RP-A and DS-RPM-A** (was item 1). `main.cpp` section 2e polls peer 389002's Analog @@ -36,7 +145,7 @@ own scope (bottom of this file). - **Trend Log writable properties** (`Enable`, `Record_Count`, `Log_Interval`) are in the PICS; Wire Test `trend_log_write_test.py`. -## Known limitations at 1.2.0 +## Known limitations (since 1.2.0, unchanged at 1.3.0) None of these is a stack gap; they are this example's design, listed so a support request can quote them. diff --git a/TUTORIAL.md b/TUTORIAL.md index c34c0c9..971c738 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -146,12 +146,74 @@ know before you copy it: client reading `Present_Value` gets a value, and `Reliability` tells it how far to trust it. +4. **Only on the data links whose bytes you see.** On BACnet/IP and + BACnet/IPv6 every datagram passes through this example's receive callback + whole. On MS/TP the stack's own engine frames the bytes, and on BACnet/SC + the message arrives inside a hub's WebSocket frame; this example does not + decode the reply there, so section 2e runs on `ipv4` and `ipv6` only (see + [TODO.md](TODO.md)). + The peer's address is learned from its I-Am with `BACnetStack_RegisterHookIAm` (the hook runs after the stack has updated its own Device Address Binding table). The example only addresses a peer on its own network; a peer behind a router needs its SNET/SADR passed as `destinationNetwork` / `destinationAddress` on every read. +### Running on another data link + +`--datalink` picks the data link at start-up; everything above the data link +is the same code. What changes per data link is in four places in `main.cpp`: + +1. **The Network Port object** (section 1b, and "Add the Network Port object" + in `main()`). Each data link has its own instance - 1 BACnet/IP, 2 + BACnet/IPv6, 3 MS/TP, 4 BACnet/SC - and the device creates only the active + one. `ActiveNetworkPortInstance()` is the number every transport callback + and every `BACnetStack_Send*` call names: the stack identifies a link by its + Network Port instance, so a send that names the wrong one goes nowhere. +2. **What the port's properties say.** The stack serves most of a Network Port + itself, and asks the Get callbacks for what only the application knows - + the host's IPv6 address, the MS/TP station address. The `GetDataLinkPort*` + helpers in section 1b answer those, and each Get callback calls its helper + first. On MS/TP the stack's engine *reads its own configuration* through + them: `MAC_Address`, `Max_Master`, `Max_Info_Frames` and `Link_Speed` are + how `--mstp-mac`, `--mstp-max-master`, `--mstp-max-info-frames` and + `--mstp-baud` reach the token ring. +3. **The transport callbacks** (end of section 2e). BACnet/IP and BACnet/IPv6 + send and receive whole datagrams on this example's sockets; BACnet/SC hands + whole messages to the hub connection (`sc/ScNode.cpp`). MS/TP is the odd + one out: the stack runs the token ring in **byte mode** and moves octets + through three other callbacks (`mstp/MstpDataLink.cpp`), and the main loop + must call `BACnetStack_LoopMSTP()` every millisecond or two. +4. **What a broadcast is.** The local subnet broadcast address (BACnet/IP), + no address at all - the multicast group FF02::BAC0 (BACnet/IPv6), station + 255 (MS/TP), or the hub's URI (BACnet/SC: the hub sends it on to every + node). `SendIAmBroadcast()` and `SendWhoIsBroadcast()` hold all four. + +On BACnet/IPv6 the send functions still want a connection string with +`broadcast` true; the example passes the multicast group, [FF02::BAC0] on its +UDP port. The stack sends an Original-Broadcast-NPDU and hands it to the send +callback with `broadcast` true and no connection string, and the callback +multicasts it. + +Timing differs too. On BACnet/IP and BACnet/IPv6 the start-up I-Am goes out at once. An MS/TP station may only send while it holds the token, so the +example waits until it has joined the token ring; a BACnet/SC node has +nowhere to send until the hub has accepted it, so the example waits for that. + +**BACnet/SC rules this example follows** - they hold for any application that +connects the stack to a hub itself: + +- Never call a `BACnetStack_*` function from a libwebsockets callback. The + stack's callbacks (`InitiateWebsocket`, `SendMessage`) only queue work; the + main loop does it and reports connection changes with + `BACnetStack_SetBACnetSCWebSocketStatus`. +- Keep one TLS context for the life of the program. libwebsockets' OpenSSL + set-up is global, and making and destroying contexts per connection leaks + and races. +- Enforce the 1600-octet maximum message size on what you receive, before it + reaches the stack - the same value given to `BACnetStack_SetBACnetSCSettings`. +- The send callback must return the number of octets it accepted - the + message length - not a boolean. + ### Adding a Trend Log `BACnetStack_AddTrendLogObject` creates the object itself - no separate @@ -181,7 +243,7 @@ router needs its SNET/SADR passed as `destinationNetwork` / | Multi-State Output | `Object_Name`, `Number_Of_States`, `Relinquish_Default` | same priority-array pattern | | Analog Value (alarm-capable) | `Object_Name`, `Units` | `Present_Value` writable; `Event_State` genuinely computed once an intrinsic algorithm is armed | | Notification Class | `Object_Name` | `Priority`/`Ack_Required`/`Recipient_List` held by the stack's own host-configuration API (`AddNotificationClassObject` / `AddRecipientToNotificationClass`), not a `GetProperty*` callback | -| Network Port | `Object_Name`, `Out_Of_Service`, `Network_Type`, `Protocol_Level`, `Changes_Pending` | BACnet/IP addressing via `GetPropertyOctetString` | +| Network Port | `Object_Name`, `Out_Of_Service`, `Network_Type`, `Protocol_Level`, `Changes_Pending` | BACnet/IP addressing via `GetPropertyOctetString`; BACnet/IPv6 address and gateway (`GetPropertyOctetString`), prefix length and UDP port (`GetPropertyUnsignedInteger`); MS/TP `MAC_Address` (one octet), `Max_Master`, `Max_Info_Frames`, `Link_Speed` = baud rate; BACnet/SC: nothing - the stack holds it all | | Schedule | `Object_Name`, `Reliability`, `Out_Of_Service` | `Present_Value`/`Effective_Period`/`Schedule_Default`/`List_Of_Object_Property_References` held by the stack's Schedule engine | | Calendar | `Object_Name` | Stack-held: after `AddCalendarObject` the stack stores `Date_List` (populate with `AddCalendarDateEntry` / `AddCalendarDateRangeEntry` / `AddCalendarWeekNDayEntry`) and derives `Present_Value` from the device's `Local_Date`. Make `Date_List` writable with `SetPropertyWritable(..., 23, true)` to let clients edit it | | File | `Object_Name`, `File_Type`, `File_Size`, `Modification_Date`, `Archive` (writable), `Read_Only` | `File_Access_Method` served by the stack | diff --git a/command_line.cpp b/command_line.cpp new file mode 100644 index 0000000..6a14716 --- /dev/null +++ b/command_line.cpp @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +// +// command_line.cpp - see command_line.h. + +#include "command_line.h" + +#include "CASExampleHelper.h" + +#include +#include +#include +#include +#include + +#if !defined(_WIN32) +#include // B76800, where the system has it +#endif + +// 76800 baud: Windows takes any rate; on POSIX only where termios defines +// B76800 (most Linux systems do not). SimpleSerial::Open() refuses it there, so +// the parser refuses it first, with a clearer message. +#if defined(_WIN32) || defined(B76800) +#define BBC_HAS_76800_BAUD 1 +#endif + +namespace { + +void PrintUsage(const char* appName, const char* appVersion) { + CASExampleHelper::PrintVersion(appName, appVersion); + printf("\n"); + printf("Usage: BACnetExampleBBC [--datalink ipv4|ipv6|mstp|sc] [options]\n"); + printf("\n"); + printf("One device, on ONE data link at a time. Each data link has its own Network Port\n"); + printf("object: 1 BACnet/IP, 2 BACnet/IPv6, 3 MS/TP, 4 BACnet/SC.\n"); + printf("\n"); + printf("General:\n"); + printf(" --help, -h Show this help and exit.\n"); + printf(" --version Show version information and exit.\n"); + printf(" --datalink ipv4 (default), ipv6, mstp or sc.\n"); + printf(" --deviceID Device instance, 0..4194302. Default 389005.\n"); + printf(" --deviceName Device Object_Name, 1..255 bytes, no control characters.\n"); + printf(" Default \"Chipkin Example B-BC\".\n"); + printf(" --xml Print every received/sent message as XML (very verbose).\n"); + printf("\n"); + printf("BACnet/IP (--datalink ipv4) and BACnet/IPv6 (--datalink ipv6):\n"); + printf(" --port UDP port, 1..65535. Default 47808 (0xBAC0).\n"); + printf(" --interface ipv6 only: the interface to use (its index - the %%N after a\n"); + printf(" link-local address in ipconfig, or `ip link` on Linux).\n"); + printf(" Default: join the multicast group on every interface.\n"); + printf("\n"); + printf("MS/TP (--datalink mstp):\n"); + printf(" --mstp-port Serial port of the RS-485 adapter (COM3, /dev/ttyUSB0). Required.\n"); +#ifdef BBC_HAS_76800_BAUD + printf(" --mstp-baud 9600, 19200, 38400 (default), 57600, 76800 or 115200.\n"); +#else + printf(" --mstp-baud 9600, 19200, 38400 (default), 57600 or 115200. (76800 is not\n"); + printf(" available: this system's termios has no B76800.)\n"); +#endif + printf(" --mstp-mac This station's MAC address, 0..127. Default 1. Must be unique\n"); + printf(" on the segment.\n"); + printf(" --mstp-max-master Highest master address polled for, 1..127. Default 127.\n"); + printf(" --mstp-max-info-frames \n"); + printf(" Frames sent per token, 1..255. Default 1.\n"); + printf("\n"); + printf("BACnet/SC (--datalink sc):\n"); +#ifndef BBC_WITH_SC + printf(" (NOT in this build - libwebsockets, OpenSSL and zlib were not found when it was\n"); + printf(" built. See \"Building with BACnet/SC\" in README.md.)\n"); +#endif + printf(" --sc-hub The primary hub, wss://host:port. Required.\n"); + printf(" --sc-failover-hub The failover hub, wss://host:port. Optional.\n"); + printf(" --sc-cert-dir This device's certificates. Default ./certs. The first start\n"); + printf(" makes /node-cari-request.zip for a Certificate Authority.\n"); + printf(" --import-cari Install the Certificate Authority's CARI response zip into\n"); + printf(" --sc-cert-dir and exit. Then start the device again.\n"); + printf("\n"); + printf("Examples:\n"); + printf(" BACnetExampleBBC\n"); + printf(" BACnetExampleBBC --datalink ipv6 --interface 12\n"); + printf(" BACnetExampleBBC --datalink mstp --mstp-port COM3 --mstp-baud 38400 --mstp-mac 12\n"); + printf(" BACnetExampleBBC --datalink sc --sc-hub wss://192.168.1.20:4443\n"); + printf(" BACnetExampleBBC --datalink sc --import-cari node-cari-response.zip\n"); + printf("\n"); + printf("Keys while running: h help, q quit, up/down nudge Analog Input 1, s add a Schedule\n"); + printf("entry for now, m data link counters (MS/TP).\n"); +} + +// Reads a decimal number in [minimum, maximum]. False if `text` is not one. +// strtoul skips leading white space - and accepts a sign after it, " -1" +// wrapping to ULONG_MAX - so anything but a digit first is refused here. +bool ParseNumber(const char* text, const unsigned long minimum, const unsigned long maximum, unsigned long* value) { + if (text == NULL || !isdigit((unsigned char)*text)) { + return false; + } + errno = 0; + char* parseEnd = NULL; + const unsigned long parsedValue = strtoul(text, &parseEnd, 10); + if (errno != 0 || parseEnd == text || *parseEnd != '\0' || parsedValue < minimum || parsedValue > maximum) { + return false; + } + *value = parsedValue; + return true; +} + +// The options that only mean something on one data link, so a wrong +// combination can be reported by name. +struct DataLinkOption { + const char* name; + DataLink dataLink; // the data link it belongs to (--port belongs to two: see below) +}; + +const DataLinkOption DATA_LINK_OPTIONS[] = { + { "--interface", DataLink::IPv6 }, + { "--mstp-port", DataLink::MSTP }, + { "--mstp-baud", DataLink::MSTP }, + { "--mstp-mac", DataLink::MSTP }, + { "--mstp-max-master", DataLink::MSTP }, + { "--mstp-max-info-frames", DataLink::MSTP }, + { "--sc-hub", DataLink::SC }, + { "--sc-failover-hub", DataLink::SC }, + { "--sc-cert-dir", DataLink::SC }, + { "--import-cari", DataLink::SC }, +}; + +// Is `option` one this example takes (each with a value; --xml is handled +// before this is asked)? +bool IsKnownOption(const char* option) { + if (strcmp(option, "--datalink") == 0 || strcmp(option, "--deviceID") == 0 || strcmp(option, "--deviceName") == 0 || + strcmp(option, "--port") == 0) { + return true; + } + for (const DataLinkOption& dataLinkOption : DATA_LINK_OPTIONS) { + if (strcmp(dataLinkOption.name, option) == 0) { + return true; + } + } + return false; +} + +const char* DataLinkArgument(const DataLink dataLink) { + switch (dataLink) { + case DataLink::IPv4: return "ipv4"; + case DataLink::IPv6: return "ipv6"; + case DataLink::MSTP: return "mstp"; + case DataLink::SC: return "sc"; + } + return "?"; +} + +ParseResult Fail(const char* format, const char* detail, const char* moreDetail = "") { + fprintf(stderr, "Error: "); + fprintf(stderr, format, detail, moreDetail); + fprintf(stderr, "\nRun with --help for every option.\n"); + return ParseResult::ExitError; +} + +} // namespace + +const char* DataLinkName(const DataLink dataLink) { + switch (dataLink) { + case DataLink::IPv4: return "BACnet/IP"; + case DataLink::IPv6: return "BACnet/IPv6"; + case DataLink::MSTP: return "MS/TP"; + case DataLink::SC: return "BACnet/SC"; + } + return "?"; +} + +ParseResult ParseCommandLine(const int argc, char** argv, const char* appName, const char* appVersion, + CommandLineOptions* options) { + // --help and --version win over everything else, wherever they are. + for (int argumentIndex = 1; argumentIndex < argc; ++argumentIndex) { + if (strcmp(argv[argumentIndex], "--help") == 0 || strcmp(argv[argumentIndex], "-h") == 0 || + strcmp(argv[argumentIndex], "/?") == 0) { + PrintUsage(appName, appVersion); + return ParseResult::ExitSuccess; + } + if (strcmp(argv[argumentIndex], "--version") == 0) { + CASExampleHelper::PrintVersion(appName, appVersion); + return ParseResult::ExitSuccess; + } + } + + // Which options were given, to check the combination afterwards. + bool portGiven = false; + const char* dataLinkOptionsGiven[sizeof(DATA_LINK_OPTIONS) / sizeof(DATA_LINK_OPTIONS[0])] = { NULL }; + + for (int argumentIndex = 1; argumentIndex < argc; ++argumentIndex) { + const char* option = argv[argumentIndex]; + if (strcmp(option, "--xml") == 0) { + continue; // read by CASExampleHelper::ParseXmlLogArg() + } + // Every other option takes a value. + if (strncmp(option, "--", 2) != 0) { + return Fail("unexpected argument \"%s\"%s", option); + } + if (!IsKnownOption(option)) { + return Fail("unknown option \"%s\"%s", option); + } + if (argumentIndex + 1 >= argc) { + return Fail("%s needs a value%s", option); + } + const char* value = argv[++argumentIndex]; + unsigned long number = 0; + + if (strcmp(option, "--datalink") == 0) { + if (strcmp(value, "ipv4") == 0 || strcmp(value, "ip") == 0) { + options->dataLink = DataLink::IPv4; + } else if (strcmp(value, "ipv6") == 0) { + options->dataLink = DataLink::IPv6; + } else if (strcmp(value, "mstp") == 0) { + options->dataLink = DataLink::MSTP; + } else if (strcmp(value, "sc") == 0) { + options->dataLink = DataLink::SC; + } else { + return Fail("--datalink \"%s\" is not a data link this example knows (ipv4, ipv6, mstp or sc)%s", value); + } + } else if (strcmp(option, "--deviceID") == 0) { + if (!ParseNumber(value, 0, 4194302, &number)) { + return Fail("--deviceID \"%s\" is not a device instance (0..4194302)%s", value); + } + options->deviceInstance = (uint32_t)number; + } else if (strcmp(option, "--deviceName") == 0) { + // Checked by CASExampleHelper::ParseDeviceNameArg in main(): a bad name + // warns and keeps the default rather than stopping the device (1.2.0). + } else if (strcmp(option, "--port") == 0) { + if (!ParseNumber(value, 1, 65535, &number)) { + return Fail("--port \"%s\" is not a UDP port (1..65535)%s", value); + } + options->udpPort = (uint16_t)number; + portGiven = true; + } else { + // A data-link option: record it, then read its value. + size_t knownIndex = 0; + const size_t knownCount = sizeof(DATA_LINK_OPTIONS) / sizeof(DATA_LINK_OPTIONS[0]); + while (knownIndex < knownCount && strcmp(DATA_LINK_OPTIONS[knownIndex].name, option) != 0) { + ++knownIndex; + } + if (knownIndex == knownCount) { + return Fail("unknown option \"%s\"%s", option); + } + dataLinkOptionsGiven[knownIndex] = option; + + if (strcmp(option, "--interface") == 0) { + if (!ParseNumber(value, 1, 0xFFFFFFFFUL, &number)) { + return Fail("--interface \"%s\" is not an interface index%s", value); + } + options->ipv6InterfaceIndex = (uint32_t)number; + } else if (strcmp(option, "--mstp-port") == 0) { + options->mstpPortName = value; + } else if (strcmp(option, "--mstp-baud") == 0) { + const unsigned long supportedBaudRates[] = { 9600, 19200, 38400, 57600, 76800, 115200 }; + bool supported = false; + if (ParseNumber(value, 1, 0xFFFFFFFFUL, &number)) { + for (const unsigned long baudRate : supportedBaudRates) { + supported = supported || number == baudRate; + } + } + if (!supported) { + return Fail("--mstp-baud \"%s\" is not an MS/TP baud rate (9600, 19200, 38400, 57600, 76800 " + "or 115200)%s", value); + } +#ifndef BBC_HAS_76800_BAUD + if (number == 76800) { + return Fail("--mstp-baud %s is not available on this system: its termios has no B76800%s", + value); + } +#endif + options->mstpBaudRate = (uint32_t)number; + } else if (strcmp(option, "--mstp-mac") == 0) { + if (!ParseNumber(value, 0, 127, &number)) { + return Fail("--mstp-mac \"%s\" is not an MS/TP master MAC address (0..127)%s", value); + } + options->mstpMacAddress = (uint8_t)number; + } else if (strcmp(option, "--mstp-max-master") == 0) { + if (!ParseNumber(value, 1, 127, &number)) { + return Fail("--mstp-max-master \"%s\" is not 1..127%s", value); + } + options->mstpMaxMaster = (uint8_t)number; + } else if (strcmp(option, "--mstp-max-info-frames") == 0) { + if (!ParseNumber(value, 1, 255, &number)) { + return Fail("--mstp-max-info-frames \"%s\" is not 1..255%s", value); + } + options->mstpMaxInfoFrames = (uint8_t)number; + } else if (strcmp(option, "--sc-hub") == 0 || strcmp(option, "--sc-failover-hub") == 0) { + if (strncmp(value, "wss://", 6) != 0 || strlen(value) <= 6) { + return Fail("%s \"%s\" is not a secure WebSocket URI (wss://host:port)", option, value); + } + // The start-up I-Am / Who-Is hand the hub URI to the stack with + // a one-octet length. + if (strlen(value) > 255) { + return Fail("%s is longer than 255 characters%s", option); + } + (strcmp(option, "--sc-hub") == 0 ? options->scPrimaryHubUri : options->scFailoverHubUri) = value; + } else if (strcmp(option, "--sc-cert-dir") == 0) { + options->scCertificateDirectory = value; + } else if (strcmp(option, "--import-cari") == 0) { + options->importCariZip = value; + } + } + } + + // The combination: every data-link option must belong to the chosen link. + for (size_t knownIndex = 0; knownIndex < sizeof(DATA_LINK_OPTIONS) / sizeof(DATA_LINK_OPTIONS[0]); ++knownIndex) { + if (dataLinkOptionsGiven[knownIndex] != NULL && DATA_LINK_OPTIONS[knownIndex].dataLink != options->dataLink) { + fprintf(stderr, "Error: %s is a --datalink %s option, but the data link is %s (--datalink %s).\n", + dataLinkOptionsGiven[knownIndex], DataLinkArgument(DATA_LINK_OPTIONS[knownIndex].dataLink), + DataLinkName(options->dataLink), DataLinkArgument(options->dataLink)); + fprintf(stderr, "Add --datalink %s, or leave %s out. Run with --help for every option.\n", + DataLinkArgument(DATA_LINK_OPTIONS[knownIndex].dataLink), dataLinkOptionsGiven[knownIndex]); + return ParseResult::ExitError; + } + } + if (portGiven && (options->dataLink == DataLink::MSTP || options->dataLink == DataLink::SC)) { + return Fail("--port is a UDP port, for --datalink ipv4 or ipv6; %s has none%s", + DataLinkName(options->dataLink)); + } + if (options->dataLink == DataLink::MSTP) { + if (options->mstpPortName.empty()) { + return Fail("--datalink mstp needs the serial port: --mstp-port COM3 (Windows) or --mstp-port " + "/dev/ttyUSB0 (Linux)%s%s", ""); + } + if (options->mstpMacAddress > options->mstpMaxMaster) { + fprintf(stderr, "Error: --mstp-mac %u is above --mstp-max-master %u: no station would ever pass this " + "one the token.\n", options->mstpMacAddress, options->mstpMaxMaster); + return ParseResult::ExitError; + } + } + if (options->dataLink == DataLink::SC && options->scPrimaryHubUri.empty() && options->importCariZip.empty()) { + return Fail("--datalink sc needs the hub to connect to: --sc-hub wss://host:port%s%s", ""); + } + return ParseResult::Run; +} diff --git a/command_line.h b/command_line.h new file mode 100644 index 0000000..63ec5cc --- /dev/null +++ b/command_line.h @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +#ifndef BBC_EXAMPLE_COMMAND_LINE_H +#define BBC_EXAMPLE_COMMAND_LINE_H + +// command_line.h +// ============================================================================= +// Every command-line option of the B-BC example, checked in one place. +// +// One executable runs on any ONE of four BACnet data links, chosen with +// --datalink (BACnet/IP when it is left out, exactly as before): +// +// --datalink ipv4 BACnet/IP (Annex J) UDP, --port +// --datalink ipv6 BACnet/IPv6 (Annex U) UDP multicast, --port, --interface +// --datalink mstp MS/TP (clause 9) RS-485, --mstp-* +// --datalink sc BACnet/SC (Annex AB) a TLS WebSocket to a hub, --sc-* +// +// An option that belongs to another data link than the one chosen is an error, +// not silently ignored: "--mstp-port COM3" without "--datalink mstp" almost +// certainly means the --datalink was forgotten. +// ============================================================================= + +#include + +#include + +enum class DataLink { IPv4, IPv6, MSTP, SC }; + +struct CommandLineOptions { + DataLink dataLink = DataLink::IPv4; + uint32_t deviceInstance = 389005; + + // BACnet/IP and BACnet/IPv6 + uint16_t udpPort = 47808; + // BACnet/IPv6: the interface index to join the multicast group on and take + // the address from (0 = every interface that is up / the first one). + uint32_t ipv6InterfaceIndex = 0; + + // MS/TP + std::string mstpPortName; // COM3, /dev/ttyUSB0 (required for --datalink mstp) + uint32_t mstpBaudRate = 38400; + uint8_t mstpMacAddress = 1; + uint8_t mstpMaxMaster = 127; + uint8_t mstpMaxInfoFrames = 1; + + // BACnet/SC + std::string scPrimaryHubUri; // wss://host:port (required for --datalink sc) + std::string scFailoverHubUri; // optional + std::string scCertificateDirectory = "./certs"; + std::string importCariZip; // --import-cari: install a CA's response and exit +}; + +enum class ParseResult { + Run, // options are good: run the device + ExitSuccess, // --help or --version was printed + ExitError // a bad option; the reason was printed +}; + +// Parses and checks argv. On ExitError the problem has been printed, with a +// pointer to --help. +ParseResult ParseCommandLine(int argc, char** argv, const char* appName, const char* appVersion, + CommandLineOptions* options); + +const char* DataLinkName(DataLink dataLink); + +#endif // BBC_EXAMPLE_COMMAND_LINE_H diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index b7dcff7..fb974c0 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -12,6 +12,27 @@ entry here, and must then be re-copied into **every** example in the series. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the folder adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +Added in the B-BC example (`BACnetProfileExample-B-BC-CPP`, branch `ipv6`) and +not yet copied to the rest of the series; `COMMON_VERSION` is not bumped yet. +Both files are new and nothing else in `common/` changed, so an example without +them is unaffected. + +### Added + +- **`SimpleUDP6`** - a BACnet/IPv6 (Annex U) UDP socket: binds `[::]:port`, + joins the multicast group FF02::BAC0 on every IPv6 interface that is up (or + one), `Send` / `SendMulticast` / `Receive` with 16-octet addresses, and + remembers which interface each link-local peer was heard on. +- **`SimpleSerial`** - a serial port for MS/TP: 8N1 at a given baud rate, a + `Read` that never blocks, and a `Write` that returns when the driver has sent + the frame (Windows `CreateFile` + `COMMTIMEOUTS` + `FlushFileBuffers`; POSIX + termios raw mode + `tcdrain`; 76800 baud where the platform defines + `B76800`). On POSIX a full driver buffer is waited on with `poll` (up to a + second) instead of spinning, and a real read error such as EIO (an adapter + unplugged) is printed once. + ## [3.5.0] - unreleased ### Added diff --git a/common/SimpleSerial.cpp b/common/SimpleSerial.cpp new file mode 100644 index 0000000..be95bd0 --- /dev/null +++ b/common/SimpleSerial.cpp @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// SimpleSerial.cpp +// ============================================================================= +// Cross-platform serial port wrapper - see SimpleSerial.h for the interface. +// ============================================================================= + +#include "SimpleSerial.h" + +#include +#include + +#if defined(_WIN32) +#include +#define SERIAL_INVALID_HANDLE ((intptr_t)INVALID_HANDLE_VALUE) +#else +#include +#include +#include +#include +#include +#define SERIAL_INVALID_HANDLE ((intptr_t)-1) +#endif + +SimpleSerial::SimpleSerial() : m_handle(SERIAL_INVALID_HANDLE), m_readErrorReported(false) { + m_lastError[0] = '\0'; +} + +SimpleSerial::~SimpleSerial() { + Close(); +} + +bool SimpleSerial::IsOpen() const { + return m_handle != SERIAL_INVALID_HANDLE; +} + +const char* SimpleSerial::GetLastErrorText() const { + return m_lastError; +} + +#if defined(_WIN32) + +bool SimpleSerial::Open(const char* portName, const uint32_t baudRate) { + Close(); + // "\\.\COM3": the device namespace. Plain "COM3" works for COM1..COM9 only. + char devicePath[64]; + snprintf(devicePath, sizeof(devicePath), "\\\\.\\%s", portName); + HANDLE portHandle = CreateFileA(devicePath, GENERIC_READ | GENERIC_WRITE, 0 /*no sharing*/, NULL, + OPEN_EXISTING, 0 /*synchronous I/O*/, NULL); + if (portHandle == INVALID_HANDLE_VALUE) { + snprintf(m_lastError, sizeof(m_lastError), "cannot open %s (Windows error %lu%s)", portName, + (unsigned long)GetLastError(), + GetLastError() == ERROR_ACCESS_DENIED ? ": in use by another program?" : + GetLastError() == ERROR_FILE_NOT_FOUND ? ": no such port" : ""); + return false; + } + + DCB settings; + memset(&settings, 0, sizeof(settings)); + settings.DCBlength = sizeof(settings); + if (!GetCommState(portHandle, &settings)) { + snprintf(m_lastError, sizeof(m_lastError), "GetCommState failed on %s (error %lu)", portName, + (unsigned long)GetLastError()); + CloseHandle(portHandle); + return false; + } + settings.BaudRate = baudRate; + settings.ByteSize = 8; + settings.Parity = NOPARITY; + settings.StopBits = ONESTOPBIT; + settings.fBinary = TRUE; + settings.fParity = FALSE; + // No flow control of any kind: MS/TP has none, and an RS-485 adapter that + // switches its driver itself must not see RTS/DTR toggled by the driver. + settings.fOutxCtsFlow = FALSE; + settings.fOutxDsrFlow = FALSE; + settings.fDtrControl = DTR_CONTROL_DISABLE; + settings.fRtsControl = RTS_CONTROL_DISABLE; + settings.fDsrSensitivity = FALSE; + settings.fOutX = FALSE; + settings.fInX = FALSE; + settings.fErrorChar = FALSE; + settings.fNull = FALSE; + settings.fAbortOnError = FALSE; // a framing error must not stall every later read + if (!SetCommState(portHandle, &settings)) { + snprintf(m_lastError, sizeof(m_lastError), "SetCommState failed on %s at %u baud (error %lu)", portName, + (unsigned)baudRate, (unsigned long)GetLastError()); + CloseHandle(portHandle); + return false; + } + + // ReadIntervalTimeout = MAXDWORD with both read multipliers 0: ReadFile + // returns immediately with whatever is already buffered, even nothing. That + // is what the MS/TP receive callback needs - it must never block. + COMMTIMEOUTS timeouts; + memset(&timeouts, 0, sizeof(timeouts)); + timeouts.ReadIntervalTimeout = MAXDWORD; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 0; + timeouts.WriteTotalTimeoutMultiplier = 0; + timeouts.WriteTotalTimeoutConstant = 1000; // a frame at 9600 baud is well under a second + SetCommTimeouts(portHandle, &timeouts); + // A deep receive buffer: the engine is only called every millisecond or so. + SetupComm(portHandle, 4096, 4096); + PurgeComm(portHandle, PURGE_RXCLEAR | PURGE_TXCLEAR); + + m_handle = (intptr_t)portHandle; + return true; +} + +void SimpleSerial::Close() { + if (m_handle != SERIAL_INVALID_HANDLE) { + CloseHandle((HANDLE)m_handle); + m_handle = SERIAL_INVALID_HANDLE; + } +} + +size_t SimpleSerial::Read(uint8_t* buffer, const size_t maxLength) { + if (m_handle == SERIAL_INVALID_HANDLE || maxLength == 0) { + return 0; + } + DWORD bytesRead = 0; + if (!ReadFile((HANDLE)m_handle, buffer, (DWORD)maxLength, &bytesRead, NULL)) { + // A line error (framing, overrun) - clear it so reading continues. + DWORD lineErrors = 0; + ClearCommError((HANDLE)m_handle, &lineErrors, NULL); + return 0; + } + return (size_t)bytesRead; +} + +bool SimpleSerial::Write(const uint8_t* data, const size_t length) { + if (m_handle == SERIAL_INVALID_HANDLE) { + return false; + } + DWORD bytesWritten = 0; + if (!WriteFile((HANDLE)m_handle, data, (DWORD)length, &bytesWritten, NULL) || bytesWritten != length) { + return false; + } + // Wait until the driver has transmitted everything: the stack switches the + // node back to receiving the moment this returns (see SimpleSerial.h). + FlushFileBuffers((HANDLE)m_handle); + return true; +} + +#else // POSIX + +static speed_t BaudRateConstant(const uint32_t baudRate) { + switch (baudRate) { + case 9600: return B9600; + case 19200: return B19200; + case 38400: return B38400; + case 57600: return B57600; +#ifdef B76800 + case 76800: return B76800; +#endif + case 115200: return B115200; + default: return 0; + } +} + +bool SimpleSerial::Open(const char* portName, const uint32_t baudRate) { + Close(); + const speed_t speed = BaudRateConstant(baudRate); + if (speed == 0) { + snprintf(m_lastError, sizeof(m_lastError), + "%u baud has no termios constant on this system (76800 is missing on Linux - see TODO.md)", + (unsigned)baudRate); + return false; + } + const int fileDescriptor = open(portName, O_RDWR | O_NOCTTY | O_NONBLOCK); + if (fileDescriptor < 0) { + snprintf(m_lastError, sizeof(m_lastError), "cannot open %s: %s", portName, strerror(errno)); + return false; + } + struct termios settings; + if (tcgetattr(fileDescriptor, &settings) != 0) { + snprintf(m_lastError, sizeof(m_lastError), "tcgetattr failed on %s: %s", portName, strerror(errno)); + close(fileDescriptor); + return false; + } + cfmakeraw(&settings); // no echo, no line editing, no character translation + settings.c_cflag &= ~(CSIZE | PARENB | CSTOPB | CRTSCTS); + settings.c_cflag |= CS8 | CLOCAL | CREAD; // 8N1, ignore modem lines + settings.c_cc[VMIN] = 0; // read() returns at once with what is there + settings.c_cc[VTIME] = 0; + cfsetispeed(&settings, speed); + cfsetospeed(&settings, speed); + if (tcsetattr(fileDescriptor, TCSANOW, &settings) != 0) { + snprintf(m_lastError, sizeof(m_lastError), "tcsetattr failed on %s: %s", portName, strerror(errno)); + close(fileDescriptor); + return false; + } + tcflush(fileDescriptor, TCIOFLUSH); + m_handle = (intptr_t)fileDescriptor; + m_readErrorReported = false; + return true; +} + +void SimpleSerial::Close() { + if (m_handle != SERIAL_INVALID_HANDLE) { + close((int)m_handle); + m_handle = SERIAL_INVALID_HANDLE; + } +} + +size_t SimpleSerial::Read(uint8_t* buffer, const size_t maxLength) { + if (m_handle == SERIAL_INVALID_HANDLE || maxLength == 0) { + return 0; + } + const ssize_t bytesRead = read((int)m_handle, buffer, maxLength); + if (bytesRead < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR && !m_readErrorReported) { + // A real error, such as EIO when a USB adapter is unplugged. Say so once; + // it is still returned as "nothing received". + printf("Error: serial port read failed: %s (adapter unplugged?)\n", strerror(errno)); + m_readErrorReported = true; + } + return bytesRead > 0 ? (size_t)bytesRead : 0; // EAGAIN (nothing waiting) is 0 too +} + +bool SimpleSerial::Write(const uint8_t* data, const size_t length) { + if (m_handle == SERIAL_INVALID_HANDLE) { + return false; + } + size_t written = 0; + while (written < length) { + const ssize_t result = write((int)m_handle, data + written, length - written); + if (result > 0) { + written += (size_t)result; + } else if (result < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + // The driver's buffer is full: wait until it can take more, rather + // than spinning. A second with no room is a stuck port. + struct pollfd writable; + writable.fd = (int)m_handle; + writable.events = POLLOUT; + writable.revents = 0; + if (poll(&writable, 1, 1000) == 0) { + return false; + } + } else if (result < 0 && errno != EINTR) { + return false; + } + } + // Wait until the last octet has been transmitted (see SimpleSerial.h). + tcdrain((int)m_handle); + return true; +} + +#endif diff --git a/common/SimpleSerial.h b/common/SimpleSerial.h new file mode 100644 index 0000000..6e6b034 --- /dev/null +++ b/common/SimpleSerial.h @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef SIMPLE_SERIAL_H +#define SIMPLE_SERIAL_H + +// SimpleSerial.h +// ============================================================================= +// A minimal, cross-platform serial port wrapper for MS/TP (ANSI/ASHRAE 135-2024 +// clause 9): open a port at a baud rate, 8 data bits, no parity, 1 stop bit +// (MS/TP's only framing, cl. 9.2.1), read whatever octets are waiting without +// ever blocking, and write a frame and wait until it has left the wire. +// +// Windows CreateFile("\\\\.\\COM3") + SetCommState + COMMTIMEOUTS that make +// ReadFile return at once with what is buffered; Write() ends with +// FlushFileBuffers, which returns when the driver has sent every octet. +// POSIX open("/dev/ttyUSB0", O_NONBLOCK) + termios raw mode; Write() ends +// with tcdrain(), which returns when the last octet has been sent. +// +// The RS-485 driver (transmit enable) is NOT switched here: USB-to-RS-485 +// adapters switch it themselves, in hardware, from the UART's transmit line. +// An adapter that needs RTS to drive it needs a few more lines - see the MS/TP +// notes in the example's README. +// +// "Has left the wire" is as good as the driver's report. A USB serial adapter +// reports the end of a write when the USB transfer completes, which can be a +// little before the adapter's own UART has shifted out the last stop bit - see +// the MS/TP notes in the example's README and TODO.md. +// +// This is plain, unrestricted example code - copy it into your own project. +// ============================================================================= + +#include +#include + +class SimpleSerial { +public: + SimpleSerial(); + ~SimpleSerial(); + + // Opens `portName` ("COM3" on Windows - COM10 and up work too - or a device + // path such as "/dev/ttyUSB0" elsewhere) at `baudRate`, 8N1, no flow control. + // Returns false (with a reason in GetLastErrorText()) if it cannot. + bool Open(const char* portName, const uint32_t baudRate); + + void Close(); + bool IsOpen() const; + + // Copies up to maxLength octets that have already been received into buffer + // and returns how many (0 when nothing is waiting). Never blocks. + size_t Read(uint8_t* buffer, const size_t maxLength); + + // Writes `length` octets and returns only once they have been sent (see the + // note above). Returns false if the write failed. + bool Write(const uint8_t* data, const size_t length); + + // Why the last Open() failed, for the log. + const char* GetLastErrorText() const; + +private: + intptr_t m_handle; + bool m_readErrorReported; // POSIX: a read error has been printed once already + char m_lastError[160]; +}; + +#endif // SIMPLE_SERIAL_H diff --git a/common/SimpleUDP6.cpp b/common/SimpleUDP6.cpp new file mode 100644 index 0000000..64701af --- /dev/null +++ b/common/SimpleUDP6.cpp @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// SimpleUDP6.cpp +// ============================================================================= +// Cross-platform IPv6 UDP socket wrapper - see SimpleUDP6.h for the interface. +// ============================================================================= + +#include "SimpleUDP6.h" + +#include +#include + +#if defined(_WIN32) +#include +#include +#include +// ws2_32 and iphlpapi are linked by CMakeLists.txt. If you copy this file into a non-CMake MSVC project, add: +// #pragma comment(lib, "ws2_32.lib") and #pragma comment(lib, "iphlpapi.lib") +typedef int socklen_t; +#define INVALID_SOCK INVALID_SOCKET +#else +#include +#include +#include +#include +#include +#include +#include +#include +#define INVALID_SOCK (-1) +#endif + +namespace { +// The BACnet/IPv6 link-local multicast group FF02::BAC0 (Annex U.4). +const uint8_t DEFAULT_GROUP[16] = { 0xFF, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xBA, 0xC0 }; + +bool IsLinkLocal(const uint8_t* address) { + return address[0] == 0xFE && (address[1] & 0xC0) == 0x80; +} + +// The index of every IPv6 interface that is up and can multicast, loopback excluded. Returns how many were stored. +size_t ListMulticastInterfaces(uint32_t* indexes, const size_t maximum) { + size_t count = 0; +#if defined(_WIN32) + ULONG size = 0; + GetAdaptersAddresses(AF_INET6, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, NULL, NULL, &size); + if (size == 0) { + return 0; + } + IP_ADAPTER_ADDRESSES* adapters = (IP_ADAPTER_ADDRESSES*)malloc(size); + if (adapters == NULL) { + return 0; + } + if (GetAdaptersAddresses(AF_INET6, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, NULL, adapters, &size) == NO_ERROR) { + for (IP_ADAPTER_ADDRESSES* adapter = adapters; adapter != NULL && count < maximum; adapter = adapter->Next) { + if (adapter->OperStatus == IfOperStatusUp && adapter->IfType != IF_TYPE_SOFTWARE_LOOPBACK && adapter->Ipv6IfIndex != 0 && + !(adapter->Flags & IP_ADAPTER_NO_MULTICAST)) { + indexes[count++] = adapter->Ipv6IfIndex; + } + } + } + free(adapters); +#else + struct ifaddrs* addresses = NULL; + if (getifaddrs(&addresses) != 0) { + return 0; + } + for (struct ifaddrs* entry = addresses; entry != NULL && count < maximum; entry = entry->ifa_next) { + if (entry->ifa_addr == NULL || entry->ifa_addr->sa_family != AF_INET6 || !(entry->ifa_flags & IFF_UP) || + (entry->ifa_flags & IFF_LOOPBACK) || !(entry->ifa_flags & IFF_MULTICAST)) { + continue; + } + const uint32_t index = if_nametoindex(entry->ifa_name); + bool known = false; + for (size_t seen = 0; seen < count; seen++) { + known = known || indexes[seen] == index; + } + if (index != 0 && !known) { + indexes[count++] = index; + } + } + freeifaddrs(addresses); +#endif + return count; +} + +// One-time Winsock startup/teardown. No-op on POSIX. +struct PlatformInit { + PlatformInit() { +#if defined(_WIN32) + WSADATA wsaData; + WSAStartup(MAKEWORD(2, 2), &wsaData); +#endif + } + ~PlatformInit() { +#if defined(_WIN32) + WSACleanup(); +#endif + } +}; +PlatformInit g_platformInit; +} // namespace + +SimpleUDP6::SimpleUDP6() : m_socket(INVALID_SOCK), m_connected(false), m_localPort(0), m_interfaceCount(0), m_nextSender(0) { + memcpy(m_group, DEFAULT_GROUP, sizeof(m_group)); + memset(m_interfaces, 0, sizeof(m_interfaces)); + memset(m_senders, 0, sizeof(m_senders)); +} + +SimpleUDP6::~SimpleUDP6() { + Disconnect(); +} + +bool SimpleUDP6::Connect(const uint16_t localPort, const uint32_t interfaceIndex, const uint8_t* multicastGroup) { + m_socket = (intptr_t)socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); + if (m_socket == (intptr_t)INVALID_SOCK) { + return false; + } + memcpy(m_group, multicastGroup != NULL ? multicastGroup : DEFAULT_GROUP, sizeof(m_group)); + + // IPv6 only: BACnet/IPv4 is a different data link with its own socket, and a dual-stack socket would hand this one IPv4 datagrams. + const int ipv6Only = 1; + setsockopt((int)m_socket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6Only, sizeof(ipv6Only)); + + // Port-sharing policy: as SimpleUDP.cpp explains. Windows: exclusive, so a stale instance cannot steal the traffic. + // POSIX: SO_REUSEADDR, for a quick rebind after a restart. +#if defined(_WIN32) + const int exclusive = 1; + setsockopt((int)m_socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&exclusive, sizeof(exclusive)); +#else + const int reuse = 1; + setsockopt((int)m_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)); +#endif + + // A short receive timeout so Receive() does not block the tick loop (0 would mean "forever" for SO_RCVTIMEO). +#if defined(_WIN32) + const DWORD timeoutMilliseconds = 10; + setsockopt((int)m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeoutMilliseconds, sizeof(timeoutMilliseconds)); +#else + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 10 * 1000; + setsockopt((int)m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); +#endif + + struct sockaddr_in6 address; + memset(&address, 0, sizeof(address)); + address.sin6_family = AF_INET6; + address.sin6_addr = in6addr_any; + address.sin6_port = htons(localPort); + if (bind((int)m_socket, (struct sockaddr*)&address, sizeof(address)) != 0) { + Disconnect(); + return false; + } + m_localPort = localPort; + + // The multicast group, on the interface asked for or on every one that can: a BACnet broadcast is delivered by multicast + // (Annex U.4), so a node that has not joined hears no Who-Is. + uint32_t candidates[MAX_INTERFACES]; + size_t candidateCount = 0; + if (interfaceIndex != 0) { + candidates[candidateCount++] = interfaceIndex; + } else { + candidateCount = ListMulticastInterfaces(candidates, MAX_INTERFACES); + } + m_interfaceCount = 0; + for (size_t candidateIndex = 0; candidateIndex < candidateCount; candidateIndex++) { + struct ipv6_mreq request; + memcpy(&request.ipv6mr_multiaddr, m_group, sizeof(m_group)); + request.ipv6mr_interface = candidates[candidateIndex]; + if (setsockopt((int)m_socket, IPPROTO_IPV6, IPV6_JOIN_GROUP, (const char*)&request, sizeof(request)) == 0) { + m_interfaces[m_interfaceCount++] = candidates[candidateIndex]; + } + } + m_connected = true; + return true; +} + +void SimpleUDP6::Disconnect() { + if (m_socket != (intptr_t)INVALID_SOCK) { +#if defined(_WIN32) + closesocket((SOCKET)m_socket); +#else + close((int)m_socket); +#endif + m_socket = (intptr_t)INVALID_SOCK; + } + m_connected = false; + m_interfaceCount = 0; +} + +void SimpleUDP6::RememberSender(const uint8_t* address, const uint32_t interfaceIndex) { + if (interfaceIndex == 0 || !IsLinkLocal(address)) { + return; // only a link-local address needs its interface kept + } + for (size_t index = 0; index < MAX_REMEMBERED_SENDERS; index++) { + if (m_senders[index].inUse && memcmp(m_senders[index].address, address, 16) == 0) { + m_senders[index].interfaceIndex = interfaceIndex; + return; + } + } + RememberedSender& slot = m_senders[m_nextSender]; + m_nextSender = (m_nextSender + 1) % MAX_REMEMBERED_SENDERS; + slot.inUse = true; + memcpy(slot.address, address, 16); + slot.interfaceIndex = interfaceIndex; +} + +uint32_t SimpleUDP6::InterfaceOf(const uint8_t* address) const { + for (size_t index = 0; index < MAX_REMEMBERED_SENDERS; index++) { + if (m_senders[index].inUse && memcmp(m_senders[index].address, address, 16) == 0) { + return m_senders[index].interfaceIndex; + } + } + // Never heard from: the first interface the group was joined on - the default for a one-interface host. + return m_interfaceCount > 0 ? m_interfaces[0] : 0; +} + +uint16_t SimpleUDP6::Send(const uint8_t* ipAddress, const uint16_t port, const uint8_t* data, const uint16_t length) { + if (!m_connected || ipAddress == NULL || data == NULL) { + return 0; + } + struct sockaddr_in6 destination; + memset(&destination, 0, sizeof(destination)); + destination.sin6_family = AF_INET6; + memcpy(&destination.sin6_addr, ipAddress, 16); + destination.sin6_port = htons(port); + if (IsLinkLocal(ipAddress)) { + destination.sin6_scope_id = InterfaceOf(ipAddress); + } + const int sent = (int)sendto((int)m_socket, (const char*)data, length, 0, (struct sockaddr*)&destination, sizeof(destination)); + return sent > 0 ? (uint16_t)sent : 0; +} + +uint16_t SimpleUDP6::SendMulticast(const uint8_t* data, const uint16_t length) { + if (!m_connected || data == NULL) { + return 0; + } + uint16_t firstSent = 0; + // One datagram per interface the group is joined on: the multicast interface decides where a multicast leaves. + const size_t sendCount = m_interfaceCount > 0 ? m_interfaceCount : 1; + for (size_t interfaceIndex = 0; interfaceIndex < sendCount; interfaceIndex++) { + const uint32_t multicastInterface = m_interfaceCount > 0 ? m_interfaces[interfaceIndex] : 0; + setsockopt((int)m_socket, IPPROTO_IPV6, IPV6_MULTICAST_IF, (const char*)&multicastInterface, sizeof(multicastInterface)); + struct sockaddr_in6 destination; + memset(&destination, 0, sizeof(destination)); + destination.sin6_family = AF_INET6; + memcpy(&destination.sin6_addr, m_group, 16); + destination.sin6_port = htons(m_localPort); + destination.sin6_scope_id = multicastInterface; + const int sent = (int)sendto((int)m_socket, (const char*)data, length, 0, (struct sockaddr*)&destination, sizeof(destination)); + if (sent > 0 && firstSent == 0) { + firstSent = (uint16_t)sent; + } + } + return firstSent; +} + +uint16_t SimpleUDP6::Receive(uint8_t* buffer, const uint16_t maxLength, uint8_t* fromIpAddress, uint16_t* fromPort) { + if (!m_connected || buffer == NULL) { + return 0; + } + struct sockaddr_in6 from; + socklen_t fromLength = sizeof(from); + const int received = (int)recvfrom((int)m_socket, (char*)buffer, maxLength, 0, (struct sockaddr*)&from, &fromLength); + if (received <= 0) { + return 0; + } + if (fromIpAddress != NULL) { + memcpy(fromIpAddress, &from.sin6_addr, 16); + RememberSender(fromIpAddress, from.sin6_scope_id); + } + if (fromPort != NULL) { + *fromPort = ntohs(from.sin6_port); + } + return (uint16_t)received; +} + +uint32_t SimpleUDP6::GetJoinedInterfaceCount() const { + return (uint32_t)m_interfaceCount; +} + +uint16_t SimpleUDP6::GetLocalPort() const { + return m_localPort; +} diff --git a/common/SimpleUDP6.h b/common/SimpleUDP6.h new file mode 100644 index 0000000..e024226 --- /dev/null +++ b/common/SimpleUDP6.h @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef SIMPLE_UDP6_H +#define SIMPLE_UDP6_H + +// SimpleUDP6.h +// ============================================================================= +// A minimal, cross-platform IPv6 UDP socket wrapper for BACnet/IPv6 (ANSI/ASHRAE +// 135-2024 Annex U). Like SimpleUDP it does just enough: bind a port, send a +// datagram to a B/IPv6 address, receive one (waiting a few ms at most) - and what +// IPv6 adds: it joins the BACnet/IPv6 multicast group on the host's interfaces, +// and sends a BACnet broadcast to that group. +// +// A B/IPv6 address is 18 octets: the 16-octet IPv6 address, then the 2-octet UDP +// port, each most significant octet first (Annex U.1.1.2). That is also the stack's +// connection string for a BACnet/IPv6 peer. +// +// Link-local peers: a link-local IPv6 address (fe80::/10) means nothing without +// the interface it is on, and the 18 octets do not say. Receive() remembers the +// interface each sender was heard on, and Send() uses it for a link-local +// destination; one never heard from is sent on the default interface. +// +// This is plain, unrestricted example code - copy it into your own project. +// ============================================================================= + +#include +#include + +class SimpleUDP6 { +public: + static const uint8_t ADDRESS_LENGTH = 16; + + SimpleUDP6(); + ~SimpleUDP6(); + + // Binds [::]:localPort (IPv6 only: a BACnet/IPv4 socket is a separate one) and joins the BACnet/IPv6 multicast group + // `multicastGroup` (16 octets, FF02::BAC0 by default) on every IPv6 interface that is up, or only on `interfaceIndex` + // when it is not 0. Returns true when the socket is bound; the group is joined on at least one interface + // (GetJoinedInterfaceCount() says how many). + bool Connect(const uint16_t localPort, const uint32_t interfaceIndex = 0, const uint8_t* multicastGroup = NULL); + + void Disconnect(); + + // Sends `length` bytes to the IPv6 address ipAddress[16] : port. Returns the number of bytes sent, or 0. + uint16_t Send(const uint8_t* ipAddress, const uint16_t port, const uint8_t* data, const uint16_t length); + + // Sends `length` bytes to the multicast group on the port this socket is bound to - a BACnet broadcast - out of every + // interface the group was joined on (or the one chosen in Connect). Returns the bytes sent on the first interface that + // took it, or 0. + uint16_t SendMulticast(const uint8_t* data, const uint16_t length); + + // Receives one datagram into buffer (up to maxLength). Waits at most ~10 ms. Returns the bytes received, 0 if none; fills + // fromIpAddress[16] and *fromPort with the sender. + uint16_t Receive(uint8_t* buffer, const uint16_t maxLength, uint8_t* fromIpAddress, uint16_t* fromPort); + + uint32_t GetJoinedInterfaceCount() const; + uint16_t GetLocalPort() const; + +private: + static const size_t MAX_INTERFACES = 16; + static const size_t MAX_REMEMBERED_SENDERS = 32; + + struct RememberedSender { + bool inUse; + uint8_t address[16]; + uint32_t interfaceIndex; + }; + + intptr_t m_socket; + bool m_connected; + uint16_t m_localPort; + uint8_t m_group[16]; + uint32_t m_interfaces[MAX_INTERFACES]; + size_t m_interfaceCount; + RememberedSender m_senders[MAX_REMEMBERED_SENDERS]; + size_t m_nextSender; + + void RememberSender(const uint8_t* address, const uint32_t interfaceIndex); + uint32_t InterfaceOf(const uint8_t* address) const; +}; + +#endif // SIMPLE_UDP6_H diff --git a/docs/PICS.md b/docs/PICS.md index 32bb347..7f40d4c 100644 --- a/docs/PICS.md +++ b/docs/PICS.md @@ -20,13 +20,13 @@ see [README.md](../README.md). | **Vendor Identifier** | 389 | | **Product Name** | CAS BACnet Stack Example - B-BC | | **Product Model Number** | CAS BACnet Stack Example - B-BC | -| **Application Software Version** | 1.2.0 | +| **Application Software Version** | 1.3.0 | | **Firmware Revision** | 6.0.23.0 (the CAS BACnet Stack version) | | **BACnet Protocol Version** | 1 | | **BACnet Protocol Revision** | 30 | -**Product Description:** a BACnet/IP Building Controller built on the CAS -BACnet Stack. It reads a humidity sensor in a peer device (ReadProperty and +**Product Description:** a Building Controller built on the CAS BACnet Stack, +on BACnet/IP, BACnet/IPv6, MS/TP or BACnet/SC (one at a time, chosen at start-up). It reads a humidity sensor in a peer device (ReadProperty and ReadPropertyMultiple), alarms on and trends that reading, and reports communication loss with the peer through Reliability. It presents fifteen objects spanning read-only sensors, @@ -101,7 +101,7 @@ life-safety BIBB. | AtomicWriteFile | no | **yes** | | ReadRange | no | **yes** (against `Log_Buffer` of either Trend Log) | -An unsolicited I-Am is broadcast to the local subnet at start-up and after a +An unsolicited I-Am is broadcast on the active data link at start-up and after a ReinitializeDevice restart, as well as in response to Who-Is. This device also initiates a Who-Is at start-up (DM-DDB-A), initiates WriteProperty when Schedule 1 ("Saffron") fires a transition, targeting both a local object and a @@ -119,7 +119,8 @@ Segmentation is **supported in both directions** properties are required if, and shall be present only if, segmentation of any kind is supported" - they are not rows in section 11 because its generator lists only unconditionally required properties. `Max_APDU_Length_Accepted` is -1476 octets, the BACnet/IP maximum. (At the previous pin, `00aa2d0e`, this +1476 octets, the BACnet/IP maximum - and 480 with `--datalink mstp`, the MS/TP +maximum. (At the previous pin, `00aa2d0e`, this example answered `no-segmentation`.) ## 6. Standard object types supported @@ -137,10 +138,11 @@ No object is dynamically creatable or deletable. | Multi-state Output | 1 | Indigo | - (commandable: writable Present_Value) | | Analog Value | 1 | Diamond | Reliability; intrinsic OutOfRange alarming (Present_Value is read-only: it is the peer's reading) | | Notification Class | 1 | Crimson | writable Recipient_List (AE-CRL-B) | -| Network Port | 1 | Vermilion | - | +| Network Port | 1, 2, 3 or 4 | Vermilion, Cerulean, Amber or Teal | One, the active data link's (section 7). MS/TP: writable Max_Master, Max_Info_Frames. BACnet/SC: Current_Health, SC_Primary/Failover_Hub_Connection_Status | | Schedule | 1 | Saffron | - | | Calendar | 1 | Cream | Stack-held Date_List (December 25), writable; drives Schedule 1's calendar-reference exception | | File | 1 | Ivory | writable Archive | +| File | 2, 3, 4, 5 | Operational Certificate, Issuer Certificate 1, Issuer Certificate 2, Certificate Signing Request | `--datalink sc` only: the BACnet/SC certificate files (2-4 written with AtomicWriteFile) | | Trend Log | 1 | Lilac | Enable, Record_Count (0 clears the buffer) and Log_Interval are writable; the other logging properties are fixed | | Trend Log Multiple | 1 | Magenta | - | @@ -152,11 +154,32 @@ defaults. ## 7. Data link layer options -**BACnet/IP (Annex J)**, UDP port 47808 (0xBAC0) by default, configurable at run -time with `--port`. - -BBMD is not supported, Foreign Device registration is not supported, and -BACnet/SC, MS/TP, Ethernet (Annex H) and PTP are not supported. +One data link at a time, chosen at start-up with `--datalink`; each has its own +Network Port object instance, and the device has only the active one's: + +| `--datalink` | Data link | Network Port | Options | +|---|---|---|---| +| `ipv4` (default) | **BACnet/IP (Annex J)** | 1 "Vermilion" | UDP port 47808 (0xBAC0) by default, `--port` | +| `ipv6` | **BACnet/IPv6 (Annex U)** | 2 "Cerulean" | UDP port 47808 by default, `--port`; multicast group FF02::BAC0; `--interface` | +| `mstp` | **MS/TP (Clause 9), master node** | 3 "Amber" | 9600, 19200, 38400, 57600, 76800 or 115200 baud; MAC 0..127 | +| `sc` | **BACnet/SC (Annex AB), node** | 4 "Teal" | primary and failover hub; needs a build with libwebsockets | + +This example configures no BBMD and no Foreign Device registration, on +BACnet/IP or on BACnet/IPv6. On BACnet/IPv6 the pinned stack makes the +BBMD and foreign-device properties of Network Port 2 writable +(BACnet_IPv6_Mode, FD_BBMD_Address, FD_Subscription_Lifetime, +BBMD_Broadcast_Distribution_Table and BBMD_Accept_FD_Registrations), so a +client CAN configure them and activate them. Do not rely on that with this +example: as a BBMD it would forward its own link's broadcasts +to its peers, but not its peers' broadcasts to its own link, because it does +not pass each datagram's destination address to the stack (the stack needs it +to tell a forwarded broadcast from a unicast; see `ipv6/README.md`). Ethernet +(Annex H) and PTP are not supported. On BACnet/SC the device is a node only: +it neither is a hub nor accepts direct connections. + +On MS/TP, Network Port 3's Max_Master and Max_Info_Frames are writable; a +written value is pending (Changes_Pending TRUE) until ReinitializeDevice +ACTIVATE_CHANGES or WARMSTART. The stack's Network Port object still lists its BACnet/IP properties in `Property_List` - including `IP_DNS_Server`, `FD_BBMD_Address` and @@ -178,8 +201,9 @@ that peer's I-Am, which the example observes with `BACnetStack_RegisterHookIAm` ## 9. Networking options -None. The device is not a router, not a BBMD, and does not register as a -foreign device. +None. The device is not a router, is not configured as a BBMD, and does not +register as a foreign device (on BACnet/IPv6 a client could configure either +through Network Port 2 - see section 7 for why a BBMD would be incomplete). ## 10. Character sets supported @@ -339,7 +363,7 @@ Every object this example creates, and every REQUIRED property of each (per ANSI | Recipient_List | BACnetLIST of BACnetDestination | stack default, accepted (None known - a read fails with `unknown-property` or an empt) | yes | | Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | -### Network Port 1 "Vermilion" - BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal). Link_Speed is read once at start-up from the host's primary network interface (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond) - 0.0 if the host OS can't report one, which is the spec-correct 'indeterminable' answer, not a bug +### Network Port 1 "Vermilion" - --datalink ipv4 (the default) only: the device has one Network Port, the active data link's (README 'Data links'). BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal). Link_Speed is read once at start-up from the host's primary network interface (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond) - 0.0 if the host OS can't report one, which is the spec-correct 'indeterminable' answer, not a bug | Property | Datatype | Served by | Writable | |---|---|---|:---:| @@ -354,6 +378,58 @@ Every object this example creates, and every REQUIRED property of each (per ANSI | Changes_Pending | Boolean | app | no | | Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | +### Network Port 2 "Cerulean" - --datalink ipv6 only. BACnet/IPv6 (Network_Type ipv6, 9). IPv6_Address, IPv6_Prefix_Length and IPv6_Default_Gateway are the host interface's (ipv6/LocalIPv6Address.cpp: a global address when the interface has one, else its link-local one), read once at start-up; BACnet_IPv6_UDP_Port is --port. IPv6_DNS_Server is the host's first IPv6 DNS server, one element (the interface's on Windows, /etc/resolv.conf's on POSIX); with none the app declines it and the stack reports one unconfigured entry. The stack serves MAC_Address (the 3-octet VMAC, the device instance) and the multicast address. Link_Speed (optional on this port, so enabled at start-up) is that interface's speed on Windows, else as for Network Port 1. The stack also holds BACnet_IPv6_Mode, FD_BBMD_Address, FD_Subscription_Lifetime, BBMD_Broadcast_Distribution_Table and BBMD_Accept_FD_Registrations, writable by a client; this example configures none of them, and as a BBMD it would not pass its peers' broadcasts on (no destination address is given to the stack - see ipv6/README.md). Checked with tests/ipv6_probe.py + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| Status_Flags | BACnetStatusFlags | stack | no | +| Reliability | BACnetReliability | stack default, accepted (Generic Enumerated default: `0`) | no | +| Out_Of_Service | Boolean | app | no | +| Network_Type | BACnetNetworkType | stack | no | +| Protocol_Level | BACnetProtocolLevel | stack | no | +| Changes_Pending | Boolean | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | +| Link_Speed *(optional, enabled)* | (not in the reference) | app | no | + +### Network Port 3 "Amber" - --datalink mstp only. MS/TP (Network_Type mstp, 2). MAC_Address is --mstp-mac (one octet), Link_Speed the baud rate (--mstp-baud; optional on this port, so enabled at start-up), Max_Master and Max_Info_Frames --mstp-max-master / --mstp-max-info-frames - and the stack's MS/TP engine reads its own settings from these same callbacks. Max_Master and Max_Info_Frames are writable as pending changes (Changes_Pending TRUE) that take effect on ReinitializeDevice ACTIVATE_CHANGES. APDU_Length is the stack's 480; the Device's Max_APDU_Length_Accepted reads 480 in this mode + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| Status_Flags | BACnetStatusFlags | stack | no | +| Reliability | BACnetReliability | stack default, accepted (Generic Enumerated default: `0`) | no | +| Out_Of_Service | Boolean | app | no | +| Network_Type | BACnetNetworkType | stack | no | +| Protocol_Level | BACnetProtocolLevel | stack | no | +| Changes_Pending | Boolean | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | +| Link_Speed *(optional, enabled)* | (not in the reference) | app | no | +| Max_Master | (not in the reference) | app | yes | +| Max_Info_Frames | (not in the reference) | app | yes | + +### Network Port 4 "Teal" - --datalink sc only, and only in a build with BACnet/SC (README 'Building with BACnet/SC'). A BACnet/SC node (Network_Type secure-connect, 11) - sc/ScNode.cpp. The stack holds every BACnet/SC property: the hub URIs (--sc-hub, --sc-failover-hub), the 6-octet VMAC, the hub connection status, and the certificate File references (Files 2-5). SC_Primary_Hub_Connection_Status reads connected once the hub has accepted the device + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| Status_Flags | BACnetStatusFlags | stack | no | +| Reliability | BACnetReliability | stack default, accepted (Generic Enumerated default: `0`) | no | +| Out_Of_Service | Boolean | app | no | +| Network_Type | BACnetNetworkType | stack | no | +| Protocol_Level | BACnetProtocolLevel | stack | no | +| Changes_Pending | Boolean | stack | no | +| Current_Health *(optional, enabled)* | BACnetHealth | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | +| SC_Primary_Hub_Connection_Status *(optional, enabled)* | (not in the reference) | stack | no | +| SC_Failover_Hub_Connection_Status *(optional, enabled)* | (not in the reference) | stack | no | + ### Schedule 1 "Saffron" - SCHED-E-B. Present_Value, Effective_Period, Schedule_Default, List_Of_Object_Property_References, Priority_For_Writing and Status_Flags are NOT stack DEFAULTS - they are genuinely held and served by the stack's Schedule engine (BACnetStack_AddScheduleObject plus the BACnetStack_SetSchedule*/AddSchedule* configuration calls in main.cpp). List_Of_Object_Property_References has TWO entries (each BACnetStack_AddScheduleObjectPropertyReference call appends): a LOCAL one at Analog Output 1 (Chartreuse) Present_Value, and a REMOTE one at a peer device's (default instance 389002, e.g. a locally-built B-SA-CPP) Analog Output 1 Present_Value - the SCHED-E-B / F-EXTWRITE remote fan-out. Both writes are checked: the local one is inherited from B-AAC's SCHED-I-B, and the remote one is the Wire Test tests/sched_e_b_remote_peer.py. A write made before the peer is bound is kept until it binds (cas-bacnet-stack #2343, fixed at 64b2cfac5; checked by hand). One weekly transition (Monday 08:00) and one exception - a calendar reference to Calendar 1 (Cream), whose Date_List holds December 25 - are seeded at start-up; the 's' key (common/'s DemoAdvance) adds a transition for right now so the change can be observed without waiting for the wall clock | Property | Datatype | Served by | Writable | @@ -397,6 +473,66 @@ Every object this example creates, and every REQUIRED property of each (per ANSI | File_Access_Method | BACnetFileAccessMethod | stack | no | | Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | +### File 2 "Operational Certificate" - --datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| File_Type | CharacterString | app | no | +| File_Size | Unsigned | app | no | +| Modification_Date | BACnetDateTime | app | no | +| Archive | Boolean | app | no | +| Read_Only | Boolean | app | no | +| File_Access_Method | BACnetFileAccessMethod | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | + +### File 3 "Issuer Certificate 1" - --datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| File_Type | CharacterString | app | no | +| File_Size | Unsigned | app | no | +| Modification_Date | BACnetDateTime | app | no | +| Archive | Boolean | app | no | +| Read_Only | Boolean | app | no | +| File_Access_Method | BACnetFileAccessMethod | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | + +### File 4 "Issuer Certificate 2" - --datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| File_Type | CharacterString | app | no | +| File_Size | Unsigned | app | no | +| Modification_Date | BACnetDateTime | app | no | +| Archive | Boolean | app | no | +| Read_Only | Boolean | app | no | +| File_Access_Method | BACnetFileAccessMethod | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | + +### File 5 "Certificate Signing Request" - --datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Read-only: the device makes it (Network Port Command GENERATE_CSR_FILE) + +| Property | Datatype | Served by | Writable | +|---|---|---|:---:| +| Object_Identifier | BACnetObjectIdentifier | stack | no | +| Object_Name | CharacterString | app | no | +| Object_Type | BACnetObjectType | stack | no | +| File_Type | CharacterString | app | no | +| File_Size | Unsigned | app | no | +| Modification_Date | BACnetDateTime | app | no | +| Archive | Boolean | app | no | +| Read_Only | Boolean | app | no | +| File_Access_Method | BACnetFileAccessMethod | stack | no | +| Property_List | BACnetARRAY[N] of BACnetPropertyIdentifier | stack | no | + ### Trend Log 1 "Lilac" - T-VMT-I-B / T-ATR-B. T-ATR-B: Lilac reports BUFFER_READY intrinsically (BACnetStack_SetAlarmsAndEventsForObjectEnabled + SetIntrinsicBufferReadyAlgorithm, cl. 13.3.7) through Notification Class 1 (Crimson), notify type EVENT, every 30 new records (Notification_Threshold 30); the stack holds the event-reporting properties listed here and Event_State, which stays normal (BUFFER_READY notifies without a state change). Wire Test trend_retrieval_test.py. Enable, Stop_When_Full, Buffer_Size, Log_Buffer, Record_Count and Logging_Type are NOT stack defaults - they are genuinely held and served by the stack's Trend Log engine (BACnetStack_AddTrendLogObject + SetTrendLogTypeToPolled + SetTrendLogStartStopTime), marked accepted only because property-profile-reference.md's generic table does not know about this host-configuration API. Polls Analog Input 1 (Bronze) Present_Value every second. Log_Buffer is readable only via ReadRange (a plain ReadProperty is rejected with Error(OBJECT, READ_ACCESS_DENIED) - verified live). Record_Count climbs correctly (fixed cas-bacnet-stack#2051 - the Start_Time/Stop_Time window is now built from the same clock, UTC via gmtime, that the stack itself compares against, not local wall-clock) - live-verified: Record_Count climbed from 14 to 44 over 30 seconds. Total_Record_Count (145) is listed in Property_List and climbs with Record_Count (checked by hand at 64b2cfac5; the phase-1 'missing' note read property 322 by mistake - TODO.md). (The #2050 log flood is fixed.) | Property | Datatype | Served by | Writable | diff --git a/docs/objects.json b/docs/objects.json index e24f06e..86cd766 100644 --- a/docs/objects.json +++ b/docs/objects.json @@ -121,7 +121,40 @@ "enabled": [], "writable": [], "accepted": ["Reliability"], - "note": "BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal). Link_Speed is read once at start-up from the host's primary network interface (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond) - 0.0 if the host OS can't report one, which is the spec-correct 'indeterminable' answer, not a bug" + "note": "--datalink ipv4 (the default) only: the device has one Network Port, the active data link's (README 'Data links'). BACnet/IP; Network_Type and Protocol_Level are set from BACnetStack_AddNetworkPortObject()'s arguments (IPv4, BACnet Application) at start-up, not a GetProperty callback like the object's other app-served rows; Changes_Pending is likewise computed and answered natively by the stack's Network Port object. Reliability has no fault condition this example detects, so it is accepted at the generic default (normal). Link_Speed is read once at start-up from the host's primary network interface (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond) - 0.0 if the host OS can't report one, which is the spec-correct 'indeterminable' answer, not a bug" + }, + { + "type": "Network Port", + "instance": 2, + "name": "Cerulean", + "app": ["Object_Name", "Out_Of_Service", "Link_Speed", "IPv6_Address", "IPv6_Prefix_Length", "BACnet_IPv6_UDP_Port", "IPv6_Default_Gateway", "IPv6_DNS_Server"], + "stack": ["Network_Type", "Protocol_Level", "Changes_Pending", "MAC_Address", "APDU_Length", "BACnet_IPv6_Multicast_Address"], + "enabled": ["Link_Speed"], + "writable": [], + "accepted": ["Reliability"], + "note": "--datalink ipv6 only. BACnet/IPv6 (Network_Type ipv6, 9). IPv6_Address, IPv6_Prefix_Length and IPv6_Default_Gateway are the host interface's (ipv6/LocalIPv6Address.cpp: a global address when the interface has one, else its link-local one), read once at start-up; BACnet_IPv6_UDP_Port is --port. IPv6_DNS_Server is the host's first IPv6 DNS server, one element (the interface's on Windows, /etc/resolv.conf's on POSIX); with none the app declines it and the stack reports one unconfigured entry. The stack serves MAC_Address (the 3-octet VMAC, the device instance) and the multicast address. Link_Speed (optional on this port, so enabled at start-up) is that interface's speed on Windows, else as for Network Port 1. The stack also holds BACnet_IPv6_Mode, FD_BBMD_Address, FD_Subscription_Lifetime, BBMD_Broadcast_Distribution_Table and BBMD_Accept_FD_Registrations, writable by a client; this example configures none of them, and as a BBMD it would not pass its peers' broadcasts on (no destination address is given to the stack - see ipv6/README.md). Checked with tests/ipv6_probe.py" + }, + { + "type": "Network Port", + "instance": 3, + "name": "Amber", + "app": ["Object_Name", "Out_Of_Service", "Link_Speed", "MAC_Address", "Max_Master", "Max_Info_Frames"], + "stack": ["Network_Type", "Protocol_Level", "Changes_Pending", "APDU_Length"], + "enabled": ["Link_Speed"], + "writable": ["Max_Master", "Max_Info_Frames"], + "accepted": ["Reliability"], + "note": "--datalink mstp only. MS/TP (Network_Type mstp, 2). MAC_Address is --mstp-mac (one octet), Link_Speed the baud rate (--mstp-baud; optional on this port, so enabled at start-up), Max_Master and Max_Info_Frames --mstp-max-master / --mstp-max-info-frames - and the stack's MS/TP engine reads its own settings from these same callbacks. Max_Master and Max_Info_Frames are writable as pending changes (Changes_Pending TRUE) that take effect on ReinitializeDevice ACTIVATE_CHANGES. APDU_Length is the stack's 480; the Device's Max_APDU_Length_Accepted reads 480 in this mode" + }, + { + "type": "Network Port", + "instance": 4, + "name": "Teal", + "app": ["Object_Name", "Out_Of_Service"], + "stack": ["Network_Type", "Protocol_Level", "Changes_Pending", "Current_Health", "MAC_Address", "APDU_Length", "SC_Primary_Hub_URI", "SC_Failover_Hub_URI", "SC_Primary_Hub_Connection_Status", "SC_Failover_Hub_Connection_Status", "Operational_Certificate_File", "Issuer_Certificate_Files", "Certificate_Signing_Request_File"], + "enabled": ["Current_Health", "SC_Primary_Hub_Connection_Status", "SC_Failover_Hub_Connection_Status"], + "writable": [], + "accepted": ["Reliability"], + "note": "--datalink sc only, and only in a build with BACnet/SC (README 'Building with BACnet/SC'). A BACnet/SC node (Network_Type secure-connect, 11) - sc/ScNode.cpp. The stack holds every BACnet/SC property: the hub URIs (--sc-hub, --sc-failover-hub), the 6-octet VMAC, the hub connection status, and the certificate File references (Files 2-5). SC_Primary_Hub_Connection_Status reads connected once the hub has accepted the device" }, { "type": "Schedule", @@ -154,6 +187,46 @@ "accepted": ["Event_State"], "note": "DM-BR-B. A small in-memory STREAM-access file that AtomicReadFile/AtomicWriteFile operate on, and the backup/restore payload for ReinitializeDevice's STARTBACKUP/ENDBACKUP/STARTRESTORE/ENDRESTORE/ABORTRESTORE states (2-6), all accepted by ReinitializeDevice alongside COLDSTART/WARMSTART. BACnetStack_SetBackupAndRestoreEnabled plus the four Prepare/Complete Backup/Restore callbacks are registered. Verified live: File_Size reads 0 (nothing written yet this session) and a WriteProperty of Archive=true reads back correctly" }, + { + "type": "File", + "instance": 2, + "name": "Operational Certificate", + "app": ["Object_Name", "File_Type", "File_Size", "Modification_Date", "Archive", "Read_Only"], + "enabled": [], + "writable": [], + "accepted": ["Event_State"], + "note": "--datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect" + }, + { + "type": "File", + "instance": 3, + "name": "Issuer Certificate 1", + "app": ["Object_Name", "File_Type", "File_Size", "Modification_Date", "Archive", "Read_Only"], + "enabled": [], + "writable": [], + "accepted": ["Event_State"], + "note": "--datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect" + }, + { + "type": "File", + "instance": 4, + "name": "Issuer Certificate 2", + "app": ["Object_Name", "File_Type", "File_Size", "Modification_Date", "Archive", "Read_Only"], + "enabled": [], + "writable": [], + "accepted": ["Event_State"], + "note": "--datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Written with AtomicWriteFile: a new certificate is staged, and ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place - or refuses it, changing nothing, if it would leave the device unable to connect" + }, + { + "type": "File", + "instance": 5, + "name": "Certificate Signing Request", + "app": ["Object_Name", "File_Type", "File_Size", "Modification_Date", "Archive", "Read_Only"], + "enabled": [], + "writable": [], + "accepted": ["Event_State"], + "note": "--datalink sc only: a BACnet/SC certificate file in --sc-cert-dir (PEM, File_Type application/x-pem-file; Modification_Date from the file on disk; Archive false). Read-only: the device makes it (Network Port Command GENERATE_CSR_FILE)" + }, { "type": "Trend Log", "instance": 1, diff --git a/ipv6/LocalIPv6Address.cpp b/ipv6/LocalIPv6Address.cpp new file mode 100644 index 0000000..6f16877 --- /dev/null +++ b/ipv6/LocalIPv6Address.cpp @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// LocalIPv6Address.cpp - see LocalIPv6Address.h. + +#include "LocalIPv6Address.h" + +#include +#include + +#if defined(_WIN32) +#include +#include +#include // GetAdaptersAddresses - iphlpapi is linked by CMakeLists.txt +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace { + +bool IsLinkLocal(const uint8_t address[16]) { + return address[0] == 0xFE && (address[1] & 0xC0) == 0x80; // fe80::/10 +} + +#if !defined(_WIN32) +bool IsZero(const uint8_t address[16]) { + for (int octetIndex = 0; octetIndex < 16; ++octetIndex) { + if (address[octetIndex] != 0) { + return false; + } + } + return true; +} +#endif + +} // namespace + +const char* FormatIPv6Address(const uint8_t address[16], char* text, const unsigned textSize) { + struct in6_addr binary; + memcpy(&binary, address, 16); + if (inet_ntop(AF_INET6, &binary, text, textSize) == NULL) { + snprintf(text, textSize, "?"); + } + return text; +} + +#if defined(_WIN32) + +bool GetLocalIPv6Address(const uint32_t interfaceIndex, LocalIPv6Address* out) { + memset(out, 0, sizeof(*out)); + ULONG bufferSize = 16 * 1024; + std::vector buffer; + ULONG result = ERROR_BUFFER_OVERFLOW; + for (int attempt = 0; attempt < 3 && result == ERROR_BUFFER_OVERFLOW; ++attempt) { + buffer.resize(bufferSize); + result = GetAdaptersAddresses(AF_INET6, GAA_FLAG_INCLUDE_GATEWAYS, NULL, + (IP_ADAPTER_ADDRESSES*)buffer.data(), &bufferSize); + } + if (result != NO_ERROR) { + return false; + } + for (IP_ADAPTER_ADDRESSES* adapter = (IP_ADAPTER_ADDRESSES*)buffer.data(); adapter != NULL; + adapter = adapter->Next) { + // An adapter that cannot do multicast cannot carry BACnet/IPv6 broadcasts. + if (adapter->OperStatus != IfOperStatusUp || adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK || + (adapter->Flags & IP_ADAPTER_NO_MULTICAST) != 0) { + continue; + } + if (interfaceIndex != 0 && adapter->Ipv6IfIndex != interfaceIndex) { + continue; + } + // NOTE: without --interface this is simply the first adapter that is up, + // which can be a Hyper-V or WSL virtual switch. Name the interface with + // --interface when the host has more than one. + // + // A global address if there is one, else the link-local one. Skipped: + // temporary (privacy) addresses, which the host replaces every few hours, + // and addresses that are not Preferred (deprecated, or still in + // duplicate address detection). + const IP_ADAPTER_UNICAST_ADDRESS* chosen = NULL; + for (const IP_ADAPTER_UNICAST_ADDRESS* unicast = adapter->FirstUnicastAddress; unicast != NULL; + unicast = unicast->Next) { + if (unicast->Address.lpSockaddr->sa_family != AF_INET6 || unicast->SuffixOrigin == IpSuffixOriginRandom || + unicast->DadState != IpDadStatePreferred) { + continue; + } + const uint8_t* candidate = ((const sockaddr_in6*)unicast->Address.lpSockaddr)->sin6_addr.s6_addr; + if (chosen == NULL || (!IsLinkLocal(candidate) && + IsLinkLocal(((const sockaddr_in6*)chosen->Address.lpSockaddr)->sin6_addr.s6_addr))) { + chosen = unicast; + } + } + if (chosen == NULL) { + continue; + } + memcpy(out->address, ((const sockaddr_in6*)chosen->Address.lpSockaddr)->sin6_addr.s6_addr, 16); + out->prefixLength = chosen->OnLinkPrefixLength; + out->interfaceIndex = adapter->Ipv6IfIndex; + // The interface's transmit speed, for Link_Speed. All ones means unknown. + if (adapter->TransmitLinkSpeed != 0 && adapter->TransmitLinkSpeed != (ULONG64)-1) { + out->linkSpeedBitsPerSecond = (double)adapter->TransmitLinkSpeed; + } + for (const IP_ADAPTER_GATEWAY_ADDRESS_LH* gateway = adapter->FirstGatewayAddress; gateway != NULL; + gateway = gateway->Next) { + if (gateway->Address.lpSockaddr->sa_family == AF_INET6) { + memcpy(out->defaultGateway, ((const sockaddr_in6*)gateway->Address.lpSockaddr)->sin6_addr.s6_addr, 16); + break; + } + } + // The first IPv6 DNS server configured on this interface. + for (const IP_ADAPTER_DNS_SERVER_ADDRESS* dnsServer = adapter->FirstDnsServerAddress; dnsServer != NULL; + dnsServer = dnsServer->Next) { + if (dnsServer->Address.lpSockaddr->sa_family == AF_INET6) { + memcpy(out->dnsServer, ((const sockaddr_in6*)dnsServer->Address.lpSockaddr)->sin6_addr.s6_addr, 16); + out->hasDnsServer = true; + break; + } + } + return true; + } + return false; +} + +#else // POSIX + +namespace { + +// The number of leading one bits in a netmask. +uint8_t PrefixLengthOf(const uint8_t mask[16]) { + uint8_t length = 0; + for (int octetIndex = 0; octetIndex < 16; ++octetIndex) { + for (int bitIndex = 7; bitIndex >= 0; --bitIndex) { + if ((mask[octetIndex] >> bitIndex) & 1) { + ++length; + } else { + return length; + } + } + } + return length; +} + +// Linux: the default IPv6 route's next hop, from /proc/net/ipv6_route (one route +// per line: destination, prefix length, source, source prefix length, next hop, +// metric, ..., interface name). Elsewhere it is left unset. +void ReadDefaultGateway(const char* interfaceName, uint8_t gateway[16]) { + FILE* routes = fopen("/proc/net/ipv6_route", "r"); + if (routes == NULL) { + return; + } + char destinationText[33], sourceText[33], nextHopText[33], routeInterface[64]; + unsigned destinationPrefix = 0, sourcePrefix = 0, metric = 0, referenceCount = 0, useCount = 0, flags = 0; + while (fscanf(routes, "%32s %x %32s %x %32s %x %x %x %x %63s", destinationText, &destinationPrefix, sourceText, + &sourcePrefix, nextHopText, &metric, &referenceCount, &useCount, &flags, routeInterface) == 10) { + if (destinationPrefix != 0 || strcmp(routeInterface, interfaceName) != 0) { + continue; + } + uint8_t nextHop[16]; + for (int octetIndex = 0; octetIndex < 16; ++octetIndex) { + unsigned octetValue = 0; + sscanf(nextHopText + 2 * octetIndex, "%2x", &octetValue); + nextHop[octetIndex] = (uint8_t)octetValue; + } + if (!IsZero(nextHop)) { + memcpy(gateway, nextHop, 16); + break; + } + } + fclose(routes); +} + +// The first IPv6 "nameserver" line of /etc/resolv.conf (an IPv4 one is skipped; +// a "%zone" suffix is dropped). Systems that use a local resolver list only +// that resolver here, which is then what IPv6_DNS_Server reports. +void ReadDnsServer(LocalIPv6Address* out) { + FILE* resolverConfiguration = fopen("/etc/resolv.conf", "r"); + if (resolverConfiguration == NULL) { + return; + } + char line[256]; + while (fgets(line, sizeof(line), resolverConfiguration) != NULL) { + char keyword[32]; + char addressText[64]; + if (sscanf(line, "%31s %63s", keyword, addressText) != 2 || strcmp(keyword, "nameserver") != 0) { + continue; + } + char* zoneSeparator = strchr(addressText, '%'); + if (zoneSeparator != NULL) { + *zoneSeparator = '\0'; + } + struct in6_addr parsedAddress; + if (inet_pton(AF_INET6, addressText, &parsedAddress) == 1) { + memcpy(out->dnsServer, parsedAddress.s6_addr, 16); + out->hasDnsServer = true; + break; + } + } + fclose(resolverConfiguration); +} + +} // namespace + +bool GetLocalIPv6Address(const uint32_t interfaceIndex, LocalIPv6Address* out) { + memset(out, 0, sizeof(*out)); + struct ifaddrs* interfaces = NULL; + if (getifaddrs(&interfaces) != 0) { + return false; + } + const struct ifaddrs* chosen = NULL; + for (const struct ifaddrs* entry = interfaces; entry != NULL; entry = entry->ifa_next) { + if (entry->ifa_addr == NULL || entry->ifa_addr->sa_family != AF_INET6 || (entry->ifa_flags & IFF_UP) == 0 || + (entry->ifa_flags & IFF_LOOPBACK) != 0) { + continue; + } + if (interfaceIndex != 0 && if_nametoindex(entry->ifa_name) != interfaceIndex) { + continue; + } + // NOTE: getifaddrs() does not say whether an address is temporary + // (privacy) or deprecated - that takes netlink (IFA_F_TEMPORARY, + // IFA_F_DEPRECATED) on Linux - so they are not skipped here as they are + // on Windows. Name the interface with --interface to be sure, and + // check the address the device prints at start-up. + const uint8_t* candidate = ((const struct sockaddr_in6*)entry->ifa_addr)->sin6_addr.s6_addr; + if (chosen == NULL) { + chosen = entry; + } else if (strcmp(chosen->ifa_name, entry->ifa_name) == 0 && !IsLinkLocal(candidate) && + IsLinkLocal(((const struct sockaddr_in6*)chosen->ifa_addr)->sin6_addr.s6_addr)) { + chosen = entry; // a global address on the same interface + } + } + if (chosen != NULL) { + memcpy(out->address, ((const struct sockaddr_in6*)chosen->ifa_addr)->sin6_addr.s6_addr, 16); + if (chosen->ifa_netmask != NULL) { + out->prefixLength = PrefixLengthOf(((const struct sockaddr_in6*)chosen->ifa_netmask)->sin6_addr.s6_addr); + } + out->interfaceIndex = if_nametoindex(chosen->ifa_name); + ReadDefaultGateway(chosen->ifa_name, out->defaultGateway); + ReadDnsServer(out); + } + freeifaddrs(interfaces); + return chosen != NULL; +} + +#endif diff --git a/ipv6/LocalIPv6Address.h b/ipv6/LocalIPv6Address.h new file mode 100644 index 0000000..c506cdd --- /dev/null +++ b/ipv6/LocalIPv6Address.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef BBC_EXAMPLE_LOCAL_IPV6_ADDRESS_H +#define BBC_EXAMPLE_LOCAL_IPV6_ADDRESS_H + +// LocalIPv6Address.h +// ============================================================================= +// The host's IPv6 addressing, for the BACnet/IPv6 Network Port object +// (--datalink ipv6). The stack cannot know it, so the application serves +// IPv6_Address, IPv6_Prefix_Length, IPv6_Default_Gateway and IPv6_DNS_Server from its Get +// callbacks - the same way the BACnet/IP port serves IP_Address and +// IP_Subnet_Mask from CASExampleHelper::GetLocalIPv4(). +// +// Which address: the interface named by --interface , or else the first +// interface that is up and is not a loopback (on Windows, one that can do +// multicast). On it, a global address is preferred over a link-local one +// (fe80::/10), which every IPv6 interface has. On Windows, temporary (privacy) +// and non-preferred (deprecated) addresses are skipped; on POSIX they are not. +// ============================================================================= + +#include + +struct LocalIPv6Address { + uint8_t address[16]; // all zero when none was found + uint8_t prefixLength; // 0..128 + uint8_t defaultGateway[16]; // all zero when there is none (or it can't be read) + bool hasDnsServer; // true when dnsServer holds the host's first IPv6 DNS server + uint8_t dnsServer[16]; // Windows: the interface's; POSIX: /etc/resolv.conf's first IPv6 nameserver + uint32_t interfaceIndex; // the interface it is on + double linkSpeedBitsPerSecond; // that interface's speed; 0 when unknown (always 0 on POSIX) +}; + +// Fills *out. interfaceIndex 0 = choose (see above). False if no interface has +// an IPv6 address; *out is then all zero. +bool GetLocalIPv6Address(uint32_t interfaceIndex, LocalIPv6Address* out); + +// "fe80::1" style text for the log. `text` should hold at least 48 characters. +const char* FormatIPv6Address(const uint8_t address[16], char* text, unsigned textSize); + +#endif // BBC_EXAMPLE_LOCAL_IPV6_ADDRESS_H diff --git a/ipv6/README.md b/ipv6/README.md new file mode 100644 index 0000000..0605a63 --- /dev/null +++ b/ipv6/README.md @@ -0,0 +1,56 @@ +# BACnet/IPv6 - `--datalink ipv6` + +The same Building Controller device, speaking BACnet/IPv6 (ANSI/ASHRAE 135-2024 Annex U) instead of BACnet/IP. It is a +run-time choice of the one executable, not a separate build: + +```bash +cmake -B build -S . +cmake --build build --config Release +build/Release/BACnetExampleBBC --datalink ipv6 # Windows; build/BACnetExampleBBC elsewhere +build/Release/BACnetExampleBBC --datalink ipv6 --interface 12 # one interface only (its index) +``` + +The device then has **Network Port 2 "Cerulean"** (Network_Type `ipv6`) instead of Network Port 1. The stack serves its +MAC_Address (the 3-octet VMAC) and the multicast address; `main.cpp` (section 1b) serves IPv6_Address, +IPv6_Prefix_Length, IPv6_Default_Gateway and IPv6_DNS_Server from the host (`ipv6/LocalIPv6Address.cpp`: a global +address if the interface has one, otherwise its link-local address; the first IPv6 DNS server, or one unconfigured entry +when there is none) and BACnet_IPv6_UDP_Port from `--port`. The socket is `common/SimpleUDP6.cpp`; it joins the multicast group FF02::BAC0 on +every IPv6 interface that is up, or on `--interface` only. + +## Check it from outside + +```bash +python tests/ipv6_probe.py --target "fe80::
%" --device 389005 --multicast --interface +python tests/ipv6_probe.py --target "" --device 389005 +``` + +`tests/ipv6_probe.py` is a small BACnet/IPv6 node in Python's standard library. It finds the device's VMAC with a +Virtual-Address-Resolution, reads the Device and Analog Input 1, runs a ReadPropertyMultiple, writes Analog Output 1 at +priority 8, reads it back and relinquishes it, reads Network Port 2 (Object_Name, Network_Type 9, MAC_Address equal +to the VMAC, BACnet_IPv6_UDP_Port, IPv6_Address) and (`--multicast`) checks that an Address-Resolution sent to +FF02::BAC0 is answered. + +## What a host has to know + +- A peer is 18 octets: the 16-octet IPv6 address, then the UDP port, most significant octet first. +- A BACnet broadcast reaches the host's send callback with **no** connection string and the broadcast flag set; send it to + FF02::BAC0 (`SimpleUDP6::SendMulticast`). +- To START a broadcast (the start-up I-Am and Who-Is), call `BACnetStack_SendIAm` / `BACnetStack_SendWhoIs` with + `broadcast` true and an 18-octet connection string - this example passes [FF02::BAC0] on its UDP port. The stack sends + an Original-Broadcast-NPDU and hands it over as above: broadcast flag set, no connection string. +- The device's VMAC is its device instance in three octets. + +## BBMD and foreign devices + +The pinned stack (`632165847`, cas-bacnet-stack #4612) supports a BACnet/IPv6 BBMD and foreign-device registration, +configured through the IPv6 Network Port's properties: BACnet_IPv6_Mode, FD_BBMD_Address, FD_Subscription_Lifetime, +BBMD_Broadcast_Distribution_Table and BBMD_Accept_FD_Registrations are writable on Network Port 2, held by the stack +and activated by ReinitializeDevice. This example does not configure either, so it reaches devices on its own link +only - but a client can write those properties. + +If you make it a BBMD that way, it is incomplete: the receive callback passes the stack no destination address. A +BBMD must hand the stack each datagram's real destination (the multicast group it arrived on, or this node's unicast +address), because that is how the stack tells a peer BBMD's forwarded broadcast from a unicast. Without it the device +still forwards its own link's broadcasts to its peers and foreign devices, but never passes its peers' broadcasts on +to its own link. Reading the destination needs `IPV6_PKTINFO` / `recvmsg` (`WSARecvMsg` on Windows) in +`common/SimpleUDP6.cpp`, which this example does not do. Foreign-device registration with another BBMD does not need it. diff --git a/main.cpp b/main.cpp index b988e1e..633d98a 100644 --- a/main.cpp +++ b/main.cpp @@ -55,7 +55,12 @@ // Analog Value 1 "Diamond" (REAL, read from the peer's Analog Input 1; // intrinsic OutOfRange alarm; Reliability) // Notification Class 1 "Crimson" (routes Diamond's alarms; Recipient_List WRITABLE) -// Network Port 1 "Vermilion" (the BACnet/IP port - required) +// Network Port 1 "Vermilion" (the BACnet/IP port - required; --datalink ipv4) +// or Network Port 2 "Cerulean" (BACnet/IPv6, --datalink ipv6) +// or Network Port 3 "Amber" (MS/TP, --datalink mstp) +// or Network Port 4 "Teal" (BACnet/SC, --datalink sc; plus the +// certificate Files 2-5) +// ONE data link runs at a time - see section 1b. // Schedule 1 "Saffron" (drives Chartreuse on a weekly + exception basis, // and a remote peer object - SCHED-E-B) // Calendar 1 "Cream" (stack-held Date_List: every December 25; @@ -91,18 +96,28 @@ // Interactive keys (handled by the shared helper): h = help, q = quit, // up/down = nudge Analog Input 1 by +/-1.1, s = advance Schedule 1 ("Saffron") // with a Weekly_Schedule transition for right now. To fire an alarm, drive the -// peer's Analog Input 1 above 90 or below 10. Command line: --port , -// --deviceID , --deviceName . +// peer's Analog Input 1 above 90 or below 10; m = MS/TP counters (--datalink +// mstp). Command line: --datalink ipv4|ipv6|mstp|sc, --port , --deviceID , +// --deviceName and each data link's own options - run with --help for +// the list (command_line.cpp). // -// Most of the plumbing (CLI, keyboard, frame logging, time) lives in +// Most of the plumbing (keyboard, frame logging, time) lives in // common/CASExampleHelper so this file can stay focused on the BACnet logic. The -// UDP socket is the exception: this example owns it, so it can read the answers -// to its own ReadProperty requests (section 2e). +// data link is the exception: this example owns its UDP socket, so it can read +// the answers to its own ReadProperty requests (section 2e), and it drives the +// MS/TP and BACnet/SC data links itself (mstp/, sc/). // ============================================================================= #include "CASExampleHelper.h" #include "CASBACnetStackExampleConstants.h" -#include "SimpleUDP.h" // this example owns its BACnet/IP socket - see section 2e +#include "SimpleUDP.h" // --datalink ipv4: this example owns its BACnet/IP socket - see section 2e +#include "SimpleUDP6.h" // --datalink ipv6: ... and its BACnet/IPv6 socket +#include "command_line.h" // --datalink and every other option (command_line.cpp) +#include "ipv6/LocalIPv6Address.h" // the host's IPv6 address, for the IPv6 Network Port +#include "mstp/MstpDataLink.h" // --datalink mstp: the stack's MS/TP engine on a serial port +#ifdef BBC_WITH_SC +#include "sc/ScNode.h" // --datalink sc: BACnet/SC node (built when libwebsockets is found) +#endif #include "CASBACnetStackAdapter.h" // the CAS BACnet Stack C API (BACnetStack_*); call // LoadBACnetFunctions() before any BACnetStack_* call - // see the top of main() below. @@ -115,6 +130,7 @@ #if defined(_WIN32) #include // Sleep() +#include // timeBeginPeriod() - 1 ms sleeps for MS/TP (winmm) #else #include // usleep() #endif @@ -125,7 +141,7 @@ using namespace CASBACnetStackExampleConstants; // 1. Example + device configuration // ----------------------------------------------------------------------------- static const char* APP_NAME = "BACnet B-BC (Building Controller) Example - C++"; -static const char* APP_VERSION = "1.2.0"; +static const char* APP_VERSION = "1.3.0"; // The device instance. BACnet requires this to be configurable, so it defaults // to 389005 and can be overridden on the command line with --deviceID. Keep it @@ -192,6 +208,12 @@ static const char* MODEL_NAME = "CAS BACnet Stack Example - B-BC"; // (no password required). Change this to your device's secret before shipping - // it crosses the wire in PLAINTEXT, so treat it as a guard against accidents, // not a security boundary. +// +// It is EMPTY here on purpose, so a test client can try every service, and the +// device prints a warning at every start while it is. On BACnet/SC it matters +// more: ReinitializeDevice ACTIVATE_CHANGES is how a client installs the +// certificates it wrote to the certificate File objects, so with no password +// any peer on the hub can replace this device's certificates. static const char* DCC_PASSWORD = ""; // "" = no password required // Firmware_Revision (Device object property 44) reflects the underlying CAS @@ -342,6 +364,7 @@ static const uint32_t REINITIALIZE_STATE_ENDBACKUP = 3; static const uint32_t REINITIALIZE_STATE_STARTRESTORE = 4; static const uint32_t REINITIALIZE_STATE_ENDRESTORE = 5; static const uint32_t REINITIALIZE_STATE_ABORTRESTORE = 6; +static const uint32_t REINITIALIZE_STATE_ACTIVATE_CHANGES = 7; // apply pending Network Port changes static const uint32_t SERVICE_ATOMIC_READ_FILE = 6; static const uint32_t SERVICE_ATOMIC_WRITE_FILE = 7; @@ -460,6 +483,244 @@ static bool ReadPrioritySlot(const Commandable* c, uint32_t propertyIdentifier, return true; } +// ----------------------------------------------------------------------------- +// 1b. The data link - chosen at run time with --datalink +// +// ONE executable, four BACnet data links, ONE of them at a time: +// +// --datalink ipv4 BACnet/IP Network Port 1 "Vermilion" (the default) +// --datalink ipv6 BACnet/IPv6 Network Port 2 "Cerulean" +// --datalink mstp MS/TP Network Port 3 "Amber" +// --datalink sc BACnet/SC Network Port 4 "Teal" +// +// Every data link gets its OWN Network Port instance, even though only one runs +// at a time. That is a choice, not a rule: a client that remembers "Network Port +// 1 is the BACnet/IP port" must not find an MS/TP port there after a restart. +// The device has only the active data link's Network Port object. +// +// The stack serves most of a Network Port itself (Network_Type, Protocol_Level, +// MAC_Address for IPv6 and SC, APDU_Length ...). What it cannot know - the +// host's IPv6 address, the MS/TP station address the installer chose - it asks +// for through the same Get callbacks as every other property. The helpers below +// answer those for the IPv6, MS/TP and SC ports; the BACnet/IP port's answers +// stay inline in the callbacks, as they were. Each Get callback calls the +// matching helper first. +// ----------------------------------------------------------------------------- +static CommandLineOptions g_options; // --datalink and every data-link setting (command_line.h) + +static const uint32_t IPV6_NETWORK_PORT_INSTANCE = 2; // "Cerulean" +static const uint32_t MSTP_NETWORK_PORT_INSTANCE = 3; // "Amber" +static const uint32_t SC_NETWORK_PORT_INSTANCE = 4; // "Teal" + +// BACnetNetworkType (cl. 12.56.9) values, and Network Port / Device property +// identifiers, that are not in common/CASBACnetStackExampleConstants.h +// (checked against the stack's BACnetPropertyIdentifier.h at the pin). +static const uint8_t NETWORK_PORT_NETWORK_TYPE_MSTP = 2; +static const uint8_t NETWORK_PORT_NETWORK_TYPE_IPV6 = 9; +static const uint32_t PROPERTY_IDENTIFIER_IPV6_ADDRESS = 436; +static const uint32_t PROPERTY_IDENTIFIER_IPV6_PREFIX_LENGTH = 437; +static const uint32_t PROPERTY_IDENTIFIER_BACNET_IPV6_UDP_PORT = 438; +static const uint32_t PROPERTY_IDENTIFIER_IPV6_DEFAULT_GATEWAY = 439; +static const uint32_t PROPERTY_IDENTIFIER_IPV6_DNS_SERVER = 441; +static const uint32_t PROPERTY_IDENTIFIER_MAX_INFO_FRAMES = 63; +static const uint32_t PROPERTY_IDENTIFIER_MAX_MASTER = 64; // "Max_Manager" in 135-2024 +static const uint32_t PROPERTY_IDENTIFIER_MAX_APDU_LENGTH_ACCEPTED = 62; +static const uint32_t PROPERTY_IDENTIFIER_NETWORK_NUMBER = 425; + +// The largest APDU on MS/TP is 480 octets (the stack's MS/TP Network Port reports +// APDU_Length 480 by itself). The Device object's Max_APDU_Length_Accepted must +// agree, so in MS/TP mode this example serves 480 for it; on the other data links +// the stack's default (1476) stands. +static const uint32_t MSTP_MAX_APDU_LENGTH = 480; + +// --datalink ipv6: the host's IPv6 addressing, read once at start-up. +static LocalIPv6Address g_ipv6Address; + +// The active data link's Network Port instance - the one the transport callbacks +// and every BACnetStack_Send* call name. +static uint32_t ActiveNetworkPortInstance() { + switch (g_options.dataLink) { + case DataLink::IPv6: return IPV6_NETWORK_PORT_INSTANCE; + case DataLink::MSTP: return MSTP_NETWORK_PORT_INSTANCE; + case DataLink::SC: return SC_NETWORK_PORT_INSTANCE; + case DataLink::IPv4: + default: return NETWORK_PORT_INSTANCE; + } +} + +// The colour name of the IPv6, MS/TP or SC Network Port, when it is the active +// one; NULL otherwise (the BACnet/IP port's "Vermilion" is served inline). +static const char* DataLinkPortName(const uint16_t objectType, const uint32_t objectInstance) { + if (objectType != OBJECT_TYPE_NETWORK_PORT || objectInstance != ActiveNetworkPortInstance()) { + return NULL; + } + switch (g_options.dataLink) { + case DataLink::IPv6: return "Cerulean"; + case DataLink::MSTP: return "Amber"; + case DataLink::SC: return "Teal"; + case DataLink::IPv4: + default: return NULL; + } +} + +// Is this the active port, and is it the given data link's? +static bool IsDataLinkPort(const uint16_t objectType, const uint32_t objectInstance, const DataLink dataLink) { + return g_options.dataLink == dataLink && objectType == OBJECT_TYPE_NETWORK_PORT && + objectInstance == ActiveNetworkPortInstance(); +} + +// REAL: Link_Speed. On MS/TP it is the baud rate - and the stack's MS/TP engine +// reads it from here to know how fast the line runs. On BACnet/IPv6 it is the +// interface speed, as for the BACnet/IP port. +static bool GetDataLinkPortReal(const uint16_t objectType, const uint32_t objectInstance, + const uint32_t propertyIdentifier, float* value) { + if (propertyIdentifier != PROPERTY_IDENTIFIER_LINK_SPEED) { + return false; + } + if (IsDataLinkPort(objectType, objectInstance, DataLink::MSTP)) { + *value = (float)g_options.mstpBaudRate; + return true; + } + if (IsDataLinkPort(objectType, objectInstance, DataLink::IPv6)) { + *value = g_linkSpeedBitsPerSecond; + return true; + } + return false; +} + +// UNSIGNED: the IPv6 port's prefix length and UDP port; the MS/TP port's +// Max_Master and Max_Info_Frames (which the MS/TP engine reads too); and, in +// MS/TP mode, the Device's Max_APDU_Length_Accepted. +static bool GetDataLinkPortUnsigned(const uint16_t objectType, const uint32_t objectInstance, + const uint32_t propertyIdentifier, const bool useArrayIndex, + const uint32_t propertyArrayIndex, uint32_t* value) { + if (g_options.dataLink == DataLink::MSTP && objectType == OBJECT_TYPE_DEVICE && + objectInstance == g_deviceInstance && propertyIdentifier == PROPERTY_IDENTIFIER_MAX_APDU_LENGTH_ACCEPTED) { + *value = MSTP_MAX_APDU_LENGTH; + return true; + } + if (IsDataLinkPort(objectType, objectInstance, DataLink::IPv6)) { + if (propertyIdentifier == PROPERTY_IDENTIFIER_IPV6_PREFIX_LENGTH) { + *value = g_ipv6Address.prefixLength; + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_BACNET_IPV6_UDP_PORT) { + *value = g_options.udpPort; + return true; + } + // IPv6_DNS_Server is an array: the stack asks for its length here + // (array index 0) and for each address from the OCTET STRING callback. + // With no IPv6 DNS server this declines, and the stack reports one + // unconfigured entry. + if (propertyIdentifier == PROPERTY_IDENTIFIER_IPV6_DNS_SERVER && useArrayIndex && propertyArrayIndex == 0 && + g_ipv6Address.hasDnsServer) { + *value = 1; + return true; + } + } + if (IsDataLinkPort(objectType, objectInstance, DataLink::MSTP)) { + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_MASTER) { + *value = g_options.mstpMaxMaster; + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_INFO_FRAMES) { + *value = g_options.mstpMaxInfoFrames; + return true; + } + } + return false; +} + +// UNSIGNED write, at activation: a client may write the MS/TP port's Max_Master +// and Max_Info_Frames. The stack holds the write as PENDING (Changes_Pending +// TRUE) and hands it here only on ReinitializeDevice ACTIVATE_CHANGES (or +// WARMSTART). Storing it is enough: the stack re-reads both through the Get +// callback above after every activation and reconfigures the MS/TP engine. +// +// DO NOT REFUSE A VALUE HERE. The stack range-checked the write when it arrived +// (Max_Master 0..127, Max_Info_Frames 1..255) and has no hook for the app to +// check it then. By the time this runs, CallbackReinitializeDevice has already +// accepted the request - and for WARMSTART armed the restart - so a refusal now +// answers the client with an Error while the device restarts anyway, and leaves +// the value pending to fail every later activation. Accept, and warn instead. +static bool SetDataLinkPortUnsigned(const uint16_t objectType, const uint32_t objectInstance, + const uint32_t propertyIdentifier, const uint32_t value, uint32_t* errorCode) { + (void)errorCode; + if (!IsDataLinkPort(objectType, objectInstance, DataLink::MSTP)) { + return false; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_MASTER) { + g_options.mstpMaxMaster = (uint8_t)(value > 127 ? 127 : value); + printf("Network Port %u (Amber): Max_Master is now %u\n", objectInstance, (unsigned)g_options.mstpMaxMaster); + if (g_options.mstpMaxMaster < g_options.mstpMacAddress) { + printf("Warning: Max_Master %u is below this station's MAC %u: no station will pass this one the " + "token until Max_Master is raised again.\n", + (unsigned)g_options.mstpMaxMaster, (unsigned)g_options.mstpMacAddress); + } + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_INFO_FRAMES) { + g_options.mstpMaxInfoFrames = (uint8_t)(value < 1 ? 1 : (value > 255 ? 255 : value)); + printf("Network Port %u (Amber): Max_Info_Frames is now %u\n", objectInstance, + (unsigned)g_options.mstpMaxInfoFrames); + return true; + } + // Any other pending unsigned value of this port - a client-written + // Network_Number, say - is held and served by the stack itself: there is + // nothing for the app to store, but returning false would refuse it. + return true; +} + +// OCTET STRING: the IPv6 port's address, default gateway and DNS server (16 +// octets each), and the MS/TP port's MAC_Address - ONE octet, the station +// address. The stack serves MAC_Address from this, and its MS/TP engine takes +// its own address from it: this is where --mstp-mac reaches the token ring. +static bool GetDataLinkPortOctetString(const uint16_t objectType, const uint32_t objectInstance, + const uint32_t propertyIdentifier, const bool useArrayIndex, + const uint32_t propertyArrayIndex, uint8_t* value, + uint32_t* valueElementCount, const uint32_t maxElementCount) { + if (IsDataLinkPort(objectType, objectInstance, DataLink::IPv6) && maxElementCount >= 16) { + if (propertyIdentifier == PROPERTY_IDENTIFIER_IPV6_ADDRESS) { + memcpy(value, g_ipv6Address.address, 16); + *valueElementCount = 16; + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_IPV6_DEFAULT_GATEWAY) { + memcpy(value, g_ipv6Address.defaultGateway, 16); + *valueElementCount = 16; + return true; + } + // IPv6_DNS_Server[1], the only element (its length is in section 1b's + // UNSIGNED helper above). + if (propertyIdentifier == PROPERTY_IDENTIFIER_IPV6_DNS_SERVER && g_ipv6Address.hasDnsServer && + (!useArrayIndex || propertyArrayIndex == 1)) { + memcpy(value, g_ipv6Address.dnsServer, 16); + *valueElementCount = 16; + return true; + } + } + if (IsDataLinkPort(objectType, objectInstance, DataLink::MSTP) && maxElementCount >= 1 && + propertyIdentifier == PROPERTY_IDENTIFIER_MAC_ADDRESS) { + value[0] = g_options.mstpMacAddress; + *valueElementCount = 1; + return true; + } + return false; +} + +// The BACnet/SC certificate File objects (Files 2-5, --datalink sc only). Their +// contents are the certificate files in --sc-cert-dir; sc/ScNode.cpp serves them. +static bool IsScCertificateFile(const uint16_t objectType, const uint32_t objectInstance) { +#ifdef BBC_WITH_SC + return g_options.dataLink == DataLink::SC && objectType == OBJECT_TYPE_FILE && + ScNode::IsCertificateFile(objectInstance); +#else + (void)objectType; + (void)objectInstance; + return false; +#endif +} + // ----------------------------------------------------------------------------- // 2. Property "get" callbacks // @@ -535,6 +796,10 @@ bool GetPropertyReal(const uint32_t deviceInstance, const uint16_t objectType, if (deviceInstance != g_deviceInstance) { return false; } + // The IPv6 / MS/TP Network Port's Link_Speed (section 1b). + if (GetDataLinkPortReal(objectType, objectInstance, propertyIdentifier, value)) { + return true; + } if (objectType == OBJECT_TYPE_ANALOG_INPUT && objectInstance == ANALOG_INPUT_INSTANCE && propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) { @@ -692,6 +957,18 @@ bool GetPropertyUnsignedInteger(const uint32_t deviceInstance, const uint16_t ob if (deviceInstance != g_deviceInstance) { return false; } + // The IPv6 / MS/TP Network Port's numbers, and the MS/TP Max_APDU (section 1b). + if (GetDataLinkPortUnsigned(objectType, objectInstance, propertyIdentifier, useArrayIndex, propertyArrayIndex, + value)) { + return true; + } +#ifdef BBC_WITH_SC + // The BACnet/SC certificate File objects (Files 2-5): File_Size is the size + // of the certificate file on disk. + if (IsScCertificateFile(objectType, objectInstance) && propertyIdentifier == PROPERTY_IDENTIFIER_FILE_SIZE) { + return ScNode::GetCertificateFileSize(objectInstance, value); + } +#endif if (objectType == OBJECT_TYPE_MULTI_STATE_INPUT && objectInstance == MULTI_STATE_INPUT_INSTANCE) { if (propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) { @@ -800,6 +1077,21 @@ bool GetPropertyBool(const uint32_t deviceInstance, const uint16_t objectType, *value = false; return true; } +#ifdef BBC_WITH_SC + // The BACnet/SC certificate File objects: never archived; the certificate + // signing request is read-only (the device makes it), the rest are written + // by a client to install new certificates. + if (IsScCertificateFile(objectType, objectInstance)) { + if (propertyIdentifier == PROPERTY_IDENTIFIER_ARCHIVE) { + *value = false; + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_READ_ONLY) { + *value = ScNode::IsCertificateFileReadOnly(objectInstance); + return true; + } + } +#endif // Ivory (File 1) - Archive (writable, DM-BR-B configuration-file marker) and // Read_Only are both REQUIRED with no stack default. if (objectType == OBJECT_TYPE_FILE && objectInstance == FILE_INSTANCE) { @@ -824,10 +1116,15 @@ bool GetPropertyOctetString(const uint32_t deviceInstance, const uint16_t object uint8_t* value, uint32_t* valueElementCount, const uint32_t maxElementCount, const bool useArrayIndex, const uint32_t propertyArrayIndex, uint32_t* errorCode) { - (void)useArrayIndex; (void)errorCode; - (void)propertyArrayIndex; - if (deviceInstance != g_deviceInstance || + // The IPv6 port's addresses and the MS/TP port's MAC_Address (section 1b). + if (deviceInstance == g_deviceInstance && + GetDataLinkPortOctetString(objectType, objectInstance, propertyIdentifier, useArrayIndex, propertyArrayIndex, + value, valueElementCount, maxElementCount)) { + return true; + } + // The BACnet/IP port "Vermilion" - only when BACnet/IP is the data link. + if (deviceInstance != g_deviceInstance || g_options.dataLink != DataLink::IPv4 || objectType != OBJECT_TYPE_NETWORK_PORT || objectInstance != NETWORK_PORT_INSTANCE || maxElementCount < 4) { @@ -939,6 +1236,17 @@ bool GetPropertyCharString(const uint32_t deviceInstance, const uint16_t objectT if (objectType == OBJECT_TYPE_NETWORK_PORT && objectInstance == NETWORK_PORT_INSTANCE) { return ReturnCharacterString("Vermilion", value, valueElementCount, maxElementCount, encodingType); } + // "Cerulean" / "Amber" / "Teal" - the IPv6, MS/TP or BACnet/SC port. + const char* dataLinkPortName = DataLinkPortName(objectType, objectInstance); + if (dataLinkPortName != NULL) { + return ReturnCharacterString(dataLinkPortName, value, valueElementCount, maxElementCount, encodingType); + } +#ifdef BBC_WITH_SC + if (IsScCertificateFile(objectType, objectInstance)) { + return ReturnCharacterString(ScNode::CertificateFileName(objectInstance), value, valueElementCount, + maxElementCount, encodingType); + } +#endif if (objectType == OBJECT_TYPE_SCHEDULE && objectInstance == SCHEDULE_INSTANCE) { return ReturnCharacterString("Saffron", value, valueElementCount, maxElementCount, encodingType); } @@ -961,6 +1269,11 @@ bool GetPropertyCharString(const uint32_t deviceInstance, const uint16_t objectT return ReturnCharacterString("application/octet-stream", value, valueElementCount, maxElementCount, encodingType); } + // The BACnet/SC certificate files are PEM text. + if (IsScCertificateFile(objectType, objectInstance) && propertyIdentifier == PROPERTY_IDENTIFIER_FILE_TYPE) { + return ReturnCharacterString("application/x-pem-file", value, valueElementCount, maxElementCount, + encodingType); + } // The remaining strings are all on the Device object - its identity, read // by clients and used to populate the device's I-Am / object list. @@ -1029,6 +1342,18 @@ bool GetPropertyTime(const uint32_t deviceInstance, const uint16_t objectType, *hour = 0; *minute = 0; *second = 0; *hundredthSecond = 0; return true; } +#ifdef BBC_WITH_SC + // A certificate File's Modification_Date: when the file on disk last changed. + struct tm modifiedUtc; + if (IsScCertificateFile(objectType, objectInstance) && propertyIdentifier == PROPERTY_IDENTIFIER_MODIFICATION_DATE && + ScNode::GetCertificateFileModified(objectInstance, &modifiedUtc)) { + *hour = (uint8_t)modifiedUtc.tm_hour; + *minute = (uint8_t)modifiedUtc.tm_min; + *second = (uint8_t)modifiedUtc.tm_sec; + *hundredthSecond = 0; + return true; + } +#endif if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance && propertyIdentifier == PROPERTY_IDENTIFIER_LOCAL_TIME) { struct tm nowTm; @@ -1061,6 +1386,17 @@ bool GetPropertyDate(const uint32_t deviceInstance, const uint16_t objectType, *yearMinus1900 = 126; *month = 1; *day = 1; *weekday = 4; // nominal 2026-01-01 Thu return true; } +#ifdef BBC_WITH_SC + struct tm modifiedUtc; + if (IsScCertificateFile(objectType, objectInstance) && propertyIdentifier == PROPERTY_IDENTIFIER_MODIFICATION_DATE && + ScNode::GetCertificateFileModified(objectInstance, &modifiedUtc)) { + *yearMinus1900 = (uint8_t)modifiedUtc.tm_year; + *month = (uint8_t)(modifiedUtc.tm_mon + 1); + *day = (uint8_t)modifiedUtc.tm_mday; + *weekday = (uint8_t)(((modifiedUtc.tm_wday + 6) % 7) + 1); // tm: 0=Sunday; BACnet: 1=Monday + return true; + } +#endif if (objectType == OBJECT_TYPE_DEVICE && objectInstance == g_deviceInstance && propertyIdentifier == PROPERTY_IDENTIFIER_LOCAL_DATE) { struct tm nowTm; @@ -1165,6 +1501,24 @@ bool SetPropertyUnsignedInteger(const uint32_t deviceInstance, const uint16_t ob if (deviceInstance != g_deviceInstance) { return false; } + // The MS/TP port's Max_Master / Max_Info_Frames, at activation (section 1b). + if (IsDataLinkPort(objectType, objectInstance, DataLink::MSTP)) { + return SetDataLinkPortUnsigned(objectType, objectInstance, propertyIdentifier, value, errorCode); + } + // A client-written Network_Number on the other ports, at activation: the + // stack holds and serves it; refusing it here would fail the activation + // after ReinitializeDevice already accepted it (see SetDataLinkPortUnsigned). + if (objectType == OBJECT_TYPE_NETWORK_PORT && objectInstance == ActiveNetworkPortInstance() && + propertyIdentifier == PROPERTY_IDENTIFIER_NETWORK_NUMBER) { + return true; + } +#ifdef BBC_WITH_SC + // A certificate File's File_Size: a client writes 0 to empty the file before + // writing a new certificate into it. + if (IsScCertificateFile(objectType, objectInstance) && propertyIdentifier == PROPERTY_IDENTIFIER_FILE_SIZE) { + return ScNode::ResizeCertificateFile(objectInstance, value, errorCode); + } +#endif Commandable* c = GetCommandable(objectType, objectInstance); if (c != NULL && objectType == OBJECT_TYPE_MULTI_STATE_OUTPUT && propertyIdentifier == PROPERTY_IDENTIFIER_PRESENT_VALUE) { @@ -1354,7 +1708,8 @@ bool DeviceCommunicationControl(const uint32_t deviceInstance, const uint8_t ena // ReinitializeDevice (DM-RD-B) - ALSO the DM-BR-B backup/restore state machine // entry point. reinitializedState: 0=COLDSTART, 1=WARMSTART, 2=STARTBACKUP, -// 3=ENDBACKUP, 4=STARTRESTORE, 5=ENDRESTORE, 6=ABORTRESTORE. The stack itself +// 3=ENDBACKUP, 4=STARTRESTORE, 5=ENDRESTORE, 6=ABORTRESTORE, 7=ACTIVATE_CHANGES +// (apply pending Network Port changes - see below). The stack itself // drives the backup/restore sequence (calling the four Prepare/Complete // callbacks below and moving Backup_And_Restore_State) once this callback // ACCEPTS the request; accepting only means "password OK, proceed" - it does @@ -1382,6 +1737,26 @@ bool ReinitializeDevice(const uint32_t deviceInstance, const uint32_t reinitiali // ACK is never transmitted: the client times out and reports this device as // unresponsive even though it obeyed. So record a deadline, return, let the // ACK ship, and do the actual restart from the main loop. + // + // ACTIVATE_CHANGES (and WARMSTART) first apply what is PENDING. The stack + // activates its own pending Network Port writes (the MS/TP port's Max_Master, + // say) after this callback accepts; certificates written to the BACnet/SC + // certificate Files are this example's to check and save - and if they would + // leave the device unable to connect, the request is refused and nothing + // changes. +#ifdef BBC_WITH_SC + if (g_options.dataLink == DataLink::SC && + (reinitializedState == REINITIALIZE_STATE_ACTIVATE_CHANGES || + reinitializedState == REINITIALIZE_STATE_WARMSTART) && + !ScNode::ApplyStagedCertificates(errorCode)) { + printf("ReinitializeDevice: REJECTED (the new certificates would not work)\n"); + return false; + } +#endif + if (reinitializedState == REINITIALIZE_STATE_ACTIVATE_CHANGES) { + printf("ReinitializeDevice: ACTIVATE_CHANGES accepted (pending Network Port changes take effect)\n"); + return true; + } if (reinitializedState == REINITIALIZE_STATE_COLDSTART) { printf("ReinitializeDevice: COLDSTART accepted (restarting in %u ms)\n", (unsigned)CASExampleHelper::RESTART_DELAY_MS); @@ -1415,6 +1790,13 @@ bool ReadFile(const uint32_t deviceInstance, const uint32_t fileInstance, const const uint32_t requestedCount, uint8_t* fileData, uint32_t* fileDataLength, const uint32_t maxFileDataLength, bool* endOfFile, uint32_t* errorCode) { (void)errorCode; +#ifdef BBC_WITH_SC + // The BACnet/SC certificate Files (2-5) are files in --sc-cert-dir. + if (deviceInstance == g_deviceInstance && IsScCertificateFile(OBJECT_TYPE_FILE, fileInstance)) { + return ScNode::ReadCertificateFile(fileInstance, fileStart, requestedCount, fileData, fileDataLength, + maxFileDataLength, endOfFile); + } +#endif if (deviceInstance != g_deviceInstance || fileInstance != FILE_INSTANCE) { return false; } @@ -1437,10 +1819,18 @@ bool WriteFile(const uint32_t deviceInstance, const uint32_t fileInstance, const const uint8_t* fileData, const uint32_t fileDataLength, int32_t* ackFileStart, uint32_t* errorCode) { (void)errorCode; +#ifdef BBC_WITH_SC + // A new certificate written to a BACnet/SC certificate File is STAGED, not + // used: ReinitializeDevice ACTIVATE_CHANGES checks it and puts it in place. + if (deviceInstance == g_deviceInstance && IsScCertificateFile(OBJECT_TYPE_FILE, fileInstance)) { + return ScNode::WriteCertificateFile(fileInstance, fileStart, fileData, fileDataLength, ackFileStart, + errorCode); + } +#endif if (deviceInstance != g_deviceInstance || fileInstance != FILE_INSTANCE) { return false; } - uint32_t start = (fileStart == -1) ? g_fileDataLength : (uint32_t)fileStart; + uint32_t start =(fileStart == -1) ? g_fileDataLength : (uint32_t)fileStart; if (start + fileDataLength > FILE_MAX_SIZE) { return false; } @@ -1453,6 +1843,34 @@ bool WriteFile(const uint32_t deviceInstance, const uint32_t fileInstance, const return true; } +// Network Port Command (the Command property, cl. 12.56). The stack runs the +// command itself and asks the application only about the two that touch data +// the application holds: +// DISCARD_CHANGES (1) - throw away pending changes; on the BACnet/SC port that +// includes certificates written but not yet activated. +// GENERATE_CSR_FILE (9) - the BACnet/SC port: a new key pair and certificate +// signing request (File 5). +// Every other command, and every other port, needs nothing from the application. +static const uint32_t NETWORK_PORT_COMMAND_DISCARD_CHANGES = 1; +bool NetworkPortCommand(const uint32_t deviceInstance, const uint32_t networkPortInstance, const uint32_t command, + uint32_t* errorCode) { + if (deviceInstance != g_deviceInstance) { + *errorCode = ERROR_CODE_OPTIONAL_FUNCTIONALITY_NOT_SUPPORTED; + return false; + } +#ifdef BBC_WITH_SC + if (g_options.dataLink == DataLink::SC && networkPortInstance == SC_NETWORK_PORT_INSTANCE) { + return ScNode::NetworkPortCommand(command, errorCode); + } +#endif + if (command == NETWORK_PORT_COMMAND_DISCARD_CHANGES) { + printf("Network Port %u Command DISCARD_CHANGES\n", networkPortInstance); + return true; // the stack reverts its own pending values + } + *errorCode = ERROR_CODE_OPTIONAL_FUNCTIONALITY_NOT_SUPPORTED; + return false; +} + bool PrepareBackup(const uint32_t deviceInstance) { if (deviceInstance != g_deviceInstance) { return false; @@ -1566,6 +1984,54 @@ bool AcknowledgeAlarm(const uint32_t deviceInstance, const uint32_t /*acknowledg return true; // accept the acknowledgement } +// ----------------------------------------------------------------------------- +// The transport's addressing, per data link +// +// The stack names every peer by a CONNECTION STRING - the data link's own address +// for it - and every message by the Network Port it travels on: +// +// ipv4 IP[4] + UDP port[2], network order (6 octets) +// ipv6 IPv6[16] + UDP port[2] - its B/IPv6 address (18 octets, Annex U); a +// BACnet broadcast goes out with NO connection string, to the multicast +// group FF02::BAC0 (SimpleUDP6::SendMulticast) +// mstp the one-octet station address (MAC); 0xFF is the broadcast +// sc the hub's URI: on BACnet/SC every message goes through the hub +// (sc/ScNode.cpp) +// ----------------------------------------------------------------------------- + +// How many octets of an IP connection string are the address (the rest is the +// UDP port). Only meaningful on ipv4 / ipv6. +static uint8_t TransportAddressLength() { + return g_options.dataLink == DataLink::IPv6 ? 16 : 4; +} + +// How long an IP connection string is: the address, then the 2-octet UDP port. +static uint8_t TransportConnectionStringLength() { + return (uint8_t)(TransportAddressLength() + 2); +} + +// Is the data link one of the two UDP ones (which this example reads replies on)? +static bool IsIpDataLink() { + return g_options.dataLink == DataLink::IPv4 || g_options.dataLink == DataLink::IPv6; +} + +// A peer's address as text, for the log: a.b.c.d:port, or [ipv6]:port. +static const char* AddressText(const uint8_t* connectionString, char* text, const size_t textSize) { + if (g_options.dataLink == DataLink::IPv6) { + char digits[64] = ""; + size_t used = 0; + for (int groupIndex = 0; groupIndex < 8; ++groupIndex) { + used += (size_t)snprintf(digits + used, sizeof(digits) - used, groupIndex == 0 ? "%x" : ":%x", + (unsigned)((connectionString[2 * groupIndex] << 8) | connectionString[2 * groupIndex + 1])); + } + snprintf(text, textSize, "[%s]:%u", digits, (unsigned)((connectionString[16] << 8) | connectionString[17])); + } else { + snprintf(text, textSize, "%u.%u.%u.%u:%u", connectionString[0], connectionString[1], connectionString[2], + connectionString[3], (unsigned)((connectionString[4] << 8) | connectionString[5])); + } + return text; +} + // Build the 6-octet BACnet/IP connection string for the LOCAL SUBNET BROADCAST: // the directed broadcast address (IP | ~mask) followed by the UDP port in network // byte order. (When the mask is 0.0.0.0 - the helper's fallback - this collapses to @@ -1579,6 +2045,9 @@ static void LocalBroadcastConnString(uint8_t out[6]) { out[5] = (uint8_t)(g_bacnetIpUdpPort & 0xFF); } +// The MS/TP broadcast station address. +static const uint8_t MSTP_BROADCAST_MAC_ADDRESS = 0xFF; + // ----------------------------------------------------------------------------- // 2e. Reading another device's objects (DS-RP-A, DS-RPM-A) // @@ -1597,13 +2066,16 @@ static void LocalBroadcastConnString(uint8_t out[6]) { // asked for by hand, which keeps the build to the two commands in the README. // ----------------------------------------------------------------------------- -static SimpleUDP g_udp; +// One socket per IP data link; only the active data link's is opened. +static SimpleUDP g_udp; // --datalink ipv4 +static SimpleUDP6 g_udp6; // --datalink ipv6 // The peer, as this controller knows it. bound = we have its BACnet/IP address, // learned from its I-Am (HookIAm below). struct RemotePeer { bool bound; - uint8_t connectionString[6]; // IP[4] + UDP port[2], network order + uint8_t connectionString[18]; // IP[4] + UDP port[2] (BACnet/IP), or IPv6[16] + UDP port[2] (BACnet/IPv6), network order; + // TransportConnectionStringLength() of them uint8_t readPropertyInvokeId; // the outstanding ReadProperty, if any bool readPropertyPending; uint8_t readPropertyMultipleInvokeId; // the outstanding ReadPropertyMultiple, if any @@ -1674,15 +2146,18 @@ void HookIAm(const uint32_t deviceIdentifier, const uint32_t maxApduLengthAccept (void)sourceAddressLength; // Only the peer, and only when it is on this network (no router in between: // a remote peer would need its DNET/DADR on every read, which this example - // does not do). - if (deviceIdentifier != REMOTE_DEVICE_INSTANCE || sourceNetwork != 0 || connectionStringLength != 6) { + // does not do). And only on BACnet/IP or BACnet/IPv6: the replies are decoded + // from the UDP receive path (HandleReplyFromPeer below), which MS/TP and + // BACnet/SC do not have in this example - see TODO.md. + if (!IsIpDataLink() || deviceIdentifier != REMOTE_DEVICE_INSTANCE || sourceNetwork != 0 || + connectionStringLength != TransportConnectionStringLength()) { return; } - if (!g_peer.bound || memcmp(g_peer.connectionString, connectionString, 6) != 0) { - memcpy(g_peer.connectionString, connectionString, 6); - printf("PEER: device %u is at %u.%u.%u.%u:%u - polling its Analog Input %u\n", - REMOTE_DEVICE_INSTANCE, connectionString[0], connectionString[1], connectionString[2], - connectionString[3], (unsigned)((connectionString[4] << 8) | connectionString[5]), + if (!g_peer.bound || memcmp(g_peer.connectionString, connectionString, connectionStringLength) != 0) { + memcpy(g_peer.connectionString, connectionString, connectionStringLength); + char peerText[64]; + printf("PEER: device %u is at %s - polling its Analog Input %u\n", + REMOTE_DEVICE_INSTANCE, AddressText(connectionString, peerText, sizeof(peerText)), REMOTE_ANALOG_INPUT_INSTANCE); // A device at a new address may be a different one: try // ReadPropertyMultiple again. @@ -1745,8 +2220,8 @@ static void PollPeer() { const uint32_t elementCount = useReadPropertyMultiple ? 2 : 1; if (!BACnetStack_SendReadProperty(&invokeId, (uint8_t)(useReadPropertyMultiple ? SERVICE_READ_PROPERTY_MULTIPLE : SERVICE_READ_PROPERTY), - g_peer.connectionString, sizeof(g_peer.connectionString), - NETWORK_PORT_INSTANCE, 0, NULL, 0, + g_peer.connectionString, TransportConnectionStringLength(), + ActiveNetworkPortInstance(), 0, NULL, 0, elementCount, elements, elementCount * 15)) { printf("PEER: FYI could not send the %s to device %u\n", useReadPropertyMultiple ? "ReadPropertyMultiple" : "ReadProperty", REMOTE_DEVICE_INSTANCE); @@ -1918,18 +2393,30 @@ static void HandleReadPropertyMultipleAck(const uint8_t* apdu, size_t apduLength // Anything that is not an answer from the peer to one of our two reads is left to // the stack alone. static void HandleReplyFromPeer(const uint8_t* message, size_t messageLength, - const uint8_t fromIp[4], uint16_t fromPort) { - if (!g_peer.bound || memcmp(fromIp, g_peer.connectionString, 4) != 0 || - fromPort != (uint16_t)((g_peer.connectionString[4] << 8) | g_peer.connectionString[5])) { + const uint8_t* fromAddress, uint16_t fromPort) { + const uint8_t addressLength = TransportAddressLength(); + if (!g_peer.bound || memcmp(fromAddress, g_peer.connectionString, addressLength) != 0 || + fromPort != (uint16_t)((g_peer.connectionString[addressLength] << 8) | g_peer.connectionString[addressLength + 1])) { return; } - // BVLL (Annex J.2): 0x81, function, length[2]. Original-Unicast-NPDU only - the - // answer to a unicast request is unicast. - if (messageLength < 4 || message[0] != 0x81 || message[1] != 0x0A) { - return; + size_t position = 0; + if (g_options.dataLink == DataLink::IPv6) { + // BVLL-IPv6 (Annex U.2.2): 0x82, function 0x01, length[2], source VMAC[3], + // destination VMAC[3]: 10 octets. Original-Unicast-NPDU only - the answer + // to a unicast request is unicast. + if (messageLength < 10 || message[0] != 0x82 || message[1] != 0x01) { + return; + } + position = 10; + } else { + // BVLL (Annex J.2): 0x81, function, length[2]. Original-Unicast-NPDU only - + // the answer to a unicast request is unicast. + if (messageLength < 4 || message[0] != 0x81 || message[1] != 0x0A) { + return; + } + position = 4; } // NPDU (cl. 6.2): version 1, control, then the optional DNET/SNET fields. - size_t position = 4; if (messageLength < position + 2 || message[position] != 0x01) { return; } @@ -2004,42 +2491,100 @@ static void HandleReplyFromPeer(const uint8_t* message, size_t messageLength, } } -// --- The transport callbacks (this example owns its socket; see above) -------- -uint16_t CallbackReceiveMessage(uint8_t* message, const uint16_t maxMessageLength, - uint8_t* sourceConnectionString, uint8_t* sourceConnectionStringLength, - uint8_t* destinationConnectionString, uint8_t* destinationConnectionStringLength, - const uint8_t maxConnectionStringLength, uint32_t* networkPortInstance) { - (void)destinationConnectionString; - (void)destinationConnectionStringLength; - if (maxConnectionStringLength < 6) { +// --- The transport callbacks ------------------------------------------------- +// The stack calls these to receive and send whole BACnet messages on the active +// data link. BACnet/IP and BACnet/IPv6 use this example's own UDP socket; +// BACnet/SC hands the message to the hub connection (sc/ScNode). MS/TP is +// different: its engine moves OCTETS through the byte callbacks +// (mstp/MstpDataLink) and needs nothing here. + +// Receive one BACnet/IP or BACnet/IPv6 datagram. +static uint16_t ReceiveFromUdp(uint8_t* message, const uint16_t maxMessageLength, uint8_t* sourceConnectionString, + uint8_t* sourceConnectionStringLength, const uint8_t maxConnectionStringLength) { + const uint8_t addressLength = TransportAddressLength(); + const uint8_t connectionStringLength = TransportConnectionStringLength(); + if (maxConnectionStringLength < connectionStringLength) { return 0; } - uint8_t fromIp[4] = { 0, 0, 0, 0 }; + uint8_t fromAddress[16] = { 0 }; uint16_t fromPort = 0; - const uint16_t received = g_udp.Receive(message, maxMessageLength, fromIp, &fromPort); + const uint16_t received = g_options.dataLink == DataLink::IPv6 + ? g_udp6.Receive(message, maxMessageLength, fromAddress, &fromPort) + : g_udp.Receive(message, maxMessageLength, fromAddress, &fromPort); if (received == 0) { return 0; } - printf("RX %u bytes from %u.%u.%u.%u:%u (Network Port %u)", (unsigned)received, - fromIp[0], fromIp[1], fromIp[2], fromIp[3], (unsigned)fromPort, NETWORK_PORT_INSTANCE); + char fromText[64]; + uint8_t fromConnectionString[18] = { 0 }; + memcpy(fromConnectionString, fromAddress, addressLength); + fromConnectionString[addressLength] = (uint8_t)(fromPort >> 8); + fromConnectionString[addressLength + 1] = (uint8_t)(fromPort & 0xFF); + printf("RX %u bytes from %s (Network Port %u)", (unsigned)received, + AddressText(fromConnectionString, fromText, sizeof(fromText)), ActiveNetworkPortInstance()); CASExampleHelper::LogBacnetFrame(message, received); - memcpy(sourceConnectionString, fromIp, 4); - sourceConnectionString[4] = (uint8_t)(fromPort >> 8); - sourceConnectionString[5] = (uint8_t)(fromPort & 0xFF); - *sourceConnectionStringLength = 6; - *networkPortInstance = NETWORK_PORT_INSTANCE; + memcpy(sourceConnectionString, fromConnectionString, connectionStringLength); + *sourceConnectionStringLength = connectionStringLength; // Look at a COPY's worth of it (nothing here changes `message`), then hand the // same bytes to the stack, which does all of its normal processing. - HandleReplyFromPeer(message, received, fromIp, fromPort); + HandleReplyFromPeer(message, received, fromAddress, fromPort); return received; } -uint16_t CallbackSendMessage(const uint8_t* message, const uint16_t messageLength, - const uint8_t* connectionString, const uint8_t connectionStringLength, - const uint32_t networkPortInstance, const bool broadcast) { - if (networkPortInstance != NETWORK_PORT_INSTANCE) { +uint16_t CallbackReceiveMessage(uint8_t* message, const uint16_t maxMessageLength, + uint8_t* sourceConnectionString, uint8_t* sourceConnectionStringLength, + uint8_t* destinationConnectionString, uint8_t* destinationConnectionStringLength, + const uint8_t maxConnectionStringLength, uint32_t* networkPortInstance) { + (void)destinationConnectionString; + (void)destinationConnectionStringLength; + *networkPortInstance = ActiveNetworkPortInstance(); + switch (g_options.dataLink) { + case DataLink::IPv4: + case DataLink::IPv6: + return ReceiveFromUdp(message, maxMessageLength, sourceConnectionString, sourceConnectionStringLength, + maxConnectionStringLength); +#ifdef BBC_WITH_SC + case DataLink::SC: { + const uint16_t received = ScNode::ReceiveFromHub(message, maxMessageLength, sourceConnectionString, + sourceConnectionStringLength, maxConnectionStringLength); + if (received > 0) { + printf("RX %u bytes from the hub (Network Port %u)\n", (unsigned)received, SC_NETWORK_PORT_INSTANCE); + } + return received; + } +#endif + default: + return 0; // MS/TP: the engine receives through the byte callbacks + } +} + +// Send on BACnet/IPv6: to one peer, or - a broadcast - to the multicast group. +static uint16_t SendToUdp6(const uint8_t* message, const uint16_t messageLength, const uint8_t* connectionString, + const uint8_t connectionStringLength, const bool broadcast) { + char destinationText[64]; + // A BACnet/IPv6 broadcast carries no address (Annex U): the multicast group is + // this example's to choose, and it is the link-local FF02::BAC0. + if (broadcast || connectionString == NULL || connectionStringLength == 0) { + const uint16_t sent = g_udp6.SendMulticast(message, messageLength); + printf("TX %u bytes to [ff02::bac0]:%u (multicast broadcast) (Network Port %u)", (unsigned)sent, + (unsigned)g_udp6.GetLocalPort(), IPV6_NETWORK_PORT_INSTANCE); + CASExampleHelper::LogBacnetFrame(message, messageLength); + return sent; + } + if (connectionStringLength < 18) { return 0; } + const uint16_t port = (uint16_t)((connectionString[16] << 8) | connectionString[17]); + const uint16_t sent = g_udp6.Send(connectionString, port, message, messageLength); + printf("TX %u bytes to %s (Network Port %u)", (unsigned)sent, + AddressText(connectionString, destinationText, sizeof(destinationText)), IPV6_NETWORK_PORT_INSTANCE); + CASExampleHelper::LogBacnetFrame(message, messageLength); + return sent; +} + +// Send on BACnet/IP: to one peer, or - no address - to the local subnet broadcast. +static uint16_t SendToUdp(const uint8_t* message, const uint16_t messageLength, const uint8_t* connectionString, + const uint8_t connectionStringLength, const bool broadcast) { + char destinationText[64]; uint8_t destination[6]; bool isBroadcast = broadcast; if (connectionString == NULL || connectionStringLength == 0) { @@ -2053,19 +2598,129 @@ uint16_t CallbackSendMessage(const uint8_t* message, const uint16_t messageLengt } const uint16_t port = (uint16_t)((destination[4] << 8) | destination[5]); const uint16_t sent = g_udp.Send(destination, port, message, messageLength); - printf("TX %u bytes to %u.%u.%u.%u:%u%s (Network Port %u)", (unsigned)sent, - destination[0], destination[1], destination[2], destination[3], (unsigned)port, + printf("TX %u bytes to %s%s (Network Port %u)", (unsigned)sent, + AddressText(destination, destinationText, sizeof(destinationText)), isBroadcast ? " (broadcast)" : "", NETWORK_PORT_INSTANCE); CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; } -// The start-up / restart I-Am, to the local subnet broadcast. -static void SendIAmToLocalSubnet() { - uint8_t broadcastConn[6]; - LocalBroadcastConnString(broadcastConn); - BACnetStack_SendIAm(g_deviceInstance, broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, - true /*broadcast*/, 0 /*local network*/, NULL, 0); +uint16_t CallbackSendMessage(const uint8_t* message, const uint16_t messageLength, + const uint8_t* connectionString, const uint8_t connectionStringLength, + const uint32_t networkPortInstance, const bool broadcast) { + if (networkPortInstance != ActiveNetworkPortInstance()) { + return 0; + } + switch (g_options.dataLink) { + case DataLink::IPv4: + return SendToUdp(message, messageLength, connectionString, connectionStringLength, broadcast); + case DataLink::IPv6: + return SendToUdp6(message, messageLength, connectionString, connectionStringLength, broadcast); +#ifdef BBC_WITH_SC + case DataLink::SC: { + const uint16_t sent = ScNode::SendToHub(message, messageLength, connectionString, + connectionStringLength); + printf("TX %u bytes to the hub%s (Network Port %u)\n", (unsigned)messageLength, + broadcast ? " (broadcast)" : "", SC_NETWORK_PORT_INSTANCE); + return sent; + } +#endif + default: + // MS/TP: the engine sends through the byte callbacks. A message that + // arrives here was sent before the engine started (it starts on the + // first BACnetStack_Tick after the callbacks are registered), and there + // is no wire to put it on yet. + return 0; + } +} + +// BACnet/IPv6: the send functions need an 18-octet connection string even for a +// broadcast, so this passes the multicast group FF02::BAC0 on our UDP port. With +// broadcast=true the stack sends an Original-Broadcast-NPDU and hands it to the +// send callback with broadcast=true and NO connection string; SendToUdp6() +// multicasts it to FF02::BAC0. +static void Ipv6MulticastConnectionString(uint8_t connectionString[18]) { + static const uint8_t BACNET_IPV6_MULTICAST_GROUP[16] = { 0xFF, 0x02, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0xBA, 0xC0 }; + memcpy(connectionString, BACNET_IPV6_MULTICAST_GROUP, 16); + connectionString[16] = (uint8_t)(g_options.udpPort >> 8); + connectionString[17] = (uint8_t)(g_options.udpPort & 0xFF); +} + +// The start-up / restart I-Am, as a broadcast on the active data link. What +// "broadcast" means is the data link's: the local subnet broadcast address +// (BACnet/IP), the multicast group (BACnet/IPv6), station 255 (MS/TP), or the +// hub, which sends it on to every node (BACnet/SC). +static void SendIAmBroadcast() { + switch (g_options.dataLink) { + case DataLink::IPv4: { + uint8_t broadcastConnectionString[6]; + LocalBroadcastConnString(broadcastConnectionString); + BACnetStack_SendIAm(g_deviceInstance, broadcastConnectionString, sizeof(broadcastConnectionString), + NETWORK_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); + break; + } + case DataLink::IPv6: { + uint8_t multicastConnectionString[18]; + Ipv6MulticastConnectionString(multicastConnectionString); + BACnetStack_SendIAm(g_deviceInstance, multicastConnectionString, sizeof(multicastConnectionString), + IPV6_NETWORK_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); + break; + } + case DataLink::MSTP: + BACnetStack_SendIAm(g_deviceInstance, &MSTP_BROADCAST_MAC_ADDRESS, 1, MSTP_NETWORK_PORT_INSTANCE, + true /*broadcast*/, 0 /*local network*/, NULL, 0); + break; + case DataLink::SC: { +#ifdef BBC_WITH_SC + const std::string hubUri = ScNode::ConnectedHubUri(); + if (!hubUri.empty()) { // not connected yet: main() sends it when the hub connects + BACnetStack_SendIAm(g_deviceInstance, (const uint8_t*)hubUri.c_str(), (uint8_t)hubUri.size(), + SC_NETWORK_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); + } +#endif + break; + } + } +} + +// The start-up Who-Is (DM-DDB-A), as a broadcast on the active data link. On +// BACnet/IP, BACnet/IPv6 and BACnet/SC it goes to the local network only (DNET +// 0). On MS/TP it is GLOBAL (DNET 65535), so devices on the far side of an MS/TP +// to BACnet/IP router answer too: on an MS/TP trunk, the router is often the way +// to everything else. +static void SendWhoIsBroadcast() { + static const uint16_t GLOBAL_BROADCAST_NETWORK = 65535; + switch (g_options.dataLink) { + case DataLink::IPv4: { + uint8_t broadcastConnectionString[6]; + LocalBroadcastConnString(broadcastConnectionString); + BACnetStack_SendWhoIs(broadcastConnectionString, sizeof(broadcastConnectionString), NETWORK_PORT_INSTANCE, + true /*broadcast*/, 0, NULL, 0); + break; + } + case DataLink::IPv6: { + uint8_t multicastConnectionString[18]; + Ipv6MulticastConnectionString(multicastConnectionString); + BACnetStack_SendWhoIs(multicastConnectionString, sizeof(multicastConnectionString), + IPV6_NETWORK_PORT_INSTANCE, true /*broadcast*/, 0, NULL, 0); + break; + } + case DataLink::MSTP: + BACnetStack_SendWhoIs(&MSTP_BROADCAST_MAC_ADDRESS, 1, MSTP_NETWORK_PORT_INSTANCE, true /*broadcast*/, + GLOBAL_BROADCAST_NETWORK, NULL, 0); + break; + case DataLink::SC: { +#ifdef BBC_WITH_SC + const std::string hubUri = ScNode::ConnectedHubUri(); + if (!hubUri.empty()) { + BACnetStack_SendWhoIs((const uint8_t*)hubUri.c_str(), (uint8_t)hubUri.size(), + SC_NETWORK_PORT_INSTANCE, true /*broadcast*/, 0, NULL, 0); + } +#endif + break; + } + } } // ----------------------------------------------------------------------------- @@ -2101,52 +2756,132 @@ int main(int argc, char** argv) { } // --- Command line + version -------------------------------------------- - // --help / --version print and exit, so handle them before we bind a socket - // or touch the stack. - // The DeviceCommunicationControl / ReinitializeDevice password is the source - // constant DCC_PASSWORD, not a command-line option, so the help must not - // offer --dcc-password. - if (CASExampleHelper::HandleHelpAndVersionArgs(argc, argv, APP_NAME, APP_VERSION, - false, // no --dcc-password option - true)) { // help lists --deviceName - return 0; - } - const uint16_t port = CASExampleHelper::ParsePortArg(argc, argv, 47808); - g_deviceInstance = CASExampleHelper::ParseDeviceIdArg(argc, argv, g_deviceInstance); + // --help / --version print and exit, and a bad option is reported, before we + // open a socket or a serial port or touch the stack. command_line.cpp checks + // every option, including the ones that only make sense on another data link. + switch (ParseCommandLine(argc, argv, APP_NAME, APP_VERSION, &g_options)) { + case ParseResult::ExitSuccess: return 0; + case ParseResult::ExitError: return 1; + case ParseResult::Run: break; + } + g_deviceInstance = g_options.deviceInstance; + // --deviceName: a bad name warns and keeps the default (command_line.cpp lets it through). g_deviceName = CASExampleHelper::ParseDeviceNameArg(argc, argv, DEVICE_NAME); CASExampleHelper::ParseXmlLogArg(argc, argv); // --xml: dump every RX/TX frame as XML instead of one line (off by default) CASExampleHelper::PrintVersion(APP_NAME, APP_VERSION); - - // --- Bind the BACnet/IP socket ----------------------------------------- - // This example binds its own socket (g_udp, section 2e) rather than calling - // CASExampleHelper::SetupUDP(), so its receive callback can see the peer's - // answers to its reads. - if (!g_udp.Connect(port)) { - printf("Error: Failed to bind UDP port %u.\n", (unsigned)port); + printf("FYI: Data link: %s (Network Port %u). Run with --help for the others.\n", + DataLinkName(g_options.dataLink), ActiveNetworkPortInstance()); + +#ifndef BBC_WITH_SC + // This executable was built without BACnet/SC: CMake did not find + // libwebsockets, OpenSSL and zlib. Say how to get them, rather than failing + // somewhere obscure. + if (g_options.dataLink == DataLink::SC) { + printf("Error: this build does not include BACnet/SC (--datalink sc).\n" + " BACnet/SC needs libwebsockets, OpenSSL and zlib. Rebuild with them, e.g. on Windows\n" + " with vcpkg (Visual Studio ships one - run from a Developer PowerShell):\n" + " cmake -B build -S . (VCPKG_ROOT set: vcpkg.json's libraries are installed)\n" + " cmake --build build --config Release\n" + " On Linux: sudo apt install libwebsockets-dev libssl-dev zlib1g-dev, then the same two\n" + " commands. CMake prints \"B-BC: BACnet/SC is built\" when it found them.\n" + " See \"Building with BACnet/SC\" in README.md.\n"); return 1; } - printf("FYI: Listening for BACnet/IP on UDP port %u (Network Port %u).\n", - (unsigned)port, NETWORK_PORT_INSTANCE); +#else + // --import-cari: install a Certificate Authority's response and stop. The + // next start runs with the new certificate. + if (!g_options.importCariZip.empty()) { + return ScNode::ImportCari(g_options.scCertificateDirectory, g_deviceInstance, g_options.importCariZip); + } +#endif - // Capture the BACnet/IP addressing the Network Port object will report. - g_bacnetIpUdpPort = port; - if (!CASExampleHelper::GetLocalIPv4(g_ipAddress, g_ipSubnetMask)) { - printf("FYI: could not read a local IPv4 address; Network Port IP_Address " - "will report 0.0.0.0.\n"); + // --- Open the data link ------------------------------------------------ + // Only the chosen data link is opened. This example owns each one itself: + // its own UDP socket for BACnet/IP and BACnet/IPv6 (rather than calling + // CASExampleHelper::SetupUDP(), so its receive callback can see the peer's + // answers to its reads - section 2e), the serial port for MS/TP, and the + // hub connection for BACnet/SC. + g_bacnetIpUdpPort = g_options.udpPort; + if (g_options.dataLink == DataLink::IPv4) { + if (!g_udp.Connect(g_options.udpPort)) { + printf("Error: Failed to bind UDP port %u.\n", (unsigned)g_options.udpPort); + return 1; + } + printf("FYI: Listening for BACnet/IP on UDP port %u (Network Port %u).\n", + (unsigned)g_options.udpPort, NETWORK_PORT_INSTANCE); + // Capture the BACnet/IP addressing the Network Port object will report. + if (!CASExampleHelper::GetLocalIPv4(g_ipAddress, g_ipSubnetMask)) { + printf("FYI: could not read a local IPv4 address; Network Port IP_Address " + "will report 0.0.0.0.\n"); + } } - double linkSpeedBitsPerSecond = 0.0; - if (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond(&linkSpeedBitsPerSecond)) { - g_linkSpeedBitsPerSecond = (float)linkSpeedBitsPerSecond; - } else { - printf("FYI: could not determine the local link speed; Network Port " - "Link_Speed will report 0.0 (indeterminable).\n"); + if (g_options.dataLink == DataLink::IPv6) { + // --interface : join the multicast group on one interface only (0 = every + // IPv6 interface that is up). + if (!g_udp6.Connect(g_options.udpPort, g_options.ipv6InterfaceIndex)) { + printf("Error: Failed to bind UDP port %u over IPv6.\n", (unsigned)g_options.udpPort); + return 1; + } + printf("FYI: Listening for BACnet/IPv6 on UDP port %u (Network Port %u); joined the multicast group " + "FF02::BAC0 on %u interface(s).\n", + (unsigned)g_options.udpPort, IPV6_NETWORK_PORT_INSTANCE, (unsigned)g_udp6.GetJoinedInterfaceCount()); + // The IPv6 Network Port reports the host's address, prefix length and + // default gateway (section 1b). + if (GetLocalIPv6Address(g_options.ipv6InterfaceIndex, &g_ipv6Address)) { + char addressText[64]; + printf("FYI: IPv6 address %s/%u (Network Port %u IPv6_Address)\n", + FormatIPv6Address(g_ipv6Address.address, addressText, sizeof(addressText)), + (unsigned)g_ipv6Address.prefixLength, IPV6_NETWORK_PORT_INSTANCE); + } else { + printf("FYI: could not read a local IPv6 address; Network Port IPv6_Address will report ::.\n"); + } + } + if (g_options.dataLink == DataLink::IPv6 && g_ipv6Address.linkSpeedBitsPerSecond > 0.0) { + // The speed of the interface the IPv6 address came from (Windows). + g_linkSpeedBitsPerSecond = (float)g_ipv6Address.linkSpeedBitsPerSecond; + } else if (g_options.dataLink == DataLink::IPv4 || g_options.dataLink == DataLink::IPv6) { + // On POSIX the IPv6 port falls back to this too: the IPv4 helper's + // primary interface, which may not be the IPv6 one. + double linkSpeedBitsPerSecond = 0.0; + if (CASExampleHelper::GetLocalLinkSpeedBitsPerSecond(&linkSpeedBitsPerSecond)) { + g_linkSpeedBitsPerSecond = (float)linkSpeedBitsPerSecond; + } else { + printf("FYI: could not determine the local link speed; Network Port " + "Link_Speed will report 0.0 (indeterminable).\n"); + } + } + if (g_options.dataLink == DataLink::MSTP) { + if (!MstpDataLink::Open(g_options.mstpPortName.c_str(), g_options.mstpBaudRate)) { + return 1; // the reason has been printed + } + printf("FYI: MS/TP on %s at %u baud, MAC %u, Max_Master %u, Max_Info_Frames %u (Network Port %u).\n", + g_options.mstpPortName.c_str(), g_options.mstpBaudRate, (unsigned)g_options.mstpMacAddress, + (unsigned)g_options.mstpMaxMaster, (unsigned)g_options.mstpMaxInfoFrames, + MSTP_NETWORK_PORT_INSTANCE); +#if defined(_WIN32) + // MS/TP's timers are a few milliseconds long, and the main loop sleeps + // 1 ms per pass. Windows' default timer tick is 15.6 ms, which would make + // that sleep 15 ms and the station miss its token. timeBeginPeriod(1) + // asks for a 1 ms tick for as long as the program runs. + timeBeginPeriod(1); +#endif } +#ifdef BBC_WITH_SC + if (g_options.dataLink == DataLink::SC) { + // The certificates come first. Without an operational certificate there + // is nothing to connect with: the request zip has been made and how to go + // on has been printed. + if (!ScNode::PrepareCertificates(g_options.scCertificateDirectory, g_deviceInstance, g_deviceName)) { + return 1; + } + } +#endif // --- Register callbacks ------------------------------------------------- // The time callback is shared boilerplate (RegisterCommonCallbacks also // registers the helper's transport callbacks; the two calls after it replace - // those with this example's own, which name NETWORK_PORT_INSTANCE - the stack - // identifies a link by its Network Port INSTANCE). + // those with this example's own, which name the active data link's Network + // Port - the stack identifies a link by its Network Port INSTANCE). CASExampleHelper::RegisterCommonCallbacks(); BACnetStack_RegisterCallbackReceiveMessageForPort(CallbackReceiveMessage); BACnetStack_RegisterCallbackSendMessageForPort(CallbackSendMessage); @@ -2181,6 +2916,14 @@ int main(int argc, char** argv) { BACnetStack_RegisterCallbackCompleteBackup(CompleteBackup); BACnetStack_RegisterCallbackPrepareRestore(PrepareRestore); BACnetStack_RegisterCallbackCompleteRestore(CompleteRestore); + // The Network Port Command property (DISCARD_CHANGES, and GENERATE_CSR_FILE + // on the BACnet/SC port). + BACnetStack_RegisterCallbackNetworkPortCommand(NetworkPortCommand); + // MS/TP: the engine's byte callbacks. From the first BACnetStack_Tick() after + // the MS/TP Network Port exists, the stack runs the token ring itself. + if (g_options.dataLink == DataLink::MSTP) { + MstpDataLink::RegisterCallbacks(); + } // --- Create the device -------------------------------------------------- if (!BACnetStack_AddDevice(g_deviceInstance)) { @@ -2276,7 +3019,12 @@ int main(int argc, char** argv) { // networkNumber 0 with quality "unknown" describes a local port that has not // learned its network number - the right answer for a device that is not a // router and has not been told one. - if (!BACnetStack_AddNetworkPortObject( + // + // ONE Network Port, the active data link's (section 1b). The stack serves its + // Network_Type-specific properties and asks the Get callbacks for the values + // only the application knows. + if (g_options.dataLink == DataLink::IPv4 && + !BACnetStack_AddNetworkPortObject( g_deviceInstance, NETWORK_PORT_INSTANCE, NETWORK_PORT_NETWORK_TYPE_IPV4, NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION, @@ -2286,6 +3034,48 @@ int main(int argc, char** argv) { printf("Error: Failed to add Network Port 1 (Vermilion).\n"); return 1; } + // BACnet/IPv6: IPv6_Address, IPv6_Prefix_Length, BACnet_IPv6_UDP_Port and + // IPv6_Default_Gateway come from the Get callbacks; MAC_Address (the 3-octet + // VMAC, from the device instance) and the multicast address from the stack. + if (g_options.dataLink == DataLink::IPv6 && + !BACnetStack_AddNetworkPortObject(g_deviceInstance, IPV6_NETWORK_PORT_INSTANCE, + NETWORK_PORT_NETWORK_TYPE_IPV6, + NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION, 0, + NETWORK_NUMBER_QUALITY_UNKNOWN, NETWORK_PORT_REFERENCE_PORT_NONE)) { + printf("Error: Failed to add Network Port %u (Cerulean).\n", IPV6_NETWORK_PORT_INSTANCE); + return 1; + } + // MS/TP: MAC_Address, Max_Master, Max_Info_Frames and Link_Speed (the baud + // rate) come from the Get callbacks - and the MS/TP engine reads its own + // settings from them too. + if (g_options.dataLink == DataLink::MSTP && + !BACnetStack_AddNetworkPortObject(g_deviceInstance, MSTP_NETWORK_PORT_INSTANCE, + NETWORK_PORT_NETWORK_TYPE_MSTP, + NETWORK_PORT_PROTOCOL_LEVEL_BACNET_APPLICATION, 0, + NETWORK_NUMBER_QUALITY_UNKNOWN, NETWORK_PORT_REFERENCE_PORT_NONE)) { + printf("Error: Failed to add Network Port %u (Amber).\n", MSTP_NETWORK_PORT_INSTANCE); + return 1; + } + // Link_Speed is OPTIONAL on the stack's BACnet/IPv6 and MS/TP Network Ports: + // without this a read answers unknown-property and the Get callback is never + // asked. (On MS/TP it is the baud rate; checked through an MS/TP router.) + if (g_options.dataLink == DataLink::IPv6 || g_options.dataLink == DataLink::MSTP) { + const uint32_t dataLinkPortInstance = ActiveNetworkPortInstance(); + if (!BACnetStack_SetPropertyEnabled(g_deviceInstance, OBJECT_TYPE_NETWORK_PORT, dataLinkPortInstance, + PROPERTY_IDENTIFIER_LINK_SPEED, true)) { + printf("Error: Failed to enable Link_Speed on Network Port %u.\n", dataLinkPortInstance); + return 1; + } + } +#ifdef BBC_WITH_SC + // BACnet/SC: the port, its hubs, its timers and its certificate Files 2-5 - + // sc/ScNode.cpp has the order the stack needs them in. + if (g_options.dataLink == DataLink::SC && + !ScNode::AddNetworkPort(g_deviceInstance, SC_NETWORK_PORT_INSTANCE, g_options.scPrimaryHubUri, + g_options.scFailoverHubUri)) { + return 1; // the reason has been printed + } +#endif // --- Enable the OPTIONAL properties we choose to expose ------------------ // The stack automatically enables an object's REQUIRED properties when the @@ -2394,30 +3184,37 @@ int main(int argc, char** argv) { // by ADDRESS (the form the stack can actually send to). The MAC is the // BACnet/IP recipient: four IP octets followed by the two-octet UDP port. // validDays 0x7F = every day; the time window 00:00:00 - 23:59:59 = always. - uint8_t recipientMac[6]; - if (RECIPIENT_USE_BROADCAST) { - LocalBroadcastConnString(recipientMac); - } else { - memcpy(recipientMac, RECIPIENT_IP, 4); - recipientMac[4] = (uint8_t)(g_bacnetIpUdpPort >> 8); - recipientMac[5] = (uint8_t)(g_bacnetIpUdpPort & 0xFF); - } - const uint8_t validDaysAll = 0x7F; - if (!BACnetStack_AddRecipientToNotificationClass( - g_deviceInstance, NOTIFICATION_CLASS_INSTANCE, - validDaysAll, - 0, 0, 0, 0, // from 00:00:00.00 - 23, 59, 59, 99, // to 23:59:59.99 - RECIPIENT_PROCESS_IDENTIFIER, - false, // issue UNCONFIRMED notifications (works to a broadcast) - true, true, true, // notify on to-offnormal, to-fault, to-normal - false, 0, // NOT using the device choice - true, // use the ADDRESS choice - 0, // network number 0 = this local network - recipientMac, sizeof(recipientMac))) { - printf("Error: could not seed the Notification Class recipient (Crimson).\n"); - return 1; - } + // + // BACnet/IP only. On the other data links Notification Class 1 starts with + // an EMPTY Recipient_List, and a management station writes one (it is + // writable, below) - the address form of a recipient is the data link's own + // MAC, and a broadcast recipient means something different on each. + if (g_options.dataLink == DataLink::IPv4) { + uint8_t recipientMac[6]; + if (RECIPIENT_USE_BROADCAST) { + LocalBroadcastConnString(recipientMac); + } else { + memcpy(recipientMac, RECIPIENT_IP, 4); + recipientMac[4] = (uint8_t)(g_bacnetIpUdpPort >> 8); + recipientMac[5] = (uint8_t)(g_bacnetIpUdpPort & 0xFF); + } + const uint8_t validDaysAll = 0x7F; + if (!BACnetStack_AddRecipientToNotificationClass( + g_deviceInstance, NOTIFICATION_CLASS_INSTANCE, + validDaysAll, + 0, 0, 0, 0, // from 00:00:00.00 + 23, 59, 59, 99, // to 23:59:59.99 + RECIPIENT_PROCESS_IDENTIFIER, + false, // issue UNCONFIRMED notifications (works to a broadcast) + true, true, true, // notify on to-offnormal, to-fault, to-normal + false, 0, // NOT using the device choice + true, // use the ADDRESS choice + 0, // network number 0 = this local network + recipientMac, sizeof(recipientMac))) { + printf("Error: could not seed the Notification Class recipient (Crimson).\n"); + return 1; + } + } // BACnet/IP only // 4) Turn on intrinsic event reporting for Diamond, routed through Crimson. if (!BACnetStack_SetAlarmsAndEventsForObjectEnabled( @@ -2706,18 +3503,44 @@ int main(int argc, char** argv) { // Who-Is is answered automatically. The spec also requires a device to // announce itself on start-up, so broadcast an unsolicited I-Am now (to the - // local subnet broadcast - the Network Port's own network). - SendIAmToLocalSubnet(); - - // A B-BC must also be able to DISCOVER other devices (DM-DDB-A), so broadcast - // a Who-Is on start-up - every device on the subnet answers with its I-Am. - uint8_t broadcastConn[6]; - LocalBroadcastConnString(broadcastConn); - BACnetStack_SendWhoIs(broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, - true /*broadcast*/, 0, NULL, 0); + // Network Port's own network). A B-BC must also be able to DISCOVER other + // devices (DM-DDB-A), so broadcast a Who-Is too - every device that hears it + // answers with its I-Am. + // + // NOW on BACnet/IP and BACnet/IPv6. LATER on the other two, which have no + // wire to send on yet: + // MS/TP - the engine starts on the first BACnetStack_Tick(), and a + // station may only send while it holds the token. Sent once it + // has joined the token ring (or after MSTP_ANNOUNCE_TIMEOUT). + // BACnet/SC - every message goes through the hub. Sent once the hub + // connection is up (and again after a reconnect). + bool announcementPending = true; + const std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now(); + static const uint32_t MSTP_ANNOUNCE_TIMEOUT_MILLISECONDS = 10000; + static const uint32_t MSTP_STATUS_INTERVAL_MILLISECONDS = 10000; + std::chrono::steady_clock::time_point lastMstpStatus = startTime; + static const uint32_t MSTP_TOKEN_RING_SNAPSHOT_MILLISECONDS = 60000; + bool wasInTokenRing = false; + bool tokenRingSnapshotPending = false; + std::chrono::steady_clock::time_point joinedTokenRingTime = startTime; + if (IsIpDataLink()) { + SendIAmBroadcast(); + SendWhoIsBroadcast(); + announcementPending = false; + } printf("FYI: Device %u (\"%s\") ready. Vendor ID %u. Press 'h' for help.\n", g_deviceInstance, g_deviceName, VENDOR_IDENTIFIER); + // The tutorial ships with no password so every client can try the + // DM-DCC-B / DM-RD-B services. Say so, every start: on BACnet/SC that + // password is all that stands between any peer on the hub and rewriting + // and activating this device's certificate Files. + if (DCC_PASSWORD == NULL || DCC_PASSWORD[0] == '\0') { + printf("Warning: no DeviceCommunicationControl / ReinitializeDevice password (DCC_PASSWORD in main.cpp " + "is empty): any BACnet client can silence or restart this device%s. Set one before using it " + "outside a test bench.\n", + g_options.dataLink == DataLink::SC ? ", or replace and activate its BACnet/SC certificates" : ""); + } // --- Run the stack ------------------------------------------------------ // BACnetStack_Tick() processes incoming messages and timers. Call it @@ -2726,8 +3549,63 @@ int main(int argc, char** argv) { while (running) { BACnetStack_Tick(); + // --- The data link's own work ----------------------------------------- + if (g_options.dataLink == DataLink::MSTP) { + // Run the MS/TP engine. It must run at least every few milliseconds - + // the token, and every reply, is timed. This loop sleeps 1 ms a pass. + MstpDataLink::Loop(MSTP_NETWORK_PORT_INSTANCE); + const bool inTokenRing = MstpDataLink::IsInTokenRing(MSTP_NETWORK_PORT_INSTANCE); + if (announcementPending && + (inTokenRing || MillisecondsSince(startTime) > MSTP_ANNOUNCE_TIMEOUT_MILLISECONDS)) { + printf("MS/TP: %s - sending the start-up I-Am and Who-Is.\n", + inTokenRing ? "in the token ring" : "no token ring yet"); + SendIAmBroadcast(); + SendWhoIsBroadcast(); + announcementPending = false; + } + // Joining or leaving the token ring is worth a line with the + // counters - and so is one more look a minute after joining, which + // shows the token keeps coming round (frames sent and heard climb). + if (inTokenRing != wasInTokenRing) { + wasInTokenRing = inTokenRing; + printf("MS/TP: %s the token ring.\n", inTokenRing ? "joined" : "LEFT"); + MstpDataLink::PrintCounters(MSTP_NETWORK_PORT_INSTANCE); + if (inTokenRing) { + joinedTokenRingTime = std::chrono::steady_clock::now(); + tokenRingSnapshotPending = true; + } + } + if (inTokenRing && tokenRingSnapshotPending && + MillisecondsSince(joinedTokenRingTime) > MSTP_TOKEN_RING_SNAPSHOT_MILLISECONDS) { + tokenRingSnapshotPending = false; + printf("MS/TP: one minute in the token ring:\n"); + MstpDataLink::PrintCounters(MSTP_NETWORK_PORT_INSTANCE); + } + // While the station has not found the token ring, say what the + // engine sees, so a wrong baud rate or wiring is easy to spot. + if (!inTokenRing && MillisecondsSince(lastMstpStatus) > MSTP_STATUS_INTERVAL_MILLISECONDS) { + lastMstpStatus = std::chrono::steady_clock::now(); + printf("MS/TP: not in a token ring yet:\n"); + MstpDataLink::PrintCounters(MSTP_NETWORK_PORT_INSTANCE); + } + } +#ifdef BBC_WITH_SC + if (g_options.dataLink == DataLink::SC) { + // Move WebSocket frames, and tell the stack about connection changes. + ScNode::Service(); + if (ScNode::TakeHubConnectedEvent()) { + printf("BACnet/SC: connected to the hub %s - sending I-Am and Who-Is.\n", + ScNode::ConnectedHubUri().c_str()); + SendIAmBroadcast(); + SendWhoIsBroadcast(); + announcementPending = false; + } + } +#endif + // DS-RP-A / DS-RPM-A: read the peer's sensor when a poll is due, and - // notice when it has gone quiet (section 2e). + // notice when it has gone quiet (section 2e). BACnet/IP and BACnet/IPv6 + // only (HookIAm binds the peer only there). PollPeer(); // --- Deferred restart (DM-RD-B) ------------------------------------- @@ -2767,7 +3645,7 @@ int main(int argc, char** argv) { // Both kinds re-announce: a restarted device must issue an I-Am so // clients that had it bound learn it is back (and re-bind if its // address changed). - SendIAmToLocalSubnet(); + SendIAmBroadcast(); printf("Restart: complete. Device %u is back.\n", g_deviceInstance); } @@ -2815,6 +3693,14 @@ int main(int argc, char** argv) { } break; } + case CASExampleHelper::KeyCommand::Metrics: + // 'm': the MS/TP engine's counters (frames, tokens, errors). + if (g_options.dataLink == DataLink::MSTP) { + MstpDataLink::PrintCounters(MSTP_NETWORK_PORT_INSTANCE); + } else { + printf("'m' shows the MS/TP counters (--datalink mstp).\n"); + } + break; case CASExampleHelper::KeyCommand::None: default: break; @@ -2829,5 +3715,12 @@ int main(int argc, char** argv) { CASExampleHelper::RestoreInput(); g_udp.Disconnect(); + g_udp6.Disconnect(); + if (g_options.dataLink == DataLink::MSTP) { + MstpDataLink::Close(); +#if defined(_WIN32) + timeEndPeriod(1); +#endif + } return 0; } diff --git a/mstp/MstpDataLink.cpp b/mstp/MstpDataLink.cpp new file mode 100644 index 0000000..91ba2cc --- /dev/null +++ b/mstp/MstpDataLink.cpp @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// MstpDataLink.cpp - see MstpDataLink.h. + +#include "MstpDataLink.h" + +#include "CASBACnetStackAdapter.h" +#include "SimpleSerial.h" + +#include +#include + +namespace MstpDataLink { +namespace { + +// This example has one MS/TP port, so one serial port. +SimpleSerial g_serialPort; + +// The stack calls this from BACnetStack_LoopMSTP() to take the octets the UART +// has received. It must not block, and SimpleSerial::Read() does not. +uint16_t CallbackReceiveBytes(const uint32_t networkPortInstance, uint8_t* buffer, const uint16_t maxLength) { + (void)networkPortInstance; // there is only one MS/TP port + return (uint16_t)g_serialPort.Read(buffer, maxLength); +} + +// One complete MS/TP frame. The stack releases the RS-485 driver as soon as this +// returns, so it must not return until the frame has gone out - Write() waits +// for the driver to report the last octet sent. +bool CallbackSendBytes(const uint32_t networkPortInstance, const uint8_t* buffer, const uint16_t length) { + (void)networkPortInstance; + return g_serialPort.Write(buffer, length); +} + +// The MS/TP timers (Tframe_abort, Tno_token, Tusage_timeout, Treply_delay ...) +// run on this clock: microseconds from any fixed point, wrapping at 2^32 (the +// engine subtracts readings with unsigned arithmetic, so the wrap is harmless). +// steady_clock never jumps when the wall clock is changed. +uint32_t CallbackMicroseconds() { + static const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); + return (uint32_t)std::chrono::duration_cast( + std::chrono::steady_clock::now() - start).count(); +} + +uint32_t Counter(const uint32_t counters[BACnetMSTPCounter_Count], BACnetMSTPCounter which) { + return counters[which]; +} + +} // namespace + +bool Open(const char* portName, const uint32_t baudRate) { + if (!g_serialPort.Open(portName, baudRate)) { + printf("Error: MS/TP: %s\n", g_serialPort.GetLastErrorText()); + return false; + } + printf("FYI: MS/TP: serial port %s open at %u baud, 8N1.\n", portName, (unsigned)baudRate); + return true; +} + +void RegisterCallbacks() { + // All three are needed for byte mode; registering them is all it takes. + BACnetStack_RegisterCallbackMSTPReceiveBytes(CallbackReceiveBytes); + BACnetStack_RegisterCallbackMSTPSendBytes(CallbackSendBytes); + BACnetStack_RegisterCallbackMSTPMicroseconds(CallbackMicroseconds); +} + +void Loop(const uint32_t networkPortInstance) { + BACnetStack_LoopMSTP(networkPortInstance); +} + +bool IsInTokenRing(const uint32_t networkPortInstance) { + uint32_t counters[BACnetMSTPCounter_Count] = { 0 }; + return BACnetStack_GetMSTPCounters(networkPortInstance, counters, BACnetMSTPCounter_Count) && + Counter(counters, BACnetMSTPCounter_InTokenRing) == 1; +} + +void PrintCounters(const uint32_t networkPortInstance) { + uint32_t counters[BACnetMSTPCounter_Count] = { 0 }; + if (!BACnetStack_GetMSTPCounters(networkPortInstance, counters, BACnetMSTPCounter_Count)) { + printf("MS/TP: the engine has not started yet (it starts on the first tick).\n"); + return; + } + // LastFrameType is 255 until a valid frame header has been heard. + const uint32_t lastFrameType = Counter(counters, BACnetMSTPCounter_LastFrameType); + printf("MS/TP: %s; frames heard %u (for us %u), sent %u, dropped %u; octets lost %u; NPDUs received %u; " + "last frame type %u from %u to %u\n", + Counter(counters, BACnetMSTPCounter_InTokenRing) ? "IN the token ring" : "NOT in the token ring", + Counter(counters, BACnetMSTPCounter_FramesHeard), Counter(counters, BACnetMSTPCounter_FramesForThisStation), + Counter(counters, BACnetMSTPCounter_FramesSent), Counter(counters, BACnetMSTPCounter_FramesDropped), + Counter(counters, BACnetMSTPCounter_BytesLost), Counter(counters, BACnetMSTPCounter_NpdusDelivered), + lastFrameType, Counter(counters, BACnetMSTPCounter_LastFrameSource), + Counter(counters, BACnetMSTPCounter_LastFrameDestination)); +} + +void Close() { + // Byte mode ends when any of the three callbacks is cleared. + BACnetStack_RegisterCallbackMSTPReceiveBytes(NULL); + g_serialPort.Close(); +} + +} // namespace MstpDataLink diff --git a/mstp/MstpDataLink.h b/mstp/MstpDataLink.h new file mode 100644 index 0000000..c32ef00 --- /dev/null +++ b/mstp/MstpDataLink.h @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef BBC_EXAMPLE_MSTP_DATA_LINK_H +#define BBC_EXAMPLE_MSTP_DATA_LINK_H + +// MstpDataLink.h +// ============================================================================= +// --datalink mstp: BACnet MS/TP (ANSI/ASHRAE 135-2024 clause 9) on an RS-485 +// serial port, with the CAS BACnet Stack running the MS/TP state machines. +// +// The stack's "byte mode" (see "Stack-owned MS/TP" in CASBACnetStackDLL.h) does +// the hard part - framing, CRCs, token passing, Poll For Master, replies - and +// the application only moves octets. Four callbacks connect it to the port: +// +// ReceiveBytes hand the stack the octets the UART has received (never block) +// SendBytes write one whole frame, and return only once it has been sent +// Microseconds a free-running microsecond clock (the MS/TP timers run on it) +// (TransmitEnable, for an RS-485 driver the application switches itself, is +// not needed: USB-to-RS-485 adapters switch theirs in hardware.) +// +// and one call: BACnetStack_LoopMSTP(port), at least every few milliseconds. +// +// The engine's settings (MAC address, Max_Master, Max_Info_Frames, baud rate) +// are NOT passed here: the stack reads them from the MS/TP Network Port object +// through the ordinary property callbacks - see main.cpp's Get callbacks. +// ============================================================================= + +#include + +namespace MstpDataLink { + +// Opens the serial port. False (with the reason printed) if it cannot. +bool Open(const char* portName, uint32_t baudRate); + +// Registers the stack's MS/TP byte callbacks. From the next BACnetStack_Tick() +// on, the MS/TP Network Port is in byte mode. +void RegisterCallbacks(); + +// Runs the engine once: call it from the main loop at least every few ms. +void Loop(uint32_t networkPortInstance); + +// True while this station holds a place in the token ring (it has heard the +// token and found a successor to pass it to). +bool IsInTokenRing(uint32_t networkPortInstance); + +// Prints the engine's counters, one line (the 'm' key, and every 10 s while +// the station is still looking for the token ring). +void PrintCounters(uint32_t networkPortInstance); + +void Close(); + +} // namespace MstpDataLink + +#endif // BBC_EXAMPLE_MSTP_DATA_LINK_H diff --git a/sc/KeyPassword.cpp b/sc/KeyPassword.cpp new file mode 100644 index 0000000..8555798 --- /dev/null +++ b/sc/KeyPassword.cpp @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// KeyPassword.cpp - see KeyPassword.h. + +#include "KeyPassword.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#include +#include +#endif + +namespace CASSc { +namespace KeyPassword { + +namespace { + +// The password for the whole run. A std::string that is never reassigned after +// Prepare(), so the c_str() handed to libwebsockets stays valid. +std::string g_password; +bool g_hasPassword = false; + +// How many times a wrong password may be typed before the device gives up asking. +const int kMaxAttempts = 3; + +std::string ReadFileText(const std::string& path) { + std::ifstream file(path, std::ios::binary); + if (!file) { + return ""; + } + std::ostringstream text; + text << file.rdbuf(); + return text.str(); +} + +// Tries the password on the key: true when it decrypts it. +bool Unlocks(const std::string& keyText, const std::string& password) { + BIO* bio = BIO_new_mem_buf(keyText.data(), static_cast(keyText.size())); + if (bio == nullptr) { + return false; + } + // The password is passed as the callback's userdata: PEM_read_bio_PrivateKey + // treats a non-null u with a null callback as the passphrase itself. + EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, const_cast(password.c_str())); + BIO_free(bio); + if (key == nullptr) { + return false; + } + EVP_PKEY_free(key); + return true; +} + +// Reads one line from the console with the typing hidden. +bool ReadHiddenLine(std::string* line) { +#ifdef _WIN32 + HANDLE input = GetStdHandle(STD_INPUT_HANDLE); + DWORD mode = 0; + const bool isConsole = input != INVALID_HANDLE_VALUE && GetConsoleMode(input, &mode); + if (isConsole) { + SetConsoleMode(input, mode & ~ENABLE_ECHO_INPUT); + } + const bool ok = static_cast(std::getline(std::cin, *line)); + if (isConsole) { + SetConsoleMode(input, mode); + } +#else + termios previous{}; + const bool isTerminal = isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &previous) == 0; + if (isTerminal) { + termios hidden = previous; + hidden.c_lflag &= ~static_cast(ECHO); + tcsetattr(STDIN_FILENO, TCSANOW, &hidden); + } + const bool ok = static_cast(std::getline(std::cin, *line)); + if (isTerminal) { + tcsetattr(STDIN_FILENO, TCSANOW, &previous); + } +#endif + std::printf("\n"); + std::fflush(stdout); + if (!line->empty() && line->back() == '\r') { + line->pop_back(); + } + return ok; +} + +} // namespace + +bool IsEncryptedKeyFile(const std::string& keyPath) { + const std::string text = ReadFileText(keyPath); + return text.find("BEGIN ENCRYPTED PRIVATE KEY") != std::string::npos || + text.find("Proc-Type: 4,ENCRYPTED") != std::string::npos; +} + +bool Prepare(const std::string& keyPath, std::string* message) { + const std::string keyText = ReadFileText(keyPath); + if (keyText.empty() || !IsEncryptedKeyFile(keyPath)) { + // No key yet (the "certificates missing" check reports that), or not + // encrypted: nothing to ask for. + return true; + } + + for (int attempt = 1; attempt <= kMaxAttempts; attempt++) { + std::printf("The private key \"%s\" is password protected.\nEnter its password (it is kept in memory " + "only, and asked for once): ", keyPath.c_str()); + std::fflush(stdout); + std::string typed; + if (!ReadHiddenLine(&typed)) { + break; // input closed + } + if (Unlocks(keyText, typed)) { + g_password = typed; + g_hasPassword = true; + return true; + } + std::printf("That password does not unlock the key%s\n", attempt < kMaxAttempts ? ". Try again." : "."); + } + if (message != nullptr) { + *message = "no password that unlocks the private key \"" + keyPath + "\" was entered. BACnet/SC can't start " + "until the device is restarted and the right password is typed."; + } + return false; +} + +const char* Get() { + return g_hasPassword ? g_password.c_str() : nullptr; +} + +int PemCallback(char* buffer, int size, int /*rwflag*/, void* /*userdata*/) { + if (!g_hasPassword || buffer == nullptr || size <= 0) { + return 0; + } + const int length = static_cast(g_password.size()); + if (length >= size) { + return 0; + } + std::memcpy(buffer, g_password.data(), static_cast(length)); + buffer[length] = '\0'; + return length; +} + +} // namespace KeyPassword +} // namespace CASSc diff --git a/sc/KeyPassword.h b/sc/KeyPassword.h new file mode 100644 index 0000000..fdd04f4 --- /dev/null +++ b/sc/KeyPassword.h @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// KeyPassword.h - the password for this device's private key, asked for once. +// +// A certificate package can hold a password-protected (encrypted) private key. +// Left to itself, OpenSSL asks for the password on the console every time +// something loads the key: the start-up certificate check, the hub connection, +// and every listener restart. +// +// Prepare() is called once at start-up. For an encrypted key it asks on the +// console, with the typing hidden, checks the password by decrypting the key +// (asking again if it's wrong), and keeps it in memory for the rest of the run. +// Everything that loads the key then gets it from here: libwebsockets through +// Get(), OpenSSL's PEM readers through PemCallback(). PemCallback() never +// prompts, so OpenSSL can't ask on its own. + +#pragma once + +#include + +namespace CASSc { +namespace KeyPassword { + +// True when the PEM file holds an encrypted private key +// ("BEGIN ENCRYPTED PRIVATE KEY", or a legacy "Proc-Type: 4,ENCRYPTED" key). +bool IsEncryptedKeyFile(const std::string& keyPath); + +// Call once, before anything loads the key. Returns false, with a reason in +// *message, when the key is encrypted and no working password was typed; the +// device then starts without BACnet/SC credentials and logs why, as for any +// unusable key. +bool Prepare(const std::string& keyPath, std::string* message); + +// The password Prepare() settled on, or nullptr when the key isn't encrypted +// (or none was given). Stays valid for the life of the process - libwebsockets +// keeps the pointer. +const char* Get(); + +// An OpenSSL pem_password_cb: copies the password Prepare() settled on. Never +// prompts; returns 0 (no password) when there is none. +int PemCallback(char* buffer, int size, int rwflag, void* userdata); + +} // namespace KeyPassword +} // namespace CASSc diff --git a/sc/ScHubConnector.cpp b/sc/ScHubConnector.cpp new file mode 100644 index 0000000..4f9a066 --- /dev/null +++ b/sc/ScHubConnector.cpp @@ -0,0 +1,413 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// ScHubConnector.cpp - see ScHubConnector.h. Adapted from the plugfest +// example's libwebsockets client (ScWebSocketClient), with the B-SCHUB +// example's queueing, ingress ceiling and lifetime TLS context. + +#include "ScHubConnector.h" + +#include +// libwebsockets 4.1 added LWS_PROTOCOL_LIST_TERM; Ubuntu 22.04 ships 4.0, whose +// lws_protocols has the same seven members. +#ifndef LWS_PROTOCOL_LIST_TERM +#define LWS_PROTOCOL_LIST_TERM { NULL, NULL, 0, 0, 0, NULL, 0 } +#endif +#include + +#include +#include +#include +#include +#include + +namespace ScHubConnector { +namespace { + +// Annex AB.7.1: the subprotocol of a connection to a hub. NOT "hub.bacnet.org". +const char* const HUB_SUBPROTOCOL = "hub.bsc.bacnet.org"; + +// The largest frame handed to the stack (see the header, rule 4). +const size_t MAX_RECEIVED_FRAME_OCTETS = 1600; + +// The most frames waiting to be written on one connection. A hub that stops +// reading must not grow this without bound. +const size_t MAX_QUEUED_FRAMES = 64; + +// One connection (the stack opens at most two: primary and failover hub). +// Entries are never erased, so the pointer handed to libwebsockets as the +// connection's user data stays valid for the life of the process. +// +// A second Connect() to the same URI reuses the entry while the earlier +// attempt's socket may still be alive. `socket` is the CURRENT attempt's: an +// event from any other socket is a stale attempt's, and is ignored (or closes +// that socket) instead of touching the current connection's state. +struct Connection { + std::string uri; + lws* socket = NULL; // the current attempt's socket + bool open = false; // ESTABLISHED and not yet closed + bool closeRequested = false; + std::deque> sendQueue; + std::vector receiveAssembly; // the fragments of the frame being received + bool receiveOverflow = false; // the frame being received is too big: drop it +}; + +lws_context* g_context = NULL; +TlsFiles g_tlsFiles; +std::map g_connections; +std::deque g_statusEvents; +std::deque g_receivedFrames; +// True while ReloadCredentials() destroys the context: the closes that causes +// are reported by ReloadCredentials() itself, once each. +bool g_reloading = false; + +void QueueStatus(const std::string& uri, const WebSocketStatus status) { + StatusEvent event; + event.uri = uri; + event.status = status; + g_statusEvents.push_back(event); +} + +// wss://host[:port][/path] -> host, port, path. A bracketed IPv6 literal +// ("wss://[fd00::1]:4443") is accepted too. +bool ParseHubUri(const std::string& uri, std::string* host, int* port, std::string* path) { + const std::string scheme = "wss://"; + if (uri.compare(0, scheme.size(), scheme) != 0) { + return false; + } + const std::string rest = uri.substr(scheme.size()); + const size_t slashPosition = rest.find('/'); + const std::string hostAndPort = rest.substr(0, slashPosition); + *path = slashPosition == std::string::npos ? "/" : rest.substr(slashPosition); + *port = 443; + std::string portText; + if (!hostAndPort.empty() && hostAndPort[0] == '[') { + const size_t closePosition = hostAndPort.find(']'); + if (closePosition == std::string::npos) { + return false; + } + *host = hostAndPort.substr(1, closePosition - 1); + if (closePosition + 1 < hostAndPort.size()) { + if (hostAndPort[closePosition + 1] != ':') { + return false; + } + portText = hostAndPort.substr(closePosition + 2); + } + } else { + const size_t colonPosition = hostAndPort.rfind(':'); + *host = hostAndPort.substr(0, colonPosition); + if (colonPosition != std::string::npos) { + portText = hostAndPort.substr(colonPosition + 1); + } + } + if (host->empty()) { + return false; + } + if (!portText.empty()) { + char* parseEnd = NULL; + const long parsedPort = strtol(portText.c_str(), &parseEnd, 10); + if (*parseEnd != '\0' || parsedPort < 1 || parsedPort > 65535) { + return false; + } + *port = (int)parsedPort; + } + return true; +} + +// libwebsockets' callback for every event on a hub connection. ONLY queues - +// no BACnetStack_* call here (header, rule 3). +int HubProtocolCallback(lws* socket, lws_callback_reasons reason, void* user, void* in, size_t length) { + (void)user; + Connection* connection = (Connection*)lws_get_opaque_user_data(socket); + if (connection == NULL || g_reloading) { + return 0; + } + if (socket != connection->socket) { + // A superseded attempt (see Connection). If it is up or still talking, + // close it; its error or close is not the current connection's. + if (reason == LWS_CALLBACK_CLIENT_ESTABLISHED || reason == LWS_CALLBACK_CLIENT_RECEIVE || + reason == LWS_CALLBACK_CLIENT_WRITEABLE) { + return -1; + } + return 0; + } + switch (reason) { + case LWS_CALLBACK_CLIENT_ESTABLISHED: + connection->open = true; + connection->socket = socket; + printf("BACnet/SC: connected to %s\n", connection->uri.c_str()); + QueueStatus(connection->uri, WEBSOCKET_STATUS_CONNECTED); + if (!connection->sendQueue.empty()) { + lws_callback_on_writable(socket); + } + break; + + case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: + // TLS refused (an untrusted hub certificate, or the hub refused + // ours), nothing listening, a wrong subprotocol ... + printf("BACnet/SC: could not connect to %s: %.*s\n", connection->uri.c_str(), + in != NULL ? (int)length : 7, in != NULL ? (const char*)in : "unknown"); + connection->open = false; + connection->socket = NULL; + connection->sendQueue.clear(); + QueueStatus(connection->uri, WEBSOCKET_STATUS_ERROR); + break; + + case LWS_CALLBACK_CLIENT_CLOSED: + printf("BACnet/SC: connection to %s closed\n", connection->uri.c_str()); + connection->open = false; + connection->socket = NULL; + connection->sendQueue.clear(); + QueueStatus(connection->uri, WEBSOCKET_STATUS_DISCONNECTED); + break; + + case LWS_CALLBACK_CLIENT_RECEIVE: { + // A WebSocket message may arrive in several fragments; put them + // together, and drop a message over the ceiling (rule 4). + if (!lws_frame_is_binary(socket)) { + printf("BACnet/SC: %s sent a text frame - BACnet/SC is binary only; ignored\n", + connection->uri.c_str()); + break; + } + if (!connection->receiveOverflow) { + if (connection->receiveAssembly.size() + length > MAX_RECEIVED_FRAME_OCTETS) { + connection->receiveOverflow = true; + connection->receiveAssembly.clear(); + printf("BACnet/SC: dropped a frame from %s larger than %u octets\n", connection->uri.c_str(), + (unsigned)MAX_RECEIVED_FRAME_OCTETS); + } else { + const uint8_t* octets = (const uint8_t*)in; + connection->receiveAssembly.insert(connection->receiveAssembly.end(), octets, octets + length); + } + } + if (lws_is_final_fragment(socket)) { + if (!connection->receiveOverflow && !connection->receiveAssembly.empty()) { + ReceivedFrame frame; + frame.uri = connection->uri; + frame.data.swap(connection->receiveAssembly); + g_receivedFrames.push_back(frame); + } + connection->receiveAssembly.clear(); + connection->receiveOverflow = false; + } + break; + } + + case LWS_CALLBACK_CLIENT_WRITEABLE: { + if (connection->closeRequested) { + lws_close_reason(socket, LWS_CLOSE_STATUS_NORMAL, NULL, 0); + return -1; // closes the connection; CLIENT_CLOSED follows + } + if (connection->sendQueue.empty()) { + break; + } + // lws_write needs LWS_PRE octets of room in front of the data. + const std::vector& frame = connection->sendQueue.front(); + std::vector buffer(LWS_PRE + frame.size()); + memcpy(buffer.data() + LWS_PRE, frame.data(), frame.size()); + const int written = lws_write(socket, buffer.data() + LWS_PRE, frame.size(), LWS_WRITE_BINARY); + if (written < (int)frame.size()) { + printf("BACnet/SC: write to %s failed\n", connection->uri.c_str()); + return -1; + } + connection->sendQueue.pop_front(); + if (!connection->sendQueue.empty()) { + lws_callback_on_writable(socket); + } + break; + } + + default: + break; + } + return 0; +} + +lws_protocols g_protocols[] = { + { HUB_SUBPROTOCOL, HubProtocolCallback, 0, 4096, 0, NULL, 0 }, + LWS_PROTOCOL_LIST_TERM +}; + +int LifetimeCallback(lws*, lws_callback_reasons, void*, void*, size_t) { + return 0; +} + +// Rule 5: one TLS-initialised context, created once and never destroyed. +void EnsureLifetimeContext() { + static lws_context* lifetimeContext = NULL; + if (lifetimeContext != NULL) { + return; + } + static lws_protocols lifetimeProtocols[] = { + { "bacnet-sc-tls-lifetime", LifetimeCallback, 0, 0, 0, NULL, 0 }, + LWS_PROTOCOL_LIST_TERM + }; + lws_context_creation_info info; + memset(&info, 0, sizeof(info)); + info.port = CONTEXT_PORT_NO_LISTEN; + info.protocols = lifetimeProtocols; + info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; + info.gid = (gid_t)-1; + info.uid = (uid_t)-1; + lifetimeContext = lws_create_context(&info); // deliberately never destroyed +} + +bool CreateContext() { + lws_context_creation_info info; + memset(&info, 0, sizeof(info)); + info.port = CONTEXT_PORT_NO_LISTEN; // a client only + info.protocols = g_protocols; + info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; + // The client's TLS material is loaded once, here, not per connection. + info.client_ssl_ca_filepath = g_tlsFiles.trustedIssuers.c_str(); + info.client_ssl_cert_filepath = g_tlsFiles.certificate.c_str(); + info.client_ssl_private_key_filepath = g_tlsFiles.privateKey.c_str(); + info.client_ssl_private_key_password = g_tlsFiles.privateKeyPassword; + // BACnet/SC uses TLS 1.3 only: switch every older version off. + info.ssl_client_options_set = SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; + info.gid = (gid_t)-1; + info.uid = (uid_t)-1; + g_context = lws_create_context(&info); + if (g_context == NULL) { + printf("BACnet/SC: libwebsockets could not load this device's certificate files (%s, %s, %s)\n", + g_tlsFiles.certificate.c_str(), g_tlsFiles.privateKey.c_str(), g_tlsFiles.trustedIssuers.c_str()); + return false; + } + return true; +} + +} // namespace + +bool Start(const TlsFiles& tlsFiles) { + // libwebsockets' own log: errors and warnings only. + lws_set_log_level(LLL_ERR | LLL_WARN, NULL); + EnsureLifetimeContext(); + g_tlsFiles = tlsFiles; + return CreateContext(); +} + +bool Connect(const std::string& uri) { + if (g_context == NULL) { + return false; + } + std::string host; + std::string path; + int port = 0; + if (!ParseHubUri(uri, &host, &port, &path)) { + printf("BACnet/SC: \"%s\" is not a wss://host:port URI\n", uri.c_str()); + return false; + } + Connection& connection = g_connections[uri]; + if (connection.socket != NULL) { + // An earlier attempt is still alive: have libwebsockets close it. Its + // later events no longer match connection.socket and are ignored. + lws_set_timeout(connection.socket, PENDING_TIMEOUT_USER_OK, LWS_TO_KILL_ASYNC); + } + connection.uri = uri; + connection.socket = NULL; + connection.open = false; + connection.closeRequested = false; + connection.sendQueue.clear(); + connection.receiveAssembly.clear(); + connection.receiveOverflow = false; + + lws_client_connect_info connectInfo; + memset(&connectInfo, 0, sizeof(connectInfo)); + connectInfo.context = g_context; + connectInfo.address = host.c_str(); + connectInfo.port = port; + connectInfo.path = path.c_str(); + connectInfo.host = host.c_str(); + connectInfo.origin = host.c_str(); + connectInfo.protocol = HUB_SUBPROTOCOL; + connectInfo.alpn = "http/1.1"; // a WebSocket upgrade over HTTP/1.1, never HTTP/2 + // TLS, with the hub's certificate checked against the trusted issuers + // but not against the host name (header, rule 6). + connectInfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK; + connectInfo.opaque_user_data = &connection; + // No pwsi: it would point every attempt at the same connection.socket, and + // libwebsockets clears *pwsi when an attempt fails - the new one's too. + printf("BACnet/SC: connecting to %s\n", uri.c_str()); + connection.socket = lws_client_connect_via_info(&connectInfo); + if (connection.socket == NULL) { + // A failure that libwebsockets has not already reported through the + // callback (which queued an Error status) - report it now. + if (g_statusEvents.empty() || g_statusEvents.back().uri != uri) { + QueueStatus(uri, WEBSOCKET_STATUS_ERROR); + } + return true; // the attempt was made; its failure is reported as a status + } + return true; +} + +void Disconnect(const std::string& uri) { + std::map::iterator found = g_connections.find(uri); + if (found == g_connections.end() || found->second.socket == NULL) { + return; + } + found->second.closeRequested = true; + lws_callback_on_writable(found->second.socket); // the close happens in the WRITEABLE callback +} + +bool Send(const std::string& uri, const uint8_t* data, const uint16_t length) { + std::map::iterator found = g_connections.find(uri); + if (found == g_connections.end() || !found->second.open || found->second.socket == NULL || + found->second.sendQueue.size() >= MAX_QUEUED_FRAMES) { + return false; + } + found->second.sendQueue.push_back(std::vector(data, data + length)); + lws_callback_on_writable(found->second.socket); + return true; +} + +void Service() { + if (g_context == NULL) { + return; + } + // lws_service() can wait for an event; lws_cancel_service() first makes + // it handle what is pending and return at once. + lws_cancel_service(g_context); + lws_service(g_context, 0); +} + +bool PopStatusEvent(StatusEvent* event) { + if (g_statusEvents.empty()) { + return false; + } + *event = g_statusEvents.front(); + g_statusEvents.pop_front(); + return true; +} + +bool PopReceived(ReceivedFrame* frame) { + if (g_receivedFrames.empty()) { + return false; + } + *frame = g_receivedFrames.front(); + g_receivedFrames.pop_front(); + return true; +} + +bool ReloadCredentials(const TlsFiles& tlsFiles) { + // Destroying the context closes every connection; report each one here + // (and only here - see g_reloading). + for (std::map::iterator entry = g_connections.begin(); entry != g_connections.end(); + ++entry) { + if (entry->second.socket != NULL || entry->second.open) { + entry->second.open = false; + entry->second.socket = NULL; + entry->second.sendQueue.clear(); + QueueStatus(entry->first, WEBSOCKET_STATUS_DISCONNECTED); + } + } + if (g_context != NULL) { + g_reloading = true; + lws_context_destroy(g_context); // safe: the lifetime context keeps OpenSSL alive + g_reloading = false; + g_context = NULL; + } + g_tlsFiles = tlsFiles; + return CreateContext(); +} + +} // namespace ScHubConnector diff --git a/sc/ScHubConnector.h b/sc/ScHubConnector.h new file mode 100644 index 0000000..0e07457 --- /dev/null +++ b/sc/ScHubConnector.h @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef BBC_EXAMPLE_SC_HUB_CONNECTOR_H +#define BBC_EXAMPLE_SC_HUB_CONNECTOR_H + +// ScHubConnector.h +// ============================================================================= +// The WebSocket half of a BACnet/SC node (ANSI/ASHRAE 135-2024 Annex AB): the +// TLS connection to a hub. The CAS BACnet Stack runs everything BACnet/SC +// itself - Connect-Request/Accept, heartbeats, reconnect timing, which hub to +// use - and asks the application only to open, close and carry bytes over a +// secure WebSocket. This file does that with libwebsockets, as a CLIENT only: +// this device connects to a hub, it never listens (that is the B-SCHUB +// example's job). +// +// stack -> CallbackInitiateWebsocket(uri) -> Connect(uri) +// stack -> CallbackDisconnectWebsocket(uri)-> Disconnect(uri) +// stack -> CallbackSendMessageForPort(...) -> Send(uri, frame) +// main loop: Service(), then +// PopStatusEvent() -> BACnetStack_SetBACnetSCWebSocketStatus() +// (frames are fetched by CallbackReceiveMessageForPort -> +// PopReceived()) +// +// THE RULES THAT MAKE THIS CORRECT (see also the B-SCHUB example's +// sc_transport/README.md, where they were established): +// 1. The WebSocket subprotocol is "hub.bsc.bacnet.org" (Annex AB.7.1). +// 2. The status values the stack takes are Connecting = 1, Connected = 2, +// Disconnected = 3, Error = 4. +// 3. Never call BACnetStack_* from inside a stack callback or an lws +// callback. Connect() is called from inside the stack's +// CallbackInitiateWebsocket, and libwebsockets can report a failure +// before it even returns - so every status change is QUEUED here, and +// the main loop reports it to the stack after Service(). +// 4. A received frame larger than 1600 octets is dropped (the stack's input +// buffer, and Annex AB's minimum BVLC length). +// 5. One TLS-initialised libwebsockets context lives for the whole process: +// destroying the last one tears OpenSSL down process-wide, and the next +// lws_create_context() then crashes. So reloading the certificates +// (ReloadCredentials) can replace the connection context safely. +// 6. The hub's certificate is checked against the trusted issuers (the CA +// chain), but not against the host name in the URI: a BACnet/SC +// certificate identifies a DEVICE, not a DNS host, so a hub dialled by +// IP address or by another name than its certificate's is still accepted +// when its certificate chains to a trusted issuer. +// ============================================================================= + +#include + +#include +#include + +namespace ScHubConnector { + +struct TlsFiles { + std::string trustedIssuers; // PEM bundle: the CA(s) the hub's certificate must chain to + std::string certificate; // PEM: this device's operational certificate + std::string privateKey; // PEM: its private key + const char* privateKeyPassword; // NULL for a key with no password +}; + +// BACnetStack_SetBACnetSCWebSocketStatus's status values. +enum WebSocketStatus : uint8_t { + WEBSOCKET_STATUS_CONNECTING = 1, + WEBSOCKET_STATUS_CONNECTED = 2, + WEBSOCKET_STATUS_DISCONNECTED = 3, + WEBSOCKET_STATUS_ERROR = 4 +}; + +struct StatusEvent { + std::string uri; + WebSocketStatus status; +}; + +struct ReceivedFrame { + std::string uri; + std::vector data; +}; + +// Creates the libwebsockets context with this device's certificate. False if +// libwebsockets refuses (a certificate or key it cannot load). +bool Start(const TlsFiles& tlsFiles); + +// Starts a connection to wss://host:port[/path]. True once the attempt has +// started; the outcome arrives later as a StatusEvent. +bool Connect(const std::string& uri); + +// Closes the connection to `uri`, if there is one. +void Disconnect(const std::string& uri); + +// Queues one binary frame on the connection to `uri`. False if that connection +// is not open (the stack then counts the send as failed). +bool Send(const std::string& uri, const uint8_t* data, uint16_t length); + +// Moves bytes: call it every main-loop pass. Never blocks. +void Service(); + +bool PopStatusEvent(StatusEvent* event); +bool PopReceived(ReceivedFrame* frame); + +// New certificates were activated: rebuild the TLS context so they are used. +// Every open connection is closed (each reported Disconnected); the stack +// reconnects on its own. +bool ReloadCredentials(const TlsFiles& tlsFiles); + +} // namespace ScHubConnector + +#endif // BBC_EXAMPLE_SC_HUB_CONNECTOR_H diff --git a/sc/ScNode.cpp b/sc/ScNode.cpp new file mode 100644 index 0000000..f709ce2 --- /dev/null +++ b/sc/ScNode.cpp @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +// +// ScNode.cpp - see ScNode.h. + +#include "ScNode.h" + +#include "CASBACnetStackAdapter.h" +#include "KeyPassword.h" +#include "ScHubConnector.h" +#include "cert_layout.h" +#include "cert_store.h" +#include "cert_tool.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace ScNode { +namespace { + +// BACnetNetworkType secure-connect (cl. 12.56.9) and the other values this file +// passes to the stack. Local, like the B-SCHUB example's: common/'s constants +// header has none of them. +const uint8_t NETWORK_TYPE_SECURE_CONNECT = 11; +const uint8_t PROTOCOL_LEVEL_BACNET_APPLICATION = 2; +const uint8_t NETWORK_NUMBER_QUALITY_UNKNOWN = 0; +const uint32_t REFERENCE_PORT_NONE = 4194303; +const uint16_t OBJECT_TYPE_NETWORK_PORT = 56; +const uint8_t FILE_ACCESS_METHOD_STREAM = 1; +// The properties this device ENABLES on its BACnet/SC port: the stack serves +// them, but leaves turning them on to the application. +const uint32_t PROPERTY_IDENTIFIER_CURRENT_HEALTH = 4194307; +const uint32_t PROPERTY_IDENTIFIER_SC_PRIMARY_HUB_CONNECTION_STATUS = 4194324; +const uint32_t PROPERTY_IDENTIFIER_SC_FAILOVER_HUB_CONNECTION_STATUS = 4194316; +// BACnetNetworkPortCommand values the stack hands to the application. +const uint32_t NETWORK_PORT_COMMAND_DISCARD_CHANGES = 1; +const uint32_t NETWORK_PORT_COMMAND_GENERATE_CSR_FILE = 9; +const uint32_t ERROR_CODE_INVALID_CONFIGURATION_DATA = 46; +const uint32_t ERROR_CODE_OPTIONAL_FUNCTIONALITY_NOT_SUPPORTED = 45; + +// The BACnet/SC sizes and timers (BACnetStack_SetBACnetSCSettings). 1600 and +// 1497 are the smallest the stack accepts; the timers are in seconds. +const uint16_t SC_MAXIMUM_BVLC_LENGTH = 1600; +const uint16_t SC_MAXIMUM_NPDU_LENGTH = 1497; +const uint16_t SC_CONNECT_WAIT_TIMEOUT = 10; +const uint16_t SC_WEBSOCKET_CONNECT_TIMEOUT = 10; +const uint16_t SC_WEBSOCKET_RECONNECT_DELAY = 10; +const uint16_t SC_HEARTBEAT_TIMEOUT = 300; + +// The hub-connection-status state machine (BACnetStack_RegisterCallbackBACnetSCStateChange): +// 0 none, 1 connected to the primary hub, 2 to the failover hub. +const uint8_t STATE_MACHINE_HUB_CONNECTION_STATUS = 1; + +CertLayout::NodeCertPaths g_certPaths; +uint32_t g_networkPortInstance = 0; +bool g_reloadCredentialsRequested = false; +bool g_hubConnectedEvent = false; +std::string g_primaryHubUri; +std::string g_failoverHubUri; +uint8_t g_hubConnectionStatus = 0; // 0 none, 1 primary, 2 failover + +ScHubConnector::TlsFiles CurrentTlsFiles() { + ScHubConnector::TlsFiles tlsFiles; + tlsFiles.trustedIssuers = g_certPaths.trustedIssuers; + tlsFiles.certificate = g_certPaths.operationalCertificate; + tlsFiles.privateKey = g_certPaths.privateKey; + tlsFiles.privateKeyPassword = CASSc::KeyPassword::Get(); + return tlsFiles; +} + +std::string CertificateFilePath(const uint32_t fileInstance) { + switch (fileInstance) { + case FILE_OPERATIONAL_CERTIFICATE_INSTANCE: return g_certPaths.operationalCertificate; + case FILE_ISSUER_CERTIFICATE_1_INSTANCE: return g_certPaths.issuerCertificate1; + case FILE_ISSUER_CERTIFICATE_2_INSTANCE: return g_certPaths.issuerCertificate2; + case FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE: return g_certPaths.certificateSigningRequest; + default: return std::string(); + } +} + +// The device UUID (Annex AB) must stay the same across restarts - the +// stack derives the device's default VMAC from it - and must differ from every +// other device's. So it is made once, at random (an RFC 4122 version 4 UUID), +// and kept in --sc-cert-dir. +bool LoadOrCreateDeviceUuid(const std::string& certDir, uint8_t uuid[16]) { + const fs::path uuidPath = fs::path(certDir) / "sc-device-uuid.txt"; + std::ifstream existing(uuidPath); + std::string hexText; + if (existing >> hexText && hexText.size() == 32) { + bool valid = true; + for (int octetIndex = 0; octetIndex < 16 && valid; ++octetIndex) { + const std::string octetText = hexText.substr(2 * octetIndex, 2); + char* parseEnd = NULL; + const unsigned long octetValue = strtoul(octetText.c_str(), &parseEnd, 16); + valid = parseEnd == octetText.c_str() + 2; + uuid[octetIndex] = (uint8_t)octetValue; + } + if (valid) { + return true; + } + } + std::random_device randomSource; + for (int octetIndex = 0; octetIndex < 16; ++octetIndex) { + uuid[octetIndex] = (uint8_t)(randomSource() & 0xFF); + } + uuid[6] = (uint8_t)((uuid[6] & 0x0F) | 0x40); // version 4 (random) + uuid[8] = (uint8_t)((uuid[8] & 0x3F) | 0x80); // RFC 4122 variant + std::ofstream created(uuidPath); + for (int octetIndex = 0; octetIndex < 16; ++octetIndex) { + char octetText[3]; + snprintf(octetText, sizeof(octetText), "%02x", uuid[octetIndex]); + created << octetText; + } + created << "\n"; + if (!created) { + printf("Error: BACnet/SC: could not save the device UUID to %s\n", uuidPath.string().c_str()); + return false; + } + printf("FYI: BACnet/SC: made this device's UUID, saved in %s\n", uuidPath.string().c_str()); + return true; +} + +// --- The stack's BACnet/SC callbacks. Each runs INSIDE a stack call, so none +// --- calls back into the stack (ScHubConnector.h, rule 3). + +bool CallbackInitiateWebsocket(const char* websocketUri, const uint32_t websocketUriLength) { + return ScHubConnector::Connect(std::string(websocketUri, websocketUriLength)); +} + +void CallbackDisconnectWebsocket(const char* websocketUri, const uint32_t websocketUriLength) { + ScHubConnector::Disconnect(std::string(websocketUri, websocketUriLength)); +} + +void CallbackBACnetSCStateChange(const uint32_t deviceInstance, const uint32_t networkPortInstance, + const uint8_t stateMachine, const uint8_t previousState, const uint8_t newState, + const char* websocketUri, const uint32_t websocketUriLength) { + (void)deviceInstance; + (void)networkPortInstance; + (void)previousState; + (void)websocketUri; + (void)websocketUriLength; + if (stateMachine == STATE_MACHINE_HUB_CONNECTION_STATUS) { + g_hubConnectionStatus = newState; + printf("BACnet/SC: hub connection: %s\n", + newState == 1 ? "connected to the PRIMARY hub" : + newState == 2 ? "connected to the FAILOVER hub" : "no hub"); + if (newState == 1 || newState == 2) { + g_hubConnectedEvent = true; // main() sends the I-Am, outside this callback + } + } +} + +} // namespace + +int ImportCari(const std::string& certDir, const uint32_t deviceInstance, const std::string& zipPath) { + return CertTool::ImportCariResponse(certDir, deviceInstance, zipPath) ? 0 : 1; +} + +bool PrepareCertificates(const std::string& certDir, const uint32_t deviceInstance, const char* deviceName) { + std::error_code directoryError; + fs::create_directories(certDir, directoryError); + g_certPaths = CertLayout::ResolveNodeCertPaths(certDir, deviceInstance); + printf("FYI: BACnet/SC certificates: CARI tree in \"%s\", port folder %s\n", certDir.c_str(), + g_certPaths.portFolder.c_str()); + if (!g_certPaths.note.empty()) { + printf("FYI: BACnet/SC certificates: %s\n", g_certPaths.note.c_str()); + } + + // A password-protected private key: ask for its password once, here. + std::string keyPasswordMessage; + if (!CASSc::KeyPassword::Prepare(g_certPaths.privateKey, &keyPasswordMessage)) { + printf("Error: BACnet/SC certificates: %s\n", keyPasswordMessage.c_str()); + } + + // CertStore serves the certificate File objects and runs the clause 19.8.3 + // certificate procedures (see cert_store.h). + CertStore::Layout layout; + const uint32_t certificateInstances[4] = { FILE_OPERATIONAL_CERTIFICATE_INSTANCE, FILE_ISSUER_CERTIFICATE_1_INSTANCE, + FILE_ISSUER_CERTIFICATE_2_INSTANCE, + FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE }; + for (const uint32_t instance : certificateInstances) { + layout.paths[instance] = CertificateFilePath(instance); + } + // Until something is written to it, Issuer_Certificate_Files[2] serves [1]. + layout.readFallbackInstances[FILE_ISSUER_CERTIFICATE_2_INSTANCE] = FILE_ISSUER_CERTIFICATE_1_INSTANCE; + layout.operationalInstance = FILE_OPERATIONAL_CERTIFICATE_INSTANCE; + layout.issuerInstances = { FILE_ISSUER_CERTIFICATE_1_INSTANCE, FILE_ISSUER_CERTIFICATE_2_INSTANCE }; + layout.privateKeyPath = g_certPaths.privateKey; + layout.pendingPrivateKeyPath = g_certPaths.pendingPrivateKey; + layout.csrInstance = FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE; + CertStore::SetLayout(layout); + std::string reconcileMessage; + if (!CertStore::ReconcilePendingKey(&reconcileMessage)) { + printf("Error: BACnet/SC certificates: %s\n", reconcileMessage.c_str()); + } else if (!reconcileMessage.empty()) { + printf("FYI: BACnet/SC certificates: %s\n", reconcileMessage.c_str()); + } + + // The CARI certificate request: made now if it doesn't exist, never + // overwritten. A device with no key at all gets a new key and CSR first. + std::string requestMessage; + const CertTool::RequestResult request = + CertTool::EnsureNodeRequest(certDir, deviceInstance, deviceName, &requestMessage); + printf("%s: BACnet/SC certificate request: %s\n", request == CertTool::RequestResult::Failed ? "Error" : "FYI", + requestMessage.c_str()); + + std::error_code fileError; + if (!fs::exists(g_certPaths.operationalCertificate, fileError)) { + printf("\n"); + printf("This device has no BACnet/SC certificate yet, so it cannot connect to a hub.\n"); + printf(" 1. Send %s to your Certificate Authority.\n", + (fs::path(certDir) / CertTool::NODE_REQUEST_ZIP).string().c_str()); + printf(" (For a test: python tools/sign_cari_request.py, with the B-SCHUB example's demo CA.)\n"); + printf(" 2. Install the CARI response it sends back:\n"); + printf(" BACnetExampleBBC --datalink sc --sc-cert-dir %s --import-cari \n", certDir.c_str()); + printf(" 3. Start the device again with --datalink sc --sc-hub wss://:.\n"); + return false; + } + + // TLS trusts every issuer certificate in both Issuer_Certificate_Files. + std::string bundleReason; + if (!CertStore::WriteTrustedIssuerBundle(g_certPaths.trustedIssuers, &bundleReason)) { + printf("Error: BACnet/SC certificates: no issuer certificate to trust the hub with (%s)\n", + bundleReason.c_str()); + return false; + } + return ScHubConnector::Start(CurrentTlsFiles()); +} + +bool AddNetworkPort(const uint32_t deviceInstance, const uint32_t networkPortInstance, + const std::string& primaryHubUri, const std::string& failoverHubUri) { + g_networkPortInstance = networkPortInstance; + g_primaryHubUri = primaryHubUri; + g_failoverHubUri = failoverHubUri; + + BACnetStack_RegisterCallbackInitiateWebsocket(CallbackInitiateWebsocket); + BACnetStack_RegisterCallbackDisconnectWebsocket(CallbackDisconnectWebsocket); + BACnetStack_RegisterCallbackBACnetSCStateChange(CallbackBACnetSCStateChange); + + if (!BACnetStack_AddNetworkPortObject(deviceInstance, networkPortInstance, NETWORK_TYPE_SECURE_CONNECT, + PROTOCOL_LEVEL_BACNET_APPLICATION, 0, NETWORK_NUMBER_QUALITY_UNKNOWN, + REFERENCE_PORT_NONE)) { + printf("Error: Failed to add Network Port %u (BACnet/SC).\n", networkPortInstance); + return false; + } + // Current_Health and the two hub connection statuses: served by the stack, + // turned on by the application. SC_Primary_Hub_Connection_Status is how a + // client (or you) sees whether the device is connected. + const uint32_t statusProperties[3] = { PROPERTY_IDENTIFIER_CURRENT_HEALTH, + PROPERTY_IDENTIFIER_SC_PRIMARY_HUB_CONNECTION_STATUS, + PROPERTY_IDENTIFIER_SC_FAILOVER_HUB_CONNECTION_STATUS }; + for (const uint32_t property : statusProperties) { + if (!BACnetStack_SetPropertyEnabled(deviceInstance, OBJECT_TYPE_NETWORK_PORT, networkPortInstance, property, + true)) { + printf("Error: Failed to enable property %u on Network Port %u.\n", property, networkPortInstance); + return false; + } + } + + // The device UUID - once per run, after the BACnet/SC port exists. + uint8_t uuid[16]; + if (!LoadOrCreateDeviceUuid(g_certPaths.certDir, uuid) || !BACnetStack_SetBACnetSCUuid(uuid, sizeof(uuid))) { + printf("Error: Failed to set the BACnet/SC device UUID.\n"); + return false; + } + // The hubs. No VMAC given: the stack derives one from the UUID. + if (!BACnetStack_SetBACnetSCHubConnectorForNetworkPort( + deviceInstance, networkPortInstance, NULL, 0, primaryHubUri.c_str(), (uint16_t)primaryHubUri.size(), + failoverHubUri.c_str(), (uint16_t)failoverHubUri.size())) { + printf("Error: Failed to set the BACnet/SC hub URIs (%s, %s).\n", primaryHubUri.c_str(), + failoverHubUri.empty() ? "no failover" : failoverHubUri.c_str()); + return false; + } + if (!BACnetStack_SetBACnetSCSettings(SC_MAXIMUM_BVLC_LENGTH, SC_MAXIMUM_NPDU_LENGTH, SC_CONNECT_WAIT_TIMEOUT, + SC_WEBSOCKET_CONNECT_TIMEOUT, SC_WEBSOCKET_RECONNECT_DELAY, + SC_HEARTBEAT_TIMEOUT)) { + printf("Error: Failed to set the BACnet/SC settings.\n"); + return false; + } + + // The four certificate File objects. The operational and issuer + // certificates are writable (the clause 19.8.3 procedures); the signing + // request is the device's own and read-only. + const struct { + uint32_t instance; + bool writable; + } files[4] = { + { FILE_OPERATIONAL_CERTIFICATE_INSTANCE, true }, + { FILE_ISSUER_CERTIFICATE_1_INSTANCE, true }, + { FILE_ISSUER_CERTIFICATE_2_INSTANCE, true }, + { FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE, false }, + }; + for (const auto& file : files) { + if (!BACnetStack_AddFileObject(deviceInstance, file.instance, file.writable, false /*isConfigurationFile*/, + FILE_ACCESS_METHOD_STREAM)) { + printf("Error: Failed to add File %u (%s).\n", file.instance, CertificateFileName(file.instance)); + return false; + } + } + const uint32_t issuerFileInstances[2] = { FILE_ISSUER_CERTIFICATE_1_INSTANCE, FILE_ISSUER_CERTIFICATE_2_INSTANCE }; + if (!BACnetStack_SetBACnetSCCertificateFileObjects(deviceInstance, networkPortInstance, + true, FILE_OPERATIONAL_CERTIFICATE_INSTANCE, + true, FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE, + issuerFileInstances, 2)) { + printf("Error: Failed to bind Network Port %u's certificate File objects.\n", networkPortInstance); + return false; + } + // Binding the File objects leaves them PENDING (Changes_Pending TRUE), as a + // client's write would. This is the device's own start-up configuration, + // so make it active now - otherwise the port reports Changes_Pending for a + // change nobody made, and does not start until a ReinitializeDevice. + if (!BACnetStack_ActivateNetworkPortPendingChanges(deviceInstance, networkPortInstance)) { + printf("Error: Failed to activate Network Port %u's BACnet/SC configuration.\n", networkPortInstance); + return false; + } + printf("FYI: BACnet/SC: Network Port %u connects to the primary hub %s%s%s.\n", networkPortInstance, + primaryHubUri.c_str(), failoverHubUri.empty() ? "" : ", failover ", failoverHubUri.c_str()); + return true; +} + +void Service() { + ScHubConnector::Service(); + // Report each connection change to the stack - here in the main loop, never + // from inside a callback. + ScHubConnector::StatusEvent event; + while (ScHubConnector::PopStatusEvent(&event)) { + BACnetStack_SetBACnetSCWebSocketStatus(event.uri.c_str(), (uint16_t)event.uri.size(), event.status, 0); + } + // New certificates were activated (ApplyStagedCertificates): use them. The + // connection drops and the stack reconnects with the new certificate. + if (g_reloadCredentialsRequested) { + g_reloadCredentialsRequested = false; + printf("FYI: BACnet/SC: reloading the TLS certificates\n"); + ScHubConnector::ReloadCredentials(CurrentTlsFiles()); + } +} + +bool TakeHubConnectedEvent() { + const bool connected = g_hubConnectedEvent; + g_hubConnectedEvent = false; + return connected; +} + +std::string ConnectedHubUri() { + return g_hubConnectionStatus == 1 ? g_primaryHubUri : g_hubConnectionStatus == 2 ? g_failoverHubUri : std::string(); +} + +uint16_t ReceiveFromHub(uint8_t* message, const uint16_t maxMessageLength, uint8_t* sourceConnectionString, + uint8_t* sourceConnectionStringLength, const uint8_t maxConnectionStringLength) { + ScHubConnector::ReceivedFrame frame; + if (!ScHubConnector::PopReceived(&frame)) { + return 0; + } + if (frame.data.size() > maxMessageLength || frame.uri.size() > maxConnectionStringLength) { + printf("BACnet/SC: dropped a %u-octet frame from %s (too big for the stack's buffer)\n", + (unsigned)frame.data.size(), frame.uri.c_str()); + return 0; + } + // The source "address" of a frame from the hub is the hub connection's URI. + memcpy(message, frame.data.data(), frame.data.size()); + memcpy(sourceConnectionString, frame.uri.data(), frame.uri.size()); + *sourceConnectionStringLength = (uint8_t)frame.uri.size(); + return (uint16_t)frame.data.size(); +} + +uint16_t SendToHub(const uint8_t* message, const uint16_t messageLength, const uint8_t* connectionString, + const uint8_t connectionStringLength) { + // The stack names the connection by its URI. Success is the frame's length. + const std::string uri((const char*)connectionString, connectionStringLength); + return ScHubConnector::Send(uri, message, messageLength) ? messageLength : 0; +} + +// --- The certificate File objects -------------------------------------------- + +bool IsCertificateFile(const uint32_t fileInstance) { + return fileInstance >= FILE_OPERATIONAL_CERTIFICATE_INSTANCE && + fileInstance <= FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE; +} + +const char* CertificateFileName(const uint32_t fileInstance) { + switch (fileInstance) { + case FILE_OPERATIONAL_CERTIFICATE_INSTANCE: return "Operational Certificate"; + case FILE_ISSUER_CERTIFICATE_1_INSTANCE: return "Issuer Certificate 1"; + case FILE_ISSUER_CERTIFICATE_2_INSTANCE: return "Issuer Certificate 2"; + case FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE: return "Certificate Signing Request"; + default: return "?"; + } +} + +bool GetCertificateFileSize(const uint32_t fileInstance, uint32_t* size) { + long fileSize = 0; + time_t modified = 0; + if (!IsCertificateFile(fileInstance) || !CertStore::Stat(fileInstance, &fileSize, &modified)) { + return false; + } + *size = (uint32_t)fileSize; + return true; +} + +bool IsCertificateFileReadOnly(const uint32_t fileInstance) { + return fileInstance == FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE; +} + +bool GetCertificateFileModified(const uint32_t fileInstance, struct tm* utc) { + long fileSize = 0; + time_t modified = 0; + if (!IsCertificateFile(fileInstance) || !CertStore::Stat(fileInstance, &fileSize, &modified)) { + return false; + } +#if defined(_WIN32) + return gmtime_s(utc, &modified) == 0; +#else + return gmtime_r(&modified, utc) != NULL; +#endif +} + +bool ReadCertificateFile(const uint32_t fileInstance, const uint32_t fileStart, const uint32_t requestedCount, + uint8_t* fileData, uint32_t* fileDataLength, const uint32_t maxFileDataLength, + bool* endOfFile) { + // CertStore serves what a certificate procedure has staged, else the file. + // Never the private key: no File object maps to it. + std::string bytes; + if (!IsCertificateFile(fileInstance) || !CertStore::Read(fileInstance, &bytes) || fileStart > bytes.size()) { + return false; + } + uint32_t count = (uint32_t)bytes.size() - fileStart; + if (count > requestedCount) { + count = requestedCount; + } + if (count > maxFileDataLength) { + count = maxFileDataLength; + } + memcpy(fileData, bytes.data() + fileStart, count); + *fileDataLength = count; + *endOfFile = fileStart + count >= bytes.size(); + return true; +} + +bool WriteCertificateFile(const uint32_t fileInstance, const int32_t fileStart, const uint8_t* fileData, + const uint32_t fileDataLength, int32_t* ackFileStart, uint32_t* errorCode) { + if (!IsCertificateFile(fileInstance) || IsCertificateFileReadOnly(fileInstance)) { + return false; + } + if (!CertStore::Write(fileInstance, fileStart, fileData, fileDataLength, ackFileStart, errorCode)) { + return false; + } + printf("AtomicWriteFile: File %u (%s): %u octets staged - used after ReinitializeDevice ACTIVATE_CHANGES\n", + fileInstance, CertificateFileName(fileInstance), fileDataLength); + return true; +} + +bool ResizeCertificateFile(const uint32_t fileInstance, const uint32_t newSize, uint32_t* errorCode) { + if (!IsCertificateFile(fileInstance) || IsCertificateFileReadOnly(fileInstance)) { + return false; + } + return CertStore::Resize(fileInstance, newSize, errorCode); +} + +bool ApplyStagedCertificates(uint32_t* errorCode) { + if (!CertStore::HasStagedChanges()) { + return true; + } + std::string reason; + if (!CertStore::ValidateStaged(&reason) || !CertStore::CommitStaged(&reason)) { + printf("ReinitializeDevice: the certificates written were REFUSED, nothing changed: %s\n", reason.c_str()); + *errorCode = ERROR_CODE_INVALID_CONFIGURATION_DATA; + return false; + } + if (!CertStore::WriteTrustedIssuerBundle(g_certPaths.trustedIssuers, &reason)) { + printf("Error: BACnet/SC: could not refresh the trusted issuers: %s\n", reason.c_str()); + } + printf("ReinitializeDevice: new BACnet/SC certificates saved\n"); + g_reloadCredentialsRequested = true; // Service() reloads TLS, outside this callback + return true; +} + +bool NetworkPortCommand(const uint32_t command, uint32_t* errorCode) { + if (command == NETWORK_PORT_COMMAND_DISCARD_CHANGES) { + CertStore::DiscardStaged(); + printf("Network Port %u Command DISCARD_CHANGES: staged certificate writes discarded\n", + g_networkPortInstance); + return true; + } + if (command == NETWORK_PORT_COMMAND_GENERATE_CSR_FILE) { + std::string reason; + if (!CertStore::GenerateKeyAndCsr(&reason)) { + printf("Network Port %u Command GENERATE_CSR_FILE: FAILED: %s\n", g_networkPortInstance, reason.c_str()); + *errorCode = ERROR_CODE_INVALID_CONFIGURATION_DATA; + return false; + } + printf("Network Port %u Command GENERATE_CSR_FILE: a new key pair and signing request (File %u)\n", + g_networkPortInstance, FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE); + return true; + } + *errorCode = ERROR_CODE_OPTIONAL_FUNCTIONALITY_NOT_SUPPORTED; + return false; +} + +} // namespace ScNode diff --git a/sc/ScNode.h b/sc/ScNode.h new file mode 100644 index 0000000..ede391f --- /dev/null +++ b/sc/ScNode.h @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see ../LICENSE. +#ifndef BBC_EXAMPLE_SC_NODE_H +#define BBC_EXAMPLE_SC_NODE_H + +// ScNode.h +// ============================================================================= +// --datalink sc: this device as a BACnet/SC NODE (ANSI/ASHRAE 135-2024 Annex +// AB) - it connects to a hub, and every BACnet message goes through that hub. +// +// What the application does for BACnet/SC, in the order main() calls it: +// +// 1. PrepareCertificates() the device's certificate files, a CARI tree in +// --sc-cert-dir (the same layout and the same flow +// as the B-SCHUB example's hub): +// - the first start makes a private key, a certificate signing request +// and /node-cari-request.zip, and stops: send the zip to a +// Certificate Authority; +// - --import-cari installs what the CA sends back +// (ImportCari below); +// - every start after that runs with the installed certificate. +// 2. AddNetworkPort() Network Port 4 (secure-connect), its device UUID, +// the hub URIs, the BACnet/SC timing settings, and +// the four certificate File objects the port's +// certificate properties point at (Files 2-5). +// 3. Service() every main-loop pass: move WebSocket bytes, then +// report connection changes to the stack. +// +// The stack runs BACnet/SC itself; ScHubConnector does the TLS WebSocket. The +// certificate files can also be replaced over BACnet - the clause 19.8.3 +// certificate procedures, which CertStore implements (see cert_store.h). +// ============================================================================= + +#include +#include + +#include + +namespace ScNode { + +// The File objects BACnet/SC's certificate properties point at. File 1 (Ivory) +// is the backup/restore file and has nothing to do with BACnet/SC. +static const uint32_t FILE_OPERATIONAL_CERTIFICATE_INSTANCE = 2; // Operational_Certificate_File +static const uint32_t FILE_ISSUER_CERTIFICATE_1_INSTANCE = 3; // Issuer_Certificate_Files[1] +static const uint32_t FILE_ISSUER_CERTIFICATE_2_INSTANCE = 4; // Issuer_Certificate_Files[2] +static const uint32_t FILE_CERTIFICATE_SIGNING_REQUEST_INSTANCE = 5; // Certificate_Signing_Request_File + +// --import-cari: installs a CA's CARI response and returns the process exit code. +int ImportCari(const std::string& certDir, uint32_t deviceInstance, const std::string& zipPath); + +// Step 1. False when the device cannot connect yet (no certificate: the request +// zip was made, and how to go on has been printed) - main() then exits. +bool PrepareCertificates(const std::string& certDir, uint32_t deviceInstance, const char* deviceName); + +// Step 2, after BACnetStack_AddDevice(). Registers the BACnet/SC callbacks too. +bool AddNetworkPort(uint32_t deviceInstance, uint32_t networkPortInstance, const std::string& primaryHubUri, + const std::string& failoverHubUri); + +// Step 3. Also reloads the TLS certificates after a certificate procedure. +void Service(); + +// True once each time the device has connected to a hub (primary or +// failover): main() then announces itself with an I-Am. +bool TakeHubConnectedEvent(); + +// The URI of the hub this device is connected to now ("" when none). It is the +// connection string to hand BACnetStack_SendIAm / SendWhoIs for a broadcast: +// on BACnet/SC a broadcast goes to the hub, which sends it on to every node. +std::string ConnectedHubUri(); + +// The stack's message callbacks, for the BACnet/SC port. The connection string +// is the hub's URI. +uint16_t ReceiveFromHub(uint8_t* message, uint16_t maxMessageLength, uint8_t* sourceConnectionString, + uint8_t* sourceConnectionStringLength, uint8_t maxConnectionStringLength); +uint16_t SendToHub(const uint8_t* message, uint16_t messageLength, const uint8_t* connectionString, + uint8_t connectionStringLength); + +// --- The certificate File objects (Files 2-5) ------------------------------- +bool IsCertificateFile(uint32_t fileInstance); +const char* CertificateFileName(uint32_t fileInstance); +bool GetCertificateFileSize(uint32_t fileInstance, uint32_t* size); +bool IsCertificateFileReadOnly(uint32_t fileInstance); +bool GetCertificateFileModified(uint32_t fileInstance, struct tm* utc); +bool ReadCertificateFile(uint32_t fileInstance, uint32_t fileStart, uint32_t requestedCount, uint8_t* fileData, + uint32_t* fileDataLength, uint32_t maxFileDataLength, bool* endOfFile); +bool WriteCertificateFile(uint32_t fileInstance, int32_t fileStart, const uint8_t* fileData, uint32_t fileDataLength, + int32_t* ackFileStart, uint32_t* errorCode); +bool ResizeCertificateFile(uint32_t fileInstance, uint32_t newSize, uint32_t* errorCode); + +// ReinitializeDevice ACTIVATE_CHANGES / WARMSTART: checks and saves certificates +// written over BACnet. False (with *errorCode) if they would leave the device +// unable to connect - nothing is changed then. +bool ApplyStagedCertificates(uint32_t* errorCode); + +// Network Port Command DISCARD_CHANGES / GENERATE_CSR_FILE on the SC port. +bool NetworkPortCommand(uint32_t command, uint32_t* errorCode); + +} // namespace ScNode + +#endif // BBC_EXAMPLE_SC_NODE_H diff --git a/sc/cari.cpp b/sc/cari.cpp new file mode 100644 index 0000000..191bb62 --- /dev/null +++ b/sc/cari.cpp @@ -0,0 +1,559 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +// +// cari.cpp - see cari.h. + +#include "cari.h" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace Cari { +namespace { + +// --- little-endian helpers --------------------------------------------------- + +uint16_t Get16(const std::string& b, size_t at) { + return (uint16_t)((uint8_t)b[at] | ((uint8_t)b[at + 1] << 8)); +} +uint32_t Get32(const std::string& b, size_t at) { + return (uint32_t)Get16(b, at) | ((uint32_t)Get16(b, at + 2) << 16); +} +void Put16(std::string* b, uint16_t v) { + b->push_back((char)(v & 0xFF)); + b->push_back((char)(v >> 8)); +} +void Put32(std::string* b, uint32_t v) { + Put16(b, (uint16_t)(v & 0xFFFF)); + Put16(b, (uint16_t)(v >> 16)); +} + +const uint32_t LOCAL_HEADER_SIG = 0x04034b50; +const uint32_t CENTRAL_HEADER_SIG = 0x02014b50; +const uint32_t END_OF_CENTRAL_DIR_SIG = 0x06054b50; + +bool Inflate(const std::string& in, size_t expected, std::string* out) { + out->assign(expected, '\0'); + z_stream s; + std::memset(&s, 0, sizeof(s)); + if (inflateInit2(&s, -MAX_WBITS) != Z_OK) { // raw deflate, as zip stores it + return false; + } + s.next_in = (Bytef*)in.data(); + s.avail_in = (uInt)in.size(); + s.next_out = (Bytef*)&(*out)[0]; + s.avail_out = (uInt)expected; + const int rc = inflate(&s, Z_FINISH); + const bool ok = rc == Z_STREAM_END && s.total_out == expected; + inflateEnd(&s); + return ok || (expected == 0 && rc == Z_BUF_ERROR); +} + +std::string Deflate(const std::string& in) { + z_stream s; + std::memset(&s, 0, sizeof(s)); + deflateInit2(&s, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY); + std::string out(deflateBound(&s, (uLong)in.size()), '\0'); + s.next_in = (Bytef*)in.data(); + s.avail_in = (uInt)in.size(); + s.next_out = (Bytef*)&out[0]; + s.avail_out = (uInt)out.size(); + deflate(&s, Z_FINISH); + out.resize(s.total_out); + deflateEnd(&s); + return out; +} + +// A path a zip may name: relative, '/'-separated, no "." or ".." parts, no +// backslash, colon or control characters. +bool IsSafeZipPath(const std::string& path) { + if (path.empty() || path[0] == '/' || path.find('\\') != std::string::npos || + path.find(':') != std::string::npos) { + return false; + } + std::stringstream parts(path); + std::string part; + while (std::getline(parts, part, '/')) { + if (part.empty() || part == "." || part == "..") { + return false; + } + for (const char c : part) { + if ((unsigned char)c < 0x20 || c == 0x7F) { + return false; + } + } + } + return true; +} + +std::vector Split(const std::string& path) { + std::vector parts; + std::stringstream in(path); + std::string part; + while (std::getline(in, part, '/')) { + parts.push_back(part); + } + return parts; +} + +bool StartsWith(const std::string& s, const char* prefix) { + return s.compare(0, std::strlen(prefix), prefix) == 0; +} +bool EndsWith(const std::string& s, const char* suffix) { + const size_t n = std::strlen(suffix); + return s.size() >= n && s.compare(s.size() - n, n, suffix) == 0; +} + +// "device-12" -> 12, if it is a legal device folder name. +bool DeviceInstance(const std::string& folder, uint32_t* instance) { + if (!StartsWith(folder, "device-") || folder.size() == 7 || folder.size() > 14) { + return false; + } + const std::string digits = folder.substr(7); + if (digits.find_first_not_of("0123456789") != std::string::npos) { + return false; + } + const unsigned long v = std::strtoul(digits.c_str(), nullptr, 10); + if (v > 4194302UL) { + return false; + } + *instance = (uint32_t)v; + return true; +} + +// "csr-abc.pem" with prefix "csr-" -> "abc", if legal. +bool FileName(const std::string& file, const char* prefix, std::string* name) { + if (!StartsWith(file, prefix) || !EndsWith(file, ".pem")) { + return false; + } + *name = file.substr(std::strlen(prefix), file.size() - std::strlen(prefix) - 4); + return IsValidName(*name); +} + +} // namespace + +// --- Tree ---------------------------------------------------------------------- + +void Tree::AddFolder(const std::string& path) { + std::string partial; + for (const std::string& part : Split(path)) { + partial += (partial.empty() ? "" : "/") + part; + folders.insert(partial); + } +} + +void Tree::AddFile(const std::string& path, const std::string& bytes) { + const size_t slash = path.rfind('/'); + if (slash != std::string::npos) { + AddFolder(path.substr(0, slash)); + } + files[path] = bytes; +} + +void Tree::Remove(const std::string& path) { + files.erase(path); +} + +bool IsValidName(const std::string& text) { + if (text.empty() || text.size() > 128) { + return false; + } + for (const char c : text) { + const unsigned char u = (unsigned char)c; + if (u < 0x20 || u == 0x7F || std::strchr("<>:\"/\\|?*", c) != nullptr) { + return false; + } + } + return true; +} + +// --- zip ------------------------------------------------------------------------- + +bool ReadZip(const std::string& zip, Tree* out, std::string* error) { + *out = Tree(); + if (zip.size() > MAX_ZIP_BYTES) { + *error = "the file is " + std::to_string(zip.size()) + " bytes; the limit is " + + std::to_string(MAX_ZIP_BYTES); + return false; + } + if (zip.size() < 22 || Get32(zip, 0) != LOCAL_HEADER_SIG) { + *error = "not a zip file (a CARI file is a .zip with a cert1/ folder in it)"; + return false; + } + // The end-of-central-directory record: within the last 64 KiB + 22 bytes. + size_t eocd = std::string::npos; + const size_t lowest = zip.size() > 65557 ? zip.size() - 65557 : 0; + for (size_t at = zip.size() - 22 + 1; at-- > lowest;) { + if (Get32(zip, at) == END_OF_CENTRAL_DIR_SIG) { + eocd = at; + break; + } + } + if (eocd == std::string::npos) { + *error = "the zip file is damaged (no end-of-central-directory record)"; + return false; + } + const uint16_t entries = Get16(zip, eocd + 10); + const uint32_t cdSize = Get32(zip, eocd + 12); + const uint32_t cdOffset = Get32(zip, eocd + 16); + if (Get16(zip, eocd + 4) != 0 || Get16(zip, eocd + 6) != 0 || entries != Get16(zip, eocd + 8)) { + *error = "multi-part zip files are not supported"; + return false; + } + if (entries > MAX_ENTRIES) { + *error = "the zip has " + std::to_string(entries) + " entries; the limit is " + std::to_string(MAX_ENTRIES); + return false; + } + if ((uint64_t)cdOffset + cdSize > eocd) { + *error = "the zip file is damaged (central directory out of range)"; + return false; + } + size_t total = 0; + size_t at = cdOffset; + for (uint16_t i = 0; i < entries; ++i) { + if (at + 46 > eocd || Get32(zip, at) != CENTRAL_HEADER_SIG) { + *error = "the zip file is damaged (central directory entry " + std::to_string(i) + ")"; + return false; + } + const uint16_t flags = Get16(zip, at + 8); + const uint16_t method = Get16(zip, at + 10); + const uint32_t crc = Get32(zip, at + 16); + const uint32_t csize = Get32(zip, at + 20); + const uint32_t usize = Get32(zip, at + 24); + const uint16_t nameLen = Get16(zip, at + 28); + const uint16_t extraLen = Get16(zip, at + 30); + const uint16_t commentLen = Get16(zip, at + 32); + const uint32_t localOffset = Get32(zip, at + 42); + if (at + 46 + nameLen > eocd) { + *error = "the zip file is damaged (entry name out of range)"; + return false; + } + std::string name = zip.substr(at + 46, nameLen); + at += 46 + nameLen + extraLen + commentLen; + + if ((flags & 0x0001) != 0) { + *error = "\"" + name + "\" is encrypted; CARI files are not"; + return false; + } + if (csize == 0xFFFFFFFF || usize == 0xFFFFFFFF || localOffset == 0xFFFFFFFF) { + *error = "zip64 files are not supported"; + return false; + } + if (method != 0 && method != 8) { + *error = "\"" + name + "\" uses compression method " + std::to_string(method) + + "; only stored (0) and deflate (8) are supported"; + return false; + } + const bool isFolder = !name.empty() && name.back() == '/'; + if (isFolder) { + name.pop_back(); + } + if (!IsSafeZipPath(name)) { + *error = "unsafe path in the zip: \"" + name + "\""; + return false; + } + if (isFolder) { + out->AddFolder(name); + continue; + } + total += usize; + if (total > MAX_TOTAL_UNCOMPRESSED) { + *error = "the zip unpacks to more than " + std::to_string(MAX_TOTAL_UNCOMPRESSED) + " bytes"; + return false; + } + if ((uint64_t)localOffset + 30 > zip.size() || Get32(zip, localOffset) != LOCAL_HEADER_SIG) { + *error = "the zip file is damaged (local header for \"" + name + "\")"; + return false; + } + const size_t dataAt = localOffset + 30 + Get16(zip, localOffset + 26) + Get16(zip, localOffset + 28); + if ((uint64_t)dataAt + csize > zip.size()) { + *error = "the zip file is damaged (data for \"" + name + "\" out of range)"; + return false; + } + const std::string compressed = zip.substr(dataAt, csize); + std::string data; + if (method == 0) { + if (csize != usize) { + *error = "the zip file is damaged (size of \"" + name + "\")"; + return false; + } + data = compressed; + } else if (!Inflate(compressed, usize, &data)) { + *error = "could not decompress \"" + name + "\""; + return false; + } + if (crc32(0L, (const Bytef*)data.data(), (uInt)data.size()) != crc) { + *error = "\"" + name + "\" is damaged (CRC mismatch)"; + return false; + } + if (out->files.count(name) != 0) { + *error = "\"" + name + "\" appears twice in the zip"; + return false; + } + out->AddFile(name, data); + } + return true; +} + +std::string WriteZip(const Tree& tree) { + // Every folder (with a trailing '/') then every file, in path order, so the + // zip lists cert1/ first. + struct Entry { + std::string name; + std::string data; + }; + std::vector entries; + for (const std::string& folder : tree.folders) { + entries.push_back({folder + "/", std::string()}); + } + for (const auto& file : tree.files) { + entries.push_back({file.first, file.second}); + } + + // DOS date/time of "now", for every entry. + const time_t now = time(nullptr); + struct tm t; +#if defined(_WIN32) + localtime_s(&t, &now); +#else + localtime_r(&now, &t); +#endif + const uint16_t dosTime = (uint16_t)((t.tm_hour << 11) | (t.tm_min << 5) | (t.tm_sec / 2)); + const uint16_t dosDate = (uint16_t)(((t.tm_year - 80) << 9) | ((t.tm_mon + 1) << 5) | t.tm_mday); + + std::string zip; + std::string central; + for (const Entry& e : entries) { + const bool isFolder = e.name.back() == '/'; + const std::string body = isFolder ? std::string() : Deflate(e.data); + const uint16_t method = isFolder ? 0 : 8; + const uint32_t crc = (uint32_t)crc32(0L, (const Bytef*)e.data.data(), (uInt)e.data.size()); + const uint32_t offset = (uint32_t)zip.size(); + + Put32(&zip, LOCAL_HEADER_SIG); + Put16(&zip, 20); // version needed + Put16(&zip, 0x0800); // UTF-8 names + Put16(&zip, method); + Put16(&zip, dosTime); + Put16(&zip, dosDate); + Put32(&zip, crc); + Put32(&zip, (uint32_t)body.size()); + Put32(&zip, (uint32_t)e.data.size()); + Put16(&zip, (uint16_t)e.name.size()); + Put16(&zip, 0); + zip += e.name; + zip += body; + + Put32(¢ral, CENTRAL_HEADER_SIG); + Put16(¢ral, 20); // version made by + Put16(¢ral, 20); + Put16(¢ral, 0x0800); + Put16(¢ral, method); + Put16(¢ral, dosTime); + Put16(¢ral, dosDate); + Put32(¢ral, crc); + Put32(¢ral, (uint32_t)body.size()); + Put32(¢ral, (uint32_t)e.data.size()); + Put16(¢ral, (uint16_t)e.name.size()); + Put16(¢ral, 0); // extra + Put16(¢ral, 0); // comment + Put16(¢ral, 0); // disk + Put16(¢ral, 0); // internal attributes + Put32(¢ral, isFolder ? 0x10 : 0); // external: MS-DOS directory bit + Put32(¢ral, offset); + central += e.name; + } + const uint32_t cdOffset = (uint32_t)zip.size(); + zip += central; + Put32(&zip, END_OF_CENTRAL_DIR_SIG); + Put16(&zip, 0); + Put16(&zip, 0); + Put16(&zip, (uint16_t)entries.size()); + Put16(&zip, (uint16_t)entries.size()); + Put32(&zip, (uint32_t)central.size()); + Put32(&zip, cdOffset); + Put16(&zip, 0); + return zip; +} + +// --- CARI rules --------------------------------------------------------------------- + +bool Validate(const Tree& tree, bool response, std::vector* problems) { + problems->clear(); + auto problem = [problems](const std::string& path, const std::string& why) { + problems->push_back(path + ": " + why); + }; + bool sawDevice = false; + std::set devicesWithPort; + + for (const std::string& folder : tree.folders) { + const std::vector p = Split(folder); + uint32_t instance = 0; + if (p[0] != "cert1") { + problem(folder, "everything must be inside the cert1/ folder"); + } else if (p.size() == 1) { + // cert1 itself + } else if (p.size() == 2 && p[1] == "issuer") { + if (!response) { + problem(folder, "issuer/ belongs in a response, not a request"); + } + } else if (!DeviceInstance(p[1], &instance)) { + problem(folder, "a folder in cert1/ must be device- (0..4194302) or issuer"); + } else if (p.size() == 2) { + sawDevice = true; + } else if (p.size() == 3 && p[2] == "router") { + // empty marker: the device routes between BACnet/SC networks + } else if (!StartsWith(p[2], "port-") || !IsValidName(p[2].substr(5))) { + problem(folder, "a folder in a device folder must be router or port- (no < > : \" / \\ | ? *)"); + } else if (p.size() == 3) { + devicesWithPort.insert(p[1]); + } else if (p.size() == 4 && p[3] == "hub") { + // empty marker: this port is a hub function + } else { + problem(folder, "unexpected folder (a port folder may only contain hub/)"); + } + } + + for (const auto& file : tree.files) { + const std::string& path = file.first; + const size_t size = file.second.size(); + const std::vector p = Split(path); + std::string name; + uint32_t instance = 0; + if (p[0] != "cert1" || p.size() < 2) { + problem(path, "everything must be inside the cert1/ folder"); + } else if (p.size() == 2) { + if (p[1] == "vendor-data") { + if (size > MAX_VENDOR_DATA) problem(path, "larger than 1 MB"); + } else if (p[1] == "request-notes.txt") { + if (size > MAX_NOTES) problem(path, "larger than 10 kB"); + } else if (response && (p[1] == "response-notes.txt" || p[1] == "errors.txt")) { + if (size > MAX_NOTES && p[1] != "errors.txt") problem(path, "larger than 10 kB"); + } else { + problem(path, "not a CARI file name (cert1/ may hold vendor-data, request-notes.txt" + + std::string(response ? ", response-notes.txt, errors.txt" : "") + ")"); + } + } else if (p.size() == 3 && p[1] == "issuer") { + if (!response) { + problem(path, "issuer files belong in a response, not a request"); + } else if (p[2] != "iss-1.pem" && p[2] != "iss-2.pem") { + problem(path, "the issuer folder may only hold iss-1.pem and iss-2.pem"); + } + } else if (p.size() == 4 && DeviceInstance(p[1], &instance) && StartsWith(p[2], "port-")) { + const bool known = FileName(p[3], "csr-", &name) || FileName(p[3], "key-", &name) || + (response && FileName(p[3], "opr-", &name)); + if (!known) { + problem(path, std::string("a port folder may only hold csr-.pem, key-.pem") + + (response ? ", opr-.pem" : "") + " (no < > : \" / \\ | ? * in )"); + } else if (size > MAX_PEM) { + problem(path, "larger than 64 kB"); + } + } else { + problem(path, "not a place a CARI file can be"); + } + } + + if (!sawDevice) { + problems->push_back("cert1/: there is no device- folder"); + } + for (const std::string& folder : tree.folders) { + const std::vector p = Split(folder); + uint32_t instance = 0; + if (p.size() == 2 && DeviceInstance(p[1], &instance) && devicesWithPort.count(p[1]) == 0) { + problem(folder, "a device folder must contain at least one port- folder"); + } + } + return problems->empty(); +} + +std::vector ListCsrs(const Tree& tree) { + std::vector csrs; + for (const auto& file : tree.files) { + const std::vector p = Split(file.first); + CsrEntry e; + if (p.size() != 4 || p[0] != "cert1" || !DeviceInstance(p[1], &e.deviceInstance) || + !StartsWith(p[2], "port-") || !FileName(p[3], "csr-", &e.name)) { + continue; + } + e.deviceFolder = p[1]; + e.portFolder = p[2]; + const std::string port = "cert1/" + p[1] + "/" + p[2]; + e.csrPath = file.first; + e.oprPath = port + "/opr-" + e.name + ".pem"; + e.keyPath = tree.Has(port + "/key-" + e.name + ".pem") ? port + "/key-" + e.name + ".pem" : std::string(); + e.isHubPort = tree.folders.count(port + "/hub") != 0; + e.isRouter = tree.folders.count("cert1/" + p[1] + "/router") != 0; + csrs.push_back(e); + } + return csrs; +} + +// --- disk ---------------------------------------------------------------------------- + +bool WriteToDir(const Tree& tree, const std::string& baseDir, std::string* error) { + const fs::path base(baseDir); + std::error_code ec; + for (const std::string& folder : tree.folders) { + if (!IsSafeZipPath(folder)) { + *error = "unsafe folder \"" + folder + "\""; + return false; + } + fs::create_directories(base / fs::path(folder), ec); + } + for (const auto& file : tree.files) { + if (!IsSafeZipPath(file.first)) { + *error = "unsafe path \"" + file.first + "\""; + return false; + } + const fs::path path = base / fs::path(file.first); + fs::create_directories(path.parent_path(), ec); + std::ofstream f(path, std::ios::binary | std::ios::trunc); + if (!f) { + *error = "could not write \"" + path.string() + "\""; + return false; + } + f.write(file.second.data(), (std::streamsize)file.second.size()); + f.close(); + if (path.filename().string().compare(0, 4, "key-") == 0) { + fs::permissions(path, fs::perms::owner_read | fs::perms::owner_write, fs::perm_options::replace, ec); + } + } + return true; +} + +bool ReadFromDir(const std::string& baseDir, Tree* out, std::string* error) { + *out = Tree(); + const fs::path base(baseDir); + std::error_code ec; + if (!fs::is_directory(base / "cert1", ec)) { + *error = "no cert1/ folder in \"" + baseDir + "\""; + return false; + } + out->AddFolder("cert1"); + for (auto it = fs::recursive_directory_iterator(base / "cert1", ec); !ec && it != fs::recursive_directory_iterator(); + it.increment(ec)) { + const std::string rel = fs::relative(it->path(), base, ec).generic_string(); + if (it->is_directory()) { + out->AddFolder(rel); + } else if (it->is_regular_file()) { + std::ifstream f(it->path(), std::ios::binary); + std::stringstream bytes; + bytes << f.rdbuf(); + out->AddFile(rel, bytes.str()); + } + } + return true; +} + +} // namespace Cari diff --git a/sc/cari.h b/sc/cari.h new file mode 100644 index 0000000..8e13152 --- /dev/null +++ b/sc/cari.h @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +#ifndef BSCHUB_EXAMPLE_CARI_H +#define BSCHUB_EXAMPLE_CARI_H + +// cari.h +// ============================================================================= +// CARI files: Certificate Authority Requirements Interchange, ANSI/ASHRAE +// 135-2024 Annex AA.2 (Addendum cs to 135-2020). A CARI file is a zip of a +// strict folder tree with the root folder cert1/: +// +// cert1/vendor-data, request-notes.txt optional (request) +// cert1/response-notes.txt, errors.txt optional / on errors (response) +// cert1/device-/ one per device +// router/ empty: it routes between SC networks +// port-/ one per BACnet/SC port +// hub/ empty: this port is a hub function +// csr-.pem the request (PKCS#10) +// key-.pem optional; the CA ignores it but keeps it +// opr-.pem the signed operational certificate (response) +// cert1/issuer/iss-1.pem, iss-2.pem the issuer(s) (response) +// +// This file holds the zip reader/writer (on zlib) and the tree model. The +// signing itself is in cert_tool.cpp. The zip reader is written for input +// from anyone: it checks sizes, entry counts, compression methods and every +// path before anything is extracted, and refuses anything else. +// ============================================================================= + +#include + +#include +#include +#include +#include + +namespace Cari { + +// Limits (AA.2.1.1/AA.2.1.2 for the notes and vendor-data; the rest are this +// hub's own, generous for a site's worth of devices). +static const size_t MAX_ZIP_BYTES = 4 * 1024 * 1024; +static const size_t MAX_ENTRIES = 4096; +static const size_t MAX_TOTAL_UNCOMPRESSED = 16 * 1024 * 1024; +static const size_t MAX_VENDOR_DATA = 1024 * 1024; +static const size_t MAX_NOTES = 10 * 1024; +static const size_t MAX_PEM = 64 * 1024; + +// A CARI tree in memory: file path -> contents, and the (possibly empty) +// folders. Paths are relative, '/'-separated, start with "cert1", and have no +// trailing '/'. +struct Tree { + std::map files; + std::set folders; + + void AddFile(const std::string& path, const std::string& bytes); // adds the parent folders too + void AddFolder(const std::string& path); // and its parents + void Remove(const std::string& path); + bool Has(const std::string& path) const { return files.count(path) != 0; } +}; + +// One CSR in a request, and where its answer goes. +struct CsrEntry { + std::string deviceFolder; // "device-12" + uint32_t deviceInstance = 0; + std::string portFolder; // "port-1" + std::string name; // the in csr-.pem + std::string csrPath; // "cert1/device-12/port-1/csr-.pem" + std::string oprPath; // the matching opr-.pem + std::string keyPath; // key-.pem ("" if absent) + bool isHubPort = false; // the port folder has hub/ + bool isRouter = false; // the device folder has router/ +}; + +// --- zip --------------------------------------------------------------------- + +// Reads a zip (stored or deflate entries only; no encryption, no zip64). +// Folder entries ("name/") go to `folders`. False with a reason on anything +// malformed or over the limits above. +bool ReadZip(const std::string& zipBytes, Tree* out, std::string* error); + +// Writes `tree` as a zip (deflate), folders as their own entries so empty +// ones (hub/, router/) survive. +std::string WriteZip(const Tree& tree); + +// --- CARI rules ---------------------------------------------------------------- + +// Checks every path against AA.2.1 (only the names above, legal characters in +// and , device instances 0..4194302, sizes) and that there is at +// least one device folder with one port folder. `response` also allows the +// response-only names. Each problem is one line in *problems. +bool Validate(const Tree& tree, bool response, std::vector* problems); + +// Every csr-*.pem in the tree. +std::vector ListCsrs(const Tree& tree); + +// True if `text` may be a port or a file : printable, non-empty, +// and none of < > : " / \ | ? *. +bool IsValidName(const std::string& text); + +// --- disk ------------------------------------------------------------------------ + +// Writes the tree under baseDir (baseDir/cert1/...), creating folders. Never +// writes outside baseDir. Private keys get owner-only permissions. +bool WriteToDir(const Tree& tree, const std::string& baseDir, std::string* error); + +// Reads baseDir/cert1/ back into a tree. False if there is no cert1/. +bool ReadFromDir(const std::string& baseDir, Tree* out, std::string* error); + +} // namespace Cari + +#endif // BSCHUB_EXAMPLE_CARI_H diff --git a/sc/cert_layout.cpp b/sc/cert_layout.cpp new file mode 100644 index 0000000..100c025 --- /dev/null +++ b/sc/cert_layout.cpp @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +// +// cert_layout.cpp - see cert_layout.h. + +#include "cert_layout.h" + +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace CertLayout { +namespace { + +std::string Join(const fs::path& directory, const std::string& relative) { + return (directory / fs::path(relative)).generic_string(); +} + +// "device-389005" -> 389005. False if `name` isn't device-<0..4194302>. +bool ParseDeviceFolder(const std::string& name, uint32_t* instance) { + const std::string prefix = "device-"; + if (name.compare(0, prefix.size(), prefix) != 0 || name.size() == prefix.size()) { + return false; + } + const std::string digits = name.substr(prefix.size()); + if (digits.find_first_not_of("0123456789") != std::string::npos || digits.size() > 7) { + return false; + } + errno = 0; + const unsigned long value = std::strtoul(digits.c_str(), nullptr, 10); + if (errno == ERANGE || value > 4194302UL) { + return false; + } + *instance = (uint32_t)value; + return true; +} + +// Every cert1/device-*/port-4/ folder that holds one of this device's node +// files, as (relative port folder, device instance). +std::vector> FindNodePorts(const fs::path& certDir) { + std::vector> found; + const std::string portName = std::string("port-") + NODE_PORT_ID; + const std::string fileName = NODE_FILE_NAME; + std::error_code directoryError; + for (const auto& device : fs::directory_iterator(certDir / "cert1", directoryError)) { + uint32_t instance = 0; + if (!device.is_directory() || !ParseDeviceFolder(device.path().filename().string(), &instance)) { + continue; + } + const fs::path port = device.path() / portName; + if (fs::exists(port / ("key-" + fileName + ".pem")) || fs::exists(port / ("csr-" + fileName + ".pem")) || + fs::exists(port / ("opr-" + fileName + ".pem"))) { + found.emplace_back("cert1/" + device.path().filename().string() + "/" + portName, instance); + } + } + return found; +} + +void FillCari(NodeCertPaths* paths, const fs::path& directory, const std::string& portFolder, uint32_t instance) { + paths->certDir = directory.generic_string(); + paths->trustedIssuers = Join(directory, "trusted-issuers.pem"); + paths->portFolder = portFolder; + paths->folderDeviceInstance = instance; + const std::string name = NODE_FILE_NAME; + paths->operationalCertificate = Join(directory, portFolder + "/opr-" + name + ".pem"); + paths->certificateSigningRequest = Join(directory, portFolder + "/csr-" + name + ".pem"); + paths->privateKey = Join(directory, portFolder + "/key-" + name + ".pem"); + paths->issuerCertificate1 = Join(directory, "cert1/issuer/iss-1.pem"); + paths->issuerCertificate2 = Join(directory, "cert1/issuer/iss-2.pem"); + paths->pendingPrivateKey = Join(directory, "key-" + name + "-pending.pem"); +} + +// The paths a NEW set uses: cert1/device-/port-4. +NodeCertPaths NewNodeCertPaths(const std::string& certDir, uint32_t deviceInstance) { + NodeCertPaths paths; + FillCari(&paths, fs::path(certDir), "cert1/device-" + std::to_string(deviceInstance) + "/port-" + NODE_PORT_ID, + deviceInstance); + return paths; +} + +} // namespace + +NodeCertPaths ResolveNodeCertPaths(const std::string& certDirArgument, uint32_t deviceInstance) { + const fs::path directory(certDirArgument); + std::error_code directoryError; + if (!fs::is_directory(directory / "cert1", directoryError)) { + return NewNodeCertPaths(certDirArgument, deviceInstance); // nothing yet + } + const std::vector> ports = FindNodePorts(directory); + if (ports.empty()) { + return NewNodeCertPaths(certDirArgument, deviceInstance); + } + size_t chosenIndex = 0; + for (size_t portIndex = 0; portIndex < ports.size(); ++portIndex) { + if (ports[portIndex].second == deviceInstance) { + chosenIndex = portIndex; + } + } + NodeCertPaths paths; + FillCari(&paths, directory, ports[chosenIndex].first, ports[chosenIndex].second); + if (ports[chosenIndex].second != deviceInstance) { + paths.note = "the certificate folder " + ports[chosenIndex].first + " is for device instance " + + std::to_string(ports[chosenIndex].second) + ", but this device is " + + std::to_string(deviceInstance) + "; using it anyway (rename the folder to device-" + + std::to_string(deviceInstance) + " to match)"; + } + if (ports.size() > 1) { + paths.note += std::string(paths.note.empty() ? "" : "; ") + std::to_string(ports.size()) + + " node port folders found under cert1/, using " + ports[chosenIndex].first; + } + return paths; +} + +std::string RelativeTo(const std::string& base, const std::string& path) { + std::error_code relativeError; + const fs::path relative = fs::relative(fs::path(path), fs::path(base), relativeError); + if (relativeError || relative.empty() || relative.generic_string().compare(0, 2, "..") == 0) { + return fs::path(path).generic_string(); + } + return relative.generic_string(); +} + +} // namespace CertLayout diff --git a/sc/cert_layout.h b/sc/cert_layout.h new file mode 100644 index 0000000..8abcec5 --- /dev/null +++ b/sc/cert_layout.h @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +#ifndef BBC_EXAMPLE_CERT_LAYOUT_H +#define BBC_EXAMPLE_CERT_LAYOUT_H + +// cert_layout.h +// ============================================================================= +// Where this device's BACnet/SC certificate files are in --sc-cert-dir. The ONE +// place that knows the file names; everything else asks ResolveNodeCertPaths(). +// +// Copied from the B-SCHUB example (BACnetProfileExample-B-SCHUB-CPP), where the +// same folder holds a HUB's certificate. This device is a BACnet/SC NODE - it +// connects to a hub - so its port folder has no hub/ marker, and its files are +// called "node" instead of "hub". Everything else is the same. +// +// The folder is a CARI tree (Certificate Authority Requirements Interchange, +// ANSI/ASHRAE 135-2024 Annex AA.2) for this device: +// +// / +// cert1/ only CARI files in here +// device-/port-4/ Network Port 4, the BACnet/SC port +// csr-node.pem File 5 Certificate_Signing_Request_File +// opr-node.pem File 2 Operational_Certificate_File +// key-node.pem the operational certificate's key (no File object) +// issuer/iss-1.pem File 3 Issuer_Certificate_Files[1] +// issuer/iss-2.pem File 4 Issuer_Certificate_Files[2] (optional) +// key-node-pending.pem GENERATE_CSR_FILE's new key, until activated +// trusted-issuers.pem written at start-up (every issuer this device trusts) +// node-cari-request.zip written at start-up if missing, for the CA +// ============================================================================= + +#include + +#include + +namespace CertLayout { + +// The CARI port folder this device uses: Network Port 4, its BACnet/SC port +// (main.cpp's SC_NETWORK_PORT_INSTANCE). +static const char* const NODE_PORT_ID = "4"; +// The in this device's own csr-/opr-/key- file names. +static const char* const NODE_FILE_NAME = "node"; + +struct NodeCertPaths { + std::string certDir; + // The port folder in use (relative to certDir), e.g. + // "cert1/device-389005/port-4", and the instance in its name. + std::string portFolder; + uint32_t folderDeviceInstance = 0; + // A note for the start-up log, e.g. that the folder's device instance + // differs from the device's own. Empty if nothing to say. + std::string note; + + // Full paths. Every one is set, whether or not the file exists yet. + std::string operationalCertificate; // Operational_Certificate_File + std::string certificateSigningRequest; // Certificate_Signing_Request_File + std::string issuerCertificate1; // Issuer_Certificate_Files[1] + std::string issuerCertificate2; // Issuer_Certificate_Files[2] (may not exist: then it serves [1]) + std::string privateKey; + std::string pendingPrivateKey; // GENERATE_CSR_FILE + std::string trustedIssuers; // written at start-up +}; + +// Works out the paths in certDir. `deviceInstance` names the CARI device +// folder for a new set; an existing CARI tree is found by looking for +// cert1/device-*/port-4/ with a node file in it, so a tree made for another +// device instance is still used (with a note). +NodeCertPaths ResolveNodeCertPaths(const std::string& certDir, uint32_t deviceInstance); + +// `path` relative to `base` with '/' separators, or `path` itself if it isn't +// under `base`. For messages. +std::string RelativeTo(const std::string& base, const std::string& path); + +} // namespace CertLayout + +#endif // BBC_EXAMPLE_CERT_LAYOUT_H diff --git a/sc/cert_store.cpp b/sc/cert_store.cpp new file mode 100644 index 0000000..d4e20ea --- /dev/null +++ b/sc/cert_store.cpp @@ -0,0 +1,683 @@ +// SPDX-License-Identifier: CC0-1.0 +// Public-domain example code (CC0) - see LICENSE. +// +// cert_store.cpp - see cert_store.h for what this does and why. + +#include "cert_store.h" +#include "KeyPassword.h" + +#include +#include +#include +#include +#include +#include +#include // X509_check_ca, X509_PURPOSE_* + +#include +#include + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include // _commit - flush a file to disk +#include // MoveFileExA - an atomic replace that works over an existing file +#else +#include // open(O_CREAT | O_EXCL, 0600) - private temp files +#include // fsync, close +#endif + +namespace fs = std::filesystem; + +namespace CertStore { +namespace { + +// BACnetErrorCode values the stack honours for AtomicWriteFile / WriteProperty. +const uint32_t ERROR_INVALID_FILE_START_POSITION = 11; +const uint32_t ERROR_FILE_FULL = 128; +const uint32_t ERROR_VALUE_OUT_OF_RANGE = 37; + +struct Staged { + std::string bytes; + time_t modified = 0; +}; + +Layout g_layout; +std::map g_staged; // file instance -> staged contents +// Set by ValidateStaged() when the staged operational certificate is for the +// pending key (GENERATE_CSR_FILE) rather than the current one; CommitStaged() +// then swaps the pending key in. +bool g_commitPromotesPendingKey = false; + +bool ReadDisk(const std::string& path, std::string* out) { + std::ifstream f(path, std::ios::binary); + if (!f) { + return false; + } + out->assign(std::istreambuf_iterator(f), std::istreambuf_iterator()); + return true; +} + +// The file a File object's bytes live in, or "" if it isn't one we manage. +std::string OwnPath(uint32_t fileInstance) { + auto it = g_layout.paths.find(fileInstance); + return it == g_layout.paths.end() ? std::string() : it->second; +} + +// The File object this one serves instead, while it has no staged copy and +// no file of its own (Issuer Certificate slot 2 serves slot 1 until something +// is written to it), or 0. +uint32_t FallbackInstance(uint32_t fileInstance) { + if (g_staged.count(fileInstance) != 0) { + return 0; + } + std::error_code ec; + const std::string path = OwnPath(fileInstance); + if (path.empty() || fs::exists(path, ec)) { + return 0; + } + auto fb = g_layout.readFallbackInstances.find(fileInstance); + return fb == g_layout.readFallbackInstances.end() ? 0 : fb->second; +} + +// The staged copy of a File object, created from its current contents on the +// first write since the last commit. +Staged* Stage(uint32_t fileInstance) { + auto it = g_staged.find(fileInstance); + if (it != g_staged.end()) { + return &it->second; + } + if (g_layout.paths.find(fileInstance) == g_layout.paths.end()) { + return nullptr; + } + Staged s; + if (!Read(fileInstance, &s.bytes)) { // a missing file stages as empty + s.bytes.clear(); + } + s.modified = time(NULL); + return &(g_staged[fileInstance] = s); +} + +void FreeAll(std::vector* certs) { + for (X509* c : *certs) { + X509_free(c); + } + certs->clear(); +} + +// Splits a PEM blob into its "-----BEGIN