From eae67aaa0ee161bb04b0397a7d7ad157c951193b Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Wed, 28 Oct 2026 00:43:01 -0700 Subject: [PATCH 1/9] B-BC: BACnet/IPv6 build (-DBBC_IPV6=ON), SimpleUDP6, probe and README Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + CMakeLists.txt | 40 +++- common/SimpleUDP6.cpp | 285 +++++++++++++++++++++++++++ common/SimpleUDP6.h | 82 ++++++++ ipv6/README.md | 43 ++++ ipv6/cas_bacnet_stack_options_ipv6.h | 55 ++++++ main.cpp | 169 +++++++++++++--- submodules/cas-bacnet-stack | 2 +- tests/ipv6_probe.py | 239 ++++++++++++++++++++++ 9 files changed, 881 insertions(+), 35 deletions(-) create mode 100644 common/SimpleUDP6.cpp create mode 100644 common/SimpleUDP6.h create mode 100644 ipv6/README.md create mode 100644 ipv6/cas_bacnet_stack_options_ipv6.h create mode 100644 tests/ipv6_probe.py diff --git a/.gitignore b/.gitignore index 01c0e0c..a144452 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ build/ # Python bytecode from tests/ and wiretest/ __pycache__/ +build-*/ diff --git a/CMakeLists.txt b/CMakeLists.txt index ca56d94..3c9b834 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,6 +37,12 @@ endif() set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) +# --- BACnet/IPv6 -------------------------------------------------------------- +# cmake -B build-ipv6 -S . -DBBC_IPV6=ON builds the same device as a BACnet/IPv6 (Annex U) node instead of a BACnet/IP one: +# IPv6 is then the ONLY data link the stack is built with (ipv6/cas_bacnet_stack_options_ipv6.h), the socket is +# common/SimpleUDP6.cpp, and the executable is named BACnetExampleBBCIPv6. See ipv6/README.md. +option(BBC_IPV6 "Build the BACnet/IPv6 (Annex U) device instead of the BACnet/IP one" OFF) + # --- Locate the pieces this project ships ----------------------------------- # The shared helper is vendored into this repository at ./common. if(NOT DEFINED EXAMPLES_COMMON_DIR) @@ -64,20 +70,44 @@ endif() # submodules/cas-bacnet-stack/adapters/cpp/CMakeLists.txt for what each mode does. add_subdirectory("${CAS_STACK_DIR}/adapters/cpp" cas-bacnet-stack-adapter) +# --- The stack's options, for the IPv6 build ---------------------------------- +# The stack picks its option set from source/CIBuildSettingsDefaults.h unless told otherwise, and that is the FULL target with every +# data link. The IPv6 build forces its own header in front of every stack source (DONT_BUILD_ALL_OPTIONS says the defaults do not apply). +if(BBC_IPV6) + set(BBC_STACK_OPTIONS_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/ipv6/cas_bacnet_stack_options_ipv6.h") + target_compile_definitions(cas_bacnet_stack_adapter PUBLIC DONT_BUILD_ALL_OPTIONS) + if(MSVC) + target_compile_options(cas_bacnet_stack_adapter PUBLIC "/FI${BBC_STACK_OPTIONS_HEADER}") + else() + target_compile_options(cas_bacnet_stack_adapter PUBLIC "-include" "${BBC_STACK_OPTIONS_HEADER}") + endif() +endif() + # --- The shared example helper ---------------------------------------------- set(COMMON_SOURCES "${EXAMPLES_COMMON_DIR}/CASExampleHelper.cpp" - "${EXAMPLES_COMMON_DIR}/SimpleUDP.cpp") + "${EXAMPLES_COMMON_DIR}/SimpleUDP.cpp") # CASExampleHelper's own BACnet/IP socket, which this example does not open +if(BBC_IPV6) + list(APPEND COMMON_SOURCES "${EXAMPLES_COMMON_DIR}/SimpleUDP6.cpp") +endif() # --- The executable --------------------------------------------------------- -add_executable(BACnetExampleBBC +if(BBC_IPV6) + set(BBC_TARGET_NAME BACnetExampleBBCIPv6) +else() + set(BBC_TARGET_NAME BACnetExampleBBC) +endif() +add_executable(${BBC_TARGET_NAME} main.cpp ${COMMON_SOURCES}) +if(BBC_IPV6) + target_compile_definitions(${BBC_TARGET_NAME} PRIVATE BBC_IPV6) +endif() -target_include_directories(BACnetExampleBBC PRIVATE +target_include_directories(${BBC_TARGET_NAME} PRIVATE "${EXAMPLES_COMMON_DIR}") -target_link_libraries(BACnetExampleBBC PRIVATE CASBACnetStack::Adapter) +target_link_libraries(${BBC_TARGET_NAME} PRIVATE CASBACnetStack::Adapter) # --- Warnings on OUR sources only ------------------------------------------- # Apply strict warnings to the example + helper sources, but NOT to the bundled @@ -94,5 +124,5 @@ set_source_files_properties(main.cpp ${COMMON_SOURCES} # --- Platform sockets ------------------------------------------------------- # ws2_32 = Winsock (UDP); iphlpapi = GetAdaptersInfo (local broadcast address). if(WIN32) - target_link_libraries(BACnetExampleBBC PRIVATE ws2_32 iphlpapi) + target_link_libraries(${BBC_TARGET_NAME} PRIVATE ws2_32 iphlpapi) endif() 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/ipv6/README.md b/ipv6/README.md new file mode 100644 index 0000000..5ddfbd3 --- /dev/null +++ b/ipv6/README.md @@ -0,0 +1,43 @@ +# BACnet/IPv6 build of the B-BC example + +The same Building Controller device, speaking BACnet/IPv6 (ANSI/ASHRAE 135-2024 Annex U) instead of BACnet/IP. It is +a build option of this project, not a second program: `main.cpp` has `BBC_IPV6` branches where the two transports differ. + +## Build and run + +Needs a CAS BACnet Stack with the BACnet/IPv6 data link (cas-bacnet-stack#4609, slice 1; the submodule must point at +a commit that has it). + +```bash +cmake -B build-ipv6 -S . -DBBC_IPV6=ON +cmake --build build-ipv6 --config Release +build-ipv6/Release/BACnetExampleBBCIPv6 # Windows; build-ipv6/BACnetExampleBBCIPv6 elsewhere +``` + +IPv6 is the only data link this build contains (`ipv6/cas_bacnet_stack_options_ipv6.h`): with more than one transport the +stack needs a Network Port object to name the one a send goes out of, and the IPv6 Network Port object is a later slice +(#4611). The socket is `common/SimpleUDP6.cpp`; it joins the multicast group FF02::BAC0 on every IPv6 interface that is up. + +## 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, and (`--multicast`) checks that an Address-Resolution sent to FF02::BAC0 is +answered. Observed 2026-10-28 on Windows 11: 9/9 over the link-local address with `--multicast`, 8/8 over the global address. + +## 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`). +- The device's VMAC is its device instance in three octets. + +## Not yet + +Sending to a peer that has not spoken first (address resolution, #4610), the IPv6 Network Port object (#4611), BBMD and +foreign devices (#4612), and several devices behind one address (#4610 carries the request's source VMAC). diff --git a/ipv6/cas_bacnet_stack_options_ipv6.h b/ipv6/cas_bacnet_stack_options_ipv6.h new file mode 100644 index 0000000..bba9c97 --- /dev/null +++ b/ipv6/cas_bacnet_stack_options_ipv6.h @@ -0,0 +1,55 @@ +// The CAS BACnet Stack's feature switches for the BACnet/IPv6 build of this B-BC example (cmake -DBBC_IPV6=ON). +// +// CMakeLists.txt force-includes this header ahead of every stack source file and defines DONT_BUILD_ALL_OPTIONS, so it +// decides what is compiled: the B-BC profile and the 15 objects of B-BC-CPP, and BACnet/IPv6 as the ONLY data link. Every switch is +// documented in submodules/cas-bacnet-stack/source/CASBACnetStackOptions.h. It is the Zephyr example's options header with its data +// links replaced. +// +#ifndef CAS_BACNET_STACK_OPTIONS_IPV6_H +#define CAS_BACNET_STACK_OPTIONS_IPV6_H + +// A resource-constrained device: nothing is compiled unless it is asked for below. +#define STACK_OPTION_TARGET_EMBEDDED + +// The B-BC profile (Annex L.4.1): turns on the BIBBs a Building Controller requires - +// DM-DCC-B, DM-RD-B, DM-BR-B, DM-TS-B / DM-UTC-B, the alarm and event services and +// T-VMT-I-B. The core services (ReadProperty, WriteProperty, Who-Is/I-Am, +// Who-Has/I-Have) are always compiled. +#define STACK_OPTION_PROFILE_B_BC + +// The BIBBs B-BC needs that the profile switch leaves to you. +#define STACK_OPTION_SEGMENTATION // ReadPropertyMultiple answers bigger than one APDU +#define STACK_OPTION_AE_ACKNOWLEDGE_ALARMS // AE-ACK-B +#define STACK_OPTION_AE_INFORMATION // AE-INFO-B (GetEventInformation) +// Trend Log Multiple 1 "Multi-Point Trend" (part of B-BC-CPP's object set) needs T-VMMV. B-BC itself +// only requires T-VMT, so the profile switch does not turn it on: without this line +// BACnetStack_AddTrendLogMultipleObject() returns false. +#define STACK_OPTION_T_VMMV_TRENDING_VIEWING_AND_MODIFYING_MULTIPLE_VALUES + +// The embedded target limits character strings to 64 octets. B-BC-CPP's Device +// Description is longer, and a string over the limit makes the whole read fail +// (BACnetProfileExample-B-BC-CPP#7), so keep the full build's 256. +#define STACK_OPTION_MAX_CHARACTER_STRING_SIZE 256 + +// The object types this device has (B-BC-CPP's 15 objects). +#define STACK_OPTION_OBJECT_TYPE_ANALOG_INPUT +#define STACK_OPTION_OBJECT_TYPE_ANALOG_OUTPUT +#define STACK_OPTION_OBJECT_TYPE_ANALOG_VALUE +#define STACK_OPTION_OBJECT_TYPE_BINARY_INPUT +#define STACK_OPTION_OBJECT_TYPE_BINARY_OUTPUT +#define STACK_OPTION_OBJECT_TYPE_MULTISTATE_INPUT +#define STACK_OPTION_OBJECT_TYPE_MULTISTATE_OUTPUT +#define STACK_OPTION_OBJECT_TYPE_NOTIFICATION_CLASS +#define STACK_OPTION_OBJECT_TYPE_NETWORK_PORT +#define STACK_OPTION_OBJECT_TYPE_SCHEDULE +#define STACK_OPTION_OBJECT_TYPE_CALENDAR +#define STACK_OPTION_OBJECT_TYPE_FILE +#define STACK_OPTION_OBJECT_TYPE_TREND_LOG +#define STACK_OPTION_OBJECT_TYPE_TREND_LOG_MULTIPLE + +// The three datalinks. Only one is active at a time (chosen in the Dashboard), but all are +// compiled in so one image can switch between them. BACnet/SC needs IPV4 as well. +// BACnet/IPv6 (Annex U) is the only data link: this build speaks IPv6 and nothing else (cas-bacnet-stack#255). +#define STACK_OPTION_DATA_LINK_LAYER_IPV6 + +#endif // CAS_BACNET_STACK_OPTIONS_IPV6_H diff --git a/main.cpp b/main.cpp index c2dce5e..032461d 100644 --- a/main.cpp +++ b/main.cpp @@ -101,7 +101,11 @@ #include "CASExampleHelper.h" #include "CASBACnetStackExampleConstants.h" +#ifdef BBC_IPV6 +#include "SimpleUDP6.h" // BACnet/IPv6 build (cmake -DBBC_IPV6=ON): this example owns its BACnet/IPv6 socket - see section 2e +#else #include "SimpleUDP.h" // this example owns its BACnet/IP socket - see section 2e +#endif #include "CASBACnetStackAdapter.h" // the CAS BACnet Stack C API (BACnetStack_*); call // LoadBACnetFunctions() before any BACnetStack_* call - // see the top of main() below. @@ -1527,6 +1531,38 @@ bool AcknowledgeAlarm(const uint32_t deviceInstance, const uint32_t /*acknowledg // 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 // the limited broadcast 255.255.255.255.) +#ifdef BBC_IPV6 +// BACnet/IPv6 (Annex U): the stack's connection string for a peer is its B/IPv6 address - 16 octets of IPv6 address, then +// the 2-octet UDP port, most significant octet first - and a BACnet broadcast is sent with NO connection string, to the +// multicast group FF02::BAC0 (SimpleUDP6::SendMulticast). The stack has no Network Port object for an IPv6 port yet +// (cas-bacnet-stack#4611), so this build adds none and names its transport with the default port instance. +static const uint8_t TRANSPORT_ADDRESS_LENGTH = 16; +static const uint8_t TRANSPORT_CONNECTION_STRING_LENGTH = 18; +static const uint32_t TRANSPORT_PORT_INSTANCE = BACNET_NETWORK_PORT_DEFAULT; +#else +static const uint8_t TRANSPORT_ADDRESS_LENGTH = 4; +static const uint8_t TRANSPORT_CONNECTION_STRING_LENGTH = 6; +static const uint32_t TRANSPORT_PORT_INSTANCE = NETWORK_PORT_INSTANCE; +#endif + +// 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) { +#ifdef BBC_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])); +#endif + return text; +} + +#ifndef BBC_IPV6 static void LocalBroadcastConnString(uint8_t out[6]) { out[0] = (uint8_t)(g_ipAddress[0] | ~g_ipSubnetMask[0]); out[1] = (uint8_t)(g_ipAddress[1] | ~g_ipSubnetMask[1]); @@ -1535,6 +1571,7 @@ static void LocalBroadcastConnString(uint8_t out[6]) { out[4] = (uint8_t)(g_bacnetIpUdpPort >> 8); out[5] = (uint8_t)(g_bacnetIpUdpPort & 0xFF); } +#endif // !BBC_IPV6 // ----------------------------------------------------------------------------- // 2e. Reading another device's objects (DS-RP-A, DS-RPM-A) @@ -1554,13 +1591,18 @@ static void LocalBroadcastConnString(uint8_t out[6]) { // asked for by hand, which keeps the build to the two commands in the README. // ----------------------------------------------------------------------------- +#ifdef BBC_IPV6 +static SimpleUDP6 g_udp; +#else static SimpleUDP g_udp; +#endif // 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; + // TRANSPORT_CONNECTION_STRING_LENGTH of them uint8_t readPropertyInvokeId; // the outstanding ReadProperty, if any bool readPropertyPending; uint8_t readPropertyMultipleInvokeId; // the outstanding ReadPropertyMultiple, if any @@ -1629,14 +1671,14 @@ void HookIAm(const uint32_t deviceIdentifier, const uint32_t maxApduLengthAccept // 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) { + if (deviceIdentifier != REMOTE_DEVICE_INSTANCE || sourceNetwork != 0 || connectionStringLength != TRANSPORT_CONNECTION_STRING_LENGTH) { 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, TRANSPORT_CONNECTION_STRING_LENGTH) != 0) { + memcpy(g_peer.connectionString, connectionString, TRANSPORT_CONNECTION_STRING_LENGTH); + 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); } if (!g_peer.bound) { @@ -1696,8 +1738,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, TRANSPORT_CONNECTION_STRING_LENGTH, + TRANSPORT_PORT_INSTANCE, 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); @@ -1869,18 +1911,27 @@ 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) { + if (!g_peer.bound || memcmp(fromAddress, g_peer.connectionString, TRANSPORT_ADDRESS_LENGTH) != 0 || + fromPort != (uint16_t)((g_peer.connectionString[TRANSPORT_ADDRESS_LENGTH] << 8) | g_peer.connectionString[TRANSPORT_ADDRESS_LENGTH + 1])) { + return; + } +#ifdef BBC_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; } + size_t 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; } - // NPDU (cl. 6.2): version 1, control, then the optional DNET/SNET fields. size_t position = 4; +#endif + // NPDU (cl. 6.2): version 1, control, then the optional DNET/SNET fields. if (messageLength < position + 2 || message[position] != 0x01) { return; } @@ -1945,35 +1996,58 @@ uint16_t CallbackReceiveMessage(uint8_t* message, const uint16_t maxMessageLengt const uint8_t maxConnectionStringLength, uint32_t* networkPortInstance) { (void)destinationConnectionString; (void)destinationConnectionStringLength; - if (maxConnectionStringLength < 6) { + if (maxConnectionStringLength < TRANSPORT_CONNECTION_STRING_LENGTH) { 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_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, TRANSPORT_ADDRESS_LENGTH); + fromConnectionString[TRANSPORT_ADDRESS_LENGTH] = (uint8_t)(fromPort >> 8); + fromConnectionString[TRANSPORT_ADDRESS_LENGTH + 1] = (uint8_t)(fromPort & 0xFF); + printf("RX %u bytes from %s (Network Port %u)", (unsigned)received, + AddressText(fromConnectionString, fromText, sizeof(fromText)), TRANSPORT_PORT_INSTANCE); 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, TRANSPORT_CONNECTION_STRING_LENGTH); + *sourceConnectionStringLength = TRANSPORT_CONNECTION_STRING_LENGTH; + *networkPortInstance = TRANSPORT_PORT_INSTANCE; // 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) { + if (networkPortInstance != TRANSPORT_PORT_INSTANCE) { return 0; } + char destinationText[64]; +#ifdef BBC_IPV6 + // BACnet/IPv6: a broadcast carries no address (Annex U.4): the multicast group is this example's to choose. + if (broadcast || connectionString == NULL || connectionStringLength == 0) { + const uint16_t sent = g_udp.SendMulticast(message, messageLength); + printf("TX %u bytes to [ff02::bac0]:%u (multicast broadcast) (Network Port %u)", (unsigned)sent, + (unsigned)g_udp.GetLocalPort(), TRANSPORT_PORT_INSTANCE); + CASExampleHelper::LogBacnetFrame(message, messageLength); + return sent; + } + if (connectionStringLength < TRANSPORT_CONNECTION_STRING_LENGTH) { + return 0; + } + const uint16_t port = (uint16_t)((connectionString[16] << 8) | connectionString[17]); + const uint16_t sent = g_udp.Send(connectionString, port, message, messageLength); + printf("TX %u bytes to %s (Network Port %u)", (unsigned)sent, + AddressText(connectionString, destinationText, sizeof(destinationText)), TRANSPORT_PORT_INSTANCE); + CASExampleHelper::LogBacnetFrame(message, messageLength); + return sent; +#else uint8_t destination[6]; bool isBroadcast = broadcast; if (connectionString == NULL || connectionStringLength == 0) { @@ -1987,19 +2061,24 @@ 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, - isBroadcast ? " (broadcast)" : "", NETWORK_PORT_INSTANCE); + printf("TX %u bytes to %s%s (Network Port %u)", (unsigned)sent, + AddressText(destination, destinationText, sizeof(destinationText)), + isBroadcast ? " (broadcast)" : "", TRANSPORT_PORT_INSTANCE); CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; +#endif } -// The start-up / restart I-Am, to the local subnet broadcast. +// The start-up / restart I-Am, to the local subnet broadcast (BACnet/IP) or the multicast group (BACnet/IPv6). static void SendIAmToLocalSubnet() { +#ifdef BBC_IPV6 + BACnetStack_SendIAm(g_deviceInstance, NULL, 0, TRANSPORT_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); +#else uint8_t broadcastConn[6]; LocalBroadcastConnString(broadcastConn); BACnetStack_SendIAm(g_deviceInstance, broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); +#endif } // ----------------------------------------------------------------------------- @@ -2049,15 +2128,32 @@ int main(int argc, char** argv) { // 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. +#ifdef BBC_IPV6 + // --interface : join the multicast group on one interface only (its index: `ipconfig` shows it as the %n after a link-local address) + uint32_t ipv6Interface = 0; // 0 = every IPv6 interface that is up + for (int argumentIndex = 1; argumentIndex + 1 < argc; ++argumentIndex) { + if (strcmp(argv[argumentIndex], "--interface") == 0) { + ipv6Interface = (uint32_t)strtoul(argv[argumentIndex + 1], NULL, 10); + } + } + if (!g_udp.Connect(port, ipv6Interface)) { + printf("Error: Failed to bind UDP port %u over IPv6.\n", (unsigned)port); + return 1; + } + printf("FYI: Listening for BACnet/IPv6 on UDP port %u; joined the multicast group FF02::BAC0 on %u interface(s).\n", + (unsigned)port, (unsigned)g_udp.GetJoinedInterfaceCount()); +#else if (!g_udp.Connect(port)) { printf("Error: Failed to bind UDP port %u.\n", (unsigned)port); return 1; } printf("FYI: Listening for BACnet/IP on UDP port %u (Network Port %u).\n", (unsigned)port, NETWORK_PORT_INSTANCE); +#endif // Capture the BACnet/IP addressing the Network Port object will report. g_bacnetIpUdpPort = port; +#ifndef BBC_IPV6 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"); @@ -2069,6 +2165,7 @@ int main(int argc, char** argv) { printf("FYI: could not determine the local link speed; Network Port " "Link_Speed will report 0.0 (indeterminable).\n"); } +#endif // !BBC_IPV6 // --- Register callbacks ------------------------------------------------- // The time callback is shared boilerplate (RegisterCommonCallbacks also @@ -2204,6 +2301,10 @@ 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. +#ifdef BBC_IPV6 + // BACnet/IPv6 build: the stack has no IPv6 Network Port object yet (cas-bacnet-stack#4611), and its IPv6 data link is the + // only transport, which the default port instance names - so there is no Network Port object to add here. +#else if (!BACnetStack_AddNetworkPortObject( g_deviceInstance, NETWORK_PORT_INSTANCE, NETWORK_PORT_NETWORK_TYPE_IPV4, @@ -2214,6 +2315,7 @@ int main(int argc, char** argv) { printf("Error: Failed to add Network Port 1 (Vermilion).\n"); return 1; } +#endif // BBC_IPV6 // --- Enable the OPTIONAL properties we choose to expose ------------------ // The stack automatically enables an object's REQUIRED properties when the @@ -2322,6 +2424,10 @@ 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. +#ifdef BBC_IPV6 + // BACnet/IPv6 build: the seeded recipient is a BACnet/IP address (4 IP octets and a port), which a B/IPv6 network has no use for. + // Notification Class 1 starts with an empty Recipient_List; a management station writes one (it is writable, below). +#else uint8_t recipientMac[6]; if (RECIPIENT_USE_BROADCAST) { LocalBroadcastConnString(recipientMac); @@ -2346,6 +2452,7 @@ int main(int argc, char** argv) { printf("Error: could not seed the Notification Class recipient (Crimson).\n"); return 1; } +#endif // BBC_IPV6 // 4) Turn on intrinsic event reporting for Diamond, routed through Crimson. if (!BACnetStack_SetAlarmsAndEventsForObjectEnabled( @@ -2614,10 +2721,14 @@ int main(int argc, char** argv) { // 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. +#ifdef BBC_IPV6 + BACnetStack_SendWhoIs(NULL, 0, TRANSPORT_PORT_INSTANCE, true /*broadcast*/, 0, NULL, 0); +#else uint8_t broadcastConn[6]; LocalBroadcastConnString(broadcastConn); BACnetStack_SendWhoIs(broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, true /*broadcast*/, 0, NULL, 0); +#endif printf("FYI: Device %u (\"%s\") ready. Vendor ID %u. Press 'h' for help.\n", g_deviceInstance, DEVICE_NAME, VENDOR_IDENTIFIER); diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 64b2cfa..404fc34 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 64b2cfac5a70055cf4811ac7256b9bfbc08cc5dd +Subproject commit 404fc34b7c1defb57b25599faa75ec6f188fd656 diff --git a/tests/ipv6_probe.py b/tests/ipv6_probe.py new file mode 100644 index 0000000..65fd9d2 --- /dev/null +++ b/tests/ipv6_probe.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: CC0-1.0 +# Public-domain example code (CC0) - see ../LICENSE. +"""Talk BACnet/IPv6 (ANSI/ASHRAE 135-2024 Annex U) to the B-BC example from outside it. + +A minimal BACnet/IPv6 node in Python's standard library, just enough to read and write the device: + + python tests/ipv6_probe.py --target "fe80::9e0e:ff1f:9a6a:8f1%10" --port 47808 --device 389005 + +The device and this script can run on the same PC: this script uses its own UDP port for everything it sends and +receives, and finds the device's VMAC address (its device instance, in three octets: Annex U.1.3) with a +Virtual-Address-Resolution, a unicast, so it needs no multicast. With --multicast it also checks the part that does: +an Address-Resolution sent to the BACnet/IPv6 multicast group FF02::BAC0 on the device's port, whose +Address-Resolution-ACK comes back by unicast. + +Checks: + - Virtual-Address-Resolution is answered with the device's VMAC: its instance in three octets; + - ReadProperty of Device Object_Name, Protocol_Revision and Analog Input 1 Present_Value + (DS-RP-B over Original-Unicast-NPDU); + - ReadPropertyMultiple of Device Object_Identifier and Object_Type; + - WriteProperty of Analog Output 1 at priority 8, read back, then relinquished; + - (--multicast) Address-Resolution to FF02::BAC0 is answered with an Address-Resolution-ACK. +""" +import argparse +import socket +import struct +import sys +import time + +BVLC_TYPE = 0x82 +BVLC_RESULT = 0x00 +ORIGINAL_UNICAST_NPDU = 0x01 +ORIGINAL_BROADCAST_NPDU = 0x02 +ADDRESS_RESOLUTION = 0x03 +ADDRESS_RESOLUTION_ACK = 0x05 +VIRTUAL_ADDRESS_RESOLUTION = 0x06 +VIRTUAL_ADDRESS_RESOLUTION_ACK = 0x07 + +OBJECT_ANALOG_INPUT = 0 +OBJECT_ANALOG_OUTPUT = 1 +OBJECT_DEVICE = 8 +PROPERTY_OBJECT_IDENTIFIER = 75 +PROPERTY_OBJECT_NAME = 77 +PROPERTY_OBJECT_TYPE = 79 +PROPERTY_PRESENT_VALUE = 85 +PROPERTY_PROTOCOL_REVISION = 139 + + +def vmac_of(device_instance): + """Annex H.7.2: three octets, high octet first, the top two bits zero.""" + return bytes([(device_instance >> 16) & 0x3F, (device_instance >> 8) & 0xFF, device_instance & 0xFF]) + + +def bvll(function, payload=b"", *vmacs): + body = b"".join(vmacs) + payload + return bytes([BVLC_TYPE, function]) + struct.pack(">H", 4 + len(body)) + body + + +def context_unsigned(tag, value): + octets = value.to_bytes(4, "big").lstrip(b"\0") or b"\0" + return bytes([(tag << 4) | 0x08 | len(octets)]) + octets + + +def object_id(object_type, instance): + return struct.pack(">I", (object_type << 22) | instance) + + +def read_property_apdu(invoke_id, object_type, instance, property_identifier): + return (bytes([0x00, 0x05, invoke_id, 0x0C, 0x0C]) + object_id(object_type, instance) + + context_unsigned(1, property_identifier)) + + +def read_property_multiple_apdu(invoke_id, object_type, instance, properties): + body = bytes([0x0C]) + object_id(object_type, instance) + b"\x1e" + for property_identifier in properties: + body += context_unsigned(0, property_identifier) + return bytes([0x00, 0x05, invoke_id, 0x0E]) + body + b"\x1f" + + +def write_property_real_apdu(invoke_id, object_type, instance, property_identifier, value, priority): + # [0] object id, [1] property id, [3] value (opening 3E, REAL 44 xx xx xx xx, closing 3F), [4] priority + return (bytes([0x00, 0x05, invoke_id, 0x0F, 0x0C]) + object_id(object_type, instance) + + context_unsigned(1, property_identifier) + b"\x3e\x44" + struct.pack(">f", value) + b"\x3f" + + context_unsigned(4, priority)) + + +def write_property_null_apdu(invoke_id, object_type, instance, property_identifier, priority): + return (bytes([0x00, 0x05, invoke_id, 0x0F, 0x0C]) + object_id(object_type, instance) + + context_unsigned(1, property_identifier) + b"\x3e\x00\x3f" + context_unsigned(4, priority)) + + +def first_application_value(apdu): + """The first application-tagged value of a ComplexACK's service ACK, decoded to a Python value; or the hex text.""" + start = apdu.find(b"\x3e") + if start < 0: + return apdu.hex() + index = start + 1 + tag = apdu[index] + length = tag & 0x07 + kind = tag >> 4 + index += 1 + if length == 5: + length = apdu[index] + index += 1 + value = apdu[index:index + length] + if kind == 7: # character string: encoding octet then text + return value[1:].decode("utf-8", "replace") + if kind == 2: # unsigned + return int.from_bytes(value, "big") + if kind == 4 and len(value) == 4: # real + return round(struct.unpack(">f", value)[0], 3) + if kind == 12 and len(value) == 4: # object identifier + raw = struct.unpack(">I", value)[0] + return (raw >> 22, raw & 0x3FFFFF) + return apdu.hex() + + +class Node: + def __init__(self, target, port, local_port, multicast_interface): + self.target = socket.getaddrinfo(target, port, socket.AF_INET6, socket.SOCK_DGRAM)[0][4] + self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) + self.socket.bind(("::", local_port)) + self.socket.settimeout(0.3) + self.multicast_interface = multicast_interface + self.own_vmac = vmac_of(4194001) # this node's VMAC: a device instance nobody has + self.device_vmac = None + self.port = port + + def send(self, message, destination=None): + self.socket.sendto(message, destination or self.target) + + def receive(self, seconds): + end = time.time() + seconds + while time.time() < end: + try: + data, source = self.socket.recvfrom(2048) + except socket.timeout: + continue + except OSError: + continue + yield data, source + + def multicast_destination(self): + return ("ff02::bac0", self.port, 0, self.multicast_interface) + + def request(self, function, message, seconds=3.0): + """Sends `message`; returns the first BVLL-IPv6 reply of `function`, or None.""" + self.send(message) + for data, _ in self.receive(seconds): + if len(data) >= 4 and data[0] == BVLC_TYPE and data[1] == function: + return data + return None + + def confirmed(self, invoke_id, apdu, seconds=4.0): + """An Original-Unicast-NPDU carrying a confirmed request (NPDU 01 04); returns the answering APDU, or None.""" + message = bvll(ORIGINAL_UNICAST_NPDU, b"\x01\x04" + apdu, self.own_vmac, self.device_vmac) + self.send(message) + for data, _ in self.receive(seconds): + if len(data) < 12 or data[0] != BVLC_TYPE or data[1] != ORIGINAL_UNICAST_NPDU: + continue + if data[10] != 0x01 or data[11] & 0x80: # NPDU version 1, and not a network layer message + continue + answer = data[12:] + if len(answer) >= 2 and answer[1] == invoke_id: + return answer + return None + + +def main(): + arguments = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + arguments.add_argument("--target", required=True, help="the device's IPv6 address, with %%interface for a link-local one") + arguments.add_argument("--port", type=int, default=47808) + arguments.add_argument("--device", type=int, default=389005) + arguments.add_argument("--local-port", type=int, default=0, help="this script's UDP port (0 = any)") + arguments.add_argument("--multicast", action="store_true", help="also check the multicast Address-Resolution") + arguments.add_argument("--interface", type=int, default=0, help="the interface index for multicast (Windows: ipconfig, the %%N)") + args = arguments.parse_args() + + node = Node(args.target, args.port, args.local_port, args.interface) + results = [] + + def check(name, ok, detail=""): + results.append(ok) + print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else "")) + + expected_vmac = vmac_of(args.device) + + # 1. Virtual-Address-Resolution (Annex U.2.7): unicast; the ACK carries the device's own VMAC. + reply = node.request(VIRTUAL_ADDRESS_RESOLUTION_ACK, bvll(VIRTUAL_ADDRESS_RESOLUTION, b"", node.own_vmac)) + ok = reply is not None and len(reply) == 10 and reply[4:7] == expected_vmac and reply[7:10] == node.own_vmac + check(f"Virtual-Address-Resolution is answered with the device's VMAC {expected_vmac.hex()} (instance {args.device})", ok, + reply.hex() if reply else "no answer") + if not ok: + return summary(results) + node.device_vmac = reply[4:7] + + # 2. ReadProperty and ReadPropertyMultiple over Original-Unicast-NPDU. + answer = node.confirmed(1, read_property_apdu(1, OBJECT_DEVICE, args.device, PROPERTY_OBJECT_NAME)) + value = first_application_value(answer[2:]) if answer and (answer[0] >> 4) == 3 else None + check("ReadProperty Device Object_Name", isinstance(value, str) and value != "", repr(value)) + answer = node.confirmed(2, read_property_apdu(2, OBJECT_DEVICE, args.device, PROPERTY_PROTOCOL_REVISION)) + value = first_application_value(answer[2:]) if answer and (answer[0] >> 4) == 3 else None + check("ReadProperty Device Protocol_Revision", isinstance(value, int) and value >= 24, repr(value)) + answer = node.confirmed(3, read_property_apdu(3, OBJECT_ANALOG_INPUT, 1, PROPERTY_PRESENT_VALUE)) + value = first_application_value(answer[2:]) if answer and (answer[0] >> 4) == 3 else None + check("ReadProperty Analog Input 1 Present_Value", isinstance(value, float), repr(value)) + answer = node.confirmed(4, read_property_multiple_apdu(4, OBJECT_DEVICE, args.device, [PROPERTY_OBJECT_IDENTIFIER, PROPERTY_OBJECT_TYPE])) + check("ReadPropertyMultiple Device Object_Identifier and Object_Type", answer is not None and (answer[0] >> 4) == 3 and object_id(OBJECT_DEVICE, args.device) in answer, + answer.hex() if answer else "no answer") + + # 3. WriteProperty at priority 8, read back, relinquish. + answer = node.confirmed(5, write_property_real_apdu(5, OBJECT_ANALOG_OUTPUT, 1, PROPERTY_PRESENT_VALUE, 42.5, 8)) + check("WriteProperty Analog Output 1 Present_Value = 42.5 at priority 8 (SimpleACK)", answer is not None and (answer[0] >> 4) == 2, answer.hex() if answer else "no answer") + answer = node.confirmed(6, read_property_apdu(6, OBJECT_ANALOG_OUTPUT, 1, PROPERTY_PRESENT_VALUE)) + value = first_application_value(answer[2:]) if answer and (answer[0] >> 4) == 3 else None + check("ReadProperty Analog Output 1 Present_Value reads the write back", value == 42.5, repr(value)) + answer = node.confirmed(7, write_property_null_apdu(7, OBJECT_ANALOG_OUTPUT, 1, PROPERTY_PRESENT_VALUE, 8)) + check("WriteProperty NULL at priority 8 relinquishes it (SimpleACK)", answer is not None and (answer[0] >> 4) == 2, answer.hex() if answer else "no answer") + + # 4. Multicast: an Address-Resolution to FF02::BAC0 for the device's VMAC; the ACK comes back by unicast. + if args.multicast: + node.send(bvll(ADDRESS_RESOLUTION, b"", node.own_vmac, expected_vmac), node.multicast_destination()) + acknowledged = False + for data, _ in node.receive(3.0): + if len(data) == 10 and data[1] == ADDRESS_RESOLUTION_ACK and data[4:7] == expected_vmac: + acknowledged = True + break + check("Address-Resolution to FF02::BAC0 is answered with an Address-Resolution-ACK by unicast", acknowledged) + return summary(results) + + +def summary(results): + passed = sum(1 for ok in results if ok) + print(f"\n{passed}/{len(results)} checks passed") + return 0 if passed == len(results) else 1 + + +if __name__ == "__main__": + sys.exit(main()) From ca9dab113eb43a958b6472aac691a63536c7624d Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Wed, 28 Oct 2026 00:44:22 -0700 Subject: [PATCH 2/9] B-BC: submodule at the merged BACnet/IPv6 slice 1 (stack #4632) Co-Authored-By: Claude Sonnet 5.5 --- submodules/cas-bacnet-stack | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 404fc34..88de00c 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 404fc34b7c1defb57b25599faa75ec6f188fd656 +Subproject commit 88de00ce0144f6297b4db7ad99b188bd7cefde1e From e1d65151db54609b5368a5f01440cd637823ef3d Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Wed, 28 Oct 2026 02:00:37 -0700 Subject: [PATCH 3/9] B-BC: stack submodule at b79d4b5bb (BACnet/IPv6 Network Port) Moves the CAS BACnet Stack to b79d4b5bb (issues/runbook): BACnet/IPv6 VMAC resolution, the IPv6 Network Port object (network type 9) and its activation properties (#4610, #4611, #4406). Co-Authored-By: Claude Opus 5.5 --- submodules/cas-bacnet-stack | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/submodules/cas-bacnet-stack b/submodules/cas-bacnet-stack index 88de00c..b79d4b5 160000 --- a/submodules/cas-bacnet-stack +++ b/submodules/cas-bacnet-stack @@ -1 +1 @@ -Subproject commit 88de00ce0144f6297b4db7ad99b188bd7cefde1e +Subproject commit b79d4b5bb7d653991d00fc3e98f44e816d11c435 From 9fdf88117641b9cd73013efa36073a261726d8c6 Mon Sep 17 00:00:00 2001 From: SWS-Chipkin Date: Wed, 28 Oct 2026 02:58:30 -0700 Subject: [PATCH 4/9] B-BC 1.2.0: one executable, four data links (--datalink) BACnetExampleBBC --datalink ipv4|ipv6|mstp|sc picks the data link at run time; ipv4 is the default and the same device as 1.1.0. Each data link has its own Network Port (1 Vermilion, 2 Cerulean, 3 Amber, 4 Teal) and only the active one is added. - command_line.cpp: every option checked, wrong-link options and unknown options reported with a pointer to --help. - ipv6: BBC_IPV6 and its options header are gone. Network Port 2 serves IPv6_Address, prefix, gateway, DNS server and Link_Speed from the host; the stack serves the VMAC. No start-up I-Am/Who-Is on IPv6: the stack cannot send an application broadcast there (TODO.md). - mstp: common/SimpleSerial plus mstp/MstpDataLink on the stack's byte-mode callbacks, LoopMSTP every 1 ms (timeBeginPeriod(1)). Network Port 3 serves MAC, Max_Master, Max_Info_Frames, Link_Speed; announcements wait for the token ring; counters on ring changes. - sc: optional (BBC_SC, on when vcpkg/system libwebsockets, OpenSSL and zlib are found). sc/ScHubConnector (one TLS context, 1600-octet ingress ceiling, no stack calls from lws callbacks) and sc/ScNode (Network Port 4, Files 2-5, the B-SCHUB CARI flow, --import-cari). tools/sign_cari_request.py signs a request with a test CA. - ReinitializeDevice ACTIVATE_CHANGES and a Network Port Command callback. Verified on Windows 11: - ipv4: tests/run_wire_tests.py, ALL WIRE TESTS PASSED. - ipv6: tests/ipv6_probe.py --multicast, 14/14; DNS, prefix, gateway, multicast address read by hand. - sc: B-SCHUB hub on 127.0.0.1:4443, CARI request -> signed -> imported -> connected; SC_Primary_Hub_Connection_Status read connected through the hub. - mstp: CP210x RS-485 adapter on a live 38400-baud segment, MAC 12; joined the ring (1917 frames sent, 0 dropped in a minute); I-Am and ReadProperty through an MS/TP to BACnet/IP router (SNET 5). Co-Authored-By: Claude Opus 5.5 --- .gitignore | 6 + CMakeLists.txt | 155 +++- command_line.cpp | 298 +++++++ command_line.h | 66 ++ common/SimpleSerial.cpp | 231 ++++++ common/SimpleSerial.h | 64 ++ ipv6/LocalIPv6Address.cpp | 230 +++++ ipv6/LocalIPv6Address.h | 37 + ipv6/cas_bacnet_stack_options_ipv6.h | 55 -- main.cpp | 1155 +++++++++++++++++++++----- mstp/MstpDataLink.cpp | 101 +++ mstp/MstpDataLink.h | 54 ++ sc/KeyPassword.cpp | 158 ++++ sc/KeyPassword.h | 45 + sc/ScHubConnector.cpp | 386 +++++++++ sc/ScHubConnector.h | 107 +++ sc/ScNode.cpp | 505 +++++++++++ sc/ScNode.h | 100 +++ sc/cari.cpp | 559 +++++++++++++ sc/cari.h | 110 +++ sc/cert_layout.cpp | 126 +++ sc/cert_layout.h | 76 ++ sc/cert_store.cpp | 677 +++++++++++++++ sc/cert_store.h | 124 +++ sc/cert_tool.cpp | 484 +++++++++++ sc/cert_tool.h | 87 ++ tests/ipv6_probe.py | 33 +- tools/sign_cari_request.py | 164 ++++ vcpkg.json | 11 + 29 files changed, 5899 insertions(+), 305 deletions(-) create mode 100644 command_line.cpp create mode 100644 command_line.h create mode 100644 common/SimpleSerial.cpp create mode 100644 common/SimpleSerial.h create mode 100644 ipv6/LocalIPv6Address.cpp create mode 100644 ipv6/LocalIPv6Address.h delete mode 100644 ipv6/cas_bacnet_stack_options_ipv6.h create mode 100644 mstp/MstpDataLink.cpp create mode 100644 mstp/MstpDataLink.h create mode 100644 sc/KeyPassword.cpp create mode 100644 sc/KeyPassword.h create mode 100644 sc/ScHubConnector.cpp create mode 100644 sc/ScHubConnector.h create mode 100644 sc/ScNode.cpp create mode 100644 sc/ScNode.h create mode 100644 sc/cari.cpp create mode 100644 sc/cari.h create mode 100644 sc/cert_layout.cpp create mode 100644 sc/cert_layout.h create mode 100644 sc/cert_store.cpp create mode 100644 sc/cert_store.h create mode 100644 sc/cert_tool.cpp create mode 100644 sc/cert_tool.h create mode 100644 tools/sign_cari_request.py create mode 100644 vcpkg.json diff --git a/.gitignore b/.gitignore index a144452..141a699 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,9 @@ 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/CMakeLists.txt b/CMakeLists.txt index 3c9b834..a528163 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) @@ -37,12 +67,6 @@ endif() set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) -# --- BACnet/IPv6 -------------------------------------------------------------- -# cmake -B build-ipv6 -S . -DBBC_IPV6=ON builds the same device as a BACnet/IPv6 (Annex U) node instead of a BACnet/IP one: -# IPv6 is then the ONLY data link the stack is built with (ipv6/cas_bacnet_stack_options_ipv6.h), the socket is -# common/SimpleUDP6.cpp, and the executable is named BACnetExampleBBCIPv6. See ipv6/README.md. -option(BBC_IPV6 "Build the BACnet/IPv6 (Annex U) device instead of the BACnet/IP one" OFF) - # --- Locate the pieces this project ships ----------------------------------- # The shared helper is vendored into this repository at ./common. if(NOT DEFINED EXAMPLES_COMMON_DIR) @@ -63,51 +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) + find_package(libwebsockets CONFIG QUIET) + 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 stack's options, for the IPv6 build ---------------------------------- -# The stack picks its option set from source/CIBuildSettingsDefaults.h unless told otherwise, and that is the FULL target with every -# data link. The IPv6 build forces its own header in front of every stack source (DONT_BUILD_ALL_OPTIONS says the defaults do not apply). -if(BBC_IPV6) - set(BBC_STACK_OPTIONS_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/ipv6/cas_bacnet_stack_options_ipv6.h") - target_compile_definitions(cas_bacnet_stack_adapter PUBLIC DONT_BUILD_ALL_OPTIONS) - if(MSVC) - target_compile_options(cas_bacnet_stack_adapter PUBLIC "/FI${BBC_STACK_OPTIONS_HEADER}") - else() - target_compile_options(cas_bacnet_stack_adapter PUBLIC "-include" "${BBC_STACK_OPTIONS_HEADER}") - endif() -endif() - # --- The shared example helper ---------------------------------------------- set(COMMON_SOURCES "${EXAMPLES_COMMON_DIR}/CASExampleHelper.cpp" - "${EXAMPLES_COMMON_DIR}/SimpleUDP.cpp") # CASExampleHelper's own BACnet/IP socket, which this example does not open -if(BBC_IPV6) - list(APPEND COMMON_SOURCES "${EXAMPLES_COMMON_DIR}/SimpleUDP6.cpp") -endif() + "${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) + +# --- This example's own sources --------------------------------------------- +set(EXAMPLE_SOURCES + main.cpp + 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_IPV6) - set(BBC_TARGET_NAME BACnetExampleBBCIPv6) +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() - set(BBC_TARGET_NAME BACnetExampleBBC) -endif() -add_executable(${BBC_TARGET_NAME} - main.cpp - ${COMMON_SOURCES}) -if(BBC_IPV6) - target_compile_definitions(${BBC_TARGET_NAME} PRIVATE BBC_IPV6) + add_executable(BACnetExampleBBC ${EXAMPLE_SOURCES} ${COMMON_SOURCES}) endif() -target_include_directories(${BBC_TARGET_NAME} PRIVATE - "${EXAMPLES_COMMON_DIR}") +target_include_directories(BACnetExampleBBC PRIVATE + "${EXAMPLES_COMMON_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}") -target_link_libraries(${BBC_TARGET_NAME} PRIVATE CASBACnetStack::Adapter) +target_link_libraries(BACnetExampleBBC PRIVATE CASBACnetStack::Adapter) # --- Warnings on OUR sources only ------------------------------------------- # Apply strict warnings to the example + helper sources, but NOT to the bundled @@ -118,11 +186,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(${BBC_TARGET_NAME} 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/command_line.cpp b/command_line.cpp new file mode 100644 index 0000000..43bc813 --- /dev/null +++ b/command_line.cpp @@ -0,0 +1,298 @@ +// 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 + +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(" --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"); + printf(" --mstp-baud 9600, 19200, 38400 (default), 57600, 76800 or 115200.\n"); + 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. +bool ParseNumber(const char* text, const unsigned long minimum, const unsigned long maximum, unsigned long* value) { + if (text == NULL || *text == '\0' || *text == '-' || *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, "--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, "--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); + } + 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); + } + (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/SimpleSerial.cpp b/common/SimpleSerial.cpp new file mode 100644 index 0000000..818cfc4 --- /dev/null +++ b/common/SimpleSerial.cpp @@ -0,0 +1,231 @@ +// 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 +#define SERIAL_INVALID_HANDLE ((intptr_t)-1) +#endif + +SimpleSerial::SimpleSerial() : m_handle(SERIAL_INVALID_HANDLE) { + 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; + 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); + 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 != 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..0d9f1de --- /dev/null +++ b/common/SimpleSerial.h @@ -0,0 +1,64 @@ +// 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; + char m_lastError[160]; +}; + +#endif // SIMPLE_SERIAL_H diff --git a/ipv6/LocalIPv6Address.cpp b/ipv6/LocalIPv6Address.cpp new file mode 100644 index 0000000..fb92d86 --- /dev/null +++ b/ipv6/LocalIPv6Address.cpp @@ -0,0 +1,230 @@ +// 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) { + if (adapter->OperStatus != IfOperStatusUp || adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) { + continue; + } + if (interfaceIndex != 0 && adapter->Ipv6IfIndex != interfaceIndex) { + continue; + } + // A global address if there is one, else the link-local one. + 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) { + 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; + 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; + } + 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..d8e273b --- /dev/null +++ b/ipv6/LocalIPv6Address.h @@ -0,0 +1,37 @@ +// 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 it, a global address is +// preferred over a link-local one (fe80::/10), which every IPv6 interface has. +// ============================================================================= + +#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 +}; + +// 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/cas_bacnet_stack_options_ipv6.h b/ipv6/cas_bacnet_stack_options_ipv6.h deleted file mode 100644 index bba9c97..0000000 --- a/ipv6/cas_bacnet_stack_options_ipv6.h +++ /dev/null @@ -1,55 +0,0 @@ -// The CAS BACnet Stack's feature switches for the BACnet/IPv6 build of this B-BC example (cmake -DBBC_IPV6=ON). -// -// CMakeLists.txt force-includes this header ahead of every stack source file and defines DONT_BUILD_ALL_OPTIONS, so it -// decides what is compiled: the B-BC profile and the 15 objects of B-BC-CPP, and BACnet/IPv6 as the ONLY data link. Every switch is -// documented in submodules/cas-bacnet-stack/source/CASBACnetStackOptions.h. It is the Zephyr example's options header with its data -// links replaced. -// -#ifndef CAS_BACNET_STACK_OPTIONS_IPV6_H -#define CAS_BACNET_STACK_OPTIONS_IPV6_H - -// A resource-constrained device: nothing is compiled unless it is asked for below. -#define STACK_OPTION_TARGET_EMBEDDED - -// The B-BC profile (Annex L.4.1): turns on the BIBBs a Building Controller requires - -// DM-DCC-B, DM-RD-B, DM-BR-B, DM-TS-B / DM-UTC-B, the alarm and event services and -// T-VMT-I-B. The core services (ReadProperty, WriteProperty, Who-Is/I-Am, -// Who-Has/I-Have) are always compiled. -#define STACK_OPTION_PROFILE_B_BC - -// The BIBBs B-BC needs that the profile switch leaves to you. -#define STACK_OPTION_SEGMENTATION // ReadPropertyMultiple answers bigger than one APDU -#define STACK_OPTION_AE_ACKNOWLEDGE_ALARMS // AE-ACK-B -#define STACK_OPTION_AE_INFORMATION // AE-INFO-B (GetEventInformation) -// Trend Log Multiple 1 "Multi-Point Trend" (part of B-BC-CPP's object set) needs T-VMMV. B-BC itself -// only requires T-VMT, so the profile switch does not turn it on: without this line -// BACnetStack_AddTrendLogMultipleObject() returns false. -#define STACK_OPTION_T_VMMV_TRENDING_VIEWING_AND_MODIFYING_MULTIPLE_VALUES - -// The embedded target limits character strings to 64 octets. B-BC-CPP's Device -// Description is longer, and a string over the limit makes the whole read fail -// (BACnetProfileExample-B-BC-CPP#7), so keep the full build's 256. -#define STACK_OPTION_MAX_CHARACTER_STRING_SIZE 256 - -// The object types this device has (B-BC-CPP's 15 objects). -#define STACK_OPTION_OBJECT_TYPE_ANALOG_INPUT -#define STACK_OPTION_OBJECT_TYPE_ANALOG_OUTPUT -#define STACK_OPTION_OBJECT_TYPE_ANALOG_VALUE -#define STACK_OPTION_OBJECT_TYPE_BINARY_INPUT -#define STACK_OPTION_OBJECT_TYPE_BINARY_OUTPUT -#define STACK_OPTION_OBJECT_TYPE_MULTISTATE_INPUT -#define STACK_OPTION_OBJECT_TYPE_MULTISTATE_OUTPUT -#define STACK_OPTION_OBJECT_TYPE_NOTIFICATION_CLASS -#define STACK_OPTION_OBJECT_TYPE_NETWORK_PORT -#define STACK_OPTION_OBJECT_TYPE_SCHEDULE -#define STACK_OPTION_OBJECT_TYPE_CALENDAR -#define STACK_OPTION_OBJECT_TYPE_FILE -#define STACK_OPTION_OBJECT_TYPE_TREND_LOG -#define STACK_OPTION_OBJECT_TYPE_TREND_LOG_MULTIPLE - -// The three datalinks. Only one is active at a time (chosen in the Dashboard), but all are -// compiled in so one image can switch between them. BACnet/SC needs IPV4 as well. -// BACnet/IPv6 (Annex U) is the only data link: this build speaks IPv6 and nothing else (cas-bacnet-stack#255). -#define STACK_OPTION_DATA_LINK_LAYER_IPV6 - -#endif // CAS_BACNET_STACK_OPTIONS_IPV6_H diff --git a/main.cpp b/main.cpp index 032461d..f0cda52 100644 --- a/main.cpp +++ b/main.cpp @@ -54,7 +54,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; @@ -90,21 +95,27 @@ // 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 . +// 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 +// 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" -#ifdef BBC_IPV6 -#include "SimpleUDP6.h" // BACnet/IPv6 build (cmake -DBBC_IPV6=ON): this example owns its BACnet/IPv6 socket - see section 2e -#else -#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 - @@ -118,6 +129,7 @@ #if defined(_WIN32) #include // Sleep() +#include // timeBeginPeriod() - 1 ms sleeps for MS/TP (winmm) #else #include // usleep() #endif @@ -128,7 +140,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.1.0"; +static const char* APP_VERSION = "1.2.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 @@ -341,6 +353,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; @@ -456,6 +469,234 @@ 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; + +// 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. +static bool SetDataLinkPortUnsigned(const uint16_t objectType, const uint32_t objectInstance, + const uint32_t propertyIdentifier, const uint32_t value, uint32_t* errorCode) { + if (!IsDataLinkPort(objectType, objectInstance, DataLink::MSTP)) { + return false; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_MASTER) { + if (value < g_options.mstpMacAddress || value > 127) { + *errorCode = ERROR_CODE_VALUE_OUT_OF_RANGE; + return false; + } + g_options.mstpMaxMaster = (uint8_t)value; + printf("Network Port %u (Amber): Max_Master is now %u\n", objectInstance, value); + return true; + } + if (propertyIdentifier == PROPERTY_IDENTIFIER_MAX_INFO_FRAMES) { + if (value < 1 || value > 255) { + *errorCode = ERROR_CODE_VALUE_OUT_OF_RANGE; + return false; + } + g_options.mstpMaxInfoFrames = (uint8_t)value; + printf("Network Port %u (Amber): Max_Info_Frames is now %u\n", objectInstance, value); + return true; + } + return false; +} + +// 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 // @@ -531,6 +772,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) { @@ -688,6 +933,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) { @@ -796,6 +1053,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) { @@ -820,10 +1092,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) { @@ -935,6 +1212,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); } @@ -957,6 +1245,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. @@ -1015,6 +1308,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; @@ -1047,6 +1352,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; @@ -1151,6 +1467,17 @@ 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); + } +#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) { @@ -1340,7 +1667,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 @@ -1368,6 +1696,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); @@ -1401,6 +1749,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; } @@ -1423,10 +1778,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; } @@ -1439,6 +1802,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; @@ -1527,42 +1918,58 @@ bool AcknowledgeAlarm(const uint32_t deviceInstance, const uint32_t /*acknowledg return true; // accept the acknowledgement } -// 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 -// the limited broadcast 255.255.255.255.) -#ifdef BBC_IPV6 -// BACnet/IPv6 (Annex U): the stack's connection string for a peer is its B/IPv6 address - 16 octets of IPv6 address, then -// the 2-octet UDP port, most significant octet first - and a BACnet broadcast is sent with NO connection string, to the -// multicast group FF02::BAC0 (SimpleUDP6::SendMulticast). The stack has no Network Port object for an IPv6 port yet -// (cas-bacnet-stack#4611), so this build adds none and names its transport with the default port instance. -static const uint8_t TRANSPORT_ADDRESS_LENGTH = 16; -static const uint8_t TRANSPORT_CONNECTION_STRING_LENGTH = 18; -static const uint32_t TRANSPORT_PORT_INSTANCE = BACNET_NETWORK_PORT_DEFAULT; -#else -static const uint8_t TRANSPORT_ADDRESS_LENGTH = 4; -static const uint8_t TRANSPORT_CONNECTION_STRING_LENGTH = 6; -static const uint32_t TRANSPORT_PORT_INSTANCE = NETWORK_PORT_INSTANCE; -#endif +// ----------------------------------------------------------------------------- +// 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) { -#ifdef BBC_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])); -#endif + 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; } -#ifndef BBC_IPV6 +// 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 +// the limited broadcast 255.255.255.255.) static void LocalBroadcastConnString(uint8_t out[6]) { out[0] = (uint8_t)(g_ipAddress[0] | ~g_ipSubnetMask[0]); out[1] = (uint8_t)(g_ipAddress[1] | ~g_ipSubnetMask[1]); @@ -1571,7 +1978,9 @@ static void LocalBroadcastConnString(uint8_t out[6]) { out[4] = (uint8_t)(g_bacnetIpUdpPort >> 8); out[5] = (uint8_t)(g_bacnetIpUdpPort & 0xFF); } -#endif // !BBC_IPV6 + +// 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) @@ -1591,18 +2000,16 @@ static void LocalBroadcastConnString(uint8_t out[6]) { // asked for by hand, which keeps the build to the two commands in the README. // ----------------------------------------------------------------------------- -#ifdef BBC_IPV6 -static SimpleUDP6 g_udp; -#else -static SimpleUDP g_udp; -#endif +// 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[18]; // IP[4] + UDP port[2] (BACnet/IP), or IPv6[16] + UDP port[2] (BACnet/IPv6), network order; - // TRANSPORT_CONNECTION_STRING_LENGTH of them + // TransportConnectionStringLength() of them uint8_t readPropertyInvokeId; // the outstanding ReadProperty, if any bool readPropertyPending; uint8_t readPropertyMultipleInvokeId; // the outstanding ReadPropertyMultiple, if any @@ -1670,12 +2077,15 @@ 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 != TRANSPORT_CONNECTION_STRING_LENGTH) { + // 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, TRANSPORT_CONNECTION_STRING_LENGTH) != 0) { - memcpy(g_peer.connectionString, connectionString, TRANSPORT_CONNECTION_STRING_LENGTH); + 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)), @@ -1738,8 +2148,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, TRANSPORT_CONNECTION_STRING_LENGTH, - TRANSPORT_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); @@ -1912,25 +2322,28 @@ static void HandleReadPropertyMultipleAck(const uint8_t* apdu, size_t apduLength // the stack alone. static void HandleReplyFromPeer(const uint8_t* message, size_t messageLength, const uint8_t* fromAddress, uint16_t fromPort) { - if (!g_peer.bound || memcmp(fromAddress, g_peer.connectionString, TRANSPORT_ADDRESS_LENGTH) != 0 || - fromPort != (uint16_t)((g_peer.connectionString[TRANSPORT_ADDRESS_LENGTH] << 8) | g_peer.connectionString[TRANSPORT_ADDRESS_LENGTH + 1])) { - return; - } -#ifdef BBC_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) { + 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; } - size_t 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; + 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; } - size_t position = 4; -#endif // NPDU (cl. 6.2): version 1, control, then the optional DNET/SNET fields. if (messageLength < position + 2 || message[position] != 0x01) { return; @@ -1989,65 +2402,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 < TRANSPORT_CONNECTION_STRING_LENGTH) { +// --- 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 fromAddress[16] = { 0 }; uint16_t fromPort = 0; - const uint16_t received = g_udp.Receive(message, maxMessageLength, fromAddress, &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; } char fromText[64]; uint8_t fromConnectionString[18] = { 0 }; - memcpy(fromConnectionString, fromAddress, TRANSPORT_ADDRESS_LENGTH); - fromConnectionString[TRANSPORT_ADDRESS_LENGTH] = (uint8_t)(fromPort >> 8); - fromConnectionString[TRANSPORT_ADDRESS_LENGTH + 1] = (uint8_t)(fromPort & 0xFF); + 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)), TRANSPORT_PORT_INSTANCE); + AddressText(fromConnectionString, fromText, sizeof(fromText)), ActiveNetworkPortInstance()); CASExampleHelper::LogBacnetFrame(message, received); - memcpy(sourceConnectionString, fromConnectionString, TRANSPORT_CONNECTION_STRING_LENGTH); - *sourceConnectionStringLength = TRANSPORT_CONNECTION_STRING_LENGTH; - *networkPortInstance = TRANSPORT_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, 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 != TRANSPORT_PORT_INSTANCE) { - return 0; +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]; -#ifdef BBC_IPV6 - // BACnet/IPv6: a broadcast carries no address (Annex U.4): the multicast group is this example's to choose. + // 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_udp.SendMulticast(message, messageLength); + 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_udp.GetLocalPort(), TRANSPORT_PORT_INSTANCE); + (unsigned)g_udp6.GetLocalPort(), IPV6_NETWORK_PORT_INSTANCE); CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; } - if (connectionStringLength < TRANSPORT_CONNECTION_STRING_LENGTH) { + if (connectionStringLength < 18) { return 0; } const uint16_t port = (uint16_t)((connectionString[16] << 8) | connectionString[17]); - const uint16_t sent = g_udp.Send(connectionString, port, message, messageLength); + 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)), TRANSPORT_PORT_INSTANCE); + AddressText(connectionString, destinationText, sizeof(destinationText)), IPV6_NETWORK_PORT_INSTANCE); CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; -#else +} + +// 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) { @@ -2063,22 +2511,120 @@ uint16_t CallbackSendMessage(const uint8_t* message, const uint16_t messageLengt const uint16_t sent = g_udp.Send(destination, port, message, messageLength); printf("TX %u bytes to %s%s (Network Port %u)", (unsigned)sent, AddressText(destination, destinationText, sizeof(destinationText)), - isBroadcast ? " (broadcast)" : "", TRANSPORT_PORT_INSTANCE); + isBroadcast ? " (broadcast)" : "", NETWORK_PORT_INSTANCE); CASExampleHelper::LogBacnetFrame(message, messageLength); return sent; +} + +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; + } } -// The start-up / restart I-Am, to the local subnet broadcast (BACnet/IP) or the multicast group (BACnet/IPv6). -static void SendIAmToLocalSubnet() { -#ifdef BBC_IPV6 - BACnetStack_SendIAm(g_deviceInstance, NULL, 0, TRANSPORT_PORT_INSTANCE, true /*broadcast*/, 0 /*local network*/, NULL, 0); -#else - uint8_t broadcastConn[6]; - LocalBroadcastConnString(broadcastConn); - BACnetStack_SendIAm(g_deviceInstance, broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, - true /*broadcast*/, 0 /*local network*/, NULL, 0); +// BACnet/IPv6: this stack version gives the application no way to START a +// broadcast. On BACnet/IPv6 a broadcast is a message with no connection string +// (the host sends it to the multicast group FF02::BAC0), but BACnetStack_SendIAm +// and BACnetStack_SendWhoIs refuse a call without one, and with one the IPv6 +// data link sends a unicast. So on --datalink ipv6 this example does not +// announce itself; it still ANSWERS a Who-Is, and the stack multicasts that +// I-Am. Recorded in TODO.md (stack gaps). +static void Ipv6BroadcastNotAvailable(const char* serviceName) { + printf("FYI: BACnet/IPv6: no start-up %s broadcast (this stack version cannot send an application " + "broadcast on BACnet/IPv6 - see TODO.md). The device still answers Who-Is.\n", + serviceName); +} + +// 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: + // Not sent: see Ipv6BroadcastNotAvailable() below. + Ipv6BroadcastNotAvailable("I-Am"); + 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: + Ipv6BroadcastNotAvailable("Who-Is"); + 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; + } + } } // ----------------------------------------------------------------------------- @@ -2114,64 +2660,125 @@ 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. - if (CASExampleHelper::HandleHelpAndVersionArgs(argc, argv, APP_NAME, APP_VERSION)) { - 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; 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); + 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; + } +#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 - // --- Bind the BACnet/IP socket ----------------------------------------- - // This example binds its own socket (g_udp, section 2e) rather than calling + // --- 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. -#ifdef BBC_IPV6 - // --interface : join the multicast group on one interface only (its index: `ipconfig` shows it as the %n after a link-local address) - uint32_t ipv6Interface = 0; // 0 = every IPv6 interface that is up - for (int argumentIndex = 1; argumentIndex + 1 < argc; ++argumentIndex) { - if (strcmp(argv[argumentIndex], "--interface") == 0) { - ipv6Interface = (uint32_t)strtoul(argv[argumentIndex + 1], NULL, 10); + // 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"); } } - if (!g_udp.Connect(port, ipv6Interface)) { - printf("Error: Failed to bind UDP port %u over IPv6.\n", (unsigned)port); - return 1; + 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"); + } } - printf("FYI: Listening for BACnet/IPv6 on UDP port %u; joined the multicast group FF02::BAC0 on %u interface(s).\n", - (unsigned)port, (unsigned)g_udp.GetJoinedInterfaceCount()); -#else - if (!g_udp.Connect(port)) { - printf("Error: Failed to bind UDP port %u.\n", (unsigned)port); - return 1; + if (g_options.dataLink == DataLink::IPv4 || g_options.dataLink == DataLink::IPv6) { + 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"); + } } - printf("FYI: Listening for BACnet/IP on UDP port %u (Network Port %u).\n", - (unsigned)port, NETWORK_PORT_INSTANCE); + 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 - - // Capture the BACnet/IP addressing the Network Port object will report. - g_bacnetIpUdpPort = port; -#ifndef BBC_IPV6 - 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"); +#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, DEVICE_NAME)) { + return 1; + } } -#endif // !BBC_IPV6 +#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); @@ -2206,6 +2813,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)) { @@ -2301,11 +2916,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. -#ifdef BBC_IPV6 - // BACnet/IPv6 build: the stack has no IPv6 Network Port object yet (cas-bacnet-stack#4611), and its IPv6 data link is the - // only transport, which the default port instance names - so there is no Network Port object to add here. -#else - 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, @@ -2315,7 +2931,48 @@ int main(int argc, char** argv) { printf("Error: Failed to add Network Port 1 (Vermilion).\n"); return 1; } -#endif // BBC_IPV6 + // 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 @@ -2424,35 +3081,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. -#ifdef BBC_IPV6 - // BACnet/IPv6 build: the seeded recipient is a BACnet/IP address (4 IP octets and a port), which a B/IPv6 network has no use for. - // Notification Class 1 starts with an empty Recipient_List; a management station writes one (it is writable, below). -#else - 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; - } -#endif // BBC_IPV6 + // + // 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( @@ -2716,19 +3375,31 @@ 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. -#ifdef BBC_IPV6 - BACnetStack_SendWhoIs(NULL, 0, TRANSPORT_PORT_INSTANCE, true /*broadcast*/, 0, NULL, 0); -#else - uint8_t broadcastConn[6]; - LocalBroadcastConnString(broadcastConn); - BACnetStack_SendWhoIs(broadcastConn, sizeof(broadcastConn), NETWORK_PORT_INSTANCE, - true /*broadcast*/, 0, NULL, 0); -#endif + // 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, DEVICE_NAME, VENDOR_IDENTIFIER); @@ -2740,8 +3411,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) ------------------------------------- @@ -2781,7 +3507,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); } @@ -2832,6 +3558,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; @@ -2846,5 +3580,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..8c55577 --- /dev/null +++ b/sc/ScHubConnector.cpp @@ -0,0 +1,386 @@ +// 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 +#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. +struct Connection { + std::string uri; + lws* socket = NULL; + 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; + } + 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]; + connection.uri = uri; + 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; + connectInfo.pwsi = &connection.socket; + printf("BACnet/SC: connecting to %s\n", uri.c_str()); + if (lws_client_connect_via_info(&connectInfo) == 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..39f7e55 --- /dev/null +++ b/sc/cert_store.cpp @@ -0,0 +1,677 @@ +// 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