Rebuild obu-firmware on Niklas Dathe's microbu-firmware
Replace the vanetza-idf port with his current station firmware (microbu-firmware e4e4bd8: main/, components/microbu_v2x, components/vanetza, external/vanetza) and re-apply the MicrOBU additions, each marked "MicrOBU:" in the sources: - V2X_RX (opcode 0x90): every received ITS message, signed or not, through gn_unwrap.c, because the stack drops unsigned and foreign-root traffic. 0x85 is the spec's RAW_FRAME and 0x86 is reserved. The body is built in v2x_rx.hpp. - Unsigned transmission (geonet.c) for security profile 1 or station security 0, from a random MAC per configuration. - Radio polled from STATION_CONFIGURE on; manual country policy, TX power read-back, static RX buffer, short frames ignored. - Battery guard (battery_policy.hpp): deep sleep below 3.30 V with no phone on USB. - No USB writes without a host; last_frame_ms() for the guard. - 80 KB NVS with the app at 0x20000, 8 MB flash, XIAO ESP32-C5 board, 20 dBm. Remove the old C firmware, the bench listener and the old vanetza-idf copy. Add docs/station-link.tex as revision 2 of the interface reference (V2X_RX, unsigned sending, battery rule, revision history). Add 39 host unit tests (make firmware in test/host) next to the existing chain, replay, fuzz and battery tests, and point tools/station_status_watch.py at the new CONFIRM-based status.
This commit is contained in:
@@ -0,0 +1,166 @@
|
||||
# micrOBU V2X runtime on the Vanetza component (LGPL-3.0-or-later).
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
set(V2X_PORT "${CMAKE_CURRENT_LIST_DIR}")
|
||||
|
||||
if(ESP_PLATFORM)
|
||||
# IDF dependency discovery evaluates this file before Kconfig is available.
|
||||
idf_component_register(SRCS "${V2X_PORT}/src/access.cpp"
|
||||
INCLUDE_DIRS "${V2X_PORT}/include"
|
||||
REQUIRES vanetza mbedtls ${MICROBU_CRYPTO_ADAPTER_COMPONENT}
|
||||
PRIV_REQUIRES esp_wifi esp_phy esp_event nvs_flash)
|
||||
if(CMAKE_BUILD_EARLY_EXPANSION)
|
||||
return()
|
||||
endif()
|
||||
if(NOT CONFIG_COMPILER_CXX_EXCEPTIONS OR NOT CONFIG_COMPILER_CXX_RTTI)
|
||||
message(FATAL_ERROR "microbu_v2x requires CONFIG_COMPILER_CXX_EXCEPTIONS=y and CONFIG_COMPILER_CXX_RTTI=y")
|
||||
endif()
|
||||
set(V2X_TARGET ${COMPONENT_LIB})
|
||||
set(V2X_NETWORK ${CONFIG_MICROBU_V2X_NETWORK})
|
||||
set(V2X_CAM ${CONFIG_MICROBU_V2X_CAM})
|
||||
set(V2X_DENM ${CONFIG_MICROBU_V2X_DENM})
|
||||
set(V2X_VAM ${CONFIG_MICROBU_V2X_VAM})
|
||||
set(V2X_HIL ${CONFIG_MICROBU_V2X_HIL})
|
||||
set(V2X_SECURITY ${CONFIG_MICROBU_V2X_SECURITY})
|
||||
set(V2X_SECURITY_VERIFY ${CONFIG_MICROBU_V2X_SECURITY_VERIFY})
|
||||
set(V2X_PKI ${CONFIG_MICROBU_V2X_PKI})
|
||||
set(V2X_NVS_CREDENTIALS ${CONFIG_MICROBU_V2X_NVS_CREDENTIALS})
|
||||
else()
|
||||
project(microbu_v2x LANGUAGES C CXX)
|
||||
option(V2X_NETWORK "GeoNetworking router, BTP and DCC" ON)
|
||||
option(V2X_CAM "Release 2 CAM codec/endpoint" ON)
|
||||
option(V2X_DENM "Release 2 DENM codec/endpoint" ON)
|
||||
option(V2X_VAM "Release 2 VAM codec/endpoint" ON)
|
||||
set(V2X_HIL OFF)
|
||||
option(V2X_SECURITY "TS 103 097 signing security entity and TS 102 723-8 identifier-change service" ON)
|
||||
option(V2X_SECURITY_VERIFY "SN-DECAP verification of received secured packets (IEEE 1609.2 clause 5.2, TS 103 097 clause 7.1)" ON)
|
||||
option(V2X_PKI "TS 102 941 enrolment/authorization request-response core" OFF)
|
||||
set(V2X_MBEDTLS_ROOT "" CACHE PATH
|
||||
"Host only: mbedTLS (>= 3.6 or 4.x/TF-PSA-Crypto) source tree; builds the PSA backend for testing against OpenSSL")
|
||||
set(VANETZA_SOURCE_DIR "" CACHE PATH
|
||||
"Host only: an already patched Vanetza tree (default: build it from external/vanetza and ../vanetza/patches)")
|
||||
add_subdirectory("${V2X_PORT}/../vanetza" "${CMAKE_BINARY_DIR}/vanetza")
|
||||
add_library(microbu_v2x STATIC src/access.cpp)
|
||||
add_library(Microbu::v2x ALIAS microbu_v2x)
|
||||
set(V2X_TARGET microbu_v2x)
|
||||
target_include_directories(${V2X_TARGET} PUBLIC include)
|
||||
target_link_libraries(${V2X_TARGET} PUBLIC vanetza)
|
||||
endif()
|
||||
|
||||
target_compile_features(${V2X_TARGET} PUBLIC cxx_std_17)
|
||||
set_target_properties(${V2X_TARGET} PROPERTIES C_STANDARD 11 CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
|
||||
if(V2X_SECURITY AND NOT V2X_NETWORK)
|
||||
message(FATAL_ERROR "The security entity serves the GeoNetworking layer: V2X_SECURITY requires V2X_NETWORK")
|
||||
endif()
|
||||
if(V2X_SECURITY_VERIFY AND NOT V2X_SECURITY)
|
||||
message(FATAL_ERROR "V2X_SECURITY_VERIFY requires V2X_SECURITY")
|
||||
endif()
|
||||
if(V2X_PKI AND NOT V2X_SECURITY)
|
||||
message(FATAL_ERROR "V2X_PKI requires V2X_SECURITY")
|
||||
endif()
|
||||
target_compile_definitions(${V2X_TARGET} PUBLIC
|
||||
V2X_NETWORK=$<BOOL:${V2X_NETWORK}> V2X_CAM=$<BOOL:${V2X_CAM}>
|
||||
V2X_DENM=$<BOOL:${V2X_DENM}> V2X_VAM=$<BOOL:${V2X_VAM}> V2X_HIL=$<BOOL:${V2X_HIL}>
|
||||
V2X_SECURITY=$<BOOL:${V2X_SECURITY}> V2X_SECURITY_VERIFY=$<BOOL:${V2X_SECURITY_VERIFY}>
|
||||
V2X_PKI=$<BOOL:${V2X_PKI}>)
|
||||
set(_sources "${V2X_PORT}/src/its_g5_frame.cpp")
|
||||
if(V2X_NETWORK)
|
||||
list(APPEND _sources "${V2X_PORT}/src/stack.cpp" "${V2X_PORT}/src/management.cpp")
|
||||
if(NOT ESP_PLATFORM)
|
||||
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
|
||||
target_link_libraries(${V2X_TARGET} PRIVATE OpenSSL::Crypto)
|
||||
endif()
|
||||
endif()
|
||||
if(V2X_CAM OR V2X_DENM OR V2X_VAM)
|
||||
list(APPEND _sources "${V2X_PORT}/src/facilities.cpp")
|
||||
endif()
|
||||
if(V2X_HIL)
|
||||
list(APPEND _sources "${V2X_PORT}/src/hil.cpp")
|
||||
endif()
|
||||
if(V2X_SECURITY)
|
||||
list(APPEND _sources "${V2X_PORT}/src/ecc.cpp" "${V2X_PORT}/src/security_module.cpp"
|
||||
"${V2X_PORT}/src/security.cpp" "${V2X_PORT}/src/identity_manager.cpp"
|
||||
"${V2X_PORT}/src/sign_header_policy.cpp" "${V2X_PORT}/src/credentials.cpp")
|
||||
if(ESP_PLATFORM)
|
||||
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp" "${V2X_PORT}/src/security_backend.cpp"
|
||||
"${V2X_PORT}/src/local_security.cpp")
|
||||
if(CONFIG_MICROBU_V2X_CRYPTO_SE051 OR CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM)
|
||||
if(NOT MICROBU_CRYPTO_ADAPTER_COMPONENT)
|
||||
message(FATAL_ERROR "External security module selected: set MICROBU_CRYPTO_ADAPTER_COMPONENT to a real adapter component")
|
||||
endif()
|
||||
endif()
|
||||
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
|
||||
if(V2X_NVS_CREDENTIALS)
|
||||
# CredentialStore on nvs_flash (credentials.hpp); the application initialises NVS
|
||||
list(APPEND _sources "${V2X_PORT}/src/nvs_credential_store.cpp")
|
||||
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_NVS_CREDENTIALS=1)
|
||||
endif()
|
||||
else()
|
||||
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_OPENSSL=1)
|
||||
target_compile_definitions(${V2X_TARGET} PRIVATE OPENSSL_API_COMPAT=0x10101000L)
|
||||
if(V2X_MBEDTLS_ROOT)
|
||||
set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE)
|
||||
set(ENABLE_TESTING OFF CACHE BOOL "" FORCE)
|
||||
set(MBEDTLS_FATAL_WARNINGS OFF CACHE BOOL "" FORCE)
|
||||
set(GEN_FILES OFF CACHE BOOL "" FORCE)
|
||||
# ESP-IDF's mbedTLS fork includes "mbedtls/bignum.h"/"mbedtls/ecp.h" wrappers that only
|
||||
# its own port directory provides (they wrap the TF-PSA-Crypto private headers and add
|
||||
# hardware-acceleration hooks). Recreate the plain wrappers so the same tree builds here.
|
||||
set(_v2x_mbedtls_shim "${CMAKE_BINARY_DIR}/mbedtls-shim/mbedtls")
|
||||
foreach(_hdr bignum ecp)
|
||||
if(EXISTS "${V2X_MBEDTLS_ROOT}/tf-psa-crypto/drivers/builtin/include/mbedtls/private/${_hdr}.h"
|
||||
AND NOT EXISTS "${V2X_MBEDTLS_ROOT}/include/mbedtls/${_hdr}.h")
|
||||
file(WRITE "${_v2x_mbedtls_shim}/${_hdr}.h"
|
||||
"#pragma once
|
||||
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
|
||||
#include \"mbedtls/private/${_hdr}.h\"
|
||||
")
|
||||
endif()
|
||||
endforeach()
|
||||
if(EXISTS "${_v2x_mbedtls_shim}")
|
||||
file(WRITE "${CMAKE_BINARY_DIR}/mbedtls-shim/sdkconfig.h" "#pragma once
|
||||
")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I${CMAKE_BINARY_DIR}/mbedtls-shim")
|
||||
endif()
|
||||
add_subdirectory("${V2X_MBEDTLS_ROOT}" "${CMAKE_BINARY_DIR}/mbedtls" EXCLUDE_FROM_ALL)
|
||||
if(TARGET tfpsacrypto)
|
||||
set(_v2x_psa tfpsacrypto) # mbedTLS 4.x
|
||||
else()
|
||||
set(_v2x_psa mbedcrypto) # mbedTLS 3.x
|
||||
endif()
|
||||
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp")
|
||||
target_link_libraries(${V2X_TARGET} PUBLIC ${_v2x_psa})
|
||||
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
|
||||
endif()
|
||||
endif()
|
||||
if(V2X_PKI)
|
||||
list(APPEND _sources "${V2X_PORT}/src/pki.cpp" "${V2X_PORT}/src/trust_update.cpp")
|
||||
if(ESP_PLATFORM OR V2X_MBEDTLS_ROOT)
|
||||
list(APPEND _sources "${V2X_PORT}/src/ecies_mbedtls.cpp")
|
||||
endif()
|
||||
if(NOT ESP_PLATFORM)
|
||||
list(APPEND _sources "${V2X_PORT}/src/ecies_openssl.cpp")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
list(REMOVE_DUPLICATES _sources)
|
||||
target_sources(${V2X_TARGET} PRIVATE ${_sources})
|
||||
if(ESP_PLATFORM AND CONFIG_MICROBU_V2X_RADIO_C5)
|
||||
include("${V2X_PORT}/radio_c5.cmake")
|
||||
endif()
|
||||
if(ESP_PLATFORM AND CONFIG_IDF_TARGET_ESP32C5)
|
||||
# ROM UART0 clock repair for warm resets (see the source); kept by an undefined-symbol reference.
|
||||
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/esp32c5_rom_uart_clock.c")
|
||||
target_link_libraries(${V2X_TARGET} INTERFACE "-u v2x_esp32c5_rom_uart_clock_link")
|
||||
endif()
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
target_compile_options(${V2X_TARGET} PRIVATE -ffunction-sections -fdata-sections
|
||||
-Wno-error=deprecated-declarations)
|
||||
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15)
|
||||
target_compile_options(${V2X_TARGET} PRIVATE -Wno-error=deprecated-variadic-comma-omission)
|
||||
endif()
|
||||
endif()
|
||||
if(ESP_PLATFORM)
|
||||
target_compile_options(${V2X_TARGET} PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wno-error=unused-function>
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wno-error=maybe-uninitialized>)
|
||||
endif()
|
||||
@@ -0,0 +1,98 @@
|
||||
menu "micrOBU V2X stack (Vanetza)"
|
||||
choice MICROBU_V2X_PROFILE
|
||||
prompt "Stack entry point"
|
||||
default MICROBU_V2X_PROFILE_NETWORK
|
||||
config MICROBU_V2X_PROFILE_ACCESS
|
||||
bool "Access: AL_DATA / IN-SAP"
|
||||
config MICROBU_V2X_PROFILE_NETWORK
|
||||
bool "Network: BTP-DATA / NF-SAP"
|
||||
config MICROBU_V2X_PROFILE_FACILITIES
|
||||
bool "Facilities endpoints (CAM, DENM, VAM)"
|
||||
endchoice
|
||||
config MICROBU_V2X_NETWORK
|
||||
bool
|
||||
default y if !MICROBU_V2X_PROFILE_ACCESS
|
||||
config MICROBU_V2X_CAM
|
||||
bool "Release 2 CAM codec and endpoint"
|
||||
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||
depends on MICROBU_V2X_NETWORK
|
||||
config MICROBU_V2X_DENM
|
||||
bool "Release 2 DENM codec and endpoint"
|
||||
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||
depends on MICROBU_V2X_NETWORK
|
||||
config MICROBU_V2X_VAM
|
||||
bool "Release 2 VAM codec and endpoint"
|
||||
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||
depends on MICROBU_V2X_NETWORK
|
||||
config MICROBU_V2X_SECURITY
|
||||
bool "TS 103 097 signing security entity and identifier-change service"
|
||||
default y
|
||||
depends on MICROBU_V2X_NETWORK
|
||||
help
|
||||
SN-SAP security entity: signs outgoing GeoNetworking packets with
|
||||
authorization tickets the application provisions (TS 103 097
|
||||
V2.2.1, IEEE Std 1609.2) on the mbedTLS PSA backend and runs the
|
||||
TS 102 723-8 clause 6.3 identifier-change two-phase commit that
|
||||
the GN core, access adapter and facilities subscribe to. Without
|
||||
it a stack with itsGnSecurity enabled fails closed.
|
||||
choice MICROBU_V2X_CRYPTO
|
||||
prompt "Security module"
|
||||
depends on MICROBU_V2X_SECURITY
|
||||
default MICROBU_V2X_CRYPTO_ESP32
|
||||
help
|
||||
Where the station's private keys live and are used
|
||||
(security_module.hpp). Hashing, verification and point
|
||||
decompression run on the ESP32 PSA backend unless the V2X HSM
|
||||
takes them as well.
|
||||
config MICROBU_V2X_CRYPTO_ESP32
|
||||
bool "Software on the ESP32 (keys in NVS, PSA crypto)"
|
||||
config MICROBU_V2X_CRYPTO_SE051
|
||||
bool "SE051 over I2C (requires an adapter component)"
|
||||
config MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
bool "V2X HSM for keys and public operations (requires an adapter component)"
|
||||
endchoice
|
||||
config MICROBU_V2X_SECURITY_VERIFY
|
||||
bool "SN-DECAP verification of received secured packets"
|
||||
default y
|
||||
depends on MICROBU_V2X_SECURITY
|
||||
help
|
||||
Verify received EtsiTs103097Data-Signed packets (IEEE 1609.2
|
||||
clause 5.2 with the TS 103 097 clause 7.1 profile checks, the
|
||||
certificate chain to the provisioned trust anchors, generation
|
||||
time plausibility and replay detection). Without it SN-DECAP
|
||||
reports Configuration_Problem and a strict GeoNetworking receiver
|
||||
drops every secured packet.
|
||||
config MICROBU_V2X_NVS_CREDENTIALS
|
||||
bool "Credential store on NVS"
|
||||
default y
|
||||
depends on MICROBU_V2X_SECURITY
|
||||
help
|
||||
NvsCredentialStore keeps the station's provisioned credentials
|
||||
(root and CA certificates, authorization tickets with their
|
||||
private keys, credentials.hpp bundle) as one blob in the
|
||||
nvs_flash component's storage. The application initialises NVS
|
||||
and decides on NVS encryption; without this option the
|
||||
application supplies its own CredentialStore.
|
||||
config MICROBU_V2X_PKI
|
||||
bool "TS 102 941 enrolment and authorization request-response core"
|
||||
default n
|
||||
depends on MICROBU_V2X_SECURITY
|
||||
help
|
||||
Builds and parses EtsiTs102941Data enrolment/authorization
|
||||
requests and responses (TS 102 941 V2.2.1 clause 6.2.3). The
|
||||
transport to the EA/AA and credential storage are supplied by the
|
||||
application.
|
||||
choice MICROBU_V2X_RADIO
|
||||
prompt "Access adapter"
|
||||
default MICROBU_V2X_RADIO_EXTERNAL
|
||||
config MICROBU_V2X_RADIO_EXTERNAL
|
||||
bool "Application-provided access adapter"
|
||||
config MICROBU_V2X_RADIO_C5
|
||||
bool "Experimental integrated ESP32-C5 ITS-G5 radio"
|
||||
depends on IDF_TARGET_ESP32C5
|
||||
help
|
||||
Uses OpenTrafficMap's private driver transmit path. Only the
|
||||
pinned ESP-IDF version is accepted. Hardware/RF and DCC
|
||||
qualification remain separate acceptance requirements.
|
||||
endchoice
|
||||
endmenu
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/net/mac_address.hpp>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#if V2X_NETWORK
|
||||
#include <vanetza/common/runtime.hpp>
|
||||
#include <vanetza/dcc/channel_load.hpp>
|
||||
#endif
|
||||
|
||||
namespace microbu_v2x {
|
||||
|
||||
// Implementation result, NOT an additional ETSI AL-DATA.confirm primitive.
|
||||
enum class Result { accepted, invalid_argument, unsupported, wrong_entry_point,
|
||||
security_unavailable, resource_limit, rejected, time_regression,
|
||||
identity_change_pending /*< TS 102 723-8 clause 6.3.1.3: between PREPARE and COMMIT */ };
|
||||
|
||||
// Named PHY modes avoid confusing legacy OFDM coding schemes with the SDK's
|
||||
// rate indices or HT/NGV MCS indices. EN 303 797 clauses 4.3.1 and 4.3.2.
|
||||
enum class OfdmMcs : std::uint8_t {
|
||||
bpsk_1_2, bpsk_3_4, qpsk_1_2, qpsk_3_4,
|
||||
qam16_1_2, qam16_3_4, qam64_2_3, qam64_3_4
|
||||
};
|
||||
|
||||
/** Technology-specific AL_DATA.request: EN 303 797 V2.1.1, Annex B.2.
|
||||
* See EN 303 797 V2.1.1 Annex B. This is the AL_DATA binding,
|
||||
* not the separate IN-UNITDATA interface of TS 102 723-10.
|
||||
* This C++ binding is local: the standard does not prescribe a C++/BLE ABI.
|
||||
* Owns the GNPDU bytes; they exclude LLC, MAC and PHY headers.
|
||||
*/
|
||||
struct AlDataRequest {
|
||||
vanetza::MacAddress source;
|
||||
vanetza::MacAddress destination;
|
||||
std::uint8_t priority = 0; // IEEE 802.1D user priority 0..7, not EDCA ordinal
|
||||
double transmit_power_dbm = 0.0;
|
||||
OfdmMcs mcs = OfdmMcs::qpsk_1_2; // 6 Mbit/s at 10 MHz
|
||||
std::uint16_t bandwidth_mhz = 10;
|
||||
std::uint16_t channel_number = 180;
|
||||
std::uint8_t transceiver_id = 0;
|
||||
std::optional<std::uint8_t> transceiver_mode;
|
||||
std::optional<std::uint32_t> datastream_id;
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
/** AL_DATA.indication, EN 303 797 V2.1.1 Annex B.2.
|
||||
* Optional radio measurements are absent when the backend cannot measure them;
|
||||
* zero must never stand for a made-up measurement.
|
||||
*/
|
||||
struct AlDataIndication {
|
||||
vanetza::MacAddress source;
|
||||
vanetza::MacAddress destination;
|
||||
std::optional<double> channel_busy_ratio;
|
||||
std::optional<double> received_power_dbm;
|
||||
std::uint16_t channel_number = 180;
|
||||
std::uint8_t receiver_id = 0;
|
||||
std::optional<std::uint8_t> receiver_mode;
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
/** Device-independent access adapter. Backend must reject unsupported controls,
|
||||
* apply DCC when allocated to access, and report reception via Stack::indicate.
|
||||
* request takes ownership even on failure. No callback from an interrupt.
|
||||
*/
|
||||
class Access {
|
||||
public:
|
||||
virtual Result request(AlDataRequest) = 0;
|
||||
virtual ~Access() = default;
|
||||
};
|
||||
|
||||
Result validate(const AlDataRequest&, std::size_t maximum_gnpdu);
|
||||
|
||||
/** Access profile has no BTP/GN state and preserves the AL_DATA parameters.
|
||||
*
|
||||
* On a V2X_NETWORK build, optionally runs DCC_ACC (TS 102 687 V1.2.1 clause 5.4 Adaptive
|
||||
* approach, gated by the Annex B budget/gate-keeper) in front of the backend.
|
||||
* Disabled by default so existing callers (host tests, other
|
||||
* applications) are unaffected; the ESP32-C5 firmware enables it once it has a real CBR
|
||||
* source. The DCC methods below do not exist on an access-only build (no
|
||||
* V2X_NETWORK): the Adaptive approach lives in vanetza/dcc, which that configuration does
|
||||
* not compile, matching the documented access-only deployment (docs/conformance.md).
|
||||
*/
|
||||
class AccessStack {
|
||||
public:
|
||||
explicit AccessStack(Access& access, std::size_t maximum_gnpdu = 4096);
|
||||
~AccessStack();
|
||||
AccessStack(const AccessStack&) = delete;
|
||||
AccessStack& operator=(const AccessStack&) = delete;
|
||||
|
||||
#if V2X_NETWORK
|
||||
/** Enable the Adaptive DCC_ACC gate. cbr_target defaults to TS 103 836-4-2's
|
||||
* itsGNCBRTarget = 0.62
|
||||
* (not TS 102 687 Table 3's older, superseded 0.68 default).
|
||||
* runtime must outlive this AccessStack and must be the same Runtime driving the caller's
|
||||
* periodic advance()/trigger() (e.g. the Stack's ManualRuntime), since the Adaptive approach
|
||||
* reschedules itself every 200 ms of that runtime's own clock.
|
||||
* Call once, before the first request().
|
||||
*/
|
||||
void enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target = vanetza::dcc::ChannelLoad(0.62));
|
||||
|
||||
/** Feed the latest channel-busy-ratio measurement at roughly the T_Cbr cadence (100 ms):
|
||||
* local LCBR, or CBR_G when a Release-2 DCC_NET has one available. No-op unless
|
||||
* enable_dcc was called.
|
||||
*/
|
||||
void report_channel_load(vanetza::dcc::ChannelLoad);
|
||||
|
||||
/** Permitted duty cycle (delta) from the last periodic Adaptive-approach update.
|
||||
* Returns UnitInterval(1.0) (unrestricted) when DCC is not enabled.
|
||||
*/
|
||||
vanetza::UnitInterval permitted_duty_cycle() const;
|
||||
#endif
|
||||
|
||||
Result request(AlDataRequest);
|
||||
private:
|
||||
#if V2X_NETWORK
|
||||
class Dcc;
|
||||
std::unique_ptr<Dcc> dcc_;
|
||||
#endif
|
||||
Access& access_;
|
||||
std::size_t maximum_gnpdu_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace microbu_v2x {
|
||||
|
||||
/** vanetza::security::Backend on the PSA Crypto API of mbedTLS.
|
||||
*
|
||||
* ESP-IDF 6.0.2 ships mbedTLS 4.1.0 (TF-PSA-Crypto), where the classic
|
||||
* ecp/ecdsa/bignum headers are private; the PSA API (psa/crypto.h) is the only
|
||||
* public cryptography interface and is also present in mbedTLS 3.6 (ESP-IDF 5.x).
|
||||
*
|
||||
* Algorithms are those TS 103 097 V2.2.1 clause 5.2 selects through IEEE Std
|
||||
* 1609.2: ECDSA over NIST P-256, brainpoolP256r1 (SHA-256) and brainpoolP384r1
|
||||
* (SHA-384), clauses 5.3.1, 5.3.3, 6.3.38/6.3.39. ECDSA is randomized
|
||||
* (PSA_ALG_ECDSA(SHA-256/SHA-384) over the caller-supplied digest of that
|
||||
* length, which lets ESP-IDF's PSA driver use the ESP32-C5 ECDSA peripheral for
|
||||
* verification; IEEE Std 1609.2 does not require RFC 6979). Compressed points
|
||||
* are recovered by microbu_v2x::ecc, since PSA imports Weierstrass public keys
|
||||
* only in SEC 1 uncompressed form.
|
||||
*
|
||||
* Private keys are imported as volatile PSA keys the first time they are used
|
||||
* and kept in a small bounded cache until the backend is destroyed. Every
|
||||
* failure raises std::runtime_error or returns false; nothing is faked.
|
||||
*/
|
||||
class BackendMbedTls : public vanetza::security::Backend, public security::KeyGenerator {
|
||||
public:
|
||||
static constexpr auto backend_name = "mbedTLS-PSA";
|
||||
|
||||
BackendMbedTls();
|
||||
~BackendMbedTls() override;
|
||||
BackendMbedTls(const BackendMbedTls&) = delete;
|
||||
BackendMbedTls& operator=(const BackendMbedTls&) = delete;
|
||||
|
||||
/// Legacy NIST P-256 + SHA-256 signature of data (TS 103 097 v1.x, IEEE 1609.2 5.3.1)
|
||||
vanetza::security::EcdsaSignature sign_data(const vanetza::security::ecdsa256::PrivateKey&,
|
||||
const vanetza::ByteBuffer& data) override;
|
||||
/// ECDSA over a precomputed digest; curve follows the key type
|
||||
vanetza::security::Signature sign_digest(const vanetza::security::PrivateKey&,
|
||||
const vanetza::ByteBuffer& digest) override;
|
||||
bool verify_data(const vanetza::security::ecdsa256::PublicKey&, const vanetza::ByteBuffer& data,
|
||||
const vanetza::security::EcdsaSignature&) override;
|
||||
bool verify_digest(const vanetza::security::PublicKey&, const vanetza::ByteBuffer& digest,
|
||||
const vanetza::security::Signature&) override;
|
||||
/// NIST P-256 only, matching the upstream OpenSSL backend (EccPoint carries no curve)
|
||||
boost::optional<vanetza::security::Uncompressed> decompress_point(const vanetza::security::EccPoint&) override;
|
||||
vanetza::ByteBuffer calculate_hash(vanetza::security::HashAlgorithm, const vanetza::ByteBuffer&) override;
|
||||
/// Fresh NIST P-256 key pair from the PSA random generator
|
||||
vanetza::security::ecdsa256::KeyPair generate_key_pair() override;
|
||||
/// Fresh ECDSA key pair on any TS 103 097 curve from the PSA random generator (SoftwareSecurityModule)
|
||||
security::KeyPair generate_key(vanetza::security::KeyType) override;
|
||||
|
||||
/** Maximum number of imported private keys kept resident (default 4:
|
||||
* the current and next authorization tickets plus enrolment material). */
|
||||
void set_key_cache_size(std::size_t);
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
#include <sdkconfig.h>
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32C5) || !defined(CONFIG_MICROBU_V2X_RADIO_C5)
|
||||
#error "C5Radio requires ESP32-C5 and CONFIG_MICROBU_V2X_RADIO_C5"
|
||||
#endif
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <esp_err.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace microbu_v2x {
|
||||
struct C5RadioConfig {
|
||||
std::uint16_t channel_number = 180;
|
||||
double transmit_power_dbm = 10.0;
|
||||
unsigned receive_queue_length = 8;
|
||||
// Explicit laboratory mode until real CBR/DCC enforcement is integrated.
|
||||
// The default supports a receive-only second C5 without any packet TX.
|
||||
bool laboratory_transmission = false;
|
||||
};
|
||||
|
||||
/** ITS-G5 AL_DATA device binding, EN 303 797 Annex B.2.
|
||||
* This adapter owns the Wi-Fi driver while started. Invoke start/stop/request/
|
||||
* poll in one application task. Radio callbacks only copy into a bounded queue.
|
||||
* No MQTT, Ethernet, storage, facilities service or test runtime is included.
|
||||
*/
|
||||
class C5Radio final : public Access {
|
||||
public:
|
||||
using Receive = std::function<void(AlDataIndication)>;
|
||||
using Capture = std::function<void(const vanetza::ByteBuffer&, int, std::uint32_t)>;
|
||||
explicit C5Radio(C5RadioConfig = {});
|
||||
~C5Radio();
|
||||
C5Radio(const C5Radio&) = delete;
|
||||
C5Radio& operator=(const C5Radio&) = delete;
|
||||
esp_err_t start();
|
||||
void stop();
|
||||
Result request(AlDataRequest) override;
|
||||
// Dispatch reception in the owning task. Capture contains the original
|
||||
// MPDU including FCS, before LLC/MAC removal; timestamp is radio-local us.
|
||||
void poll(const Receive&, const Capture& = {});
|
||||
std::uint32_t dropped_frames() const;
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/** A station's provisioned credentials and how they are kept.
|
||||
*
|
||||
* TS 102 940 V2.1.1 clause 6 (trust model: root CA, EA/AA, tickets) and TS 102 941
|
||||
* V2.2.1 (credential life cycle) leave the obtaining and keeping of certificates to
|
||||
* the station; TS 102 723-8 has no primitive for it. The security entity takes
|
||||
* them as a TrustConfiguration and a CertificatePool (security.hpp). This header
|
||||
* fixes the octets in between. Certificates are COER EtsiTs103097Certificate
|
||||
* values (TS 103 097 V2.2.1 clause 6).
|
||||
*
|
||||
* Credentials is the laboratory provisioning bundle, which carries the private
|
||||
* scalar of each ticket's verification key (IEEE Std 1609.2 clause 6.4.36 curves).
|
||||
* Format (this library's definition, version 1): the ASCII magic "VCR1" followed
|
||||
* by records [type: 1 octet][length: 2 octets, big-endian][payload]. Types: 1 root
|
||||
* CA certificate, 2 subordinate CA certificate (AA/EA), 3 ticket certificate, 4
|
||||
* ticket private key ([curve: 1 octet, 1 = NIST P-256, 2 = brainpoolP256r1, 3 =
|
||||
* brainpoolP384r1][scalar]) which follows its ticket certificate. The keys travel
|
||||
* in the clear, so the transport must be a trusted one. import_keys() moves them
|
||||
* into the security module.
|
||||
*
|
||||
* StoredCredentials is what the station keeps: the same certificates, and for each
|
||||
* ticket the KeyId of its key in the security module instead of the key. Format
|
||||
* "VCS1" with the record types 1 to 3 above and 5, the KeyId (4 octets, big-endian),
|
||||
* which follows its ticket certificate. Decoding fails closed on any deviation.
|
||||
*/
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
struct Credentials {
|
||||
struct Ticket {
|
||||
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
|
||||
PrivateKey key; // private scalar of verifyKeyIndicator
|
||||
};
|
||||
std::vector<ByteBuffer> roots; // clause 7.2.3, self-signed
|
||||
std::vector<ByteBuffer> authorities; // clause 7.2.4, issued by a root or another CA
|
||||
std::vector<Ticket> tickets; // clause 7.2.1, with keys
|
||||
|
||||
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
|
||||
};
|
||||
|
||||
struct StoredCredentials {
|
||||
struct Ticket {
|
||||
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
|
||||
KeyId key; // the verification key in the security module
|
||||
};
|
||||
std::vector<ByteBuffer> roots;
|
||||
std::vector<ByteBuffer> authorities;
|
||||
std::vector<Ticket> tickets;
|
||||
|
||||
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
|
||||
};
|
||||
|
||||
/// bundle octets of the credentials (formats above)
|
||||
ByteBuffer encode(const Credentials&);
|
||||
ByteBuffer encode(const StoredCredentials&);
|
||||
/// parse a bundle; false (and an untouched output) when the octets are not a well-formed bundle
|
||||
bool decode(const ByteBuffer& bundle, Credentials& out);
|
||||
bool decode(const ByteBuffer& bundle, StoredCredentials& out);
|
||||
|
||||
/** Import every ticket key of a provisioning bundle into the module, paired with the verification key of its
|
||||
* certificate. None, with every key of this call destroyed again, when a ticket certificate does not decode or
|
||||
* its key does not belong to it. Throws what the module throws. */
|
||||
std::optional<StoredCredentials> import_keys(const Credentials&, SecurityModule&);
|
||||
|
||||
/** Result of feeding credentials into the trust configuration and the pool: how many
|
||||
* of each were accepted and the first refusal (Result::accepted when everything was). */
|
||||
struct ApplyReport {
|
||||
std::size_t roots = 0, authorities = 0, tickets = 0;
|
||||
Result result = Result::accepted;
|
||||
};
|
||||
/** Add every root, then every authority, then every ticket, each through the checks of
|
||||
* TrustConfiguration::add_* and CertificatePool::add (TS 103 097 profiles, key/certificate
|
||||
* match); stops at the first refusal so that a broken item is not silently skipped. */
|
||||
ApplyReport apply(const StoredCredentials&, TrustConfiguration&, CertificatePool&);
|
||||
|
||||
/** Storage the application chooses: keeps one set. load() returns Result::rejected
|
||||
* when nothing is stored and Result::invalid_argument when the stored octets do not
|
||||
* decode; save() replaces what was there; erase() removes it. */
|
||||
class CredentialStore {
|
||||
public:
|
||||
virtual ~CredentialStore() = default;
|
||||
virtual Result save(const StoredCredentials&) = 0;
|
||||
virtual Result load(StoredCredentials&) = 0;
|
||||
virtual Result erase() = 0;
|
||||
};
|
||||
|
||||
/// a bundle in one file (hosts, or an ESP-IDF VFS the application mounted)
|
||||
class FileCredentialStore final : public CredentialStore {
|
||||
public:
|
||||
explicit FileCredentialStore(std::string path) : path_(std::move(path)) {}
|
||||
Result save(const StoredCredentials&) override;
|
||||
Result load(StoredCredentials&) override;
|
||||
Result erase() override;
|
||||
private:
|
||||
std::string path_;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/security/ecc_point.hpp>
|
||||
#include <vanetza/security/key_type.hpp>
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <cstddef>
|
||||
|
||||
namespace microbu_v2x::ecc {
|
||||
|
||||
/** Short Weierstrass domain parameters y^2 = x^3 + a*x + b (mod p), big-endian octets.
|
||||
* NIST P-256 (FIPS 186-4 D.1.2.3), brainpoolP256r1 and brainpoolP384r1 (RFC 5639
|
||||
* clause 3.4/3.6): the three curves TS 103 097 V2.2.1 clause 6 admits for
|
||||
* verification keys (IEEE Std 1609.2 clause 6.4.36 PublicVerificationKey).
|
||||
* All three primes satisfy p = 3 (mod 4).
|
||||
*/
|
||||
struct CurveParameters {
|
||||
vanetza::security::KeyType type;
|
||||
std::size_t octets; // field element length
|
||||
const char* p;
|
||||
const char* a;
|
||||
const char* b;
|
||||
};
|
||||
|
||||
/** Domain parameters for a key type, nullptr for KeyType::Unspecified. */
|
||||
const CurveParameters* curve(vanetza::security::KeyType);
|
||||
|
||||
/** Recover an affine point from its x coordinate and the parity of y.
|
||||
* IEEE Std 1609.2 clause 6.3.23 EccP256CurvePoint / 6.3.24 EccP384CurvePoint
|
||||
* compressed-y-0 / compressed-y-1 forms (SEC 1 clause 2.3.4). Pure integer
|
||||
* arithmetic (Boost.Multiprecision), so it is independent of the crypto backend.
|
||||
* \return uncompressed point, or none if x has the wrong length or is not on the curve
|
||||
*/
|
||||
boost::optional<vanetza::security::Uncompressed>
|
||||
decompress(vanetza::security::KeyType, const vanetza::ByteBuffer& x, bool y_odd);
|
||||
|
||||
/** SEC 1 clause 2.3.3 octet-string point encoding 0x04 || X || Y. */
|
||||
vanetza::ByteBuffer encode_uncompressed(const vanetza::security::Uncompressed&);
|
||||
|
||||
} // namespace microbu_v2x::ecc
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/pki.hpp>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
|
||||
/** EciesBackend on the PSA Crypto API of mbedTLS (see backend_mbedtls.hpp for the
|
||||
* version rationale): psa_raw_key_agreement(PSA_ALG_ECDH) for the shared x
|
||||
* coordinate, psa_mac_compute(PSA_ALG_HMAC(SHA-256)), psa_generate_random and
|
||||
* psa_aead_encrypt/decrypt(PSA_ALG_CCM) with a 16-octet tag. */
|
||||
class EciesMbedTls : public EciesBackend {
|
||||
public:
|
||||
EciesMbedTls(); // psa_crypto_init, throws on failure
|
||||
KeyPair generate_key(KeyType) override;
|
||||
std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) override;
|
||||
ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) override;
|
||||
ByteBuffer random(std::size_t octets) override;
|
||||
bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) override;
|
||||
bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/pki.hpp>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
|
||||
/// EciesBackend on OpenSSL (host builds only): ECDH via EC_KEY, HMAC-SHA256, RAND_bytes, EVP AES-128-CCM.
|
||||
class EciesOpenSsl : public EciesBackend {
|
||||
public:
|
||||
KeyPair generate_key(KeyType) override;
|
||||
std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) override;
|
||||
ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) override;
|
||||
ByteBuffer random(std::size_t octets) override;
|
||||
bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) override;
|
||||
bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/support/uper_decoder.h>
|
||||
#if V2X_CAM
|
||||
#include <vanetza/asn1/its/r2/CAM.h>
|
||||
#endif
|
||||
#if V2X_DENM
|
||||
#include <vanetza/asn1/its/r2/DENM.h>
|
||||
#endif
|
||||
#if V2X_VAM
|
||||
#include <vanetza/asn1/its/r2/VAM.h>
|
||||
#endif
|
||||
|
||||
namespace microbu_v2x::facilities {
|
||||
template<class T>
|
||||
struct CompletePerMessage : vanetza::asn1::asn1c_per_wrapper<T> {
|
||||
using vanetza::asn1::asn1c_per_wrapper<T>::asn1c_per_wrapper;
|
||||
|
||||
bool decode_exact(const vanetza::ByteBuffer& bytes) {
|
||||
if (bytes.empty()) return false;
|
||||
// X.691 complete encoding: consume the PDU and only its zero padding.
|
||||
// Comparing a re-encoding would incorrectly reject unknown extensions
|
||||
// which an extensible ASN.1 decoder is permitted to skip.
|
||||
void* decoded = nullptr;
|
||||
asn_codec_ctx_t context{};
|
||||
context.max_stack_size = 16384;
|
||||
const auto result = uper_decode(&context, this->m_type, &decoded,
|
||||
bytes.data(), bytes.size(), 0, 0);
|
||||
const bool complete = result.code == RC_OK && result.consumed > 0 &&
|
||||
(result.consumed + 7) / 8 == bytes.size();
|
||||
const unsigned padding = complete ? (8 - result.consumed % 8) % 8 : 0;
|
||||
if (!complete || (bytes.back() & ((1u << padding) - 1u))) {
|
||||
vanetza::asn1::free(*this->m_type, decoded);
|
||||
return false;
|
||||
}
|
||||
vanetza::asn1::free(*this->m_type, this->m_struct);
|
||||
this->m_struct = static_cast<T*>(decoded);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
// Explicit R2 aliases avoid Vanetza's backwards-compatible R1 Cam/Denm aliases.
|
||||
// TS 103 900 V2.3.1, TS 103 831 V2.3.1,
|
||||
// TS 103 300-3 V2.3.1 ASN.1; CDD TS 102 894-2 V2.4.1.
|
||||
#if V2X_CAM
|
||||
struct Cam : CompletePerMessage<Vanetza_ITS2_CAM_t> {
|
||||
Cam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_CAM) {}
|
||||
};
|
||||
#endif
|
||||
#if V2X_DENM
|
||||
struct Denm : CompletePerMessage<Vanetza_ITS2_DENM_t> {
|
||||
Denm() : CompletePerMessage(asn_DEF_Vanetza_ITS2_DENM) {}
|
||||
};
|
||||
#endif
|
||||
#if V2X_VAM
|
||||
struct Vam : CompletePerMessage<Vanetza_ITS2_VAM_t> {
|
||||
Vam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_VAM) {}
|
||||
};
|
||||
#endif
|
||||
|
||||
enum class Kind { cam, denm, vam };
|
||||
struct Descriptor { std::uint16_t port; unsigned message_id; unsigned protocol_version; };
|
||||
Descriptor descriptor(Kind);
|
||||
|
||||
/** Decode + constraints + identity + exact UPER consumption.
|
||||
* This boundary validates an encoded PDU. It is NOT a complete CA, DEN or VRU
|
||||
* Basic Service: generation rules/lifecycle/SSP decisions belong to that service.
|
||||
*/
|
||||
Result validate_pdu(Kind, const vanetza::ByteBuffer&, std::size_t maximum = 1394);
|
||||
|
||||
/** Application owns generation and lifecycle; this function selects the standard
|
||||
* BTP port and validates the Release 2 PDU before entering the NF-SAP.
|
||||
*/
|
||||
#if V2X_NETWORK
|
||||
}
|
||||
#include <microbu_v2x/stack.hpp>
|
||||
namespace microbu_v2x::facilities {
|
||||
Result send(Stack&, Kind, vanetza::ByteBuffer, BtpRequest transport);
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/security/hashed_id.hpp>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
/** Identifier-change service of the security entity.
|
||||
*
|
||||
* TS 102 723-8 V2.0.0 clause 5 incorporates V1.1.1: clauses 5.2.5 to 5.2.10
|
||||
* (SN-IDCHANGE-SUBSCRIBE/-EVENT/-UNSUBSCRIBE/-TRIGGER, SN-ID-LOCK/-UNLOCK) and
|
||||
* clause 6.3 (ID management: hook function, two-phase commit, lock, trigger).
|
||||
* TS 102 723-9 V1.1.1 clauses 5.2.5 to 5.2.10 define the identical SF-SAP
|
||||
* primitives (Tables 10 to 21 carry the same names and ranges), and clause
|
||||
* 4.1.5 allows one security entity to serve several layers, so one service
|
||||
* instance is exposed through both sn_sap.hpp and sf_sap.hpp. TS 102 940
|
||||
* V2.1.1 clause 6.5 requires every layer holding an identifier to subscribe
|
||||
* and derive its identifier from the HashedId8 given in the event.
|
||||
*
|
||||
* A subscriber may live in the same task, another task or process, or another
|
||||
* device: the hook is an ordinary callback and the response object may be used
|
||||
* inside the callback or later. The library defines no transport for that.
|
||||
*/
|
||||
|
||||
/// SN-IDCHANGE-EVENT.indication command (TS 102 723-8 V1.1.1 Table 12; clause 6.3.1.2 a-d)
|
||||
enum class IdChangeCommand : std::uint8_t { PREPARE, COMMIT, ABORT, DEREG };
|
||||
|
||||
/// Table 11 / Table 14 subscription: INTEGER 0 to 2^64-1
|
||||
using SubscriptionHandle = std::uint64_t;
|
||||
/// Table 19 / Table 20 lock_handle: INTEGER 0 to 2^64-1
|
||||
using LockHandle = std::uint64_t;
|
||||
/// Table 12 id: OCTET STRING of 8 octets, the HashedId8 of the authorization ticket (TS 102 940 clause 6.5)
|
||||
using Identifier = vanetza::security::HashedId8;
|
||||
|
||||
/** SN-IDCHANGE-EVENT.response (Table 13 return_code).
|
||||
* Hand the object back within the hook call for a local subscriber, or keep it
|
||||
* and respond once the remote party has answered. Responding twice, or after
|
||||
* the phase finished (timeout, abort, unsubscribe), is ignored.
|
||||
*/
|
||||
class IdChangeResponder {
|
||||
public:
|
||||
virtual void respond(bool return_code) = 0;
|
||||
virtual ~IdChangeResponder() = default;
|
||||
};
|
||||
|
||||
/** Hook function (clause 6.3.1.2): command, id to be set and the subscriber_data
|
||||
* given at subscription (Table 12). For PREPARE and COMMIT the service waits
|
||||
* for the response; ABORT and DEREG expect no response (responder is null). */
|
||||
using IdChangeHook = std::function<void(IdChangeCommand, const Identifier&, const vanetza::ByteBuffer& subscriber_data,
|
||||
std::shared_ptr<IdChangeResponder>)>;
|
||||
|
||||
/** The identifier-change service of the security entity (TS 102 723-8 V1.1.1 clause 6.3
|
||||
* "ID management"): SN-IDCHANGE-SUBSCRIBE/-UNSUBSCRIBE/-TRIGGER and SN-ID-LOCK/-UNLOCK
|
||||
* (clauses 5.2.5, 5.2.7 to 5.2.10) as virtual calls; the same instance serves the
|
||||
* SF-SAP (TS 102 723-9 V1.1.1 clauses 5.2.5 to 5.2.10). */
|
||||
class IdChangeService {
|
||||
public:
|
||||
virtual ~IdChangeService() = default;
|
||||
|
||||
/// SN-IDCHANGE-SUBSCRIBE.request (Table 10) -> .confirm subscription (Table 11)
|
||||
virtual SubscriptionHandle subscribe(IdChangeHook idchange_event_hook, vanetza::ByteBuffer subscriber_data = {}) = 0;
|
||||
|
||||
/// SN-IDCHANGE-UNSUBSCRIBE.request (Table 14); .confirm carries no parameter (Table 15)
|
||||
virtual Result unsubscribe(SubscriptionHandle subscription) = 0;
|
||||
|
||||
/** SN-IDCHANGE-TRIGGER.request (Table 16). Queues an identifier change; clause 6.3.3 NOTE:
|
||||
* this does not lead to an immediate change, the two-phase commit is invoked, after any
|
||||
* lock is released. Result::rejected when no other valid authorization ticket exists. */
|
||||
virtual Result trigger() = 0;
|
||||
|
||||
/// SN-ID-LOCK.request Duration 0..255 seconds (Table 18) -> lock_handle (Table 19); clause 6.3.2
|
||||
virtual LockHandle lock(std::uint8_t duration_seconds) = 0;
|
||||
|
||||
/// SN-ID-UNLOCK.request (Table 20); .confirm carries no parameter (Table 21)
|
||||
virtual Result unlock(LockHandle lock_handle) = 0;
|
||||
|
||||
/// HashedId8 of the authorization ticket currently in use (TS 102 940 clause 6.5)
|
||||
virtual Identifier current_identifier() const = 0;
|
||||
|
||||
/// true while PREPARE has been issued and COMMIT/ABORT is outstanding (clause 6.3.1.3 item 2)
|
||||
virtual bool change_pending() const = 0;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
|
||||
namespace microbu_v2x::its_g5 {
|
||||
// IEEE 802.11 QoS Data header (26 octets) and IEEE 802 LLC/SNAP (8 octets).
|
||||
// EN 303 797 clauses 4.4/4.5 and Annex B.2; GeoNetworking EtherType 0x8947.
|
||||
constexpr std::size_t maximum_gnpdu = 2296;
|
||||
Result encode_frame(const AlDataRequest&, std::uint16_t sequence, vanetza::ByteBuffer&);
|
||||
// Caller declares FCS presence; this function never guesses from payload bytes.
|
||||
// Receive PHY/FCS status must be checked by the radio before calling this:
|
||||
// on ESP32-C5, any frame reaching the promiscuous callback has already passed
|
||||
// a real hardware FCS check (WIFI_PROMIS_FILTER_MASK_FCSFAIL is never set),
|
||||
// and the 4 trailing bytes this flag strips are not a software-recoverable
|
||||
// copy of that FCS -- see c5_radio.cpp's receive() for the measured evidence.
|
||||
Result decode_frame(const std::uint8_t*, std::size_t, bool includes_fcs, AlDataIndication&);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
/** ITS time base: TAI microseconds since the ITS epoch 2004-01-01T00:00:00.000 UTC.
|
||||
*
|
||||
* TS 102 894-2 V2.4.1 DE_TimestampIts: "elapsed milliseconds since the ITS epoch
|
||||
* ... TAI is a continuous time scale. UTC has discontinuities, as it is occasionally
|
||||
* adjusted by leap seconds. As of 1 January, 2022, TimestampIts is 5 seconds ahead
|
||||
* of UTC" (example: 2007-01-01T00:00:00.000Z is 94 694 401 000 ms, one leap second
|
||||
* since the epoch). IEEE Std 1609.2 Time64 is the same scale in microseconds and
|
||||
* Time32 in seconds ("the number of (TAI) microseconds/seconds since 00:00:00 UTC,
|
||||
* 1 January, 2004", Ieee1609Dot2BaseTypes ASN.1 module as published by ETSI);
|
||||
* TS 103 097 V2.2.1 generationTime and certificate validityPeriod use them. vanetza::Clock::time_point counts these
|
||||
* microseconds; upstream's Clock::at(posix_time) subtracts the epoch in UTC without
|
||||
* leap seconds and is therefore 5 s behind since 2017: convert wall-clock time with
|
||||
* this header.
|
||||
*
|
||||
* Leap seconds are announced by the IERS at most six months ahead; the table ends
|
||||
* with the insertion of 2016-12-31 (Bulletin C 52). It must be extended when a new
|
||||
* one is announced, the same as any TAI-UTC table (tzdata leap-seconds.list).
|
||||
*/
|
||||
namespace microbu_v2x::its_time {
|
||||
|
||||
/// Unix time (seconds since 1970-01-01T00:00:00Z, no leap seconds) of the ITS epoch.
|
||||
constexpr std::int64_t epoch_unix_seconds = 1072915200;
|
||||
|
||||
/// Unix instants at which UTC gained a leap second after the ITS epoch: 2006-01-01,
|
||||
/// 2009-01-01, 2012-07-01, 2015-07-01, 2017-01-01 (each 00:00:00Z, the first second
|
||||
/// after the inserted 23:59:60). TAI-UTC was 32 s at the epoch and is 37 s since 2017.
|
||||
constexpr std::array<std::int64_t, 5> leap_second_unix_seconds = {
|
||||
1136073600, 1230768000, 1341100800, 1435708800, 1483228800};
|
||||
|
||||
/// Number of leap seconds inserted between the ITS epoch and the given Unix instant.
|
||||
constexpr int leap_seconds_since_epoch(std::int64_t unix_seconds) {
|
||||
int count = 0;
|
||||
for (auto at : leap_second_unix_seconds) if (unix_seconds >= at) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/// TAI microseconds since the ITS epoch for a Unix instant given as seconds and an
|
||||
/// additional sub-second part in microseconds.
|
||||
constexpr std::int64_t microseconds_since_epoch(std::int64_t unix_seconds, std::int64_t sub_second_microseconds = 0) {
|
||||
return (unix_seconds - epoch_unix_seconds + leap_seconds_since_epoch(unix_seconds)) * 1000000 + sub_second_microseconds;
|
||||
}
|
||||
|
||||
/// The same for a std::chrono system clock instant (Unix time on every platform this library targets).
|
||||
inline std::chrono::microseconds since_epoch(std::chrono::system_clock::time_point at) {
|
||||
// ("unix" itself is a predefined macro on GNU/Linux)
|
||||
const auto unix_us = std::chrono::duration_cast<std::chrono::microseconds>(at.time_since_epoch()).count();
|
||||
const std::int64_t seconds = unix_us >= 0 ? unix_us / 1000000 : -((-unix_us + 999999) / 1000000);
|
||||
return std::chrono::microseconds(microseconds_since_epoch(seconds, unix_us - seconds * 1000000));
|
||||
}
|
||||
|
||||
/// TS 102 894-2 TimestampIts (milliseconds) for a system clock instant.
|
||||
inline std::uint64_t timestamp_its(std::chrono::system_clock::time_point at) {
|
||||
return static_cast<std::uint64_t>(since_epoch(at).count() / 1000);
|
||||
}
|
||||
|
||||
/// IEEE Std 1609.2 Time32 (seconds) for a system clock instant.
|
||||
inline std::uint32_t time32(std::chrono::system_clock::time_point at) {
|
||||
return static_cast<std::uint32_t>(since_epoch(at).count() / 1000000);
|
||||
}
|
||||
|
||||
/// Inverse: Unix microseconds for TAI microseconds since the ITS epoch. An instant inside an
|
||||
/// inserted leap second (UTC 23:59:60) has no Unix second of its own and maps onto the
|
||||
/// following 00:00:00.
|
||||
constexpr std::int64_t unix_microseconds(std::int64_t microseconds_since_its_epoch) {
|
||||
const std::int64_t tai_seconds = microseconds_since_its_epoch / 1000000;
|
||||
int inserted = 0;
|
||||
for (std::size_t i = 0; i < leap_second_unix_seconds.size(); ++i) {
|
||||
// TAI value (since the ITS epoch) of the first second after the i-th insertion
|
||||
const std::int64_t tai_of_leap = leap_second_unix_seconds[i] - epoch_unix_seconds + static_cast<std::int64_t>(i + 1);
|
||||
if (tai_seconds >= tai_of_leap) ++inserted;
|
||||
}
|
||||
return (tai_seconds + epoch_unix_seconds - inserted) * 1000000 + microseconds_since_its_epoch % 1000000;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::its_time
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <microbu_v2x/mn_sap.hpp>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
/** MF-SAP language binding: management entity -> facilities layer.
|
||||
*
|
||||
* - TS 102 723-5 V2.0.0 clause 5 incorporates V1.1.1 altogether, which (like
|
||||
* TS 102 723-4 for MN) provides MF-COMMAND and MF-REQUEST with the generic
|
||||
* envelope of TS 102 723-1: entity identifier, CommandRef, command/request
|
||||
* number and value, ErrStatus in the confirm.
|
||||
* - TS 103 175 V1.1.1 clause 8.4: MF-SET.request/.confirm (Tables 11/12) with
|
||||
* the DCC F-Params of Table 13, i.e. the channel-load feedback the DCC
|
||||
* management entity gives the facilities layer (clause 6.5 DCC_CROSS_Facilities).
|
||||
* The facilities layer implements FacilitiesParameterSink; it may live in
|
||||
* another task, process or device, the library defines no transport.
|
||||
*/
|
||||
namespace microbu_v2x::MF_SAP {
|
||||
|
||||
using MN_SAP::ErrStatus;
|
||||
|
||||
/// TS 103 175 V1.1.1 Table 13: F-Param.No for the DCC interface at the MF-SAP
|
||||
enum class F_Param_No : std::uint8_t {
|
||||
CHANNEL_NUMBER = 0, // R/W, 1 octet 1..7 (selects the channel for consecutive reads/writes)
|
||||
AVAILABLE_RESOURCE = 1, // R/W, 2 octets, reciprocal value of CBRa on the selected channel
|
||||
};
|
||||
struct F_Param { F_Param_No no; std::uint32_t value; };
|
||||
struct F_Error { F_Param_No f_param_no; ErrStatus err_status; };
|
||||
|
||||
/// Table 11: MF-SET.request
|
||||
struct MF_SET_request { std::uint32_t fac_id; std::uint8_t command_ref; std::vector<F_Param> f_param; };
|
||||
/// Table 12: MF-SET.confirm (Errors optional)
|
||||
struct MF_SET_confirm { std::uint32_t fac_id; std::uint8_t command_ref; std::vector<F_Error> errors; };
|
||||
|
||||
/// TS 102 723-1 envelope (through TS 102 723-5): MF-COMMAND.request/.confirm, MF-REQUEST.request/.confirm.
|
||||
/// Command and request numbers are entity specific (annexes of the respective part); opaque here.
|
||||
struct MF_COMMAND_request { std::uint32_t fac_id; std::uint8_t command_ref; std::uint32_t command_no; vanetza::ByteBuffer value; };
|
||||
struct MF_COMMAND_confirm { std::uint32_t fac_id; std::uint8_t command_ref; ErrStatus err_status; };
|
||||
struct MF_REQUEST_request { std::uint32_t fac_id; std::uint8_t command_ref; std::uint32_t request_no; vanetza::ByteBuffer value; };
|
||||
struct MF_REQUEST_confirm { std::uint32_t fac_id; std::uint8_t command_ref; ErrStatus err_status; vanetza::ByteBuffer value; };
|
||||
|
||||
/** Implemented by the facilities layer (e.g. the message generation services that
|
||||
* adapt their rate to the available resource). */
|
||||
class FacilitiesParameterSink {
|
||||
public:
|
||||
virtual ~FacilitiesParameterSink() = default;
|
||||
virtual ErrStatus set(F_Param_No, std::uint32_t value) = 0;
|
||||
/// MF-COMMAND / MF-REQUEST are delivered unchanged; a sink that knows no such number
|
||||
/// answers INVALID_COMMAND_REQUEST_NUMBER (TS 102 723-3 clause 5.2.3 wording).
|
||||
virtual MF_COMMAND_confirm command(const MF_COMMAND_request& request) {
|
||||
return {request.fac_id, request.command_ref, ErrStatus::INVALID_COMMAND_REQUEST_NUMBER};
|
||||
}
|
||||
virtual MF_REQUEST_confirm request(const MF_REQUEST_request& request) {
|
||||
return {request.fac_id, request.command_ref, ErrStatus::INVALID_COMMAND_REQUEST_NUMBER, {}};
|
||||
}
|
||||
};
|
||||
|
||||
bool f_param_value_in_format(F_Param_No, std::uint32_t value);
|
||||
|
||||
/** MF-SET over a sink; format checked first (Table 13), a null sink answers UNSUPPORTED. */
|
||||
MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink*, const MF_SET_request&);
|
||||
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink*, const MF_COMMAND_request&);
|
||||
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink*, const MF_REQUEST_request&);
|
||||
|
||||
} // namespace microbu_v2x::MF_SAP
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/mn_sap.hpp>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
/** MI-SAP language binding: management entity <-> access layer, DCC subset.
|
||||
*
|
||||
* - TS 102 723-3 V1.1.1 clauses 7 and 8: MI-SET.request/.confirm (Tables 5/6)
|
||||
* and MI-GET.request/.confirm (Tables 7/8) with MAC-ID, CommandRef and a
|
||||
* sequence of I-Param; clause 5.2.3: an undefined command is acknowledged
|
||||
* with ErrStatus 5 "INVALID COMMAND/REQUEST NUMBER".
|
||||
* - TS 103 175 V1.1.1 clause 8.2: the DCC I-Params of Table 5 (clauses 6.2 and
|
||||
* 6.3 DCC_CROSS_Access).
|
||||
* Binding only: the access adapter of the application may implement
|
||||
* AccessParameterProvider; the library reads channel load and transmit
|
||||
* timing from nowhere else and invents no values.
|
||||
*/
|
||||
namespace microbu_v2x::MI_SAP {
|
||||
|
||||
using MN_SAP::ErrStatus;
|
||||
|
||||
/// TS 103 175 V1.1.1 Table 5: I-Param.No for the DCC interface at the MI-SAP
|
||||
enum class I_Param_No : std::uint8_t {
|
||||
CHANNEL_NUMBER = 52, // R/W, 1 octet 1..7
|
||||
LOCAL_CBR = 53, // R, 1 octet 0..100 (CL measurement of TS 102 687)
|
||||
MESSAGE_LENGTH = 54, // R, 1 octet, granularity 1 OFDM symbol = 8 us (air time Ton)
|
||||
LAST_TRANSMIT_TIME = 55, // R, 4 octets, granularity 1 OFDM symbol = 8 us
|
||||
IDLE_TIME = 56, // R/W, 2 octets in ms (Toff)
|
||||
TX_POWER_LEVEL_LIMIT = 57, // R/W, 1 octet, bits 0..4 EIRP 0..31 dBm, bits 5..7 reserved
|
||||
};
|
||||
struct I_Param { I_Param_No no; std::uint32_t value; };
|
||||
struct I_Error { I_Param_No i_param_no; ErrStatus err_status; };
|
||||
|
||||
/// TS 102 723-3 Table 7 / TS 103 175 Table 1: MI-GET.request (MAC-ID structure of TS 102 723-1 reduced to an id)
|
||||
struct MI_GET_request { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param_No> i_param_no; };
|
||||
/// TS 102 723-3 Table 8 / TS 103 175 Table 2: MI-GET.confirm
|
||||
struct MI_GET_confirm { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param> i_param; std::vector<I_Error> errors; };
|
||||
/// TS 102 723-3 Table 5 / TS 103 175 Table 3: MI-SET.request
|
||||
struct MI_SET_request { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param> i_param; };
|
||||
/// TS 102 723-3 Table 6 / TS 103 175 Table 4: MI-SET.confirm (Errors optional)
|
||||
struct MI_SET_confirm { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Error> errors; };
|
||||
|
||||
class AccessParameterProvider {
|
||||
public:
|
||||
virtual ~AccessParameterProvider() = default;
|
||||
virtual ErrStatus get(I_Param_No, std::uint32_t& value) = 0;
|
||||
virtual ErrStatus set(I_Param_No, std::uint32_t value) = 0;
|
||||
};
|
||||
|
||||
bool i_param_value_in_format(I_Param_No, std::uint32_t value);
|
||||
bool i_param_writable(I_Param_No);
|
||||
|
||||
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider*, const MI_GET_request&);
|
||||
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider*, const MI_SET_request&);
|
||||
|
||||
} // namespace microbu_v2x::MI_SAP
|
||||
@@ -0,0 +1,101 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/stack.hpp>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/position_fix.hpp>
|
||||
#include <vanetza/geonet/address.hpp>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
/** MN-SAP language binding: management entity <-> networking & transport layer.
|
||||
*
|
||||
* - TS 102 723-4 V1.1.1 clause 5: the MN-SAP provides MN-COMMAND and MN-REQUEST
|
||||
* whose primitives are specified in TS 102 723-1 (not reproduced here; the
|
||||
* generic envelope is the one of TS 102 723-3 Tables 1 to 4: id, CommandRef,
|
||||
* command/request number and value, ErrStatus).
|
||||
* - TS 103 836-4-1 V2.2.1 Annex K: CORE_MMT.request/.response carry time, the
|
||||
* local position vector, the GeoNetworking address and the TC mapping from
|
||||
* the N&T management entity to the GN core; EN 302 890-2 V2.1.1 clause
|
||||
* 5.5.2 names the PoTi minimum data set (timestamp, latitude, longitude,
|
||||
* horizontal confidence) a networking function receives.
|
||||
* - TS 103 175 V1.1.1 clause 8.3: MN-GET/MN-SET for the DCC N-Params of
|
||||
* Table 10, served by the access/DCC adapter of the application.
|
||||
* The management entity may run in the same task or elsewhere; the library
|
||||
* only applies what it receives and forwards what it cannot answer itself.
|
||||
*/
|
||||
namespace microbu_v2x::MN_SAP {
|
||||
|
||||
/// TS 103 836-4-1 V2.2.1 clause K.2: CORE_MMT.request Request cause
|
||||
enum class RequestCause : std::uint8_t { TIME, POSITION_VECTOR, GN_ADDRESS_INITIAL, GN_ADDRESS_DAD, TC_MAPPING };
|
||||
struct CORE_MMT_request { RequestCause request_cause; };
|
||||
|
||||
/// Clause K.3: CORE_MMT.response, all parameters optional, at least one present
|
||||
struct CORE_MMT_response {
|
||||
std::optional<vanetza::Clock::time_point> time; // reference time for freshness of received packets
|
||||
std::optional<vanetza::PositionFix> local_position_vector; // position, speed, heading, timestamp, accuracy
|
||||
std::optional<vanetza::geonet::Address> geonetworking_address;
|
||||
std::optional<std::vector<std::uint8_t>> tc_mapping; // Annex G traffic class parameters (opaque here)
|
||||
};
|
||||
|
||||
/** Apply a CORE_MMT.response to the GN core. Time -> Stack::advance, position ->
|
||||
* Stack::update_position. The GeoNetworking address is accepted only with
|
||||
* itsGnLocalAddrConfMethod == Managed (clause 10.2.1.3.3: the GN core updates the
|
||||
* MID with an unsolicited CORE_MMT.response); with Auto (10.2.1.2: the address is
|
||||
* not changed) or Anonymous (10.2.1.4: the security entity owns the identifier) it
|
||||
* is refused with Result::unsupported. TC mapping is refused as unsupported: the
|
||||
* port uses the fixed TS 102 687 profile-to-access-category mapping. An empty
|
||||
* response is Result::invalid_argument; the first failing parameter stops. */
|
||||
Result CORE_MMT_response_apply(Stack&, const CORE_MMT_response&);
|
||||
|
||||
/// TS 102 723-3 V1.1.1 Table 2 ErrStatus is "specified in TS 102 723-1"; that text is not
|
||||
/// available to this library, so only the values named in TS 102 723-3 clause 5.2.3
|
||||
/// (5 = INVALID COMMAND/REQUEST NUMBER) and this library's outcomes are enumerated.
|
||||
enum class ErrStatus : std::uint8_t {
|
||||
SUCCESS = 0,
|
||||
INVALID_COMMAND_REQUEST_NUMBER = 5,
|
||||
UNSUPPORTED = 250, // library: no provider for this parameter
|
||||
READ_ONLY = 251, // library: TS 103 175 Table 10 access R
|
||||
INVALID_VALUE = 252, // library: outside the Table 10 format
|
||||
FAILED = 253 // library: provider reported a failure
|
||||
};
|
||||
|
||||
/// TS 103 175 V1.1.1 Table 10: N-Param.No for the DCC interface at the MN-SAP
|
||||
enum class N_Param_No : std::uint8_t {
|
||||
GLOBAL_CBR = 0, // R, 1 octet 0..100 (TS 102 636-4-2 global CBR of the selected channel)
|
||||
CHANNEL_NUMBER = 1, // R/W, 1 octet 1..7 (selects the channel for consecutive reads/writes)
|
||||
LOCAL_CBR = 2, // R, 1 octet 0..100 (from the MI-SAP for the selected channel)
|
||||
AVAILABLE_RESOURCE = 3, // R, 2 octets, reciprocal value of CBRa
|
||||
LAST_TRANSMIT_TIME = 4, // R, 4 octets, granularity 1 OFDM symbol = 8 us
|
||||
IDLE_TIME = 5, // R/W, 2 octets in ms (Toff per radio channel)
|
||||
TX_POWER_LEVEL_LIMIT = 6, // R/W, 1 octet, bits 0..4 EIRP 0..31 dBm, bits 5..7 reserved
|
||||
};
|
||||
struct N_Param { N_Param_No no; std::uint32_t value; };
|
||||
struct N_Error { N_Param_No n_param_no; ErrStatus err_status; };
|
||||
|
||||
/// Table 6: MN-GET.request
|
||||
struct MN_GET_request { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param_No> n_param_no; };
|
||||
/// Table 7: MN-GET.confirm
|
||||
struct MN_GET_confirm { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param> n_param; std::vector<N_Error> errors; };
|
||||
/// Table 8: MN-SET.request
|
||||
struct MN_SET_request { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param> n_param; };
|
||||
/// Table 9: MN-SET.confirm (Errors optional)
|
||||
struct MN_SET_confirm { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Error> errors; };
|
||||
|
||||
/** Implemented by the access/DCC adapter of the application: the only source of
|
||||
* channel load, transmit times and power limits. The stack never invents these. */
|
||||
class NetworkParameterProvider {
|
||||
public:
|
||||
virtual ~NetworkParameterProvider() = default;
|
||||
virtual ErrStatus get(N_Param_No, std::uint32_t& value) = 0;
|
||||
virtual ErrStatus set(N_Param_No, std::uint32_t value) = 0;
|
||||
};
|
||||
|
||||
/// Format limits of Table 10; a value outside is INVALID_VALUE before the provider sees it
|
||||
bool n_param_value_in_format(N_Param_No, std::uint32_t value);
|
||||
bool n_param_writable(N_Param_No);
|
||||
|
||||
/** MN-GET/MN-SET over a provider; a null provider answers UNSUPPORTED for every parameter. */
|
||||
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider*, const MN_GET_request&);
|
||||
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider*, const MN_SET_request&);
|
||||
|
||||
} // namespace microbu_v2x::MN_SAP
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/stack.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace microbu_v2x::NF_SAP {
|
||||
|
||||
enum class SecurityProfile { UNSECURED, SECURED };
|
||||
|
||||
/** BTP-DATA.request language binding.
|
||||
* TS 102 723-11 V2.0.0 clause 5 incorporates V1.1.1; the complete BTP
|
||||
* parameter contract is TS 103 836-5-1 V2.1.1 Annex A.2.
|
||||
* '-' and '.' in primitive names become '_' in C++ identifiers.
|
||||
* Parameters retain the extracted snake_case names. length counts octets;
|
||||
* gn_maximum_packet_lifetime uses the GN lifetime value, not an unlabelled int.
|
||||
*/
|
||||
struct BTP_DATA_request {
|
||||
vanetza::ByteBuffer fl_sdu;
|
||||
std::size_t length = 0;
|
||||
BtpType btp_type = BtpType::b;
|
||||
std::uint16_t destination_port = 0;
|
||||
std::optional<std::uint16_t> destination_port_info;
|
||||
std::optional<std::uint16_t> source_port;
|
||||
vanetza::geonet::TransportType gn_packet_transport_type = vanetza::geonet::TransportType::SHB;
|
||||
vanetza::geonet::CommunicationProfile gn_communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
|
||||
std::optional<SecurityProfile> gn_security_profile;
|
||||
vanetza::geonet::TrafficClass gn_traffic_class;
|
||||
std::optional<vanetza::geonet::Lifetime> gn_maximum_packet_lifetime;
|
||||
vanetza::geonet::DestinationVariant gn_destination_address = nullptr;
|
||||
std::optional<unsigned> gn_maximum_hop_limit;
|
||||
std::optional<vanetza::geonet::DataRequest::Repetition> gn_repetition;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
// SN-ENCAP context_information (TS 102 723-8 V1.1.1 Table 24), forwarded by GN
|
||||
// as the TRANSP_CORE.request Security context information (TS 103 836-4-1 Annex J.2)
|
||||
vanetza::ByteBuffer context_information;
|
||||
};
|
||||
|
||||
/** BTP-DATA.indication, TS 103 836-5-1 V2.1.1 Annex A.3.
|
||||
* received_fl_sdu is the facilities payload; gn preserves the complete
|
||||
* router indication, including source position and security report metadata.
|
||||
*/
|
||||
struct BTP_DATA_indication {
|
||||
vanetza::ByteBuffer received_fl_sdu;
|
||||
std::size_t length;
|
||||
BtpType btp_type;
|
||||
std::uint16_t destination_port;
|
||||
std::optional<std::uint16_t> destination_port_info;
|
||||
std::optional<std::uint16_t> source_port;
|
||||
vanetza::geonet::DataIndication gn;
|
||||
std::optional<vanetza::ByteBuffer> certificate_id;
|
||||
};
|
||||
|
||||
inline BTP_DATA_indication BTP_DATA_indication_from(BtpIndication indication) {
|
||||
const auto length = indication.data.size();
|
||||
return {std::move(indication.data), length, indication.type,
|
||||
indication.destination_port, indication.destination_port_info,
|
||||
indication.source_port, std::move(indication.gn),
|
||||
std::move(indication.certificate_id)};
|
||||
}
|
||||
|
||||
inline Result BTP_DATA_request_submit(Stack& stack, BTP_DATA_request primitive) {
|
||||
if (primitive.length != primitive.fl_sdu.size()) return Result::invalid_argument;
|
||||
if (primitive.gn_security_profile) {
|
||||
if (*primitive.gn_security_profile != SecurityProfile::SECURED &&
|
||||
*primitive.gn_security_profile != SecurityProfile::UNSECURED)
|
||||
return Result::invalid_argument;
|
||||
const bool secured = *primitive.gn_security_profile == SecurityProfile::SECURED;
|
||||
// A per-request profile cannot silently change station security policy.
|
||||
if (secured != stack.config().mib.itsGnSecurity) return Result::unsupported;
|
||||
}
|
||||
BtpRequest request;
|
||||
request.type = primitive.btp_type;
|
||||
request.source_port = primitive.source_port;
|
||||
request.destination_port = primitive.destination_port;
|
||||
request.destination_port_info = primitive.destination_port_info;
|
||||
request.transport = primitive.gn_packet_transport_type;
|
||||
request.communication_profile = primitive.gn_communication_profile;
|
||||
request.traffic_class = primitive.gn_traffic_class;
|
||||
request.maximum_lifetime = primitive.gn_maximum_packet_lifetime;
|
||||
request.destination = primitive.gn_destination_address;
|
||||
request.maximum_hop_limit = primitive.gn_maximum_hop_limit;
|
||||
request.repetition = primitive.gn_repetition;
|
||||
request.its_aid = primitive.its_aid;
|
||||
request.permissions = std::move(primitive.permissions);
|
||||
request.security_context = std::move(primitive.context_information);
|
||||
request.data = std::move(primitive.fl_sdu);
|
||||
return stack.request(std::move(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/credentials.hpp>
|
||||
#include <string>
|
||||
|
||||
/** CredentialStore on ESP-IDF non-volatile storage (the nvs_flash component).
|
||||
*
|
||||
* The stored credentials (credentials.hpp: certificates and KeyIds, no private
|
||||
* keys) as one NVS blob under a namespace and key of the application's choosing.
|
||||
* The application initialises NVS itself (nvs_flash_init or nvs_flash_secure_init)
|
||||
* before using the store. Built with
|
||||
* CONFIG_MICROBU_V2X_NVS_CREDENTIALS (default on with the security entity).
|
||||
*/
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
class NvsCredentialStore final : public CredentialStore {
|
||||
public:
|
||||
/// namespace_name up to 15 characters, key up to 15 characters (NVS limits)
|
||||
explicit NvsCredentialStore(std::string namespace_name = "microbu_v2x", std::string key = "credentials") :
|
||||
namespace_(std::move(namespace_name)), key_(std::move(key)) {}
|
||||
Result save(const StoredCredentials&) override;
|
||||
Result load(StoredCredentials&) override;
|
||||
Result erase() override;
|
||||
private:
|
||||
std::string namespace_;
|
||||
std::string key_;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,293 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/hash_algorithm.hpp>
|
||||
#include <vanetza/security/hashed_id.hpp>
|
||||
#include <vanetza/security/private_key.hpp>
|
||||
#include <vanetza/security/public_key.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
/** TS 102 941 V2.2.1 enrolment and authorization request/response core.
|
||||
*
|
||||
* Clause 6.2.3.2 (EnrolmentRequest/Response) and clause 6.2.3.3
|
||||
* (AuthorizationRequest/Response with proof of possession), message formats
|
||||
* of Annex A.2, signed structures per TS 103 097 V2.2.1 clause 5.2 with
|
||||
* psid = secured certificate request (TS 102 965 V2.4.1 Table A.1, 623),
|
||||
* encryption per TS 103 097 clause 5.3: ECIES (IEEE Std 1609.2 clause 5.3.5,
|
||||
* KDF2 of IEEE Std 1363a, HMAC-SHA256 tag truncated to 128 bit, key
|
||||
* derivation parameter = SHA-256 of the recipient certificate) and
|
||||
* AES-128-CCM (IEEE Std 1609.2 clause 5.3.8: 12-octet nonce, 16-octet tag
|
||||
* appended to the ciphertext).
|
||||
*
|
||||
* The library builds and parses the messages only. Transport to the EA/AA
|
||||
* (TS 102 941 clause 6.1 reference points S3/S4, HTTP in practice) and the
|
||||
* retrieval of CTL and CRL from a distribution centre (clause 6.3.5, Annex D:
|
||||
* GET <dc>/getctl/<HashedId8>, GET <dc>/getcrl/<HashedId8>) are supplied by the
|
||||
* application; the lists themselves are built, verified and read here (clause
|
||||
* 6.3.2 to 6.3.6, formats of clause A.2.7 as compiled from the TS 102 941
|
||||
* V1.3.1 module, unchanged for these types in V2.2.1); butterfly keys (clause
|
||||
* 6.2.3.5) are not implemented.
|
||||
*/
|
||||
namespace microbu_v2x::pki {
|
||||
|
||||
using vanetza::ByteBuffer;
|
||||
using vanetza::security::HashAlgorithm;
|
||||
using vanetza::security::HashedId8;
|
||||
using vanetza::security::KeyType;
|
||||
using vanetza::security::PrivateKey;
|
||||
using vanetza::security::PublicKey;
|
||||
using vanetza::security::v3::Certificate;
|
||||
|
||||
/// A verification or encryption key pair (IEEE Std 1609.2 PublicVerificationKey /
|
||||
/// BasePublicEncryptionKey, TS 103 097 V2.2.1 clause 6) outside a security module.
|
||||
using KeyPair = security::KeyPair;
|
||||
|
||||
/// ECDSA signature over a digest with a key the caller holds (IEEE Std 1609.2 clause 5.3.1); throws on failure.
|
||||
using Signer = std::function<vanetza::security::Signature(const ByteBuffer& digest)>;
|
||||
/// a key of the station's security module (the station's TS 102 941 client)
|
||||
Signer module_signer(security::SecurityModule&, security::KeyId);
|
||||
/// a private key at hand (authorities in the issuing tools, tests)
|
||||
Signer key_signer(vanetza::security::Backend&, PrivateKey);
|
||||
|
||||
/// The public key a request names and the signature with its private key.
|
||||
struct SigningKey {
|
||||
PublicKey pub; // uncompressed
|
||||
Signer sign;
|
||||
};
|
||||
/// a key pair at hand (tests and tools that act as a station)
|
||||
SigningKey signing_key(vanetza::security::Backend&, const KeyPair&);
|
||||
|
||||
/** Primitives beyond vanetza::security::Backend that ECIES and AES-CCM need.
|
||||
* Implemented on OpenSSL (host) and the PSA Crypto API (device). generate_key()
|
||||
* (KeyGenerator) gives a fresh key pair on the given curve (NIST P-256 or
|
||||
* brainpoolP256r1 for ECIES). */
|
||||
class EciesBackend : public security::KeyGenerator {
|
||||
public:
|
||||
/// x coordinate of the ECDH shared point (IEEE 1609.2 5.3.5: the shared secret value)
|
||||
virtual std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) = 0;
|
||||
/// HMAC-SHA256 (FIPS PUB 198-1), full 32-octet tag
|
||||
virtual ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) = 0;
|
||||
/// cryptographically strong random octets
|
||||
virtual ByteBuffer random(std::size_t octets) = 0;
|
||||
/// AES-128-CCM, 12-octet nonce, no associated data; output = ciphertext || 16-octet tag
|
||||
virtual bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) = 0;
|
||||
virtual bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) = 0;
|
||||
};
|
||||
|
||||
/// IEEE 1609.2 clause 6.3.36 EciesP256EncryptedKey: ephemeral point v, wrapped key c, tag t
|
||||
struct EncryptedKey {
|
||||
PublicKey v;
|
||||
std::array<std::uint8_t, 16> c;
|
||||
std::array<std::uint8_t, 16> t;
|
||||
};
|
||||
|
||||
/// KDF2 (IEEE 1363a-2004 clause 13.2 with SHA-256): counter starts at 1, big-endian
|
||||
ByteBuffer kdf2_sha256(vanetza::security::Backend&, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length);
|
||||
|
||||
/// ECIES encryption of a 16-octet AES key for a recipient public key; p1 = key derivation parameter
|
||||
std::optional<EncryptedKey> ecies_encrypt_key(vanetza::security::Backend&, EciesBackend&, const PublicKey& recipient,
|
||||
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key);
|
||||
/// ECIES decryption with the recipient private key; none when the tag does not verify
|
||||
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(vanetza::security::Backend&, EciesBackend&,
|
||||
const PrivateKey& recipient, const ByteBuffer& p1,
|
||||
const EncryptedKey&);
|
||||
|
||||
/** State kept from a request for reading its response: the AES key (the response is
|
||||
* encrypted with it, referenced by pskRecipInfo) and the request hash the response
|
||||
* must echo (left-most 16 octets of SHA-256 of the encrypted request). */
|
||||
inline void erase_secret(std::uint8_t* data, std::size_t length) {
|
||||
volatile std::uint8_t* target = data;
|
||||
while (length--) *target++ = 0;
|
||||
}
|
||||
|
||||
struct RequestContext {
|
||||
// TS 103 601 clause 5.1.2: erase the retained session key on termination.
|
||||
void clear() {
|
||||
erase_secret(aes_key.data(), aes_key.size());
|
||||
request_hash.fill(0);
|
||||
}
|
||||
~RequestContext() { clear(); }
|
||||
std::array<std::uint8_t, 16> aes_key {};
|
||||
std::array<std::uint8_t, 16> request_hash {};
|
||||
};
|
||||
|
||||
/// requested appPermissions (IEEE Std 1609.2 SequenceOfPsidSsp: ITS-AID and opaque SSP),
|
||||
/// TS 102 941 V2.2.1 clause 6.2.3.2/6.2.3.3 request parameters
|
||||
using Permissions = std::vector<std::pair<vanetza::ItsAid, ByteBuffer>>;
|
||||
|
||||
/// TS 102 941 clauses 6.2.3.2.2/6.2.3.3.2: validate an issued credential before installation.
|
||||
/// Check its issuer signature, profile, interval, granted permissions and that its verification key is the
|
||||
/// requested one.
|
||||
bool validate_issued_certificate(vanetza::security::Backend&, const Certificate&, const Certificate& issuer,
|
||||
const PublicKey& requested_key, vanetza::Clock::time_point,
|
||||
const Permissions&, bool enrolment);
|
||||
|
||||
/// Clause 6.2.3.2.1 inputs
|
||||
struct EnrolmentRequestParameters {
|
||||
ByteBuffer its_id; // canonical identifier (initial) or HashedId8 of the current EC (re-enrolment)
|
||||
SigningKey verification_key; // new key; its signature is the proof of possession
|
||||
Permissions app_permissions; // requestedSubjectAttributes.appPermissions
|
||||
Signer outer_signer; // canonical key (initial) or current EC key
|
||||
const Certificate* current_ec = nullptr; // set for re-enrolment: outer signer = digest of the EC
|
||||
HashAlgorithm hash = HashAlgorithm::SHA256;
|
||||
};
|
||||
|
||||
/** Build the EtsiTs103097Data-Encrypted EnrolmentRequest for the EA whose certificate
|
||||
* carries the encryption key. Result::invalid_argument for missing keys or an EA
|
||||
* certificate without encryptionKey, security_unavailable on backend failure. */
|
||||
Result build_enrolment_request(vanetza::security::Backend&, EciesBackend&, vanetza::Clock::time_point now,
|
||||
const EnrolmentRequestParameters&, const Certificate& ea, ByteBuffer& encoded,
|
||||
RequestContext&);
|
||||
|
||||
/// Clause 6.2.3.2.2 InnerEcResponse
|
||||
struct EnrolmentResponse {
|
||||
std::uint8_t response_code = 0; // EnrolmentResponseCode, 0 = ok
|
||||
std::optional<Certificate> certificate;
|
||||
};
|
||||
|
||||
/** Decrypt with the request context (pskRecipInfo must match), verify the EA signature
|
||||
* (signer digest = HashedId8 of ea, psid 623), check the requestHash, decode. Result::rejected
|
||||
* when any check fails; the response is never trusted on decoding alone. */
|
||||
Result parse_enrolment_response(vanetza::security::Backend&, EciesBackend&, const RequestContext&, const Certificate& ea,
|
||||
const ByteBuffer& encoded, EnrolmentResponse&);
|
||||
|
||||
/// Clause 6.2.3.3.1 inputs
|
||||
struct AuthorizationRequestParameters {
|
||||
SigningKey verification_key; // new AT key
|
||||
std::optional<PublicKey> encryption_key; // optional AT encryption key
|
||||
Permissions app_permissions; // shall be present
|
||||
std::optional<std::pair<vanetza::Clock::time_point, std::uint16_t>> validity_period; // start, hours
|
||||
const Certificate* ec = nullptr; // enrolment credential signing SharedAtRequest
|
||||
Signer ec_signer; // with the EC's key
|
||||
bool privacy = true; // [Itss_WithPrivacy]: EC signature encrypted for the EA
|
||||
bool include_pop = true; // AuthorizationRequestMessageWithPop
|
||||
HashAlgorithm hash = HashAlgorithm::SHA256;
|
||||
};
|
||||
|
||||
Result build_authorization_request(vanetza::security::Backend&, EciesBackend&, vanetza::Clock::time_point now,
|
||||
const AuthorizationRequestParameters&, const Certificate& ea, const Certificate& aa,
|
||||
ByteBuffer& encoded, RequestContext&);
|
||||
|
||||
/// Clause 6.2.3.3.2 InnerAtResponse
|
||||
struct AuthorizationResponse {
|
||||
std::uint8_t response_code = 0; // AuthorizationResponseCode, 0 = ok
|
||||
std::optional<Certificate> certificate;
|
||||
};
|
||||
|
||||
Result parse_authorization_response(vanetza::security::Backend&, EciesBackend&, const RequestContext&, const Certificate& aa,
|
||||
const ByteBuffer& encoded, AuthorizationResponse&);
|
||||
|
||||
// ---- Building blocks shared with tests and authority-side tooling ---------------------
|
||||
|
||||
/// EtsiTs103097Data-Signed over a payload: signer self (signer_cert null) or digest of signer_cert
|
||||
std::optional<ByteBuffer> sign_data(vanetza::security::Backend&, vanetza::Clock::time_point now, HashAlgorithm,
|
||||
const ByteBuffer& payload, const Signer&, const Certificate* signer_cert);
|
||||
/// EtsiTs103097Data-SignedExternalPayload: extDataHash = SHA-256 of external_payload
|
||||
std::optional<ByteBuffer> sign_external(vanetza::security::Backend&, vanetza::Clock::time_point now,
|
||||
const ByteBuffer& external_payload, const Signer&,
|
||||
const Certificate& signer_cert);
|
||||
/// EtsiTs103097Data-Encrypted for one certificate recipient; aes_key/nonce generated, key returned
|
||||
std::optional<ByteBuffer> encrypt_for(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
|
||||
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key);
|
||||
/// EtsiTs103097Data-Encrypted with pskRecipInfo for a known symmetric key
|
||||
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend&, const std::array<std::uint8_t, 16>& aes_key, const ByteBuffer& plaintext);
|
||||
/// Decrypt an EtsiTs103097Data-Encrypted addressed to a certificate (certRecipInfo) with its private encryption key
|
||||
std::optional<ByteBuffer> decrypt_as_recipient(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
|
||||
const PrivateKey& encryption_key, const ByteBuffer& encoded,
|
||||
std::array<std::uint8_t, 16>* aes_key = nullptr);
|
||||
/// Decrypt an EtsiTs103097Data-Encrypted whose pskRecipInfo matches aes_key
|
||||
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend&, const std::array<std::uint8_t, 16>& aes_key, const ByteBuffer& encoded);
|
||||
/// Verify an EtsiTs103097Data-Signed: self-signed with public_key, or by signer_cert when given; returns the payload
|
||||
std::optional<ByteBuffer> verify_signed(vanetza::security::Backend&, const ByteBuffer& encoded, const PublicKey* self_key,
|
||||
const Certificate* signer_cert, vanetza::ItsAid expected_psid);
|
||||
|
||||
// ---- TS 102 941 V2.2.1 clause 6.3: trust list and revocation list of a root CA ----------
|
||||
//
|
||||
// RcaCertificateTrustListMessage (clause 6.3.2, 6.3.4, A.2.7): EtsiTs103097Data-Signed over an
|
||||
// EtsiTs102941Data{certificateTrustListRca ToBeSignedRcaCtl}, signed with the RCA's key, the
|
||||
// signer carrying the RCA certificate, psid = CTL service (TS 102 965 Table A.1, 624), the RCA
|
||||
// certificate holding the CTL appPermissions (TS 102 941 Table B.3: 0138 for a root CTL).
|
||||
// CertificateRevocationListMessage (clause 6.3.3): the same over
|
||||
// EtsiTs102941Data{certificateRevocationList ToBeSignedCrl}, psid = CRL service (622).
|
||||
// Clause 6.3.6: an ITS-S accepts either only when it verifies as signed by its RCA; it then
|
||||
// takes the EA/AA entries as trusted issuers and the CRL entries as revoked.
|
||||
|
||||
using Time32 = std::uint32_t; // IEEE Std 1609.2 Time32, seconds since 2004-01-01 00:00:00 TAI
|
||||
|
||||
struct TrustListEntries {
|
||||
struct Authority { ByteBuffer certificate; std::string access_point; std::string its_access_point {}; }; // EaEntry / AaEntry
|
||||
struct DistributionCentre { std::string url; std::vector<HashedId8> certificates; }; // DcEntry
|
||||
std::vector<Authority> ea, aa;
|
||||
std::vector<DistributionCentre> dc;
|
||||
};
|
||||
|
||||
/// FullCtl (isFullCtl true, ctlCommands add only) of an RCA, version 1; ctl_sequence 0..255
|
||||
std::optional<ByteBuffer> build_rca_ctl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
||||
const PrivateKey& rca_key, const TrustListEntries&, Time32 next_update,
|
||||
std::uint8_t ctl_sequence);
|
||||
// TS 102 941 clauses 6.3.2 and 6.3.4: one full and delta pair per update.
|
||||
struct RcaTrustListUpdate { ByteBuffer full, delta; std::uint8_t sequence = 0; };
|
||||
std::optional<RcaTrustListUpdate> build_rca_ctl_update(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||
const Certificate& rca, const PrivateKey&, const ByteBuffer& previous_full,
|
||||
const TrustListEntries&, Time32 next_update);
|
||||
|
||||
/// CRL of an RCA, version 1
|
||||
std::optional<ByteBuffer> build_crl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
||||
const PrivateKey& rca_key, const std::vector<HashedId8>& revoked, Time32 this_update,
|
||||
Time32 next_update);
|
||||
|
||||
struct RcaTrustList {
|
||||
std::uint8_t sequence = 0;
|
||||
Time32 next_update = 0;
|
||||
bool full = true;
|
||||
std::vector<Certificate> ea, aa; // added entries (issuer of each: the RCA, checked)
|
||||
std::vector<TrustListEntries::DistributionCentre> dc;
|
||||
std::vector<HashedId8> deleted; // DeltaCtl delete commands (certificates)
|
||||
std::vector<std::string> deleted_dc;
|
||||
};
|
||||
/// Clause 6.3.6: the message verifies as signed by rca (signer certificate equal to rca,
|
||||
/// psid 624, rca permitted for the CTL service), decodes as an RCA CTL of version 1 and every
|
||||
/// EA/AA entry is issued by rca with a verifying signature (IEEE Std 1609.2 clause 5.3.1).
|
||||
std::optional<RcaTrustList> parse_rca_ctl(vanetza::security::Backend&, const ByteBuffer& message, const Certificate& rca);
|
||||
|
||||
// TS 102 941 clauses 6.3.1 and 6.3.4. Full ECTLs authenticate root and successor TLM certificates.
|
||||
struct TlmTrustList {
|
||||
std::uint8_t sequence = 0;
|
||||
Time32 next_update = 0;
|
||||
bool full = true;
|
||||
std::vector<Certificate> roots, tlms;
|
||||
};
|
||||
std::optional<TlmTrustList> parse_tlm_ctl(vanetza::security::Backend&, const ByteBuffer&, const Certificate& tlm);
|
||||
std::optional<ByteBuffer> build_tlm_ctl(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||
const Certificate& tlm, const PrivateKey&, const std::vector<Certificate>& roots,
|
||||
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence);
|
||||
|
||||
struct RevocationList {
|
||||
Time32 this_update = 0, next_update = 0;
|
||||
std::vector<HashedId8> revoked;
|
||||
};
|
||||
/// the same for a CRL (psid 622, rca permitted for the CRL service)
|
||||
std::optional<RevocationList> parse_crl(vanetza::security::Backend&, const ByteBuffer& message, const Certificate& rca);
|
||||
|
||||
/// Clause 6.3.6: the EA/AA entries become trusted issuers (TrustConfiguration::add_authority);
|
||||
/// returns the number added (entries already known are not counted)
|
||||
std::size_t apply(const RcaTrustList&, microbu_v2x::security::TrustConfiguration&);
|
||||
/// Clause 6.3.6: the CRL entries become revocations by the RCA (TrustConfiguration::revoke),
|
||||
/// replacing the RCA's earlier list; returns the number of entries
|
||||
std::size_t apply(const RevocationList&, const Certificate& rca, microbu_v2x::security::TrustConfiguration&);
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
|
||||
// ETSI TS 103 601 V2.1.1 clauses 5.1.2 and 5.1.4.
|
||||
// Times use a monotonic millisecond clock. N1 includes the initial attempt.
|
||||
struct RetryPolicy {
|
||||
std::uint64_t interval_ms = 60000;
|
||||
std::uint64_t lifetime_ms = 190000;
|
||||
std::uint32_t attempts = 3;
|
||||
std::uint64_t minimum_response_ms = 55000;
|
||||
std::uint64_t authority_context_ms = 3600000;
|
||||
|
||||
bool valid() const {
|
||||
return attempts && interval_ms >= minimum_response_ms && interval_ms && lifetime_ms &&
|
||||
(lifetime_ms - 1) / attempts >= interval_ms && authority_context_ms >= lifetime_ms;
|
||||
}
|
||||
};
|
||||
|
||||
class RetrySchedule {
|
||||
public:
|
||||
bool begin(std::uint64_t now, RetryPolicy policy = {}) {
|
||||
stop();
|
||||
if (!policy.valid()) return false;
|
||||
policy_ = policy;
|
||||
start_ = last_ = now;
|
||||
attempts_ = 1;
|
||||
active_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool poll(std::uint64_t now) {
|
||||
if (active_ && (now < last_ || now - start_ >= policy_.lifetime_ms ||
|
||||
(attempts_ == policy_.attempts && now - last_ >= policy_.interval_ms))) stop();
|
||||
return active_;
|
||||
}
|
||||
|
||||
bool repeat(std::uint64_t now) {
|
||||
if (!poll(now) || now - last_ < policy_.interval_ms || attempts_ >= policy_.attempts) return false;
|
||||
last_ = now;
|
||||
++attempts_;
|
||||
return true;
|
||||
}
|
||||
|
||||
void stop() { active_ = false; }
|
||||
bool active() const { return active_; }
|
||||
std::uint32_t attempts() const { return attempts_; }
|
||||
|
||||
private:
|
||||
RetryPolicy policy_;
|
||||
std::uint64_t start_ = 0;
|
||||
std::uint64_t last_ = 0;
|
||||
std::uint32_t attempts_ = 0;
|
||||
bool active_ = false;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,382 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <microbu_v2x/id_change.hpp>
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/common/position_provider.hpp>
|
||||
#include <vanetza/common/runtime.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/hashed_id.hpp>
|
||||
#include <vanetza/security/security_entity.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <vanetza/security/v3/certificate_provider.hpp>
|
||||
#include <vanetza/security/v3/certificate_validator.hpp>
|
||||
#include <vanetza/security/v3/issuer_memory_lookup.hpp>
|
||||
#include <vanetza/security/v3/location_checker.hpp>
|
||||
#include <vanetza/security/v3/revocation_lookup.hpp>
|
||||
#include <vanetza/security/v3/sign_header_policy.hpp>
|
||||
#include <vanetza/security/v3/trust_store.hpp>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
/** Signing security entity for the SN-SAP.
|
||||
*
|
||||
* Standards: TS 103 097 V2.2.1 (secured message and certificate formats,
|
||||
* clause 5.2 SignedData constraints, clause 7 profiles), IEEE Std 1609.2
|
||||
* (hashing and ECDSA, clause 5.3), TS 102 940 V2.1.1 (trust model: root CA ->
|
||||
* AA -> authorization ticket, clause 6.5 identity management), TS 102 941
|
||||
* V2.2.1 (credential life cycle), TS 102 723-8 V2.0.0/V1.1.1 (SN-SAP
|
||||
* primitives), TS 103 300-3 V2.3.1 clause 6.5 (VAM signing and certificate
|
||||
* attachment). Verification of received messages (SN-DECAP) follows IEEE Std
|
||||
* 1609.2 clause 5.2 as TS 103 097 clause 5.2 requires, with the profile checks of
|
||||
* clause 7.1 and the chain checks of TS 102 940 clause 6; it is built when
|
||||
* V2X_SECURITY_VERIFY is set (default with the security feature), otherwise
|
||||
* SN-DECAP reports Configuration_Problem.
|
||||
*/
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
using vanetza::ByteBuffer;
|
||||
using vanetza::security::HashedId8;
|
||||
using vanetza::security::PrivateKey;
|
||||
using vanetza::security::v3::Certificate;
|
||||
|
||||
// IEEE Std 1609.2 Duration: a year is 31556952 seconds.
|
||||
// Bounds outside Time32 are invalid rather than wrapping into the past.
|
||||
vanetza::security::v3::StartAndEndValidity validity_bounds(const Certificate&);
|
||||
|
||||
|
||||
/** SN-ENCAP.request context_information values understood by this entity
|
||||
* (TS 102 723-8 V1.1.1 Table 24: opaque octets "used in selecting properties
|
||||
* of the underlying security protocol"; the standard leaves the content to the
|
||||
* implementation, these values are this library's definition). */
|
||||
namespace context {
|
||||
/// VAM generated for a VRU cluster: TS 103 300-3 V2.3.1 clause 6.5.3 500 ms certificate cadence
|
||||
inline const ByteBuffer vam_cluster {0x01};
|
||||
}
|
||||
|
||||
/** Authorization tickets owned by this station, each with the KeyId of its private key in the security module.
|
||||
*
|
||||
* TS 103 097 V2.2.1 clause 7.2.1 (AT profile), TS 102 940 V2.1.1 clause 6.5
|
||||
* ("multiple authorization tickets ... to be used ... over its life time").
|
||||
* Tickets come from the station's TS 102 941 client (key generated in the
|
||||
* module) or from laboratory provisioning (key imported into the module,
|
||||
* credentials.hpp). The pool never holds a private key: own_private_key() of
|
||||
* the upstream CertificateProvider contract throws, and SN-ENCAP signs through
|
||||
* SecurityModule::sign_digest with own_key().
|
||||
*/
|
||||
class CertificatePool : public vanetza::security::v3::BaseCertificateProvider {
|
||||
public:
|
||||
/// An authorization ticket (TS 103 097 V2.2.1 clause 7.2.1 profile) and the module key of its verifyKeyIndicator.
|
||||
struct Ticket {
|
||||
Certificate certificate;
|
||||
KeyId key;
|
||||
HashedId8 digest; // HashedId8 per TS 103 097 clause 6 / IEEE 1609.2 clause 6.4.3
|
||||
};
|
||||
|
||||
explicit CertificatePool(SecurityModule&);
|
||||
|
||||
/** Add a ticket. Fails closed (Result::invalid_argument) when the certificate
|
||||
* does not decode, is not an authorization ticket (clause 7.2.1: issuer
|
||||
* sha256AndDigest/sha384AndDigest, appPermissions present, no
|
||||
* certIssuePermissions), or the module holds no key with the certificate's
|
||||
* verification key. Duplicate digests are rejected. */
|
||||
Result add(const ByteBuffer& coer_certificate, KeyId);
|
||||
Result add(Certificate, KeyId);
|
||||
|
||||
/// pool bookkeeping for the application's provisioning and persistence
|
||||
std::size_t size() const { return tickets_.size(); }
|
||||
bool empty() const { return tickets_.empty(); }
|
||||
const std::vector<Ticket>& tickets() const { return tickets_; }
|
||||
/// currently selected ticket, nullptr when the pool is empty
|
||||
const Ticket* current() const;
|
||||
/// next different ticket valid at now (round robin), nullptr when none
|
||||
const Ticket* next_valid(vanetza::Clock::time_point now) const;
|
||||
/// make the ticket with this digest current (identifier change COMMIT)
|
||||
Result select(const HashedId8&);
|
||||
/// drop tickets whose validity ended before now, never the current one; returns count
|
||||
std::size_t prune(vanetza::Clock::time_point now);
|
||||
|
||||
/// the module that holds the ticket keys
|
||||
SecurityModule& module() { return module_; }
|
||||
/// module key of the current ticket; std::logic_error when empty
|
||||
KeyId own_key() const;
|
||||
|
||||
// v3::CertificateProvider: the current ticket; std::logic_error when empty
|
||||
const Certificate& own_certificate() override;
|
||||
/// std::logic_error: private keys stay in the security module
|
||||
const PrivateKey& own_private_key() override;
|
||||
|
||||
private:
|
||||
SecurityModule& module_;
|
||||
std::vector<Ticket> tickets_;
|
||||
std::size_t current_ = 0;
|
||||
};
|
||||
|
||||
/** Trust anchors and issuing authorities supplied by the application.
|
||||
* TS 102 940 V2.1.1 clause 6.1 (root CA, AA), TS 103 097 clauses 7.2.3/7.2.4;
|
||||
* TS 102 941 V2.2.1 clause 6.3 CTL/CRL retrieval is not part of this library. */
|
||||
class TrustConfiguration {
|
||||
public:
|
||||
/// self-signed root CA certificate (clause 7.2.3) -> trust store and issuer lookup
|
||||
Result add_root(const ByteBuffer& coer_certificate);
|
||||
Result add_root(const Certificate&);
|
||||
/// AA or other subordinate CA certificate (clause 7.2.4) -> issuer lookup; a certificate
|
||||
/// already known is Result::rejected (nothing changes), a non-CA one invalid_argument
|
||||
Result add_authority(const ByteBuffer& coer_certificate);
|
||||
Result add_authority(const Certificate&);
|
||||
|
||||
const vanetza::security::v3::TrustStore& roots() const { return roots_; }
|
||||
const vanetza::security::v3::IssuerMemoryLookup& issuers() const { return issuers_; }
|
||||
/// every CA certificate added, in the order added (views into the issuer lookup, which holds the one copy)
|
||||
std::vector<const Certificate*> authorities() const;
|
||||
/// the CA certificate whose digest ends in this HashedId3 (P2P certificate distribution), or nullptr
|
||||
const Certificate* authority(const vanetza::security::HashedId3& id) const;
|
||||
|
||||
/** TS 102 941 V2.2.1 clause 6.3.3/6.3.6: a certificate the named issuer has revoked
|
||||
* (the RCA's CRL lists the CA certificates it no longer trusts). The validator walks
|
||||
* every chain link against this list (IEEE Std 1609.2 clause 5.2: a revoked
|
||||
* certificate anywhere in the chain invalidates it), so a revoked AA takes all its
|
||||
* tickets with it; the station's own tickets included (it stops signing). */
|
||||
void revoke(const HashedId8& issuer, const HashedId8& certificate);
|
||||
/// forget every revocation recorded for this issuer (a fresh CRL replaces the old one)
|
||||
void clear_revocations(const HashedId8& issuer);
|
||||
const vanetza::security::v3::RevocationLookup& revocations() const { return revocations_; }
|
||||
|
||||
private:
|
||||
vanetza::security::v3::TrustStore roots_;
|
||||
vanetza::security::v3::IssuerMemoryLookup issuers_;
|
||||
// Digests only : a decoded certificate costs about 3.5 kB of heap on the ESP32-C5, and a second copy
|
||||
// of every CA certificate here left the Wi-Fi driver without TX buffers. issuers_ holds the certificate.
|
||||
std::vector<HashedId8> authority_digests_;
|
||||
vanetza::security::v3::RevocationMemoryLookup revocations_;
|
||||
};
|
||||
|
||||
/** IEEE Std 1609.2 clause 5.3.1 certificate signature: Hash(Hash(toBeSigned) || Hash(issuer
|
||||
* certificate)) with the hash algorithm of the IssuerIdentifier choice (sha256AndDigest /
|
||||
* sha384AndDigest, or the algorithm named in the self choice with the empty string as
|
||||
* issuer hash), verified with the issuer's verification key; issuer == nullptr means
|
||||
* self-signed. TS 103 097 V2.2.1 clause 6 admits NIST P-256, brainpoolP256r1 (SHA-256)
|
||||
* and brainpoolP384r1 (SHA-384). */
|
||||
bool verify_certificate_signature(vanetza::security::Backend&, const Certificate& subject, const Certificate* issuer);
|
||||
|
||||
/** IEEE Std 1609.2-2025 clause 5.1.2 permission consistency of a certificate chain, chain[0]
|
||||
* the end entity and the last element the anchor: every appPermissions entry of the end
|
||||
* entity is covered by a PsidGroupPermissions group of each ancestor whose chain-length
|
||||
* window (6.4.28) reaches down to the end entity and whose eeType admits it, the SSP
|
||||
* inside the group's range (6.4.29/6.4.30 SspRange, BitmapSspRange: a 1 bit of the mask
|
||||
* fixes the subordinate's bit; an omitted SSP needs "all"); every subordinate CA's ranges
|
||||
* nest inside its issuer's. Unknown CHOICE alternatives are critical (5.2.6): false.
|
||||
* Used by the receive-side chain validator and by the issuing tools before they write. */
|
||||
bool chain_permissions_consistent(const std::vector<const Certificate*>& chain);
|
||||
|
||||
/** IEEE Std 1609.2-2025 clause 6.4.17: no part of the subject's region may lie outside the
|
||||
* issuer's. No issuer region: true; issuer region but none on the subject: false;
|
||||
* geometric issuer regions by the upstream geometry; identifiedRegion issuer (6.4.21 to
|
||||
* 6.4.24): identifier containment for an identifiedRegion subject, the
|
||||
* permissive_identified_region policy for a geometric subject (no border database). */
|
||||
bool region_within(const Certificate& subject, const Certificate& issuer, bool permissive_identified_region);
|
||||
|
||||
/** Receive-side parameters that TS 103 097 leaves to the station. generationTime
|
||||
* plausibility: IEEE Std 1609.2 clause 5.2.3.2 lists it among the relevance checks
|
||||
* without fixing values; the defaults are a 3 s clock tolerance into the future and the
|
||||
* 5 min window the TS 103 096-2 test purposes apply to generation times (the CAM/DENM
|
||||
* services apply their own, tighter freshness rules on top). Replay: a message whose
|
||||
* (signer digest, generationTime) pair was already accepted is DUPLICATE_MESSAGE
|
||||
* (TS 102 723-8 Table 27 report). */
|
||||
struct VerificationPolicy {
|
||||
std::chrono::seconds generation_time_future_tolerance {3};
|
||||
std::chrono::seconds generation_time_max_age {300};
|
||||
std::size_t replay_window = 256; // remembered accepted (signer, time) pairs, 0 disables
|
||||
std::size_t verified_chain_cache = 64; // authorization tickets whose chain signature was verified
|
||||
std::size_t certificate_cache_limit = 32; // learned certificates kept (the cache is emptied beyond it)
|
||||
std::size_t learned_authority_limit = 8; // AA certificates learned through P2P distribution
|
||||
bool permissive_identified_region = true; // identifiedRegion without a country database: accept (see docs)
|
||||
};
|
||||
|
||||
/** TS 103 097 V2.2.1 clause 5.2 and 7.1.1 to 7.1.3 structural checks of a received
|
||||
* signed message, before any cryptography: protocolVersion 3 on both levels, hashId
|
||||
* consistent with the signature choice, generationTime present, p2pcdLearningRequest and
|
||||
* missingCrlIdentifier absent, per ITS-AID: CAM without expiryTime, generationLocation
|
||||
* and encryptionKey; DENM with generationLocation and with a certificate as signer,
|
||||
* without expiryTime and encryptionKey; signer digest or certificate (not self).
|
||||
* Returns Success when the structure is admissible, otherwise the report to give. */
|
||||
vanetza::security::VerificationReport check_profile(const vanetza::security::v3::SecuredMessage&);
|
||||
|
||||
/** Header fields and signer identifier per message profile.
|
||||
*
|
||||
* TS 103 097 V2.2.1 clause 5.2: psid and generationTime always present,
|
||||
* p2pcdLearningRequest and missingCrlIdentifier always absent.
|
||||
* - CAM (ITS-AID 36, TS 102 965 Table A.1): clause 7.1.1 - digest by default,
|
||||
* certificate once one second after its last inclusion, immediately after a
|
||||
* CAM from an unknown AT (request_certificate) or an inline P2PCD request for
|
||||
* our AT, inlineP2pcdRequest for unknown certificates, requestedCertificate
|
||||
* for known CA certificates; no other header fields.
|
||||
* - DENM (37): clause 7.1.2 - certificate always, generationLocation present.
|
||||
* - VAM (638): TS 103 300-3 V2.3.1 clause 6.5.3 - individual VAM: certificate
|
||||
* if >= 1 s since the last certificate attached to a VAM or a new CAM signer
|
||||
* was observed (report_new_cam_signer), else digest; cluster VAM (SN-ENCAP
|
||||
* context_information == context::vam_cluster): certificate if >= 500 ms,
|
||||
* else digest.
|
||||
* - other ITS-AIDs, including GN-MGMT beacons (141): clause 7.1.3 generic
|
||||
* profile, which constrains only clause 5.2; this library includes the
|
||||
* certificate once per second per ITS-AID and the digest otherwise.
|
||||
*/
|
||||
class Ts103097SignHeaderPolicy : public vanetza::security::v3::SignHeaderPolicy {
|
||||
public:
|
||||
Ts103097SignHeaderPolicy(const vanetza::Runtime&, vanetza::PositionProvider&, CertificatePool&,
|
||||
const TrustConfiguration&);
|
||||
~Ts103097SignHeaderPolicy() override;
|
||||
void prepare_header(const vanetza::security::SignRequest&, vanetza::security::v3::SecuredMessage&) override;
|
||||
void request_unrecognized_certificate(HashedId8) override;
|
||||
void request_certificate() override;
|
||||
void enqueue_p2p_request(vanetza::security::HashedId3) override;
|
||||
void discard_p2p_request(vanetza::security::HashedId3) override;
|
||||
/// TS 103 300-3 clause 6.5.3 item 2: a CAM was received from a not previously seen signer
|
||||
void report_new_cam_signer();
|
||||
/// after an identifier change the new ticket has never been announced: attach it next
|
||||
void reset_after_identifier_change();
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
/** SN-LOG-SECURITY-EVENT.request (TS 102 723-8 V1.1.1 Table 22). Events are
|
||||
* kept in a bounded log the application can drain for misbehaviour reporting. */
|
||||
struct SecurityEvent {
|
||||
enum class Type : std::uint8_t {
|
||||
TIME_CONSISTENCY_FAILED, LOCATION_CONSISTENCY_FAILED, ID_CONSISTENCY_FAILED,
|
||||
DISALLOWED_MESSAGE_CONTENT, DISALLOWED_MESSAGE_FREQUENCY, REPLAY_DETECTION_TIME,
|
||||
REPLAY_DETECTION_LOCATION, MOVEMENT_PLAUSIBILITY, APPEARANCE_PLAUSIBILITY,
|
||||
LOCATION_PLAUSIBILITY_SENSOR, LOCATION_PLAUSIBILITY_MAP, LOCATION_PLAUSIBILITY_CONTRADICTION,
|
||||
APPLICATION_SPECIFIC
|
||||
};
|
||||
struct Location { std::int32_t latitude; std::int32_t longitude; };
|
||||
struct Evidence { std::uint8_t type; ByteBuffer content; }; // event_evidence_type/content
|
||||
Type event_type;
|
||||
std::vector<HashedId8> neighbour_id_list;
|
||||
std::uint32_t event_time; // INTEGER 0..2^32-1, shall be in the past
|
||||
std::optional<Location> event_location;
|
||||
std::vector<Evidence> event_evidence_list;
|
||||
};
|
||||
|
||||
/// The steps of the signature in SN-ENCAP, reported to a SignObserver.
|
||||
enum class SignStep : std::uint8_t {
|
||||
header, ///< header fields and signer choice (Ts103097SignHeaderPolicy::prepare_header)
|
||||
ticket, ///< the current ticket is valid for signing this ITS-AID (validity, permissions, region)
|
||||
digest, ///< IEEE Std 1609.2 clause 5.3.1 hash of the to-be-signed data and the signer
|
||||
signature, ///< ECDSA signature in the security module
|
||||
};
|
||||
|
||||
/// Instrumentation of SN-ENCAP (power markers): begin() and end() bracket each SignStep in order.
|
||||
class SignObserver {
|
||||
public:
|
||||
virtual ~SignObserver() = default;
|
||||
virtual void begin(SignStep) = 0;
|
||||
virtual void end(SignStep) = 0;
|
||||
};
|
||||
|
||||
class IdentityManager;
|
||||
|
||||
/** The security entity: SN-ENCAP/SN-DECAP plus the identifier-change service.
|
||||
* Runtime, position provider, backend, pool and trust configuration are
|
||||
* owned by the application and must outlive the entity. SN-ENCAP signs with
|
||||
* the pool's security module; the backend serves hashing, verification and
|
||||
* point decompression. All calls come from the one task that also drives the
|
||||
* stack. */
|
||||
class SecurityEntity : public vanetza::security::SecurityEntity {
|
||||
public:
|
||||
SecurityEntity(vanetza::Runtime&, vanetza::PositionProvider&, vanetza::security::Backend&, CertificatePool&,
|
||||
const TrustConfiguration&);
|
||||
~SecurityEntity() override;
|
||||
|
||||
/** SN-ENCAP.request/.confirm (TS 102 723-8 V1.1.1 Tables 24/25; TS 103 836-4-1 V2.2.1
|
||||
* Table 34). Refused (SignConfirmError::No_Certificate) when the pool is empty, the current
|
||||
* ticket is not valid for the ITS-AID, or an identifier change is between PREPARE and COMMIT
|
||||
* (clause 6.3.1.3: messages with old identifiers shall be avoided). */
|
||||
vanetza::security::EncapConfirm encapsulate_packet(vanetza::security::EncapRequest&&) override;
|
||||
|
||||
/** SN-DECAP.request/.confirm (Tables 26/27). With V2X_SECURITY_VERIFY: check_profile(),
|
||||
* then IEEE Std 1609.2 clause 5.2 verification (signer lookup in the learned-certificate
|
||||
* cache or the inline certificate, authorization ticket validity, permissions for the
|
||||
* ITS-AID, chain to a trust anchor with verified certificate signatures, region, message
|
||||
* signature), generationTime plausibility and replay detection per VerificationPolicy;
|
||||
* a CAM/DENM from an unknown station or with an unknown AA drives the P2P certificate
|
||||
* distribution of TS 103 097 clause 7.1.1 through the header policy, and an AA carried
|
||||
* in requestedCertificate is learned once its signature chains to a trust anchor.
|
||||
* Without V2X_SECURITY_VERIFY: unsigned messages report UNSIGNED_MESSAGE, signed ones
|
||||
* Configuration_Problem, never success; a receiver with
|
||||
* itsGnSnDecapResultHandling = STRICT drops them either way. */
|
||||
vanetza::security::DecapConfirm decapsulate_packet(vanetza::security::DecapRequest&&) override;
|
||||
void set_verification_policy(const VerificationPolicy&);
|
||||
/// report the signing steps of SN-ENCAP to the observer (nullptr: none); it must outlive the entity
|
||||
void observe_signing(SignObserver*);
|
||||
const VerificationPolicy& verification_policy() const;
|
||||
/// authorities learned through P2P certificate distribution (requestedCertificate), verified
|
||||
const std::deque<Certificate>& learned_authorities() const;
|
||||
|
||||
/// SN-LOG-SECURITY-EVENT.request (Table 22); .confirm has no parameters (Table 23)
|
||||
void log_security_event(SecurityEvent);
|
||||
/// take all logged events, oldest first
|
||||
std::deque<SecurityEvent> drain_security_events();
|
||||
void set_security_event_capacity(std::size_t);
|
||||
|
||||
/** Outcome counters. The GN router reports GN-DATA.confirm before SN-ENCAP runs
|
||||
* (TS 103 836-4-1 clause 10.3.10.2 step 2 happens at transmission), so a refused
|
||||
* encapsulation is visible here and in the absence of a packet, not in Stack::request. */
|
||||
struct Statistics { unsigned signed_messages = 0, refused_no_ticket = 0, refused_change_pending = 0,
|
||||
refused_permission = 0, failed = 0;
|
||||
// SN-DECAP outcomes (V2X_SECURITY_VERIFY)
|
||||
unsigned verified = 0, rejected_profile = 0, rejected_signer = 0, rejected_certificate = 0,
|
||||
rejected_signature = 0, rejected_time = 0, replayed = 0, learned_authorities = 0; };
|
||||
const Statistics& statistics() const;
|
||||
|
||||
IdChangeService& id_change();
|
||||
const IdChangeService& id_change() const;
|
||||
IdentityManager& identity_manager();
|
||||
Ts103097SignHeaderPolicy& header_policy();
|
||||
vanetza::security::v3::DefaultCertificateValidator& validator();
|
||||
CertificatePool& certificates();
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
/** TS 102 723-8 V1.1.1 clause 6.3 implementation: subscriptions, the two-phase commit
|
||||
* (clause 6.3.1.3, Figures 11 to 13), locks with automatic release (clause 6.3.2,
|
||||
* Table 18) and deferred triggers (clause 6.3.3). New identifier = HashedId8 of the
|
||||
* next authorization ticket in the pool (TS 102 940 V2.1.1 clause 6.5). */
|
||||
class IdentityManager : public IdChangeService {
|
||||
public:
|
||||
IdentityManager(vanetza::Runtime&, CertificatePool&);
|
||||
~IdentityManager() override; // DEREG to every subscriber (Figure 15)
|
||||
|
||||
SubscriptionHandle subscribe(IdChangeHook, ByteBuffer subscriber_data = {}) override;
|
||||
Result unsubscribe(SubscriptionHandle) override;
|
||||
Result trigger() override;
|
||||
LockHandle lock(std::uint8_t duration_seconds) override;
|
||||
Result unlock(LockHandle) override;
|
||||
Identifier current_identifier() const override;
|
||||
bool change_pending() const override;
|
||||
|
||||
/** Time allowed for all PREPARE (or COMMIT) responses before the change is aborted
|
||||
* (or the COMMIT is closed). Not specified by TS 102 723-8; library default 500 ms. */
|
||||
void set_response_timeout(vanetza::Clock::duration);
|
||||
/// invoked after a successful COMMIT with the new identifier
|
||||
void on_committed(std::function<void(const Identifier&)>);
|
||||
|
||||
struct Statistics { unsigned committed = 0, aborted = 0, timed_out = 0, commit_failures = 0; };
|
||||
const Statistics& statistics() const;
|
||||
bool locked() const;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::shared_ptr<Impl> impl_; // responders keep a weak reference across the manager's lifetime
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <memory>
|
||||
|
||||
// The station's cryptography behind two interfaces, chosen at build time (Kconfig "Security module"):
|
||||
// SecurityModule (security_module.hpp) every private key and the signatures made with it
|
||||
// vanetza::security::Backend hashing, verification and point decompression of public data
|
||||
// The station never sees which implementation is behind either.
|
||||
namespace microbu_v2x {
|
||||
|
||||
std::unique_ptr<vanetza::security::Backend> make_security_backend();
|
||||
std::unique_ptr<security::SecurityModule> make_security_module();
|
||||
const char* security_module_name();
|
||||
|
||||
// An external adapter component implements these factories. Each must return a working implementation or throw;
|
||||
// a missing adapter never falls back to software. make_external_security_backend() is needed only when the
|
||||
// adapter takes the public operations as well (V2X HSM).
|
||||
std::unique_ptr<security::SecurityModule> make_external_security_module();
|
||||
std::unique_ptr<vanetza::security::Backend> make_external_security_backend();
|
||||
|
||||
/// NVS location of the keys of the local software module (the station's credential checkpoint copies it).
|
||||
constexpr const char* local_key_namespace = "v2x_keys";
|
||||
constexpr const char* local_key_name = "keys";
|
||||
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,125 @@
|
||||
#pragma once
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/key_type.hpp>
|
||||
#include <vanetza/security/private_key.hpp>
|
||||
#include <vanetza/security/public_key.hpp>
|
||||
#include <vanetza/security/signature.hpp>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
|
||||
/** The station's security module: the only place that holds private keys.
|
||||
*
|
||||
* Everything that the micrOBU hardware puts into its secure element (SE051 on the
|
||||
* prototype mainboard) or a later V2X HSM is behind SecurityModule: generation
|
||||
* and import of key pairs, keeping them across resets, and the ECDSA signature
|
||||
* over a digest (IEEE Std 1609.2 clause 5.3.1). Callers hold a KeyId, never a
|
||||
* private key value; the operations follow the key management and asymmetric
|
||||
* signature functions of the PSA Certified Crypto API (psa_generate_key,
|
||||
* psa_import_key, psa_export_public_key, psa_sign_hash, psa_destroy_key), which
|
||||
* a secure element integrates as an opaque key location.
|
||||
*
|
||||
* Operations on public data stay with vanetza::security::Backend on the
|
||||
* application processor: hashing, verification and point decompression.
|
||||
* Ephemeral ECIES keys and the AES-CCM session key of a TS 102 941 request
|
||||
* (pki.hpp) are short-lived and stay there too.
|
||||
*/
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
using vanetza::ByteBuffer;
|
||||
using vanetza::security::KeyType;
|
||||
using vanetza::security::PrivateKey;
|
||||
using vanetza::security::PublicKey;
|
||||
using vanetza::security::Signature;
|
||||
|
||||
/// A key held by a SecurityModule. A stored KeyId stays valid across resets until the key is destroyed.
|
||||
struct KeyId {
|
||||
std::uint32_t value = 0; // 0 is no key
|
||||
explicit operator bool() const { return value != 0; }
|
||||
friend bool operator==(KeyId a, KeyId b) { return a.value == b.value; }
|
||||
friend bool operator!=(KeyId a, KeyId b) { return a.value != b.value; }
|
||||
friend bool operator<(KeyId a, KeyId b) { return a.value < b.value; }
|
||||
};
|
||||
|
||||
/// A key pair outside a security module: an authority's key in the issuing tools, an ephemeral ECIES key, or a
|
||||
/// laboratory ticket key on its way into the module. Public key uncompressed.
|
||||
struct KeyPair {
|
||||
PrivateKey priv;
|
||||
PublicKey pub;
|
||||
};
|
||||
|
||||
class SecurityModule {
|
||||
public:
|
||||
virtual ~SecurityModule() = default;
|
||||
/// New key pair on the curve, kept in the module; throws std::runtime_error when the module cannot create it.
|
||||
virtual KeyId generate_key(KeyType) = 0;
|
||||
/// Laboratory provisioning of a key pair created outside the station (VCR1 bundle, issuing tools). None when
|
||||
/// the two halves do not belong together; throws std::runtime_error when the module cannot store the key.
|
||||
virtual std::optional<KeyId> import_key(const KeyPair&) = 0;
|
||||
/// The public half (uncompressed), none for a KeyId the module does not hold.
|
||||
virtual std::optional<PublicKey> public_key(KeyId) const = 0;
|
||||
/// ECDSA with the curve of the key over a digest of the curve's length; throws std::runtime_error for a KeyId
|
||||
/// the module does not hold or a failed operation.
|
||||
virtual Signature sign_digest(KeyId, const ByteBuffer& digest) = 0;
|
||||
/// Removes the key for good; false when the module holds no such key.
|
||||
virtual bool destroy_key(KeyId) = 0;
|
||||
};
|
||||
|
||||
/// True when both keys are the same point on the same curve, in compressed or uncompressed form.
|
||||
bool same_public_key(const PublicKey&, const PublicKey&);
|
||||
|
||||
/// Creates key pairs for SoftwareSecurityModule (the platform's random generator).
|
||||
class KeyGenerator {
|
||||
public:
|
||||
virtual ~KeyGenerator() = default;
|
||||
virtual KeyPair generate_key(KeyType) = 0;
|
||||
};
|
||||
|
||||
/// Where SoftwareSecurityModule keeps its keys between resets: one blob, written as a whole.
|
||||
class KeyStorage {
|
||||
public:
|
||||
virtual ~KeyStorage() = default;
|
||||
/// false when nothing is stored
|
||||
virtual bool load(ByteBuffer&) = 0;
|
||||
virtual bool save(const ByteBuffer&) = 0;
|
||||
};
|
||||
|
||||
class MemoryKeyStorage final : public KeyStorage {
|
||||
public:
|
||||
bool load(ByteBuffer& out) override;
|
||||
bool save(const ByteBuffer& blob) override;
|
||||
private:
|
||||
ByteBuffer blob_;
|
||||
};
|
||||
|
||||
/** SecurityModule in software on the application processor: the stand-in for the SE051 until its adapter
|
||||
* exists. Signs through a Backend and keeps the keys in a KeyStorage, whose protection at rest is the
|
||||
* platform's (NVS encryption on the ESP32-C5). Storage format: "MSM1", next KeyId (4 octets), then per key
|
||||
* [KeyId: 4][curve: 1][private scalar][public x][public y], all big-endian. */
|
||||
class SoftwareSecurityModule final : public SecurityModule {
|
||||
public:
|
||||
/// Loads the stored keys; throws std::runtime_error when the stored blob does not decode.
|
||||
SoftwareSecurityModule(vanetza::security::Backend&, KeyGenerator&, KeyStorage&);
|
||||
~SoftwareSecurityModule() override;
|
||||
SoftwareSecurityModule(const SoftwareSecurityModule&) = delete;
|
||||
SoftwareSecurityModule& operator=(const SoftwareSecurityModule&) = delete;
|
||||
|
||||
KeyId generate_key(KeyType) override;
|
||||
std::optional<KeyId> import_key(const KeyPair&) override;
|
||||
std::optional<PublicKey> public_key(KeyId) const override;
|
||||
Signature sign_digest(KeyId, const ByteBuffer& digest) override;
|
||||
bool destroy_key(KeyId) override;
|
||||
|
||||
private:
|
||||
KeyId keep(KeyPair);
|
||||
void persist();
|
||||
|
||||
vanetza::security::Backend& backend_;
|
||||
KeyGenerator& generator_;
|
||||
KeyStorage& storage_;
|
||||
std::map<KeyId, KeyPair> keys_;
|
||||
std::uint32_t next_ = 1;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,164 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
/** SF-SAP language binding: TS 102 723-9 V1.1.1 (interface between the
|
||||
* security entity and the facilities layer). Tables 10 to 21 carry the same
|
||||
* parameters as the SN-SAP identifier-change primitives of TS 102 723-8, and
|
||||
* clause 4.1.5 allows one security entity to serve several layers: the SF
|
||||
* primitives below are served by the same IdChangeService instance the GN
|
||||
* core subscribes to. TS 103 300-3 V2.3.1 clause 5.3.5 requires the VRU
|
||||
* basic service to subscribe, stop generating VAMs on PREPARE, resume after
|
||||
* COMMIT with a new StationId, and to use the lock for elevated-hazard
|
||||
* situations. The facilities-side subscriber may run in the same task, in
|
||||
* another task or process, or on another device; the library defines no
|
||||
* transport, only these bindings.
|
||||
*
|
||||
* SF-SIGN/-VERIFY/-ENCRYPT/-DECRYPT/-ENCAP/-DECAP (Tables 2 to 9, 24 to 27)
|
||||
* are declared as parameter types only: for messages carried over BTP and
|
||||
* GeoNetworking the security envelope is applied at the GeoNetworking layer
|
||||
* (TS 103 300-3 clause 6.5.1; TS 103 836-4-1 clause 10.3.10.2 SN-ENCAP), so
|
||||
* this library provides no facilities-level signing service.
|
||||
*/
|
||||
namespace microbu_v2x::SF_SAP {
|
||||
|
||||
// The same identifier-change service types as sn_sap.hpp (TS 102 723-9 V1.1.1 clause 4.1.5:
|
||||
// one security entity serves several layers), under the SF-SAP names.
|
||||
using security::Identifier;
|
||||
using security::IdChangeCommand;
|
||||
using security::LockHandle;
|
||||
using security::SubscriptionHandle;
|
||||
|
||||
/// Table 10: SF-IDCHANGE-SUBSCRIBE.request
|
||||
struct SF_IDCHANGE_SUBSCRIBE_request {
|
||||
security::IdChangeHook idchange_event_hook; // Mandatory, signature of clause 5.2.6
|
||||
vanetza::ByteBuffer subscriber_data; // Optional
|
||||
};
|
||||
/// Table 11: SF-IDCHANGE-SUBSCRIBE.confirm
|
||||
struct SF_IDCHANGE_SUBSCRIBE_confirm { SubscriptionHandle subscription; };
|
||||
/// Table 12: SF-IDCHANGE-EVENT.indication (the hook arguments)
|
||||
struct SF_IDCHANGE_EVENT_indication {
|
||||
IdChangeCommand command;
|
||||
Identifier id;
|
||||
vanetza::ByteBuffer subscriber_data;
|
||||
};
|
||||
/// Table 13: SF-IDCHANGE-EVENT.response
|
||||
struct SF_IDCHANGE_EVENT_response { bool return_code; };
|
||||
/// Table 14: SF-IDCHANGE-UNSUBSCRIBE.request; Table 15 confirm carries no parameter
|
||||
struct SF_IDCHANGE_UNSUBSCRIBE_request { SubscriptionHandle subscription; };
|
||||
/// Tables 16/17: SF-IDCHANGE-TRIGGER.request/.confirm carry no parameter
|
||||
struct SF_IDCHANGE_TRIGGER_request {};
|
||||
/// Table 18: SF-ID-LOCK.request
|
||||
struct SF_ID_LOCK_request { std::uint8_t Duration; };
|
||||
/// Table 19: SF-ID-LOCK.confirm
|
||||
struct SF_ID_LOCK_confirm { LockHandle lock_handle; };
|
||||
/// Table 20: SF-ID-UNLOCK.request; Table 21 confirm carries no parameter
|
||||
struct SF_ID_UNLOCK_request { LockHandle lock_handle; };
|
||||
/// Clause 5.2.11 / Table 22 (message example): SF-LOG-SECURITY-EVENT.request
|
||||
using SF_LOG_SECURITY_EVENT_request = security::SecurityEvent;
|
||||
|
||||
/// TS 102 723-9 V1.1.1 clause 5.2.5: SF-IDCHANGE-SUBSCRIBE (Tables 10/11)
|
||||
inline SF_IDCHANGE_SUBSCRIBE_confirm SF_IDCHANGE_SUBSCRIBE_request_submit(security::IdChangeService& service,
|
||||
SF_IDCHANGE_SUBSCRIBE_request primitive) {
|
||||
return {service.subscribe(std::move(primitive.idchange_event_hook), std::move(primitive.subscriber_data))};
|
||||
}
|
||||
/// Clause 5.2.7: SF-IDCHANGE-UNSUBSCRIBE (Tables 14/15)
|
||||
inline Result SF_IDCHANGE_UNSUBSCRIBE_request_submit(security::IdChangeService& service,
|
||||
SF_IDCHANGE_UNSUBSCRIBE_request primitive) {
|
||||
return service.unsubscribe(primitive.subscription);
|
||||
}
|
||||
/// Clause 5.2.8: SF-IDCHANGE-TRIGGER (Tables 16/17)
|
||||
inline Result SF_IDCHANGE_TRIGGER_request_submit(security::IdChangeService& service, SF_IDCHANGE_TRIGGER_request) {
|
||||
return service.trigger();
|
||||
}
|
||||
/// Clause 5.2.9: SF-ID-LOCK (Tables 18/19), Duration in seconds 0..255
|
||||
inline SF_ID_LOCK_confirm SF_ID_LOCK_request_submit(security::IdChangeService& service, SF_ID_LOCK_request primitive) {
|
||||
return {service.lock(primitive.Duration)};
|
||||
}
|
||||
/// Clause 5.2.10: SF-ID-UNLOCK (Tables 20/21)
|
||||
inline Result SF_ID_UNLOCK_request_submit(security::IdChangeService& service, SF_ID_UNLOCK_request primitive) {
|
||||
return service.unlock(primitive.lock_handle);
|
||||
}
|
||||
/// Clause 5.2.11: SF-LOG-SECURITY-EVENT (Tables 22/23)
|
||||
inline void SF_LOG_SECURITY_EVENT_request_submit(security::SecurityEntity& entity,
|
||||
SF_LOG_SECURITY_EVENT_request primitive) {
|
||||
entity.log_security_event(std::move(primitive));
|
||||
}
|
||||
|
||||
// ---- Parameter types only (see the header comment) -------------------------
|
||||
|
||||
/// Table 2: SF-SIGN.request
|
||||
struct SF_SIGN_request {
|
||||
std::size_t tbs_message_length = 0;
|
||||
vanetza::ByteBuffer tbs_message;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
std::size_t permissions_length = 0;
|
||||
vanetza::ByteBuffer Permissions; // <= 31 octets, SSP of the ITS-AID
|
||||
vanetza::ByteBuffer context_information; // Optional
|
||||
std::optional<std::uint64_t> key_handle; // Optional
|
||||
};
|
||||
/// Table 3: SF-SIGN.confirm
|
||||
struct SF_SIGN_confirm { std::size_t sec_message_length = 0; vanetza::ByteBuffer sec_message; };
|
||||
/// Table 4: SF-VERIFY.request
|
||||
struct SF_VERIFY_request {
|
||||
std::size_t sec_header_length = 0;
|
||||
vanetza::ByteBuffer sec_header;
|
||||
std::size_t message_length = 0;
|
||||
vanetza::ByteBuffer message;
|
||||
};
|
||||
/// Table 5: SF-VERIFY.confirm (report values of TS 102 723-8 Table 27 / vanetza::security::VerificationReport)
|
||||
struct SF_VERIFY_confirm {
|
||||
vanetza::security::VerificationReport report;
|
||||
std::optional<security::HashedId8> certificate_id;
|
||||
std::size_t its_aid_length = 0;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
};
|
||||
/// Table 6: SF-ENCRYPT.request
|
||||
struct SF_ENCRYPT_request {
|
||||
std::size_t tbe_payload_length = 0;
|
||||
vanetza::ByteBuffer tbe_payload;
|
||||
std::size_t target_id_list_length = 0;
|
||||
std::vector<security::HashedId8> target_id_list;
|
||||
vanetza::ByteBuffer context_information; // Optional
|
||||
};
|
||||
/// Table 7: SF-ENCRYPT.confirm
|
||||
struct SF_ENCRYPT_confirm { std::size_t encrypted_message_length = 0; vanetza::ByteBuffer encrypted_message; };
|
||||
/// Table 8: SF-DECRYPT.request
|
||||
struct SF_DECRYPT_request { std::size_t encrypted_message_length = 0; vanetza::ByteBuffer encrypted_message; };
|
||||
/// Table 9: SF-DECRYPT.confirm
|
||||
struct SF_DECRYPT_confirm {
|
||||
enum class Report : std::uint8_t { SUCCESS, UNENCRYPTED_MESSAGE, DECRYPTION_ERROR, INCOMPATIBLE_PROTOCOL };
|
||||
std::size_t plaintext_message_length = 0;
|
||||
vanetza::ByteBuffer plaintext_message;
|
||||
Report report;
|
||||
};
|
||||
/// Table 24: SF-ENCAP.request (identical parameters to SN-ENCAP.request)
|
||||
struct SF_ENCAP_request {
|
||||
std::size_t tbe_packet_length = 0;
|
||||
vanetza::ByteBuffer tbe_packet;
|
||||
std::optional<std::uint16_t> sec_services;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
vanetza::ByteBuffer context_information;
|
||||
std::vector<security::HashedId8> target_id_list;
|
||||
};
|
||||
/// Table 25: SF-ENCAP.confirm
|
||||
struct SF_ENCAP_confirm { std::size_t sec_packet_length = 0; vanetza::ByteBuffer sec_packet; };
|
||||
/// Table 26: SF-DECAP.request
|
||||
struct SF_DECAP_request { std::size_t sec_packet_length = 0; vanetza::ByteBuffer sec_packet; };
|
||||
/// Table 27: SF-DECAP.confirm
|
||||
struct SF_DECAP_confirm {
|
||||
std::size_t plaintext_packet_length = 0;
|
||||
vanetza::ByteBuffer plaintext_packet;
|
||||
vanetza::security::VerificationReport report;
|
||||
std::optional<security::HashedId8> certificate_id;
|
||||
std::size_t its_aid_length = 0;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
};
|
||||
|
||||
} // namespace microbu_v2x::SF_SAP
|
||||
@@ -0,0 +1,189 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/common/byte_buffer_sink.hpp>
|
||||
#include <vanetza/net/osi_layer.hpp>
|
||||
#include <vanetza/net/packet.hpp>
|
||||
#include <vanetza/security/secured_message.hpp>
|
||||
#include <boost/iostreams/stream.hpp>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
/** SN-SAP language binding: TS 102 723-8 V2.0.0 clause 5 incorporates V1.1.1,
|
||||
* whose Tables 10 to 27 define the primitives below. '-' and '.' in primitive
|
||||
* names become '_'; parameters keep the tables' names in snake_case. The
|
||||
* *_submit functions are thin calls into the security entity, like
|
||||
* NF_SAP::BTP_DATA_request_submit. Inside the stack the GeoNetworking router
|
||||
* calls the same entity directly (vanetza::security::SecurityEntity), so
|
||||
* these bindings serve a caller in another task, process or device and the
|
||||
* test adapters; the library defines no transport for that.
|
||||
*/
|
||||
namespace microbu_v2x::SN_SAP {
|
||||
|
||||
// Types of the identifier-change service (id_change.hpp: TS 102 723-8 V1.1.1 clause 6.3,
|
||||
// identifier = HashedId8 per TS 102 940 V2.1.1 clause 6.5) under the SN-SAP names.
|
||||
using security::Identifier;
|
||||
using security::IdChangeCommand;
|
||||
using security::LockHandle;
|
||||
using security::SubscriptionHandle;
|
||||
|
||||
/// TS 102 723-8 V1.1.1 Table 10: SN-IDCHANGE-SUBSCRIBE.request
|
||||
struct SN_IDCHANGE_SUBSCRIBE_request {
|
||||
security::IdChangeHook idchange_event_hook; // Mandatory: hook function, signature of clause 5.2.6
|
||||
vanetza::ByteBuffer subscriber_data; // Optional: passed back on every hook call
|
||||
};
|
||||
/// Table 11: SN-IDCHANGE-SUBSCRIBE.confirm
|
||||
struct SN_IDCHANGE_SUBSCRIBE_confirm {
|
||||
SubscriptionHandle subscription; // INTEGER 0 to 2^64-1
|
||||
};
|
||||
/// Table 12: SN-IDCHANGE-EVENT.indication (the arguments of the hook function)
|
||||
struct SN_IDCHANGE_EVENT_indication {
|
||||
IdChangeCommand command; // PREPARE, COMMIT, ABORT, DEREG (clause 6.3)
|
||||
Identifier id; // OCTET STRING, 8 octets: id to be set
|
||||
vanetza::ByteBuffer subscriber_data; // Optional
|
||||
};
|
||||
/// Table 13: SN-IDCHANGE-EVENT.response
|
||||
struct SN_IDCHANGE_EVENT_response {
|
||||
bool return_code; // acknowledgement to the given command
|
||||
};
|
||||
/// Table 14: SN-IDCHANGE-UNSUBSCRIBE.request; Table 15 confirm carries no parameter
|
||||
struct SN_IDCHANGE_UNSUBSCRIBE_request {
|
||||
SubscriptionHandle subscription;
|
||||
};
|
||||
/// Table 16/17: SN-IDCHANGE-TRIGGER.request/.confirm carry no parameter
|
||||
struct SN_IDCHANGE_TRIGGER_request {};
|
||||
/// Table 18: SN-ID-LOCK.request
|
||||
struct SN_ID_LOCK_request {
|
||||
std::uint8_t Duration; // INTEGER 0 to 2^8-1: number of seconds to lock
|
||||
};
|
||||
/// Table 19: SN-ID-LOCK.confirm
|
||||
struct SN_ID_LOCK_confirm {
|
||||
LockHandle lock_handle; // INTEGER 0 to 2^64-1: handle to unlock manually
|
||||
};
|
||||
/// Table 20: SN-ID-UNLOCK.request; Table 21 confirm carries no parameter
|
||||
struct SN_ID_UNLOCK_request {
|
||||
LockHandle lock_handle;
|
||||
};
|
||||
/// Table 22: SN-LOG-SECURITY-EVENT.request; Table 23 confirm carries no parameter
|
||||
using SN_LOG_SECURITY_EVENT_request = security::SecurityEvent;
|
||||
|
||||
/// Table 24: SN-ENCAP.request (the GeoNetworking source fills it per TS 103 836-4-1 V2.2.1 Table 34)
|
||||
struct SN_ENCAP_request {
|
||||
std::size_t tbe_packet_length = 0; // Mandatory: length of tbe_packet
|
||||
vanetza::ByteBuffer tbe_packet; // Mandatory: packet to encapsulate (Common Header onwards)
|
||||
std::optional<std::uint16_t> sec_services; // Optional: security service(s) to invoke
|
||||
vanetza::ItsAid its_aid = 0; // Mandatory: ITS-AID selecting the security profile
|
||||
vanetza::ByteBuffer permissions; // Mandatory: SSP associated with the ITS-AID (<= 31 octets)
|
||||
vanetza::ByteBuffer context_information; // Optional: opaque, see security::context
|
||||
std::vector<security::HashedId8> target_id_list; // Optional: recipients (encryption is not implemented)
|
||||
};
|
||||
/// Table 25: SN-ENCAP.confirm
|
||||
struct SN_ENCAP_confirm {
|
||||
std::size_t sec_packet_length = 0;
|
||||
vanetza::ByteBuffer sec_packet; // the Secured Packet, EtsiTs103097Data (COER)
|
||||
};
|
||||
/// Table 26: SN-DECAP.request
|
||||
struct SN_DECAP_request {
|
||||
std::size_t sec_packet_length = 0;
|
||||
vanetza::ByteBuffer sec_packet; // EtsiTs103097Data (COER), without the GN basic header
|
||||
};
|
||||
/// TS 102 723-8 Table 27: SN-DECAP.confirm carries the verification outcome.
|
||||
/// Callers enforce their receive policy using report and the signer permissions.
|
||||
/// Verification requires V2X_SECURITY_VERIFY. Builds without it report
|
||||
/// CONFIGURATION_PROBLEM for signed messages and UNSIGNED_MESSAGE otherwise.
|
||||
struct SN_DECAP_confirm {
|
||||
std::size_t plaintext_packet_length = 0;
|
||||
vanetza::ByteBuffer plaintext_packet;
|
||||
vanetza::security::VerificationReport report = vanetza::security::VerificationReport::Configuration_Problem;
|
||||
std::optional<security::HashedId8> certificate_id;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
};
|
||||
|
||||
/// TS 102 723-8 V1.1.1 clause 5.2.5: SN-IDCHANGE-SUBSCRIBE (Tables 10/11)
|
||||
inline SN_IDCHANGE_SUBSCRIBE_confirm SN_IDCHANGE_SUBSCRIBE_request_submit(security::IdChangeService& service,
|
||||
SN_IDCHANGE_SUBSCRIBE_request primitive) {
|
||||
return {service.subscribe(std::move(primitive.idchange_event_hook), std::move(primitive.subscriber_data))};
|
||||
}
|
||||
/// Clause 5.2.7: SN-IDCHANGE-UNSUBSCRIBE (Tables 14/15)
|
||||
inline Result SN_IDCHANGE_UNSUBSCRIBE_request_submit(security::IdChangeService& service,
|
||||
SN_IDCHANGE_UNSUBSCRIBE_request primitive) {
|
||||
return service.unsubscribe(primitive.subscription);
|
||||
}
|
||||
/// Clause 5.2.8: SN-IDCHANGE-TRIGGER (Tables 16/17)
|
||||
inline Result SN_IDCHANGE_TRIGGER_request_submit(security::IdChangeService& service, SN_IDCHANGE_TRIGGER_request) {
|
||||
return service.trigger();
|
||||
}
|
||||
/// Clause 5.2.9: SN-ID-LOCK (Tables 18/19), Duration in seconds 0..255
|
||||
inline SN_ID_LOCK_confirm SN_ID_LOCK_request_submit(security::IdChangeService& service, SN_ID_LOCK_request primitive) {
|
||||
return {service.lock(primitive.Duration)};
|
||||
}
|
||||
/// Clause 5.2.10: SN-ID-UNLOCK (Tables 20/21)
|
||||
inline Result SN_ID_UNLOCK_request_submit(security::IdChangeService& service, SN_ID_UNLOCK_request primitive) {
|
||||
return service.unlock(primitive.lock_handle);
|
||||
}
|
||||
/// Clause 5.2.11: SN-LOG-SECURITY-EVENT (Tables 22/23)
|
||||
inline void SN_LOG_SECURITY_EVENT_request_submit(security::SecurityEntity& entity,
|
||||
SN_LOG_SECURITY_EVENT_request primitive) {
|
||||
entity.log_security_event(std::move(primitive));
|
||||
}
|
||||
|
||||
/** SN-ENCAP over raw octets. Result::invalid_argument on a length mismatch or a
|
||||
* permissions field beyond 31 octets, Result::unsupported when sec_services or
|
||||
* target_id_list request anything but signing, Result::security_unavailable
|
||||
* when the entity refuses (no usable ticket, identifier change pending). */
|
||||
/// Clause 5.2.12: SN-ENCAP (Tables 24/25); clause 5.2.13 SN-DECAP (Tables 26/27) below
|
||||
inline Result SN_ENCAP_request_submit(vanetza::security::SecurityEntity& entity, SN_ENCAP_request primitive,
|
||||
SN_ENCAP_confirm& confirm) {
|
||||
if (primitive.tbe_packet_length != primitive.tbe_packet.size() || primitive.tbe_packet.empty() ||
|
||||
primitive.permissions.size() > 31) return Result::invalid_argument;
|
||||
if (primitive.sec_services || !primitive.target_id_list.empty()) return Result::unsupported;
|
||||
vanetza::security::SignRequest request;
|
||||
request.plain_message[vanetza::OsiLayer::Network] = std::move(primitive.tbe_packet);
|
||||
request.its_aid = primitive.its_aid;
|
||||
request.permissions = std::move(primitive.permissions);
|
||||
request.context_information = std::move(primitive.context_information);
|
||||
auto result = entity.encapsulate_packet(vanetza::security::EncapRequest {std::move(request)});
|
||||
const auto* secured = result.secured_message();
|
||||
if (!secured) return Result::security_unavailable;
|
||||
confirm.sec_packet.clear();
|
||||
vanetza::byte_buffer_sink sink(confirm.sec_packet);
|
||||
boost::iostreams::stream_buffer<vanetza::byte_buffer_sink> stream(sink);
|
||||
vanetza::OutputArchive archive(stream);
|
||||
vanetza::security::serialize(archive, *secured);
|
||||
stream.pubsync();
|
||||
confirm.sec_packet_length = confirm.sec_packet.size();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
/** SN-DECAP over raw octets (clause 5.2.13). Result::invalid_argument on a length
|
||||
* mismatch or when sec_packet is not a decodable EtsiTs103097Data; otherwise the
|
||||
* confirm carries the entity's report (never Success, see SN_DECAP_confirm). */
|
||||
inline Result SN_DECAP_request_submit(vanetza::security::SecurityEntity& entity, const SN_DECAP_request& primitive,
|
||||
SN_DECAP_confirm& confirm) {
|
||||
if (primitive.sec_packet_length != primitive.sec_packet.size() || primitive.sec_packet.empty())
|
||||
return Result::invalid_argument;
|
||||
vanetza::security::v3::SecuredMessage message;
|
||||
if (!message.decode(primitive.sec_packet)) return Result::invalid_argument;
|
||||
vanetza::security::SecuredMessage variant {std::move(message)};
|
||||
auto result = entity.decapsulate_packet(vanetza::security::DecapRequest {vanetza::security::SecuredMessageView {variant}});
|
||||
confirm = SN_DECAP_confirm {};
|
||||
if (const auto* report = boost::get<vanetza::security::VerificationReport>(&result.report)) confirm.report = *report;
|
||||
if (result.certificate_id) confirm.certificate_id = *result.certificate_id;
|
||||
confirm.its_aid = result.its_aid;
|
||||
confirm.permissions = std::move(result.permissions);
|
||||
if (const auto* packet = boost::get<vanetza::CohesivePacket>(&result.plaintext_payload)) {
|
||||
confirm.plaintext_packet.assign(packet->buffer().begin(), packet->buffer().end());
|
||||
} else if (const auto* chunks = boost::get<vanetza::ChunkPacket>(&result.plaintext_payload)) {
|
||||
for (auto layer : vanetza::osi_layer_range<vanetza::OsiLayer::Network, vanetza::OsiLayer::Application>()) {
|
||||
const auto& part = (*chunks)[layer];
|
||||
vanetza::ByteBuffer bytes;
|
||||
part.convert(bytes);
|
||||
confirm.plaintext_packet.insert(confirm.plaintext_packet.end(), bytes.begin(), bytes.end());
|
||||
}
|
||||
}
|
||||
confirm.plaintext_packet_length = confirm.plaintext_packet.size();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::SN_SAP
|
||||
@@ -0,0 +1,174 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <microbu_v2x/id_change.hpp>
|
||||
#include <vanetza/common/manual_runtime.hpp>
|
||||
#include <vanetza/common/position_fix.hpp>
|
||||
#include <vanetza/dcc/channel_load.hpp>
|
||||
#include <vanetza/geonet/data_request.hpp>
|
||||
#include <vanetza/geonet/data_indication.hpp>
|
||||
#include <vanetza/geonet/data_confirm.hpp>
|
||||
#include <vanetza/security/security_entity.hpp>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace microbu_v2x {
|
||||
enum class BtpType { a, b };
|
||||
|
||||
/** NF-SAP / BTP-DATA.request: TS 103 836-5-1 V2.1.1 Annex A.2
|
||||
* and clauses 7, 8.2; TS 102 723-11 V2.0.0 clause 5
|
||||
* incorporates V1.1.1, including its clause 5.1 GeoAware SAP.
|
||||
* All port numbers are HOST order. data.size() is the Length parameter.
|
||||
* Omitted GN parameters inherit the configured MIB. No magic sentinel values.
|
||||
*/
|
||||
struct BtpRequest {
|
||||
BtpType type = BtpType::b;
|
||||
std::optional<std::uint16_t> source_port;
|
||||
std::uint16_t destination_port = 0;
|
||||
std::optional<std::uint16_t> destination_port_info;
|
||||
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
|
||||
vanetza::geonet::DestinationVariant destination = nullptr;
|
||||
vanetza::geonet::CommunicationProfile communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
|
||||
// The selected security entity implements this profile; ITS-AID, SSP and
|
||||
// context information are SN-ENCAP inputs (TS 102 723-8 V2.0.0 clause 5 /
|
||||
// V1.1.1 Table 24) that GN forwards unchanged (TS 103 836-4-1 V2.2.1
|
||||
// Table 34, Annex J.2 "Security context information").
|
||||
std::optional<std::uint32_t> security_profile;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
vanetza::ByteBuffer security_context; // see security::context for the values this library defines
|
||||
std::optional<vanetza::geonet::Lifetime> maximum_lifetime;
|
||||
std::optional<vanetza::geonet::DataRequest::Repetition> repetition;
|
||||
std::optional<unsigned> maximum_hop_limit;
|
||||
vanetza::geonet::TrafficClass traffic_class;
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
/** BTP-DATA.indication: TS 103 836-5-1 V2.1.1 Annex A.3/8.3.
|
||||
* gn retains the transport, destination, source vector, report, permissions,
|
||||
* traffic class, remaining lifetime and hop limit. Owns the received payload.
|
||||
*/
|
||||
struct BtpIndication {
|
||||
BtpType type;
|
||||
std::optional<std::uint16_t> source_port;
|
||||
std::uint16_t destination_port;
|
||||
std::optional<std::uint16_t> destination_port_info;
|
||||
vanetza::geonet::DataIndication gn;
|
||||
std::optional<vanetza::ByteBuffer> certificate_id;
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
/** GN-DATA.request: TS 103 836-4-1 V2.2.1 clause 9.3 N-SAP (EN 302 636-4-1
|
||||
* clause 9.3 heritage). Unlike BtpRequest, data is the raw SDU
|
||||
* with no assumed upper-layer header; the Common Header next_header is
|
||||
* "Any". Only SHB and GBC are implemented; GUC, GAC and TSB are rejected
|
||||
* as Result::unsupported, matching Stack::request(BtpRequest).
|
||||
*/
|
||||
struct GnRequest {
|
||||
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
|
||||
vanetza::geonet::DestinationVariant destination = nullptr; // Area for GBC, null for SHB
|
||||
vanetza::geonet::CommunicationProfile communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
|
||||
vanetza::geonet::TrafficClass traffic_class;
|
||||
std::optional<vanetza::geonet::Lifetime> maximum_lifetime;
|
||||
std::optional<unsigned> maximum_hop_limit;
|
||||
std::optional<vanetza::geonet::DataRequest::Repetition> repetition;
|
||||
vanetza::ItsAid its_aid = 0;
|
||||
vanetza::ByteBuffer permissions;
|
||||
vanetza::ByteBuffer security_context; // TS 103 836-4-1 V2.2.1 Annex J.2 Security context information
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
/** GN-DATA.indication for a packet whose Common Header next_header is "Any"
|
||||
* (no upper protocol registered by BtpRequest's handler), TS 103 836-4-1
|
||||
* V2.2.1 clause 9.3. gn retains the complete router indication.
|
||||
*/
|
||||
struct GnIndication {
|
||||
vanetza::geonet::DataIndication gn;
|
||||
vanetza::ByteBuffer data;
|
||||
};
|
||||
|
||||
struct StackConfig {
|
||||
vanetza::geonet::MIB mib;
|
||||
std::size_t maximum_gnpdu = 4096;
|
||||
std::uint32_t security_profile = 0;
|
||||
AlDataRequest radio_parameters;
|
||||
StackConfig();
|
||||
};
|
||||
|
||||
/** Portable network/transport module for the NF-SAP entry point.
|
||||
* The caller serializes all calls in ONE task/event loop, including reception,
|
||||
* clock advancement and destruction. Access/SecurityEntity must outlive Stack.
|
||||
* Timer source is injectable for host tests, HIL and ESP-IDF esp_timer.
|
||||
* No FreeRTOS task, radio, BLE link, socket or filesystem is opened internally.
|
||||
* This is a port of the upstream router; see docs/conformance.md for R2 gaps.
|
||||
*
|
||||
* Identifier change (TS 103 836-4-1 V2.2.1 clause 10.2.1.4, anonymous address
|
||||
* configuration): with itsGnLocalAddrConfMethod == Anonymous and an
|
||||
* IdChangeService, the GN core subscribes at construction and unsubscribes at
|
||||
* destruction. On COMMIT the GN address MID becomes the 48 least significant
|
||||
* bits of the new HashedId8 (TS 102 940 V2.1.1 clause 6.5), with the I/G bit
|
||||
* cleared (a source address is individual) and the U/L bit set; the link-layer
|
||||
* source follows because every request takes it from the GN address. Between
|
||||
* PREPARE and COMMIT the forwarding buffers are flushed and request() returns
|
||||
* Result::identity_change_pending (TS 102 723-8 clause 6.3.1.3). The access
|
||||
* adapter is not notified by the stack: it may subscribe to the same service
|
||||
* (TS 102 723-7 analogy for the IN-SAP side is not defined here).
|
||||
*/
|
||||
class Stack {
|
||||
public:
|
||||
using Receive = std::function<void(BtpIndication)>;
|
||||
using ReceiveGn = std::function<void(GnIndication)>;
|
||||
using Report = std::function<void(Result)>;
|
||||
/** id_change may be omitted: when security is a microbu_v2x::security::SecurityEntity
|
||||
* its own identifier-change service is used. */
|
||||
Stack(StackConfig, vanetza::ManualRuntime&, Access&,
|
||||
vanetza::security::SecurityEntity* security = nullptr,
|
||||
security::IdChangeService* id_change = nullptr);
|
||||
~Stack();
|
||||
Stack(const Stack&) = delete;
|
||||
Stack& operator=(const Stack&) = delete;
|
||||
Result request(BtpRequest);
|
||||
Result request(GnRequest);
|
||||
Result indicate(AlDataIndication);
|
||||
Result update_position(const vanetza::PositionFix&);
|
||||
Result advance(vanetza::Clock::time_point);
|
||||
void on_receive(Receive);
|
||||
void on_receive_gn(ReceiveGn);
|
||||
void on_access_result(Report);
|
||||
/// Observe the native Vanetza packet drop reason without changing its decision.
|
||||
void on_packet_drop(std::function<void(const std::string&)>);
|
||||
const StackConfig& config() const;
|
||||
/// the identifier-change service this stack subscribed to, nullptr without one
|
||||
security::IdChangeService* id_change();
|
||||
vanetza::security::SecurityEntity* security_entity();
|
||||
/// true between PREPARE and COMMIT (or ABORT) of an identifier change
|
||||
bool identity_change_pending() const;
|
||||
/// GeoNetworking address currently in use (MID follows the identifier change)
|
||||
const vanetza::geonet::Address& address() const;
|
||||
/** Managed address configuration (TS 103 836-4-1 V2.2.1 clause 10.2.1.3.3): the N&T
|
||||
* management entity updates the GN address with an unsolicited CORE_MMT.response
|
||||
* (MN_SAP::CORE_MMT_response_apply). Result::unsupported with Auto (10.2.1.2) or
|
||||
* Anonymous (10.2.1.4) configuration, identity_change_pending during a change. */
|
||||
Result set_address(const vanetza::geonet::Address&);
|
||||
|
||||
/** Release-2 DCC_NET (TS 103 836-4-2 V2.1.1 clauses 5, 6.2, 6.3.3, 7.2).
|
||||
* Always active for this ITS-G5-only Stack: outgoing SHB packets carry a real DCC-MCO
|
||||
* field (local/one-hop CBR, TX power) instead of the upstream NullDccFieldGenerator's
|
||||
* reserved zero field, and every received SHB packet's DCC-MCO updates LocTEX-G5
|
||||
* (already unconditional in the upstream router once itsGnIfType is ITS_G5, which this
|
||||
* Stack requires). report_local_channel_load feeds DCC_NET's own CBR_G calculation
|
||||
* (clause 5.3); it is independent of AccessStack::report_channel_load (DCC_ACC), which
|
||||
* the caller should feed with global_channel_busy_ratio() when available, else the same
|
||||
* local measurement.
|
||||
*/
|
||||
void report_local_channel_load(vanetza::dcc::ChannelLoad);
|
||||
/// EIRP of the station's own transmissions, for the outgoing DCC-MCO field's TX-power octet.
|
||||
void report_tx_power(unsigned dbm);
|
||||
/** CBR_G (TS 103 836-4-2 clause 5.3), once at least one 100 ms aggregation cycle has run;
|
||||
* std::nullopt beforehand (no neighbour data collected yet). */
|
||||
std::optional<vanetza::dcc::ChannelLoad> global_channel_busy_ratio() const;
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/pki.hpp>
|
||||
#include <microbu_v2x/credentials.hpp>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
// TS 102 941 clauses 6.3.1 to 6.3.6. One complete authenticated transaction.
|
||||
struct TrustSnapshot {
|
||||
ByteBuffer tlm, rca, ectl, ctl, crl;
|
||||
Time32 deadline = 0;
|
||||
};
|
||||
ByteBuffer encode_snapshot(const TrustSnapshot&);
|
||||
bool decode_snapshot(const ByteBuffer&, TrustSnapshot&);
|
||||
// Initial bootstrap requires the independently pinned TLM. Later TLM changes
|
||||
// require a successor authenticated by the previously accepted ECTL.
|
||||
bool validate_update(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
|
||||
const TrustSnapshot& proposed, TrustSnapshot& accepted);
|
||||
bool snapshot_credentials(vanetza::security::Backend&, const TrustSnapshot&,
|
||||
microbu_v2x::security::StoredCredentials&, microbu_v2x::security::TrustConfiguration* = nullptr);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# Kconfig hides this backend on other SoCs; this independent guard also rejects
|
||||
# forced/stale configurations. The private ABI is qualified per SDK version.
|
||||
if(NOT IDF_TARGET STREQUAL "esp32c5")
|
||||
message(FATAL_ERROR "Integrated ITS-G5 radio requires IDF_TARGET=esp32c5")
|
||||
endif()
|
||||
if(NOT IDF_VERSION_MAJOR EQUAL 6 OR NOT IDF_VERSION_MINOR EQUAL 0 OR NOT IDF_VERSION_PATCH EQUAL 2)
|
||||
message(FATAL_ERROR "C5 private radio ABI is pinned to ESP-IDF 6.0.2")
|
||||
endif()
|
||||
set(_otm_source "${V2X_PORT}/third_party/otm/main/tx_custom.c")
|
||||
if(NOT EXISTS "${_otm_source}")
|
||||
message(FATAL_ERROR "Initialize the OpenTrafficMap submodule before selecting the C5 radio")
|
||||
endif()
|
||||
file(READ "${_otm_source}" _otm)
|
||||
string(REPLACE "\r\n" "\n" _otm "${_otm}")
|
||||
string(SHA256 _otm_hash "${_otm}")
|
||||
if(NOT _otm_hash STREQUAL "cb1dccfef96912ca59275e8a9102f41f56925b94a19d4a4629082aaeb779be1b")
|
||||
message(FATAL_ERROR "OpenTrafficMap transmitter differs from the reviewed source revision")
|
||||
endif()
|
||||
# Keep the upstream checkout immutable. The sole logic patch preserves the
|
||||
# actual driver submission result, which upstream discarded. ESP_OK still
|
||||
# means submission, not independent observation of transmission on air.
|
||||
string(REPLACE " ieee80211_post_hmac_tx(eb);"
|
||||
" result = ieee80211_post_hmac_tx(eb);" _otm "${_otm}")
|
||||
set(_otm_generated "${CMAKE_CURRENT_BINARY_DIR}/otm_tx_custom.c")
|
||||
file(WRITE "${_otm_generated}" "#include <assert.h>\n#include <stddef.h>\n${_otm}\n_Static_assert(offsetof(x_ebuf_t, txdesc) == 0x38, \"ebuf txdesc offset\");\n_Static_assert(offsetof(x_eb_txdesc_t, rate) == 0x0c, \"txdesc rate offset\");\n")
|
||||
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/c5_radio.cpp" "${_otm_generated}")
|
||||
target_include_directories(${V2X_TARGET} PRIVATE "${V2X_PORT}/third_party/otm/main")
|
||||
@@ -0,0 +1,97 @@
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#if V2X_NETWORK
|
||||
#include <vanetza/access/data_rates.hpp>
|
||||
#include <vanetza/dcc/limeric.hpp>
|
||||
#include <vanetza/dcc/limeric_budget.hpp>
|
||||
#include <vanetza/dcc/profile.hpp>
|
||||
#include <vanetza/dcc/transmission.hpp>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#endif
|
||||
|
||||
namespace microbu_v2x {
|
||||
Result validate(const AlDataRequest& request, std::size_t maximum) {
|
||||
if (request.data.empty() || request.data.size() > maximum || request.priority > 7 ||
|
||||
!std::isfinite(request.transmit_power_dbm) || request.bandwidth_mhz == 0)
|
||||
return Result::invalid_argument;
|
||||
return Result::accepted;
|
||||
}
|
||||
#if V2X_NETWORK
|
||||
namespace {
|
||||
// EN 303 797 V2.1.1 clause 4.6.2's Ton limit; a single
|
||||
// frame at or below this duration also cannot alone exceed the 3 % duty cycle at Toff>=25 ms.
|
||||
constexpr vanetza::Clock::duration max_ton = std::chrono::milliseconds(4);
|
||||
// Index by OfdmMcs; mirrors the rate table in C5Radio::request/transmit_burst.
|
||||
constexpr std::array<const vanetza::access::DataRateG5*, 8> g5_rates {
|
||||
&vanetza::access::G5_3Mbps, &vanetza::access::G5_4dot5Mbps, &vanetza::access::G5_6Mbps,
|
||||
&vanetza::access::G5_9Mbps, &vanetza::access::G5_12Mbps, &vanetza::access::G5_18bps,
|
||||
&vanetza::access::G5_24Mbps, &vanetza::access::G5_27Mbps,
|
||||
};
|
||||
// Airtime-only use of Transmission::channel_occupancy(); profile is immaterial here since no
|
||||
// FlowControl queueing is involved, only the data-rate/length formula.
|
||||
vanetza::Clock::duration request_airtime(const AlDataRequest& request) {
|
||||
vanetza::dcc::TransmissionLite transmission(vanetza::dcc::Profile::DP2, request.data.size());
|
||||
const auto index = static_cast<unsigned>(request.mcs);
|
||||
transmission.m_data_rate = index < g5_rates.size() ? g5_rates[index] : nullptr;
|
||||
return transmission.channel_occupancy();
|
||||
}
|
||||
// TS 102 687 V1.2.1 Table 3 defaults, with cbr_target overridden to the project's Release-2
|
||||
// value.
|
||||
vanetza::dcc::Limeric::Parameters limeric_parameters(vanetza::dcc::ChannelLoad cbr_target) {
|
||||
vanetza::dcc::Limeric::Parameters parameters;
|
||||
parameters.cbr_target = cbr_target;
|
||||
return parameters;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class AccessStack::Dcc {
|
||||
public:
|
||||
Dcc(vanetza::Runtime& rt, vanetza::dcc::ChannelLoad target) :
|
||||
limeric(rt, limeric_parameters(target)),
|
||||
budget(limeric, rt)
|
||||
{
|
||||
// TS 102 687 V1.2.1 Annex B: the gate-opening time depends on the current permitted
|
||||
// duty cycle, so it must be recalculated whenever the Adaptive approach updates delta.
|
||||
limeric.on_duty_cycle_change = [this](const vanetza::dcc::Limeric*, vanetza::Clock::time_point) {
|
||||
budget.update();
|
||||
};
|
||||
}
|
||||
vanetza::dcc::Limeric limeric;
|
||||
vanetza::dcc::LimericBudget budget;
|
||||
};
|
||||
|
||||
void AccessStack::enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target) {
|
||||
dcc_ = std::make_unique<Dcc>(runtime, cbr_target);
|
||||
}
|
||||
|
||||
void AccessStack::report_channel_load(vanetza::dcc::ChannelLoad load) {
|
||||
if (dcc_) dcc_->limeric.update_cbr(load);
|
||||
}
|
||||
|
||||
vanetza::UnitInterval AccessStack::permitted_duty_cycle() const {
|
||||
return dcc_ ? dcc_->limeric.permitted_duty_cycle() : vanetza::UnitInterval(1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
AccessStack::AccessStack(Access& access, std::size_t maximum) :
|
||||
access_(access), maximum_gnpdu_(maximum) {}
|
||||
AccessStack::~AccessStack() = default;
|
||||
|
||||
Result AccessStack::request(AlDataRequest request) {
|
||||
auto result = validate(request, maximum_gnpdu_);
|
||||
if (result != Result::accepted) return result;
|
||||
#if V2X_NETWORK
|
||||
if (dcc_) {
|
||||
const auto ton = request_airtime(request);
|
||||
if (ton <= vanetza::Clock::duration::zero() || ton > max_ton) return Result::invalid_argument;
|
||||
if (dcc_->budget.delay() > vanetza::Clock::duration::zero()) return Result::resource_limit;
|
||||
result = access_.request(std::move(request));
|
||||
if (result == Result::accepted) dcc_->budget.notify(ton);
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
return access_.request(std::move(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/sha.hpp>
|
||||
#include <psa/crypto.h>
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
|
||||
psa_ecc_family_t family(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
|
||||
case KeyType::BrainpoolP256r1:
|
||||
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
|
||||
default: throw std::runtime_error("unsupported key type");
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t curve_bits(KeyType type) { return key_length(type) * 8; }
|
||||
|
||||
struct ScopedKey {
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
~ScopedKey() { if (id) psa_destroy_key(id); }
|
||||
};
|
||||
|
||||
// SEC 1 uncompressed encoding of a generic public key, recovering y when compressed.
|
||||
vanetza::ByteBuffer public_key_octets(const PublicKey& key) {
|
||||
Uncompressed point;
|
||||
switch (key.compression) {
|
||||
case KeyCompression::NoCompression:
|
||||
point.x = key.x; point.y = key.y;
|
||||
break;
|
||||
case KeyCompression::Y0:
|
||||
case KeyCompression::Y1: {
|
||||
auto recovered = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
|
||||
if (!recovered) throw std::runtime_error("public key is not on the curve");
|
||||
point = std::move(*recovered);
|
||||
break;
|
||||
}
|
||||
default: throw std::runtime_error("unsupported point compression");
|
||||
}
|
||||
if (point.x.size() != key_length(key.type) || point.y.size() != key_length(key.type))
|
||||
throw std::runtime_error("public key coordinate length");
|
||||
return ecc::encode_uncompressed(point);
|
||||
}
|
||||
|
||||
// The digest handed in is the SHA-256/SHA-384 output IEEE Std 1609.2 clause 5.3.1 prescribes
|
||||
// for the curve, so the operation names that hash: implementations that accelerate ECDSA
|
||||
// (ESP-IDF's PSA driver for the ESP32-C5 ECDSA peripheral, CONFIG_MBEDTLS_HARDWARE_ECDSA_VERIFY)
|
||||
// only take PSA_ALG_ECDSA(PSA_ALG_SHA_256/384), never PSA_ALG_ECDSA_ANY, which falls back to
|
||||
// software. Keys are imported with the wildcard policy so either form is permitted.
|
||||
psa_algorithm_t ecdsa_algorithm(std::size_t digest_octets) {
|
||||
switch (digest_octets) {
|
||||
case 32: return PSA_ALG_ECDSA(PSA_ALG_SHA_256);
|
||||
case 48: return PSA_ALG_ECDSA(PSA_ALG_SHA_384);
|
||||
default: return PSA_ALG_ECDSA_ANY;
|
||||
}
|
||||
}
|
||||
|
||||
mbedtls_svc_key_id_t import_public(KeyType type, const vanetza::ByteBuffer& sec1) {
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(family(type)));
|
||||
psa_set_key_bits(&attributes, curve_bits(type));
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, sec1.data(), sec1.size(), &id) != PSA_SUCCESS)
|
||||
throw std::runtime_error("PSA public key import failed");
|
||||
return id;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer raw_signature(mbedtls_svc_key_id_t key, KeyType type, const vanetza::ByteBuffer& digest) {
|
||||
vanetza::ByteBuffer signature(2 * key_length(type));
|
||||
std::size_t length = 0;
|
||||
const auto status = psa_sign_hash(key, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
|
||||
signature.data(), signature.size(), &length);
|
||||
if (status != PSA_SUCCESS || length != signature.size()) throw std::runtime_error("PSA ECDSA signing failed");
|
||||
return signature;
|
||||
}
|
||||
|
||||
bool verify_raw(KeyType type, const vanetza::ByteBuffer& sec1, const vanetza::ByteBuffer& digest,
|
||||
const vanetza::ByteBuffer& r, const vanetza::ByteBuffer& s) {
|
||||
const auto n = key_length(type);
|
||||
if (r.size() != n || s.size() != n) return false;
|
||||
vanetza::ByteBuffer signature;
|
||||
signature.reserve(2 * n);
|
||||
signature.insert(signature.end(), r.begin(), r.end());
|
||||
signature.insert(signature.end(), s.begin(), s.end());
|
||||
ScopedKey key;
|
||||
try { key.id = import_public(type, sec1); } catch (const std::runtime_error&) { return false; }
|
||||
return psa_verify_hash(key.id, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
|
||||
signature.data(), signature.size()) == PSA_SUCCESS;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class BackendMbedTls::Impl {
|
||||
public:
|
||||
struct Entry { KeyType type; vanetza::ByteBuffer secret; mbedtls_svc_key_id_t id; };
|
||||
std::deque<Entry> cache;
|
||||
std::size_t capacity = 4;
|
||||
|
||||
~Impl() { for (auto& entry : cache) psa_destroy_key(entry.id); }
|
||||
|
||||
mbedtls_svc_key_id_t signing_key(KeyType type, const vanetza::ByteBuffer& secret) {
|
||||
if (secret.size() != key_length(type)) throw std::runtime_error("private key length");
|
||||
for (auto it = cache.begin(); it != cache.end(); ++it) {
|
||||
if (it->type == type && it->secret == secret) {
|
||||
Entry hit = std::move(*it);
|
||||
cache.erase(it);
|
||||
cache.push_front(std::move(hit)); // most recently used first
|
||||
return cache.front().id;
|
||||
}
|
||||
}
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
|
||||
psa_set_key_bits(&attributes, curve_bits(type));
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, secret.data(), secret.size(), &id) != PSA_SUCCESS)
|
||||
throw std::runtime_error("PSA private key import failed");
|
||||
while (cache.size() >= capacity) {
|
||||
psa_destroy_key(cache.back().id);
|
||||
cache.pop_back();
|
||||
}
|
||||
cache.push_front(Entry {type, secret, id});
|
||||
return id;
|
||||
}
|
||||
};
|
||||
|
||||
BackendMbedTls::BackendMbedTls() : impl_(std::make_unique<Impl>()) {
|
||||
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
|
||||
}
|
||||
BackendMbedTls::~BackendMbedTls() = default;
|
||||
void BackendMbedTls::set_key_cache_size(std::size_t size) { impl_->capacity = std::max<std::size_t>(1, size); }
|
||||
|
||||
EcdsaSignature BackendMbedTls::sign_data(const ecdsa256::PrivateKey& key, const vanetza::ByteBuffer& data) {
|
||||
const auto digest = calculate_sha256_digest(data.data(), data.size());
|
||||
const vanetza::ByteBuffer secret(key.key.begin(), key.key.end());
|
||||
const auto id = impl_->signing_key(KeyType::NistP256, secret);
|
||||
auto raw = raw_signature(id, KeyType::NistP256, vanetza::ByteBuffer(digest.begin(), digest.end()));
|
||||
EcdsaSignature signature;
|
||||
X_Coordinate_Only r;
|
||||
r.x.assign(raw.begin(), raw.begin() + 32);
|
||||
signature.R = std::move(r);
|
||||
signature.s.assign(raw.begin() + 32, raw.end());
|
||||
return signature;
|
||||
}
|
||||
|
||||
Signature BackendMbedTls::sign_digest(const PrivateKey& key, const vanetza::ByteBuffer& digest) {
|
||||
const auto id = impl_->signing_key(key.type, key.key);
|
||||
auto raw = raw_signature(id, key.type, digest);
|
||||
const auto n = key_length(key.type);
|
||||
Signature signature;
|
||||
signature.type = key.type;
|
||||
signature.r.assign(raw.begin(), raw.begin() + n);
|
||||
signature.s.assign(raw.begin() + n, raw.end());
|
||||
return signature;
|
||||
}
|
||||
|
||||
bool BackendMbedTls::verify_data(const ecdsa256::PublicKey& key, const vanetza::ByteBuffer& data,
|
||||
const EcdsaSignature& signature) {
|
||||
const auto digest = calculate_sha256_digest(data.data(), data.size());
|
||||
Uncompressed point;
|
||||
point.x.assign(key.x.begin(), key.x.end());
|
||||
point.y.assign(key.y.begin(), key.y.end());
|
||||
return verify_raw(KeyType::NistP256, ecc::encode_uncompressed(point),
|
||||
vanetza::ByteBuffer(digest.begin(), digest.end()),
|
||||
convert_for_signing(signature.R), signature.s);
|
||||
}
|
||||
|
||||
bool BackendMbedTls::verify_digest(const PublicKey& key, const vanetza::ByteBuffer& digest, const Signature& signature) {
|
||||
if (key.type != signature.type) return false;
|
||||
try {
|
||||
return verify_raw(key.type, public_key_octets(key), digest, signature.r, signature.s);
|
||||
} catch (const std::runtime_error&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<Uncompressed> BackendMbedTls::decompress_point(const EccPoint& ecc_point) {
|
||||
struct Visitor : boost::static_visitor<boost::optional<Uncompressed>> {
|
||||
boost::optional<Uncompressed> operator()(const X_Coordinate_Only&) const { return boost::none; }
|
||||
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_0& p) const {
|
||||
return ecc::decompress(KeyType::NistP256, p.x, false);
|
||||
}
|
||||
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_1& p) const {
|
||||
return ecc::decompress(KeyType::NistP256, p.x, true);
|
||||
}
|
||||
boost::optional<Uncompressed> operator()(const Uncompressed& p) const { return p; }
|
||||
};
|
||||
Visitor visitor;
|
||||
return boost::apply_visitor(visitor, ecc_point);
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer BackendMbedTls::calculate_hash(HashAlgorithm algorithm, const vanetza::ByteBuffer& data) {
|
||||
psa_algorithm_t alg;
|
||||
std::size_t size;
|
||||
switch (algorithm) {
|
||||
case HashAlgorithm::SHA256: alg = PSA_ALG_SHA_256; size = 32; break;
|
||||
case HashAlgorithm::SHA384: alg = PSA_ALG_SHA_384; size = 48; break;
|
||||
default: return {};
|
||||
}
|
||||
vanetza::ByteBuffer digest(size);
|
||||
std::size_t written = 0;
|
||||
if (psa_hash_compute(alg, data.data(), data.size(), digest.data(), digest.size(), &written) != PSA_SUCCESS ||
|
||||
written != size) throw std::runtime_error("PSA hash failed");
|
||||
return digest;
|
||||
}
|
||||
|
||||
ecdsa256::KeyPair BackendMbedTls::generate_key_pair() {
|
||||
const auto generated = generate_key(KeyType::NistP256);
|
||||
ecdsa256::KeyPair pair;
|
||||
std::copy(generated.priv.key.begin(), generated.priv.key.end(), pair.private_key.key.begin());
|
||||
std::copy(generated.pub.x.begin(), generated.pub.x.end(), pair.public_key.x.begin());
|
||||
std::copy(generated.pub.y.begin(), generated.pub.y.end(), pair.public_key.y.begin());
|
||||
return pair;
|
||||
}
|
||||
|
||||
security::KeyPair BackendMbedTls::generate_key(KeyType type) {
|
||||
const std::size_t n = key_length(type);
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
|
||||
psa_set_key_bits(&attributes, n * 8);
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA_ANY);
|
||||
ScopedKey key;
|
||||
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
||||
security::KeyPair pair;
|
||||
pair.priv.type = pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.priv.key.resize(n);
|
||||
std::size_t length = 0;
|
||||
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
|
||||
throw std::runtime_error("PSA private key export failed");
|
||||
vanetza::ByteBuffer sec1(1 + 2 * n);
|
||||
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() ||
|
||||
sec1[0] != 0x04) throw std::runtime_error("PSA public key export failed");
|
||||
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
|
||||
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
|
||||
return pair;
|
||||
}
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,165 @@
|
||||
#include <microbu_v2x/c5_radio.hpp>
|
||||
#include <microbu_v2x/its_g5_frame.hpp>
|
||||
#include <esp_event.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <hal/modem_syscon_ll.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" {
|
||||
void phy_11p_set(int, int);
|
||||
void phy_change_channel(int, int, int, int);
|
||||
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t, const void*, int32_t, bool,
|
||||
wifi_tx_rate_config_t*, wifi_band_t, wifi_bandwidth_t);
|
||||
}
|
||||
|
||||
namespace microbu_v2x {
|
||||
class C5Radio::Impl {
|
||||
public:
|
||||
struct Raw {
|
||||
std::uint16_t length;
|
||||
std::int8_t rssi;
|
||||
std::uint32_t timestamp;
|
||||
std::uint8_t bytes[2346];
|
||||
};
|
||||
C5RadioConfig config;
|
||||
QueueHandle_t queue = nullptr;
|
||||
bool initialized = false, started = false, own_event_loop = false;
|
||||
std::uint16_t sequence = 0;
|
||||
std::atomic<std::uint32_t> dropped {0};
|
||||
static Impl* active;
|
||||
static std::mutex callback_mutex;
|
||||
explicit Impl(C5RadioConfig c) : config(c) {}
|
||||
static void receive(void* buffer, wifi_promiscuous_pkt_type_t type) {
|
||||
if (!buffer || type != WIFI_PKT_DATA) return;
|
||||
const auto* packet = static_cast<const wifi_promiscuous_pkt_t*>(buffer);
|
||||
if (packet->rx_ctrl.rx_state != 0) return;
|
||||
// esp_wifi_he_types.h documents sig_len on this chip as "the length of the
|
||||
// reception MPDU", not "MPDU + FCS" as older-chip ESP-IDF documentation
|
||||
// states; measured on real hardware, it is consistently 4 bytes longer than
|
||||
// the actual frame, and those 4 trailing bytes are a fixed, content-independent
|
||||
// value (00 00 99 00), not a real, software-recoverable FCS. This promiscuous
|
||||
// filter never sets WIFI_PROMIS_FILTER_MASK_FCSFAIL, so the frame itself has
|
||||
// already passed a real hardware FCS check by the time it reaches this callback
|
||||
// -- see components/microbu_v2x/tools/radio_pair.py's docstring for the full evidence.
|
||||
const auto length = packet->rx_ctrl.sig_len;
|
||||
std::lock_guard<std::mutex> lock(callback_mutex);
|
||||
if (!active || !active->queue) return;
|
||||
if (length < 38 || length > sizeof(Raw::bytes)) { ++active->dropped; return; }
|
||||
Raw raw {};
|
||||
raw.length = length; raw.rssi = packet->rx_ctrl.rssi;
|
||||
raw.timestamp = packet->rx_ctrl.timestamp;
|
||||
std::memcpy(raw.bytes, packet->payload, length);
|
||||
if (xQueueSend(active->queue, &raw, 0) != pdTRUE) ++active->dropped;
|
||||
}
|
||||
};
|
||||
C5Radio::Impl* C5Radio::Impl::active = nullptr;
|
||||
std::mutex C5Radio::Impl::callback_mutex;
|
||||
C5Radio::C5Radio(C5RadioConfig c) : impl_(std::make_unique<Impl>(c)) {}
|
||||
C5Radio::~C5Radio() { stop(); }
|
||||
esp_err_t C5Radio::start() {
|
||||
auto& p = *impl_;
|
||||
const auto& c = p.config;
|
||||
if (p.initialized) return ESP_ERR_INVALID_STATE;
|
||||
if (c.channel_number < 172 || c.channel_number > 184 || c.channel_number % 2 ||
|
||||
!std::isfinite(c.transmit_power_dbm) || c.transmit_power_dbm < 2 || c.transmit_power_dbm > 20 ||
|
||||
std::floor(c.transmit_power_dbm * 4) != c.transmit_power_dbm * 4 ||
|
||||
c.receive_queue_length == 0 || c.receive_queue_length > 32) return ESP_ERR_INVALID_ARG;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
|
||||
if (Impl::active) return ESP_ERR_INVALID_STATE;
|
||||
p.queue = xQueueCreate(c.receive_queue_length, sizeof(Impl::Raw));
|
||||
if (!p.queue) return ESP_ERR_NO_MEM;
|
||||
Impl::active = &p;
|
||||
}
|
||||
auto result = esp_event_loop_create_default();
|
||||
p.own_event_loop = result == ESP_OK;
|
||||
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { stop(); return result; }
|
||||
// OpenTrafficMap main/main.c and cmd_sniffer.c establish the FE clock and
|
||||
// NON_NGV_10 PHY mode. These private calls are SDK-specific, not ETSI SAPs.
|
||||
modem_syscon_ll_enable_fe_40m_clock(&MODEM_SYSCON, true);
|
||||
wifi_init_config_t wifi = WIFI_INIT_CONFIG_DEFAULT();
|
||||
wifi.nvs_enable = 0;
|
||||
result = esp_wifi_init(&wifi);
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
p.initialized = true;
|
||||
auto attempt = [&](esp_err_t r) { if (result == ESP_OK) result = r; };
|
||||
attempt(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
attempt(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
if (result == ESP_OK) { result = esp_wifi_start(); p.started = result == ESP_OK; }
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
attempt(esp_wifi_set_band_mode(WIFI_BAND_MODE_5G_ONLY));
|
||||
attempt(esp_wifi_set_ps(WIFI_PS_NONE));
|
||||
attempt(esp_wifi_set_max_tx_power(static_cast<std::int8_t>(c.transmit_power_dbm * 4)));
|
||||
wifi_promiscuous_filter_t filter {};
|
||||
filter.filter_mask = WIFI_PROMIS_FILTER_MASK_DATA;
|
||||
attempt(esp_wifi_set_promiscuous_filter(&filter));
|
||||
attempt(esp_wifi_set_promiscuous_rx_cb(Impl::receive));
|
||||
attempt(esp_wifi_set_promiscuous(true));
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
phy_11p_set(1, 0); // 10 MHz; never infer PHY width from WIFI_BW20 below.
|
||||
phy_change_channel(5000 + 5 * c.channel_number, 1, 0, 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
void C5Radio::stop() {
|
||||
if (!impl_) return;
|
||||
auto& p = *impl_;
|
||||
if (p.started) esp_wifi_set_promiscuous(false);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
|
||||
if (Impl::active == &p) Impl::active = nullptr;
|
||||
if (p.queue) { vQueueDelete(p.queue); p.queue = nullptr; }
|
||||
}
|
||||
if (p.started) esp_wifi_stop();
|
||||
if (p.initialized) esp_wifi_deinit();
|
||||
if (p.own_event_loop) esp_event_loop_delete_default();
|
||||
p.started = p.initialized = p.own_event_loop = false;
|
||||
}
|
||||
Result C5Radio::request(AlDataRequest request) {
|
||||
auto& p = *impl_;
|
||||
if (!p.started) return Result::rejected;
|
||||
if (!p.config.laboratory_transmission) return Result::unsupported;
|
||||
// Reject controls this fixed-channel backend cannot honour. In particular,
|
||||
// do not silently reinterpret an AL_DATA bandwidth or transceiver mode.
|
||||
if (request.bandwidth_mhz != 10 || request.channel_number != p.config.channel_number ||
|
||||
request.transceiver_id != 0 || request.transceiver_mode || request.datastream_id ||
|
||||
request.transmit_power_dbm != p.config.transmit_power_dbm) return Result::unsupported;
|
||||
constexpr wifi_phy_rate_t rates[] = {WIFI_PHY_RATE_6M, WIFI_PHY_RATE_9M, WIFI_PHY_RATE_12M,
|
||||
WIFI_PHY_RATE_18M, WIFI_PHY_RATE_24M, WIFI_PHY_RATE_36M, WIFI_PHY_RATE_48M, WIFI_PHY_RATE_54M};
|
||||
const auto index = static_cast<unsigned>(request.mcs);
|
||||
if (index >= std::size(rates)) return Result::invalid_argument;
|
||||
vanetza::ByteBuffer bytes;
|
||||
const auto encoded = its_g5::encode_frame(request, p.sequence, bytes);
|
||||
if (encoded != Result::accepted) return encoded;
|
||||
p.sequence = (p.sequence + 1) & 4095;
|
||||
wifi_tx_rate_config_t rate {};
|
||||
rate.phymode = WIFI_PHY_MODE_11A; rate.rate = rates[index];
|
||||
// Legacy OFDM rate identifiers are halved by the 10 MHz PHY mode.
|
||||
// The driver consumes the frame synchronously into its own ebuf.
|
||||
const auto result = esp_wifi_80211_tx_custom(WIFI_IF_STA, bytes.data(), bytes.size(), false,
|
||||
&rate, WIFI_BAND_5G, WIFI_BW20);
|
||||
return result == ESP_OK ? Result::accepted : result == ESP_ERR_NO_MEM ? Result::resource_limit : Result::rejected;
|
||||
}
|
||||
void C5Radio::poll(const Receive& receive, const Capture& capture) {
|
||||
auto& p = *impl_;
|
||||
if (!p.queue) return;
|
||||
Impl::Raw raw {};
|
||||
// Bound work per poll even if the radio continuously fills the queue.
|
||||
for (unsigned i = 0; i < p.config.receive_queue_length && xQueueReceive(p.queue, &raw, 0) == pdTRUE; ++i) {
|
||||
if (capture) capture(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.length), raw.rssi, raw.timestamp);
|
||||
AlDataIndication ind;
|
||||
if (its_g5::decode_frame(raw.bytes, raw.length, true, ind) != Result::accepted) continue;
|
||||
ind.channel_number = p.config.channel_number;
|
||||
ind.received_power_dbm = raw.rssi;
|
||||
// The SDK does not provide channel-busy time here. CBR remains absent;
|
||||
// counting received packets would not be a valid CBR measurement.
|
||||
if (receive) receive(std::move(ind));
|
||||
}
|
||||
}
|
||||
std::uint32_t C5Radio::dropped_frames() const { return impl_->dropped.load(); }
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
#include <microbu_v2x/credentials.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using vanetza::security::KeyType;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint8_t bundle_magic[4] = {'V', 'C', 'R', '1'};
|
||||
constexpr std::uint8_t stored_magic[4] = {'V', 'C', 'S', '1'};
|
||||
enum Record : std::uint8_t { root = 1, authority = 2, ticket = 3, ticket_key = 4, ticket_key_id = 5 };
|
||||
|
||||
std::uint8_t curve_code(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return 1;
|
||||
case KeyType::BrainpoolP256r1: return 2;
|
||||
case KeyType::BrainpoolP384r1: return 3;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
KeyType curve_type(std::uint8_t code) {
|
||||
switch (code) {
|
||||
case 1: return KeyType::NistP256;
|
||||
case 2: return KeyType::BrainpoolP256r1;
|
||||
case 3: return KeyType::BrainpoolP384r1;
|
||||
default: return KeyType::Unspecified;
|
||||
}
|
||||
}
|
||||
void put(ByteBuffer& out, std::uint8_t type, const ByteBuffer& payload) {
|
||||
out.push_back(type);
|
||||
out.push_back(static_cast<std::uint8_t>(payload.size() >> 8));
|
||||
out.push_back(static_cast<std::uint8_t>(payload.size()));
|
||||
out.insert(out.end(), payload.begin(), payload.end());
|
||||
}
|
||||
|
||||
ByteBuffer key_record(const PrivateKey& key) {
|
||||
ByteBuffer out {curve_code(key.type)};
|
||||
out.insert(out.end(), key.key.begin(), key.key.end());
|
||||
return out;
|
||||
}
|
||||
ByteBuffer key_record(KeyId key) {
|
||||
return {static_cast<std::uint8_t>(key.value >> 24), static_cast<std::uint8_t>(key.value >> 16),
|
||||
static_cast<std::uint8_t>(key.value >> 8), static_cast<std::uint8_t>(key.value)};
|
||||
}
|
||||
|
||||
bool read_key(const ByteBuffer& payload, PrivateKey& key) {
|
||||
const KeyType curve = curve_type(payload[0]);
|
||||
if (curve == KeyType::Unspecified || payload.size() - 1 != vanetza::security::key_length(curve)) return false;
|
||||
key.type = curve;
|
||||
key.key.assign(payload.begin() + 1, payload.end());
|
||||
return true;
|
||||
}
|
||||
bool read_key(const ByteBuffer& payload, KeyId& key) {
|
||||
if (payload.size() != 4) return false;
|
||||
key.value = std::uint32_t(payload[0]) << 24 | std::uint32_t(payload[1]) << 16 | std::uint32_t(payload[2]) << 8 | payload[3];
|
||||
return bool(key);
|
||||
}
|
||||
|
||||
/// Both formats: magic, then roots, authorities and tickets, each ticket certificate followed by its key record.
|
||||
template <class Set>
|
||||
ByteBuffer encode_set(const Set& set, const std::uint8_t (&magic)[4], std::uint8_t key_type) {
|
||||
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||
for (const auto& coer : set.roots) put(out, Record::root, coer);
|
||||
for (const auto& coer : set.authorities) put(out, Record::authority, coer);
|
||||
for (const auto& t : set.tickets) {
|
||||
put(out, Record::ticket, t.certificate);
|
||||
put(out, key_type, key_record(t.key));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
template <class Set>
|
||||
bool decode_set(const ByteBuffer& bundle, const std::uint8_t (&magic)[4], std::uint8_t key_type, Set& out) {
|
||||
if (bundle.size() < sizeof(magic) || !std::equal(std::begin(magic), std::end(magic), bundle.begin())) return false;
|
||||
Set parsed;
|
||||
bool key_pending = false; // a ticket certificate awaits its key record
|
||||
std::size_t at = sizeof(magic);
|
||||
while (at < bundle.size()) {
|
||||
if (bundle.size() - at < 3) return false;
|
||||
const std::uint8_t type = bundle[at];
|
||||
const std::size_t length = (static_cast<std::size_t>(bundle[at + 1]) << 8) | bundle[at + 2];
|
||||
at += 3;
|
||||
if (bundle.size() - at < length || length == 0) return false;
|
||||
ByteBuffer payload(bundle.begin() + at, bundle.begin() + at + length);
|
||||
at += length;
|
||||
if (key_pending != (type == key_type)) return false;
|
||||
if (type == Record::root) {
|
||||
parsed.roots.push_back(std::move(payload));
|
||||
} else if (type == Record::authority) {
|
||||
parsed.authorities.push_back(std::move(payload));
|
||||
} else if (type == Record::ticket) {
|
||||
parsed.tickets.push_back({std::move(payload), {}});
|
||||
key_pending = true;
|
||||
} else if (type == key_type) {
|
||||
if (!read_key(payload, parsed.tickets.back().key)) return false;
|
||||
key_pending = false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (key_pending) return false;
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ByteBuffer encode(const Credentials& credentials) { return encode_set(credentials, bundle_magic, Record::ticket_key); }
|
||||
ByteBuffer encode(const StoredCredentials& credentials) {
|
||||
return encode_set(credentials, stored_magic, Record::ticket_key_id);
|
||||
}
|
||||
|
||||
bool decode(const ByteBuffer& bundle, Credentials& out) {
|
||||
return decode_set(bundle, bundle_magic, Record::ticket_key, out);
|
||||
}
|
||||
bool decode(const ByteBuffer& bundle, StoredCredentials& out) {
|
||||
return decode_set(bundle, stored_magic, Record::ticket_key_id, out);
|
||||
}
|
||||
|
||||
std::optional<StoredCredentials> import_keys(const Credentials& credentials, SecurityModule& module) {
|
||||
StoredCredentials stored {credentials.roots, credentials.authorities, {}};
|
||||
const auto undo = [&]() -> std::optional<StoredCredentials> {
|
||||
for (const auto& t : stored.tickets) module.destroy_key(t.key);
|
||||
return std::nullopt;
|
||||
};
|
||||
for (const auto& t : credentials.tickets) {
|
||||
vanetza::security::v3::Certificate certificate;
|
||||
if (!certificate.decode(t.certificate)) return undo();
|
||||
const auto verification_key = vanetza::security::v3::get_public_key(*certificate.content());
|
||||
if (!verification_key) return undo();
|
||||
const auto key = module.import_key(KeyPair {t.key, *verification_key});
|
||||
if (!key) return undo();
|
||||
stored.tickets.push_back({t.certificate, *key});
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
ApplyReport apply(const StoredCredentials& credentials, TrustConfiguration& trust, CertificatePool& pool) {
|
||||
ApplyReport report;
|
||||
for (const auto& coer : credentials.roots) {
|
||||
if ((report.result = trust.add_root(coer)) != Result::accepted) return report;
|
||||
++report.roots;
|
||||
}
|
||||
for (const auto& coer : credentials.authorities) {
|
||||
if ((report.result = trust.add_authority(coer)) != Result::accepted) return report;
|
||||
++report.authorities;
|
||||
}
|
||||
for (const auto& t : credentials.tickets) {
|
||||
if ((report.result = pool.add(t.certificate, t.key)) != Result::accepted) return report;
|
||||
++report.tickets;
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::save(const StoredCredentials& credentials) {
|
||||
const ByteBuffer bundle = encode(credentials);
|
||||
std::ofstream out(path_, std::ios::binary | std::ios::trunc);
|
||||
out.write(reinterpret_cast<const char*>(bundle.data()), bundle.size());
|
||||
return out ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::load(StoredCredentials& credentials) {
|
||||
std::ifstream in(path_, std::ios::binary);
|
||||
if (!in) return Result::rejected;
|
||||
const ByteBuffer bundle(std::istreambuf_iterator<char>(in), {});
|
||||
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::erase() {
|
||||
return std::remove(path_.c_str()) == 0 ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,82 @@
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <boost/multiprecision/cpp_int.hpp>
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
|
||||
namespace microbu_v2x::ecc {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
// Fixed width, no heap: a 384-bit product needs 768 bits before reduction.
|
||||
using Int = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<
|
||||
1024, 1024, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
|
||||
|
||||
// FIPS 186-4 D.1.2.3 (P-256), RFC 5639 3.4 (brainpoolP256r1) and 3.6 (brainpoolP384r1).
|
||||
// The host regression compares every constant with OpenSSL's built-in groups.
|
||||
constexpr CurveParameters curves[] = {
|
||||
{KeyType::NistP256, 32,
|
||||
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
|
||||
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
|
||||
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"},
|
||||
{KeyType::BrainpoolP256r1, 32,
|
||||
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377",
|
||||
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9",
|
||||
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6"},
|
||||
{KeyType::BrainpoolP384r1, 48,
|
||||
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53",
|
||||
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826",
|
||||
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11"},
|
||||
};
|
||||
|
||||
Int from_hex(const char* hex) { return Int(std::string("0x") + hex); }
|
||||
|
||||
Int from_bytes(const vanetza::ByteBuffer& bytes) {
|
||||
Int value;
|
||||
boost::multiprecision::import_bits(value, bytes.begin(), bytes.end(), 8, true);
|
||||
return value;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer to_bytes(const Int& value, std::size_t octets) {
|
||||
vanetza::ByteBuffer out;
|
||||
boost::multiprecision::export_bits(value, std::back_inserter(out), 8, true);
|
||||
if (out.size() > octets) return {};
|
||||
out.insert(out.begin(), octets - out.size(), 0);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
const CurveParameters* curve(KeyType type) {
|
||||
for (const auto& c : curves) if (c.type == type) return &c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
boost::optional<Uncompressed> decompress(KeyType type, const vanetza::ByteBuffer& x_bytes, bool y_odd) {
|
||||
const auto* c = curve(type);
|
||||
if (!c || x_bytes.size() != c->octets) return boost::none;
|
||||
const Int p = from_hex(c->p), a = from_hex(c->a), b = from_hex(c->b);
|
||||
const Int x = from_bytes(x_bytes);
|
||||
if (x >= p) return boost::none;
|
||||
// rhs = x^3 + a*x + b (mod p)
|
||||
Int rhs = (x * x) % p;
|
||||
rhs = (rhs * x) % p;
|
||||
rhs = (rhs + (a * x) % p) % p;
|
||||
rhs = (rhs + b) % p;
|
||||
// p = 3 (mod 4): sqrt(n) = n^((p+1)/4) (mod p) when n is a quadratic residue.
|
||||
Int y = boost::multiprecision::powm(rhs, (p + 1) / 4, p);
|
||||
if ((y * y) % p != rhs) return boost::none; // x is not on the curve
|
||||
if (static_cast<bool>(y & 1) != y_odd) y = p - y;
|
||||
Uncompressed point;
|
||||
point.x = x_bytes;
|
||||
point.y = to_bytes(y, c->octets);
|
||||
if (point.y.empty()) return boost::none;
|
||||
return point;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer encode_uncompressed(const Uncompressed& point) {
|
||||
vanetza::ByteBuffer out;
|
||||
out.reserve(1 + point.x.size() + point.y.size());
|
||||
out.push_back(0x04);
|
||||
out.insert(out.end(), point.x.begin(), point.x.end());
|
||||
out.insert(out.end(), point.y.begin(), point.y.end());
|
||||
return out;
|
||||
}
|
||||
} // namespace microbu_v2x::ecc
|
||||
@@ -0,0 +1,135 @@
|
||||
#include <microbu_v2x/ecies_mbedtls.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <psa/crypto.h>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
psa_ecc_family_t family_of(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
|
||||
case KeyType::BrainpoolP256r1:
|
||||
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
|
||||
default: throw std::runtime_error("unsupported key type");
|
||||
}
|
||||
}
|
||||
struct ScopedKey {
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
~ScopedKey() { if (id) psa_destroy_key(id); }
|
||||
};
|
||||
mbedtls_svc_key_id_t import_raw(psa_key_type_t type, std::size_t bits, psa_key_usage_t usage, psa_algorithm_t alg,
|
||||
const std::uint8_t* data, std::size_t length) {
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, type);
|
||||
if (bits) psa_set_key_bits(&attributes, bits);
|
||||
psa_set_key_usage_flags(&attributes, usage);
|
||||
psa_set_key_algorithm(&attributes, alg);
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, data, length, &id) != PSA_SUCCESS) throw std::runtime_error("PSA key import failed");
|
||||
return id;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
EciesMbedTls::EciesMbedTls() {
|
||||
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
|
||||
}
|
||||
|
||||
KeyPair EciesMbedTls::generate_key(KeyType type) {
|
||||
const std::size_t n = key_length(type);
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(type)));
|
||||
psa_set_key_bits(&attributes, n * 8);
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDH);
|
||||
ScopedKey key;
|
||||
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
||||
KeyPair pair;
|
||||
pair.priv.type = type;
|
||||
pair.priv.key.resize(n);
|
||||
std::size_t length = 0;
|
||||
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
|
||||
throw std::runtime_error("PSA private key export failed");
|
||||
ByteBuffer sec1(1 + 2 * n);
|
||||
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() || sec1[0] != 0x04)
|
||||
throw std::runtime_error("PSA public key export failed");
|
||||
pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
|
||||
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
|
||||
return pair;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> EciesMbedTls::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
|
||||
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
|
||||
const std::size_t n = key_length(own.type);
|
||||
if (own.key.size() != n || peer.x.size() != n || peer.y.size() != n) return std::nullopt;
|
||||
try {
|
||||
ScopedKey key;
|
||||
key.id = import_raw(PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(own.type)), n * 8, PSA_KEY_USAGE_DERIVE, PSA_ALG_ECDH,
|
||||
own.key.data(), own.key.size());
|
||||
Uncompressed point;
|
||||
point.x = peer.x; point.y = peer.y;
|
||||
const ByteBuffer sec1 = ecc::encode_uncompressed(point);
|
||||
ByteBuffer secret(n);
|
||||
std::size_t length = 0;
|
||||
// PSA raw ECDH output is the x coordinate of the shared point (PSA Crypto API 1.1, PSA_ALG_ECDH)
|
||||
if (psa_raw_key_agreement(PSA_ALG_ECDH, key.id, sec1.data(), sec1.size(), secret.data(), secret.size(), &length) != PSA_SUCCESS ||
|
||||
length != n) return std::nullopt;
|
||||
return secret;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer EciesMbedTls::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
|
||||
ScopedKey mac_key;
|
||||
mac_key.id = import_raw(PSA_KEY_TYPE_HMAC, 0, PSA_KEY_USAGE_SIGN_MESSAGE, PSA_ALG_HMAC(PSA_ALG_SHA_256),
|
||||
key.data(), key.size());
|
||||
ByteBuffer out(32);
|
||||
std::size_t length = 0;
|
||||
if (psa_mac_compute(mac_key.id, PSA_ALG_HMAC(PSA_ALG_SHA_256), data.data(), data.size(), out.data(), out.size(), &length) != PSA_SUCCESS ||
|
||||
length != 32) throw std::runtime_error("PSA HMAC failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
ByteBuffer EciesMbedTls::random(std::size_t octets) {
|
||||
ByteBuffer out(octets);
|
||||
if (octets && psa_generate_random(out.data(), out.size()) != PSA_SUCCESS) throw std::runtime_error("PSA random failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
bool EciesMbedTls::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& out) {
|
||||
try {
|
||||
ScopedKey aes;
|
||||
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_ENCRYPT, PSA_ALG_CCM, key.data(), key.size());
|
||||
out.resize(plaintext.size() + 16);
|
||||
std::size_t length = 0;
|
||||
if (psa_aead_encrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, plaintext.data(), plaintext.size(),
|
||||
out.data(), out.size(), &length) != PSA_SUCCESS || length != out.size()) { out.clear(); return false; }
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool EciesMbedTls::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& in, ByteBuffer& plaintext) {
|
||||
if (in.size() < 16) return false;
|
||||
try {
|
||||
ScopedKey aes;
|
||||
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_DECRYPT, PSA_ALG_CCM, key.data(), key.size());
|
||||
plaintext.resize(in.size() - 16);
|
||||
std::size_t length = 0;
|
||||
if (psa_aead_decrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, in.data(), in.size(),
|
||||
plaintext.data(), plaintext.size(), &length) != PSA_SUCCESS || length != plaintext.size()) {
|
||||
plaintext.clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,121 @@
|
||||
#include <microbu_v2x/ecies_openssl.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/openssl_wrapper.hpp>
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/ecdh.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/hmac.h>
|
||||
#include <openssl/obj_mac.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
int nid_of(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return NID_X9_62_prime256v1;
|
||||
case KeyType::BrainpoolP256r1: return NID_brainpoolP256r1;
|
||||
case KeyType::BrainpoolP384r1: return NID_brainpoolP384r1;
|
||||
default: return NID_undef;
|
||||
}
|
||||
}
|
||||
struct CipherContext {
|
||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
||||
~CipherContext() { EVP_CIPHER_CTX_free(ctx); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
KeyPair EciesOpenSsl::generate_key(KeyType type) {
|
||||
openssl::Key key(nid_of(type));
|
||||
openssl::check(EC_KEY_generate_key(key));
|
||||
const std::size_t n = key_length(type);
|
||||
KeyPair pair;
|
||||
pair.priv.type = type;
|
||||
pair.priv.key.resize(n);
|
||||
BN_bn2binpad(EC_KEY_get0_private_key(key), pair.priv.key.data(), n);
|
||||
openssl::BigNumber x, y;
|
||||
openssl::BigNumberContext ctx;
|
||||
openssl::check(EC_POINT_get_affine_coordinates(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key), x, y, ctx));
|
||||
pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.pub.x.resize(n); pair.pub.y.resize(n);
|
||||
BN_bn2binpad(x, pair.pub.x.data(), n);
|
||||
BN_bn2binpad(y, pair.pub.y.data(), n);
|
||||
return pair;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> EciesOpenSsl::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
|
||||
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
|
||||
try {
|
||||
openssl::Key key(nid_of(own.type));
|
||||
openssl::BigNumber d(own.key);
|
||||
openssl::check(EC_KEY_set_private_key(key, d));
|
||||
openssl::Group group(nid_of(peer.type));
|
||||
openssl::Point point(group);
|
||||
openssl::BigNumberContext ctx;
|
||||
openssl::check(EC_POINT_set_affine_coordinates(group, point, openssl::BigNumber(peer.x), openssl::BigNumber(peer.y), ctx));
|
||||
openssl::check(EC_POINT_is_on_curve(group, point, ctx) == 1);
|
||||
ByteBuffer secret(key_length(own.type));
|
||||
// no KDF here: the raw x coordinate is the ECIES shared secret input to KDF2
|
||||
const int written = ECDH_compute_key(secret.data(), secret.size(), point, key, nullptr);
|
||||
if (written != static_cast<int>(secret.size())) return std::nullopt;
|
||||
return secret;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer EciesOpenSsl::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
|
||||
ByteBuffer out(32);
|
||||
unsigned length = 0;
|
||||
if (!HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()), data.data(), data.size(), out.data(), &length) ||
|
||||
length != 32) throw std::runtime_error("HMAC-SHA256 failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
ByteBuffer EciesOpenSsl::random(std::size_t octets) {
|
||||
ByteBuffer out(octets);
|
||||
if (octets && RAND_bytes(out.data(), static_cast<int>(octets)) != 1) throw std::runtime_error("RAND_bytes failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
bool EciesOpenSsl::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& out) {
|
||||
CipherContext c;
|
||||
if (!c.ctx) return false;
|
||||
int length = 0;
|
||||
if (EVP_EncryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, nullptr) != 1 ||
|
||||
EVP_EncryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
|
||||
EVP_EncryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(plaintext.size())) != 1) return false;
|
||||
out.resize(plaintext.size() + 16);
|
||||
if (EVP_EncryptUpdate(c.ctx, out.data(), &length, plaintext.data(), static_cast<int>(plaintext.size())) != 1 ||
|
||||
length != static_cast<int>(plaintext.size())) return false;
|
||||
int final_length = 0;
|
||||
if (EVP_EncryptFinal_ex(c.ctx, out.data() + length, &final_length) != 1) return false;
|
||||
if (EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_GET_TAG, 16, out.data() + plaintext.size()) != 1) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EciesOpenSsl::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& in, ByteBuffer& plaintext) {
|
||||
if (in.size() < 16) return false;
|
||||
const std::size_t payload = in.size() - 16;
|
||||
CipherContext c;
|
||||
if (!c.ctx) return false;
|
||||
int length = 0;
|
||||
if (EVP_DecryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, const_cast<std::uint8_t*>(in.data() + payload)) != 1 ||
|
||||
EVP_DecryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
|
||||
EVP_DecryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(payload)) != 1) return false;
|
||||
plaintext.resize(payload);
|
||||
// CCM verifies the tag inside this update; a mismatch returns 0
|
||||
if (EVP_DecryptUpdate(c.ctx, plaintext.data(), &length, in.data(), static_cast<int>(payload)) != 1 ||
|
||||
length != static_cast<int>(payload)) { plaintext.clear(); return false; }
|
||||
return true;
|
||||
}
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,27 @@
|
||||
// ESP32-C5 boot repair, linked into every application that uses this component on
|
||||
// that target (the component's CMake forces the object in with "-u").
|
||||
//
|
||||
// ESP-IDF's esp_system/port/soc/esp32c5/system_internal.c documents that the C5
|
||||
// ROM's UART initialisation misses the UART0 function clock enable
|
||||
// (PCR_UART0_SCLK_EN, "does not reset with the UART module") and repairs it inside
|
||||
// esp_restart(). A reset triggered over USB-Serial/JTAG or JTAG (esptool's
|
||||
// DTR/RTS toggle, OpenOCD, a debugger) bypasses esp_restart(), so once an
|
||||
// application has left the bit cleared the next boot's ROM stage waits forever
|
||||
// for PCR_UART0_READY and the board stays unreachable until a power cycle.
|
||||
// Setting the bit early in every boot keeps warm resets working regardless of what
|
||||
// the application does with UART0; the cost is one register write.
|
||||
#include "sdkconfig.h"
|
||||
#if CONFIG_IDF_TARGET_ESP32C5
|
||||
#include <esp_err.h>
|
||||
#include <esp_private/startup_internal.h>
|
||||
#include <soc/pcr_reg.h>
|
||||
#include <soc/soc.h>
|
||||
|
||||
ESP_SYSTEM_INIT_FN(v2x_esp32c5_rom_uart_clock, CORE, BIT(0), 120) {
|
||||
REG_SET_BIT(PCR_UART0_SCLK_CONF_REG, PCR_UART0_SCLK_EN);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Referenced through "-u" so the linker keeps this object and its init entry.
|
||||
void v2x_esp32c5_rom_uart_clock_link(void) {}
|
||||
#endif
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <microbu_v2x/facilities.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace microbu_v2x::facilities {
|
||||
Descriptor descriptor(Kind kind) {
|
||||
// TS 103 248 BTP well-known ports; CDD MessageId values. The service
|
||||
// protocolVersion comes from each service ASN.1 definition: CAM/DENM 2,
|
||||
// VAM 3 (TS 103 300-3 V2.3.1 ItsPduHeaderVam). Release != protocolVersion.
|
||||
switch (kind) {
|
||||
case Kind::cam: return {2001, 2, 2};
|
||||
case Kind::denm: return {2002, 1, 2};
|
||||
// TS 103 248 V2.4.1, Table 1: VA (VAM) is 2018; 2009 is CP (CPM).
|
||||
case Kind::vam: return {2018, 16, 3};
|
||||
}
|
||||
return {0, 0, 0};
|
||||
}
|
||||
template<class Message>
|
||||
Result check(Kind kind, const vanetza::ByteBuffer& data) {
|
||||
Message message;
|
||||
if (!message.decode_exact(data) || !message.validate()) return Result::invalid_argument;
|
||||
const auto expected = descriptor(kind);
|
||||
if (message->header.messageId != expected.message_id ||
|
||||
message->header.protocolVersion != expected.protocol_version) return Result::invalid_argument;
|
||||
return Result::accepted;
|
||||
}
|
||||
Result validate_pdu(Kind kind, const vanetza::ByteBuffer& data, std::size_t maximum) {
|
||||
if (data.empty() || data.size() > maximum) return Result::invalid_argument;
|
||||
try {
|
||||
switch (kind) {
|
||||
#if V2X_CAM
|
||||
case Kind::cam: return check<Cam>(kind, data);
|
||||
#endif
|
||||
#if V2X_DENM
|
||||
case Kind::denm: return check<Denm>(kind, data);
|
||||
#endif
|
||||
#if V2X_VAM
|
||||
case Kind::vam: return check<Vam>(kind, data);
|
||||
#endif
|
||||
default: return Result::unsupported;
|
||||
}
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::invalid_argument; }
|
||||
}
|
||||
#if V2X_NETWORK
|
||||
Result send(Stack& stack, Kind kind, vanetza::ByteBuffer bytes, BtpRequest req) {
|
||||
auto result = validate_pdu(kind, bytes, stack.config().mib.itsGnMaxSduSize - 4u);
|
||||
if (result != Result::accepted) return result;
|
||||
req.type = BtpType::b;
|
||||
req.source_port.reset();
|
||||
req.destination_port = descriptor(kind).port;
|
||||
req.destination_port_info = 0;
|
||||
if (req.its_aid == 0) {
|
||||
// SN-ENCAP its_aid selects the security profile: TS 102 965 V2.4.1 Table A.1
|
||||
// (CA 36, DEN 37, VRU 638); TS 103 300-3 V2.3.1 clause 6.5.1 for VAMs.
|
||||
switch (kind) {
|
||||
case Kind::cam: req.its_aid = vanetza::aid::CA; break;
|
||||
case Kind::denm: req.its_aid = vanetza::aid::DEN; break;
|
||||
case Kind::vam: req.its_aid = vanetza::aid::VRU; break;
|
||||
}
|
||||
}
|
||||
if (kind == Kind::vam && req.permissions.empty()) {
|
||||
// TS 103 300-3 V2.3.1 clause 6.5.2: BitmapSsp whose first octet, value 1, is the SSP version.
|
||||
req.permissions = {0x01};
|
||||
}
|
||||
req.data = std::move(bytes);
|
||||
return stack.request(std::move(req));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// TS 102 723-8 V1.1.1 clause 6.3 identifier-change procedures over one pool of
|
||||
// authorization tickets. See id_change.hpp and security.hpp for the contracts.
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using namespace vanetza;
|
||||
|
||||
class IdentityManager::Impl : public std::enable_shared_from_this<IdentityManager::Impl> {
|
||||
public:
|
||||
struct Subscription { IdChangeHook hook; ByteBuffer data; };
|
||||
struct Round {
|
||||
std::uint64_t id;
|
||||
IdChangeCommand phase; // PREPARE or COMMIT
|
||||
Identifier new_identifier;
|
||||
std::set<SubscriptionHandle> outstanding;
|
||||
};
|
||||
|
||||
Runtime& runtime;
|
||||
CertificatePool& pool;
|
||||
std::map<SubscriptionHandle, Subscription> subscriptions;
|
||||
SubscriptionHandle next_subscription = 1;
|
||||
std::map<LockHandle, Clock::time_point> locks;
|
||||
LockHandle next_lock = 1;
|
||||
std::unique_ptr<Round> round;
|
||||
std::uint64_t round_counter = 0;
|
||||
bool pending_trigger = false;
|
||||
Clock::duration response_timeout = std::chrono::milliseconds(500);
|
||||
std::function<void(const Identifier&)> committed;
|
||||
Statistics stats;
|
||||
unsigned notify_depth = 0; // hooks run re-entrantly; phase changes wait until delivery completed
|
||||
char round_timer_scope = 0;
|
||||
char lock_timer_scope = 0;
|
||||
|
||||
Impl(Runtime& rt, CertificatePool& p) : runtime(rt), pool(p) {}
|
||||
|
||||
Identifier current() const {
|
||||
const auto* ticket = pool.current();
|
||||
return ticket ? ticket->digest : Identifier {};
|
||||
}
|
||||
|
||||
bool locked() const { return !locks.empty(); }
|
||||
|
||||
// Table 13 return_code carrier handed to hooks for PREPARE and COMMIT.
|
||||
class Responder : public IdChangeResponder {
|
||||
public:
|
||||
Responder(std::weak_ptr<Impl> owner, std::uint64_t round, SubscriptionHandle handle) :
|
||||
owner_(std::move(owner)), round_(round), handle_(handle) {}
|
||||
void respond(bool return_code) override {
|
||||
if (auto impl = owner_.lock()) impl->handle_response(round_, handle_, return_code);
|
||||
}
|
||||
private:
|
||||
std::weak_ptr<Impl> owner_;
|
||||
std::uint64_t round_;
|
||||
SubscriptionHandle handle_;
|
||||
};
|
||||
|
||||
// Deliver a command to every current subscriber; hooks may respond, unsubscribe or
|
||||
// subscribe re-entrantly, so iterate over a snapshot and re-check membership.
|
||||
void notify(IdChangeCommand command, const Identifier& id, bool expect_response) {
|
||||
std::vector<SubscriptionHandle> handles;
|
||||
for (const auto& entry : subscriptions) handles.push_back(entry.first);
|
||||
if (expect_response && round) round->outstanding.insert(handles.begin(), handles.end());
|
||||
const auto round_id = round ? round->id : 0;
|
||||
++notify_depth;
|
||||
for (auto handle : handles) {
|
||||
// An abort raised by an earlier hook ends this round: nobody else gets PREPARE/COMMIT.
|
||||
if (expect_response && (!round || round->id != round_id)) break;
|
||||
auto it = subscriptions.find(handle);
|
||||
if (it == subscriptions.end()) {
|
||||
if (round && round->id == round_id) round->outstanding.erase(handle);
|
||||
continue;
|
||||
}
|
||||
std::shared_ptr<IdChangeResponder> responder;
|
||||
if (expect_response) responder = std::make_shared<Responder>(weak_from_this(), round_id, handle);
|
||||
IdChangeHook hook = it->second.hook;
|
||||
ByteBuffer data = it->second.data;
|
||||
hook(command, id, data, responder);
|
||||
}
|
||||
--notify_depth;
|
||||
if (expect_response && notify_depth == 0 && round && round->id == round_id) {
|
||||
if (round->outstanding.empty()) advance();
|
||||
else arm_round_timer();
|
||||
}
|
||||
}
|
||||
|
||||
void arm_round_timer() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
runtime.schedule(response_timeout, [this](Clock::time_point) { on_round_timeout(); }, &round_timer_scope);
|
||||
}
|
||||
|
||||
void try_start() {
|
||||
if (!pending_trigger || locked() || round) return;
|
||||
const auto* next = pool.next_valid(runtime.now());
|
||||
pending_trigger = false;
|
||||
if (!next) return; // nothing to change to; trigger() already reported this
|
||||
round = std::make_unique<Round>(Round {++round_counter, IdChangeCommand::PREPARE, next->digest, {}});
|
||||
notify(IdChangeCommand::PREPARE, round->new_identifier, true); // advances or arms the timer itself
|
||||
}
|
||||
|
||||
void handle_response(std::uint64_t round_id, SubscriptionHandle handle, bool return_code) {
|
||||
if (!round || round->id != round_id) return;
|
||||
if (round->outstanding.erase(handle) == 0) return;
|
||||
if (!return_code) {
|
||||
if (round->phase == IdChangeCommand::PREPARE) { abort(); return; }
|
||||
++stats.commit_failures; // COMMIT cannot be rolled back (Figure 11); recorded
|
||||
}
|
||||
if (round->outstanding.empty() && notify_depth == 0) advance();
|
||||
}
|
||||
|
||||
void advance() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
if (round->phase == IdChangeCommand::PREPARE) {
|
||||
round->phase = IdChangeCommand::COMMIT;
|
||||
pool.select(round->new_identifier);
|
||||
notify(IdChangeCommand::COMMIT, round->new_identifier, true); // finishes or arms the timer
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
void finish() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
const Identifier id = round->new_identifier;
|
||||
round.reset();
|
||||
++stats.committed;
|
||||
if (committed) committed(id);
|
||||
try_start(); // a trigger queued during this round
|
||||
}
|
||||
|
||||
void abort() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
const Identifier id = round->new_identifier;
|
||||
round.reset();
|
||||
++stats.aborted;
|
||||
notify(IdChangeCommand::ABORT, id, false); // Figures 12/13
|
||||
}
|
||||
|
||||
void on_round_timeout() {
|
||||
if (!round) return;
|
||||
++stats.timed_out;
|
||||
if (round->phase == IdChangeCommand::PREPARE) {
|
||||
abort();
|
||||
} else {
|
||||
stats.commit_failures += static_cast<unsigned>(round->outstanding.size());
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
void arm_lock_timer() {
|
||||
runtime.cancel(&lock_timer_scope);
|
||||
if (locks.empty()) return;
|
||||
Clock::time_point earliest = locks.begin()->second;
|
||||
for (const auto& lock : locks) earliest = std::min(earliest, lock.second);
|
||||
runtime.schedule(earliest, [this](Clock::time_point) { on_lock_timer(); }, &lock_timer_scope);
|
||||
}
|
||||
|
||||
void on_lock_timer() {
|
||||
const auto now = runtime.now();
|
||||
for (auto it = locks.begin(); it != locks.end();) {
|
||||
if (it->second <= now) it = locks.erase(it); else ++it;
|
||||
}
|
||||
arm_lock_timer();
|
||||
try_start();
|
||||
}
|
||||
};
|
||||
|
||||
IdentityManager::IdentityManager(Runtime& rt, CertificatePool& pool) : impl_(std::make_shared<Impl>(rt, pool)) {}
|
||||
|
||||
IdentityManager::~IdentityManager() {
|
||||
impl_->runtime.cancel(&impl_->round_timer_scope);
|
||||
impl_->runtime.cancel(&impl_->lock_timer_scope);
|
||||
impl_->round.reset();
|
||||
impl_->notify(IdChangeCommand::DEREG, impl_->current(), false); // Figure 15
|
||||
impl_->subscriptions.clear();
|
||||
}
|
||||
|
||||
SubscriptionHandle IdentityManager::subscribe(IdChangeHook hook, ByteBuffer subscriber_data) {
|
||||
const auto handle = impl_->next_subscription++;
|
||||
impl_->subscriptions.emplace(handle, Impl::Subscription {std::move(hook), std::move(subscriber_data)});
|
||||
return handle;
|
||||
}
|
||||
|
||||
Result IdentityManager::unsubscribe(SubscriptionHandle handle) {
|
||||
if (impl_->subscriptions.erase(handle) == 0) return Result::invalid_argument;
|
||||
if (impl_->round && impl_->round->outstanding.erase(handle) && impl_->round->outstanding.empty() &&
|
||||
impl_->notify_depth == 0)
|
||||
impl_->advance();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result IdentityManager::trigger() {
|
||||
if (!impl_->pool.next_valid(impl_->runtime.now())) return Result::rejected;
|
||||
impl_->pending_trigger = true;
|
||||
impl_->try_start();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
LockHandle IdentityManager::lock(std::uint8_t duration_seconds) {
|
||||
const auto handle = impl_->next_lock++;
|
||||
impl_->locks[handle] = impl_->runtime.now() + std::chrono::seconds(duration_seconds);
|
||||
impl_->arm_lock_timer();
|
||||
if (duration_seconds == 0) impl_->on_lock_timer(); // released at once
|
||||
return handle;
|
||||
}
|
||||
|
||||
Result IdentityManager::unlock(LockHandle handle) {
|
||||
if (impl_->locks.erase(handle) == 0) return Result::invalid_argument;
|
||||
impl_->arm_lock_timer();
|
||||
impl_->try_start();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Identifier IdentityManager::current_identifier() const { return impl_->current(); }
|
||||
bool IdentityManager::change_pending() const { return static_cast<bool>(impl_->round); }
|
||||
void IdentityManager::set_response_timeout(Clock::duration timeout) { impl_->response_timeout = timeout; }
|
||||
void IdentityManager::on_committed(std::function<void(const Identifier&)> callback) { impl_->committed = std::move(callback); }
|
||||
const IdentityManager::Statistics& IdentityManager::statistics() const { return impl_->stats; }
|
||||
bool IdentityManager::locked() const { return impl_->locked(); }
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <microbu_v2x/its_g5_frame.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
namespace microbu_v2x::its_g5 {
|
||||
namespace {
|
||||
constexpr std::uint8_t snap[] = {0xaa, 0xaa, 0x03, 0, 0, 0, 0x89, 0x47};
|
||||
}
|
||||
Result encode_frame(const AlDataRequest& request, std::uint16_t sequence, vanetza::ByteBuffer& out) {
|
||||
if (validate(request, maximum_gnpdu) != Result::accepted || sequence > 4095)
|
||||
return Result::invalid_argument;
|
||||
out.assign(34 + request.data.size(), 0);
|
||||
out[0] = 0x88; // QoS Data; To DS=From DS=0 (OCB), no encryption at MAC.
|
||||
std::copy(request.destination.octets.begin(), request.destination.octets.end(), out.begin() + 4);
|
||||
std::copy(request.source.octets.begin(), request.source.octets.end(), out.begin() + 10);
|
||||
std::fill(out.begin() + 16, out.begin() + 22, 0xff); // wildcard BSSID
|
||||
out[22] = (sequence << 4) & 0xff; out[23] = sequence >> 4;
|
||||
out[24] = request.priority; // TID carries IEEE 802.1D user priority.
|
||||
std::copy(std::begin(snap), std::end(snap), out.begin() + 26);
|
||||
std::copy(request.data.begin(), request.data.end(), out.begin() + 34);
|
||||
return Result::accepted;
|
||||
}
|
||||
Result decode_frame(const std::uint8_t* data, std::size_t length, bool fcs, AlDataIndication& out) {
|
||||
if (!data || length < 34 + (fcs ? 4u : 0u)) return Result::invalid_argument;
|
||||
if (fcs) length -= 4;
|
||||
// Only non-fragmented, unprotected QoS Data with the OCB three-address
|
||||
// layout. Reject A-MSDU/HT-control rather than misinterpreting their offsets.
|
||||
if (data[0] != 0x88 || (data[1] & 0xc7) || (data[22] & 0x0f) ||
|
||||
(data[24] & 0x80) || !std::all_of(data + 16, data + 22, [](auto b) { return b == 0xff; }))
|
||||
return Result::unsupported;
|
||||
if (!std::equal(std::begin(snap), std::end(snap), data + 26)) return Result::unsupported;
|
||||
if (length == 34 || length - 34 > maximum_gnpdu) return Result::invalid_argument;
|
||||
std::copy(data + 4, data + 10, out.destination.octets.begin());
|
||||
std::copy(data + 10, data + 16, out.source.octets.begin());
|
||||
out.data.assign(data + 34, data + length);
|
||||
return Result::accepted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "local_security.hpp"
|
||||
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||
#include <microbu_v2x/security_backend.hpp>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
|
||||
/// One NVS blob for the keys of the local software module.
|
||||
class NvsKeyStorage final : public security::KeyStorage {
|
||||
public:
|
||||
bool load(vanetza::ByteBuffer& out) override {
|
||||
nvs_handle_t handle;
|
||||
if (nvs_open(local_key_namespace, NVS_READONLY, &handle) != ESP_OK) return false;
|
||||
std::size_t size = 0;
|
||||
bool ok = nvs_get_blob(handle, local_key_name, nullptr, &size) == ESP_OK && size > 0;
|
||||
if (ok) {
|
||||
out.resize(size);
|
||||
ok = nvs_get_blob(handle, local_key_name, out.data(), &size) == ESP_OK;
|
||||
}
|
||||
nvs_close(handle);
|
||||
return ok;
|
||||
}
|
||||
bool save(const vanetza::ByteBuffer& blob) override {
|
||||
nvs_handle_t handle;
|
||||
if (nvs_open(local_key_namespace, NVS_READWRITE, &handle) != ESP_OK) return false;
|
||||
const bool ok = nvs_set_blob(handle, local_key_name, blob.data(), blob.size()) == ESP_OK &&
|
||||
nvs_commit(handle) == ESP_OK;
|
||||
nvs_close(handle);
|
||||
return ok;
|
||||
}
|
||||
};
|
||||
|
||||
/// The SE051's role in software on the ESP32-C5: keys in NVS, signatures through PSA.
|
||||
class LocalSecurityModule final : public security::SecurityModule {
|
||||
public:
|
||||
security::KeyId generate_key(security::KeyType type) override { return module_.generate_key(type); }
|
||||
std::optional<security::KeyId> import_key(const security::KeyPair& pair) override { return module_.import_key(pair); }
|
||||
std::optional<security::PublicKey> public_key(security::KeyId id) const override { return module_.public_key(id); }
|
||||
security::Signature sign_digest(security::KeyId id, const vanetza::ByteBuffer& digest) override {
|
||||
return module_.sign_digest(id, digest);
|
||||
}
|
||||
bool destroy_key(security::KeyId id) override { return module_.destroy_key(id); }
|
||||
|
||||
private:
|
||||
BackendMbedTls psa_;
|
||||
NvsKeyStorage storage_;
|
||||
security::SoftwareSecurityModule module_ {psa_, psa_, storage_};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<vanetza::security::Backend> make_local_security_backend() { return std::make_unique<BackendMbedTls>(); }
|
||||
|
||||
std::unique_ptr<security::SecurityModule> make_local_security_module() { return std::make_unique<LocalSecurityModule>(); }
|
||||
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <memory>
|
||||
|
||||
// The implementations on the ESP32 itself (local_security.cpp): PSA crypto for the public operations, and the
|
||||
// software security module with its keys in NVS.
|
||||
namespace microbu_v2x {
|
||||
std::unique_ptr<vanetza::security::Backend> make_local_security_backend();
|
||||
std::unique_ptr<security::SecurityModule> make_local_security_module();
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,137 @@
|
||||
// Management-plane bindings: MN-SAP (TS 102 723-4, TS 103 836-4-1 Annex K,
|
||||
// TS 103 175 clause 8.3), MF-SAP (TS 102 723-5, TS 103 175 clause 8.4) and
|
||||
// MI-SAP (TS 102 723-3, TS 103 175 clause 8.2). Values only ever come from the
|
||||
// providers the application registers.
|
||||
#include <microbu_v2x/mf_sap.hpp>
|
||||
#include <microbu_v2x/mi_sap.hpp>
|
||||
#include <microbu_v2x/mn_sap.hpp>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
// Shared GET/SET machinery: format check, access check, then the provider.
|
||||
template<class No, class Param, class Error, class Provider>
|
||||
void get_all(Provider* provider, const std::vector<No>& numbers, bool (*in_format)(No, std::uint32_t),
|
||||
std::vector<Param>& out, std::vector<Error>& errors) {
|
||||
for (auto no : numbers) {
|
||||
std::uint32_t value = 0;
|
||||
auto status = provider ? provider->get(no, value) : MN_SAP::ErrStatus::UNSUPPORTED;
|
||||
if (status == MN_SAP::ErrStatus::SUCCESS && !in_format(no, value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
|
||||
if (status == MN_SAP::ErrStatus::SUCCESS) out.push_back(Param {no, value});
|
||||
else errors.push_back(Error {no, status});
|
||||
}
|
||||
}
|
||||
template<class No, class Param, class Error, class Provider>
|
||||
void set_all(Provider* provider, const std::vector<Param>& params, bool (*in_format)(No, std::uint32_t),
|
||||
bool (*writable)(No), std::vector<Error>& errors) {
|
||||
for (const auto& param : params) {
|
||||
MN_SAP::ErrStatus status;
|
||||
if (!writable(param.no)) status = MN_SAP::ErrStatus::READ_ONLY;
|
||||
else if (!in_format(param.no, param.value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
|
||||
else status = provider ? provider->set(param.no, param.value) : MN_SAP::ErrStatus::UNSUPPORTED;
|
||||
if (status != MN_SAP::ErrStatus::SUCCESS) errors.push_back(Error {param.no, status});
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace MN_SAP {
|
||||
Result CORE_MMT_response_apply(Stack& stack, const CORE_MMT_response& response) {
|
||||
if (!response.time && !response.local_position_vector && !response.geonetworking_address && !response.tc_mapping)
|
||||
return Result::invalid_argument; // clause K.3: at least one parameter is present
|
||||
if (response.time) {
|
||||
const auto result = stack.advance(*response.time);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.local_position_vector) {
|
||||
const auto result = stack.update_position(*response.local_position_vector);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.geonetworking_address) {
|
||||
const auto result = stack.set_address(*response.geonetworking_address);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.tc_mapping) return Result::unsupported; // fixed TS 102 687 mapping in this port
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
bool n_param_value_in_format(N_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 10 formats
|
||||
case N_Param_No::GLOBAL_CBR:
|
||||
case N_Param_No::LOCAL_CBR: return value <= 100;
|
||||
case N_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case N_Param_No::AVAILABLE_RESOURCE:
|
||||
case N_Param_No::IDLE_TIME: return value <= 0xffff;
|
||||
case N_Param_No::LAST_TRANSMIT_TIME: return true;
|
||||
case N_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31; // bits 5..7 reserved
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool n_param_writable(N_Param_No no) {
|
||||
return no == N_Param_No::CHANNEL_NUMBER || no == N_Param_No::IDLE_TIME || no == N_Param_No::TX_POWER_LEVEL_LIMIT;
|
||||
}
|
||||
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider* provider, const MN_GET_request& request) {
|
||||
MN_GET_confirm confirm {request.nt_id, request.command_ref, {}, {}};
|
||||
get_all<N_Param_No, N_Param, N_Error>(provider, request.n_param_no, n_param_value_in_format, confirm.n_param, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider* provider, const MN_SET_request& request) {
|
||||
MN_SET_confirm confirm {request.nt_id, request.command_ref, {}};
|
||||
set_all<N_Param_No, N_Param, N_Error>(provider, request.n_param, n_param_value_in_format, n_param_writable, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
} // namespace MN_SAP
|
||||
|
||||
namespace MF_SAP {
|
||||
bool f_param_value_in_format(F_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 13 formats
|
||||
case F_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case F_Param_No::AVAILABLE_RESOURCE: return value <= 0xffff;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink* sink, const MF_SET_request& request) {
|
||||
MF_SET_confirm confirm {request.fac_id, request.command_ref, {}};
|
||||
for (const auto& param : request.f_param) {
|
||||
ErrStatus status;
|
||||
if (!f_param_value_in_format(param.no, param.value)) status = ErrStatus::INVALID_VALUE;
|
||||
else status = sink ? sink->set(param.no, param.value) : ErrStatus::UNSUPPORTED;
|
||||
if (status != ErrStatus::SUCCESS) confirm.errors.push_back(F_Error {param.no, status});
|
||||
}
|
||||
return confirm;
|
||||
}
|
||||
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink* sink, const MF_COMMAND_request& request) {
|
||||
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED};
|
||||
return sink->command(request);
|
||||
}
|
||||
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink* sink, const MF_REQUEST_request& request) {
|
||||
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED, {}};
|
||||
return sink->request(request);
|
||||
}
|
||||
} // namespace MF_SAP
|
||||
|
||||
namespace MI_SAP {
|
||||
bool i_param_value_in_format(I_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 5 formats
|
||||
case I_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case I_Param_No::LOCAL_CBR: return value <= 100;
|
||||
case I_Param_No::MESSAGE_LENGTH: return value <= 0xff;
|
||||
case I_Param_No::LAST_TRANSMIT_TIME: return true;
|
||||
case I_Param_No::IDLE_TIME: return value <= 0xffff;
|
||||
case I_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool i_param_writable(I_Param_No no) {
|
||||
return no == I_Param_No::CHANNEL_NUMBER || no == I_Param_No::IDLE_TIME || no == I_Param_No::TX_POWER_LEVEL_LIMIT;
|
||||
}
|
||||
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider* provider, const MI_GET_request& request) {
|
||||
MI_GET_confirm confirm {request.mac_id, request.command_ref, {}, {}};
|
||||
get_all<I_Param_No, I_Param, I_Error>(provider, request.i_param_no, i_param_value_in_format, confirm.i_param, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider* provider, const MI_SET_request& request) {
|
||||
MI_SET_confirm confirm {request.mac_id, request.command_ref, {}};
|
||||
set_all<I_Param_No, I_Param, I_Error>(provider, request.i_param, i_param_value_in_format, i_param_writable, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
} // namespace MI_SAP
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,50 @@
|
||||
#include <microbu_v2x/nvs_credential_store.hpp>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
namespace {
|
||||
// nvs_open/nvs_close around one operation; NVS handles are cheap and the store is stateless
|
||||
class Handle {
|
||||
public:
|
||||
Handle(const std::string& ns, nvs_open_mode_t mode) { error_ = nvs_open(ns.c_str(), mode, &handle_); }
|
||||
~Handle() { if (error_ == ESP_OK) nvs_close(handle_); }
|
||||
esp_err_t error() const { return error_; }
|
||||
nvs_handle_t get() const { return handle_; }
|
||||
private:
|
||||
nvs_handle_t handle_ = 0;
|
||||
esp_err_t error_ = ESP_FAIL;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Result NvsCredentialStore::save(const StoredCredentials& credentials) {
|
||||
const ByteBuffer bundle = encode(credentials);
|
||||
Handle nvs(namespace_, NVS_READWRITE);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected;
|
||||
if (nvs_set_blob(nvs.get(), key_.c_str(), bundle.data(), bundle.size()) != ESP_OK) return Result::resource_limit;
|
||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
Result NvsCredentialStore::load(StoredCredentials& credentials) {
|
||||
Handle nvs(namespace_, NVS_READONLY);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected; // no such namespace yet: nothing stored
|
||||
std::size_t size = 0;
|
||||
const esp_err_t probe = nvs_get_blob(nvs.get(), key_.c_str(), nullptr, &size);
|
||||
if (probe == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
|
||||
if (probe != ESP_OK || size == 0) return Result::rejected;
|
||||
ByteBuffer bundle(size);
|
||||
if (nvs_get_blob(nvs.get(), key_.c_str(), bundle.data(), &size) != ESP_OK) return Result::rejected;
|
||||
bundle.resize(size);
|
||||
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
|
||||
}
|
||||
|
||||
Result NvsCredentialStore::erase() {
|
||||
Handle nvs(namespace_, NVS_READWRITE);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected;
|
||||
const esp_err_t error = nvs_erase_key(nvs.get(), key_.c_str());
|
||||
if (error == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
|
||||
if (error != ESP_OK) return Result::rejected;
|
||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,996 @@
|
||||
// TS 102 941 V2.2.1 enrolment/authorization messages on the upstream
|
||||
// EtsiTs103097Data wrapper. See pki.hpp for the clause map.
|
||||
#include <microbu_v2x/pki.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/asn1/security/CtlCommand.h>
|
||||
#include <vanetza/asn1/security/CtlEntry.h>
|
||||
#include <vanetza/asn1/security/EtsiTs103097Certificate.h>
|
||||
#include <vanetza/asn1/security/InnerAtRequest.h>
|
||||
#include <vanetza/asn1/security/InnerEcRequest.h>
|
||||
#include <vanetza/asn1/security/PublicEncryptionKey.h>
|
||||
#include <vanetza/asn1/security/PublicVerificationKey.h>
|
||||
#include <vanetza/asn1/security/SharedAtRequest.h>
|
||||
#include <vanetza/asn1/security/ValidityPeriod.h>
|
||||
#include <vanetza/security/sha.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/asn1_conversions.hpp>
|
||||
#include <vanetza/security/v3/hash.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
using SecuredData = v3::SecuredMessage; // EtsiTs103097Data wrapper
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t aes_key_length = 16;
|
||||
constexpr std::size_t nonce_length = 12;
|
||||
constexpr std::size_t tag_length = 16;
|
||||
|
||||
ByteBuffer octets(const OCTET_STRING_t& s) { return ByteBuffer(s.buf, s.buf + s.size); }
|
||||
|
||||
// EccP256CurvePoint -> PublicKey (x-only points carry no usable y and are refused)
|
||||
std::optional<PublicKey> point_to_key(const Vanetza_Security_EccP256CurvePoint& point, KeyType type) {
|
||||
PublicKey key;
|
||||
key.type = type;
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||
key.compression = KeyCompression::Y0; key.x = octets(point.choice.compressed_y_0); break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||
key.compression = KeyCompression::Y1; key.x = octets(point.choice.compressed_y_1); break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
|
||||
key.compression = KeyCompression::NoCompression;
|
||||
key.x = octets(point.choice.uncompressedP256.x); key.y = octets(point.choice.uncompressedP256.y); break;
|
||||
default: return std::nullopt;
|
||||
}
|
||||
if (key.x.size() != 32) return std::nullopt;
|
||||
return key;
|
||||
}
|
||||
|
||||
// uncompressed form for backends that need y (ECDH peer key)
|
||||
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||
if (key.compression == KeyCompression::NoCompression) return key;
|
||||
auto point = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
|
||||
if (!point) return std::nullopt;
|
||||
PublicKey out = key;
|
||||
out.compression = KeyCompression::NoCompression;
|
||||
out.y = point->y;
|
||||
return out;
|
||||
}
|
||||
|
||||
PublicKey compressed(const PublicKey& key) {
|
||||
if (key.compression != KeyCompression::NoCompression || key.y.empty()) return key;
|
||||
PublicKey out = key;
|
||||
out.compression = (key.y.back() & 1) ? KeyCompression::Y1 : KeyCompression::Y0;
|
||||
out.y.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
void fill_point(Vanetza_Security_EccP256CurvePoint& point, const PublicKey& key) {
|
||||
point = v3::to_asn1(make_ecc_point(compressed(key)));
|
||||
}
|
||||
|
||||
void fill_verification_key(Vanetza_Security_PublicVerificationKey& out, const PublicKey& key) {
|
||||
if (key.type == KeyType::BrainpoolP256r1) {
|
||||
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1;
|
||||
fill_point(out.choice.ecdsaBrainpoolP256r1, key);
|
||||
} else {
|
||||
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256;
|
||||
fill_point(out.choice.ecdsaNistP256, key);
|
||||
}
|
||||
}
|
||||
|
||||
void fill_encryption_key(Vanetza_Security_PublicEncryptionKey& out, const PublicKey& key) {
|
||||
out.supportedSymmAlg = Vanetza_Security_SymmAlgorithm_aes128Ccm;
|
||||
if (key.type == KeyType::BrainpoolP256r1) {
|
||||
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesBrainpoolP256r1;
|
||||
fill_point(out.publicKey.choice.eciesBrainpoolP256r1, key);
|
||||
} else {
|
||||
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256;
|
||||
fill_point(out.publicKey.choice.eciesNistP256, key);
|
||||
}
|
||||
}
|
||||
|
||||
void fill_permissions(Vanetza_Security_CertificateSubjectAttributes& attributes, const Permissions& permissions) {
|
||||
if (permissions.empty()) return;
|
||||
attributes.appPermissions = v3::asn1::allocate<Vanetza_Security_SequenceOfPsidSsp>();
|
||||
for (const auto& permission : permissions) {
|
||||
auto* entry = v3::asn1::allocate<Vanetza_Security_PsidSsp>();
|
||||
entry->psid = permission.first;
|
||||
if (!permission.second.empty()) {
|
||||
entry->ssp = v3::asn1::allocate<Vanetza_Security_ServiceSpecificPermissions>();
|
||||
entry->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
|
||||
v3::assign(&entry->ssp->choice.bitmapSsp, permission.second);
|
||||
}
|
||||
ASN_SEQUENCE_ADD(attributes.appPermissions, entry);
|
||||
}
|
||||
}
|
||||
|
||||
// IEEE 1609.2 clause 5.3.1: Hash(Hash(tbsData) || Hash(signer certificate or empty string))
|
||||
ByteBuffer message_digest(Backend& backend, HashAlgorithm hash, const ByteBuffer& tbs, const Certificate* signer) {
|
||||
if (signer) return v3::calculate_message_hash(backend, hash, tbs, *signer);
|
||||
ByteBuffer concat = backend.calculate_hash(hash, tbs);
|
||||
const ByteBuffer empty = backend.calculate_hash(hash, ByteBuffer {});
|
||||
concat.insert(concat.end(), empty.begin(), empty.end());
|
||||
return backend.calculate_hash(hash, concat);
|
||||
}
|
||||
|
||||
// Fill the common header of a signed structure (TS 102 941: psid 623, generationTime only).
|
||||
void prepare_signed(SecuredData& data, HashAlgorithm hash, Clock::time_point now, const Certificate* signer) {
|
||||
data.set_hash_id(hash);
|
||||
data.set_its_aid(aid::SCR);
|
||||
data.set_generation_time(v2::convert_time64(now));
|
||||
if (signer) {
|
||||
const auto digest = signer->calculate_digest();
|
||||
if (digest) data.set_signer_identifier(*digest); else data.set_signer_identifier_self();
|
||||
} else {
|
||||
data.set_signer_identifier_self();
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> finish_signed(Backend& backend, SecuredData& data, HashAlgorithm hash, const Signer& sign,
|
||||
const Certificate* signer) {
|
||||
try {
|
||||
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||
data.set_signature(sign(digest));
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer psk_id_input(const std::array<std::uint8_t, aes_key_length>& key) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_SymmetricEncryptionKey> wrapper(asn_DEF_Vanetza_Security_SymmetricEncryptionKey);
|
||||
wrapper->present = Vanetza_Security_SymmetricEncryptionKey_PR_aes128Ccm;
|
||||
OCTET_STRING_fromBuf(&wrapper->choice.aes128Ccm, reinterpret_cast<const char*>(key.data()), key.size());
|
||||
return wrapper.encode();
|
||||
}
|
||||
|
||||
std::array<std::uint8_t, 16> left16(const ByteBuffer& in) {
|
||||
std::array<std::uint8_t, 16> out {};
|
||||
std::copy_n(in.begin(), std::min<std::size_t>(16, in.size()), out.begin());
|
||||
return out;
|
||||
}
|
||||
|
||||
// InnerEcResponse / InnerAtResponse share the layout: requestHash, responseCode, certificate OPTIONAL
|
||||
template<class Inner>
|
||||
Result read_inner_response(const Inner& inner, const RequestContext& context, std::uint8_t& code,
|
||||
std::optional<Certificate>& certificate) {
|
||||
certificate.reset();
|
||||
if (inner.requestHash.size != 16 || std::memcmp(inner.requestHash.buf, context.request_hash.data(), 16) != 0)
|
||||
return Result::rejected; // the response answers another request
|
||||
code = static_cast<std::uint8_t>(inner.responseCode);
|
||||
if (inner.certificate) {
|
||||
// asn1c forward-declares a distinct struct tag for this member; the object it points to is
|
||||
// decoded with asn_DEF_Vanetza_Security_EtsiTs103097Certificate, i.e. an EtsiTs103097Certificate_t.
|
||||
Certificate cert(*reinterpret_cast<const Vanetza_Security_EtsiTs103097Certificate_t*>(inner.certificate));
|
||||
if (!cert.validate()) return Result::rejected;
|
||||
certificate = std::move(cert);
|
||||
} else if (code == 0) {
|
||||
return Result::rejected; // clause 6.2.3.2.2: a positive response returns a certificate
|
||||
}
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
// Decrypt, verify the authority signature and hand back the EtsiTs102941Data
|
||||
std::optional<ByteBuffer> open_response(Backend& backend, EciesBackend& ecies, const RequestContext& context,
|
||||
const Certificate& authority, const ByteBuffer& encoded) {
|
||||
auto signed_bytes = decrypt_with_psk(ecies, context.aes_key, encoded);
|
||||
if (!signed_bytes) return std::nullopt;
|
||||
return verify_signed(backend, *signed_bytes, nullptr, &authority, aid::SCR);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ByteBuffer kdf2_sha256(Backend& backend, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length) {
|
||||
ByteBuffer derived;
|
||||
for (std::uint32_t counter = 1; derived.size() < length; ++counter) {
|
||||
ByteBuffer input = shared_secret;
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 24));
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 16));
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 8));
|
||||
input.push_back(static_cast<std::uint8_t>(counter));
|
||||
input.insert(input.end(), kdp.begin(), kdp.end());
|
||||
const auto block = backend.calculate_hash(HashAlgorithm::SHA256, input);
|
||||
derived.insert(derived.end(), block.begin(), block.end());
|
||||
}
|
||||
derived.resize(length);
|
||||
return derived;
|
||||
}
|
||||
|
||||
std::optional<EncryptedKey> ecies_encrypt_key(Backend& backend, EciesBackend& ecies, const PublicKey& recipient,
|
||||
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key) {
|
||||
const auto peer = uncompressed(recipient);
|
||||
if (!peer || (peer->type != KeyType::NistP256 && peer->type != KeyType::BrainpoolP256r1)) return std::nullopt;
|
||||
try {
|
||||
const KeyPair ephemeral = ecies.generate_key(peer->type);
|
||||
const auto secret = ecies.ecdh_x(ephemeral.priv, *peer);
|
||||
if (!secret) return std::nullopt;
|
||||
// K1 (16 octets, key encryption) || K2 (32 octets, MAC key)
|
||||
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||
EncryptedKey out;
|
||||
out.v = ephemeral.pub;
|
||||
ByteBuffer c(aes_key_length);
|
||||
for (std::size_t i = 0; i < aes_key_length; ++i) c[i] = k[i] ^ aes_key[i];
|
||||
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||
if (tag.size() < tag_length) return std::nullopt;
|
||||
out.c = left16(c);
|
||||
out.t = left16(tag);
|
||||
return out;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(Backend& backend, EciesBackend& ecies,
|
||||
const PrivateKey& recipient, const ByteBuffer& p1,
|
||||
const EncryptedKey& encrypted) {
|
||||
const auto peer = uncompressed(encrypted.v);
|
||||
if (!peer) return std::nullopt;
|
||||
try {
|
||||
const auto secret = ecies.ecdh_x(recipient, *peer);
|
||||
if (!secret) return std::nullopt;
|
||||
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||
const ByteBuffer c(encrypted.c.begin(), encrypted.c.end());
|
||||
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||
if (tag.size() < tag_length) return std::nullopt;
|
||||
// constant-time comparison of the truncated tag
|
||||
unsigned diff = 0;
|
||||
for (std::size_t i = 0; i < tag_length; ++i) diff |= tag[i] ^ encrypted.t[i];
|
||||
if (diff != 0) return std::nullopt;
|
||||
std::array<std::uint8_t, 16> key {};
|
||||
for (std::size_t i = 0; i < aes_key_length; ++i) key[i] = k[i] ^ encrypted.c[i];
|
||||
return key;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- building blocks -------------------------------------------------------
|
||||
|
||||
Signer module_signer(security::SecurityModule& module, security::KeyId key) {
|
||||
return [&module, key](const ByteBuffer& digest) { return module.sign_digest(key, digest); };
|
||||
}
|
||||
|
||||
Signer key_signer(Backend& backend, PrivateKey key) {
|
||||
return [&backend, key = std::move(key)](const ByteBuffer& digest) { return backend.sign_digest(key, digest); };
|
||||
}
|
||||
|
||||
SigningKey signing_key(Backend& backend, const KeyPair& pair) { return {pair.pub, key_signer(backend, pair.priv)}; }
|
||||
|
||||
std::optional<ByteBuffer> sign_data(Backend& backend, Clock::time_point now, HashAlgorithm hash, const ByteBuffer& payload,
|
||||
const Signer& sign, const Certificate* signer) {
|
||||
SecuredData data = SecuredData::with_signed_data();
|
||||
prepare_signed(data, hash, now, signer);
|
||||
data.set_payload(payload);
|
||||
return finish_signed(backend, data, hash, sign, signer);
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> sign_external(Backend& backend, Clock::time_point now, const ByteBuffer& external_payload,
|
||||
const Signer& sign, const Certificate& signer) {
|
||||
SecuredData data = SecuredData::with_signed_data_hash();
|
||||
prepare_signed(data, HashAlgorithm::SHA256, now, &signer);
|
||||
data.set_external_payload_hash(calculate_sha256_digest(external_payload.data(), external_payload.size()));
|
||||
return finish_signed(backend, data, HashAlgorithm::SHA256, sign, &signer);
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> encrypt_for(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key) {
|
||||
const auto encryption_key = v3::get_public_encryption_key(*recipient.content());
|
||||
const auto recipient_id = recipient.calculate_digest();
|
||||
if (!encryption_key || !recipient_id) return std::nullopt;
|
||||
try {
|
||||
const ByteBuffer random = ecies.random(aes_key_length + nonce_length);
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
std::copy_n(random.begin(), aes_key_length, aes_key.begin());
|
||||
std::copy_n(random.begin() + aes_key_length, nonce_length, nonce.begin());
|
||||
ByteBuffer ciphertext;
|
||||
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||
// P1 = SHA-256 of the recipient certificate (IEEE 1609.2 clause 5.3.5, certRecipInfo)
|
||||
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||
const auto wrapped = ecies_encrypt_key(backend, ecies, *encryption_key, p1, aes_key);
|
||||
if (!wrapped) return std::nullopt;
|
||||
SecuredData data = SecuredData::with_encrypted_data();
|
||||
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
data.set_cert_recip_info(*recipient_id, wrapped->c, wrapped->t, compressed(wrapped->v));
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||
const ByteBuffer& plaintext) {
|
||||
try {
|
||||
const ByteBuffer random = ecies.random(nonce_length);
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
std::copy_n(random.begin(), nonce_length, nonce.begin());
|
||||
ByteBuffer ciphertext;
|
||||
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||
SecuredData data = SecuredData::with_encrypted_data();
|
||||
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
// pskRecipInfo = HashedId8 of the COER SymmetricEncryptionKey (IEEE 1609.2 clause 6.3.43)
|
||||
const ByteBuffer key_encoding = psk_id_input(aes_key);
|
||||
const HashedId8 psk_id = create_hashed_id8(calculate_sha256_digest(key_encoding.data(), key_encoding.size()));
|
||||
auto* recipient = v3::asn1::allocate<Vanetza_Security_RecipientInfo>();
|
||||
recipient->present = Vanetza_Security_RecipientInfo_PR_pskRecipInfo;
|
||||
OCTET_STRING_fromBuf(&recipient->choice.pskRecipInfo, reinterpret_cast<const char*>(psk_id.data()), psk_id.size());
|
||||
ASN_SEQUENCE_ADD(&data->content->choice.encryptedData.recipients.list, recipient);
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> decrypt_as_recipient(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||
const PrivateKey& encryption_key, const ByteBuffer& encoded,
|
||||
std::array<std::uint8_t, 16>* aes_key_out) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||
const auto own_id = recipient.calculate_digest();
|
||||
if (!own_id) return std::nullopt;
|
||||
const auto& recipients = data->content->choice.encryptedData.recipients.list;
|
||||
for (int i = 0; i < recipients.count; ++i) {
|
||||
const auto* info = recipients.array[i];
|
||||
if (!info || info->present != Vanetza_Security_RecipientInfo_PR_certRecipInfo) continue;
|
||||
const auto& cert_info = info->choice.certRecipInfo;
|
||||
if (cert_info.recipientId.size != 8 || std::memcmp(cert_info.recipientId.buf, own_id->data(), 8) != 0) continue;
|
||||
const Vanetza_Security_EciesP256EncryptedKey* ecies_key = nullptr;
|
||||
KeyType type = KeyType::NistP256;
|
||||
if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesNistP256) {
|
||||
ecies_key = &cert_info.encKey.choice.eciesNistP256;
|
||||
} else if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesBrainpoolP256r1) {
|
||||
ecies_key = &cert_info.encKey.choice.eciesBrainpoolP256r1;
|
||||
type = KeyType::BrainpoolP256r1;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (ecies_key->c.size != 16 || ecies_key->t.size != 16) continue;
|
||||
EncryptedKey wrapped;
|
||||
auto v = point_to_key(ecies_key->v, type);
|
||||
if (!v) continue;
|
||||
wrapped.v = *v;
|
||||
std::copy_n(ecies_key->c.buf, 16, wrapped.c.begin());
|
||||
std::copy_n(ecies_key->t.buf, 16, wrapped.t.begin());
|
||||
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||
const auto aes_key = ecies_decrypt_key(backend, ecies, encryption_key, p1, wrapped);
|
||||
if (!aes_key) return std::nullopt;
|
||||
ByteBuffer ciphertext;
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
ByteBuffer plaintext;
|
||||
if (!ecies.aes_ccm_decrypt(*aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||
if (aes_key_out) *aes_key_out = *aes_key;
|
||||
return plaintext;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||
const ByteBuffer& encoded) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||
if (!data.check_psk_match(aes_key)) return std::nullopt; // response is not for this request
|
||||
ByteBuffer ciphertext;
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
ByteBuffer plaintext;
|
||||
if (!ecies.aes_ccm_decrypt(aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> verify_signed(Backend& backend, const ByteBuffer& encoded, const PublicKey* self_key,
|
||||
const Certificate* signer, ItsAid expected_psid) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||
if (data.its_aid() != expected_psid || !data.generation_time()) return std::nullopt;
|
||||
const auto hash = data.hash_id();
|
||||
const auto signature = data.signature();
|
||||
if (hash == HashAlgorithm::Unspecified || !signature) return std::nullopt;
|
||||
const auto* signed_data = data->content->choice.signedData;
|
||||
// TS 102 941 V2.2.1 clause 6.2: management messages use only PSID and generationTime.
|
||||
const auto& header = signed_data->tbsData->headerInfo;
|
||||
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions)
|
||||
return std::nullopt;
|
||||
PublicKey key;
|
||||
if (signer) {
|
||||
const auto digest = signer->calculate_digest();
|
||||
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_digest || !digest ||
|
||||
signed_data->signer.choice.digest.size != 8 ||
|
||||
std::memcmp(signed_data->signer.choice.digest.buf, digest->data(), 8) != 0) return std::nullopt;
|
||||
const auto signer_key = v3::get_public_key(*signer->content());
|
||||
if (!signer_key) return std::nullopt;
|
||||
key = *signer_key;
|
||||
} else {
|
||||
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_self || !self_key) return std::nullopt;
|
||||
key = *self_key;
|
||||
}
|
||||
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||
if (!backend.verify_digest(key, digest, *signature)) return std::nullopt;
|
||||
auto payload = data.payload();
|
||||
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||
return ByteBuffer(view.begin(), view.end());
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.2.3.2 --------------------------------------------------
|
||||
|
||||
bool validate_issued_certificate(Backend& backend, const Certificate& certificate, const Certificate& issuer,
|
||||
const PublicKey& requested_key, Clock::time_point now, const Permissions& expected,
|
||||
bool enrolment) {
|
||||
try {
|
||||
if (certificate->version != 3 || certificate->type != Vanetza_Security_CertificateType_explicit ||
|
||||
certificate->toBeSigned.certIssuePermissions || !certificate->toBeSigned.appPermissions ||
|
||||
!certificate.valid_at_timepoint(now) || !issuer.valid_at_timepoint(now)) return false;
|
||||
const auto id = certificate->toBeSigned.id.present;
|
||||
if ((enrolment && id != Vanetza_Security_CertificateId_PR_name) ||
|
||||
(!enrolment && id != Vanetza_Security_CertificateId_PR_none)) return false;
|
||||
const auto digest = issuer.calculate_digest();
|
||||
const auto referenced = certificate.issuer_digest();
|
||||
if (!digest || !referenced || *digest != *referenced ||
|
||||
!security::verify_certificate_signature(backend, certificate, &issuer) ||
|
||||
!security::chain_permissions_consistent({&certificate, &issuer}) ||
|
||||
!security::region_within(certificate, issuer, true)) return false;
|
||||
const auto subject_time = microbu_v2x::security::validity_bounds(certificate);
|
||||
const auto assurance = certificate.assurance_level();
|
||||
const auto issuer_assurance = issuer.assurance_level();
|
||||
if (assurance) {
|
||||
if (!issuer_assurance) return false;
|
||||
const auto level = (*assurance >> 5) & 7;
|
||||
const auto issuer_level = (*issuer_assurance >> 5) & 7;
|
||||
if (level > issuer_level || (level == issuer_level &&
|
||||
((*assurance >> 2) & 7) > ((*issuer_assurance >> 2) & 7))) return false;
|
||||
}
|
||||
const auto issuer_time = microbu_v2x::security::validity_bounds(issuer);
|
||||
if (subject_time.start_validity < issuer_time.start_validity || subject_time.end_validity > issuer_time.end_validity)
|
||||
return false;
|
||||
if (certificate->toBeSigned.appPermissions->list.count != static_cast<int>(expected.size())) return false;
|
||||
for (const auto& permission : expected) {
|
||||
if (!certificate.valid_for_application(permission.first) ||
|
||||
v3::get_app_permissions(*certificate.content(), permission.first) != permission.second) return false;
|
||||
}
|
||||
const auto public_key = v3::get_public_key(*certificate.content());
|
||||
return public_key && security::same_public_key(*public_key, requested_key);
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Result build_enrolment_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||
const EnrolmentRequestParameters& params, const Certificate& ea, ByteBuffer& encoded,
|
||||
RequestContext& context) {
|
||||
if (params.its_id.empty() || !params.verification_key.sign || !params.outer_signer) return Result::invalid_argument;
|
||||
if (!v3::get_public_encryption_key(*ea.content())) return Result::invalid_argument;
|
||||
// 1. InnerEcRequest (certificateFormat ts103097v131 = 1)
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest> inner(asn_DEF_Vanetza_Security_InnerEcRequest);
|
||||
v3::assign(&inner->itsId, params.its_id);
|
||||
inner->certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
fill_verification_key(inner->publicKeys.verificationKey, params.verification_key.pub);
|
||||
fill_permissions(inner->requestedSubjectAttributes, params.app_permissions);
|
||||
if (!inner.validate()) return Result::invalid_argument;
|
||||
// 2. InnerEcRequestSignedForPop: self-signed with the new verification key
|
||||
auto pop = sign_data(backend, now, params.hash, inner.encode(), params.verification_key.sign, nullptr);
|
||||
if (!pop) return Result::security_unavailable;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentRequest;
|
||||
void* target = &mgmt->content.choice.enrolmentRequest;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *pop)) return Result::security_unavailable;
|
||||
// 3. Outer EtsiTs103097Data-Signed: self (canonical key) or digest of the current EC
|
||||
auto outer = sign_data(backend, now, params.hash, mgmt.encode(), params.outer_signer, params.current_ec);
|
||||
if (!outer) return Result::security_unavailable;
|
||||
// 4. EtsiTs103097Data-Encrypted for the EA
|
||||
auto encrypted = encrypt_for(backend, ecies, ea, *outer, context.aes_key);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
encoded = std::move(*encrypted);
|
||||
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result parse_enrolment_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& ea,
|
||||
const ByteBuffer& encoded, EnrolmentResponse& out) {
|
||||
auto mgmt_bytes = open_response(backend, ecies, context, ea, encoded);
|
||||
if (!mgmt_bytes) return Result::rejected;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentResponse) return Result::rejected;
|
||||
return read_inner_response(mgmt->content.choice.enrolmentResponse, context, out.response_code, out.certificate);
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.2.3.3 --------------------------------------------------
|
||||
|
||||
Result build_authorization_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||
const AuthorizationRequestParameters& params, const Certificate& ea,
|
||||
const Certificate& aa, ByteBuffer& encoded, RequestContext& context) {
|
||||
if (!params.ec || !params.ec_signer || !params.verification_key.sign || params.app_permissions.empty())
|
||||
return Result::invalid_argument;
|
||||
if (params.hash != HashAlgorithm::SHA256) return Result::unsupported; // extDataHash carries sha256HashedData
|
||||
if (!v3::get_public_encryption_key(*aa.content()) || (params.privacy && !v3::get_public_encryption_key(*ea.content())))
|
||||
return Result::invalid_argument;
|
||||
const auto ea_id = ea.calculate_digest();
|
||||
if (!ea_id) return Result::invalid_argument;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_authorizationRequest;
|
||||
auto& inner = mgmt->content.choice.authorizationRequest;
|
||||
// publicKeys: new verification key and optional encryption key
|
||||
fill_verification_key(inner.publicKeys.verificationKey, params.verification_key.pub);
|
||||
if (params.encryption_key) {
|
||||
inner.publicKeys.encryptionKey = v3::asn1::allocate<Vanetza_Security_PublicEncryptionKey>();
|
||||
fill_encryption_key(*inner.publicKeys.encryptionKey, *params.encryption_key);
|
||||
}
|
||||
// hmacKey: 32 random octets; keyTag = leftmost 16 octets of HMAC-SHA256(hmacKey, OER(publicKeys))
|
||||
ByteBuffer hmac_key;
|
||||
try { hmac_key = ecies.random(32); } catch (const std::exception&) { return Result::security_unavailable; }
|
||||
if (hmac_key.size() != 32) return Result::security_unavailable;
|
||||
v3::assign(&inner.hmacKey, hmac_key);
|
||||
ByteBuffer tag_input = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicVerificationKey, &inner.publicKeys.verificationKey);
|
||||
if (inner.publicKeys.encryptionKey) {
|
||||
const auto enc = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicEncryptionKey, inner.publicKeys.encryptionKey);
|
||||
tag_input.insert(tag_input.end(), enc.begin(), enc.end());
|
||||
}
|
||||
const auto key_tag = ecies.hmac_sha256(hmac_key, tag_input);
|
||||
if (key_tag.size() < 16) return Result::security_unavailable;
|
||||
// SharedAtRequest
|
||||
auto& shared = inner.sharedAtRequest;
|
||||
OCTET_STRING_fromBuf(&shared.eaId, reinterpret_cast<const char*>(ea_id->data()), ea_id->size());
|
||||
OCTET_STRING_fromBuf(&shared.keyTag, reinterpret_cast<const char*>(key_tag.data()), 16);
|
||||
shared.certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
fill_permissions(shared.requestedSubjectAttributes, params.app_permissions);
|
||||
if (params.validity_period) {
|
||||
shared.requestedSubjectAttributes.validityPeriod = v3::asn1::allocate<Vanetza_Security_ValidityPeriod>();
|
||||
shared.requestedSubjectAttributes.validityPeriod->start = v2::convert_time32(params.validity_period->first);
|
||||
shared.requestedSubjectAttributes.validityPeriod->duration.present = Vanetza_Security_Duration_PR_hours;
|
||||
shared.requestedSubjectAttributes.validityPeriod->duration.choice.hours = params.validity_period->second;
|
||||
}
|
||||
// EC signature over the SharedAtRequest (external payload), signer = digest of the EC
|
||||
const ByteBuffer shared_encoded = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_SharedAtRequest, &shared);
|
||||
auto ec_signed = sign_external(backend, now, shared_encoded, params.ec_signer, *params.ec);
|
||||
if (!ec_signed) return Result::security_unavailable;
|
||||
ByteBuffer ec_signature_bytes;
|
||||
if (params.privacy) {
|
||||
std::array<std::uint8_t, 16> throwaway {};
|
||||
auto encrypted = encrypt_for(backend, ecies, ea, *ec_signed, throwaway);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_encryptedEcSignature;
|
||||
void* target = &inner.ecSignature.choice.encryptedEcSignature;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *encrypted)) return Result::security_unavailable;
|
||||
} else {
|
||||
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_ecSignature;
|
||||
void* target = &inner.ecSignature.choice.ecSignature;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *ec_signed)) return Result::security_unavailable;
|
||||
}
|
||||
if (!mgmt.validate()) return Result::security_unavailable;
|
||||
ByteBuffer plaintext = mgmt.encode();
|
||||
if (params.include_pop) {
|
||||
auto pop = sign_data(backend, now, params.hash, plaintext, params.verification_key.sign, nullptr);
|
||||
if (!pop) return Result::security_unavailable;
|
||||
plaintext = std::move(*pop);
|
||||
} else {
|
||||
// EtsiTs103097Data unsecured envelope around the EtsiTs102941Data
|
||||
SecuredData envelope;
|
||||
envelope->protocolVersion = 3;
|
||||
envelope->content = v3::asn1::allocate<Vanetza_Security_Ieee1609Dot2Content>();
|
||||
envelope->content->present = Vanetza_Security_Ieee1609Dot2Content_PR_unsecuredData;
|
||||
v3::assign(&envelope->content->choice.unsecuredData, plaintext);
|
||||
plaintext = envelope.encode();
|
||||
}
|
||||
auto encrypted = encrypt_for(backend, ecies, aa, plaintext, context.aes_key);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
encoded = std::move(*encrypted);
|
||||
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result parse_authorization_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& aa,
|
||||
const ByteBuffer& encoded, AuthorizationResponse& out) {
|
||||
auto mgmt_bytes = open_response(backend, ecies, context, aa, encoded);
|
||||
if (!mgmt_bytes) return Result::rejected;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_authorizationResponse) return Result::rejected;
|
||||
return read_inner_response(mgmt->content.choice.authorizationResponse, context, out.response_code, out.certificate);
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.3: RCA trust list and revocation list -----------------------
|
||||
|
||||
namespace {
|
||||
void set_url(Vanetza_Security_Url_t& url, const std::string& text) {
|
||||
OCTET_STRING_fromBuf(&url, text.data(), text.size());
|
||||
}
|
||||
std::string get_url(const Vanetza_Security_Url_t& url) {
|
||||
return std::string(reinterpret_cast<const char*>(url.buf), url.size);
|
||||
}
|
||||
void set_hashed_id8(Vanetza_Security_HashedId8_t& target, const HashedId8& id) {
|
||||
OCTET_STRING_fromBuf(&target, reinterpret_cast<const char*>(id.data()), id.size());
|
||||
}
|
||||
std::optional<HashedId8> get_hashed_id8(const Vanetza_Security_HashedId8_t& source) {
|
||||
if (source.size != 8) return std::nullopt;
|
||||
HashedId8 id;
|
||||
std::copy_n(source.buf, 8, id.begin());
|
||||
return id;
|
||||
}
|
||||
// the certificate structure of an entry, decoded from COER into the inline member
|
||||
bool put_certificate(Vanetza_Security_EtsiTs103097Certificate_t& target, const ByteBuffer& coer) {
|
||||
void* into = ⌖
|
||||
return vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &into, coer);
|
||||
}
|
||||
|
||||
// TS 102 941 clauses 6.3.3 and 6.3.4. CTLs carry the issuer certificate.
|
||||
std::optional<ByteBuffer> sign_list(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
ItsAid psid, const ByteBuffer& mgmt) {
|
||||
if (!rca.valid_for_application(psid)) return std::nullopt; // TS 103 097 clause 7.2.3: CRL/CTL appPermissions
|
||||
SecuredData data = SecuredData::with_signed_data();
|
||||
const auto hash = rca->issuer.present == Vanetza_Security_IssuerIdentifier_PR_self &&
|
||||
rca->issuer.choice.self == Vanetza_Security_HashAlgorithm_sha384 ? HashAlgorithm::SHA384 : HashAlgorithm::SHA256;
|
||||
data.set_hash_id(hash);
|
||||
data.set_its_aid(psid);
|
||||
data.set_generation_time(v2::convert_time64(now));
|
||||
if (psid == aid::CRL) {
|
||||
const auto id = rca.calculate_digest();
|
||||
if (!id) return std::nullopt;
|
||||
data.set_signer_identifier(*id);
|
||||
} else data.set_signer_identifier(rca);
|
||||
data.set_payload(mgmt);
|
||||
return finish_signed(backend, data, hash, key_signer(backend, rca_key), &rca);
|
||||
}
|
||||
|
||||
// the EtsiTs102941Data of a list message that verifies as signed by rca with the given psid
|
||||
std::optional<ByteBuffer> open_list(Backend& backend, const ByteBuffer& message, const Certificate& rca, ItsAid psid) {
|
||||
SecuredData data;
|
||||
if (!data.decode(message) || data.encode() != message || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||
if (data.its_aid() != psid || !data.generation_time() ||
|
||||
(data.hash_id() != HashAlgorithm::SHA256 && data.hash_id() != HashAlgorithm::SHA384)) return std::nullopt;
|
||||
if (!rca.valid_for_application(psid)) return std::nullopt;
|
||||
const auto* signed_data = data->content->choice.signedData;
|
||||
const auto& header = signed_data->tbsData->headerInfo;
|
||||
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions) return std::nullopt;
|
||||
const auto& signer = signed_data->signer;
|
||||
if (signer.present == Vanetza_Security_SignerIdentifier_PR_certificate) {
|
||||
if (signer.choice.certificate.list.count != 1) return std::nullopt;
|
||||
const ByteBuffer inline_cert = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate,
|
||||
signer.choice.certificate.list.array[0]);
|
||||
if (inline_cert != rca.encode()) return std::nullopt;
|
||||
} else if (psid == aid::CRL && signer.present == Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||
const auto id = rca.calculate_digest();
|
||||
if (!id || signer.choice.digest.size != id->size() ||
|
||||
!std::equal(id->begin(), id->end(), signer.choice.digest.buf)) return std::nullopt;
|
||||
} else return std::nullopt;
|
||||
const auto signature = data.signature();
|
||||
const auto key = v3::get_public_key(*rca.content());
|
||||
if (!signature || !key) return std::nullopt;
|
||||
const auto digest = message_digest(backend, data.hash_id(), data.signing_payload(), &rca);
|
||||
try {
|
||||
if (!backend.verify_digest(*key, digest, *signature)) return std::nullopt;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto payload = data.payload();
|
||||
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||
return ByteBuffer(view.begin(), view.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<ByteBuffer> build_rca_ctl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
const TrustListEntries& entries, Time32 next_update, std::uint8_t ctl_sequence) {
|
||||
if (entries.dc.empty()) return std::nullopt;
|
||||
for (const auto& dc : entries.dc) if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||
auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||
ctl.version = 1; // clause 6.3.4: CtlFormat version 1
|
||||
ctl.nextUpdate = next_update;
|
||||
ctl.isFullCtl = 1;
|
||||
ctl.ctlSequence = ctl_sequence;
|
||||
const auto add = [&](Vanetza_Security_CtlEntry_PR kind) -> Vanetza_Security_CtlEntry_t& {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = kind;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
return command->choice.add;
|
||||
};
|
||||
for (const auto& ea : entries.ea) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_ea).choice.ea;
|
||||
if (!put_certificate(entry.eaCertificate, ea.certificate)) return std::nullopt;
|
||||
set_url(entry.aaAccessPoint, ea.access_point);
|
||||
if (!ea.its_access_point.empty()) {
|
||||
entry.itsAccessPoint = vanetza::asn1::allocate<Vanetza_Security_Url_t>();
|
||||
set_url(*entry.itsAccessPoint, ea.its_access_point);
|
||||
}
|
||||
}
|
||||
for (const auto& aa : entries.aa) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_aa).choice.aa;
|
||||
if (!put_certificate(entry.aaCertificate, aa.certificate)) return std::nullopt;
|
||||
set_url(entry.accessPoint, aa.access_point);
|
||||
}
|
||||
for (const auto& dc : entries.dc) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_dc).choice.dc;
|
||||
set_url(entry.url, dc.url);
|
||||
for (const auto& id : dc.certificates) {
|
||||
auto* item = vanetza::asn1::allocate<Vanetza_Security_HashedId8_t>();
|
||||
set_hashed_id8(*item, id);
|
||||
ASN_SEQUENCE_ADD(&entry.cert, item);
|
||||
}
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, rca, rca_key, aid::CTL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<RcaTrustListUpdate> build_rca_ctl_update(Backend& backend, Clock::time_point now,
|
||||
const Certificate& rca, const PrivateKey& key, const ByteBuffer& previous_full,
|
||||
const TrustListEntries& entries, Time32 next_update) {
|
||||
const auto previous = parse_rca_ctl(backend, previous_full, rca);
|
||||
if (!previous || !previous->full || next_update <= v2::convert_time32(now)) return std::nullopt;
|
||||
const auto sequence = static_cast<std::uint8_t>(previous->sequence + 1);
|
||||
const auto full = build_rca_ctl(backend, now, rca, key, entries, next_update, sequence);
|
||||
if (!full || !parse_rca_ctl(backend, *full, rca)) return std::nullopt;
|
||||
const auto old_payload = open_list(backend, previous_full, rca, aid::CTL);
|
||||
const auto new_payload = open_list(backend, *full, rca, aid::CTL);
|
||||
if (!old_payload || !new_payload) return std::nullopt;
|
||||
using Management = vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data>;
|
||||
Management old_list(asn_DEF_Vanetza_Security_EtsiTs102941Data), new_list(asn_DEF_Vanetza_Security_EtsiTs102941Data),
|
||||
delta(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!old_list.decode(*old_payload) || !new_list.decode(*new_payload)) return std::nullopt;
|
||||
delta->version = Vanetza_Security_Version_v1;
|
||||
delta->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||
auto& out = delta->content.choice.certificateTrustListRca;
|
||||
out.version = 1; out.nextUpdate = next_update; out.isFullCtl = 0; out.ctlSequence = sequence;
|
||||
// A certificate entry is identified by HashedId8. A DC entry is identified by URL.
|
||||
auto entry_key = [](const Vanetza_Security_CtlEntry_t& entry) -> ByteBuffer {
|
||||
Certificate certificate;
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_ea: certificate = Certificate(entry.choice.ea.eaCertificate); break;
|
||||
case Vanetza_Security_CtlEntry_PR_aa: certificate = Certificate(entry.choice.aa.aaCertificate); break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||
const auto url = get_url(entry.choice.dc.url);
|
||||
ByteBuffer result {1}; result.insert(result.end(), url.begin(), url.end()); return result;
|
||||
}
|
||||
default: return {};
|
||||
}
|
||||
const auto id = certificate.calculate_digest();
|
||||
if (!id) return {};
|
||||
ByteBuffer result {0}; result.insert(result.end(), id->begin(), id->end()); return result;
|
||||
};
|
||||
using Commands = std::map<ByteBuffer, const Vanetza_Security_CtlCommand_t*>;
|
||||
Commands old_entries, new_entries;
|
||||
auto collect = [&](const Vanetza_Security_CtlFormat_t& list, Commands& result) {
|
||||
for (int i = 0; i < list.ctlCommands.list.count; ++i) {
|
||||
const auto* command = list.ctlCommands.list.array[i];
|
||||
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return false;
|
||||
const auto id = entry_key(command->choice.add);
|
||||
if (id.empty() || !result.emplace(id, command).second) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!collect(old_list->content.choice.certificateTrustListRca, old_entries) ||
|
||||
!collect(new_list->content.choice.certificateTrustListRca, new_entries)) return std::nullopt;
|
||||
for (const auto& item : new_entries) {
|
||||
const auto found = old_entries.find(item.first);
|
||||
if (found != old_entries.end() && vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &found->second->choice.add) ==
|
||||
vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &item.second->choice.add)) continue;
|
||||
auto* command = static_cast<Vanetza_Security_CtlCommand_t*>(vanetza::asn1::copy(asn_DEF_Vanetza_Security_CtlCommand, item.second));
|
||||
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||
}
|
||||
for (const auto& item : old_entries) {
|
||||
if (new_entries.count(item.first)) continue;
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||
command->present = Vanetza_Security_CtlCommand_PR_delete;
|
||||
auto& removed = command->choice.Delete;
|
||||
if (item.first[0] == 0) {
|
||||
removed.present = Vanetza_Security_CtlDelete_PR_cert;
|
||||
HashedId8 id; std::copy(item.first.begin() + 1, item.first.end(), id.begin());
|
||||
set_hashed_id8(removed.choice.cert, id);
|
||||
} else {
|
||||
removed.present = Vanetza_Security_CtlDelete_PR_dc;
|
||||
set_url(removed.choice.dc, std::string(item.first.begin() + 1, item.first.end()));
|
||||
}
|
||||
}
|
||||
if (!delta.validate()) return std::nullopt;
|
||||
const auto signed_delta = sign_list(backend, now, rca, key, aid::CTL, delta.encode());
|
||||
if (!signed_delta || !parse_rca_ctl(backend, *signed_delta, rca)) return std::nullopt;
|
||||
return RcaTrustListUpdate {*full, *signed_delta, sequence};
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> build_crl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
const std::vector<HashedId8>& revoked, Time32 this_update, Time32 next_update) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList;
|
||||
auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||
crl.version = 1;
|
||||
crl.thisUpdate = this_update;
|
||||
crl.nextUpdate = next_update;
|
||||
for (const auto& id : revoked) {
|
||||
auto* entry = vanetza::asn1::allocate<Vanetza_Security_CrlEntry_t>();
|
||||
set_hashed_id8(*entry, id);
|
||||
ASN_SEQUENCE_ADD(&crl.entries, entry);
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, rca, rca_key, aid::CRL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<RcaTrustList> parse_rca_ctl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||
if (v3::get_app_permissions(*rca.content(), aid::CTL) != ByteBuffer({1, 0x38})) return std::nullopt;
|
||||
const auto mgmt_bytes = open_list(backend, message, rca, aid::CTL);
|
||||
if (!mgmt_bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca) return std::nullopt;
|
||||
const auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||
RcaTrustList list;
|
||||
list.sequence = static_cast<std::uint8_t>(ctl.ctlSequence);
|
||||
list.next_update = static_cast<Time32>(ctl.nextUpdate);
|
||||
list.full = ctl.isFullCtl != 0;
|
||||
const auto rca_digest = rca.calculate_digest();
|
||||
if (!rca_digest) return std::nullopt;
|
||||
const auto issued_by_rca = [&](const Vanetza_Security_EtsiTs103097Certificate_t& raw, Certificate& out) {
|
||||
out = Certificate(raw);
|
||||
const auto issuer = out.issuer_digest();
|
||||
return issuer && *issuer == *rca_digest && out.is_ca_certificate() &&
|
||||
microbu_v2x::security::verify_certificate_signature(backend, out, &rca);
|
||||
};
|
||||
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||
const auto* command = ctl.ctlCommands.list.array[i];
|
||||
if (!command) return std::nullopt;
|
||||
if (command->present == Vanetza_Security_CtlCommand_PR_add) {
|
||||
const auto& entry = command->choice.add;
|
||||
Certificate certificate;
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_ea:
|
||||
if (!issued_by_rca(entry.choice.ea.eaCertificate, certificate)) return std::nullopt;
|
||||
list.ea.push_back(std::move(certificate));
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_aa:
|
||||
if (!issued_by_rca(entry.choice.aa.aaCertificate, certificate)) return std::nullopt;
|
||||
list.aa.push_back(std::move(certificate));
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||
TrustListEntries::DistributionCentre dc;
|
||||
dc.url = get_url(entry.choice.dc.url);
|
||||
for (int k = 0; k < entry.choice.dc.cert.list.count; ++k) {
|
||||
const auto id = entry.choice.dc.cert.list.array[k] ? get_hashed_id8(*entry.choice.dc.cert.list.array[k]) : std::nullopt;
|
||||
if (!id) return std::nullopt;
|
||||
dc.certificates.push_back(*id);
|
||||
}
|
||||
if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||
list.dc.push_back(std::move(dc));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return std::nullopt; // clause 6.3.2: an RCA CTL carries no RCA or TLM entries
|
||||
}
|
||||
} else if (command->present == Vanetza_Security_CtlCommand_PR_delete) {
|
||||
if (list.full) return std::nullopt; // clause 6.3.4: a FullCtl has add commands only
|
||||
const auto& del = command->choice.Delete;
|
||||
if (del.present == Vanetza_Security_CtlDelete_PR_cert) {
|
||||
const auto id = get_hashed_id8(del.choice.cert);
|
||||
if (!id) return std::nullopt;
|
||||
list.deleted.push_back(*id);
|
||||
} else if (del.present == Vanetza_Security_CtlDelete_PR_dc) {
|
||||
list.deleted_dc.push_back(get_url(del.choice.dc));
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
if (list.full && list.dc.empty()) return std::nullopt;
|
||||
return list;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> build_tlm_ctl(Backend& backend, Clock::time_point now,
|
||||
const Certificate& tlm, const PrivateKey& key, const std::vector<Certificate>& roots,
|
||||
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm;
|
||||
auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||
ctl.version = 1; ctl.nextUpdate = next_update; ctl.isFullCtl = 1; ctl.ctlSequence = sequence;
|
||||
for (const auto& cert : roots) {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = Vanetza_Security_CtlEntry_PR_rca;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
if (!put_certificate(command->choice.add.choice.rca.selfsignedRootCa, cert.encode())) return std::nullopt;
|
||||
}
|
||||
for (const auto& cert : successors) {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = Vanetza_Security_CtlEntry_PR_tlm;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
auto& entry = command->choice.add.choice.tlm;
|
||||
if (!put_certificate(entry.selfSignedTLMCertificate, cert.encode())) return std::nullopt;
|
||||
set_url(entry.accessPoint, "https://cpoc.example.test/L0");
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, tlm, key, aid::CTL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<TlmTrustList> parse_tlm_ctl(Backend& backend, const ByteBuffer& message, const Certificate& tlm) {
|
||||
const auto permissions = v3::get_app_permissions(*tlm.content(), aid::CTL);
|
||||
if (permissions.size() != 2 || permissions[0] != 1 || permissions[1] != 0xc8 ||
|
||||
!microbu_v2x::security::verify_certificate_signature(backend, tlm, nullptr)) return std::nullopt;
|
||||
const auto bytes = open_list(backend, message, tlm, aid::CTL);
|
||||
if (!bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*bytes) || mgmt.encode() != *bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm) return std::nullopt;
|
||||
const auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||
TlmTrustList result;
|
||||
result.sequence = ctl.ctlSequence; result.next_update = ctl.nextUpdate; result.full = ctl.isFullCtl;
|
||||
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||
const auto* command = ctl.ctlCommands.list.array[i];
|
||||
// This client requests full lists. Never apply a delta without its complete base.
|
||||
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return std::nullopt;
|
||||
const auto& entry = command->choice.add;
|
||||
if (entry.present == Vanetza_Security_CtlEntry_PR_rca) {
|
||||
Certificate cert(entry.choice.rca.selfsignedRootCa);
|
||||
if ((cert->issuer.present != Vanetza_Security_IssuerIdentifier_PR_self || !cert.is_ca_certificate()) || !microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||
result.roots.push_back(std::move(cert));
|
||||
} else if (entry.present == Vanetza_Security_CtlEntry_PR_tlm) {
|
||||
Certificate cert(entry.choice.tlm.selfSignedTLMCertificate);
|
||||
const auto p = v3::get_app_permissions(*cert.content(), aid::CTL);
|
||||
if (p.size() != 2 || p[0] != 1 || p[1] != 0xc8 ||
|
||||
!microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||
result.tlms.push_back(std::move(cert));
|
||||
} else if (entry.present != Vanetza_Security_CtlEntry_PR_dc) return std::nullopt;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<RevocationList> parse_crl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||
if (v3::get_app_permissions(*rca.content(), aid::CRL) != ByteBuffer({1})) return std::nullopt;
|
||||
const auto mgmt_bytes = open_list(backend, message, rca, aid::CRL);
|
||||
if (!mgmt_bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList) return std::nullopt;
|
||||
const auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||
if (crl.version != 1) return std::nullopt;
|
||||
RevocationList list;
|
||||
list.this_update = static_cast<Time32>(crl.thisUpdate);
|
||||
list.next_update = static_cast<Time32>(crl.nextUpdate);
|
||||
for (int i = 0; i < crl.entries.list.count; ++i) {
|
||||
const auto id = crl.entries.list.array[i] ? get_hashed_id8(*crl.entries.list.array[i]) : std::nullopt;
|
||||
if (!id) return std::nullopt;
|
||||
list.revoked.push_back(*id);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
std::size_t apply(const RcaTrustList& list, microbu_v2x::security::TrustConfiguration& trust) {
|
||||
std::size_t added = 0;
|
||||
for (const auto* entries : {&list.ea, &list.aa}) {
|
||||
for (const auto& certificate : *entries) {
|
||||
if (trust.add_authority(certificate) == Result::accepted) ++added;
|
||||
}
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
std::size_t apply(const RevocationList& list, const Certificate& rca, microbu_v2x::security::TrustConfiguration& trust) {
|
||||
const auto issuer = rca.calculate_digest();
|
||||
if (!issuer) return 0;
|
||||
trust.clear_revocations(*issuer);
|
||||
for (const auto& id : list.revoked) trust.revoke(*issuer, id);
|
||||
return list.revoked.size();
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
#include <microbu_v2x/security_backend.hpp>
|
||||
#include "local_security.hpp"
|
||||
#include <sdkconfig.h>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
template <class T>
|
||||
std::unique_ptr<T> required(std::unique_ptr<T> made, const char* what) {
|
||||
if (!made) throw std::runtime_error(what);
|
||||
return made;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<vanetza::security::Backend> make_security_backend() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return required(make_external_security_backend(), "security adapter returned no backend");
|
||||
#else
|
||||
return make_local_security_backend();
|
||||
#endif
|
||||
}
|
||||
|
||||
std::unique_ptr<security::SecurityModule> make_security_module() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_SE051 || CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return required(make_external_security_module(), "security adapter returned no security module");
|
||||
#else
|
||||
return make_local_security_module();
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* security_module_name() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_SE051
|
||||
return "se051";
|
||||
#elif CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return "v2x-hsm";
|
||||
#else
|
||||
return "esp32-software";
|
||||
#endif
|
||||
}
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/v3/hash.hpp>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using vanetza::security::KeyCompression;
|
||||
using vanetza::security::key_length;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint8_t magic[4] = {'M', 'S', 'M', '1'};
|
||||
|
||||
void wipe(ByteBuffer& secret) {
|
||||
volatile std::uint8_t* target = secret.data();
|
||||
for (std::size_t n = secret.size(); n--;) *target++ = 0;
|
||||
secret.clear();
|
||||
}
|
||||
|
||||
std::uint8_t curve_code(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return 1;
|
||||
case KeyType::BrainpoolP256r1: return 2;
|
||||
case KeyType::BrainpoolP384r1: return 3;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
KeyType curve_type(std::uint8_t code) {
|
||||
switch (code) {
|
||||
case 1: return KeyType::NistP256;
|
||||
case 2: return KeyType::BrainpoolP256r1;
|
||||
case 3: return KeyType::BrainpoolP384r1;
|
||||
default: return KeyType::Unspecified;
|
||||
}
|
||||
}
|
||||
|
||||
void put_u32(ByteBuffer& out, std::uint32_t value) {
|
||||
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||
}
|
||||
|
||||
std::uint32_t get_u32(const ByteBuffer& in, std::size_t at) {
|
||||
return std::uint32_t(in[at]) << 24 | std::uint32_t(in[at + 1]) << 16 | std::uint32_t(in[at + 2]) << 8 | in[at + 3];
|
||||
}
|
||||
|
||||
bool well_formed(const KeyPair& pair) {
|
||||
const auto type = pair.priv.type;
|
||||
const auto n = key_length(type);
|
||||
return curve_code(type) != 0 && pair.pub.type == type && pair.priv.key.size() == n &&
|
||||
pair.pub.compression == KeyCompression::NoCompression && pair.pub.x.size() == n && pair.pub.y.size() == n;
|
||||
}
|
||||
|
||||
/// The two halves belong together when a signature with the private key verifies with the public key.
|
||||
bool halves_match(vanetza::security::Backend& backend, const KeyPair& pair) {
|
||||
const ByteBuffer probe = backend.calculate_hash(vanetza::security::v3::specified_hash_algorithm(pair.priv.type),
|
||||
pair.pub.x);
|
||||
return backend.verify_digest(pair.pub, probe, backend.sign_digest(pair.priv, probe));
|
||||
}
|
||||
|
||||
ByteBuffer encode_keys(std::uint32_t next, const std::map<KeyId, KeyPair>& keys) {
|
||||
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||
put_u32(out, next);
|
||||
for (const auto& [id, pair] : keys) {
|
||||
put_u32(out, id.value);
|
||||
out.push_back(curve_code(pair.priv.type));
|
||||
for (const auto* part : {&pair.priv.key, &pair.pub.x, &pair.pub.y}) out.insert(out.end(), part->begin(), part->end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool decode_keys(const ByteBuffer& in, std::uint32_t& next, std::map<KeyId, KeyPair>& keys) {
|
||||
if (in.size() < 8 || !std::equal(std::begin(magic), std::end(magic), in.begin())) return false;
|
||||
next = get_u32(in, 4);
|
||||
for (std::size_t at = 8; at < in.size();) {
|
||||
if (in.size() - at < 5) return false;
|
||||
const KeyId id {get_u32(in, at)};
|
||||
const KeyType type = curve_type(in[at + 4]);
|
||||
at += 5;
|
||||
const auto n = key_length(type);
|
||||
if (!id || id.value >= next || type == KeyType::Unspecified || in.size() - at < 3 * n || keys.count(id)) return false;
|
||||
KeyPair pair;
|
||||
pair.priv.type = pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.priv.key.assign(in.begin() + at, in.begin() + at + n);
|
||||
pair.pub.x.assign(in.begin() + at + n, in.begin() + at + 2 * n);
|
||||
pair.pub.y.assign(in.begin() + at + 2 * n, in.begin() + at + 3 * n);
|
||||
at += 3 * n;
|
||||
keys.emplace(id, std::move(pair));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// x and y of a public key in uncompressed form, none when a compressed point is not on its curve.
|
||||
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||
if (key.compression == KeyCompression::NoCompression) return key;
|
||||
const bool odd = key.compression == KeyCompression::Y1;
|
||||
if (!odd && key.compression != KeyCompression::Y0) return std::nullopt;
|
||||
const auto point = ecc::decompress(key.type, key.x, odd);
|
||||
if (!point) return std::nullopt;
|
||||
PublicKey out;
|
||||
out.type = key.type;
|
||||
out.compression = KeyCompression::NoCompression;
|
||||
out.x = point->x;
|
||||
out.y = point->y;
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool same_public_key(const PublicKey& a, const PublicKey& b) {
|
||||
if (a.type != b.type || a.type == KeyType::Unspecified) return false;
|
||||
const auto ua = uncompressed(a), ub = uncompressed(b);
|
||||
return ua && ub && ua->x == ub->x && ua->y == ub->y;
|
||||
}
|
||||
|
||||
bool MemoryKeyStorage::load(ByteBuffer& out) {
|
||||
if (blob_.empty()) return false;
|
||||
out = blob_;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MemoryKeyStorage::save(const ByteBuffer& blob) {
|
||||
wipe(blob_);
|
||||
blob_ = blob;
|
||||
return true;
|
||||
}
|
||||
|
||||
SoftwareSecurityModule::SoftwareSecurityModule(vanetza::security::Backend& backend, KeyGenerator& generator,
|
||||
KeyStorage& storage) :
|
||||
backend_(backend), generator_(generator), storage_(storage) {
|
||||
ByteBuffer stored;
|
||||
if (!storage_.load(stored)) return;
|
||||
const bool decoded = decode_keys(stored, next_, keys_);
|
||||
wipe(stored);
|
||||
if (!decoded) throw std::runtime_error("stored security module keys do not decode");
|
||||
}
|
||||
|
||||
SoftwareSecurityModule::~SoftwareSecurityModule() {
|
||||
for (auto& entry : keys_) wipe(entry.second.priv.key);
|
||||
}
|
||||
|
||||
KeyId SoftwareSecurityModule::generate_key(KeyType type) {
|
||||
KeyPair pair = generator_.generate_key(type);
|
||||
if (!well_formed(pair)) throw std::runtime_error("key generation returned no usable key pair");
|
||||
return keep(std::move(pair));
|
||||
}
|
||||
|
||||
std::optional<KeyId> SoftwareSecurityModule::import_key(const KeyPair& pair) {
|
||||
const auto pub = uncompressed(pair.pub);
|
||||
if (!pub) return std::nullopt;
|
||||
KeyPair copy {pair.priv, *pub};
|
||||
try {
|
||||
if (!well_formed(copy) || !halves_match(backend_, copy)) {
|
||||
wipe(copy.priv.key);
|
||||
return std::nullopt;
|
||||
}
|
||||
} catch (const std::exception&) {
|
||||
wipe(copy.priv.key);
|
||||
return std::nullopt;
|
||||
}
|
||||
return keep(std::move(copy));
|
||||
}
|
||||
|
||||
std::optional<PublicKey> SoftwareSecurityModule::public_key(KeyId id) const {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) return std::nullopt;
|
||||
return found->second.pub;
|
||||
}
|
||||
|
||||
Signature SoftwareSecurityModule::sign_digest(KeyId id, const ByteBuffer& digest) {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) throw std::runtime_error("security module holds no such key");
|
||||
return backend_.sign_digest(found->second.priv, digest);
|
||||
}
|
||||
|
||||
bool SoftwareSecurityModule::destroy_key(KeyId id) {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) return false;
|
||||
wipe(found->second.priv.key);
|
||||
keys_.erase(found);
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
KeyId SoftwareSecurityModule::keep(KeyPair pair) {
|
||||
if (next_ == 0) throw std::runtime_error("security module key identifiers exhausted");
|
||||
const KeyId id {next_++};
|
||||
keys_.emplace(id, std::move(pair));
|
||||
try {
|
||||
persist();
|
||||
} catch (...) {
|
||||
wipe(keys_[id].priv.key);
|
||||
keys_.erase(id);
|
||||
throw;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
void SoftwareSecurityModule::persist() {
|
||||
ByteBuffer blob = encode_keys(next_, keys_);
|
||||
const bool saved = storage_.save(blob);
|
||||
wipe(blob);
|
||||
if (!saved) throw std::runtime_error("security module keys not stored");
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,163 @@
|
||||
// Signer identifier and header selection per TS 103 097 V2.2.1 clause 7.1 and
|
||||
// TS 103 300-3 V2.3.1 clause 6.5.3. See the class comment in security.hpp.
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/common/position_fix.hpp>
|
||||
#include <vanetza/security/peer_request_tracker.hpp>
|
||||
#include <vanetza/security/sign_service.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
|
||||
namespace vanetza::security::v3 {
|
||||
// Defined in the upstream sign_header_policy.cpp translation unit (not declared in its header):
|
||||
// ThreeDLocation from a PositionFix (IEEE 1609.2 clause 6.3.10 encoding).
|
||||
asn1::ThreeDLocation build_location(const PositionFix& fix);
|
||||
}
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
|
||||
class Ts103097SignHeaderPolicy::Impl {
|
||||
public:
|
||||
const Runtime& runtime;
|
||||
PositionProvider& positioning;
|
||||
CertificatePool& pool;
|
||||
const TrustConfiguration& trust;
|
||||
// CAM, clause 7.1.1
|
||||
boost::optional<Clock::time_point> cam_last_certificate;
|
||||
bool cam_certificate_requested = false;
|
||||
PeerRequestTracker incoming_requests; // inlineP2pcdRequest digests received from peers
|
||||
PeerRequestTracker outgoing_requests; // certificates unknown to us
|
||||
// VAM, TS 103 300-3 clause 6.5.3
|
||||
boost::optional<Clock::time_point> vam_last_certificate;
|
||||
bool new_cam_signer = false;
|
||||
// generic profile: per ITS-AID
|
||||
std::map<ItsAid, Clock::time_point> generic_last_certificate;
|
||||
// the own certificate the timers above refer to
|
||||
boost::optional<HashedId8> signer_digest;
|
||||
|
||||
Impl(const Runtime& rt, PositionProvider& pp, CertificatePool& certificates, const TrustConfiguration& t) :
|
||||
runtime(rt), positioning(pp), pool(certificates), trust(t) {}
|
||||
|
||||
static constexpr std::chrono::milliseconds one_second {1000};
|
||||
static constexpr std::chrono::milliseconds half_second {500};
|
||||
|
||||
template<class Optional>
|
||||
static bool elapsed(const Optional& last, Clock::time_point now, std::chrono::milliseconds interval) {
|
||||
return !last || now - *last >= interval;
|
||||
}
|
||||
|
||||
void cam(const SignRequest&, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
const auto digest = at.calculate_digest();
|
||||
// Inline P2PCD request naming our own AT: include the certificate immediately.
|
||||
if (digest && incoming_requests.is_pending(truncate(*digest))) {
|
||||
cam_certificate_requested = true;
|
||||
incoming_requests.discard_request(truncate(*digest));
|
||||
}
|
||||
bool full_certificate = cam_certificate_requested || elapsed(cam_last_certificate, now, one_second);
|
||||
if (full_certificate) {
|
||||
message.set_signer_identifier(at);
|
||||
cam_last_certificate = now; // "the timer for the next inclusion ... shall be restarted"
|
||||
cam_certificate_requested = false;
|
||||
} else {
|
||||
message.set_signer_identifier(*digest);
|
||||
}
|
||||
// Digests of certificates unknown to this station (clause 7.1.1, inlineP2pcdRequest).
|
||||
message.set_inline_p2pcd_request(outgoing_requests.all());
|
||||
// requestedCertificate: a known CA certificate that a peer asked for, only while our
|
||||
// signer is the digest ("unless the component signer ... is of choice certificate").
|
||||
if (!full_certificate) {
|
||||
while (auto requested = incoming_requests.next_one()) {
|
||||
if (const auto* authority = trust.authority(*requested)) {
|
||||
message.set_requested_certificate(*authority);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void denm(v3::SecuredMessage& message, const Certificate& at) {
|
||||
message.set_signer_identifier(at);
|
||||
message.set_generation_location(v3::build_location(positioning.position_fix()));
|
||||
}
|
||||
|
||||
void vam(const SignRequest& request, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
const bool cluster = request.context_information == context::vam_cluster;
|
||||
bool attach;
|
||||
if (cluster) {
|
||||
attach = elapsed(vam_last_certificate, now, half_second);
|
||||
} else {
|
||||
attach = new_cam_signer || elapsed(vam_last_certificate, now, one_second);
|
||||
}
|
||||
if (attach) {
|
||||
message.set_signer_identifier(at);
|
||||
vam_last_certificate = now;
|
||||
new_cam_signer = false;
|
||||
} else if (auto digest = at.calculate_digest()) {
|
||||
message.set_signer_identifier(*digest);
|
||||
} else {
|
||||
message.set_signer_identifier(at);
|
||||
}
|
||||
}
|
||||
|
||||
void generic(ItsAid aid, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
auto it = generic_last_certificate.find(aid);
|
||||
const auto digest = at.calculate_digest();
|
||||
if (it == generic_last_certificate.end() || now - it->second >= one_second || !digest) {
|
||||
message.set_signer_identifier(at);
|
||||
generic_last_certificate[aid] = now;
|
||||
} else {
|
||||
message.set_signer_identifier(*digest);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ts103097SignHeaderPolicy::Ts103097SignHeaderPolicy(const Runtime& rt, PositionProvider& pp, CertificatePool& pool,
|
||||
const TrustConfiguration& trust) :
|
||||
impl_(std::make_unique<Impl>(rt, pp, pool, trust)) {}
|
||||
Ts103097SignHeaderPolicy::~Ts103097SignHeaderPolicy() = default;
|
||||
|
||||
void Ts103097SignHeaderPolicy::prepare_header(const SignRequest& request, v3::SecuredMessage& message) {
|
||||
const auto now = impl_->runtime.now();
|
||||
// Clause 5.2: psid and generationTime always present.
|
||||
message.set_its_aid(request.its_aid);
|
||||
message.set_generation_time(v2::convert_time64(now));
|
||||
const Certificate& at = impl_->pool.own_certificate();
|
||||
// A different own certificate (a newly provisioned ticket, or a ticket switch outside
|
||||
// reset_after_identifier_change) has never been sent in full: restart the inclusion timers so the
|
||||
// first message signed with it carries the certificate. Receivers cannot resolve the digest of a
|
||||
// certificate they have not seen (2026-09-29: 9 digest-signed VAMs after re-provisioning).
|
||||
const auto signer = at.calculate_digest();
|
||||
if (signer != impl_->signer_digest) {
|
||||
reset_after_identifier_change();
|
||||
impl_->signer_digest = signer;
|
||||
}
|
||||
if (request.self_signed) {
|
||||
// TS 102 941 clause 6.2.3.2 inner enrolment structures are self-signed.
|
||||
message.set_signer_identifier_self();
|
||||
return;
|
||||
}
|
||||
switch (request.its_aid) {
|
||||
case aid::CA: impl_->cam(request, message, at, now); break;
|
||||
case aid::DEN: impl_->denm(message, at); break;
|
||||
case aid::VRU: impl_->vam(request, message, at, now); break;
|
||||
default: impl_->generic(request.its_aid, message, at, now); break;
|
||||
}
|
||||
}
|
||||
|
||||
void Ts103097SignHeaderPolicy::request_unrecognized_certificate(HashedId8 id) {
|
||||
impl_->outgoing_requests.add_request(truncate(id));
|
||||
}
|
||||
void Ts103097SignHeaderPolicy::request_certificate() { impl_->cam_certificate_requested = true; }
|
||||
void Ts103097SignHeaderPolicy::enqueue_p2p_request(HashedId3 id) { impl_->incoming_requests.add_request(id); }
|
||||
void Ts103097SignHeaderPolicy::discard_p2p_request(HashedId3 id) { impl_->incoming_requests.discard_request(id); }
|
||||
void Ts103097SignHeaderPolicy::report_new_cam_signer() { impl_->new_cam_signer = true; }
|
||||
void Ts103097SignHeaderPolicy::reset_after_identifier_change() {
|
||||
impl_->cam_last_certificate = boost::none;
|
||||
impl_->cam_certificate_requested = false;
|
||||
impl_->vam_last_certificate = boost::none;
|
||||
impl_->generic_last_certificate.clear();
|
||||
}
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,344 @@
|
||||
#include <microbu_v2x/stack.hpp>
|
||||
#if V2X_SECURITY
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#endif
|
||||
#include <vanetza/access/access_category.hpp>
|
||||
#include <vanetza/btp/header.hpp>
|
||||
#include <vanetza/btp/header_conversion.hpp>
|
||||
#include <vanetza/dcc/interface.hpp>
|
||||
#include <vanetza/dcc/mapping.hpp>
|
||||
#include <vanetza/dcc/data_request.hpp>
|
||||
#include <vanetza/geonet/dcc_information_sharing.hpp>
|
||||
#include <vanetza/geonet/router.hpp>
|
||||
#include <vanetza/geonet/transport_interface.hpp>
|
||||
#include <vanetza/net/packet.hpp>
|
||||
#include <vanetza/net/packet_variant.hpp>
|
||||
#include <vanetza/common/byte_view.hpp>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace gn = vanetza::geonet;
|
||||
using namespace vanetza;
|
||||
|
||||
StackConfig::StackConfig() {
|
||||
// Explicit ITS-G5 subset. Defaults are upstream MIB, not R2 certification.
|
||||
mib.itsGnIfType = gn::InterfaceType::ITS_G5;
|
||||
mib.itsGnSnDecapResultHandling = gn::SecurityDecapHandling::Strict;
|
||||
mib.itsGnSecurity = true;
|
||||
// A GBC received again (CBF relies on duplicates, TS 103 836-4-1 V2.2.1 clause 10.3.11.3 step 3 and Annex F.3)
|
||||
// is handled by the forwarding algorithm and never passed up a second time; the upstream default (0) passes
|
||||
// every copy up. Found by TC_GEONW_PON_GBC_AREA_ALL_BO_08.
|
||||
mib.vanetzaGbcMemoryCapacity = 128;
|
||||
}
|
||||
|
||||
class Stack::Impl : public dcc::RequestInterface, public gn::TransportInterface {
|
||||
public:
|
||||
StackConfig cfg;
|
||||
ManualRuntime& runtime;
|
||||
Access& access;
|
||||
vanetza::security::SecurityEntity* security;
|
||||
security::IdChangeService* id_change;
|
||||
gn::Router router;
|
||||
// TS 103 836-4-2 Release-2 DCC_NET. Declared after router: it holds a
|
||||
// reference to router's location table, which must already be constructed.
|
||||
gn::DccInformationSharing dcc_information_sharing;
|
||||
std::optional<dcc::ChannelLoad> global_cbr;
|
||||
Receive receive;
|
||||
ReceiveGn receive_gn;
|
||||
Report report;
|
||||
bool position_valid = false;
|
||||
bool change_pending = false;
|
||||
std::optional<security::SubscriptionHandle> subscription;
|
||||
|
||||
Impl(StackConfig c, ManualRuntime& rt, Access& al, vanetza::security::SecurityEntity* sec,
|
||||
security::IdChangeService* ids) :
|
||||
cfg(std::move(c)), runtime(rt), access(al), security(sec), id_change(ids), router(rt, cfg.mib),
|
||||
// TS 103 836-4-2 clause 5.3: "all ITS-S shall start with a random time offset" so that
|
||||
// stations do not all recompute CBR_G in lockstep. No RNG dependency (host and ESP-IDF
|
||||
// newlib without configured hardware entropy behave differently): the station's own
|
||||
// startup time already differs from its neighbours', so its microsecond-level position
|
||||
// within the 100 ms trigger interval (itsGNCBRGTriggerInterval) serves as that offset.
|
||||
dcc_information_sharing(rt, router.get_location_table(), dcc::ChannelLoad(0.62),
|
||||
UnitInterval(double(rt.now().time_since_epoch().count() % 100000) / 100000.0)) {
|
||||
router.set_access_interface(this);
|
||||
router.set_security_entity(sec);
|
||||
router.set_dcc_field_generator(&dcc_information_sharing);
|
||||
dcc_information_sharing.on_global_cbr_update = [this](const gn::CbrAggregator& agg) {
|
||||
global_cbr = agg.get_global_cbr();
|
||||
};
|
||||
// MIB.itsGnLocalGnAddr is otherwise inert: Router::update_position only
|
||||
// touches timestamp/latitude/longitude/speed/heading, never the address,
|
||||
// and the router's own m_local_position_vector.gn_addr starts at
|
||||
// vanetza::geonet::Address()'s default (all-zero mid, not manually
|
||||
// configured) until this is called. Every GN packet's source position
|
||||
// vector carries that address, so leaving this out silently transmits
|
||||
// the wrong (default) station address regardless of what the caller
|
||||
// configured -- undetected by BTP's official ATS, which never checks
|
||||
// the source GN address, but not so for GeoNetworking's.
|
||||
router.set_address(cfg.mib.itsGnLocalGnAddr);
|
||||
router.set_transport_handler(gn::UpperProtocol::BTP_A, this);
|
||||
router.set_transport_handler(gn::UpperProtocol::BTP_B, this);
|
||||
router.set_transport_handler(gn::UpperProtocol::Unknown, this);
|
||||
// TS 103 836-4-1 V2.2.1 clause 10.2.1.4: the GN core of an anonymously addressed
|
||||
// station subscribes to the identifier-change service at startup (SN-IDCHANGE-SUBSCRIBE)
|
||||
// and derives its MID from the identifier of the security entity (TS 102 940 clause 6.5).
|
||||
if (cfg.mib.itsGnLocalAddrConfMethod == gn::AddrConfMethod::Anonymous && id_change) {
|
||||
subscription = id_change->subscribe(
|
||||
[this](security::IdChangeCommand command, const security::Identifier& id, const ByteBuffer&,
|
||||
std::shared_ptr<security::IdChangeResponder> responder) { on_id_change(command, id, responder); });
|
||||
const auto current = id_change->current_identifier();
|
||||
if (current != security::Identifier {}) apply_identifier(current);
|
||||
}
|
||||
}
|
||||
|
||||
~Impl() override {
|
||||
// clause 10.2.1.4: unsubscribe when the router shuts down (SN-IDCHANGE-UNSUBSCRIBE)
|
||||
if (subscription && id_change) id_change->unsubscribe(*subscription);
|
||||
}
|
||||
|
||||
// TS 102 940 V2.1.1 clause 6.5: the 48 least significant bits of the HashedId8 become the
|
||||
// MAC-layer / GN MID identifier. A source address must be individual (IEEE Std 802 clause
|
||||
// 8.2.2, I/G bit 0) and this one is not OUI-assigned (U/L bit 1).
|
||||
void apply_identifier(const security::Identifier& id) {
|
||||
MacAddress mid;
|
||||
std::copy(id.begin() + 2, id.end(), mid.octets.begin());
|
||||
mid.octets[0] = (mid.octets[0] & 0xfe) | 0x02;
|
||||
cfg.mib.itsGnLocalGnAddr.mid(mid);
|
||||
router.set_address(cfg.mib.itsGnLocalGnAddr);
|
||||
}
|
||||
|
||||
// TS 102 723-8 V1.1.1 clauses 6.3.1.2 and 6.3.1.3: hook function of the GN core.
|
||||
void on_id_change(security::IdChangeCommand command, const security::Identifier& id,
|
||||
const std::shared_ptr<security::IdChangeResponder>& responder) {
|
||||
switch (command) {
|
||||
case security::IdChangeCommand::PREPARE:
|
||||
change_pending = true;
|
||||
router.flush_forwarding_buffers(); // caches shall be flushed
|
||||
if (responder) responder->respond(true);
|
||||
break;
|
||||
case security::IdChangeCommand::COMMIT:
|
||||
apply_identifier(id);
|
||||
change_pending = false;
|
||||
if (responder) responder->respond(true);
|
||||
break;
|
||||
case security::IdChangeCommand::ABORT:
|
||||
change_pending = false;
|
||||
break;
|
||||
case security::IdChangeCommand::DEREG:
|
||||
change_pending = false;
|
||||
subscription.reset();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void request(const dcc::DataRequest& req, std::unique_ptr<ChunkPacket> packet) override {
|
||||
auto out = cfg.radio_parameters;
|
||||
out.source = req.source;
|
||||
out.destination = req.destination;
|
||||
// DCC profile to IEEE 802.1D priority: upstream TS 102 687 mapping.
|
||||
// DCC enforcement belongs to the injected Access adapter; no fake CBR.
|
||||
out.priority = access::user_priority(dcc::map_profile_onto_ac(req.dcc_profile));
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Network, max_osi_layer());
|
||||
out.data.assign(view.begin(), view.end());
|
||||
auto result = validate(out, cfg.maximum_gnpdu);
|
||||
if (result == Result::accepted) result = access.request(std::move(out));
|
||||
if (report) report(result);
|
||||
}
|
||||
|
||||
void indicate(const gn::DataIndication& ind, std::unique_ptr<UpPacket> packet) override {
|
||||
if (ind.upper_protocol == gn::UpperProtocol::Unknown) {
|
||||
// GN-DATA.indication for a packet with no registered upper protocol
|
||||
// (Common Header next_header "Any"): the raw SDU, no BTP header to strip.
|
||||
if (!receive_gn) return;
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
||||
receive_gn(GnIndication {ind, ByteBuffer(view.begin(), view.end())});
|
||||
return;
|
||||
}
|
||||
// validate length BEFORE parsing; upstream header parsing
|
||||
// alone does not reject a short BTP PDU. Never read an incomplete port.
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
||||
if (view.size() < 4 || !receive) return;
|
||||
BtpIndication out {};
|
||||
out.type = ind.upper_protocol == gn::UpperProtocol::BTP_A ? BtpType::a : BtpType::b;
|
||||
out.destination_port = (std::uint16_t(view[0]) << 8) | view[1];
|
||||
const std::uint16_t second = (std::uint16_t(view[2]) << 8) | view[3];
|
||||
if (out.type == BtpType::a) out.source_port = second;
|
||||
else out.destination_port_info = second;
|
||||
out.gn = ind;
|
||||
// SN-DECAP.confirm -> NF-SAP: TS 102 723-8 V2.0.0 clause 5 /
|
||||
// V1.1.1 Table 27 and TS 103 836-5-1 Annex A.3.
|
||||
if (ind.certificate_id)
|
||||
out.certificate_id = ByteBuffer(ind.certificate_id->begin(), ind.certificate_id->end());
|
||||
out.data.assign(view.begin() + 4, view.end());
|
||||
receive(std::move(out));
|
||||
}
|
||||
};
|
||||
|
||||
Stack::Stack(StackConfig config, ManualRuntime& runtime, Access& access,
|
||||
vanetza::security::SecurityEntity* security, security::IdChangeService* id_change) {
|
||||
if (config.mib.itsGnMaxSduSize < 4 || config.mib.itsGnMaxSduSize > 65535 ||
|
||||
config.maximum_gnpdu < config.mib.itsGnMaxSduSize ||
|
||||
config.mib.itsGnIfType != gn::InterfaceType::ITS_G5 ||
|
||||
config.mib.itsGnSnDecapResultHandling != gn::SecurityDecapHandling::Strict)
|
||||
throw std::invalid_argument("Invalid ITS-G5 stack configuration");
|
||||
#if V2X_SECURITY
|
||||
if (!id_change) {
|
||||
if (auto* own = dynamic_cast<security::SecurityEntity*>(security)) id_change = &own->id_change();
|
||||
}
|
||||
#endif
|
||||
impl_ = std::make_unique<Impl>(std::move(config), runtime, access, security, id_change);
|
||||
}
|
||||
Stack::~Stack() = default;
|
||||
const StackConfig& Stack::config() const { return impl_->cfg; }
|
||||
security::IdChangeService* Stack::id_change() { return impl_->subscription ? impl_->id_change : nullptr; }
|
||||
vanetza::security::SecurityEntity* Stack::security_entity() { return impl_->security; }
|
||||
bool Stack::identity_change_pending() const { return impl_->change_pending; }
|
||||
// The address the router uses now: DAD (clause 10.2.1.5) and identifier changes move it away from the
|
||||
// configured MIB value, and the station must report what it actually transmits.
|
||||
const gn::Address& Stack::address() const { return impl_->router.get_local_position_vector().gn_addr; }
|
||||
Result Stack::set_address(const gn::Address& address) {
|
||||
if (impl_->cfg.mib.itsGnLocalAddrConfMethod != gn::AddrConfMethod::Managed) return Result::unsupported;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
impl_->cfg.mib.itsGnLocalGnAddr = address;
|
||||
impl_->router.set_address(address);
|
||||
return Result::accepted;
|
||||
}
|
||||
void Stack::on_receive(Receive receive) { impl_->receive = std::move(receive); }
|
||||
void Stack::on_receive_gn(ReceiveGn receive) { impl_->receive_gn = std::move(receive); }
|
||||
void Stack::on_access_result(Report report) { impl_->report = std::move(report); }
|
||||
void Stack::on_packet_drop(std::function<void(const std::string&)> report) {
|
||||
impl_->router.packet_dropped = [report = std::move(report)](gn::Router::PacketDropReason reason) {
|
||||
if (report) report(gn::stringify(reason));
|
||||
};
|
||||
}
|
||||
void Stack::report_local_channel_load(dcc::ChannelLoad load) { impl_->dcc_information_sharing.update_local_cbr(load); }
|
||||
void Stack::report_tx_power(unsigned dbm) { impl_->dcc_information_sharing.set_tx_power(dbm); }
|
||||
std::optional<dcc::ChannelLoad> Stack::global_channel_busy_ratio() const { return impl_->global_cbr; }
|
||||
|
||||
Result Stack::advance(Clock::time_point time) {
|
||||
if (time < impl_->runtime.now()) return Result::time_regression;
|
||||
impl_->runtime.trigger(time);
|
||||
return Result::accepted;
|
||||
}
|
||||
Result Stack::update_position(const PositionFix& fix) {
|
||||
if (!has_horizontal_position(fix) || fix.latitude.value() < -90 || fix.latitude.value() > 90 ||
|
||||
fix.longitude.value() < -180 || fix.longitude.value() > 180 ||
|
||||
fix.timestamp > impl_->runtime.now()) return Result::invalid_argument;
|
||||
impl_->router.update_position(fix);
|
||||
impl_->position_valid = true;
|
||||
return Result::accepted;
|
||||
}
|
||||
Result Stack::indicate(AlDataIndication ind) {
|
||||
if (ind.data.empty() || ind.data.size() > impl_->cfg.maximum_gnpdu) return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<UpPacket>(CohesivePacket(std::move(ind.data), OsiLayer::Network));
|
||||
impl_->router.indicate(std::move(packet), ind.source, ind.destination);
|
||||
return Result::accepted; // submitted for processing, NOT a receive verdict
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
Result Stack::request(BtpRequest req) {
|
||||
// mutually exclusive BTP header variants and conditional fields.
|
||||
if ((req.type != BtpType::a && req.type != BtpType::b) ||
|
||||
(req.type == BtpType::a && (!req.source_port || req.destination_port_info)) ||
|
||||
(req.type == BtpType::b && req.source_port)) return Result::invalid_argument;
|
||||
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize - 4u) return Result::resource_limit;
|
||||
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
|
||||
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
|
||||
if (req.security_profile && *req.security_profile != impl_->cfg.security_profile) return Result::unsupported;
|
||||
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
if (!impl_->position_valid) return Result::rejected;
|
||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<DownPacket>();
|
||||
// TS 103 836-5-1 clauses 7 and 8.2: both headers occupy four octets.
|
||||
if (req.type == BtpType::a) {
|
||||
btp::HeaderA header { host_cast(req.destination_port), host_cast(*req.source_port) };
|
||||
(*packet)[OsiLayer::Transport] = header;
|
||||
} else {
|
||||
btp::HeaderB header { host_cast(req.destination_port), host_cast(req.destination_port_info.value_or(0)) };
|
||||
(*packet)[OsiLayer::Transport] = header;
|
||||
}
|
||||
(*packet)[OsiLayer::Application] = std::move(req.data);
|
||||
auto apply = [&](gn::DataRequest& gn_req) {
|
||||
gn_req.upper_protocol = req.type == BtpType::a ? gn::UpperProtocol::BTP_A : gn::UpperProtocol::BTP_B;
|
||||
gn_req.communication_profile = req.communication_profile;
|
||||
gn_req.its_aid = req.its_aid;
|
||||
gn_req.permissions = std::move(req.permissions);
|
||||
gn_req.security_context = std::move(req.security_context);
|
||||
gn_req.traffic_class = req.traffic_class;
|
||||
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
|
||||
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
|
||||
if (req.repetition) gn_req.repetition = *req.repetition;
|
||||
};
|
||||
gn::DataConfirm confirm;
|
||||
if (req.transport == gn::TransportType::SHB) {
|
||||
gn::ShbDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
} else {
|
||||
gn::GbcDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
gn_req.destination = boost::get<gn::Area>(req.destination);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
}
|
||||
return confirm.accepted() ? Result::accepted : Result::rejected;
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
Result Stack::request(GnRequest req) {
|
||||
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize) return Result::resource_limit;
|
||||
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
|
||||
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
|
||||
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
if (!impl_->position_valid) return Result::rejected;
|
||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<DownPacket>();
|
||||
(*packet)[OsiLayer::Application] = std::move(req.data);
|
||||
auto apply = [&](gn::DataRequest& gn_req) {
|
||||
gn_req.upper_protocol = gn::UpperProtocol::Unknown;
|
||||
gn_req.communication_profile = req.communication_profile;
|
||||
gn_req.its_aid = req.its_aid;
|
||||
gn_req.permissions = std::move(req.permissions);
|
||||
gn_req.security_context = std::move(req.security_context);
|
||||
gn_req.traffic_class = req.traffic_class;
|
||||
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
|
||||
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
|
||||
if (req.repetition) gn_req.repetition = *req.repetition;
|
||||
};
|
||||
gn::DataConfirm confirm;
|
||||
if (req.transport == gn::TransportType::SHB) {
|
||||
gn::ShbDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
} else {
|
||||
gn::GbcDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
gn_req.destination = boost::get<gn::Area>(req.destination);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
}
|
||||
return confirm.accepted() ? Result::accepted : Result::rejected;
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <microbu_v2x/trust_update.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
namespace {
|
||||
bool same_or_newer(unsigned old_seq, unsigned next_seq, const ByteBuffer& old, const ByteBuffer& next) {
|
||||
if (next_seq == old_seq) return old == next;
|
||||
auto generation_time = [](const ByteBuffer& bytes) {
|
||||
vanetza::security::v3::SecuredMessage message;
|
||||
if (!message.decode(bytes)) return decltype(message.generation_time()) {};
|
||||
return message.generation_time();
|
||||
};
|
||||
const auto old_time = generation_time(old);
|
||||
const auto next_time = generation_time(next);
|
||||
if (!old_time || !next_time || *next_time < *old_time) return false;
|
||||
// TS 102 941 clause 6.3.4 wraps ctlSequence at 255. Authenticated time
|
||||
// distinguishes a wrapped full list from replay of an earlier cycle.
|
||||
return next_seq > old_seq || *next_time > *old_time;
|
||||
}
|
||||
bool decode_certificate(const ByteBuffer& bytes, Certificate& cert) {
|
||||
return cert.decode(bytes) && cert.encode() == bytes;
|
||||
}
|
||||
}
|
||||
ByteBuffer encode_snapshot(const TrustSnapshot& snapshot) {
|
||||
ByteBuffer bytes {'T', 'S', 'N', 1};
|
||||
for (const auto* blob : {&snapshot.tlm, &snapshot.rca, &snapshot.ectl, &snapshot.ctl, &snapshot.crl}) {
|
||||
if (blob->empty() || blob->size() > 32768) return {};
|
||||
bytes.push_back(blob->size() >> 8); bytes.push_back(blob->size() & 255);
|
||||
bytes.insert(bytes.end(), blob->begin(), blob->end());
|
||||
}
|
||||
for (int shift = 24; shift >= 0; shift -= 8) bytes.push_back(snapshot.deadline >> shift);
|
||||
return bytes.size() <= 60000 ? bytes : ByteBuffer {};
|
||||
}
|
||||
bool decode_snapshot(const ByteBuffer& bytes, TrustSnapshot& out) {
|
||||
if (bytes.size() < 8 || bytes.size() > 60000 || !std::equal(bytes.begin(), bytes.begin() + 4, ByteBuffer {'T','S','N',1}.begin())) return false;
|
||||
TrustSnapshot parsed;
|
||||
std::size_t pos = 4;
|
||||
for (auto* blob : {&parsed.tlm, &parsed.rca, &parsed.ectl, &parsed.ctl, &parsed.crl}) {
|
||||
if (pos + 2 > bytes.size()) return false;
|
||||
const std::size_t length = (bytes[pos] << 8) | bytes[pos + 1]; pos += 2;
|
||||
if (!length || length > 32768 || length > bytes.size() - pos) return false;
|
||||
blob->assign(bytes.begin() + pos, bytes.begin() + pos + length); pos += length;
|
||||
}
|
||||
if (pos + 4 != bytes.size()) return false;
|
||||
for (int i = 0; i < 4; ++i) parsed.deadline = (parsed.deadline << 8) | bytes[pos++];
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
bool validate_update(vanetza::security::Backend& backend, vanetza::Clock::time_point now,
|
||||
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
|
||||
const TrustSnapshot& proposed, TrustSnapshot& accepted) {
|
||||
Certificate tlm, rca;
|
||||
if (!decode_certificate(proposed.tlm, tlm) || !decode_certificate(proposed.rca, rca) ||
|
||||
!tlm.valid_at_timepoint(now) || !rca.valid_at_timepoint(now)) return false;
|
||||
const auto time = vanetza::security::v2::convert_time32(now);
|
||||
for (const auto* wire : {&proposed.ectl, &proposed.ctl, &proposed.crl}) {
|
||||
vanetza::security::v3::SecuredMessage msg;
|
||||
if (!msg.decode(*wire) || !msg.generation_time() ||
|
||||
*msg.generation_time() > vanetza::security::v2::convert_time64(now)) return false;
|
||||
}
|
||||
// TS 102 941 clause 6.3.6: authenticate every object, releasing decoded
|
||||
// certificate graphs between lists so live reception can continue during updates.
|
||||
std::optional<unsigned> old_ectl_sequence, old_ctl_sequence;
|
||||
std::optional<RevocationList> old_crl;
|
||||
std::vector<std::pair<HashedId8, Time32>> old_authorities;
|
||||
if (previous) {
|
||||
{
|
||||
Certificate old_tlm;
|
||||
if (!decode_certificate(previous->tlm, old_tlm)) return false;
|
||||
const auto old_ectl = parse_tlm_ctl(backend, previous->ectl, old_tlm);
|
||||
if (!old_ectl) return false;
|
||||
old_ectl_sequence = old_ectl->sequence;
|
||||
if (proposed.tlm != previous->tlm &&
|
||||
std::none_of(old_ectl->tlms.begin(), old_ectl->tlms.end(),
|
||||
[&](const auto& c) { return c.encode() == proposed.tlm; })) return false;
|
||||
}
|
||||
Certificate old_rca;
|
||||
if (!decode_certificate(previous->rca, old_rca)) return false;
|
||||
{
|
||||
const auto old_ctl = parse_rca_ctl(backend, previous->ctl, old_rca);
|
||||
if (!old_ctl) return false;
|
||||
old_ctl_sequence = old_ctl->sequence;
|
||||
for (const auto* list : {&old_ctl->ea, &old_ctl->aa}) for (const auto& cert : *list) {
|
||||
const auto id = cert.calculate_digest();
|
||||
if (!id) return false;
|
||||
old_authorities.emplace_back(*id, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||
}
|
||||
}
|
||||
old_crl = parse_crl(backend, previous->crl, old_rca);
|
||||
if (!old_crl) return false;
|
||||
} else if (pinned_tlm.empty() || proposed.tlm != pinned_tlm) return false;
|
||||
Time32 deadline = std::min(microbu_v2x::security::validity_bounds(tlm).end_validity,
|
||||
microbu_v2x::security::validity_bounds(rca).end_validity);
|
||||
{
|
||||
const auto ectl = parse_tlm_ctl(backend, proposed.ectl, tlm);
|
||||
if (!ectl || !ectl->full || ectl->next_update <= time ||
|
||||
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||
[&](const auto& c) { return c.encode() == proposed.rca; })) return false;
|
||||
deadline = std::min(deadline, ectl->next_update);
|
||||
if (previous && proposed.tlm == previous->tlm &&
|
||||
!same_or_newer(*old_ectl_sequence, ectl->sequence, previous->ectl, proposed.ectl)) return false;
|
||||
}
|
||||
{
|
||||
const auto ctl = parse_rca_ctl(backend, proposed.ctl, rca);
|
||||
if (!ctl || !ctl->full || ctl->next_update <= time) return false;
|
||||
deadline = std::min(deadline, ctl->next_update);
|
||||
if (previous && proposed.rca == previous->rca &&
|
||||
!same_or_newer(*old_ctl_sequence, ctl->sequence, previous->ctl, proposed.ctl)) return false;
|
||||
for (const auto* list : {&ctl->ea, &ctl->aa}) for (const auto& cert : *list) {
|
||||
if (!cert.valid_at_timepoint(now)) return false;
|
||||
deadline = std::min(deadline, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||
}
|
||||
}
|
||||
const auto crl = parse_crl(backend, proposed.crl, rca);
|
||||
if (!crl || crl->next_update <= time || crl->this_update > time ||
|
||||
crl->next_update <= crl->this_update) return false;
|
||||
deadline = std::min(deadline, crl->next_update);
|
||||
if (previous && proposed.rca == previous->rca) {
|
||||
if (crl->this_update < old_crl->this_update ||
|
||||
(crl->this_update == old_crl->this_update && proposed.crl != previous->crl)) return false;
|
||||
// Revocation is permanent until the known certificate expires.
|
||||
// Unknown removed entries cannot be proven expired and fail closed.
|
||||
for (const auto& id : old_crl->revoked) {
|
||||
if (std::find(crl->revoked.begin(), crl->revoked.end(), id) != crl->revoked.end()) continue;
|
||||
const auto known = std::find_if(old_authorities.begin(), old_authorities.end(),
|
||||
[&](const auto& item) { return item.first == id; });
|
||||
if (known == old_authorities.end() || known->second > time) return false;
|
||||
}
|
||||
}
|
||||
accepted = proposed; accepted.deadline = deadline;
|
||||
return true;
|
||||
}
|
||||
bool snapshot_credentials(vanetza::security::Backend& backend, const TrustSnapshot& state,
|
||||
microbu_v2x::security::StoredCredentials& credentials, microbu_v2x::security::TrustConfiguration* trust) {
|
||||
Certificate tlm, rca;
|
||||
if (!decode_certificate(state.tlm, tlm) || !decode_certificate(state.rca, rca)) return false;
|
||||
const auto crl = parse_crl(backend, state.crl, rca);
|
||||
if (!crl) return false;
|
||||
// TS 102 941 clauses 6.3.1 and 6.3.6: ECTL anchors apply to reception.
|
||||
// The selected home RCA determines credential management and its CTL.
|
||||
std::vector<ByteBuffer> roots, authorities;
|
||||
{
|
||||
const auto ectl = parse_tlm_ctl(backend, state.ectl, tlm);
|
||||
if (!ectl || !ectl->full ||
|
||||
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||
[&](const auto& c) { return c.encode() == state.rca; })) return false;
|
||||
for (const auto& cert : ectl->roots) roots.push_back(cert.encode());
|
||||
}
|
||||
{
|
||||
const auto ctl = parse_rca_ctl(backend, state.ctl, rca);
|
||||
if (!ctl || !ctl->full) return false;
|
||||
for (const auto* list : {&ctl->ea, &ctl->aa})
|
||||
for (const auto& cert : *list) authorities.push_back(cert.encode());
|
||||
}
|
||||
credentials.roots = std::move(roots);
|
||||
credentials.authorities = std::move(authorities);
|
||||
if (trust) apply(*crl, rca, *trust);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "esp_private/wifi_os_adapter.h"
|
||||
#include "esp_wifi.h"
|
||||
|
||||
#include "tx_custom.h"
|
||||
|
||||
esp_err_t ieee80211_raw_frame_sanity_check(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq);
|
||||
esp_err_t ieee80211_post_hmac_tx(void *ebuf);
|
||||
void *ic_ebuf_alloc(const void *packet, uint32_t unknown, uint32_t len);
|
||||
void *ic_get_default_sched(void);
|
||||
|
||||
extern wifi_osi_funcs_t *g_osi_funcs_p;
|
||||
extern void *g_wifi_global_lock;
|
||||
|
||||
typedef struct x_eb_txdesc
|
||||
{
|
||||
uint32_t flags;
|
||||
uint32_t field_4;
|
||||
uint32_t field_8;
|
||||
uint8_t rate;
|
||||
uint8_t field_d;
|
||||
uint8_t field_e;
|
||||
uint8_t field_f;
|
||||
uint32_t field_10;
|
||||
uint32_t field_14;
|
||||
uint32_t timestamp;
|
||||
void* sched;
|
||||
uint32_t field_20;
|
||||
uint32_t field_24;
|
||||
uint32_t field_28;
|
||||
union {
|
||||
uint32_t field_2c_32;
|
||||
struct {
|
||||
uint8_t field_2c;
|
||||
uint8_t field_2d;
|
||||
uint8_t field_2e;
|
||||
uint8_t field_2f;
|
||||
};
|
||||
};
|
||||
union {
|
||||
uint32_t field_30_32;
|
||||
struct {
|
||||
uint8_t field_30;
|
||||
uint8_t field_31;
|
||||
uint8_t field_32;
|
||||
uint8_t field_33;
|
||||
};
|
||||
};
|
||||
uint32_t field_34;
|
||||
uint32_t field_38;
|
||||
uint32_t field_3c;
|
||||
uint32_t field_40;
|
||||
uint32_t field_44;
|
||||
} x_eb_txdesc_t;
|
||||
static_assert(sizeof(x_eb_txdesc_t) == 0x48);
|
||||
|
||||
typedef struct x_middle_data
|
||||
{
|
||||
uint32_t field_40;
|
||||
uint8_t* buf;
|
||||
uint32_t field_48;
|
||||
uint32_t field_4c;
|
||||
} x_middle_data_t;
|
||||
static_assert(sizeof(x_middle_data_t) == 0x10);
|
||||
|
||||
typedef struct x_ebuf
|
||||
{
|
||||
uint32_t field_0;
|
||||
x_middle_data_t* ds_head;
|
||||
x_middle_data_t* ds_tail;
|
||||
uint16_t field_c;
|
||||
uint16_t field_e;
|
||||
uint32_t extra_data_start;
|
||||
uint16_t header_length;
|
||||
uint32_t data_length;
|
||||
uint16_t field_1c;
|
||||
uint8_t alloc_type;
|
||||
uint8_t field_1f;
|
||||
uint32_t field_20;
|
||||
uint8_t field_24;
|
||||
uint8_t field_25;
|
||||
uint8_t field_26;
|
||||
uint8_t field_27;
|
||||
uint32_t field_28;
|
||||
uint8_t field_2c;
|
||||
uint32_t field_30;
|
||||
uint32_t next_free;
|
||||
x_eb_txdesc_t* txdesc;
|
||||
uint16_t field_3c;
|
||||
uint8_t field_3e;
|
||||
uint8_t field_3f;
|
||||
} x_ebuf_t;
|
||||
static_assert(sizeof(x_ebuf_t) == 0x40);
|
||||
|
||||
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw)
|
||||
{
|
||||
esp_err_t result = 0;//ieee80211_raw_frame_sanity_check(ifx, buffer, len, en_sys_seq);
|
||||
|
||||
if (!result)
|
||||
{
|
||||
g_osi_funcs_p->_mutex_lock(g_wifi_global_lock);
|
||||
x_ebuf_t* eb = ic_ebuf_alloc(buffer, 1, len);
|
||||
|
||||
if (eb)
|
||||
{
|
||||
//eb->data_length = len - 0x1a;
|
||||
eb->data_length = 0;
|
||||
x_eb_txdesc_t *txdesc_1 = eb->txdesc;
|
||||
//eb->header_length = 0x1a;
|
||||
eb->header_length = len;
|
||||
txdesc_1->flags |= 0x4000;
|
||||
txdesc_1->sched = ic_get_default_sched();
|
||||
wifi_phy_rate_t rate = tx_rate_config->rate;
|
||||
x_eb_txdesc_t *txdesc = eb->txdesc;
|
||||
|
||||
if (rate)
|
||||
txdesc->rate = (char)rate;
|
||||
else if (band != WIFI_BAND_5G)
|
||||
txdesc->rate = 0;
|
||||
else
|
||||
txdesc->rate = (char)WIFI_PHY_RATE_6M;
|
||||
|
||||
wifi_phy_mode_t phymode = tx_rate_config->phymode;
|
||||
|
||||
if (phymode == WIFI_PHY_MODE_HE20)
|
||||
{
|
||||
txdesc->flags |= 0x80000000;
|
||||
txdesc->field_2f =
|
||||
(char)((((uint32_t)tx_rate_config->ersu + 6) & 0xf) << 3)
|
||||
| (txdesc->field_2f & 0x87);
|
||||
|
||||
if ((uint32_t)tx_rate_config->dcm)
|
||||
txdesc->field_31 |= 0x80;
|
||||
}
|
||||
else if (phymode == WIFI_PHY_MODE_VHT20)
|
||||
txdesc->flags |= 0x1000000;
|
||||
|
||||
// No idea if this is correct, but this is what the original code does...
|
||||
uint32_t bw_is_bw40 = bw == WIFI_BW40;
|
||||
txdesc->field_8 = (bw_is_bw40 << 0xf) | (txdesc->field_8 & 0xffff7fff);
|
||||
|
||||
if (en_sys_seq)
|
||||
txdesc->flags |= 1;
|
||||
|
||||
txdesc->field_10 =
|
||||
(txdesc->field_10 & 0xfff3ffff) | ((ifx & WIFI_IF_MAX) << 0x12);
|
||||
txdesc->field_14 = 0x100;
|
||||
|
||||
ieee80211_post_hmac_tx(eb);
|
||||
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ESP_ERR_NO_MEM;
|
||||
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_wifi.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,130 @@
|
||||
# Vanetza (LGPL-3.0-or-later): upstream riebl/vanetza at the pinned commit plus patches/
|
||||
# (series.cmake), as an ESP-IDF component or, on the host, as the static library `vanetza`.
|
||||
# Only the sources listed in sources.cmake are compiled; the manifest fixes the compiled source set.
|
||||
#
|
||||
# Feature selection follows microbu_v2x: CONFIG_MICROBU_V2X_* on ESP-IDF, V2X_* on the host.
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/series.cmake")
|
||||
vanetza_series_prepare(VANETZA_ROOT)
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/sources.cmake")
|
||||
set(_vanetza_dir "${CMAKE_CURRENT_LIST_DIR}")
|
||||
|
||||
if(ESP_PLATFORM)
|
||||
idf_component_register(SRCS "src/sha.cpp"
|
||||
INCLUDE_DIRS "${VANETZA_ROOT}" "${VANETZA_ROOT}/vanetza/asn1/support"
|
||||
REQUIRES esp-boost
|
||||
PRIV_REQUIRES mbedtls)
|
||||
if(CMAKE_BUILD_EARLY_EXPANSION)
|
||||
return()
|
||||
endif()
|
||||
set(VANETZA_TARGET ${COMPONENT_LIB})
|
||||
foreach(_feature NETWORK CAM DENM VAM SECURITY PKI)
|
||||
set(V2X_${_feature} ${CONFIG_MICROBU_V2X_${_feature}})
|
||||
endforeach()
|
||||
else()
|
||||
foreach(_feature NETWORK CAM DENM VAM SECURITY)
|
||||
if(NOT DEFINED V2X_${_feature})
|
||||
set(V2X_${_feature} ON)
|
||||
endif()
|
||||
endforeach()
|
||||
add_library(vanetza STATIC "${_vanetza_dir}/src/sha.cpp")
|
||||
add_library(Vanetza::vanetza ALIAS vanetza)
|
||||
set(VANETZA_TARGET vanetza)
|
||||
target_include_directories(vanetza PUBLIC "${VANETZA_ROOT}" "${VANETZA_ROOT}/vanetza/asn1/support")
|
||||
if(V2X_BOOST_ROOT)
|
||||
target_include_directories(vanetza SYSTEM PUBLIC "${V2X_BOOST_ROOT}")
|
||||
if(WIN32)
|
||||
target_compile_definitions(vanetza PUBLIC BOOST_NO_USER_CONFIG
|
||||
BOOST_PLATFORM_CONFIG="boost/config/platform/win32.hpp")
|
||||
endif()
|
||||
else()
|
||||
find_package(Boost 1.70 REQUIRED)
|
||||
target_include_directories(vanetza SYSTEM PUBLIC ${Boost_INCLUDE_DIRS})
|
||||
endif()
|
||||
endif()
|
||||
|
||||
target_compile_features(${VANETZA_TARGET} PUBLIC cxx_std_17)
|
||||
set_target_properties(${VANETZA_TARGET} PROPERTIES C_STANDARD 11 CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
|
||||
|
||||
set(_sources ${V2X_BASE_SOURCES})
|
||||
if(V2X_NETWORK)
|
||||
list(APPEND _sources ${V2X_NETWORK_SOURCES} ${V2X_SECURITY_ASN_SOURCES})
|
||||
endif()
|
||||
if(NOT ESP_PLATFORM)
|
||||
# src/sha.cpp: OpenSSL digests on the host, PSA Crypto on the device
|
||||
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
|
||||
target_link_libraries(${VANETZA_TARGET} PRIVATE OpenSSL::Crypto)
|
||||
endif()
|
||||
if(V2X_NETWORK OR V2X_CAM OR V2X_DENM OR V2X_VAM)
|
||||
list(APPEND _sources ${V2X_ASN_SUPPORT_SOURCES})
|
||||
endif()
|
||||
foreach(_service CAM DENM VAM)
|
||||
if(V2X_${_service})
|
||||
list(APPEND _sources ${V2X_${_service}_SOURCES})
|
||||
endif()
|
||||
endforeach()
|
||||
if(V2X_SECURITY)
|
||||
list(APPEND _sources ${V2X_SECURITY_PROVIDER_SOURCES})
|
||||
if(NOT ESP_PLATFORM)
|
||||
# persistence.hpp declares the OpenSSL loaders under this define: keep it PUBLIC.
|
||||
list(APPEND _sources ${V2X_SECURITY_HOST_SOURCES})
|
||||
target_compile_definitions(${VANETZA_TARGET} PUBLIC VANETZA_WITH_OPENSSL)
|
||||
target_compile_definitions(${VANETZA_TARGET} PRIVATE OPENSSL_API_COMPAT=0x10101000L)
|
||||
endif()
|
||||
if(V2X_PKI)
|
||||
list(APPEND _sources ${V2X_PKI_ASN_SOURCES})
|
||||
endif()
|
||||
endif()
|
||||
list(REMOVE_DUPLICATES _sources)
|
||||
target_sources(${VANETZA_TARGET} PRIVATE ${_sources})
|
||||
|
||||
if(V2X_NETWORK)
|
||||
foreach(_module circular_buffer geometry heap rational multiprecision)
|
||||
if(NOT EXISTS "${_vanetza_dir}/third_party/${_module}/include/boost")
|
||||
message(FATAL_ERROR "Missing Boost.${_module}; run git submodule update --init --recursive")
|
||||
endif()
|
||||
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/third_party/${_module}/include")
|
||||
endforeach()
|
||||
# Last-resort fallback headers for older system Boost releases; searched after every real Boost include root.
|
||||
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/compat/include")
|
||||
endif()
|
||||
# Iostreams stream devices are header-only here; esp-boost omits these headers.
|
||||
if(V2X_IOSTREAMS_ROOT)
|
||||
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${V2X_IOSTREAMS_ROOT}")
|
||||
elseif(EXISTS "${_vanetza_dir}/third_party/iostreams/include/boost/iostreams/stream.hpp")
|
||||
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/third_party/iostreams/include")
|
||||
elseif(ESP_PLATFORM)
|
||||
message(FATAL_ERROR "Missing Boost.Iostreams. Run git submodule update --init --recursive or set V2X_IOSTREAMS_ROOT.")
|
||||
endif()
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
target_compile_options(${VANETZA_TARGET} PRIVATE -ffunction-sections -fdata-sections
|
||||
-Wno-error=deprecated-declarations)
|
||||
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15)
|
||||
target_compile_options(${VANETZA_TARGET} PRIVATE -Wno-error=deprecated-variadic-comma-omission)
|
||||
endif()
|
||||
endif()
|
||||
if(ESP_PLATFORM)
|
||||
target_compile_definitions(${VANETZA_TARGET} PUBLIC HAVE_NETINET_IN_H)
|
||||
# The generated IOC table intentionally zero-initializes trailing fields.
|
||||
set_source_files_properties("${VANETZA_ROOT}/vanetza/asn1/its/r2/WrappedExtensionContainer.c"
|
||||
PROPERTIES COMPILE_OPTIONS -Wno-error=missing-field-initializers)
|
||||
# Same for the IOC tables behind HeaderInfo's contributedExtensions; some generated object sets
|
||||
# are referenced by no constraint in this closure.
|
||||
set_source_files_properties(
|
||||
"${VANETZA_ROOT}/vanetza/asn1/security/AppExtension.c"
|
||||
"${VANETZA_ROOT}/vanetza/asn1/security/CertIssueExtension.c"
|
||||
"${VANETZA_ROOT}/vanetza/asn1/security/CertRequestExtension.c"
|
||||
"${VANETZA_ROOT}/vanetza/asn1/security/ContributedExtensionBlock.c"
|
||||
"${VANETZA_ROOT}/vanetza/asn1/security/IeeeExtension.c"
|
||||
PROPERTIES COMPILE_OPTIONS "-Wno-error=missing-field-initializers;-Wno-error=unused-const-variable")
|
||||
# ESP-IDF 6 uses picolibc's native timegm, without a tm_gmtoff member.
|
||||
# Do not confuse the missing struct member with timezone-mutating emulation.
|
||||
if(IDF_VERSION_MAJOR GREATER_EQUAL 6)
|
||||
set_source_files_properties("${VANETZA_ROOT}/vanetza/asn1/support/GeneralizedTime.c"
|
||||
PROPERTIES COMPILE_DEFINITIONS HAVE_TIMEGM)
|
||||
endif()
|
||||
target_compile_options(${VANETZA_TARGET} PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wno-error=unused-function>
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wno-error=maybe-uninitialized>)
|
||||
endif()
|
||||
@@ -0,0 +1,853 @@
|
||||
This file contains copies of the GNU Lesser General Public License as well
|
||||
as the GNU General Public License, both in their third version.
|
||||
|
||||
|
||||
# GNU Lesser General Public License (LGPL) v3
|
||||
|
||||
```
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
```
|
||||
|
||||
|
||||
# GNU General Public License (GPL) v3
|
||||
|
||||
```
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
// Minimal compatibility shim: newer Boost.Geometry (karney_inverse.hpp) calls
|
||||
// boost::core::invoke_swap(), which apt's libboost-dev 1.83 core headers do
|
||||
// not yet provide (only the older boost::swap() in <boost/core/swap.hpp>).
|
||||
// This is intentionally NOT a copy of upstream Boost's invoke_swap.hpp: that
|
||||
// file redefines the boost_swap_impl::is_const helper that <boost/core/swap.hpp>
|
||||
// already defines, which collides when both headers end up in one translation
|
||||
// unit (as happens here, since vanetza/common/position_fix.hpp pulls in
|
||||
// <boost/optional.hpp> -> <boost/core/swap.hpp> ahead of this one). Building
|
||||
// invoke_swap on top of the already-available boost::swap() avoids that clash.
|
||||
#ifndef BOOST_CORE_INVOKE_SWAP_HPP
|
||||
#define BOOST_CORE_INVOKE_SWAP_HPP
|
||||
|
||||
#include <boost/core/swap.hpp>
|
||||
|
||||
namespace boost {
|
||||
namespace core {
|
||||
|
||||
template<class T>
|
||||
inline void invoke_swap(T& left, T& right)
|
||||
{
|
||||
boost::swap(left, right);
|
||||
}
|
||||
|
||||
} // namespace core
|
||||
} // namespace boost
|
||||
|
||||
#endif // BOOST_CORE_INVOKE_SWAP_HPP
|
||||
@@ -0,0 +1,9 @@
|
||||
version: "0.1.0"
|
||||
description: "Modular Vanetza library for ESP-IDF (conformance work in progress)"
|
||||
url: https://github.com/riebl/vanetza
|
||||
repository: https://github.com/riebl/vanetza.git
|
||||
dependencies:
|
||||
idf: ">=5.3"
|
||||
espressif/esp-boost:
|
||||
version: "0.4.1"
|
||||
public: true
|
||||
@@ -0,0 +1,11 @@
|
||||
function(vanetza_series_prepare out)
|
||||
if(VANETZA_SOURCE_DIR)
|
||||
set(${out} "${VANETZA_SOURCE_DIR}" PARENT_SCOPE)
|
||||
else()
|
||||
get_filename_component(_root "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../external/vanetza" ABSOLUTE)
|
||||
if(NOT EXISTS "${_root}/vanetza/common/clock.hpp")
|
||||
message(FATAL_ERROR "Missing vendored Vanetza source at ${_root}")
|
||||
endif()
|
||||
set(${out} "${_root}" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,36 @@
|
||||
// Cryptographic digest adapter for upstream certificate/envelope helpers.
|
||||
// Algorithms are supplied by ESP-IDF PSA Crypto or host OpenSSL, never a dummy.
|
||||
#include <vanetza/security/sha.hpp>
|
||||
#include <stdexcept>
|
||||
#ifdef ESP_PLATFORM
|
||||
#include <psa/crypto.h>
|
||||
#else
|
||||
#include <openssl/sha.h>
|
||||
#endif
|
||||
|
||||
namespace vanetza::security {
|
||||
Sha256Digest calculate_sha256_digest(const std::uint8_t* data, std::size_t size) {
|
||||
Sha256Digest digest {};
|
||||
#ifdef ESP_PLATFORM
|
||||
std::size_t written = 0;
|
||||
if (psa_crypto_init() != PSA_SUCCESS ||
|
||||
psa_hash_compute(PSA_ALG_SHA_256, data, size, digest.data(), digest.size(), &written) != PSA_SUCCESS ||
|
||||
written != digest.size()) throw std::runtime_error("SHA-256 unavailable");
|
||||
#else
|
||||
if (!SHA256(data, size, digest.data())) throw std::runtime_error("SHA-256 failed");
|
||||
#endif
|
||||
return digest;
|
||||
}
|
||||
Sha384Digest calculate_sha384_digest(const std::uint8_t* data, std::size_t size) {
|
||||
Sha384Digest digest {};
|
||||
#ifdef ESP_PLATFORM
|
||||
std::size_t written = 0;
|
||||
if (psa_crypto_init() != PSA_SUCCESS ||
|
||||
psa_hash_compute(PSA_ALG_SHA_384, data, size, digest.data(), digest.size(), &written) != PSA_SUCCESS ||
|
||||
written != digest.size()) throw std::runtime_error("SHA-384 unavailable");
|
||||
#else
|
||||
if (!SHA384(data, size, digest.data())) throw std::runtime_error("SHA-384 failed");
|
||||
#endif
|
||||
return digest;
|
||||
}
|
||||
}
|
||||
Vendored
+65
@@ -0,0 +1,65 @@
|
||||
// Circular buffer library header file.
|
||||
|
||||
// Copyright (c) 2003-2008 Jan Gaspar
|
||||
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
// See www.boost.org/libs/circular_buffer for documentation.
|
||||
|
||||
/*! @file
|
||||
Includes <boost/circular_buffer/base.hpp>
|
||||
*/
|
||||
|
||||
#if !defined(BOOST_CIRCULAR_BUFFER_HPP)
|
||||
#define BOOST_CIRCULAR_BUFFER_HPP
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#include <boost/circular_buffer_fwd.hpp>
|
||||
#include <boost/config/workaround.hpp>
|
||||
#include <boost/static_assert.hpp>
|
||||
|
||||
/*! Debug support control. */
|
||||
#if !defined(BOOST_CB_ENABLE_DEBUG)
|
||||
#define BOOST_CB_ENABLE_DEBUG 0
|
||||
#endif
|
||||
|
||||
/*! INTERNAL ONLY */
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
#include <boost/assert.hpp>
|
||||
#define BOOST_CB_ASSERT(Expr) BOOST_ASSERT(Expr)
|
||||
#else
|
||||
#define BOOST_CB_ASSERT(Expr) ((void)0)
|
||||
#endif
|
||||
|
||||
/*! INTERNAL ONLY */
|
||||
#if BOOST_WORKAROUND(BOOST_BORLANDC, <= 0x0550) || BOOST_WORKAROUND(__MWERKS__, <= 0x2407)
|
||||
#define BOOST_CB_IS_CONVERTIBLE(Iterator, Type) ((void)0)
|
||||
#else
|
||||
#include <iterator>
|
||||
#include <boost/type_traits/is_convertible.hpp>
|
||||
#define BOOST_CB_IS_CONVERTIBLE(Iterator, Type) \
|
||||
BOOST_STATIC_ASSERT((is_convertible<typename std::iterator_traits<Iterator>::value_type, Type>::value))
|
||||
#endif
|
||||
|
||||
/*! INTERNAL ONLY */
|
||||
#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
|
||||
#define BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS BOOST_STATIC_ASSERT(false);
|
||||
#else
|
||||
#define BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS ((void)0);
|
||||
#endif
|
||||
|
||||
#include <boost/circular_buffer/debug.hpp>
|
||||
#include <boost/circular_buffer/details.hpp>
|
||||
#include <boost/circular_buffer/base.hpp>
|
||||
#include <boost/circular_buffer/space_optimized.hpp>
|
||||
|
||||
#undef BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS
|
||||
#undef BOOST_CB_IS_CONVERTIBLE
|
||||
#undef BOOST_CB_ASSERT
|
||||
|
||||
#endif // #if !defined(BOOST_CIRCULAR_BUFFER_HPP)
|
||||
Vendored
+3134
File diff suppressed because it is too large
Load Diff
Vendored
+248
@@ -0,0 +1,248 @@
|
||||
// Debug support for the circular buffer library.
|
||||
|
||||
// Copyright (c) 2003-2008 Jan Gaspar
|
||||
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#if !defined(BOOST_CIRCULAR_BUFFER_DEBUG_HPP)
|
||||
#define BOOST_CIRCULAR_BUFFER_DEBUG_HPP
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
#include <cstring>
|
||||
|
||||
#if defined(BOOST_NO_STDC_NAMESPACE)
|
||||
namespace std {
|
||||
using ::memset;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // BOOST_CB_ENABLE_DEBUG
|
||||
namespace boost {
|
||||
|
||||
namespace cb_details {
|
||||
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
|
||||
// The value the uninitialized memory is filled with.
|
||||
const int UNINITIALIZED = 0xcc;
|
||||
|
||||
template <class T>
|
||||
inline void do_fill_uninitialized_memory(T* data, std::size_t size_in_bytes) BOOST_NOEXCEPT {
|
||||
std::memset(static_cast<void*>(data), UNINITIALIZED, size_in_bytes);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
inline void do_fill_uninitialized_memory(T& /*data*/, std::size_t /*size_in_bytes*/) BOOST_NOEXCEPT {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
|
||||
class debug_iterator_registry;
|
||||
|
||||
/*!
|
||||
\class debug_iterator_base
|
||||
\brief Registers/unregisters iterators into the registry of valid iterators.
|
||||
|
||||
This class is intended to be a base class of an iterator.
|
||||
*/
|
||||
class debug_iterator_base {
|
||||
|
||||
private:
|
||||
// Members
|
||||
|
||||
//! Iterator registry.
|
||||
mutable const debug_iterator_registry* m_registry;
|
||||
|
||||
//! Next iterator in the iterator chain.
|
||||
mutable const debug_iterator_base* m_next;
|
||||
|
||||
public:
|
||||
// Construction/destruction
|
||||
|
||||
//! Default constructor.
|
||||
debug_iterator_base();
|
||||
|
||||
//! Constructor taking the iterator registry as a parameter.
|
||||
debug_iterator_base(const debug_iterator_registry* registry);
|
||||
|
||||
//! Copy constructor.
|
||||
debug_iterator_base(const debug_iterator_base& rhs);
|
||||
|
||||
//! Destructor.
|
||||
~debug_iterator_base();
|
||||
|
||||
// Methods
|
||||
|
||||
//! Assign operator.
|
||||
debug_iterator_base& operator = (const debug_iterator_base& rhs);
|
||||
|
||||
//! Is the iterator valid?
|
||||
bool is_valid(const debug_iterator_registry* registry) const;
|
||||
|
||||
//! Invalidate the iterator.
|
||||
/*!
|
||||
\note The method is const in order to invalidate const iterators, too.
|
||||
*/
|
||||
void invalidate() const;
|
||||
|
||||
//! Return the next iterator in the iterator chain.
|
||||
const debug_iterator_base* next() const;
|
||||
|
||||
//! Set the next iterator in the iterator chain.
|
||||
/*!
|
||||
\note The method is const in order to set a next iterator to a const iterator, too.
|
||||
*/
|
||||
void set_next(const debug_iterator_base* it) const;
|
||||
|
||||
private:
|
||||
// Helpers
|
||||
|
||||
//! Register self as a valid iterator.
|
||||
void register_self();
|
||||
|
||||
//! Unregister self from valid iterators.
|
||||
void unregister_self();
|
||||
};
|
||||
|
||||
/*!
|
||||
\class debug_iterator_registry
|
||||
\brief Registry of valid iterators.
|
||||
|
||||
This class is intended to be a base class of a container.
|
||||
*/
|
||||
class debug_iterator_registry {
|
||||
|
||||
//! Pointer to the chain of valid iterators.
|
||||
mutable const debug_iterator_base* m_iterators;
|
||||
|
||||
public:
|
||||
// Methods
|
||||
|
||||
//! Default constructor.
|
||||
debug_iterator_registry() : m_iterators(0) {}
|
||||
|
||||
//! Register an iterator into the list of valid iterators.
|
||||
/*!
|
||||
\note The method is const in order to register iterators into const containers, too.
|
||||
*/
|
||||
void register_iterator(const debug_iterator_base* it) const {
|
||||
it->set_next(m_iterators);
|
||||
m_iterators = it;
|
||||
}
|
||||
|
||||
//! Unregister an iterator from the list of valid iterators.
|
||||
/*!
|
||||
\note The method is const in order to unregister iterators from const containers, too.
|
||||
*/
|
||||
void unregister_iterator(const debug_iterator_base* it) const {
|
||||
const debug_iterator_base* previous = 0;
|
||||
for (const debug_iterator_base* p = m_iterators; p != it; previous = p, p = p->next()) {}
|
||||
remove(it, previous);
|
||||
}
|
||||
|
||||
//! Invalidate every iterator pointing to the same element as the iterator passed as a parameter.
|
||||
template <class Iterator>
|
||||
void invalidate_iterators(const Iterator& it) {
|
||||
const debug_iterator_base* previous = 0;
|
||||
for (const debug_iterator_base* p = m_iterators; p != 0; p = p->next()) {
|
||||
if (((Iterator*)p)->m_it == it.m_it) {
|
||||
p->invalidate();
|
||||
remove(p, previous);
|
||||
continue;
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
}
|
||||
|
||||
//! Invalidate all iterators except an iterator poining to the same element as the iterator passed as a parameter.
|
||||
template <class Iterator>
|
||||
void invalidate_iterators_except(const Iterator& it) {
|
||||
const debug_iterator_base* previous = 0;
|
||||
for (const debug_iterator_base* p = m_iterators; p != 0; p = p->next()) {
|
||||
if (((Iterator*)p)->m_it != it.m_it) {
|
||||
p->invalidate();
|
||||
remove(p, previous);
|
||||
continue;
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
}
|
||||
|
||||
//! Invalidate all iterators.
|
||||
void invalidate_all_iterators() {
|
||||
for (const debug_iterator_base* p = m_iterators; p != 0; p = p->next())
|
||||
p->invalidate();
|
||||
m_iterators = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
// Helpers
|
||||
|
||||
//! Remove the current iterator from the iterator chain.
|
||||
void remove(const debug_iterator_base* current,
|
||||
const debug_iterator_base* previous) const {
|
||||
if (previous == 0)
|
||||
m_iterators = m_iterators->next();
|
||||
else
|
||||
previous->set_next(current->next());
|
||||
}
|
||||
};
|
||||
|
||||
// Implementation of the debug_iterator_base methods.
|
||||
|
||||
inline debug_iterator_base::debug_iterator_base() : m_registry(0), m_next(0) {}
|
||||
|
||||
inline debug_iterator_base::debug_iterator_base(const debug_iterator_registry* registry)
|
||||
: m_registry(registry), m_next(0) {
|
||||
register_self();
|
||||
}
|
||||
|
||||
inline debug_iterator_base::debug_iterator_base(const debug_iterator_base& rhs)
|
||||
: m_registry(rhs.m_registry), m_next(0) {
|
||||
register_self();
|
||||
}
|
||||
|
||||
inline debug_iterator_base::~debug_iterator_base() { unregister_self(); }
|
||||
|
||||
inline debug_iterator_base& debug_iterator_base::operator = (const debug_iterator_base& rhs) {
|
||||
if (m_registry == rhs.m_registry)
|
||||
return *this;
|
||||
unregister_self();
|
||||
m_registry = rhs.m_registry;
|
||||
register_self();
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline bool debug_iterator_base::is_valid(const debug_iterator_registry* registry) const {
|
||||
return m_registry == registry;
|
||||
}
|
||||
|
||||
inline void debug_iterator_base::invalidate() const { m_registry = 0; }
|
||||
|
||||
inline const debug_iterator_base* debug_iterator_base::next() const { return m_next; }
|
||||
|
||||
inline void debug_iterator_base::set_next(const debug_iterator_base* it) const { m_next = it; }
|
||||
|
||||
inline void debug_iterator_base::register_self() {
|
||||
if (m_registry != 0)
|
||||
m_registry->register_iterator(this);
|
||||
}
|
||||
|
||||
inline void debug_iterator_base::unregister_self() {
|
||||
if (m_registry != 0)
|
||||
m_registry->unregister_iterator(this);
|
||||
}
|
||||
|
||||
#endif // #if BOOST_CB_ENABLE_DEBUG
|
||||
|
||||
} // namespace cb_details
|
||||
|
||||
} // namespace boost
|
||||
|
||||
#endif // #if !defined(BOOST_CIRCULAR_BUFFER_DEBUG_HPP)
|
||||
+491
@@ -0,0 +1,491 @@
|
||||
// Helper classes and functions for the circular buffer.
|
||||
|
||||
// Copyright (c) 2003-2008 Jan Gaspar
|
||||
|
||||
// Copyright 2014,2018 Glen Joseph Fernandes
|
||||
// (glenjofe@gmail.com)
|
||||
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#if !defined(BOOST_CIRCULAR_BUFFER_DETAILS_HPP)
|
||||
#define BOOST_CIRCULAR_BUFFER_DETAILS_HPP
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#include <boost/throw_exception.hpp>
|
||||
#include <boost/core/allocator_access.hpp>
|
||||
#include <boost/core/pointer_traits.hpp>
|
||||
#include <boost/move/move.hpp>
|
||||
#include <boost/type_traits/is_nothrow_move_constructible.hpp>
|
||||
#include <boost/core/no_exceptions_support.hpp>
|
||||
#include <iterator>
|
||||
|
||||
// Silence MS /W4 warnings like C4913:
|
||||
// "user defined binary operator ',' exists but no overload could convert all operands, default built-in binary operator ',' used"
|
||||
// This might happen when previously including some boost headers that overload the coma operator.
|
||||
#if defined(_MSC_VER)
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4913)
|
||||
#endif
|
||||
|
||||
namespace boost {
|
||||
|
||||
namespace cb_details {
|
||||
|
||||
template <class Alloc> struct nonconst_traits;
|
||||
|
||||
template<class ForwardIterator, class Diff, class T, class Alloc>
|
||||
void uninitialized_fill_n_with_alloc(
|
||||
ForwardIterator first, Diff n, const T& item, Alloc& alloc);
|
||||
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a);
|
||||
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
ForwardIterator uninitialized_move_if_noexcept(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a);
|
||||
|
||||
/*!
|
||||
\struct const_traits
|
||||
\brief Defines the data types for a const iterator.
|
||||
*/
|
||||
template <class Alloc>
|
||||
struct const_traits {
|
||||
// Basic types
|
||||
typedef typename Alloc::value_type value_type;
|
||||
typedef typename boost::allocator_const_pointer<Alloc>::type pointer;
|
||||
typedef const value_type& reference;
|
||||
typedef typename boost::allocator_size_type<Alloc>::type size_type;
|
||||
typedef typename boost::allocator_difference_type<Alloc>::type difference_type;
|
||||
|
||||
// Non-const traits
|
||||
typedef nonconst_traits<Alloc> nonconst_self;
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct nonconst_traits
|
||||
\brief Defines the data types for a non-const iterator.
|
||||
*/
|
||||
template <class Alloc>
|
||||
struct nonconst_traits {
|
||||
// Basic types
|
||||
typedef typename Alloc::value_type value_type;
|
||||
typedef typename boost::allocator_pointer<Alloc>::type pointer;
|
||||
typedef value_type& reference;
|
||||
typedef typename boost::allocator_size_type<Alloc>::type size_type;
|
||||
typedef typename boost::allocator_difference_type<Alloc>::type difference_type;
|
||||
|
||||
// Non-const traits
|
||||
typedef nonconst_traits<Alloc> nonconst_self;
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct iterator_wrapper
|
||||
\brief Helper iterator dereference wrapper.
|
||||
*/
|
||||
template <class Iterator>
|
||||
struct iterator_wrapper {
|
||||
mutable Iterator m_it;
|
||||
explicit iterator_wrapper(Iterator it) : m_it(it) {}
|
||||
Iterator operator () () const { return m_it++; }
|
||||
private:
|
||||
iterator_wrapper<Iterator>& operator = (const iterator_wrapper<Iterator>&); // do not generate
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct item_wrapper
|
||||
\brief Helper item dereference wrapper.
|
||||
*/
|
||||
template <class Pointer, class Value>
|
||||
struct item_wrapper {
|
||||
Value m_item;
|
||||
explicit item_wrapper(Value item) : m_item(item) {}
|
||||
Pointer operator () () const { return &m_item; }
|
||||
private:
|
||||
item_wrapper<Pointer, Value>& operator = (const item_wrapper<Pointer, Value>&); // do not generate
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct assign_n
|
||||
\brief Helper functor for assigning n items.
|
||||
*/
|
||||
template <class Value, class Alloc>
|
||||
struct assign_n {
|
||||
typedef typename boost::allocator_size_type<Alloc>::type size_type;
|
||||
size_type m_n;
|
||||
Value m_item;
|
||||
Alloc& m_alloc;
|
||||
assign_n(size_type n, Value item, Alloc& alloc) : m_n(n), m_item(item), m_alloc(alloc) {}
|
||||
template <class Pointer>
|
||||
void operator () (Pointer p) const {
|
||||
uninitialized_fill_n_with_alloc(p, m_n, m_item, m_alloc);
|
||||
}
|
||||
private:
|
||||
assign_n<Value, Alloc>& operator = (const assign_n<Value, Alloc>&); // do not generate
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct assign_range
|
||||
\brief Helper functor for assigning range of items.
|
||||
*/
|
||||
template <class Iterator, class Alloc>
|
||||
struct assign_range {
|
||||
Iterator m_first;
|
||||
Iterator m_last;
|
||||
Alloc& m_alloc;
|
||||
|
||||
assign_range(const Iterator& first, const Iterator& last, Alloc& alloc)
|
||||
: m_first(first), m_last(last), m_alloc(alloc) {}
|
||||
|
||||
template <class Pointer>
|
||||
void operator () (Pointer p) const {
|
||||
boost::cb_details::uninitialized_copy(m_first, m_last, p, m_alloc);
|
||||
}
|
||||
};
|
||||
|
||||
template <class Iterator, class Alloc>
|
||||
inline assign_range<Iterator, Alloc> make_assign_range(const Iterator& first, const Iterator& last, Alloc& a) {
|
||||
return assign_range<Iterator, Alloc>(first, last, a);
|
||||
}
|
||||
|
||||
/*!
|
||||
\class capacity_control
|
||||
\brief Capacity controller of the space optimized circular buffer.
|
||||
*/
|
||||
template <class Size>
|
||||
class capacity_control {
|
||||
|
||||
//! The capacity of the space-optimized circular buffer.
|
||||
Size m_capacity;
|
||||
|
||||
//! The lowest guaranteed or minimum capacity of the adapted space-optimized circular buffer.
|
||||
Size m_min_capacity;
|
||||
|
||||
public:
|
||||
|
||||
//! Constructor.
|
||||
capacity_control(Size buffer_capacity, Size min_buffer_capacity = 0)
|
||||
: m_capacity(buffer_capacity), m_min_capacity(min_buffer_capacity)
|
||||
{ // Check for capacity lower than min_capacity.
|
||||
BOOST_CB_ASSERT(buffer_capacity >= min_buffer_capacity);
|
||||
}
|
||||
|
||||
// Default copy constructor.
|
||||
|
||||
// Default assign operator.
|
||||
|
||||
//! Get the capacity of the space optimized circular buffer.
|
||||
Size capacity() const { return m_capacity; }
|
||||
|
||||
//! Get the minimal capacity of the space optimized circular buffer.
|
||||
Size min_capacity() const { return m_min_capacity; }
|
||||
|
||||
//! Size operator - returns the capacity of the space optimized circular buffer.
|
||||
operator Size() const { return m_capacity; }
|
||||
};
|
||||
|
||||
/*!
|
||||
\struct iterator
|
||||
\brief Random access iterator for the circular buffer.
|
||||
\param Buff The type of the underlying circular buffer.
|
||||
\param Traits Basic iterator types.
|
||||
\note This iterator is not circular. It was designed
|
||||
for iterating from begin() to end() of the circular buffer.
|
||||
*/
|
||||
template <class Buff, class Traits>
|
||||
struct iterator
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
: public debug_iterator_base
|
||||
#endif // #if BOOST_CB_ENABLE_DEBUG
|
||||
{
|
||||
// Helper types
|
||||
|
||||
//! Non-const iterator.
|
||||
typedef iterator<Buff, typename Traits::nonconst_self> nonconst_self;
|
||||
|
||||
// Basic types
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
//! The type of the elements stored in the circular buffer.
|
||||
typedef typename Traits::value_type value_type;
|
||||
|
||||
//! Pointer to the element.
|
||||
typedef typename Traits::pointer pointer;
|
||||
|
||||
//! Reference to the element.
|
||||
typedef typename Traits::reference reference;
|
||||
|
||||
//! Size type.
|
||||
typedef typename Traits::size_type size_type;
|
||||
|
||||
//! Difference type.
|
||||
typedef typename Traits::difference_type difference_type;
|
||||
|
||||
// Member variables
|
||||
|
||||
//! The circular buffer where the iterator points to.
|
||||
const Buff* m_buff;
|
||||
|
||||
//! An internal iterator.
|
||||
pointer m_it;
|
||||
|
||||
// Construction & assignment
|
||||
|
||||
// Default copy constructor.
|
||||
|
||||
//! Default constructor.
|
||||
iterator() : m_buff(0), m_it(0) {}
|
||||
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
|
||||
//! Copy constructor (used for converting from a non-const to a const iterator).
|
||||
iterator(const nonconst_self& it) : debug_iterator_base(it), m_buff(it.m_buff), m_it(it.m_it) {}
|
||||
|
||||
//! Internal constructor.
|
||||
/*!
|
||||
\note This constructor is not intended to be used directly by the user.
|
||||
*/
|
||||
iterator(const Buff* cb, const pointer p) : debug_iterator_base(cb), m_buff(cb), m_it(p) {}
|
||||
|
||||
#else
|
||||
|
||||
iterator(const nonconst_self& it) : m_buff(it.m_buff), m_it(it.m_it) {}
|
||||
|
||||
iterator(const Buff* cb, const pointer p) : m_buff(cb), m_it(p) {}
|
||||
|
||||
#endif // #if BOOST_CB_ENABLE_DEBUG
|
||||
|
||||
//! Assign operator.
|
||||
#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS)
|
||||
iterator& operator=(const iterator&) = default;
|
||||
#else
|
||||
iterator& operator=(const iterator& it) {
|
||||
if (this == &it)
|
||||
return *this;
|
||||
#if BOOST_CB_ENABLE_DEBUG
|
||||
debug_iterator_base::operator =(it);
|
||||
#endif // #if BOOST_CB_ENABLE_DEBUG
|
||||
m_buff = it.m_buff;
|
||||
m_it = it.m_it;
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Random access iterator methods
|
||||
|
||||
//! Dereferencing operator.
|
||||
reference operator * () const {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(m_it != 0); // check for iterator pointing to end()
|
||||
return *m_it;
|
||||
}
|
||||
|
||||
//! Dereferencing operator.
|
||||
pointer operator -> () const { return &(operator*()); }
|
||||
|
||||
//! Difference operator.
|
||||
template <class Traits0>
|
||||
difference_type operator - (const iterator<Buff, Traits0>& it) const {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(it.is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
return linearize_pointer(*this) - linearize_pointer(it);
|
||||
}
|
||||
|
||||
//! Increment operator (prefix).
|
||||
iterator& operator ++ () {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(m_it != 0); // check for iterator pointing to end()
|
||||
m_buff->increment(m_it);
|
||||
if (m_it == m_buff->m_last)
|
||||
m_it = 0;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Increment operator (postfix).
|
||||
iterator operator ++ (int) {
|
||||
iterator<Buff, Traits> tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! Decrement operator (prefix).
|
||||
iterator& operator -- () {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(m_it != m_buff->m_first); // check for iterator pointing to begin()
|
||||
if (m_it == 0)
|
||||
m_it = m_buff->m_last;
|
||||
m_buff->decrement(m_it);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Decrement operator (postfix).
|
||||
iterator operator -- (int) {
|
||||
iterator<Buff, Traits> tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
//! Iterator addition.
|
||||
iterator& operator += (difference_type n) {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
if (n > 0) {
|
||||
BOOST_CB_ASSERT(m_buff->end() - *this >= n); // check for too large n
|
||||
m_it = m_buff->add(m_it, n);
|
||||
if (m_it == m_buff->m_last)
|
||||
m_it = 0;
|
||||
} else if (n < 0) {
|
||||
*this -= -n;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Iterator addition.
|
||||
iterator operator + (difference_type n) const { return iterator<Buff, Traits>(*this) += n; }
|
||||
|
||||
//! Iterator subtraction.
|
||||
iterator& operator -= (difference_type n) {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
if (n > 0) {
|
||||
BOOST_CB_ASSERT(*this - m_buff->begin() >= n); // check for too large n
|
||||
m_it = m_buff->sub(m_it == 0 ? m_buff->m_last : m_it, n);
|
||||
} else if (n < 0) {
|
||||
*this += -n;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Iterator subtraction.
|
||||
iterator operator - (difference_type n) const { return iterator<Buff, Traits>(*this) -= n; }
|
||||
|
||||
//! Element access operator.
|
||||
reference operator [] (difference_type n) const { return *(*this + n); }
|
||||
|
||||
// Equality & comparison
|
||||
|
||||
//! Equality.
|
||||
template <class Traits0>
|
||||
bool operator == (const iterator<Buff, Traits0>& it) const {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(it.is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
return m_it == it.m_it;
|
||||
}
|
||||
|
||||
//! Inequality.
|
||||
template <class Traits0>
|
||||
bool operator != (const iterator<Buff, Traits0>& it) const {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(it.is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
return m_it != it.m_it;
|
||||
}
|
||||
|
||||
//! Less.
|
||||
template <class Traits0>
|
||||
bool operator < (const iterator<Buff, Traits0>& it) const {
|
||||
BOOST_CB_ASSERT(is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
BOOST_CB_ASSERT(it.is_valid(m_buff)); // check for uninitialized or invalidated iterator
|
||||
return linearize_pointer(*this) < linearize_pointer(it);
|
||||
}
|
||||
|
||||
//! Greater.
|
||||
template <class Traits0>
|
||||
bool operator > (const iterator<Buff, Traits0>& it) const { return it < *this; }
|
||||
|
||||
//! Less or equal.
|
||||
template <class Traits0>
|
||||
bool operator <= (const iterator<Buff, Traits0>& it) const { return !(it < *this); }
|
||||
|
||||
//! Greater or equal.
|
||||
template <class Traits0>
|
||||
bool operator >= (const iterator<Buff, Traits0>& it) const { return !(*this < it); }
|
||||
|
||||
// Helpers
|
||||
|
||||
//! Get a pointer which would point to the same element as the iterator in case the circular buffer is linearized.
|
||||
template <class Traits0>
|
||||
typename Traits0::pointer linearize_pointer(const iterator<Buff, Traits0>& it) const {
|
||||
return it.m_it == 0 ? m_buff->m_buff + m_buff->size() :
|
||||
(it.m_it < m_buff->m_first ? it.m_it + (m_buff->m_end - m_buff->m_first)
|
||||
: m_buff->m_buff + (it.m_it - m_buff->m_first));
|
||||
}
|
||||
};
|
||||
|
||||
//! Iterator addition.
|
||||
template <class Buff, class Traits>
|
||||
inline iterator<Buff, Traits>
|
||||
operator + (typename Traits::difference_type n, const iterator<Buff, Traits>& it) {
|
||||
return it + n;
|
||||
}
|
||||
|
||||
/*!
|
||||
\fn ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest)
|
||||
\brief Equivalent of <code>std::uninitialized_copy</code> but with explicit specification of value type.
|
||||
*/
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
inline ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a) {
|
||||
ForwardIterator next = dest;
|
||||
BOOST_TRY {
|
||||
for (; first != last; ++first, ++dest)
|
||||
boost::allocator_construct(a, boost::to_address(dest), *first);
|
||||
} BOOST_CATCH(...) {
|
||||
for (; next != dest; ++next)
|
||||
boost::allocator_destroy(a, boost::to_address(next));
|
||||
BOOST_RETHROW
|
||||
}
|
||||
BOOST_CATCH_END
|
||||
return dest;
|
||||
}
|
||||
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
ForwardIterator uninitialized_move_if_noexcept_impl(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a,
|
||||
true_type) {
|
||||
for (; first != last; ++first, ++dest)
|
||||
boost::allocator_construct(a, boost::to_address(dest), boost::move(*first));
|
||||
return dest;
|
||||
}
|
||||
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
ForwardIterator uninitialized_move_if_noexcept_impl(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a,
|
||||
false_type) {
|
||||
return uninitialized_copy(first, last, dest, a);
|
||||
}
|
||||
|
||||
/*!
|
||||
\fn ForwardIterator uninitialized_move_if_noexcept(InputIterator first, InputIterator last, ForwardIterator dest)
|
||||
\brief Equivalent of <code>std::uninitialized_copy</code> but with explicit specification of value type and moves elements if they have noexcept move constructors.
|
||||
*/
|
||||
template<class InputIterator, class ForwardIterator, class Alloc>
|
||||
ForwardIterator uninitialized_move_if_noexcept(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a) {
|
||||
typedef typename boost::is_nothrow_move_constructible<typename Alloc::value_type>::type tag_t;
|
||||
return uninitialized_move_if_noexcept_impl(first, last, dest, a, tag_t());
|
||||
}
|
||||
|
||||
/*!
|
||||
\fn void uninitialized_fill_n_with_alloc(ForwardIterator first, Diff n, const T& item, Alloc& alloc)
|
||||
\brief Equivalent of <code>std::uninitialized_fill_n</code> with allocator.
|
||||
*/
|
||||
template<class ForwardIterator, class Diff, class T, class Alloc>
|
||||
inline void uninitialized_fill_n_with_alloc(ForwardIterator first, Diff n, const T& item, Alloc& alloc) {
|
||||
ForwardIterator next = first;
|
||||
BOOST_TRY {
|
||||
for (; n > 0; ++first, --n)
|
||||
boost::allocator_construct(alloc, boost::to_address(first), item);
|
||||
} BOOST_CATCH(...) {
|
||||
for (; next != first; ++next)
|
||||
boost::allocator_destroy(alloc, boost::to_address(next));
|
||||
BOOST_RETHROW
|
||||
}
|
||||
BOOST_CATCH_END
|
||||
}
|
||||
|
||||
} // namespace cb_details
|
||||
|
||||
} // namespace boost
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#endif // #if !defined(BOOST_CIRCULAR_BUFFER_DETAILS_HPP)
|
||||
+1713
File diff suppressed because it is too large
Load Diff
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
// Forward declaration of the circular buffer and its adaptor.
|
||||
|
||||
// Copyright (c) 2003-2008 Jan Gaspar
|
||||
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
// See www.boost.org/libs/circular_buffer for documentation.
|
||||
|
||||
#if !defined(BOOST_CIRCULAR_BUFFER_FWD_HPP)
|
||||
#define BOOST_CIRCULAR_BUFFER_FWD_HPP
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#include <boost/config.hpp>
|
||||
#if !defined(BOOST_NO_STD_ALLOCATOR)
|
||||
#include <memory>
|
||||
#else
|
||||
#include <vector>
|
||||
#endif
|
||||
|
||||
namespace boost {
|
||||
|
||||
#if !defined(BOOST_NO_STD_ALLOCATOR)
|
||||
#define BOOST_CB_DEFAULT_ALLOCATOR(T) std::allocator<T>
|
||||
#else
|
||||
#define BOOST_CB_DEFAULT_ALLOCATOR(T) BOOST_DEDUCED_TYPENAME std::vector<T>::allocator_type
|
||||
#endif
|
||||
|
||||
template <class T, class Alloc = BOOST_CB_DEFAULT_ALLOCATOR(T)>
|
||||
class circular_buffer;
|
||||
|
||||
template <class T, class Alloc = BOOST_CB_DEFAULT_ALLOCATOR(T)>
|
||||
class circular_buffer_space_optimized;
|
||||
|
||||
#undef BOOST_CB_DEFAULT_ALLOCATOR
|
||||
|
||||
} // namespace boost
|
||||
|
||||
#endif // #if !defined(BOOST_CIRCULAR_BUFFER_FWD_HPP)
|
||||
@@ -0,0 +1,23 @@
|
||||
Boost Software License - Version 1.0 - August 17th, 2003
|
||||
|
||||
Permission is hereby granted, free of charge, to any person or organization
|
||||
obtaining a copy of the software and accompanying documentation covered by
|
||||
this license (the "Software") to use, reproduce, display, distribute,
|
||||
execute, and transmit the Software, and to prepare derivative works of the
|
||||
Software, and to permit third-parties to whom the Software is furnished to
|
||||
do so, all subject to the following:
|
||||
|
||||
The copyright notices in the Software and this entire statement, including
|
||||
the above license grant, this restriction and the following disclaimer,
|
||||
must be included in all copies of the Software, in whole or in part, and
|
||||
all derivative works of the Software, unless such copies or derivative
|
||||
works are solely in the form of machine-executable object code generated by
|
||||
a source language processor.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
||||
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
||||
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_HPP
|
||||
#define BOOST_GEOMETRY_HPP
|
||||
|
||||
#include <boost/geometry/geometry.hpp>
|
||||
|
||||
#endif // BOOST_GEOMETRY_HPP
|
||||
Vendored
+284
@@ -0,0 +1,284 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2014-2023.
|
||||
// Modifications copyright (c) 2014-2023, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
|
||||
|
||||
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/num_interior_rings.hpp>
|
||||
#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/signed_size_type.hpp>
|
||||
#include <boost/geometry/core/mutable_range.hpp>
|
||||
#include <boost/geometry/core/point_type.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // for backward compatibility
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace append
|
||||
{
|
||||
|
||||
struct append_no_action
|
||||
{
|
||||
template <typename Geometry, typename Point>
|
||||
static inline void apply(Geometry& , Point const& ,
|
||||
signed_size_type = -1, signed_size_type = 0)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
struct to_range_point
|
||||
{
|
||||
template <typename Geometry, typename Point>
|
||||
static inline void apply(Geometry& geometry, Point const& point,
|
||||
signed_size_type = -1, signed_size_type = 0)
|
||||
{
|
||||
geometry::point_type_t<Geometry> copy;
|
||||
geometry::detail::conversion::convert_point_to_point(point, copy);
|
||||
traits::push_back<Geometry>::apply(geometry, copy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct to_range_range
|
||||
{
|
||||
template <typename Geometry, typename Range>
|
||||
static inline void apply(Geometry& geometry, Range const& range,
|
||||
signed_size_type = -1, signed_size_type = 0)
|
||||
{
|
||||
using point_type = typename boost::range_value<Range>::type;
|
||||
|
||||
auto const end = boost::end(range);
|
||||
for (auto it = boost::begin(range); it != end; ++it)
|
||||
{
|
||||
to_range_point::apply<Geometry, point_type>(geometry, *it);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct to_polygon_point
|
||||
{
|
||||
template <typename Polygon, typename Point>
|
||||
static inline void apply(Polygon& polygon, Point const& point,
|
||||
signed_size_type ring_index, signed_size_type = 0)
|
||||
{
|
||||
using ring_type = ring_type_t<Polygon>;
|
||||
|
||||
if (ring_index == -1)
|
||||
{
|
||||
auto&& ext_ring = exterior_ring(polygon);
|
||||
to_range_point::apply<ring_type, Point>(ext_ring, point);
|
||||
}
|
||||
else if (ring_index < signed_size_type(num_interior_rings(polygon)))
|
||||
{
|
||||
auto&& int_rings = interior_rings(polygon);
|
||||
to_range_point::apply<ring_type, Point>(range::at(int_rings, ring_index), point);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct to_polygon_range
|
||||
{
|
||||
template <typename Polygon, typename Range>
|
||||
static inline void apply(Polygon& polygon, Range const& range,
|
||||
signed_size_type ring_index, signed_size_type = 0)
|
||||
{
|
||||
using ring_type = ring_type_t<Polygon>;
|
||||
|
||||
if (ring_index == -1)
|
||||
{
|
||||
auto&& ext_ring = exterior_ring(polygon);
|
||||
to_range_range::apply<ring_type, Range>(ext_ring, range);
|
||||
}
|
||||
else if (ring_index < signed_size_type(num_interior_rings(polygon)))
|
||||
{
|
||||
auto&& int_rings = interior_rings(polygon);
|
||||
to_range_range::apply<ring_type, Range>(range::at(int_rings, ring_index), range);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Policy>
|
||||
struct to_multigeometry
|
||||
{
|
||||
template <typename MultiGeometry, typename RangeOrPoint>
|
||||
static inline void apply(MultiGeometry& multigeometry,
|
||||
RangeOrPoint const& range_or_point,
|
||||
signed_size_type ring_index, signed_size_type multi_index)
|
||||
{
|
||||
Policy::template apply
|
||||
<
|
||||
typename boost::range_value<MultiGeometry>::type,
|
||||
RangeOrPoint
|
||||
>(range::at(multigeometry, multi_index), range_or_point, ring_index);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::append
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename RangeOrPoint,
|
||||
typename Tag = geometry::tag_t<Geometry>,
|
||||
typename OtherTag = geometry::tag_t<RangeOrPoint>
|
||||
>
|
||||
struct append
|
||||
: detail::append::append_no_action
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename Point>
|
||||
struct append<Geometry, Point, linestring_tag, point_tag>
|
||||
: detail::append::to_range_point
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename Point>
|
||||
struct append<Geometry, Point, ring_tag, point_tag>
|
||||
: detail::append::to_range_point
|
||||
{};
|
||||
|
||||
template <typename Polygon, typename Point>
|
||||
struct append<Polygon, Point, polygon_tag, point_tag>
|
||||
: detail::append::to_polygon_point
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename Range, typename RangeTag>
|
||||
struct append<Geometry, Range, linestring_tag, RangeTag>
|
||||
: detail::append::to_range_range
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename Range, typename RangeTag>
|
||||
struct append<Geometry, Range, ring_tag, RangeTag>
|
||||
: detail::append::to_range_range
|
||||
{};
|
||||
|
||||
template <typename Polygon, typename Range, typename RangeTag>
|
||||
struct append<Polygon, Range, polygon_tag, RangeTag>
|
||||
: detail::append::to_polygon_range
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry, typename Point>
|
||||
struct append<Geometry, Point, multi_point_tag, point_tag>
|
||||
: detail::append::to_range_point
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename Range, typename RangeTag>
|
||||
struct append<Geometry, Range, multi_point_tag, RangeTag>
|
||||
: detail::append::to_range_range
|
||||
{};
|
||||
|
||||
template <typename MultiGeometry, typename Point>
|
||||
struct append<MultiGeometry, Point, multi_linestring_tag, point_tag>
|
||||
: detail::append::to_multigeometry<detail::append::to_range_point>
|
||||
{};
|
||||
|
||||
template <typename MultiGeometry, typename Range, typename RangeTag>
|
||||
struct append<MultiGeometry, Range, multi_linestring_tag, RangeTag>
|
||||
: detail::append::to_multigeometry<detail::append::to_range_range>
|
||||
{};
|
||||
|
||||
template <typename MultiGeometry, typename Point>
|
||||
struct append<MultiGeometry, Point, multi_polygon_tag, point_tag>
|
||||
: detail::append::to_multigeometry<detail::append::to_polygon_point>
|
||||
{};
|
||||
|
||||
template <typename MultiGeometry, typename Range, typename RangeTag>
|
||||
struct append<MultiGeometry, Range, multi_polygon_tag, RangeTag>
|
||||
: detail::append::to_multigeometry<detail::append::to_polygon_range>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry, typename RangeOrPoint, typename OtherTag>
|
||||
struct append<Geometry, RangeOrPoint, dynamic_geometry_tag, OtherTag>
|
||||
{
|
||||
static inline void apply(Geometry& geometry,
|
||||
RangeOrPoint const& range_or_point,
|
||||
signed_size_type ring_index, signed_size_type multi_index)
|
||||
{
|
||||
traits::visit<Geometry>::apply([&](auto & g)
|
||||
{
|
||||
append
|
||||
<
|
||||
std::remove_reference_t<decltype(g)>, RangeOrPoint
|
||||
>::apply(g, range_or_point, ring_index, multi_index);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
// TODO: It's unclear how append should work for GeometryCollection because
|
||||
// it can hold multiple different geometries.
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
/*!
|
||||
\brief Appends one or more points to a linestring, ring, polygon, multi-geometry
|
||||
\ingroup append
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam RangeOrPoint Either a range or a point, fullfilling Boost.Range concept or Boost.Geometry Point Concept
|
||||
\param geometry \param_geometry
|
||||
\param range_or_point The point or range to add
|
||||
\param ring_index The index of the ring in case of a polygon:
|
||||
exterior ring (-1, the default) or interior ring index
|
||||
\param multi_index The index of the geometry to which the points are appended
|
||||
|
||||
\qbk{[include reference/algorithms/append.qbk]}
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename RangeOrPoint>
|
||||
inline void append(Geometry& geometry, RangeOrPoint const& range_or_point,
|
||||
signed_size_type ring_index = -1, signed_size_type multi_index = 0)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::append
|
||||
<
|
||||
Geometry, RangeOrPoint
|
||||
>::apply(geometry, range_or_point, ring_index, multi_index);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
|
||||
Vendored
+361
@@ -0,0 +1,361 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2017-2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2017-2023.
|
||||
// Modifications copyright (c) 2017-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_AREA_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_AREA_HPP
|
||||
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/core/closure.hpp>
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/interior_rings.hpp>
|
||||
#include <boost/geometry/core/point_order.hpp>
|
||||
#include <boost/geometry/core/point_type.hpp>
|
||||
#include <boost/geometry/core/ring_type.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/calculate_null.hpp>
|
||||
#include <boost/geometry/algorithms/detail/calculate_sum.hpp>
|
||||
// #include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>
|
||||
#include <boost/geometry/algorithms/detail/multi_sum.hpp>
|
||||
#include <boost/geometry/algorithms/detail/visit.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/area_result.hpp>
|
||||
#include <boost/geometry/algorithms/default_area_result.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/area/services.hpp>
|
||||
#include <boost/geometry/strategies/area/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/area/geographic.hpp>
|
||||
#include <boost/geometry/strategies/area/spherical.hpp>
|
||||
#include <boost/geometry/strategies/concepts/area_concept.hpp>
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
|
||||
#include <boost/geometry/views/detail/closed_clockwise_view.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace area
|
||||
{
|
||||
|
||||
struct box_area
|
||||
{
|
||||
template <typename Box, typename Strategies>
|
||||
static inline auto
|
||||
apply(Box const& box, Strategies const& strategies)
|
||||
{
|
||||
// Currently only works for 2D Cartesian boxes
|
||||
assert_dimension<Box, 2>();
|
||||
|
||||
return strategies.area(box).apply(box);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct ring_area
|
||||
{
|
||||
template <typename Ring, typename Strategies>
|
||||
static inline typename area_result<Ring, Strategies>::type
|
||||
apply(Ring const& ring, Strategies const& strategies)
|
||||
{
|
||||
using strategy_type = decltype(strategies.area(ring));
|
||||
|
||||
BOOST_CONCEPT_ASSERT( (geometry::concepts::AreaStrategy<Ring, strategy_type>) );
|
||||
assert_dimension<Ring, 2>();
|
||||
|
||||
// Ignore warning (because using static method sometimes) on strategy
|
||||
boost::ignore_unused(strategies);
|
||||
|
||||
// An open ring has at least three points,
|
||||
// A closed ring has at least four points,
|
||||
// if not, there is no (zero) area
|
||||
if (boost::size(ring) < detail::minimum_ring_size<Ring>::value)
|
||||
{
|
||||
return typename area_result<Ring, Strategies>::type();
|
||||
}
|
||||
|
||||
detail::closed_clockwise_view<Ring const> const view(ring);
|
||||
auto it = boost::begin(view);
|
||||
auto const end = boost::end(view);
|
||||
|
||||
strategy_type const strategy = strategies.area(ring);
|
||||
typename strategy_type::template state<Ring> state;
|
||||
|
||||
for (auto previous = it++; it != end; ++previous, ++it)
|
||||
{
|
||||
strategy.apply(*previous, *it, state);
|
||||
}
|
||||
|
||||
return strategy.result(state);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::area
|
||||
|
||||
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename Tag = tag_t<Geometry>
|
||||
>
|
||||
struct area : detail::calculate_null
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
return calculate_null::apply
|
||||
<
|
||||
typename area_result<Geometry, Strategy>::type
|
||||
>(geometry, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct area<Geometry, box_tag> : detail::area::box_area
|
||||
{};
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct area<Ring, ring_tag>
|
||||
: detail::area::ring_area
|
||||
{};
|
||||
|
||||
|
||||
template <typename Polygon>
|
||||
struct area<Polygon, polygon_tag> : detail::calculate_polygon_sum
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(Polygon const& polygon, Strategy const& strategy)
|
||||
{
|
||||
return calculate_polygon_sum::apply
|
||||
<
|
||||
typename area_result<Polygon, Strategy>::type,
|
||||
detail::area::ring_area
|
||||
>(polygon, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename MultiGeometry>
|
||||
struct area<MultiGeometry, multi_polygon_tag> : detail::multi_sum
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(MultiGeometry const& multi, Strategy const& strategy)
|
||||
{
|
||||
return multi_sum::apply
|
||||
<
|
||||
typename area_result<MultiGeometry, Strategy>::type,
|
||||
area<typename boost::range_value<MultiGeometry>::type>
|
||||
>(multi, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value
|
||||
>
|
||||
struct area
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
return dispatch::area<Geometry>::apply(geometry, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct area<Strategy, false>
|
||||
{
|
||||
template <typename Geometry>
|
||||
static auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
using strategies::area::services::strategy_converter;
|
||||
return dispatch::area
|
||||
<
|
||||
Geometry
|
||||
>::apply(geometry, strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct area<default_strategy, false>
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline auto apply(Geometry const& geometry, default_strategy)
|
||||
{
|
||||
typedef typename strategies::area::services::default_strategy
|
||||
<
|
||||
Geometry
|
||||
>::type strategy_type;
|
||||
|
||||
return dispatch::area<Geometry>::apply(geometry, strategy_type());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_dynamic
|
||||
{
|
||||
|
||||
template <typename Geometry, typename Tag = geometry::tag_t<Geometry>>
|
||||
struct area
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
return resolve_strategy::area<Strategy>::apply(geometry, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct area<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
typename area_result<Geometry, Strategy>::type result = 0;
|
||||
traits::visit<Geometry>::apply([&](auto const& g)
|
||||
{
|
||||
result = area<util::remove_cref_t<decltype(g)>>::apply(g, strategy);
|
||||
}, geometry);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct area<Geometry, geometry_collection_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline auto apply(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
typename area_result<Geometry, Strategy>::type result = 0;
|
||||
detail::visit_breadth_first([&](auto const& g)
|
||||
{
|
||||
result += area<util::remove_cref_t<decltype(g)>>::apply(g, strategy);
|
||||
return true;
|
||||
}, geometry);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{area}
|
||||
\ingroup area
|
||||
\details \details_calc{area}. \details_default_strategy
|
||||
|
||||
The area algorithm calculates the surface area of all geometries having a surface, namely
|
||||
box, polygon, ring, multipolygon. The units are the square of the units used for the points
|
||||
defining the surface. If subject geometry is defined in meters, then area is calculated
|
||||
in square meters.
|
||||
|
||||
The area calculation can be done in all three common coordinate systems, Cartesian, Spherical
|
||||
and Geographic as well.
|
||||
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry
|
||||
\return \return_calc{area}
|
||||
|
||||
\qbk{[include reference/algorithms/area.qbk]}
|
||||
\qbk{[heading Examples]}
|
||||
\qbk{[area] [area_output]}
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline auto area(Geometry const& geometry)
|
||||
{
|
||||
concepts::check<Geometry const>();
|
||||
|
||||
// detail::throw_on_empty_input(geometry);
|
||||
|
||||
return resolve_dynamic::area<Geometry>::apply(geometry, default_strategy());
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{area} \brief_strategy
|
||||
\ingroup area
|
||||
\details \details_calc{area} \brief_strategy. \details_strategy_reasons
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Strategy \tparam_strategy{Area}
|
||||
\param geometry \param_geometry
|
||||
\param strategy \param_strategy{area}
|
||||
\return \return_calc{area}
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
|
||||
\qbk{
|
||||
[include reference/algorithms/area.qbk]
|
||||
|
||||
[heading Available Strategies]
|
||||
\* [link geometry.reference.strategies.strategy_area_cartesian Cartesian]
|
||||
\* [link geometry.reference.strategies.strategy_area_spherical Spherical]
|
||||
\* [link geometry.reference.strategies.strategy_area_geographic Geographic]
|
||||
|
||||
[heading Example]
|
||||
[area_with_strategy]
|
||||
[area_with_strategy_output]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Strategy>
|
||||
inline auto area(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
concepts::check<Geometry const>();
|
||||
|
||||
// detail::throw_on_empty_input(geometry);
|
||||
|
||||
return resolve_dynamic::area<Geometry>::apply(geometry, strategy);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_AREA_HPP
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// Boost.Geometry
|
||||
|
||||
// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2020-2023.
|
||||
// Modifications copyright (c) 2020-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_AREA_RESULT_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_AREA_RESULT_HPP
|
||||
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/select_geometry_type.hpp>
|
||||
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/area/services.hpp>
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
#include <boost/geometry/strategies/detail.hpp>
|
||||
|
||||
#include <boost/geometry/util/select_most_precise.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace area
|
||||
{
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename Strategy,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value
|
||||
>
|
||||
struct area_result
|
||||
{
|
||||
typedef decltype(std::declval<Strategy>().area(std::declval<Geometry>())) strategy_type;
|
||||
typedef typename strategy_type::template result_type<Geometry>::type type;
|
||||
};
|
||||
|
||||
template <typename Geometry, typename Strategy>
|
||||
struct area_result<Geometry, Strategy, false>
|
||||
{
|
||||
typedef typename Strategy::template result_type<Geometry>::type type;
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct default_area_result
|
||||
: area_result
|
||||
<
|
||||
Geometry,
|
||||
typename geometry::strategies::area::services::default_strategy
|
||||
<
|
||||
Geometry
|
||||
>::type
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Curr, typename Next>
|
||||
struct more_precise_coordinate_type
|
||||
: std::is_same
|
||||
<
|
||||
typename geometry::coordinate_type<Curr>::type,
|
||||
typename geometry::select_most_precise
|
||||
<
|
||||
typename geometry::coordinate_type<Curr>::type,
|
||||
typename geometry::coordinate_type<Next>::type
|
||||
>::type
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Curr, typename Next>
|
||||
struct more_precise_default_area_result
|
||||
: std::is_same
|
||||
<
|
||||
typename default_area_result<Curr>::type,
|
||||
typename geometry::select_most_precise
|
||||
<
|
||||
typename default_area_result<Curr>::type,
|
||||
typename default_area_result<Next>::type
|
||||
>::type
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
}} // namespace detail::area
|
||||
#endif //DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
/*!
|
||||
\brief Meta-function defining return type of area function
|
||||
\ingroup area
|
||||
\note The return-type is defined by Geometry and Strategy
|
||||
*/
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename Strategy = default_strategy
|
||||
>
|
||||
struct area_result
|
||||
: detail::area::area_result
|
||||
<
|
||||
typename detail::select_geometry_type
|
||||
<
|
||||
Geometry,
|
||||
detail::area::more_precise_coordinate_type
|
||||
>::type,
|
||||
Strategy
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct area_result<Geometry, default_strategy>
|
||||
: detail::area::default_area_result
|
||||
<
|
||||
typename detail::select_geometry_type
|
||||
<
|
||||
Geometry,
|
||||
detail::area::more_precise_default_area_result
|
||||
>::type
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_AREA_RESULT_HPP
|
||||
Vendored
+367
@@ -0,0 +1,367 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2014 Samuel Debionne, Grenoble, France.
|
||||
// Copyright (c) 2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2020-2023.
|
||||
// Modifications copyright (c) 2020-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP
|
||||
|
||||
#include <boost/variant/static_visitor.hpp>
|
||||
#include <boost/variant/variant_fwd.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/append.hpp>
|
||||
#include <boost/geometry/algorithms/clear.hpp>
|
||||
#include <boost/geometry/algorithms/convert.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/assign_box_corners.hpp>
|
||||
#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/assign_values.hpp>
|
||||
|
||||
#include <boost/geometry/core/static_assert.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
/*!
|
||||
\brief Assign a range of points to a linestring, ring or polygon
|
||||
\note The point-type of the range might be different from the point-type of the geometry
|
||||
\ingroup assign
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Range \tparam_range_point
|
||||
\param geometry \param_geometry
|
||||
\param range \param_range_point
|
||||
|
||||
\qbk{
|
||||
[heading Notes]
|
||||
[note Assign automatically clears the geometry before assigning (use append if you don't want that)]
|
||||
[heading Example]
|
||||
[assign_points] [assign_points_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.append append]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Range>
|
||||
inline void assign_points(Geometry& geometry, Range const& range)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
clear(geometry);
|
||||
geometry::append(geometry, range, -1, 0);
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief assign to a box inverse infinite
|
||||
\details The assign_inverse function initialize a 2D or 3D box with large coordinates, the
|
||||
min corner is very large, the max corner is very small. This is a convenient starting point to
|
||||
collect the minimum bounding box of a geometry.
|
||||
\ingroup assign
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_inverse] [assign_inverse_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.make.make_inverse make_inverse]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline void assign_inverse(Geometry& geometry)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::assign_inverse
|
||||
<
|
||||
tag_t<Geometry>,
|
||||
Geometry
|
||||
>::apply(geometry);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief assign zero values to a box, point
|
||||
\ingroup assign
|
||||
\details The assign_zero function initializes a 2D or 3D point or box with coordinates of zero
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry
|
||||
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline void assign_zero(Geometry& geometry)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::assign_zero
|
||||
<
|
||||
tag_t<Geometry>,
|
||||
Geometry
|
||||
>::apply(geometry);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief Assign two coordinates to a geometry (usually a 2D point)
|
||||
\ingroup assign
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Type \tparam_numeric to specify the coordinates
|
||||
\param geometry \param_geometry
|
||||
\param c1 \param_x
|
||||
\param c2 \param_y
|
||||
|
||||
\qbk{distinguish, 2 coordinate values}
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_2d_point] [assign_2d_point_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.make.make_2_2_coordinate_values make]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Type>
|
||||
inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::assign
|
||||
<
|
||||
tag_t<Geometry>,
|
||||
Geometry,
|
||||
geometry::dimension<Geometry>::value
|
||||
>::apply(geometry, c1, c2);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief Assign three values to a geometry (usually a 3D point)
|
||||
\ingroup assign
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Type \tparam_numeric to specify the coordinates
|
||||
\param geometry \param_geometry
|
||||
\param c1 \param_x
|
||||
\param c2 \param_y
|
||||
\param c3 \param_z
|
||||
|
||||
\qbk{distinguish, 3 coordinate values}
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_3d_point] [assign_3d_point_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.make.make_3_3_coordinate_values make]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Type>
|
||||
inline void assign_values(Geometry& geometry,
|
||||
Type const& c1, Type const& c2, Type const& c3)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::assign
|
||||
<
|
||||
tag_t<Geometry>,
|
||||
Geometry,
|
||||
geometry::dimension<Geometry>::value
|
||||
>::apply(geometry, c1, c2, c3);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief Assign four values to a geometry (usually a box or segment)
|
||||
\ingroup assign
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Type \tparam_numeric to specify the coordinates
|
||||
\param geometry \param_geometry
|
||||
\param c1 First coordinate (usually x1)
|
||||
\param c2 Second coordinate (usually y1)
|
||||
\param c3 Third coordinate (usually x2)
|
||||
\param c4 Fourth coordinate (usually y2)
|
||||
|
||||
\qbk{distinguish, 4 coordinate values}
|
||||
*/
|
||||
template <typename Geometry, typename Type>
|
||||
inline void assign_values(Geometry& geometry,
|
||||
Type const& c1, Type const& c2, Type const& c3, Type const& c4)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::assign
|
||||
<
|
||||
tag_t<Geometry>,
|
||||
Geometry,
|
||||
geometry::dimension<Geometry>::value
|
||||
>::apply(geometry, c1, c2, c3, c4);
|
||||
}
|
||||
|
||||
|
||||
|
||||
namespace resolve_variant
|
||||
{
|
||||
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
struct assign
|
||||
{
|
||||
static inline void
|
||||
apply(Geometry1& geometry1, Geometry2 const& geometry2)
|
||||
{
|
||||
concepts::check<Geometry1>();
|
||||
concepts::check<Geometry2 const>();
|
||||
concepts::check_concepts_and_equal_dimensions<Geometry1, Geometry2 const>();
|
||||
|
||||
static bool const same_point_order
|
||||
= point_order<Geometry1>::value == point_order<Geometry2>::value;
|
||||
BOOST_GEOMETRY_STATIC_ASSERT(
|
||||
same_point_order,
|
||||
"Assign is not supported for different point orders.",
|
||||
Geometry1, Geometry2);
|
||||
static bool const same_closure
|
||||
= closure<Geometry1>::value == closure<Geometry2>::value;
|
||||
BOOST_GEOMETRY_STATIC_ASSERT(
|
||||
same_closure,
|
||||
"Assign is not supported for different closures.",
|
||||
Geometry1, Geometry2);
|
||||
|
||||
dispatch::convert<Geometry2, Geometry1>::apply(geometry2, geometry1);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2>
|
||||
struct assign<variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2>
|
||||
{
|
||||
struct visitor: static_visitor<void>
|
||||
{
|
||||
Geometry2 const& m_geometry2;
|
||||
|
||||
visitor(Geometry2 const& geometry2)
|
||||
: m_geometry2(geometry2)
|
||||
{}
|
||||
|
||||
template <typename Geometry1>
|
||||
result_type operator()(Geometry1& geometry1) const
|
||||
{
|
||||
return assign
|
||||
<
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply
|
||||
(geometry1, m_geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
static inline void
|
||||
apply(variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry1,
|
||||
Geometry2 const& geometry2)
|
||||
{
|
||||
return boost::apply_visitor(visitor(geometry2), geometry1);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)>
|
||||
struct assign<Geometry1, variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
|
||||
{
|
||||
struct visitor: static_visitor<void>
|
||||
{
|
||||
Geometry1& m_geometry1;
|
||||
|
||||
visitor(Geometry1 const& geometry1)
|
||||
: m_geometry1(geometry1)
|
||||
{}
|
||||
|
||||
template <typename Geometry2>
|
||||
result_type operator()(Geometry2 const& geometry2) const
|
||||
{
|
||||
return assign
|
||||
<
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply
|
||||
(m_geometry1, geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
static inline void
|
||||
apply(Geometry1& geometry1,
|
||||
variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2)
|
||||
{
|
||||
return boost::apply_visitor(visitor(geometry1), geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2)>
|
||||
struct assign<variant<BOOST_VARIANT_ENUM_PARAMS(T1)>, variant<BOOST_VARIANT_ENUM_PARAMS(T2)> >
|
||||
{
|
||||
struct visitor: static_visitor<void>
|
||||
{
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
result_type operator()(
|
||||
Geometry1& geometry1,
|
||||
Geometry2 const& geometry2) const
|
||||
{
|
||||
return assign
|
||||
<
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply
|
||||
(geometry1, geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
static inline void
|
||||
apply(variant<BOOST_VARIANT_ENUM_PARAMS(T1)>& geometry1,
|
||||
variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const& geometry2)
|
||||
{
|
||||
return boost::apply_visitor(visitor(), geometry1, geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_variant
|
||||
|
||||
|
||||
/*!
|
||||
\brief Assigns one geometry to another geometry
|
||||
\details The assign algorithm assigns one geometry, e.g. a BOX, to another
|
||||
geometry, e.g. a RING. This only works if it is possible and applicable.
|
||||
\ingroup assign
|
||||
\tparam Geometry1 \tparam_geometry
|
||||
\tparam Geometry2 \tparam_geometry
|
||||
\param geometry1 \param_geometry (target)
|
||||
\param geometry2 \param_geometry (source)
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign] [assign_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.convert convert]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
inline void assign(Geometry1& geometry1, Geometry2 const& geometry2)
|
||||
{
|
||||
resolve_variant::assign<Geometry1, Geometry2>::apply(geometry1, geometry2);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_ASSIGN_HPP
|
||||
Vendored
+221
@@ -0,0 +1,221 @@
|
||||
// Boost.Geometry
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// This file was modified by Oracle on 2014-2023.
|
||||
// Modifications copyright (c) 2014-2023, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP
|
||||
|
||||
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
|
||||
#include <boost/geometry/core/radian_access.hpp>
|
||||
#include <boost/geometry/core/tag.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
#include <boost/geometry/strategies/azimuth/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/azimuth/geographic.hpp>
|
||||
#include <boost/geometry/strategies/azimuth/spherical.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail
|
||||
{
|
||||
|
||||
} // namespace detail
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1, typename Geometry2,
|
||||
typename Tag1 = typename tag<Geometry1>::type,
|
||||
typename Tag2 = typename tag<Geometry2>::type
|
||||
>
|
||||
struct azimuth : not_implemented<Tag1, Tag2>
|
||||
{};
|
||||
|
||||
template <typename Point1, typename Point2>
|
||||
struct azimuth<Point1, Point2, point_tag, point_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static auto apply(Point1 const& p1, Point2 const& p2, Strategy const& strategy)
|
||||
{
|
||||
typedef typename decltype(strategy.azimuth())::template result_type
|
||||
<
|
||||
typename coordinate_type<Point1>::type,
|
||||
typename coordinate_type<Point2>::type
|
||||
>::type calc_t;
|
||||
|
||||
calc_t result = 0;
|
||||
calc_t const x1 = geometry::get_as_radian<0>(p1);
|
||||
calc_t const y1 = geometry::get_as_radian<1>(p1);
|
||||
calc_t const x2 = geometry::get_as_radian<0>(p2);
|
||||
calc_t const y2 = geometry::get_as_radian<1>(p2);
|
||||
|
||||
strategy.azimuth().apply(x1, y1, x2, y2, result);
|
||||
|
||||
// NOTE: It is not clear which units we should use for the result.
|
||||
// For now radians are always returned but a user could expect
|
||||
// e.g. something like this:
|
||||
/*
|
||||
bool const both_degree = std::is_same
|
||||
<
|
||||
typename detail::cs_angular_units<Point1>::type,
|
||||
geometry::degree
|
||||
>::value
|
||||
&& std::is_same
|
||||
<
|
||||
typename detail::cs_angular_units<Point2>::type,
|
||||
geometry::degree
|
||||
>::value;
|
||||
if (both_degree)
|
||||
{
|
||||
result *= math::r2d<calc_t>();
|
||||
}
|
||||
*/
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value
|
||||
>
|
||||
struct azimuth
|
||||
{
|
||||
template <typename P1, typename P2>
|
||||
static auto apply(P1 const& p1, P2 const& p2, Strategy const& strategy)
|
||||
{
|
||||
return dispatch::azimuth<P1, P2>::apply(p1, p2, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct azimuth<Strategy, false>
|
||||
{
|
||||
template <typename P1, typename P2>
|
||||
static auto apply(P1 const& p1, P2 const& p2, Strategy const& strategy)
|
||||
{
|
||||
using strategies::azimuth::services::strategy_converter;
|
||||
return dispatch::azimuth
|
||||
<
|
||||
P1, P2
|
||||
>::apply(p1, p2, strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct azimuth<default_strategy, false>
|
||||
{
|
||||
template <typename P1, typename P2>
|
||||
static auto apply(P1 const& p1, P2 const& p2, default_strategy)
|
||||
{
|
||||
typedef typename strategies::azimuth::services::default_strategy
|
||||
<
|
||||
P1, P2
|
||||
>::type strategy_type;
|
||||
|
||||
return dispatch::azimuth<P1, P2>::apply(p1, p2, strategy_type());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_variant
|
||||
{
|
||||
} // namespace resolve_variant
|
||||
|
||||
|
||||
/*!
|
||||
\brief Calculate azimuth of a segment defined by a pair of points.
|
||||
\ingroup azimuth
|
||||
\tparam Point1 Type of the first point of a segment.
|
||||
\tparam Point2 Type of the second point of a segment.
|
||||
\param point1 First point of a segment.
|
||||
\param point2 Second point of a segment.
|
||||
\return Azimuth in radians.
|
||||
|
||||
\qbk{[include reference/algorithms/azimuth.qbk]}
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[azimuth]
|
||||
[azimuth_output]
|
||||
}
|
||||
*/
|
||||
template <typename Point1, typename Point2>
|
||||
inline auto azimuth(Point1 const& point1, Point2 const& point2)
|
||||
{
|
||||
concepts::check<Point1 const>();
|
||||
concepts::check<Point2 const>();
|
||||
|
||||
return resolve_strategy::azimuth
|
||||
<
|
||||
default_strategy
|
||||
>::apply(point1, point2, default_strategy());
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief Calculate azimuth of a segment defined by a pair of points.
|
||||
\ingroup azimuth
|
||||
\tparam Point1 Type of the first point of a segment.
|
||||
\tparam Point2 Type of the second point of a segment.
|
||||
\tparam Strategy Type of an umbrella strategy defining azimuth strategy.
|
||||
\param point1 First point of a segment.
|
||||
\param point2 Second point of a segment.
|
||||
\param strategy Umbrella strategy defining azimuth strategy.
|
||||
\return Azimuth in radians.
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
\qbk{[include reference/algorithms/azimuth.qbk]}
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[azimuth_strategy]
|
||||
[azimuth_strategy_output]
|
||||
}
|
||||
*/
|
||||
template <typename Point1, typename Point2, typename Strategy>
|
||||
inline auto azimuth(Point1 const& point1, Point2 const& point2, Strategy const& strategy)
|
||||
{
|
||||
concepts::check<Point1 const>();
|
||||
concepts::check<Point2 const>();
|
||||
|
||||
return resolve_strategy::azimuth<Strategy>::apply(point1, point2, strategy);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2017-2022.
|
||||
// Modifications copyright (c) 2017-2022 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_BUFFER_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_BUFFER_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/buffer/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/implementation.hpp>
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_BUFFER_HPP
|
||||
Vendored
+650
@@ -0,0 +1,650 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2014-2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2014-2023.
|
||||
// Modifications copyright (c) 2014-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CENTROID_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CENTROID_HPP
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
#include <boost/throw_exception.hpp>
|
||||
|
||||
#include <boost/geometry/core/exception.hpp>
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/interior_rings.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/point_type.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/convert.hpp>
|
||||
#include <boost/geometry/algorithms/detail/centroid/translating_transformer.hpp>
|
||||
#include <boost/geometry/algorithms/detail/point_on_border.hpp>
|
||||
#include <boost/geometry/algorithms/is_empty.hpp>
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/centroid/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/centroid/geographic.hpp>
|
||||
#include <boost/geometry/strategies/centroid/spherical.hpp>
|
||||
#include <boost/geometry/strategies/concepts/centroid_concept.hpp>
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
#include <boost/geometry/strategies/detail.hpp>
|
||||
|
||||
#include <boost/geometry/util/algorithm.hpp>
|
||||
#include <boost/geometry/util/select_coordinate_type.hpp>
|
||||
#include <boost/geometry/util/type_traits_std.hpp>
|
||||
|
||||
#include <boost/geometry/views/closeable_view.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#if ! defined(BOOST_GEOMETRY_CENTROID_NO_THROW)
|
||||
|
||||
/*!
|
||||
\brief Centroid Exception
|
||||
\ingroup centroid
|
||||
\details The centroid_exception is thrown if the free centroid function is called with
|
||||
geometries for which the centroid cannot be calculated. For example: a linestring
|
||||
without points, a polygon without points, an empty multi-geometry.
|
||||
\qbk{
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.centroid the centroid function]
|
||||
}
|
||||
|
||||
*/
|
||||
class centroid_exception : public geometry::exception
|
||||
{
|
||||
public:
|
||||
|
||||
inline centroid_exception() {}
|
||||
|
||||
char const* what() const noexcept override
|
||||
{
|
||||
return "Boost.Geometry Centroid calculation exception";
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace centroid
|
||||
{
|
||||
|
||||
struct centroid_point
|
||||
{
|
||||
template<typename Point, typename PointCentroid, typename Strategy>
|
||||
static inline void apply(Point const& point, PointCentroid& centroid,
|
||||
Strategy const&)
|
||||
{
|
||||
geometry::convert(point, centroid);
|
||||
}
|
||||
};
|
||||
|
||||
struct centroid_indexed
|
||||
{
|
||||
template<typename Indexed, typename Point, typename Strategy>
|
||||
static inline void apply(Indexed const& indexed, Point& centroid,
|
||||
Strategy const&)
|
||||
{
|
||||
typedef typename select_coordinate_type
|
||||
<
|
||||
Indexed, Point
|
||||
>::type coordinate_type;
|
||||
|
||||
detail::for_each_dimension<Indexed>([&](auto dimension)
|
||||
{
|
||||
coordinate_type const c1 = get<min_corner, dimension>(indexed);
|
||||
coordinate_type const c2 = get<max_corner, dimension>(indexed);
|
||||
coordinate_type const two = 2;
|
||||
set<dimension>(centroid, (c1 + c2) / two);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// There is one thing where centroid is different from e.g. within.
|
||||
// If the ring has only one point, it might make sense that
|
||||
// that point is the centroid.
|
||||
template<typename Point, typename Range>
|
||||
inline bool range_ok(Range const& range, Point& centroid)
|
||||
{
|
||||
std::size_t const n = boost::size(range);
|
||||
if (n > 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else if (n <= 0)
|
||||
{
|
||||
#if ! defined(BOOST_GEOMETRY_CENTROID_NO_THROW)
|
||||
BOOST_THROW_EXCEPTION(centroid_exception());
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
else // if (n == 1)
|
||||
{
|
||||
// Take over the first point in a "coordinate neutral way"
|
||||
geometry::convert(*boost::begin(range), centroid);
|
||||
return false;
|
||||
}
|
||||
//return true; // unreachable
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief Calculate the centroid of a Ring or a Linestring.
|
||||
*/
|
||||
struct centroid_range_state
|
||||
{
|
||||
template<typename Ring, typename PointTransformer, typename Strategy, typename State>
|
||||
static inline void apply(Ring const& ring,
|
||||
PointTransformer const& transformer,
|
||||
Strategy const& strategy,
|
||||
State& state)
|
||||
{
|
||||
boost::ignore_unused(strategy);
|
||||
|
||||
detail::closed_view<Ring const> const view(ring);
|
||||
auto it = boost::begin(view);
|
||||
auto const end = boost::end(view);
|
||||
|
||||
if (it != end)
|
||||
{
|
||||
typename PointTransformer::result_type
|
||||
previous_pt = transformer.apply(*it);
|
||||
|
||||
for ( ++it ; it != end ; ++it)
|
||||
{
|
||||
typename PointTransformer::result_type
|
||||
pt = transformer.apply(*it);
|
||||
|
||||
using point_type = geometry::point_type_t<Ring const>;
|
||||
strategy.apply(static_cast<point_type const&>(previous_pt),
|
||||
static_cast<point_type const&>(pt),
|
||||
state);
|
||||
|
||||
previous_pt = pt;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct centroid_range
|
||||
{
|
||||
template<typename Range, typename Point, typename Strategy>
|
||||
static inline bool apply(Range const& range, Point& centroid,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
if (range_ok(range, centroid))
|
||||
{
|
||||
// prepare translation transformer
|
||||
translating_transformer<Range> transformer(*boost::begin(range));
|
||||
|
||||
typename Strategy::template state_type
|
||||
<
|
||||
geometry::point_type_t<Range>,
|
||||
Point
|
||||
>::type state;
|
||||
|
||||
centroid_range_state::apply(range, transformer, strategy, state);
|
||||
|
||||
if ( strategy.result(state, centroid) )
|
||||
{
|
||||
// translate the result back
|
||||
transformer.apply_reverse(centroid);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*!
|
||||
\brief Centroid of a polygon.
|
||||
\note Because outer ring is clockwise, inners are counter clockwise,
|
||||
triangle approach is OK and works for polygons with rings.
|
||||
*/
|
||||
struct centroid_polygon_state
|
||||
{
|
||||
template<typename Polygon, typename PointTransformer, typename Strategy, typename State>
|
||||
static inline void apply(Polygon const& poly,
|
||||
PointTransformer const& transformer,
|
||||
Strategy const& strategy,
|
||||
State& state)
|
||||
{
|
||||
centroid_range_state::apply(exterior_ring(poly), transformer, strategy, state);
|
||||
|
||||
auto const& rings = interior_rings(poly);
|
||||
auto const end = boost::end(rings);
|
||||
for (auto it = boost::begin(rings); it != end; ++it)
|
||||
{
|
||||
centroid_range_state::apply(*it, transformer, strategy, state);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct centroid_polygon
|
||||
{
|
||||
template<typename Polygon, typename Point, typename Strategy>
|
||||
static inline bool apply(Polygon const& poly, Point& centroid,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
if (range_ok(exterior_ring(poly), centroid))
|
||||
{
|
||||
// prepare translation transformer
|
||||
translating_transformer<Polygon>
|
||||
transformer(*boost::begin(exterior_ring(poly)));
|
||||
|
||||
typename Strategy::template state_type
|
||||
<
|
||||
geometry::point_type_t<Polygon>,
|
||||
Point
|
||||
>::type state;
|
||||
|
||||
centroid_polygon_state::apply(poly, transformer, strategy, state);
|
||||
|
||||
if ( strategy.result(state, centroid) )
|
||||
{
|
||||
// translate the result back
|
||||
transformer.apply_reverse(centroid);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*!
|
||||
\brief Building block of a multi-point, to be used as Policy in the
|
||||
more generec centroid_multi
|
||||
*/
|
||||
struct centroid_multi_point_state
|
||||
{
|
||||
template <typename Point, typename PointTransformer, typename Strategy, typename State>
|
||||
static inline void apply(Point const& point,
|
||||
PointTransformer const& transformer,
|
||||
Strategy const& strategy,
|
||||
State& state)
|
||||
{
|
||||
boost::ignore_unused(strategy);
|
||||
strategy.apply(static_cast<Point const&>(transformer.apply(point)),
|
||||
state);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*!
|
||||
\brief Generic implementation which calls a policy to calculate the
|
||||
centroid of the total of its single-geometries
|
||||
\details The Policy is, in general, the single-version, with state. So
|
||||
detail::centroid::centroid_polygon_state is used as a policy for this
|
||||
detail::centroid::centroid_multi
|
||||
|
||||
*/
|
||||
template <typename Policy>
|
||||
struct centroid_multi
|
||||
{
|
||||
template <typename Multi, typename Point, typename Strategy>
|
||||
static inline bool apply(Multi const& multi,
|
||||
Point& centroid,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
#if ! defined(BOOST_GEOMETRY_CENTROID_NO_THROW)
|
||||
// If there is nothing in any of the ranges, it is not possible
|
||||
// to calculate the centroid
|
||||
if (geometry::is_empty(multi))
|
||||
{
|
||||
BOOST_THROW_EXCEPTION(centroid_exception());
|
||||
}
|
||||
#endif
|
||||
|
||||
// prepare translation transformer
|
||||
translating_transformer<Multi> transformer(multi);
|
||||
|
||||
typename Strategy::template state_type
|
||||
<
|
||||
geometry::point_type_t<Multi>,
|
||||
Point
|
||||
>::type state;
|
||||
|
||||
for (auto it = boost::begin(multi); it != boost::end(multi); ++it)
|
||||
{
|
||||
Policy::apply(*it, transformer, strategy, state);
|
||||
}
|
||||
|
||||
if (strategy.result(state, centroid))
|
||||
{
|
||||
// translate the result back
|
||||
transformer.apply_reverse(centroid);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Algorithm>
|
||||
struct centroid_linear_areal
|
||||
{
|
||||
template <typename Geometry, typename Point, typename Strategies>
|
||||
static inline void apply(Geometry const& geom,
|
||||
Point& centroid,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
if ( ! Algorithm::apply(geom, centroid, strategies.centroid(geom)) )
|
||||
{
|
||||
geometry::point_on_border(centroid, geom);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Algorithm>
|
||||
struct centroid_pointlike
|
||||
{
|
||||
template <typename Geometry, typename Point, typename Strategies>
|
||||
static inline void apply(Geometry const& geom,
|
||||
Point& centroid,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
Algorithm::apply(geom, centroid, strategies.centroid(geom));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::centroid
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename Tag = tag_t<Geometry>
|
||||
>
|
||||
struct centroid: not_implemented<Tag>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct centroid<Geometry, point_tag>
|
||||
: detail::centroid::centroid_point
|
||||
{};
|
||||
|
||||
template <typename Box>
|
||||
struct centroid<Box, box_tag>
|
||||
: detail::centroid::centroid_indexed
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct centroid<Segment, segment_tag>
|
||||
: detail::centroid::centroid_indexed
|
||||
{};
|
||||
|
||||
template <typename Ring>
|
||||
struct centroid<Ring, ring_tag>
|
||||
: detail::centroid::centroid_linear_areal
|
||||
<
|
||||
detail::centroid::centroid_range
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename Linestring>
|
||||
struct centroid<Linestring, linestring_tag>
|
||||
: detail::centroid::centroid_linear_areal
|
||||
<
|
||||
detail::centroid::centroid_range
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename Polygon>
|
||||
struct centroid<Polygon, polygon_tag>
|
||||
: detail::centroid::centroid_linear_areal
|
||||
<
|
||||
detail::centroid::centroid_polygon
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename MultiLinestring>
|
||||
struct centroid<MultiLinestring, multi_linestring_tag>
|
||||
: detail::centroid::centroid_linear_areal
|
||||
<
|
||||
detail::centroid::centroid_multi
|
||||
<
|
||||
detail::centroid::centroid_range_state
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename MultiPolygon>
|
||||
struct centroid<MultiPolygon, multi_polygon_tag>
|
||||
: detail::centroid::centroid_linear_areal
|
||||
<
|
||||
detail::centroid::centroid_multi
|
||||
<
|
||||
detail::centroid::centroid_polygon_state
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename MultiPoint>
|
||||
struct centroid<MultiPoint, multi_point_tag>
|
||||
: detail::centroid::centroid_pointlike
|
||||
<
|
||||
detail::centroid::centroid_multi
|
||||
<
|
||||
detail::centroid::centroid_multi_point_state
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy {
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategies,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategies>::value
|
||||
>
|
||||
struct centroid
|
||||
{
|
||||
template <typename Geometry, typename Point>
|
||||
static inline void apply(Geometry const& geometry, Point& out, Strategies const& strategies)
|
||||
{
|
||||
dispatch::centroid<Geometry>::apply(geometry, out, strategies);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct centroid<Strategy, false>
|
||||
{
|
||||
template <typename Geometry, typename Point>
|
||||
static inline void apply(Geometry const& geometry, Point& out, Strategy const& strategy)
|
||||
{
|
||||
using strategies::centroid::services::strategy_converter;
|
||||
dispatch::centroid
|
||||
<
|
||||
Geometry
|
||||
>::apply(geometry, out, strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct centroid<default_strategy, false>
|
||||
{
|
||||
template <typename Geometry, typename Point>
|
||||
static inline void apply(Geometry const& geometry, Point& out, default_strategy)
|
||||
{
|
||||
using strategies_type = typename strategies::centroid::services::default_strategy
|
||||
<
|
||||
Geometry
|
||||
>::type;
|
||||
|
||||
dispatch::centroid<Geometry>::apply(geometry, out, strategies_type());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_dynamic {
|
||||
|
||||
template <typename Geometry, typename Tag = tag_t<Geometry>>
|
||||
struct centroid
|
||||
{
|
||||
template <typename Point, typename Strategy>
|
||||
static inline void apply(Geometry const& geometry, Point& out, Strategy const& strategy)
|
||||
{
|
||||
concepts::check_concepts_and_equal_dimensions<Point, Geometry const>();
|
||||
resolve_strategy::centroid<Strategy>::apply(geometry, out, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct centroid<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Point, typename Strategy>
|
||||
static inline void apply(Geometry const& geometry,
|
||||
Point& out,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
traits::visit<Geometry>::apply([&](auto const& g)
|
||||
{
|
||||
centroid<util::remove_cref_t<decltype(g)>>::apply(g, out, strategy);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{centroid} \brief_strategy
|
||||
\ingroup centroid
|
||||
\details \details_calc{centroid,geometric center (or: center of mass)}. \details_strategy_reasons
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Point \tparam_point
|
||||
\tparam Strategy \tparam_strategy{Centroid}
|
||||
\param geometry \param_geometry
|
||||
\param c \param_point \param_set{centroid}
|
||||
\param strategy \param_strategy{centroid}
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
\qbk{[include reference/algorithms/centroid.qbk]}
|
||||
\qbk{[include reference/algorithms/centroid_strategies.qbk]}
|
||||
}
|
||||
|
||||
*/
|
||||
template<typename Geometry, typename Point, typename Strategy>
|
||||
inline void centroid(Geometry const& geometry, Point& c, Strategy const& strategy)
|
||||
{
|
||||
resolve_dynamic::centroid<Geometry>::apply(geometry, c, strategy);
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{centroid}
|
||||
\ingroup centroid
|
||||
\details \details_calc{centroid,geometric center (or: center of mass)}. \details_default_strategy
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Point \tparam_point
|
||||
\param geometry \param_geometry
|
||||
\param c The calculated centroid will be assigned to this point reference
|
||||
|
||||
\qbk{[include reference/algorithms/centroid.qbk]}
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[centroid]
|
||||
[centroid_output]
|
||||
}
|
||||
*/
|
||||
template<typename Geometry, typename Point>
|
||||
inline void centroid(Geometry const& geometry, Point& c)
|
||||
{
|
||||
geometry::centroid(geometry, c, default_strategy());
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{centroid}
|
||||
\ingroup centroid
|
||||
\details \details_calc{centroid,geometric center (or: center of mass)}. \details_return{centroid}.
|
||||
\tparam Point \tparam_point
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry
|
||||
\return \return_calc{centroid}
|
||||
|
||||
\qbk{[include reference/algorithms/centroid.qbk]}
|
||||
*/
|
||||
template<typename Point, typename Geometry>
|
||||
inline Point return_centroid(Geometry const& geometry)
|
||||
{
|
||||
Point c;
|
||||
geometry::centroid(geometry, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{centroid} \brief_strategy
|
||||
\ingroup centroid
|
||||
\details \details_calc{centroid,geometric center (or: center of mass)}. \details_return{centroid}. \details_strategy_reasons
|
||||
\tparam Point \tparam_point
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Strategy \tparam_strategy{centroid}
|
||||
\param geometry \param_geometry
|
||||
\param strategy \param_strategy{centroid}
|
||||
\return \return_calc{centroid}
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
\qbk{[include reference/algorithms/centroid.qbk]}
|
||||
\qbk{[include reference/algorithms/centroid_strategies.qbk]}
|
||||
*/
|
||||
template<typename Point, typename Geometry, typename Strategy>
|
||||
inline Point return_centroid(Geometry const& geometry, Strategy const& strategy)
|
||||
{
|
||||
Point c;
|
||||
geometry::centroid(geometry, c, strategy);
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CENTROID_HPP
|
||||
Vendored
+191
@@ -0,0 +1,191 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2020-2023.
|
||||
// Modifications copyright (c) 2020-2023, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CLEAR_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CLEAR_HPP
|
||||
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/interior_rings.hpp>
|
||||
#include <boost/geometry/core/mutable_range.hpp>
|
||||
#include <boost/geometry/core/tag_cast.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // for backward compatibility
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace clear
|
||||
{
|
||||
|
||||
template <typename Geometry>
|
||||
struct collection_clear
|
||||
{
|
||||
static inline void apply(Geometry& geometry)
|
||||
{
|
||||
traits::clear<Geometry>::apply(geometry);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Polygon>
|
||||
struct polygon_clear
|
||||
{
|
||||
static inline void apply(Polygon& polygon)
|
||||
{
|
||||
traits::clear
|
||||
<
|
||||
std::remove_reference_t
|
||||
<
|
||||
typename traits::interior_mutable_type<Polygon>::type
|
||||
>
|
||||
>::apply(interior_rings(polygon));
|
||||
traits::clear
|
||||
<
|
||||
std::remove_reference_t
|
||||
<
|
||||
typename traits::ring_mutable_type<Polygon>::type
|
||||
>
|
||||
>::apply(exterior_ring(polygon));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct no_action
|
||||
{
|
||||
static inline void apply(Geometry& )
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::clear
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename Tag = tag_cast_t<tag_t<Geometry>, multi_tag>
|
||||
>
|
||||
struct clear: not_implemented<Tag>
|
||||
{};
|
||||
|
||||
// Point/box/segment do not have clear. So specialize to do nothing.
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, point_tag>
|
||||
: detail::clear::no_action<Geometry>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, box_tag>
|
||||
: detail::clear::no_action<Geometry>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, segment_tag>
|
||||
: detail::clear::no_action<Geometry>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, linestring_tag>
|
||||
: detail::clear::collection_clear<Geometry>
|
||||
{};
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, ring_tag>
|
||||
: detail::clear::collection_clear<Geometry>
|
||||
{};
|
||||
|
||||
|
||||
// Polygon can (indirectly) use std for clear
|
||||
template <typename Polygon>
|
||||
struct clear<Polygon, polygon_tag>
|
||||
: detail::clear::polygon_clear<Polygon>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, multi_tag>
|
||||
: detail::clear::collection_clear<Geometry>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
static void apply(Geometry& geometry)
|
||||
{
|
||||
traits::visit<Geometry>::apply([](auto & g)
|
||||
{
|
||||
clear<std::remove_reference_t<decltype(g)>>::apply(g);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct clear<Geometry, geometry_collection_tag>
|
||||
{
|
||||
static void apply(Geometry& geometry)
|
||||
{
|
||||
traits::clear<Geometry>::apply(geometry);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
/*!
|
||||
\brief Clears a linestring, ring or polygon (exterior+interiors) or multi*
|
||||
\details Generic function to clear a geometry. All points will be removed from the collection or collections
|
||||
making up the geometry. In most cases this is equivalent to the .clear() method of a std::vector<...>. In
|
||||
the case of a polygon, this clear functionality is automatically called for the exterior ring, and for the
|
||||
interior ring collection. In the case of a point, boxes and segments, nothing will happen.
|
||||
\ingroup clear
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry which will be cleared
|
||||
\note points and boxes cannot be cleared, instead they can be set to zero by "assign_zero"
|
||||
|
||||
\qbk{[include reference/algorithms/clear.qbk]}
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline void clear(Geometry& geometry)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
dispatch::clear<Geometry>::apply(geometry);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CLEAR_HPP
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Boost.Geometry
|
||||
|
||||
// Copyright (c) 2021, Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
|
||||
// Licensed under the Boost Software License version 1.0.
|
||||
// http://www.boost.org/users/license.html
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CLOSEST_POINTS_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CLOSEST_POINTS_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/closest_points/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/closest_points/implementation.hpp>
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CLOSEST_POINTS_HPP
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2014.
|
||||
// Modifications copyright (c) 2014, Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_COMPARABLE_DISTANCE_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_COMPARABLE_DISTANCE_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/comparable_distance/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/comparable_distance/implementation.hpp>
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_COMPARABLE_DISTANCE_HPP
|
||||
Vendored
+560
@@ -0,0 +1,560 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2014-2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2017-2023.
|
||||
// Modifications copyright (c) 2017-2023, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVERT_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CONVERT_HPP
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
#include <boost/variant/static_visitor.hpp>
|
||||
#include <boost/variant/variant_fwd.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/clear.hpp>
|
||||
#include <boost/geometry/algorithms/detail/assign_box_corners.hpp>
|
||||
#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/convert_indexed_to_indexed.hpp>
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
|
||||
#include <boost/geometry/core/closure.hpp>
|
||||
#include <boost/geometry/core/point_order.hpp>
|
||||
#include <boost/geometry/core/tag_cast.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/util/numeric_cast.hpp>
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
|
||||
#include <boost/geometry/views/detail/closed_clockwise_view.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
// Silence warning C4127: conditional expression is constant
|
||||
// Silence warning C4512: assignment operator could not be generated
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127 4512)
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace conversion
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Point,
|
||||
typename Box,
|
||||
std::size_t Index,
|
||||
std::size_t Dimension,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct point_to_box
|
||||
{
|
||||
static inline void apply(Point const& point, Box& box)
|
||||
{
|
||||
set<Index, Dimension>(box,
|
||||
util::numeric_cast<coordinate_type_t<Box>>(get<Dimension>(point)));
|
||||
point_to_box
|
||||
<
|
||||
Point, Box,
|
||||
Index, Dimension + 1, DimensionCount
|
||||
>::apply(point, box);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Point,
|
||||
typename Box,
|
||||
std::size_t Index,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct point_to_box<Point, Box, Index, DimensionCount, DimensionCount>
|
||||
{
|
||||
static inline void apply(Point const& , Box& )
|
||||
{}
|
||||
};
|
||||
|
||||
template <typename Box, typename Range, bool Close, bool Reverse>
|
||||
struct box_to_range
|
||||
{
|
||||
static inline void apply(Box const& box, Range& range)
|
||||
{
|
||||
traits::resize<Range>::apply(range, Close ? 5 : 4);
|
||||
assign_box_corners_oriented<Reverse>(box, range);
|
||||
if (Close)
|
||||
{
|
||||
range::at(range, 4) = range::at(range, 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Segment, typename Range>
|
||||
struct segment_to_range
|
||||
{
|
||||
static inline void apply(Segment const& segment, Range& range)
|
||||
{
|
||||
traits::resize<Range>::apply(range, 2);
|
||||
|
||||
auto it = boost::begin(range);
|
||||
|
||||
assign_point_from_index<0>(segment, *it);
|
||||
++it;
|
||||
assign_point_from_index<1>(segment, *it);
|
||||
}
|
||||
};
|
||||
|
||||
template
|
||||
<
|
||||
typename Range1,
|
||||
typename Range2,
|
||||
bool Reverse = false
|
||||
>
|
||||
struct range_to_range
|
||||
{
|
||||
struct default_policy
|
||||
{
|
||||
template <typename Point1, typename Point2>
|
||||
static inline void apply(Point1 const& point1, Point2 & point2)
|
||||
{
|
||||
geometry::detail::conversion::convert_point_to_point(point1, point2);
|
||||
}
|
||||
};
|
||||
|
||||
static inline void apply(Range1 const& source, Range2& destination)
|
||||
{
|
||||
apply(source, destination, default_policy());
|
||||
}
|
||||
|
||||
template <typename ConvertPointPolicy>
|
||||
static inline ConvertPointPolicy apply(Range1 const& source, Range2& destination,
|
||||
ConvertPointPolicy convert_point)
|
||||
{
|
||||
geometry::clear(destination);
|
||||
|
||||
using view_type = detail::closed_clockwise_view
|
||||
<
|
||||
Range1 const,
|
||||
geometry::closure<Range1>::value,
|
||||
Reverse ? counterclockwise : clockwise
|
||||
>;
|
||||
|
||||
// We consider input always as closed, and skip last
|
||||
// point for open output.
|
||||
view_type const view(source);
|
||||
|
||||
auto n = boost::size(view);
|
||||
if (geometry::closure<Range2>::value == geometry::open)
|
||||
{
|
||||
n--;
|
||||
}
|
||||
|
||||
// If size == 0 && geometry::open <=> n = numeric_limits<size_type>::max()
|
||||
// but ok, sice below it == end()
|
||||
|
||||
decltype(n) i = 0;
|
||||
for (auto it = boost::begin(view);
|
||||
it != boost::end(view) && i < n;
|
||||
++it, ++i)
|
||||
{
|
||||
typename boost::range_value<Range2>::type point;
|
||||
convert_point.apply(*it, point);
|
||||
range::push_back(destination, point);
|
||||
}
|
||||
|
||||
return convert_point;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Polygon1, typename Polygon2>
|
||||
struct polygon_to_polygon
|
||||
{
|
||||
using per_ring = range_to_range
|
||||
<
|
||||
geometry::ring_type_t<Polygon1>,
|
||||
geometry::ring_type_t<Polygon2>,
|
||||
geometry::point_order<Polygon1>::value != geometry::point_order<Polygon2>::value
|
||||
>;
|
||||
|
||||
static inline void apply(Polygon1 const& source, Polygon2& destination)
|
||||
{
|
||||
// Clearing managed per ring, and in the resizing of interior rings
|
||||
|
||||
per_ring::apply(geometry::exterior_ring(source),
|
||||
geometry::exterior_ring(destination));
|
||||
|
||||
// Container should be resizeable
|
||||
traits::resize
|
||||
<
|
||||
std::remove_reference_t
|
||||
<
|
||||
typename traits::interior_mutable_type<Polygon2>::type
|
||||
>
|
||||
>::apply(interior_rings(destination), num_interior_rings(source));
|
||||
|
||||
auto const& rings_source = interior_rings(source);
|
||||
auto&& rings_dest = interior_rings(destination);
|
||||
|
||||
auto it_source = boost::begin(rings_source);
|
||||
auto it_dest = boost::begin(rings_dest);
|
||||
|
||||
for ( ; it_source != boost::end(rings_source); ++it_source, ++it_dest)
|
||||
{
|
||||
per_ring::apply(*it_source, *it_dest);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Single, typename Multi, typename Policy>
|
||||
struct single_to_multi: private Policy
|
||||
{
|
||||
static inline void apply(Single const& single, Multi& multi)
|
||||
{
|
||||
traits::resize<Multi>::apply(multi, 1);
|
||||
Policy::apply(single, *boost::begin(multi));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
template <typename Multi1, typename Multi2, typename Policy>
|
||||
struct multi_to_multi: private Policy
|
||||
{
|
||||
static inline void apply(Multi1 const& multi1, Multi2& multi2)
|
||||
{
|
||||
traits::resize<Multi2>::apply(multi2, boost::size(multi1));
|
||||
|
||||
auto it1 = boost::begin(multi1);
|
||||
auto it2 = boost::begin(multi2);
|
||||
|
||||
for (; it1 != boost::end(multi1); ++it1, ++it2)
|
||||
{
|
||||
Policy::apply(*it1, *it2);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::conversion
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
// TODO: We could use std::is_assignable instead of std::is_same.
|
||||
// Then we should rather check ! std::is_array<Geometry2>::value
|
||||
// which is Destination.
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1, typename Geometry2,
|
||||
typename Tag1 = tag_cast_t<tag_t<Geometry1>, multi_tag>,
|
||||
typename Tag2 = tag_cast_t<tag_t<Geometry2>, multi_tag>,
|
||||
std::size_t DimensionCount = dimension<Geometry1>::value,
|
||||
bool UseAssignment = std::is_same<Geometry1, Geometry2>::value
|
||||
&& !std::is_array<Geometry1>::value
|
||||
>
|
||||
struct convert
|
||||
: not_implemented
|
||||
<
|
||||
Tag1, Tag2,
|
||||
std::integral_constant<std::size_t, DimensionCount>
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1, typename Geometry2,
|
||||
typename Tag,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct convert<Geometry1, Geometry2, Tag, Tag, DimensionCount, true>
|
||||
{
|
||||
// Same geometry type -> copy whole geometry
|
||||
static inline void apply(Geometry1 const& source, Geometry2& destination)
|
||||
{
|
||||
destination = source;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1, typename Geometry2,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct convert<Geometry1, Geometry2, point_tag, point_tag, DimensionCount, false>
|
||||
: detail::conversion::point_to_point<Geometry1, Geometry2, 0, DimensionCount>
|
||||
{};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Box1, typename Box2,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct convert<Box1, Box2, box_tag, box_tag, DimensionCount, false>
|
||||
: detail::conversion::indexed_to_indexed<Box1, Box2, 0, DimensionCount>
|
||||
{};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Segment1, typename Segment2,
|
||||
std::size_t DimensionCount
|
||||
>
|
||||
struct convert<Segment1, Segment2, segment_tag, segment_tag, DimensionCount, false>
|
||||
: detail::conversion::indexed_to_indexed<Segment1, Segment2, 0, DimensionCount>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Segment, typename LineString, std::size_t DimensionCount>
|
||||
struct convert<Segment, LineString, segment_tag, linestring_tag, DimensionCount, false>
|
||||
: detail::conversion::segment_to_range<Segment, LineString>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Ring1, typename Ring2, std::size_t DimensionCount>
|
||||
struct convert<Ring1, Ring2, ring_tag, ring_tag, DimensionCount, false>
|
||||
: detail::conversion::range_to_range
|
||||
<
|
||||
Ring1,
|
||||
Ring2,
|
||||
geometry::point_order<Ring1>::value != geometry::point_order<Ring2>::value
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename LineString1, typename LineString2, std::size_t DimensionCount>
|
||||
struct convert<LineString1, LineString2, linestring_tag, linestring_tag, DimensionCount, false>
|
||||
: detail::conversion::range_to_range<LineString1, LineString2>
|
||||
{};
|
||||
|
||||
template <typename Polygon1, typename Polygon2, std::size_t DimensionCount>
|
||||
struct convert<Polygon1, Polygon2, polygon_tag, polygon_tag, DimensionCount, false>
|
||||
: detail::conversion::polygon_to_polygon<Polygon1, Polygon2>
|
||||
{};
|
||||
|
||||
template <typename Box, typename Ring>
|
||||
struct convert<Box, Ring, box_tag, ring_tag, 2, false>
|
||||
: detail::conversion::box_to_range
|
||||
<
|
||||
Box,
|
||||
Ring,
|
||||
geometry::closure<Ring>::value == closed,
|
||||
geometry::point_order<Ring>::value == counterclockwise
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Box, typename Polygon>
|
||||
struct convert<Box, Polygon, box_tag, polygon_tag, 2, false>
|
||||
{
|
||||
static inline void apply(Box const& box, Polygon& polygon)
|
||||
{
|
||||
typedef typename ring_type<Polygon>::type ring_type;
|
||||
|
||||
convert
|
||||
<
|
||||
Box, ring_type,
|
||||
box_tag, ring_tag,
|
||||
2, false
|
||||
>::apply(box, exterior_ring(polygon));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Point, typename Box, std::size_t DimensionCount>
|
||||
struct convert<Point, Box, point_tag, box_tag, DimensionCount, false>
|
||||
{
|
||||
static inline void apply(Point const& point, Box& box)
|
||||
{
|
||||
detail::conversion::point_to_box
|
||||
<
|
||||
Point, Box, min_corner, 0, DimensionCount
|
||||
>::apply(point, box);
|
||||
detail::conversion::point_to_box
|
||||
<
|
||||
Point, Box, max_corner, 0, DimensionCount
|
||||
>::apply(point, box);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Ring, typename Polygon, std::size_t DimensionCount>
|
||||
struct convert<Ring, Polygon, ring_tag, polygon_tag, DimensionCount, false>
|
||||
{
|
||||
static inline void apply(Ring const& ring, Polygon& polygon)
|
||||
{
|
||||
typedef typename ring_type<Polygon>::type ring_type;
|
||||
convert
|
||||
<
|
||||
Ring, ring_type,
|
||||
ring_tag, ring_tag,
|
||||
DimensionCount, false
|
||||
>::apply(ring, exterior_ring(polygon));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Polygon, typename Ring, std::size_t DimensionCount>
|
||||
struct convert<Polygon, Ring, polygon_tag, ring_tag, DimensionCount, false>
|
||||
{
|
||||
static inline void apply(Polygon const& polygon, Ring& ring)
|
||||
{
|
||||
typedef typename ring_type<Polygon>::type ring_type;
|
||||
|
||||
convert
|
||||
<
|
||||
ring_type, Ring,
|
||||
ring_tag, ring_tag,
|
||||
DimensionCount, false
|
||||
>::apply(exterior_ring(polygon), ring);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Dispatch for multi <-> multi, specifying their single-version as policy.
|
||||
// Note that, even if the multi-types are mutually different, their single
|
||||
// version types might be the same and therefore we call std::is_same again
|
||||
|
||||
template <typename Multi1, typename Multi2, std::size_t DimensionCount>
|
||||
struct convert<Multi1, Multi2, multi_tag, multi_tag, DimensionCount, false>
|
||||
: detail::conversion::multi_to_multi
|
||||
<
|
||||
Multi1,
|
||||
Multi2,
|
||||
convert
|
||||
<
|
||||
typename boost::range_value<Multi1>::type,
|
||||
typename boost::range_value<Multi2>::type,
|
||||
single_tag_of_t<tag_t<Multi1>>,
|
||||
single_tag_of_t<tag_t<Multi2>>,
|
||||
DimensionCount
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Single, typename Multi, typename SingleTag, std::size_t DimensionCount>
|
||||
struct convert<Single, Multi, SingleTag, multi_tag, DimensionCount, false>
|
||||
: detail::conversion::single_to_multi
|
||||
<
|
||||
Single,
|
||||
Multi,
|
||||
convert
|
||||
<
|
||||
Single,
|
||||
typename boost::range_value<Multi>::type,
|
||||
tag_t<Single>,
|
||||
single_tag_of_t<tag_t<Multi>>,
|
||||
DimensionCount,
|
||||
false
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_variant {
|
||||
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
struct convert
|
||||
{
|
||||
static inline void apply(Geometry1 const& geometry1, Geometry2& geometry2)
|
||||
{
|
||||
concepts::check_concepts_and_equal_dimensions<Geometry1 const, Geometry2>();
|
||||
dispatch::convert<Geometry1, Geometry2>::apply(geometry1, geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
template <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2>
|
||||
struct convert<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2>
|
||||
{
|
||||
struct visitor: static_visitor<void>
|
||||
{
|
||||
Geometry2& m_geometry2;
|
||||
|
||||
visitor(Geometry2& geometry2)
|
||||
: m_geometry2(geometry2)
|
||||
{}
|
||||
|
||||
template <typename Geometry1>
|
||||
inline void operator()(Geometry1 const& geometry1) const
|
||||
{
|
||||
convert<Geometry1, Geometry2>::apply(geometry1, m_geometry2);
|
||||
}
|
||||
};
|
||||
|
||||
static inline void apply(
|
||||
boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry1,
|
||||
Geometry2& geometry2
|
||||
)
|
||||
{
|
||||
boost::apply_visitor(visitor(geometry2), geometry1);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief Converts one geometry to another geometry
|
||||
\details The convert algorithm converts one geometry, e.g. a BOX, to another
|
||||
geometry, e.g. a RING. This only works if it is possible and applicable.
|
||||
If the point-order is different, or the closure is different between two
|
||||
geometry types, it will be converted correctly by explicitly reversing the
|
||||
points or closing or opening the polygon rings.
|
||||
\ingroup convert
|
||||
\tparam Geometry1 \tparam_geometry
|
||||
\tparam Geometry2 \tparam_geometry
|
||||
\param geometry1 \param_geometry (source)
|
||||
\param geometry2 \param_geometry (target)
|
||||
|
||||
\qbk{[include reference/algorithms/convert.qbk]}
|
||||
*/
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
inline void convert(Geometry1 const& geometry1, Geometry2& geometry2)
|
||||
{
|
||||
resolve_variant::convert<Geometry1, Geometry2>::apply(geometry1, geometry2);
|
||||
}
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CONVERT_HPP
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2014, 2015, 2020.
|
||||
// Modifications copyright (c) 2014-2020 Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/convex_hull/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/convex_hull/graham_andrew.hpp>
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP
|
||||
Vendored
+342
@@ -0,0 +1,342 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2014-2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2017-2023.
|
||||
// Modifications copyright (c) 2017-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
|
||||
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/area.hpp>
|
||||
#include <boost/geometry/algorithms/correct_closure.hpp>
|
||||
#include <boost/geometry/algorithms/detail/multi_modify.hpp>
|
||||
#include <boost/geometry/algorithms/detail/visit.hpp>
|
||||
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/interior_rings.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/area/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/area/geographic.hpp>
|
||||
#include <boost/geometry/strategies/area/spherical.hpp>
|
||||
#include <boost/geometry/strategies/detail.hpp>
|
||||
|
||||
#include <boost/geometry/util/algorithm.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
// Silence warning C4127: conditional expression is constant
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
#endif
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace correct
|
||||
{
|
||||
|
||||
struct correct_nop
|
||||
{
|
||||
template <typename Geometry, typename Strategy>
|
||||
static inline void apply(Geometry& , Strategy const& )
|
||||
{}
|
||||
};
|
||||
|
||||
|
||||
// Correct a box: make min/max correct
|
||||
struct correct_box
|
||||
{
|
||||
template <typename Box, typename Strategy>
|
||||
static inline void apply(Box& box, Strategy const& )
|
||||
{
|
||||
// Currently only for Cartesian coordinates
|
||||
// (or spherical without crossing dateline)
|
||||
// Future version: adapt using strategies
|
||||
detail::for_each_dimension<Box>([&](auto dimension)
|
||||
{
|
||||
if (get<min_corner, dimension>(box) > get<max_corner, dimension>(box))
|
||||
{
|
||||
// Swap the coordinates
|
||||
auto max_value = get<min_corner, dimension>(box);
|
||||
auto min_value = get<max_corner, dimension>(box);
|
||||
set<min_corner, dimension>(box, min_value);
|
||||
set<max_corner, dimension>(box, max_value);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Close a ring, if not closed
|
||||
template <typename Predicate = std::less<>>
|
||||
struct correct_ring
|
||||
{
|
||||
template <typename Ring, typename Strategy>
|
||||
static inline void apply(Ring& r, Strategy const& strategy)
|
||||
{
|
||||
// Correct closure if necessary
|
||||
detail::correct_closure::close_or_open_ring::apply(r);
|
||||
|
||||
// NOTE: calculate_point_order should probably be used here instead.
|
||||
|
||||
// Check area
|
||||
using area_t = typename area_result<Ring, Strategy>::type;
|
||||
area_t const zero = 0;
|
||||
if (Predicate()(detail::area::ring_area::apply(r, strategy), zero))
|
||||
{
|
||||
std::reverse(boost::begin(r), boost::end(r));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Correct a polygon: normalizes all rings, sets outer ring clockwise, sets all
|
||||
// inner rings counter clockwise (or vice versa depending on orientation)
|
||||
struct correct_polygon
|
||||
{
|
||||
template <typename Polygon, typename Strategy>
|
||||
static inline void apply(Polygon& poly, Strategy const& strategy)
|
||||
{
|
||||
correct_ring<std::less<>>::apply(exterior_ring(poly), strategy);
|
||||
|
||||
auto&& rings = interior_rings(poly);
|
||||
auto const end = boost::end(rings);
|
||||
for (auto it = boost::begin(rings); it != end; ++it)
|
||||
{
|
||||
correct_ring<std::greater<>>::apply(*it, strategy);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::correct
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template <typename Geometry, typename Tag = tag_t<Geometry>>
|
||||
struct correct: not_implemented<Tag>
|
||||
{};
|
||||
|
||||
template <typename Point>
|
||||
struct correct<Point, point_tag>
|
||||
: detail::correct::correct_nop
|
||||
{};
|
||||
|
||||
template <typename LineString>
|
||||
struct correct<LineString, linestring_tag>
|
||||
: detail::correct::correct_nop
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct correct<Segment, segment_tag>
|
||||
: detail::correct::correct_nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename Box>
|
||||
struct correct<Box, box_tag>
|
||||
: detail::correct::correct_box
|
||||
{};
|
||||
|
||||
template <typename Ring>
|
||||
struct correct<Ring, ring_tag>
|
||||
: detail::correct::correct_ring<>
|
||||
{};
|
||||
|
||||
template <typename Polygon>
|
||||
struct correct<Polygon, polygon_tag>
|
||||
: detail::correct::correct_polygon
|
||||
{};
|
||||
|
||||
|
||||
template <typename MultiPoint>
|
||||
struct correct<MultiPoint, multi_point_tag>
|
||||
: detail::correct::correct_nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename MultiLineString>
|
||||
struct correct<MultiLineString, multi_linestring_tag>
|
||||
: detail::correct::correct_nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct<Geometry, multi_polygon_tag>
|
||||
: detail::multi_modify<detail::correct::correct_polygon>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value
|
||||
>
|
||||
struct correct
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline void apply(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
dispatch::correct<Geometry>::apply(geometry, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct correct<Strategy, false>
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline void apply(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
// NOTE: calculate_point_order strategy should probably be used here instead.
|
||||
using geometry::strategies::area::services::strategy_converter;
|
||||
dispatch::correct<Geometry>::apply(geometry, strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct correct<default_strategy, false>
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline void apply(Geometry& geometry, default_strategy const& )
|
||||
{
|
||||
// NOTE: calculate_point_order strategy should probably be used here instead.
|
||||
using strategy_type = typename strategies::area::services::default_strategy
|
||||
<
|
||||
Geometry
|
||||
>::type;
|
||||
dispatch::correct<Geometry>::apply(geometry, strategy_type());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_dynamic
|
||||
{
|
||||
|
||||
template <typename Geometry, typename Tag = tag_t<Geometry>>
|
||||
struct correct
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline void apply(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
resolve_strategy::correct<Strategy>::apply(geometry, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline void apply(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
traits::visit<Geometry>::apply([&](auto & g)
|
||||
{
|
||||
correct<util::remove_cref_t<decltype(g)>>::apply(g, strategy);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct<Geometry, geometry_collection_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline void apply(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
detail::visit_breadth_first([&](auto & g)
|
||||
{
|
||||
correct<util::remove_cref_t<decltype(g)>>::apply(g, strategy);
|
||||
return true;
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief Corrects a geometry
|
||||
\details Corrects a geometry: all rings which are wrongly oriented with respect
|
||||
to their expected orientation are reversed. To all rings which do not have a
|
||||
closing point and are typed as they should have one, the first point is
|
||||
appended. Also boxes can be corrected.
|
||||
\ingroup correct
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry which will be corrected if necessary
|
||||
|
||||
\qbk{[include reference/algorithms/correct.qbk]}
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline void correct(Geometry& geometry)
|
||||
{
|
||||
resolve_dynamic::correct<Geometry>::apply(geometry, default_strategy());
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief Corrects a geometry
|
||||
\details Corrects a geometry: all rings which are wrongly oriented with respect
|
||||
to their expected orientation are reversed. To all rings which do not have a
|
||||
closing point and are typed as they should have one, the first point is
|
||||
appended. Also boxes can be corrected.
|
||||
\ingroup correct
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Strategy \tparam_strategy{Area}
|
||||
\param geometry \param_geometry which will be corrected if necessary
|
||||
\param strategy \param_strategy{area}
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
|
||||
\qbk{[include reference/algorithms/correct.qbk]}
|
||||
*/
|
||||
template <typename Geometry, typename Strategy>
|
||||
inline void correct(Geometry& geometry, Strategy const& strategy)
|
||||
{
|
||||
resolve_dynamic::correct<Geometry>::apply(geometry, strategy);
|
||||
}
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CORRECT_HPP
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
// Boost.Geometry
|
||||
|
||||
// Copyright (c) 2017 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2024 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2020-2023.
|
||||
// Modifications copyright (c) 2020-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CORRECT_CLOSURE_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CORRECT_CLOSURE_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/multi_modify.hpp>
|
||||
#include <boost/geometry/algorithms/disjoint.hpp>
|
||||
|
||||
#include <boost/geometry/core/closure.hpp>
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/interior_rings.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp>
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
// Silence warning C4127: conditional expression is constant
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
#endif
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace correct_closure
|
||||
{
|
||||
|
||||
struct nop
|
||||
{
|
||||
template <typename Geometry>
|
||||
static inline void apply(Geometry& )
|
||||
{}
|
||||
};
|
||||
|
||||
// Close a ring, if not closed, or open it
|
||||
struct close_or_open_ring
|
||||
{
|
||||
template <typename Ring>
|
||||
static inline void apply(Ring& r)
|
||||
{
|
||||
auto size = boost::size(r);
|
||||
if (size <= 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: This requires relate(pt, pt) strategy
|
||||
bool const disjoint = geometry::disjoint(*boost::begin(r), *(boost::end(r) - 1));
|
||||
closure_selector const closure = geometry::closure<Ring>::value;
|
||||
|
||||
if (disjoint && closure == closed)
|
||||
{
|
||||
// Close it by adding first point
|
||||
geometry::append(r, *boost::begin(r));
|
||||
}
|
||||
else if (! disjoint && closure == open)
|
||||
{
|
||||
// Open it by removing last point
|
||||
range::resize(r, size - 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Close/open exterior ring and all its interior rings
|
||||
struct close_or_open_polygon
|
||||
{
|
||||
template <typename Polygon>
|
||||
static inline void apply(Polygon& poly)
|
||||
{
|
||||
close_or_open_ring::apply(exterior_ring(poly));
|
||||
|
||||
auto&& rings = interior_rings(poly);
|
||||
auto const end = boost::end(rings);
|
||||
for (auto it = boost::begin(rings); it != end; ++it)
|
||||
{
|
||||
close_or_open_ring::apply(*it);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}} // namespace detail::correct_closure
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template <typename Geometry, typename Tag = tag_t<Geometry>>
|
||||
struct correct_closure: not_implemented<Tag>
|
||||
{};
|
||||
|
||||
template <typename Point>
|
||||
struct correct_closure<Point, point_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
template <typename LineString>
|
||||
struct correct_closure<LineString, linestring_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct correct_closure<Segment, segment_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename Box>
|
||||
struct correct_closure<Box, box_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
template <typename Ring>
|
||||
struct correct_closure<Ring, ring_tag>
|
||||
: detail::correct_closure::close_or_open_ring
|
||||
{};
|
||||
|
||||
template <typename Polygon>
|
||||
struct correct_closure<Polygon, polygon_tag>
|
||||
: detail::correct_closure::close_or_open_polygon
|
||||
{};
|
||||
|
||||
|
||||
template <typename MultiPoint>
|
||||
struct correct_closure<MultiPoint, multi_point_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename MultiLineString>
|
||||
struct correct_closure<MultiLineString, multi_linestring_tag>
|
||||
: detail::correct_closure::nop
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct_closure<Geometry, multi_polygon_tag>
|
||||
: detail::multi_modify
|
||||
<
|
||||
detail::correct_closure::close_or_open_polygon
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_variant
|
||||
{
|
||||
|
||||
template <typename Geometry, typename Tag = tag_t<Geometry>>
|
||||
struct correct_closure
|
||||
{
|
||||
static inline void apply(Geometry& geometry)
|
||||
{
|
||||
concepts::check<Geometry const>();
|
||||
dispatch::correct_closure<Geometry>::apply(geometry);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct_closure<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
static void apply(Geometry& geometry)
|
||||
{
|
||||
traits::visit<Geometry>::apply([](auto & g)
|
||||
{
|
||||
correct_closure<util::remove_cref_t<decltype(g)>>::apply(g);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct correct_closure<Geometry, geometry_collection_tag>
|
||||
{
|
||||
static void apply(Geometry& geometry)
|
||||
{
|
||||
detail::visit_breadth_first([](auto & g)
|
||||
{
|
||||
correct_closure<util::remove_cref_t<decltype(g)>>::apply(g);
|
||||
return true;
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_variant
|
||||
|
||||
|
||||
// TODO: This algorithm should use relate(pt, pt) strategy
|
||||
|
||||
|
||||
/*!
|
||||
\brief Closes or opens a geometry, according to its type
|
||||
\details Corrects a geometry w.r.t. closure points to all rings which do not
|
||||
have a closing point and are typed as they should have one, the first point
|
||||
is appended.
|
||||
\ingroup correct_closure
|
||||
\tparam Geometry \tparam_geometry
|
||||
\param geometry \param_geometry which will be corrected if necessary
|
||||
*/
|
||||
template <typename Geometry>
|
||||
inline void correct_closure(Geometry& geometry)
|
||||
{
|
||||
resolve_variant::correct_closure<Geometry>::apply(geometry);
|
||||
}
|
||||
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CORRECT_CLOSURE_HPP
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2013-2022.
|
||||
// Modifications copyright (c) 2013-2022 Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP
|
||||
|
||||
|
||||
#include <boost/geometry/algorithms/detail/covered_by/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/covered_by/implementation.hpp>
|
||||
#include <boost/geometry/algorithms/detail/covered_by/implementation_gc.hpp>
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP
|
||||
Vendored
+354
@@ -0,0 +1,354 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2014 Samuel Debionne, Grenoble, France.
|
||||
|
||||
// This file was modified by Oracle on 2014-2022.
|
||||
// Modifications copyright (c) 2014-2022 Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_CROSSES_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_CROSSES_HPP
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/gc_topological_dimension.hpp>
|
||||
#include <boost/geometry/algorithms/detail/relate/relate_impl.hpp>
|
||||
#include <boost/geometry/algorithms/relate.hpp>
|
||||
#include <boost/geometry/core/access.hpp>
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp>
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
#include <boost/geometry/strategies/detail.hpp>
|
||||
#include <boost/geometry/strategies/relate/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/relate/geographic.hpp>
|
||||
#include <boost/geometry/strategies/relate/spherical.hpp>
|
||||
#include <boost/geometry/views/detail/geometry_collection_view.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1,
|
||||
typename Geometry2,
|
||||
typename Tag1 = typename tag<Geometry1>::type,
|
||||
typename Tag2 = typename tag<Geometry2>::type
|
||||
>
|
||||
struct crosses
|
||||
: detail::relate::relate_impl
|
||||
<
|
||||
detail::de9im::static_mask_crosses_type,
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
struct crosses<Geometry1, Geometry2, geometry_collection_tag, geometry_collection_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
int const dimension1 = detail::gc_topological_dimension(geometry1);
|
||||
int const dimension2 = detail::gc_topological_dimension(geometry2);
|
||||
|
||||
if (dimension1 >= 0 && dimension2 >= 0)
|
||||
{
|
||||
if (dimension1 < dimension2)
|
||||
{
|
||||
return detail::relate::relate_impl
|
||||
<
|
||||
detail::de9im::static_mask_crosses_d1_le_d2_type,
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
else if (dimension1 > dimension2)
|
||||
{
|
||||
return detail::relate::relate_impl
|
||||
<
|
||||
detail::de9im::static_mask_crosses_d2_le_d1_type,
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
else if (dimension1 == 1 && dimension2 == 1)
|
||||
{
|
||||
return detail::relate::relate_impl
|
||||
<
|
||||
detail::de9im::static_mask_crosses_d1_1_d2_1_type,
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry1, typename Geometry2, typename Tag1>
|
||||
struct crosses<Geometry1, Geometry2, Tag1, geometry_collection_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
using gc1_view_t = detail::geometry_collection_view<Geometry1>;
|
||||
return crosses
|
||||
<
|
||||
gc1_view_t, Geometry2
|
||||
>::apply(gc1_view_t(geometry1), geometry2, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry1, typename Geometry2, typename Tag2>
|
||||
struct crosses<Geometry1, Geometry2, geometry_collection_tag, Tag2>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
using gc2_view_t = detail::geometry_collection_view<Geometry2>;
|
||||
return crosses
|
||||
<
|
||||
Geometry1, gc2_view_t
|
||||
>::apply(geometry1, gc2_view_t(geometry2), strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value
|
||||
>
|
||||
struct crosses
|
||||
{
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
static inline bool apply(Geometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
concepts::check<Geometry1 const>();
|
||||
concepts::check<Geometry2 const>();
|
||||
|
||||
return dispatch::crosses
|
||||
<
|
||||
Geometry1, Geometry2
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct crosses<Strategy, false>
|
||||
{
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
static inline bool apply(Geometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
//using strategies::crosses::services::strategy_converter;
|
||||
using strategies::relate::services::strategy_converter;
|
||||
return crosses
|
||||
<
|
||||
decltype(strategy_converter<Strategy>::get(strategy))
|
||||
>::apply(geometry1, geometry2,
|
||||
strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct crosses<default_strategy, false>
|
||||
{
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
static inline bool apply(Geometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
default_strategy)
|
||||
{
|
||||
//typedef typename strategies::crosses::services::default_strategy
|
||||
typedef typename strategies::relate::services::default_strategy
|
||||
<
|
||||
Geometry1,
|
||||
Geometry2
|
||||
>::type strategy_type;
|
||||
|
||||
return crosses
|
||||
<
|
||||
strategy_type
|
||||
>::apply(geometry1, geometry2, strategy_type());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_dynamic
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry1, typename Geometry2,
|
||||
typename Tag1 = typename geometry::tag<Geometry1>::type,
|
||||
typename Tag2 = typename geometry::tag<Geometry2>::type
|
||||
>
|
||||
struct crosses
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Geometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
return resolve_strategy::crosses
|
||||
<
|
||||
Strategy
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename DynamicGeometry1, typename Geometry2, typename Tag2>
|
||||
struct crosses<DynamicGeometry1, Geometry2, dynamic_geometry_tag, Tag2>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(DynamicGeometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
bool result = false;
|
||||
traits::visit<DynamicGeometry1>::apply([&](auto const& g1)
|
||||
{
|
||||
result = resolve_strategy::crosses
|
||||
<
|
||||
Strategy
|
||||
>::apply(g1, geometry2, strategy);
|
||||
}, geometry1);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry1, typename DynamicGeometry2, typename Tag1>
|
||||
struct crosses<Geometry1, DynamicGeometry2, Tag1, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Geometry1 const& geometry1,
|
||||
DynamicGeometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
bool result = false;
|
||||
traits::visit<DynamicGeometry2>::apply([&](auto const& g2)
|
||||
{
|
||||
result = resolve_strategy::crosses
|
||||
<
|
||||
Strategy
|
||||
>::apply(geometry1, g2, strategy);
|
||||
}, geometry2);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename DynamicGeometry1, typename DynamicGeometry2>
|
||||
struct crosses<DynamicGeometry1, DynamicGeometry2, dynamic_geometry_tag, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(DynamicGeometry1 const& geometry1,
|
||||
DynamicGeometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
bool result = false;
|
||||
traits::visit<DynamicGeometry1, DynamicGeometry2>::apply([&](auto const& g1, auto const& g2)
|
||||
{
|
||||
result = resolve_strategy::crosses
|
||||
<
|
||||
Strategy
|
||||
>::apply(g1, g2, strategy);
|
||||
}, geometry1, geometry2);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_check2{crosses}
|
||||
\ingroup crosses
|
||||
\tparam Geometry1 \tparam_geometry
|
||||
\tparam Geometry2 \tparam_geometry
|
||||
\tparam Strategy \tparam_strategy{Crosses}
|
||||
\param geometry1 \param_geometry
|
||||
\param geometry2 \param_geometry
|
||||
\param strategy \param_strategy{crosses}
|
||||
\return \return_check2{crosses}
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
\qbk{[include reference/algorithms/crosses.qbk]}
|
||||
*/
|
||||
template <typename Geometry1, typename Geometry2, typename Strategy>
|
||||
inline bool crosses(Geometry1 const& geometry1,
|
||||
Geometry2 const& geometry2,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
return resolve_dynamic::crosses
|
||||
<
|
||||
Geometry1, Geometry2
|
||||
>::apply(geometry1, geometry2, strategy);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief \brief_check2{crosses}
|
||||
\ingroup crosses
|
||||
\tparam Geometry1 \tparam_geometry
|
||||
\tparam Geometry2 \tparam_geometry
|
||||
\param geometry1 \param_geometry
|
||||
\param geometry2 \param_geometry
|
||||
\return \return_check2{crosses}
|
||||
|
||||
\qbk{[include reference/algorithms/crosses.qbk]}
|
||||
\qbk{
|
||||
[heading Examples]
|
||||
[crosses]
|
||||
[crosses_output]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry1, typename Geometry2>
|
||||
inline bool crosses(Geometry1 const& geometry1, Geometry2 const& geometry2)
|
||||
{
|
||||
return resolve_dynamic::crosses
|
||||
<
|
||||
Geometry1, Geometry2
|
||||
>::apply(geometry1, geometry2, default_strategy());
|
||||
}
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_CROSSES_HPP
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DEFAULT_AREA_RESULT_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DEFAULT_AREA_RESULT_HPP
|
||||
|
||||
|
||||
#include <boost/geometry/algorithms/area_result.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
/*!
|
||||
\brief Meta-function defining return type of area function, using the default strategy
|
||||
\ingroup area
|
||||
\note The strategy defines the return-type (so this situation is different
|
||||
from length, where distance is sqr/sqrt, but length always squared)
|
||||
*/
|
||||
|
||||
template <typename Geometry>
|
||||
struct default_area_result
|
||||
: area_result<Geometry>
|
||||
{};
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DEFAULT_AREA_RESULT_HPP
|
||||
Vendored
+504
@@ -0,0 +1,504 @@
|
||||
// Boost.Geometry
|
||||
|
||||
// Copyright (c) 2023 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// Copyright (c) 2017-2023, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Licensed under the Boost Software License version 1.0.
|
||||
// http://www.boost.org/users/license.html
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP
|
||||
|
||||
|
||||
#include <boost/range/size.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
#include <boost/throw_exception.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/clear.hpp>
|
||||
#include <boost/geometry/algorithms/convert.hpp>
|
||||
#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/visit.hpp>
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
#include <boost/geometry/core/closure.hpp>
|
||||
#include <boost/geometry/core/exception.hpp>
|
||||
#include <boost/geometry/core/tag.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility
|
||||
#include <boost/geometry/strategies/default_strategy.hpp>
|
||||
#include <boost/geometry/strategies/densify/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/densify/geographic.hpp>
|
||||
#include <boost/geometry/strategies/densify/spherical.hpp>
|
||||
#include <boost/geometry/strategies/detail.hpp>
|
||||
#include <boost/geometry/util/constexpr.hpp>
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace densify
|
||||
{
|
||||
|
||||
template <typename Range>
|
||||
struct push_back_policy
|
||||
{
|
||||
typedef typename boost::range_value<Range>::type point_type;
|
||||
|
||||
inline explicit push_back_policy(Range & rng)
|
||||
: m_rng(rng)
|
||||
{}
|
||||
|
||||
inline void apply(point_type const& p)
|
||||
{
|
||||
range::push_back(m_rng, p);
|
||||
}
|
||||
|
||||
private:
|
||||
Range & m_rng;
|
||||
};
|
||||
|
||||
template <typename Range, typename Point>
|
||||
inline void convert_and_push_back(Range & range, Point const& p)
|
||||
{
|
||||
typename boost::range_value<Range>::type p2;
|
||||
geometry::detail::conversion::convert_point_to_point(p, p2);
|
||||
range::push_back(range, p2);
|
||||
}
|
||||
|
||||
template <bool AppendLastPoint = true>
|
||||
struct densify_range
|
||||
{
|
||||
template <typename FwdRng, typename MutRng, typename T, typename Strategies>
|
||||
static inline void apply(FwdRng const& rng, MutRng & rng_out,
|
||||
T const& len, Strategies const& strategies)
|
||||
{
|
||||
typedef typename boost::range_value<FwdRng>::type point_t;
|
||||
|
||||
auto it = boost::begin(rng);
|
||||
auto const end = boost::end(rng);
|
||||
|
||||
if (it == end) // empty(rng)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto strategy = strategies.densify(rng);
|
||||
push_back_policy<MutRng> policy(rng_out);
|
||||
|
||||
auto prev = it;
|
||||
for ( ++it ; it != end ; prev = it++)
|
||||
{
|
||||
point_t const& p0 = *prev;
|
||||
point_t const& p1 = *it;
|
||||
|
||||
convert_and_push_back(rng_out, p0);
|
||||
|
||||
strategy.apply(p0, p1, policy, len);
|
||||
}
|
||||
|
||||
if BOOST_GEOMETRY_CONSTEXPR (AppendLastPoint)
|
||||
{
|
||||
convert_and_push_back(rng_out, *prev); // back(rng)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <bool IsClosed1, bool IsClosed2> // false, X
|
||||
struct densify_ring
|
||||
{
|
||||
template <typename Geometry, typename GeometryOut, typename T, typename Strategies>
|
||||
static inline void apply(Geometry const& ring, GeometryOut & ring_out,
|
||||
T const& len, Strategies const& strategies)
|
||||
{
|
||||
geometry::detail::densify::densify_range<true>
|
||||
::apply(ring, ring_out, len, strategies);
|
||||
|
||||
if (boost::size(ring) <= 1)
|
||||
return;
|
||||
|
||||
auto const& p0 = range::back(ring);
|
||||
auto const& p1 = range::front(ring);
|
||||
|
||||
auto strategy = strategies.densify(ring);
|
||||
push_back_policy<GeometryOut> policy(ring_out);
|
||||
|
||||
strategy.apply(p0, p1, policy, len);
|
||||
|
||||
if BOOST_GEOMETRY_CONSTEXPR (IsClosed2)
|
||||
{
|
||||
convert_and_push_back(ring_out, p1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct densify_ring<true, true>
|
||||
: densify_range<true>
|
||||
{};
|
||||
|
||||
template <>
|
||||
struct densify_ring<true, false>
|
||||
: densify_range<false>
|
||||
{};
|
||||
|
||||
struct densify_convert
|
||||
{
|
||||
template <typename GeometryIn, typename GeometryOut, typename T, typename Strategy>
|
||||
static void apply(GeometryIn const& in, GeometryOut &out,
|
||||
T const& , Strategy const& )
|
||||
{
|
||||
geometry::convert(in, out);
|
||||
}
|
||||
};
|
||||
|
||||
}} // namespace detail::densify
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Geometry,
|
||||
typename GeometryOut,
|
||||
typename Tag1 = typename tag<Geometry>::type,
|
||||
typename Tag2 = typename tag<GeometryOut>::type
|
||||
>
|
||||
struct densify
|
||||
: not_implemented<Tag1, Tag2>
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, point_tag, point_tag>
|
||||
: geometry::detail::densify::densify_convert
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, segment_tag, segment_tag>
|
||||
: geometry::detail::densify::densify_convert
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, box_tag, box_tag>
|
||||
: geometry::detail::densify::densify_convert
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, multi_point_tag, multi_point_tag>
|
||||
: geometry::detail::densify::densify_convert
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, linestring_tag, linestring_tag>
|
||||
: geometry::detail::densify::densify_range<>
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, multi_linestring_tag, multi_linestring_tag>
|
||||
{
|
||||
template <typename T, typename Strategy>
|
||||
static void apply(Geometry const& mls, GeometryOut & mls_out,
|
||||
T const& len, Strategy const& strategy)
|
||||
{
|
||||
std::size_t count = boost::size(mls);
|
||||
range::resize(mls_out, count);
|
||||
|
||||
for (std::size_t i = 0 ; i < count ; ++i)
|
||||
{
|
||||
geometry::detail::densify::densify_range<>
|
||||
::apply(range::at(mls, i), range::at(mls_out, i),
|
||||
len, strategy);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, ring_tag, ring_tag>
|
||||
: geometry::detail::densify::densify_ring
|
||||
<
|
||||
geometry::closure<Geometry>::value != geometry::open,
|
||||
geometry::closure<GeometryOut>::value != geometry::open
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, polygon_tag, polygon_tag>
|
||||
{
|
||||
template <typename T, typename Strategy>
|
||||
static void apply(Geometry const& poly, GeometryOut & poly_out,
|
||||
T const& len, Strategy const& strategy)
|
||||
{
|
||||
apply_ring(exterior_ring(poly), exterior_ring(poly_out),
|
||||
len, strategy);
|
||||
|
||||
std::size_t count = boost::size(interior_rings(poly));
|
||||
range::resize(interior_rings(poly_out), count);
|
||||
|
||||
for (std::size_t i = 0 ; i < count ; ++i)
|
||||
{
|
||||
apply_ring(range::at(interior_rings(poly), i),
|
||||
range::at(interior_rings(poly_out), i),
|
||||
len, strategy);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Ring, typename RingOut, typename T, typename Strategy>
|
||||
static void apply_ring(Ring const& ring, RingOut & ring_out,
|
||||
T const& len, Strategy const& strategy)
|
||||
{
|
||||
densify<Ring, RingOut, ring_tag, ring_tag>
|
||||
::apply(ring, ring_out, len, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry, typename GeometryOut>
|
||||
struct densify<Geometry, GeometryOut, multi_polygon_tag, multi_polygon_tag>
|
||||
{
|
||||
template <typename T, typename Strategy>
|
||||
static void apply(Geometry const& mpoly, GeometryOut & mpoly_out,
|
||||
T const& len, Strategy const& strategy)
|
||||
{
|
||||
std::size_t count = boost::size(mpoly);
|
||||
range::resize(mpoly_out, count);
|
||||
|
||||
for (std::size_t i = 0 ; i < count ; ++i)
|
||||
{
|
||||
apply_poly(range::at(mpoly, i),
|
||||
range::at(mpoly_out, i),
|
||||
len, strategy);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Poly, typename PolyOut, typename T, typename Strategy>
|
||||
static void apply_poly(Poly const& poly, PolyOut & poly_out,
|
||||
T const& len, Strategy const& strategy)
|
||||
{
|
||||
densify<Poly, PolyOut, polygon_tag, polygon_tag>::
|
||||
apply(poly, poly_out, len, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_strategy
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategies,
|
||||
bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategies>::value
|
||||
>
|
||||
struct densify
|
||||
{
|
||||
template <typename Geometry, typename Distance>
|
||||
static inline void apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
dispatch::densify
|
||||
<
|
||||
Geometry, Geometry
|
||||
>::apply(geometry, out, max_distance, strategies);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct densify<Strategy, false>
|
||||
{
|
||||
template <typename Geometry, typename Distance>
|
||||
static inline void apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
using strategies::densify::services::strategy_converter;
|
||||
|
||||
dispatch::densify
|
||||
<
|
||||
Geometry, Geometry
|
||||
>::apply(geometry, out, max_distance,
|
||||
strategy_converter<Strategy>::get(strategy));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct densify<default_strategy, false>
|
||||
{
|
||||
template <typename Geometry, typename Distance>
|
||||
static inline void apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
default_strategy const&)
|
||||
{
|
||||
typedef typename strategies::densify::services::default_strategy
|
||||
<
|
||||
Geometry
|
||||
>::type strategies_type;
|
||||
|
||||
dispatch::densify
|
||||
<
|
||||
Geometry, Geometry
|
||||
>::apply(geometry, out, max_distance, strategies_type());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_strategy
|
||||
|
||||
|
||||
namespace resolve_dynamic {
|
||||
|
||||
template <typename Geometry, typename Tag = typename tag<Geometry>::type>
|
||||
struct densify
|
||||
{
|
||||
template <typename Distance, typename Strategy>
|
||||
static inline void apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
resolve_strategy::densify
|
||||
<
|
||||
Strategy
|
||||
>::apply(geometry, out, max_distance, strategy);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct densify<Geometry, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Distance, typename Strategy>
|
||||
static inline void
|
||||
apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
traits::visit<Geometry>::apply([&](auto const& g)
|
||||
{
|
||||
using geom_t = util::remove_cref_t<decltype(g)>;
|
||||
geom_t o;
|
||||
densify<geom_t>::apply(g, o, max_distance, strategy);
|
||||
out = std::move(o);
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Geometry>
|
||||
struct densify<Geometry, geometry_collection_tag>
|
||||
{
|
||||
template <typename Distance, typename Strategy>
|
||||
static inline void
|
||||
apply(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
detail::visit_breadth_first([&](auto const& g)
|
||||
{
|
||||
using geom_t = util::remove_cref_t<decltype(g)>;
|
||||
geom_t o;
|
||||
densify<geom_t>::apply(g, o, max_distance, strategy);
|
||||
traits::emplace_back<Geometry>::apply(out, std::move(o));
|
||||
return true;
|
||||
}, geometry);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief Densify a geometry using a specified strategy
|
||||
\ingroup densify
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Distance A numerical distance measure
|
||||
\tparam Strategy A type fulfilling a DensifyStrategy concept
|
||||
\param geometry Input geometry, to be densified
|
||||
\param out Output geometry, densified version of the input geometry
|
||||
\param max_distance Distance threshold (in units depending on strategy)
|
||||
\param strategy Densify strategy to be used for densification
|
||||
|
||||
\qbk{distinguish,with strategy}
|
||||
\qbk{[include reference/algorithms/densify.qbk]}
|
||||
|
||||
\qbk{
|
||||
[heading Available Strategies]
|
||||
\* [link geometry.reference.strategies.strategy_densify_cartesian Cartesian]
|
||||
\* [link geometry.reference.strategies.strategy_densify_spherical Spherical]
|
||||
\* [link geometry.reference.strategies.strategy_densify_geographic Geographic]
|
||||
|
||||
[heading Example]
|
||||
[densify_strategy]
|
||||
[densify_strategy_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.line_interpolate line_interpolate]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Distance, typename Strategy>
|
||||
inline void densify(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
concepts::check<Geometry>();
|
||||
|
||||
if (max_distance <= Distance(0))
|
||||
{
|
||||
BOOST_THROW_EXCEPTION(geometry::invalid_input_exception());
|
||||
}
|
||||
|
||||
geometry::clear(out);
|
||||
|
||||
resolve_dynamic::densify
|
||||
<
|
||||
Geometry
|
||||
>::apply(geometry, out, max_distance, strategy);
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief Densify a geometry
|
||||
\ingroup densify
|
||||
\tparam Geometry \tparam_geometry
|
||||
\tparam Distance A numerical distance measure
|
||||
\param geometry Input geometry, to be densified
|
||||
\param out Output geometry, densified version of the input geometry
|
||||
\param max_distance Distance threshold (in units depending on coordinate system)
|
||||
|
||||
\qbk{[include reference/algorithms/densify.qbk]}
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[densify]
|
||||
[densify_output]
|
||||
|
||||
[heading See also]
|
||||
\* [link geometry.reference.algorithms.line_interpolate line_interpolate]
|
||||
}
|
||||
*/
|
||||
template <typename Geometry, typename Distance>
|
||||
inline void densify(Geometry const& geometry,
|
||||
Geometry& out,
|
||||
Distance const& max_distance)
|
||||
{
|
||||
densify(geometry, out, max_distance, default_strategy());
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_BOX_CORNERS_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_BOX_CORNERS_HPP
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
#include <boost/geometry/algorithms/detail/assign_values.hpp>
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail
|
||||
{
|
||||
// Note: this is moved to namespace detail because the names and parameter orders
|
||||
// are not yet 100% clear.
|
||||
|
||||
/*!
|
||||
\brief Assign the four points of a 2D box
|
||||
\ingroup assign
|
||||
\note The order is crucial. Most logical is LOWER, UPPER and sub-order LEFT, RIGHT
|
||||
so this is how it is implemented.
|
||||
\tparam Box \tparam_box
|
||||
\tparam Point \tparam_point
|
||||
\param box \param_box
|
||||
\param lower_left point being assigned to lower left coordinates of the box
|
||||
\param lower_right point being assigned to lower right coordinates of the box
|
||||
\param upper_left point being assigned to upper left coordinates of the box
|
||||
\param upper_right point being assigned to upper right coordinates of the box
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_box_corners] [assign_box_corners_output]
|
||||
}
|
||||
*/
|
||||
template <typename Box, typename Point>
|
||||
inline void assign_box_corners(Box const& box,
|
||||
Point& lower_left, Point& lower_right,
|
||||
Point& upper_left, Point& upper_right)
|
||||
{
|
||||
concepts::check<Box const>();
|
||||
concepts::check<Point>();
|
||||
|
||||
detail::assign::assign_box_2d_corner
|
||||
<min_corner, min_corner>(box, lower_left);
|
||||
detail::assign::assign_box_2d_corner
|
||||
<max_corner, min_corner>(box, lower_right);
|
||||
detail::assign::assign_box_2d_corner
|
||||
<min_corner, max_corner>(box, upper_left);
|
||||
detail::assign::assign_box_2d_corner
|
||||
<max_corner, max_corner>(box, upper_right);
|
||||
}
|
||||
|
||||
// Silence warning C4127: conditional expression is constant
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
#endif
|
||||
|
||||
|
||||
template <bool Reverse, typename Box, typename Range>
|
||||
inline void assign_box_corners_oriented(Box const& box, Range& corners)
|
||||
{
|
||||
if (Reverse)
|
||||
{
|
||||
// make counterclockwise ll,lr,ur,ul
|
||||
assign_box_corners(box,
|
||||
range::at(corners, 0), range::at(corners, 1),
|
||||
range::at(corners, 3), range::at(corners, 2));
|
||||
}
|
||||
else
|
||||
{
|
||||
// make clockwise ll,ul,ur,lr
|
||||
assign_box_corners(box,
|
||||
range::at(corners, 0), range::at(corners, 3),
|
||||
range::at(corners, 1), range::at(corners, 2));
|
||||
}
|
||||
}
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
|
||||
} // namespace detail
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_BOX_CORNERS_HPP
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2021.
|
||||
// Modifications copyright (c) 2021, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_INDEXED_POINT_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_INDEXED_POINT_HPP
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/geometry/core/access.hpp>
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
#include <boost/geometry/util/algorithm.hpp>
|
||||
#include <boost/geometry/util/numeric_cast.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail
|
||||
{
|
||||
|
||||
/*!
|
||||
\brief Assign a box or segment with the value of a point
|
||||
\ingroup assign
|
||||
\tparam Index indicates which box-corner, min_corner (0) or max_corner (1)
|
||||
or which point of segment (0/1)
|
||||
\tparam Point \tparam_point
|
||||
\tparam Geometry \tparam_box_or_segment
|
||||
\param point \param_point
|
||||
\param geometry \param_box_or_segment
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_point_to_index] [assign_point_to_index_output]
|
||||
}
|
||||
*/
|
||||
template <std::size_t Index, typename Geometry, typename Point>
|
||||
inline void assign_point_to_index(Point const& point, Geometry& geometry)
|
||||
{
|
||||
concepts::check<Point const>();
|
||||
concepts::check<Geometry>();
|
||||
|
||||
detail::for_each_dimension<Geometry>([&](auto dimension)
|
||||
{
|
||||
geometry::set<Index, dimension>(geometry,
|
||||
util::numeric_cast
|
||||
<
|
||||
typename coordinate_type<Geometry>::type
|
||||
>(geometry::get<dimension>(point)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\brief Assign a point with a point of a box or segment
|
||||
\ingroup assign
|
||||
\tparam Index indicates which box-corner, min_corner (0) or max_corner (1)
|
||||
or which point of segment (0/1)
|
||||
\tparam Geometry \tparam_box_or_segment
|
||||
\tparam Point \tparam_point
|
||||
\param geometry \param_box_or_segment
|
||||
\param point \param_point
|
||||
|
||||
\qbk{
|
||||
[heading Example]
|
||||
[assign_point_from_index] [assign_point_from_index_output]
|
||||
}
|
||||
*/
|
||||
template <std::size_t Index, typename Point, typename Geometry>
|
||||
inline void assign_point_from_index(Geometry const& geometry, Point& point)
|
||||
{
|
||||
concepts::check<Geometry const>();
|
||||
concepts::check<Point>();
|
||||
|
||||
detail::for_each_dimension<Geometry>([&](auto dimension)
|
||||
{
|
||||
geometry::set<dimension>(point,
|
||||
util::numeric_cast
|
||||
<
|
||||
typename coordinate_type<Point>::type
|
||||
>(geometry::get<Index, dimension>(geometry)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
} // namespace detail
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ASSIGN_INDEXED_POINT_HPP
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// This file was modified by Oracle on 2018-2021.
|
||||
// Modifications copyright (c) 2018-2021, Oracle and/or its affiliates.
|
||||
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
|
||||
#include <boost/concept/requires.hpp>
|
||||
#include <boost/concept_check.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/append.hpp>
|
||||
#include <boost/geometry/algorithms/clear.hpp>
|
||||
#include <boost/geometry/core/access.hpp>
|
||||
#include <boost/geometry/core/exterior_ring.hpp>
|
||||
#include <boost/geometry/core/static_assert.hpp>
|
||||
#include <boost/geometry/core/tags.hpp>
|
||||
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
|
||||
#include <boost/geometry/util/algorithm.hpp>
|
||||
#include <boost/geometry/util/bounds.hpp>
|
||||
#include <boost/geometry/util/numeric_cast.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace assign
|
||||
{
|
||||
|
||||
|
||||
struct assign_zero_point
|
||||
{
|
||||
template <typename Point>
|
||||
static inline void apply(Point& point)
|
||||
{
|
||||
typedef typename coordinate_type<Point>::type coordinate_type;
|
||||
|
||||
coordinate_type const zero = 0;
|
||||
detail::for_each_dimension<Point>([&](auto dimension)
|
||||
{
|
||||
set<dimension>(point, zero);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct assign_inverse_box_or_segment
|
||||
{
|
||||
|
||||
template <typename BoxOrSegment>
|
||||
static inline void apply(BoxOrSegment& geometry)
|
||||
{
|
||||
typedef typename coordinate_type<BoxOrSegment>::type coordinate_type;
|
||||
|
||||
coordinate_type const highest = util::bounds<coordinate_type>::highest();
|
||||
coordinate_type const lowest = util::bounds<coordinate_type>::lowest();
|
||||
detail::for_each_dimension<BoxOrSegment>([&](auto dimension)
|
||||
{
|
||||
set<0, dimension>(geometry, highest);
|
||||
set<1, dimension>(geometry, lowest);
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
struct assign_zero_box_or_segment
|
||||
{
|
||||
template <typename BoxOrSegment>
|
||||
static inline void apply(BoxOrSegment& geometry)
|
||||
{
|
||||
typedef typename coordinate_type<BoxOrSegment>::type coordinate_type;
|
||||
|
||||
coordinate_type const zero = 0;
|
||||
detail::for_each_dimension<BoxOrSegment>([&](auto dimension)
|
||||
{
|
||||
set<0, dimension>(geometry, zero);
|
||||
set<1, dimension>(geometry, zero);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
std::size_t Corner1, std::size_t Corner2,
|
||||
typename Box, typename Point
|
||||
>
|
||||
inline void assign_box_2d_corner(Box const& box, Point& point)
|
||||
{
|
||||
// Be sure both are 2-Dimensional
|
||||
assert_dimension<Box, 2>();
|
||||
assert_dimension<Point, 2>();
|
||||
|
||||
// Copy coordinates
|
||||
typedef typename coordinate_type<Point>::type coordinate_type;
|
||||
|
||||
geometry::set<0>(point, util::numeric_cast<coordinate_type>(get<Corner1, 0>(box)));
|
||||
geometry::set<1>(point, util::numeric_cast<coordinate_type>(get<Corner2, 1>(box)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct assign_2d_box_or_segment
|
||||
{
|
||||
typedef typename coordinate_type<Geometry>::type coordinate_type;
|
||||
|
||||
// Here we assign 4 coordinates to a box of segment
|
||||
// -> Most logical is: x1,y1,x2,y2
|
||||
// In case the user reverses x1/x2 or y1/y2, for a box, we could reverse them (THAT IS NOT IMPLEMENTED)
|
||||
|
||||
template <typename Type>
|
||||
static inline void apply(Geometry& geometry,
|
||||
Type const& x1, Type const& y1, Type const& x2, Type const& y2)
|
||||
{
|
||||
geometry::set<0, 0>(geometry, util::numeric_cast<coordinate_type>(x1));
|
||||
geometry::set<0, 1>(geometry, util::numeric_cast<coordinate_type>(y1));
|
||||
geometry::set<1, 0>(geometry, util::numeric_cast<coordinate_type>(x2));
|
||||
geometry::set<1, 1>(geometry, util::numeric_cast<coordinate_type>(y2));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::assign
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template <typename GeometryTag, typename Geometry, std::size_t DimensionCount>
|
||||
struct assign
|
||||
{
|
||||
BOOST_GEOMETRY_STATIC_ASSERT_FALSE(
|
||||
"Not or not yet implemented for this Geometry type.",
|
||||
GeometryTag, Geometry, std::integral_constant<std::size_t, DimensionCount>);
|
||||
};
|
||||
|
||||
template <typename Point>
|
||||
struct assign<point_tag, Point, 2>
|
||||
{
|
||||
typedef typename coordinate_type<Point>::type coordinate_type;
|
||||
|
||||
template <typename T>
|
||||
static inline void apply(Point& point, T const& c1, T const& c2)
|
||||
{
|
||||
set<0>(point, util::numeric_cast<coordinate_type>(c1));
|
||||
set<1>(point, util::numeric_cast<coordinate_type>(c2));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Point>
|
||||
struct assign<point_tag, Point, 3>
|
||||
{
|
||||
typedef typename coordinate_type<Point>::type coordinate_type;
|
||||
|
||||
template <typename T>
|
||||
static inline void apply(Point& point, T const& c1, T const& c2, T const& c3)
|
||||
{
|
||||
set<0>(point, util::numeric_cast<coordinate_type>(c1));
|
||||
set<1>(point, util::numeric_cast<coordinate_type>(c2));
|
||||
set<2>(point, util::numeric_cast<coordinate_type>(c3));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Box>
|
||||
struct assign<box_tag, Box, 2>
|
||||
: detail::assign::assign_2d_box_or_segment<Box>
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct assign<segment_tag, Segment, 2>
|
||||
: detail::assign::assign_2d_box_or_segment<Segment>
|
||||
{};
|
||||
|
||||
|
||||
|
||||
template <typename GeometryTag, typename Geometry>
|
||||
struct assign_zero {};
|
||||
|
||||
|
||||
template <typename Point>
|
||||
struct assign_zero<point_tag, Point>
|
||||
: detail::assign::assign_zero_point
|
||||
{};
|
||||
|
||||
template <typename Box>
|
||||
struct assign_zero<box_tag, Box>
|
||||
: detail::assign::assign_zero_box_or_segment
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct assign_zero<segment_tag, Segment>
|
||||
: detail::assign::assign_zero_box_or_segment
|
||||
{};
|
||||
|
||||
|
||||
template <typename GeometryTag, typename Geometry>
|
||||
struct assign_inverse {};
|
||||
|
||||
template <typename Box>
|
||||
struct assign_inverse<box_tag, Box>
|
||||
: detail::assign::assign_inverse_box_or_segment
|
||||
{};
|
||||
|
||||
template <typename Segment>
|
||||
struct assign_inverse<segment_tag, Segment>
|
||||
: detail::assign::assign_inverse_box_or_segment
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2018-2019 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_BOX_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_BOX_HPP
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/geometry/core/coordinate_dimension.hpp>
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
#include <boost/geometry/core/access.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
template <typename BoxIn, typename BoxOut, typename T, std::size_t C, std::size_t D, std::size_t N>
|
||||
struct box_loop
|
||||
{
|
||||
typedef typename coordinate_type<BoxOut>::type coordinate_type;
|
||||
|
||||
static inline void apply(BoxIn const& box_in, T const& distance, BoxOut& box_out)
|
||||
{
|
||||
coordinate_type d = distance;
|
||||
set<C, D>(box_out, get<C, D>(box_in) + d);
|
||||
box_loop<BoxIn, BoxOut, T, C, D + 1, N>::apply(box_in, distance, box_out);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename BoxIn, typename BoxOut, typename T, std::size_t C, std::size_t N>
|
||||
struct box_loop<BoxIn, BoxOut, T, C, N, N>
|
||||
{
|
||||
static inline void apply(BoxIn const&, T const&, BoxOut&) {}
|
||||
};
|
||||
|
||||
// Extends a box with the same amount in all directions
|
||||
template<typename BoxIn, typename BoxOut, typename T>
|
||||
inline void buffer_box(BoxIn const& box_in, T const& distance, BoxOut& box_out)
|
||||
{
|
||||
assert_dimension_equal<BoxIn, BoxOut>();
|
||||
|
||||
static const std::size_t N = dimension<BoxIn>::value;
|
||||
|
||||
box_loop<BoxIn, BoxOut, T, min_corner, 0, N>::apply(box_in, -distance, box_out);
|
||||
box_loop<BoxIn, BoxOut, T, max_corner, 0, N>::apply(box_in, distance, box_out);
|
||||
}
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_BOX_HPP
|
||||
+1030
File diff suppressed because it is too large
Load Diff
+289
@@ -0,0 +1,289 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// This file was modified by Oracle on 2017-2024.
|
||||
// Modifications copyright (c) 2017-2024, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
#include <boost/geometry/core/point_type.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/overlay/backtrack_check_si.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/traversal_info.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/buffer.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
class backtrack_for_buffer
|
||||
{
|
||||
public :
|
||||
typedef detail::overlay::backtrack_state state_type;
|
||||
|
||||
template
|
||||
<
|
||||
typename Operation,
|
||||
typename Rings,
|
||||
typename Turns,
|
||||
typename Geometry,
|
||||
typename Strategy,
|
||||
typename Visitor
|
||||
>
|
||||
static inline void apply(std::size_t size_at_start,
|
||||
Rings& rings, typename boost::range_value<Rings>::type& ring,
|
||||
Turns& turns,
|
||||
typename boost::range_value<Turns>::type const& /*turn*/,
|
||||
Operation& operation,
|
||||
detail::overlay::traverse_error_type /*traverse_error*/,
|
||||
Geometry const& ,
|
||||
Geometry const& ,
|
||||
Strategy const& ,
|
||||
state_type& state,
|
||||
Visitor& /*visitor*/
|
||||
)
|
||||
{
|
||||
#if defined(BOOST_GEOMETRY_COUNT_BACKTRACK_WARNINGS)
|
||||
extern int g_backtrack_warning_count;
|
||||
g_backtrack_warning_count++;
|
||||
#endif
|
||||
//std::cout << "!";
|
||||
//std::cout << "WARNING " << traverse_error_string(traverse_error) << std::endl;
|
||||
|
||||
state.m_good = false;
|
||||
|
||||
// Make bad output clean
|
||||
rings.resize(size_at_start);
|
||||
ring.clear();
|
||||
|
||||
// Reject this as a starting point
|
||||
operation.visited.set_rejected();
|
||||
|
||||
// And clear all visit info
|
||||
clear_visit_info(turns);
|
||||
}
|
||||
};
|
||||
|
||||
struct buffer_overlay_visitor
|
||||
{
|
||||
public :
|
||||
void print(char const* /*header*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Turns>
|
||||
void print(char const* /*header*/, Turns const& /*turns*/, int /*turn_index*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Turns>
|
||||
void print(char const* /*header*/, Turns const& /*turns*/, int /*turn_index*/, int /*op_index*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Turns>
|
||||
void visit_turns(int , Turns const& ) {}
|
||||
|
||||
template <typename Clusters, typename Turns>
|
||||
void visit_clusters(Clusters const& , Turns const& ) {}
|
||||
|
||||
template <typename Turns, typename Turn, typename Operation>
|
||||
void visit_traverse(Turns const& /*turns*/, Turn const& /*turn*/, Operation const& /*op*/, const char* /*header*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Turns, typename Turn, typename Operation>
|
||||
void visit_traverse_reject(Turns const& , Turn const& , Operation const& ,
|
||||
detail::overlay::traverse_error_type )
|
||||
{}
|
||||
|
||||
template <typename Rings>
|
||||
void visit_generated_rings(Rings const& )
|
||||
{}
|
||||
};
|
||||
|
||||
|
||||
// Should follow traversal-turn-concept (enrichment, visit structure)
|
||||
// and adds index in piece vector to find it back
|
||||
template <typename Point, typename SegmentRatio>
|
||||
struct buffer_turn_operation
|
||||
: public detail::overlay::traversal_turn_operation<Point, SegmentRatio>
|
||||
{
|
||||
signed_size_type piece_index;
|
||||
signed_size_type index_in_ring;
|
||||
|
||||
inline buffer_turn_operation()
|
||||
: piece_index(-1)
|
||||
, index_in_ring(-1)
|
||||
{}
|
||||
};
|
||||
|
||||
// Version of turn_info for buffer with its turn index and other helper variables
|
||||
template <typename Point, typename SegmentRatio>
|
||||
struct buffer_turn_info
|
||||
: public detail::overlay::turn_info
|
||||
<
|
||||
Point,
|
||||
SegmentRatio,
|
||||
buffer_turn_operation<Point, SegmentRatio>
|
||||
>
|
||||
{
|
||||
typedef Point point_type;
|
||||
|
||||
std::size_t turn_index;
|
||||
|
||||
// Information if turn can be used. It is not traversable if it is within
|
||||
// another piece, or within the original (depending on deflation),
|
||||
// or (for deflate) if there are not enough points to traverse it.
|
||||
bool is_turn_traversable;
|
||||
|
||||
bool is_linear_end_point;
|
||||
bool within_original;
|
||||
signed_size_type count_in_original; // increased by +1 for in ext.ring, -1 for int.ring
|
||||
|
||||
inline buffer_turn_info()
|
||||
: turn_index(0)
|
||||
, is_turn_traversable(true)
|
||||
, is_linear_end_point(false)
|
||||
, within_original(false)
|
||||
, count_in_original(0)
|
||||
{}
|
||||
};
|
||||
|
||||
struct buffer_less
|
||||
{
|
||||
template <typename Indexed>
|
||||
inline bool operator()(Indexed const& left, Indexed const& right) const
|
||||
{
|
||||
if (! (left.subject->seg_id == right.subject->seg_id))
|
||||
{
|
||||
return left.subject->seg_id < right.subject->seg_id;
|
||||
}
|
||||
|
||||
// Both left and right are located on the SAME segment.
|
||||
if (! (left.subject->fraction == right.subject->fraction))
|
||||
{
|
||||
return left.subject->fraction < right.subject->fraction;
|
||||
}
|
||||
|
||||
return left.turn_index < right.turn_index;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct piece_get_box
|
||||
{
|
||||
explicit piece_get_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Piece>
|
||||
inline void apply(Box& total, Piece const& piece) const
|
||||
{
|
||||
assert_coordinate_type_equal(total, piece.m_piece_border.m_envelope);
|
||||
|
||||
if (piece.m_piece_border.m_has_envelope)
|
||||
{
|
||||
geometry::expand(total, piece.m_piece_border.m_envelope,
|
||||
m_strategy);
|
||||
}
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct piece_overlaps_box
|
||||
{
|
||||
explicit piece_overlaps_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Piece>
|
||||
inline bool apply(Box const& box, Piece const& piece) const
|
||||
{
|
||||
assert_coordinate_type_equal(box, piece.m_piece_border.m_envelope);
|
||||
|
||||
if (piece.type == strategy::buffer::buffered_flat_end
|
||||
|| piece.type == strategy::buffer::buffered_concave)
|
||||
{
|
||||
// Turns cannot be inside a flat end (though they can be on border)
|
||||
// Neither we need to check if they are inside concave helper pieces
|
||||
|
||||
// Skip all pieces not used as soon as possible
|
||||
return false;
|
||||
}
|
||||
if (! piece.m_piece_border.m_has_envelope)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! geometry::detail::disjoint::disjoint_box_box(box, piece.m_piece_border.m_envelope,
|
||||
m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct turn_get_box
|
||||
{
|
||||
explicit turn_get_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Turn>
|
||||
inline void apply(Box& total, Turn const& turn) const
|
||||
{
|
||||
assert_coordinate_type_equal(total, turn.point);
|
||||
geometry::expand(total, turn.point, m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct turn_overlaps_box
|
||||
{
|
||||
explicit turn_overlaps_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Turn>
|
||||
inline bool apply(Box const& box, Turn const& turn) const
|
||||
{
|
||||
assert_coordinate_type_equal(turn.point, box);
|
||||
return ! geometry::detail::disjoint::disjoint_point_box(turn.point, box,
|
||||
m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP
|
||||
+1125
File diff suppressed because it is too large
Load Diff
+290
@@ -0,0 +1,290 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2012-2015 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// This file was modified by Oracle on 2020.
|
||||
// Modifications copyright (c) 2020 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFERED_RING
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFERED_RING
|
||||
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <boost/range/size.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/core/assert.hpp>
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
#include <boost/geometry/core/closure.hpp>
|
||||
#include <boost/geometry/core/point_order.hpp>
|
||||
#include <boost/geometry/core/point_type.hpp>
|
||||
|
||||
#include <boost/geometry/strategies/buffer.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/within.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/overlay/copy_segments.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/copy_segment_point.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/enrichment_info.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/get_ring.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/traversal_info.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/turn_info.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
struct buffered_ring_collection_tag : polygonal_tag, multi_tag
|
||||
{};
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct buffered_ring : public Ring
|
||||
{
|
||||
bool has_concave;
|
||||
bool has_accepted_intersections;
|
||||
bool has_discarded_intersections;
|
||||
bool is_untouched_outside_original;
|
||||
|
||||
inline buffered_ring()
|
||||
: has_concave(false)
|
||||
, has_accepted_intersections(false)
|
||||
, has_discarded_intersections(false)
|
||||
, is_untouched_outside_original(false)
|
||||
{}
|
||||
|
||||
inline bool discarded() const
|
||||
{
|
||||
return has_discarded_intersections && ! has_accepted_intersections;
|
||||
}
|
||||
inline bool has_intersections() const
|
||||
{
|
||||
return has_discarded_intersections || has_accepted_intersections;
|
||||
}
|
||||
};
|
||||
|
||||
// This is a collection now special for overlay (needs vector of rings)
|
||||
template <typename Ring>
|
||||
struct buffered_ring_collection : public std::vector<Ring>
|
||||
{
|
||||
};
|
||||
|
||||
}} // namespace detail::buffer
|
||||
|
||||
|
||||
// Turn off concept checking (for now)
|
||||
namespace concepts
|
||||
{
|
||||
|
||||
template <typename Geometry>
|
||||
struct concept_type<Geometry, geometry::detail::buffer::buffered_ring_collection_tag>
|
||||
{
|
||||
struct dummy {};
|
||||
using type = dummy;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
|
||||
// Register the types
|
||||
namespace traits
|
||||
{
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct tag<geometry::detail::buffer::buffered_ring<Ring> >
|
||||
{
|
||||
typedef ring_tag type;
|
||||
};
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct point_order<geometry::detail::buffer::buffered_ring<Ring> >
|
||||
{
|
||||
static const order_selector value = geometry::point_order<Ring>::value;
|
||||
};
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct closure<geometry::detail::buffer::buffered_ring<Ring> >
|
||||
{
|
||||
static const closure_selector value = geometry::closure<Ring>::value;
|
||||
};
|
||||
|
||||
|
||||
template <typename Ring>
|
||||
struct point_type<geometry::detail::buffer::buffered_ring_collection<Ring> >
|
||||
{
|
||||
typedef typename geometry::point_type<Ring>::type type;
|
||||
};
|
||||
|
||||
template <typename Ring>
|
||||
struct tag<geometry::detail::buffer::buffered_ring_collection<Ring> >
|
||||
{
|
||||
typedef geometry::detail::buffer::buffered_ring_collection_tag type;
|
||||
};
|
||||
|
||||
|
||||
} // namespace traits
|
||||
|
||||
|
||||
|
||||
|
||||
namespace core_dispatch
|
||||
{
|
||||
|
||||
template <typename Ring>
|
||||
struct ring_type
|
||||
<
|
||||
detail::buffer::buffered_ring_collection_tag,
|
||||
detail::buffer::buffered_ring_collection<Ring>
|
||||
>
|
||||
{
|
||||
typedef Ring type;
|
||||
};
|
||||
|
||||
|
||||
// There is a specific tag, so this specialization cannot be placed in traits
|
||||
template <typename Ring>
|
||||
struct point_order<detail::buffer::buffered_ring_collection_tag,
|
||||
geometry::detail::buffer::buffered_ring_collection
|
||||
<
|
||||
geometry::detail::buffer::buffered_ring<Ring>
|
||||
> >
|
||||
{
|
||||
static const order_selector value
|
||||
= core_dispatch::point_order<ring_tag, Ring>::value;
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
template <>
|
||||
struct single_tag_of<detail::buffer::buffered_ring_collection_tag>
|
||||
{
|
||||
typedef ring_tag type;
|
||||
};
|
||||
|
||||
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename MultiRing,
|
||||
bool Reverse,
|
||||
typename SegmentIdentifier,
|
||||
typename PointOut
|
||||
>
|
||||
struct copy_segment_point
|
||||
<
|
||||
detail::buffer::buffered_ring_collection_tag,
|
||||
MultiRing,
|
||||
Reverse,
|
||||
SegmentIdentifier,
|
||||
PointOut
|
||||
>
|
||||
: detail::copy_segments::copy_segment_point_multi
|
||||
<
|
||||
MultiRing,
|
||||
SegmentIdentifier,
|
||||
PointOut,
|
||||
detail::copy_segments::copy_segment_point_range
|
||||
<
|
||||
typename boost::range_value<MultiRing>::type,
|
||||
Reverse,
|
||||
SegmentIdentifier,
|
||||
PointOut
|
||||
>
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
template<bool Reverse>
|
||||
struct copy_segments
|
||||
<
|
||||
detail::buffer::buffered_ring_collection_tag,
|
||||
Reverse
|
||||
>
|
||||
: detail::copy_segments::copy_segments_multi
|
||||
<
|
||||
detail::copy_segments::copy_segments_ring<Reverse>
|
||||
>
|
||||
{};
|
||||
|
||||
template <typename Point, typename MultiGeometry>
|
||||
struct within
|
||||
<
|
||||
Point,
|
||||
MultiGeometry,
|
||||
point_tag,
|
||||
detail::buffer::buffered_ring_collection_tag
|
||||
>
|
||||
{
|
||||
template <typename Strategy>
|
||||
static inline bool apply(Point const& point,
|
||||
MultiGeometry const& multi, Strategy const& strategy)
|
||||
{
|
||||
return detail::within::point_in_geometry(point, multi, strategy) == 1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct is_empty<Geometry, detail::buffer::buffered_ring_collection_tag>
|
||||
: detail::is_empty::multi_is_empty<detail::is_empty::range_is_empty>
|
||||
{};
|
||||
|
||||
|
||||
template <typename Geometry>
|
||||
struct envelope<Geometry, detail::buffer::buffered_ring_collection_tag>
|
||||
: detail::envelope::envelope_multi_range
|
||||
<
|
||||
detail::envelope::envelope_range
|
||||
>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
|
||||
namespace detail { namespace overlay
|
||||
{
|
||||
|
||||
template<>
|
||||
struct get_ring<detail::buffer::buffered_ring_collection_tag>
|
||||
{
|
||||
template<typename MultiGeometry>
|
||||
static inline typename ring_type<MultiGeometry>::type const& apply(
|
||||
ring_identifier const& id,
|
||||
MultiGeometry const& multi_ring)
|
||||
{
|
||||
BOOST_GEOMETRY_ASSERT
|
||||
(
|
||||
id.multi_index >= 0
|
||||
&& id.multi_index < int(boost::size(multi_ring))
|
||||
);
|
||||
return get_ring<ring_tag>::apply(id, multi_ring[id.multi_index]);
|
||||
}
|
||||
};
|
||||
|
||||
}}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFERED_RING
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2017-2024.
|
||||
// Modifications copyright (c) 2017-2024 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_GET_PIECE_TURNS_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_GET_PIECE_TURNS_HPP
|
||||
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
#include <boost/range/begin.hpp>
|
||||
#include <boost/range/end.hpp>
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/core/assert.hpp>
|
||||
#include <boost/geometry/algorithms/equals.hpp>
|
||||
#include <boost/geometry/algorithms/detail/disjoint/box_box.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/segment_identifier.hpp>
|
||||
#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>
|
||||
#include <boost/geometry/algorithms/detail/sections/section_functions.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
// Implements a unique_sub_range for a buffered piece,
|
||||
// the range can return subsequent points
|
||||
// known as "i", "j" and "k" (and further), indexed as 0,1,2,3
|
||||
template <typename Ring>
|
||||
struct unique_sub_range_from_piece
|
||||
{
|
||||
typedef typename boost::range_iterator<Ring const>::type iterator_type;
|
||||
typedef typename geometry::point_type<Ring const>::type point_type;
|
||||
|
||||
unique_sub_range_from_piece(Ring const& ring,
|
||||
iterator_type iterator_at_i, iterator_type iterator_at_j)
|
||||
: m_ring(ring)
|
||||
, m_iterator_at_i(iterator_at_i)
|
||||
, m_iterator_at_j(iterator_at_j)
|
||||
, m_point_retrieved(false)
|
||||
{}
|
||||
|
||||
static inline bool is_first_segment() { return false; }
|
||||
static inline bool is_last_segment() { return false; }
|
||||
|
||||
static inline std::size_t size() { return 3u; }
|
||||
|
||||
inline point_type const& at(std::size_t index) const
|
||||
{
|
||||
BOOST_GEOMETRY_ASSERT(index < size());
|
||||
switch (index)
|
||||
{
|
||||
case 0 : return *m_iterator_at_i;
|
||||
case 1 : return *m_iterator_at_j;
|
||||
case 2 : return get_point_k();
|
||||
default : return *m_iterator_at_i;
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
inline point_type const& get_point_k() const
|
||||
{
|
||||
if (! m_point_retrieved)
|
||||
{
|
||||
m_iterator_at_k = advance_one(m_iterator_at_j);
|
||||
m_point_retrieved = true;
|
||||
}
|
||||
return *m_iterator_at_k;
|
||||
}
|
||||
|
||||
inline void circular_advance_one(iterator_type& next) const
|
||||
{
|
||||
++next;
|
||||
if (next == boost::end(m_ring))
|
||||
{
|
||||
next = boost::begin(m_ring) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
inline iterator_type advance_one(iterator_type it) const
|
||||
{
|
||||
iterator_type result = it;
|
||||
circular_advance_one(result);
|
||||
|
||||
// TODO: we could also use piece-boundaries
|
||||
// to check if the point equals the last one
|
||||
while (geometry::equals(*it, *result))
|
||||
{
|
||||
circular_advance_one(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Ring const& m_ring;
|
||||
iterator_type m_iterator_at_i;
|
||||
iterator_type m_iterator_at_j;
|
||||
mutable iterator_type m_iterator_at_k;
|
||||
mutable bool m_point_retrieved;
|
||||
};
|
||||
|
||||
template
|
||||
<
|
||||
typename Pieces,
|
||||
typename Rings,
|
||||
typename Turns,
|
||||
typename Strategy
|
||||
>
|
||||
class piece_turn_visitor
|
||||
{
|
||||
Pieces const& m_pieces;
|
||||
Rings const& m_rings;
|
||||
Turns& m_turns;
|
||||
Strategy const& m_strategy;
|
||||
|
||||
template <typename Piece>
|
||||
inline bool is_adjacent(Piece const& piece1, Piece const& piece2) const
|
||||
{
|
||||
if (piece1.first_seg_id.multi_index != piece2.first_seg_id.multi_index)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return piece1.index == piece2.left_index
|
||||
|| piece1.index == piece2.right_index;
|
||||
}
|
||||
|
||||
template <typename Piece>
|
||||
inline bool is_on_same_convex_ring(Piece const& piece1, Piece const& piece2) const
|
||||
{
|
||||
if (piece1.first_seg_id.multi_index != piece2.first_seg_id.multi_index)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! m_rings[piece1.first_seg_id.multi_index].has_concave;
|
||||
}
|
||||
|
||||
template <std::size_t Dimension, typename Iterator, typename Box>
|
||||
inline void move_begin_iterator(Iterator& it_begin, Iterator it_beyond,
|
||||
signed_size_type& index, int dir,
|
||||
Box const& this_bounding_box,
|
||||
Box const& other_bounding_box)
|
||||
{
|
||||
for(; it_begin != it_beyond
|
||||
&& it_begin + 1 != it_beyond
|
||||
&& detail::section::preceding<Dimension>(dir, *(it_begin + 1),
|
||||
this_bounding_box,
|
||||
other_bounding_box);
|
||||
++it_begin, index++)
|
||||
{}
|
||||
}
|
||||
|
||||
template <std::size_t Dimension, typename Iterator, typename Box>
|
||||
inline void move_end_iterator(Iterator it_begin, Iterator& it_beyond,
|
||||
int dir, Box const& this_bounding_box,
|
||||
Box const& other_bounding_box)
|
||||
{
|
||||
while (it_beyond != it_begin
|
||||
&& it_beyond - 1 != it_begin
|
||||
&& it_beyond - 2 != it_begin)
|
||||
{
|
||||
if (detail::section::exceeding<Dimension>(dir, *(it_beyond - 2),
|
||||
this_bounding_box, other_bounding_box))
|
||||
{
|
||||
--it_beyond;
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Piece, typename Section>
|
||||
inline void calculate_turns(Piece const& piece1, Piece const& piece2,
|
||||
Section const& section1, Section const& section2)
|
||||
{
|
||||
typedef typename boost::range_value<Rings const>::type ring_type;
|
||||
typedef typename boost::range_value<Turns const>::type turn_type;
|
||||
|
||||
signed_size_type const piece1_first_index = piece1.first_seg_id.segment_index;
|
||||
signed_size_type const piece2_first_index = piece2.first_seg_id.segment_index;
|
||||
if (piece1_first_index < 0 || piece2_first_index < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get indices of part of offsetted_rings for this monotonic section:
|
||||
signed_size_type const sec1_first_index = piece1_first_index + section1.begin_index;
|
||||
signed_size_type const sec2_first_index = piece2_first_index + section2.begin_index;
|
||||
|
||||
// index of last point in section, beyond-end is one further
|
||||
signed_size_type const sec1_last_index = piece1_first_index + section1.end_index;
|
||||
signed_size_type const sec2_last_index = piece2_first_index + section2.end_index;
|
||||
|
||||
// get geometry and iterators over these sections
|
||||
ring_type const& ring1 = m_rings[piece1.first_seg_id.multi_index];
|
||||
auto it1_first = boost::begin(ring1) + sec1_first_index;
|
||||
auto it1_beyond = boost::begin(ring1) + sec1_last_index + 1;
|
||||
|
||||
ring_type const& ring2 = m_rings[piece2.first_seg_id.multi_index];
|
||||
auto it2_first = boost::begin(ring2) + sec2_first_index;
|
||||
auto it2_beyond = boost::begin(ring2) + sec2_last_index + 1;
|
||||
|
||||
// Set begin/end of monotonic ranges, in both x/y directions
|
||||
signed_size_type index1 = sec1_first_index;
|
||||
move_begin_iterator<0>(it1_first, it1_beyond, index1,
|
||||
section1.directions[0], section1.bounding_box, section2.bounding_box);
|
||||
move_end_iterator<0>(it1_first, it1_beyond,
|
||||
section1.directions[0], section1.bounding_box, section2.bounding_box);
|
||||
move_begin_iterator<1>(it1_first, it1_beyond, index1,
|
||||
section1.directions[1], section1.bounding_box, section2.bounding_box);
|
||||
move_end_iterator<1>(it1_first, it1_beyond,
|
||||
section1.directions[1], section1.bounding_box, section2.bounding_box);
|
||||
|
||||
signed_size_type index2 = sec2_first_index;
|
||||
move_begin_iterator<0>(it2_first, it2_beyond, index2,
|
||||
section2.directions[0], section2.bounding_box, section1.bounding_box);
|
||||
move_end_iterator<0>(it2_first, it2_beyond,
|
||||
section2.directions[0], section2.bounding_box, section1.bounding_box);
|
||||
move_begin_iterator<1>(it2_first, it2_beyond, index2,
|
||||
section2.directions[1], section2.bounding_box, section1.bounding_box);
|
||||
move_end_iterator<1>(it2_first, it2_beyond,
|
||||
section2.directions[1], section2.bounding_box, section1.bounding_box);
|
||||
|
||||
turn_type the_model;
|
||||
the_model.operations[0].piece_index = piece1.index;
|
||||
the_model.operations[0].seg_id = piece1.first_seg_id;
|
||||
the_model.operations[0].seg_id.segment_index = index1; // override
|
||||
|
||||
auto it1 = it1_first;
|
||||
for (auto prev1 = it1++;
|
||||
it1 != it1_beyond;
|
||||
prev1 = it1++, the_model.operations[0].seg_id.segment_index++)
|
||||
{
|
||||
the_model.operations[1].piece_index = piece2.index;
|
||||
the_model.operations[1].seg_id = piece2.first_seg_id;
|
||||
the_model.operations[1].seg_id.segment_index = index2; // override
|
||||
|
||||
unique_sub_range_from_piece<ring_type> unique_sub_range1(ring1, prev1, it1);
|
||||
|
||||
auto it2 = it2_first;
|
||||
for (auto prev2 = it2++;
|
||||
it2 != it2_beyond;
|
||||
prev2 = it2++, the_model.operations[1].seg_id.segment_index++)
|
||||
{
|
||||
unique_sub_range_from_piece<ring_type> unique_sub_range2(ring2, prev2, it2);
|
||||
|
||||
typedef detail::overlay::get_turn_info
|
||||
<
|
||||
detail::overlay::assign_policy_only_start_turns
|
||||
> turn_policy;
|
||||
|
||||
turn_policy::apply(unique_sub_range1, unique_sub_range2,
|
||||
the_model,
|
||||
m_strategy,
|
||||
std::back_inserter(m_turns));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
piece_turn_visitor(Pieces const& pieces,
|
||||
Rings const& ring_collection,
|
||||
Turns& turns,
|
||||
Strategy const& strategy)
|
||||
: m_pieces(pieces)
|
||||
, m_rings(ring_collection)
|
||||
, m_turns(turns)
|
||||
, m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Section>
|
||||
inline bool apply(Section const& section1, Section const& section2,
|
||||
bool first = true)
|
||||
{
|
||||
boost::ignore_unused(first);
|
||||
|
||||
typedef typename boost::range_value<Pieces const>::type piece_type;
|
||||
piece_type const& piece1 = m_pieces[section1.ring_id.source_index];
|
||||
piece_type const& piece2 = m_pieces[section2.ring_id.source_index];
|
||||
|
||||
if ( piece1.index == piece2.index
|
||||
|| is_adjacent(piece1, piece2)
|
||||
|| is_on_same_convex_ring(piece1, piece2)
|
||||
|| detail::disjoint::disjoint_box_box(section1.bounding_box,
|
||||
section2.bounding_box,
|
||||
m_strategy) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
calculate_turns(piece1, piece2, section1, section2);
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_GET_PIECE_TURNS_HPP
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2017-2024.
|
||||
// Modifications copyright (c) 2017-2024 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_IMPLEMENTATION_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_IMPLEMENTATION_HPP
|
||||
|
||||
#include <boost/range/value_type.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_box.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/interface.hpp>
|
||||
#include <boost/geometry/algorithms/detail/visit.hpp> // for GC
|
||||
#include <boost/geometry/algorithms/envelope.hpp>
|
||||
#include <boost/geometry/algorithms/is_empty.hpp>
|
||||
#include <boost/geometry/algorithms/union.hpp> // for GC
|
||||
#include <boost/geometry/arithmetic/arithmetic.hpp>
|
||||
#include <boost/geometry/geometries/box.hpp>
|
||||
#include <boost/geometry/strategies/buffer/cartesian.hpp>
|
||||
#include <boost/geometry/strategies/buffer/geographic.hpp>
|
||||
#include <boost/geometry/strategies/buffer/spherical.hpp>
|
||||
#include <boost/geometry/util/math.hpp>
|
||||
#include <boost/geometry/util/range.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template <typename BoxIn, typename BoxOut>
|
||||
struct buffer_dc<BoxIn, BoxOut, box_tag, box_tag>
|
||||
{
|
||||
template <typename Distance>
|
||||
static inline void apply(BoxIn const& box_in, BoxOut& box_out,
|
||||
Distance const& distance, Distance const& )
|
||||
{
|
||||
detail::buffer::buffer_box(box_in, distance, box_out);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Input, typename Output, typename TagIn>
|
||||
struct buffer_all<Input, Output, TagIn, multi_polygon_tag>
|
||||
{
|
||||
template
|
||||
<
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy,
|
||||
typename Strategies
|
||||
>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
typedef typename boost::range_value<Output>::type polygon_type;
|
||||
|
||||
if (geometry::is_empty(geometry_in))
|
||||
{
|
||||
// Then output geometry is kept empty as well
|
||||
return;
|
||||
}
|
||||
|
||||
model::box<point_type_t<Input>> box;
|
||||
geometry::envelope(geometry_in, box);
|
||||
geometry::buffer(box, box, distance_strategy.max_distance(join_strategy, end_strategy));
|
||||
|
||||
detail::buffer::buffer_inserter<polygon_type>(geometry_in,
|
||||
range::back_inserter(geometry_out),
|
||||
distance_strategy,
|
||||
side_strategy,
|
||||
join_strategy,
|
||||
end_strategy,
|
||||
point_strategy,
|
||||
strategies);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template <typename Input, typename Output>
|
||||
struct buffer_all<Input, Output, geometry_collection_tag, multi_polygon_tag>
|
||||
{
|
||||
template
|
||||
<
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy,
|
||||
typename Strategies
|
||||
>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
// NOTE: The buffer normally calculates everything at once (by pieces) and traverses all
|
||||
// of them to apply the union operation. Not even by merging elements. But that is
|
||||
// complex and has led to issues as well. Here intermediate results are calculated
|
||||
// with buffer and the results are merged afterwards.
|
||||
// NOTE: This algorithm merges partial results iteratively.
|
||||
// We could first gather all of the results and after that
|
||||
// use some more optimal method like merge_elements().
|
||||
detail::visit_breadth_first([&](auto const& g)
|
||||
{
|
||||
Output buffer_result;
|
||||
buffer_all
|
||||
<
|
||||
util::remove_cref_t<decltype(g)>, Output
|
||||
>::apply(g, buffer_result, distance_strategy, side_strategy,
|
||||
join_strategy, end_strategy, point_strategy, strategies);
|
||||
|
||||
if (! geometry::is_empty(buffer_result))
|
||||
{
|
||||
Output union_result;
|
||||
geometry::union_(geometry_out, buffer_result, union_result, strategies);
|
||||
geometry_out = std::move(union_result);
|
||||
}
|
||||
|
||||
return true;
|
||||
}, geometry_in);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Input, typename Output>
|
||||
struct buffer_all<Input, Output, geometry_collection_tag, geometry_collection_tag>
|
||||
{
|
||||
template
|
||||
<
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy,
|
||||
typename Strategies
|
||||
>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy,
|
||||
Strategies const& strategies)
|
||||
{
|
||||
// NOTE: We could also allow returning GC containing only polygons.
|
||||
// We'd have to wrap them in model::multi_polygon and then
|
||||
// iteratively emplace_back() into the GC.
|
||||
using mpo_t = typename util::sequence_find_if
|
||||
<
|
||||
typename traits::geometry_types<Output>::type,
|
||||
util::is_multi_polygon
|
||||
>::type;
|
||||
mpo_t result;
|
||||
buffer_all
|
||||
<
|
||||
Input, mpo_t
|
||||
>::apply(geometry_in, result, distance_strategy, side_strategy,
|
||||
join_strategy, end_strategy, point_strategy, strategies);
|
||||
range::emplace_back(geometry_out, std::move(result));
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Input, typename Output, typename TagIn>
|
||||
struct buffer_all<Input, Output, TagIn, geometry_collection_tag>
|
||||
: buffer_all<Input, Output, geometry_collection_tag, geometry_collection_tag>
|
||||
{};
|
||||
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_IMPLEMENTATION_HPP
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
|
||||
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
|
||||
|
||||
// This file was modified by Oracle on 2017-2022.
|
||||
// Modifications copyright (c) 2017-2022 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
|
||||
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_INTERFACE_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_INTERFACE_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/clear.hpp>
|
||||
#include <boost/geometry/algorithms/not_implemented.hpp>
|
||||
#include <boost/geometry/core/visit.hpp>
|
||||
#include <boost/geometry/core/tag.hpp>
|
||||
#include <boost/geometry/geometries/adapted/boost_variant.hpp>
|
||||
#include <boost/geometry/geometries/concepts/check.hpp>
|
||||
#include <boost/geometry/strategies/buffer/services.hpp>
|
||||
#include <boost/geometry/util/type_traits_std.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DISPATCH
|
||||
namespace dispatch
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Input,
|
||||
typename Output,
|
||||
typename TagIn = typename tag<Input>::type,
|
||||
typename TagOut = typename tag<Output>::type
|
||||
>
|
||||
struct buffer_dc : not_implemented<TagIn, TagOut>
|
||||
{};
|
||||
|
||||
template
|
||||
<
|
||||
typename Input,
|
||||
typename Output,
|
||||
typename TagIn = typename tag<Input>::type,
|
||||
typename TagOut = typename tag<Output>::type
|
||||
>
|
||||
struct buffer_all : not_implemented<TagIn, TagOut>
|
||||
{};
|
||||
|
||||
} // namespace dispatch
|
||||
#endif // DOXYGEN_NO_DISPATCH
|
||||
|
||||
|
||||
namespace resolve_dynamic
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename Input,
|
||||
typename TagIn = typename geometry::tag<Input>::type
|
||||
>
|
||||
struct buffer_dc
|
||||
{
|
||||
template <typename Output, typename Distance>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
Distance const& distance,
|
||||
Distance const& chord_length)
|
||||
{
|
||||
dispatch::buffer_dc<Input, Output>::apply(geometry_in, geometry_out, distance, chord_length);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Input>
|
||||
struct buffer_dc<Input, dynamic_geometry_tag>
|
||||
{
|
||||
template <typename Output, typename Distance>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
Distance const& distance,
|
||||
Distance const& chord_length)
|
||||
{
|
||||
traits::visit<Input>::apply([&](auto const& g)
|
||||
{
|
||||
dispatch::buffer_dc
|
||||
<
|
||||
util::remove_cref_t<decltype(g)>, Output
|
||||
>::apply(g, geometry_out, distance, chord_length);
|
||||
}, geometry_in);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template
|
||||
<
|
||||
typename Input,
|
||||
typename TagIn = typename geometry::tag<Input>::type
|
||||
>
|
||||
struct buffer_all
|
||||
{
|
||||
template
|
||||
<
|
||||
typename Output,
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy
|
||||
>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy)
|
||||
{
|
||||
typename strategies::buffer::services::default_strategy
|
||||
<
|
||||
Input
|
||||
>::type strategies;
|
||||
|
||||
dispatch::buffer_all
|
||||
<
|
||||
Input, Output
|
||||
>::apply(geometry_in, geometry_out, distance_strategy, side_strategy,
|
||||
join_strategy, end_strategy, point_strategy, strategies);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Input>
|
||||
struct buffer_all<Input, dynamic_geometry_tag>
|
||||
{
|
||||
template
|
||||
<
|
||||
typename Output,
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy
|
||||
>
|
||||
static inline void apply(Input const& geometry_in,
|
||||
Output& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy)
|
||||
{
|
||||
traits::visit<Input>::apply([&](auto const& g)
|
||||
{
|
||||
buffer_all
|
||||
<
|
||||
util::remove_cref_t<decltype(g)>
|
||||
>::apply(g, geometry_out, distance_strategy, side_strategy,
|
||||
join_strategy, end_strategy, point_strategy);
|
||||
}, geometry_in);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace resolve_dynamic
|
||||
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{buffer}
|
||||
\ingroup buffer
|
||||
\details \details_calc{buffer, \det_buffer}.
|
||||
\tparam Input \tparam_geometry
|
||||
\tparam Output \tparam_geometry
|
||||
\tparam Distance \tparam_numeric
|
||||
\param geometry_in \param_geometry
|
||||
\param geometry_out \param_geometry
|
||||
\param distance The distance to be used for the buffer
|
||||
\param chord_length (optional) The length of the chord's in the generated arcs around points or bends
|
||||
|
||||
\qbk{[include reference/algorithms/buffer.qbk]}
|
||||
*/
|
||||
template <typename Input, typename Output, typename Distance>
|
||||
inline void buffer(Input const& geometry_in, Output& geometry_out,
|
||||
Distance const& distance, Distance const& chord_length = -1)
|
||||
{
|
||||
concepts::check<Input const>();
|
||||
concepts::check<Output>();
|
||||
|
||||
resolve_dynamic::buffer_dc<Input>::apply(geometry_in, geometry_out, distance, chord_length);
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{buffer}
|
||||
\ingroup buffer
|
||||
\details \details_calc{return_buffer, \det_buffer}. \details_return{buffer}.
|
||||
\tparam Input \tparam_geometry
|
||||
\tparam Output \tparam_geometry
|
||||
\tparam Distance \tparam_numeric
|
||||
\param geometry \param_geometry
|
||||
\param distance The distance to be used for the buffer
|
||||
\param chord_length (optional) The length of the chord's in the generated arcs
|
||||
around points or bends (RESERVED, NOT YET USED)
|
||||
\return \return_calc{buffer}
|
||||
*/
|
||||
template <typename Output, typename Input, typename Distance>
|
||||
inline Output return_buffer(Input const& geometry, Distance const& distance,
|
||||
Distance const& chord_length = -1)
|
||||
{
|
||||
concepts::check<Input const>();
|
||||
concepts::check<Output>();
|
||||
|
||||
Output geometry_out;
|
||||
|
||||
resolve_dynamic::buffer_dc<Input>::apply(geometry, geometry_out, distance, chord_length);
|
||||
|
||||
return geometry_out;
|
||||
}
|
||||
|
||||
/*!
|
||||
\brief \brief_calc{buffer}
|
||||
\ingroup buffer
|
||||
\details \details_calc{buffer, \det_buffer}.
|
||||
\tparam GeometryIn \tparam_geometry
|
||||
\tparam GeometryOut \tparam_geometry{GeometryOut}
|
||||
\tparam DistanceStrategy A strategy defining distance (or radius)
|
||||
\tparam SideStrategy A strategy defining creation along sides
|
||||
\tparam JoinStrategy A strategy defining creation around convex corners
|
||||
\tparam EndStrategy A strategy defining creation at linestring ends
|
||||
\tparam PointStrategy A strategy defining creation around points
|
||||
\param geometry_in \param_geometry
|
||||
\param geometry_out output geometry, e.g. multi polygon,
|
||||
will contain a buffered version of the input geometry
|
||||
\param distance_strategy The distance strategy to be used
|
||||
\param side_strategy The side strategy to be used
|
||||
\param join_strategy The join strategy to be used
|
||||
\param end_strategy The end strategy to be used
|
||||
\param point_strategy The point strategy to be used
|
||||
|
||||
\qbk{distinguish,with strategies}
|
||||
\qbk{[include reference/algorithms/buffer_with_strategies.qbk]}
|
||||
*/
|
||||
template
|
||||
<
|
||||
typename GeometryIn,
|
||||
typename GeometryOut,
|
||||
typename DistanceStrategy,
|
||||
typename SideStrategy,
|
||||
typename JoinStrategy,
|
||||
typename EndStrategy,
|
||||
typename PointStrategy
|
||||
>
|
||||
inline void buffer(GeometryIn const& geometry_in,
|
||||
GeometryOut& geometry_out,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
SideStrategy const& side_strategy,
|
||||
JoinStrategy const& join_strategy,
|
||||
EndStrategy const& end_strategy,
|
||||
PointStrategy const& point_strategy)
|
||||
{
|
||||
concepts::check<GeometryIn const>();
|
||||
concepts::check<GeometryOut>();
|
||||
|
||||
geometry::clear(geometry_out);
|
||||
|
||||
resolve_dynamic::buffer_all
|
||||
<
|
||||
GeometryIn, GeometryOut
|
||||
>::apply(geometry_in, geometry_out, distance_strategy, side_strategy,
|
||||
join_strategy, end_strategy, point_strategy);
|
||||
}
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_INTERFACE_HPP
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2012-2020 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP
|
||||
|
||||
#include <boost/geometry/algorithms/detail/make/make.hpp>
|
||||
#include <boost/geometry/arithmetic/infinite_line_functions.hpp>
|
||||
#include <boost/geometry/util/math.hpp>
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
struct line_line_intersection
|
||||
{
|
||||
template <typename Point>
|
||||
static Point between_point(Point const& a, Point const& b)
|
||||
{
|
||||
Point result;
|
||||
geometry::set<0>(result, (geometry::get<0>(a) + geometry::get<0>(b)) / 2.0);
|
||||
geometry::set<1>(result, (geometry::get<1>(a) + geometry::get<1>(b)) / 2.0);
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename Point>
|
||||
static bool
|
||||
apply(Point const& pi, Point const& pj, Point const& qi, Point const& qj,
|
||||
Point const& vertex, bool equidistant, Point& ip)
|
||||
{
|
||||
// Calculates ip (below) by either intersecting p (pi, pj)
|
||||
// with q (qi, qj) or by taking a point between pj and qi (b) and
|
||||
// intersecting r (b, v), where v is the original vertex, with p (or q).
|
||||
// The reason for dual approach: p might be nearly collinear with q,
|
||||
// and in that case the intersection points can lose precision
|
||||
// (or be plainly wrong).
|
||||
// Therefore it takes the most precise option (this is usually p, r)
|
||||
//
|
||||
// /qj |
|
||||
// / |
|
||||
// / / |
|
||||
// / / |
|
||||
// / / |
|
||||
// /qi / |
|
||||
// / |
|
||||
// ip * + b * v |
|
||||
// \ |
|
||||
// \pj \ |
|
||||
// \ \ |
|
||||
// \ \ |
|
||||
// \ \ |
|
||||
// \pi \ |
|
||||
//
|
||||
// If generated sides along the segments can have an adapted distance,
|
||||
// in a custom strategy, then the calculation of the point in between
|
||||
// might be incorrect and the optimization is not used.
|
||||
|
||||
using ct = typename coordinate_type<Point>::type;
|
||||
|
||||
auto const p = detail::make::make_infinite_line<ct>(pi, pj);
|
||||
auto const q = detail::make::make_infinite_line<ct>(qi, qj);
|
||||
|
||||
using line = decltype(p);
|
||||
using arithmetic::determinant;
|
||||
using arithmetic::assign_intersection_point;
|
||||
|
||||
// The denominator is the determinant of (a,b) values of lines p q
|
||||
// | pa pa |
|
||||
// | qb qb |
|
||||
auto const denominator_pq = determinant<line, &line::a, &line::b>(p, q);
|
||||
static decltype(denominator_pq) const zero = 0;
|
||||
|
||||
if (equidistant)
|
||||
{
|
||||
auto const between = between_point(pj, qi);
|
||||
auto const r = detail::make::make_infinite_line<ct>(vertex, between);
|
||||
auto const denominator_pr = determinant<line, &line::a, &line::b>(p, r);
|
||||
|
||||
if (math::equals(denominator_pq, zero)
|
||||
&& math::equals(denominator_pr, zero))
|
||||
{
|
||||
// Degenerate case (for example when length results in <inf>)
|
||||
return false;
|
||||
}
|
||||
|
||||
ip = geometry::math::abs(denominator_pq) > geometry::math::abs(denominator_pr)
|
||||
? assign_intersection_point<Point>(p, q, denominator_pq)
|
||||
: assign_intersection_point<Point>(p, r, denominator_pr);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (math::equals(denominator_pq, zero))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ip = assign_intersection_point<Point>(p, q, denominator_pq);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP
|
||||
+512
@@ -0,0 +1,512 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2020-2021 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2023 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2020-2022.
|
||||
// Modifications copyright (c) 2020-2022, Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP
|
||||
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <boost/core/addressof.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
|
||||
#include <boost/geometry/core/assert.hpp>
|
||||
#include <boost/geometry/core/config.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/assign.hpp>
|
||||
#include <boost/geometry/algorithms/comparable_distance.hpp>
|
||||
#include <boost/geometry/algorithms/equals.hpp>
|
||||
#include <boost/geometry/algorithms/expand.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>
|
||||
#include <boost/geometry/algorithms/detail/expand_by_epsilon.hpp>
|
||||
#include <boost/geometry/strategies/cartesian/turn_in_ring_winding.hpp>
|
||||
#include <boost/geometry/geometries/box.hpp>
|
||||
#include <boost/geometry/geometries/segment.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail
|
||||
{
|
||||
template <typename It, typename T, typename Compare>
|
||||
inline bool get_range_around(It begin, It end, T const& value, Compare const& compare, It& lower, It& upper)
|
||||
{
|
||||
lower = end;
|
||||
upper = end;
|
||||
|
||||
// Get first element not smaller than value
|
||||
if (begin == end)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (compare(value, *begin))
|
||||
{
|
||||
// The value is smaller than the first item, therefore not in range
|
||||
return false;
|
||||
}
|
||||
// *(begin + std::distance(begin, end) - 1))
|
||||
if (compare(*(end - 1), value))
|
||||
{
|
||||
// The last item is larger than the value, therefore not in range
|
||||
return false;
|
||||
}
|
||||
|
||||
// Assign the iterators.
|
||||
// lower >= begin and lower < end
|
||||
// upper > lower and upper <= end
|
||||
// lower_bound points to first element NOT LESS than value - but because
|
||||
// we want the first value LESS than value, we decrease it
|
||||
lower = std::lower_bound(begin, end, value, compare);
|
||||
// upper_bound points to first element of which value is LESS
|
||||
upper = std::upper_bound(begin, end, value, compare);
|
||||
|
||||
if (lower != begin)
|
||||
{
|
||||
--lower;
|
||||
}
|
||||
if (upper != end)
|
||||
{
|
||||
++upper;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
//! Contains the border of the piece, consisting of 4 parts:
|
||||
//! 1: the part of the offsetted ring (referenced, not copied)
|
||||
//! 2: the part of the original (one or two points)
|
||||
//! 3: the left part (from original to offsetted)
|
||||
//! 4: the right part (from offsetted to original)
|
||||
//! Besides that, it contains some properties of the piece(border);
|
||||
//! - convexity
|
||||
//! - envelope
|
||||
//! - monotonicity of the offsetted ring
|
||||
//! - min/max radius of a point buffer
|
||||
//! - if it is a "reversed" piece (linear features with partly negative buffers)
|
||||
template <typename Ring, typename Point>
|
||||
struct piece_border
|
||||
{
|
||||
typedef typename geometry::coordinate_type<Point>::type coordinate_type;
|
||||
typedef typename default_comparable_distance_result<Point>::type radius_type;
|
||||
typedef typename geometry::strategy::buffer::turn_in_ring_winding<coordinate_type>::state_type state_type;
|
||||
|
||||
bool m_reversed;
|
||||
|
||||
// Points from the offsetted ring. They are not copied, this structure
|
||||
// refers to those points
|
||||
Ring const* m_ring;
|
||||
std::size_t m_begin;
|
||||
std::size_t m_end;
|
||||
|
||||
// Points from the original (one or two, depending on piece shape)
|
||||
// Note, if there are 2 points, they are REVERSED w.r.t. the original
|
||||
// Therefore here we can walk in its order.
|
||||
std::array<Point, 2> m_originals;
|
||||
std::size_t m_original_size;
|
||||
|
||||
geometry::model::box<Point> m_envelope;
|
||||
bool m_has_envelope;
|
||||
|
||||
// True if piece is determined as "convex"
|
||||
bool m_is_convex;
|
||||
|
||||
// True if offsetted part is monotonically changing in x-direction
|
||||
bool m_is_monotonic_increasing;
|
||||
bool m_is_monotonic_decreasing;
|
||||
|
||||
radius_type m_min_comparable_radius;
|
||||
radius_type m_max_comparable_radius;
|
||||
|
||||
piece_border()
|
||||
: m_reversed(false)
|
||||
, m_ring(NULL)
|
||||
, m_begin(0)
|
||||
, m_end(0)
|
||||
, m_original_size(0)
|
||||
, m_has_envelope(false)
|
||||
, m_is_convex(false)
|
||||
, m_is_monotonic_increasing(false)
|
||||
, m_is_monotonic_decreasing(false)
|
||||
, m_min_comparable_radius(0)
|
||||
, m_max_comparable_radius(0)
|
||||
{
|
||||
}
|
||||
|
||||
// Only used for debugging (SVG)
|
||||
Ring get_full_ring() const
|
||||
{
|
||||
Ring result;
|
||||
if (ring_or_original_empty())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
std::copy(m_ring->begin() + m_begin,
|
||||
m_ring->begin() + m_end,
|
||||
std::back_inserter(result));
|
||||
std::copy(m_originals.begin(),
|
||||
m_originals.begin() + m_original_size,
|
||||
std::back_inserter(result));
|
||||
// Add the closing point
|
||||
result.push_back(*(m_ring->begin() + m_begin));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename Strategy>
|
||||
void get_properties_of_border(bool is_point_buffer, Point const& center,
|
||||
Strategy const& strategy)
|
||||
{
|
||||
m_has_envelope = calculate_envelope(m_envelope, strategy);
|
||||
if (m_has_envelope)
|
||||
{
|
||||
// Take roundings into account, enlarge box
|
||||
geometry::detail::expand_by_epsilon(m_envelope);
|
||||
}
|
||||
if (! ring_or_original_empty() && is_point_buffer)
|
||||
{
|
||||
// Determine min/max radius
|
||||
calculate_radii(center, m_ring->begin() + m_begin, m_ring->begin() + m_end);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Strategy>
|
||||
void get_properties_of_offsetted_ring_part(Strategy const& strategy)
|
||||
{
|
||||
if (! ring_or_original_empty())
|
||||
{
|
||||
m_is_convex = is_convex(strategy);
|
||||
check_monotonicity(m_ring->begin() + m_begin, m_ring->begin() + m_end);
|
||||
}
|
||||
}
|
||||
|
||||
void set_offsetted(Ring const& ring, std::size_t begin, std::size_t end)
|
||||
{
|
||||
BOOST_GEOMETRY_ASSERT(begin <= end);
|
||||
BOOST_GEOMETRY_ASSERT(begin < boost::size(ring));
|
||||
BOOST_GEOMETRY_ASSERT(end <= boost::size(ring));
|
||||
|
||||
m_ring = boost::addressof(ring);
|
||||
m_begin = begin;
|
||||
m_end = end;
|
||||
}
|
||||
|
||||
void add_original_point(Point const& point)
|
||||
{
|
||||
BOOST_GEOMETRY_ASSERT(m_original_size < 2);
|
||||
m_originals[m_original_size++] = point;
|
||||
}
|
||||
|
||||
template <typename Box, typename Strategy>
|
||||
bool calculate_envelope(Box& envelope, Strategy const& strategy) const
|
||||
{
|
||||
geometry::assign_inverse(envelope);
|
||||
if (ring_or_original_empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
expand_envelope(envelope, m_ring->begin() + m_begin, m_ring->begin() + m_end, strategy);
|
||||
expand_envelope(envelope, m_originals.begin(), m_originals.begin() + m_original_size, strategy);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// Whatever the return value, the state should be checked.
|
||||
template <typename TurnPoint, typename State>
|
||||
bool point_on_piece(TurnPoint const& point,
|
||||
bool one_sided, bool is_linear_end_point,
|
||||
State& state) const
|
||||
{
|
||||
if (ring_or_original_empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Walk over the different parts of the ring, in clockwise order
|
||||
// For performance reasons: start with the helper part (one segment)
|
||||
// then the original part (one segment, if any), then the other helper
|
||||
// part (one segment), and only then the offsetted part
|
||||
// (probably more segments, check monotonicity)
|
||||
geometry::strategy::buffer::turn_in_ring_winding<coordinate_type> tir;
|
||||
|
||||
Point const offsetted_front = *(m_ring->begin() + m_begin);
|
||||
Point const offsetted_back = *(m_ring->begin() + m_end - 1);
|
||||
|
||||
// For onesided buffers, or turns colocated with linear end points,
|
||||
// the place on the ring is changed to offsetted (because of colocation)
|
||||
geometry::strategy::buffer::place_on_ring_type const por_original
|
||||
= adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_original,
|
||||
one_sided, is_linear_end_point);
|
||||
geometry::strategy::buffer::place_on_ring_type const por_from_offsetted
|
||||
= adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_from_offsetted,
|
||||
one_sided, is_linear_end_point);
|
||||
geometry::strategy::buffer::place_on_ring_type const por_to_offsetted
|
||||
= adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_to_offsetted,
|
||||
one_sided, is_linear_end_point);
|
||||
|
||||
bool continue_processing = true;
|
||||
if (m_original_size == 1)
|
||||
{
|
||||
// One point. Walk from last offsetted to point, and from point to first offsetted
|
||||
continue_processing = step(point, offsetted_back, m_originals[0],
|
||||
tir, por_from_offsetted, state)
|
||||
&& step(point, m_originals[0], offsetted_front,
|
||||
tir, por_to_offsetted, state);
|
||||
}
|
||||
else if (m_original_size == 2)
|
||||
{
|
||||
// Two original points. Walk from last offsetted point to first original point,
|
||||
// then along original, then from second oginal to first offsetted point
|
||||
continue_processing = step(point, offsetted_back, m_originals[0],
|
||||
tir, por_from_offsetted, state)
|
||||
&& step(point, m_originals[0], m_originals[1],
|
||||
tir, por_original, state)
|
||||
&& step(point, m_originals[1], offsetted_front,
|
||||
tir, por_to_offsetted, state);
|
||||
}
|
||||
|
||||
if (continue_processing)
|
||||
{
|
||||
// Check the offsetted ring (in rounded joins, these might be
|
||||
// several segments)
|
||||
walk_offsetted(point, m_ring->begin() + m_begin, m_ring->begin() + m_end,
|
||||
tir, state);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//! Returns true if empty (no ring, or no points, or no original)
|
||||
bool ring_or_original_empty() const
|
||||
{
|
||||
return m_ring == NULL || m_begin >= m_end || m_original_size == 0;
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
static geometry::strategy::buffer::place_on_ring_type
|
||||
adapted_place_on_ring(geometry::strategy::buffer::place_on_ring_type target,
|
||||
bool one_sided, bool is_linear_end_point)
|
||||
{
|
||||
return one_sided || is_linear_end_point
|
||||
? geometry::strategy::buffer::place_on_ring_offsetted
|
||||
: target;
|
||||
}
|
||||
|
||||
template
|
||||
<
|
||||
typename TurnPoint, typename Iterator,
|
||||
typename TiRStrategy,
|
||||
typename State
|
||||
>
|
||||
bool walk_offsetted(TurnPoint const& point, Iterator begin, Iterator end,
|
||||
TiRStrategy const & strategy,
|
||||
State& state) const
|
||||
{
|
||||
Iterator it = begin;
|
||||
Iterator beyond = end;
|
||||
|
||||
// Move iterators if the offsetted ring is monotonic increasing or decreasing
|
||||
if (m_is_monotonic_increasing)
|
||||
{
|
||||
if (! get_range_around(begin, end, point, geometry::less<Point, 0>(), it, beyond))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else if (m_is_monotonic_decreasing)
|
||||
{
|
||||
if (! get_range_around(begin, end, point, geometry::greater<Point, 0>(), it, beyond))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
for (Iterator previous = it++ ; it != beyond ; ++previous, ++it )
|
||||
{
|
||||
if (! step(point, *previous, *it, strategy,
|
||||
geometry::strategy::buffer::place_on_ring_offsetted, state))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename TurnPoint, typename TiRStrategy, typename State>
|
||||
bool step(TurnPoint const& point, Point const& p1, Point const& p2,
|
||||
TiRStrategy const& strategy,
|
||||
geometry::strategy::buffer::place_on_ring_type place_on_ring, State& state) const
|
||||
{
|
||||
return strategy.apply(point, p1, p2, place_on_ring, m_is_convex, state);
|
||||
}
|
||||
|
||||
template <typename It, typename Box, typename Strategy>
|
||||
void expand_envelope(Box& envelope, It begin, It end, Strategy const& strategy) const
|
||||
{
|
||||
for (It it = begin; it != end; ++it)
|
||||
{
|
||||
geometry::expand(envelope, *it, strategy);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Strategy>
|
||||
bool is_convex(Strategy const& strategy) const
|
||||
{
|
||||
if (ring_or_original_empty())
|
||||
{
|
||||
// Convexity is undetermined, and for this case it does not matter,
|
||||
// because it is only used for optimization in point_on_piece,
|
||||
// but that is not called if the piece border is not valid
|
||||
return false;
|
||||
}
|
||||
|
||||
if (m_end - m_begin <= 2)
|
||||
{
|
||||
// The offsetted ring part of this piece has only two points.
|
||||
// If this is true, and the original ring part has only one point,
|
||||
// a triangle and it is convex. If the original ring part has two
|
||||
// points, it is a rectangle and theoretically could be concave,
|
||||
// but because of the way the buffer is generated, that is never
|
||||
// the case.
|
||||
return true;
|
||||
}
|
||||
|
||||
// The offsetted ring part of thie piece has at least three points
|
||||
// (this is often the case in a piece marked as "join")
|
||||
|
||||
// We can assume all points of the offset ring are different, and also
|
||||
// that all points on the original are different, and that the offsetted
|
||||
// ring is different from the original(s)
|
||||
Point const offsetted_front = *(m_ring->begin() + m_begin);
|
||||
Point const offsetted_second = *(m_ring->begin() + m_begin + 1);
|
||||
|
||||
// These two points will be reassigned in every is_convex call
|
||||
Point previous = offsetted_front;
|
||||
Point current = offsetted_second;
|
||||
|
||||
// Verify the offsetted range (from the second point on), the original,
|
||||
// and loop through the first two points of the offsetted range
|
||||
bool const result = is_convex(previous, current, m_ring->begin() + m_begin + 2, m_ring->begin() + m_end, strategy)
|
||||
&& is_convex(previous, current, m_originals.begin(), m_originals.begin() + m_original_size, strategy)
|
||||
&& is_convex(previous, current, offsetted_front, strategy)
|
||||
&& is_convex(previous, current, offsetted_second, strategy);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename It, typename Strategy>
|
||||
bool is_convex(Point& previous, Point& current, It begin, It end, Strategy const& strategy) const
|
||||
{
|
||||
for (It it = begin; it != end; ++it)
|
||||
{
|
||||
if (! is_convex(previous, current, *it, strategy))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename Strategy>
|
||||
bool is_convex(Point& previous, Point& current, Point const& next, Strategy const& strategy) const
|
||||
{
|
||||
int const side = strategy.side().apply(previous, current, next);
|
||||
if (side == 1)
|
||||
{
|
||||
// Next is on the left side of clockwise ring: piece is not convex
|
||||
return false;
|
||||
}
|
||||
if (! equals::equals_point_point(current, next, strategy))
|
||||
{
|
||||
previous = current;
|
||||
current = next;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <int Direction>
|
||||
inline void step_for_monotonicity(Point const& current, Point const& next)
|
||||
{
|
||||
if (geometry::get<Direction>(current) >= geometry::get<Direction>(next))
|
||||
{
|
||||
m_is_monotonic_increasing = false;
|
||||
}
|
||||
if (geometry::get<Direction>(current) <= geometry::get<Direction>(next))
|
||||
{
|
||||
m_is_monotonic_decreasing = false;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename It>
|
||||
void check_monotonicity(It begin, It end)
|
||||
{
|
||||
m_is_monotonic_increasing = true;
|
||||
m_is_monotonic_decreasing = true;
|
||||
|
||||
if (begin == end || begin + 1 == end)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
It it = begin;
|
||||
for (It previous = it++; it != end; ++previous, ++it)
|
||||
{
|
||||
step_for_monotonicity<0>(*previous, *it);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename It>
|
||||
inline void calculate_radii(Point const& center, It begin, It end)
|
||||
{
|
||||
typedef geometry::model::referring_segment<Point const> segment_type;
|
||||
|
||||
bool first = true;
|
||||
|
||||
// An offsetted point-buffer ring around a point is supposed to be closed,
|
||||
// therefore walking from start to end is fine.
|
||||
It it = begin;
|
||||
for (It previous = it++; it != end; ++previous, ++it)
|
||||
{
|
||||
Point const& p0 = *previous;
|
||||
Point const& p1 = *it;
|
||||
segment_type const s(p0, p1);
|
||||
radius_type const d = geometry::comparable_distance(center, s);
|
||||
|
||||
if (first || d < m_min_comparable_radius)
|
||||
{
|
||||
m_min_comparable_radius = d;
|
||||
}
|
||||
if (first || d > m_max_comparable_radius)
|
||||
{
|
||||
m_max_comparable_radius = d;
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_PIECE_BORDER_HPP
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2014 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
|
||||
// This file was modified by Oracle on 2016-2023.
|
||||
// Modifications copyright (c) 2016-2023 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_ORIGINAL_VISITOR
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_ORIGINAL_VISITOR
|
||||
|
||||
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
#include <boost/range/size.hpp>
|
||||
|
||||
#include <boost/geometry/core/coordinate_type.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>
|
||||
#include <boost/geometry/algorithms/detail/disjoint/interface.hpp>
|
||||
#include <boost/geometry/algorithms/expand.hpp>
|
||||
#include <boost/geometry/strategies/agnostic/point_in_poly_winding.hpp>
|
||||
#include <boost/geometry/strategies/buffer.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
|
||||
template <typename Strategy>
|
||||
struct original_get_box
|
||||
{
|
||||
explicit original_get_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Original>
|
||||
inline void apply(Box& total, Original const& original) const
|
||||
{
|
||||
assert_coordinate_type_equal(total, original.m_box);
|
||||
geometry::expand(total, original.m_box, m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct original_overlaps_box
|
||||
{
|
||||
explicit original_overlaps_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Original>
|
||||
inline bool apply(Box const& box, Original const& original) const
|
||||
{
|
||||
assert_coordinate_type_equal(box, original.m_box);
|
||||
return ! detail::disjoint::disjoint_box_box(box, original.m_box,
|
||||
m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
struct include_turn_policy
|
||||
{
|
||||
template <typename Turn>
|
||||
static inline bool apply(Turn const& turn)
|
||||
{
|
||||
return turn.is_turn_traversable;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Strategy>
|
||||
struct turn_in_original_overlaps_box
|
||||
{
|
||||
explicit turn_in_original_overlaps_box(Strategy const& strategy)
|
||||
: m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Box, typename Turn>
|
||||
inline bool apply(Box const& box, Turn const& turn) const
|
||||
{
|
||||
if (! turn.is_turn_traversable || turn.within_original)
|
||||
{
|
||||
// Skip all points already processed
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! geometry::detail::disjoint::disjoint_point_box(
|
||||
turn.point, box, m_strategy);
|
||||
}
|
||||
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
//! Check if specified is in range of specified iterators
|
||||
//! Return value of strategy (true if we can bail out)
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
typename State,
|
||||
typename Point,
|
||||
typename Iterator
|
||||
>
|
||||
inline bool point_in_range(Strategy& strategy, State& state,
|
||||
Point const& point, Iterator begin, Iterator end)
|
||||
{
|
||||
boost::ignore_unused(strategy);
|
||||
|
||||
Iterator it = begin;
|
||||
for (Iterator previous = it++; it != end; ++previous, ++it)
|
||||
{
|
||||
if (! strategy.apply(point, *previous, *it, state))
|
||||
{
|
||||
// We're probably on the boundary
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template
|
||||
<
|
||||
typename Strategy,
|
||||
typename State,
|
||||
typename Point,
|
||||
typename CoordinateType,
|
||||
typename Iterator
|
||||
>
|
||||
inline bool point_in_section(Strategy& strategy, State& state,
|
||||
Point const& point, CoordinateType const& point_x,
|
||||
Iterator begin, Iterator end,
|
||||
int direction)
|
||||
{
|
||||
if (direction == 0)
|
||||
{
|
||||
// Not a monotonic section, or no change in X-direction
|
||||
return point_in_range(strategy, state, point, begin, end);
|
||||
}
|
||||
|
||||
// We're in a monotonic section in x-direction
|
||||
Iterator it = begin;
|
||||
|
||||
for (Iterator previous = it++; it != end; ++previous, ++it)
|
||||
{
|
||||
// Depending on sections.direction we can quit for this section
|
||||
CoordinateType const previous_x = geometry::get<0>(*previous);
|
||||
|
||||
if (direction == 1 && point_x < previous_x)
|
||||
{
|
||||
// Section goes upwards, x increases, point is is below section
|
||||
return true;
|
||||
}
|
||||
else if (direction == -1 && point_x > previous_x)
|
||||
{
|
||||
// Section goes downwards, x decreases, point is above section
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! strategy.apply(point, *previous, *it, state))
|
||||
{
|
||||
// We're probably on the boundary
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
template <typename Point, typename Original, typename PointInGeometryStrategy>
|
||||
inline int point_in_original(Point const& point, Original const& original,
|
||||
PointInGeometryStrategy const& strategy)
|
||||
{
|
||||
typename PointInGeometryStrategy::state_type state;
|
||||
|
||||
if (boost::size(original.m_sections) == 0
|
||||
|| boost::size(original.m_ring) - boost::size(original.m_sections) < 16)
|
||||
{
|
||||
// There are no sections, or it does not profit to walk over sections
|
||||
// instead of over points. Boundary of 16 is arbitrary but can influence
|
||||
// performance
|
||||
point_in_range(strategy, state, point,
|
||||
original.m_ring.begin(), original.m_ring.end());
|
||||
return strategy.result(state);
|
||||
}
|
||||
|
||||
auto const point_x = geometry::get<0>(point);
|
||||
|
||||
// Walk through all monotonic sections of this original
|
||||
for (auto const& section : original.m_sections)
|
||||
{
|
||||
if (! section.duplicate
|
||||
&& section.begin_index < section.end_index
|
||||
&& point_x >= geometry::get<min_corner, 0>(section.bounding_box)
|
||||
&& point_x <= geometry::get<max_corner, 0>(section.bounding_box))
|
||||
{
|
||||
// x-coordinate of point overlaps with section
|
||||
if (! point_in_section(strategy, state, point, point_x,
|
||||
boost::begin(original.m_ring) + section.begin_index,
|
||||
boost::begin(original.m_ring) + section.end_index + 1,
|
||||
section.directions[0]))
|
||||
{
|
||||
// We're probably on the boundary
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return strategy.result(state);
|
||||
}
|
||||
|
||||
|
||||
template <typename Turns, typename Strategy>
|
||||
class turn_in_original_visitor
|
||||
{
|
||||
public:
|
||||
turn_in_original_visitor(Turns& turns, Strategy const& strategy)
|
||||
: m_mutable_turns(turns)
|
||||
, m_strategy(strategy)
|
||||
{}
|
||||
|
||||
template <typename Turn, typename Original>
|
||||
inline bool apply(Turn const& turn, Original const& original)
|
||||
{
|
||||
if (boost::empty(original.m_ring))
|
||||
{
|
||||
// Skip empty rings
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! turn.is_turn_traversable || turn.within_original)
|
||||
{
|
||||
// Skip all points already processed
|
||||
return true;
|
||||
}
|
||||
|
||||
if (geometry::disjoint(turn.point, original.m_box, m_strategy))
|
||||
{
|
||||
// Skip all disjoint
|
||||
return true;
|
||||
}
|
||||
|
||||
int const code = point_in_original(turn.point, original,
|
||||
m_strategy.relate(turn.point, original.m_ring));
|
||||
|
||||
if (code == -1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Turn& mutable_turn = m_mutable_turns[turn.turn_index];
|
||||
|
||||
if (code == 0)
|
||||
{
|
||||
// On border of original: always discard
|
||||
mutable_turn.is_turn_traversable = false;
|
||||
}
|
||||
|
||||
// Point is inside an original ring
|
||||
if (original.m_is_interior)
|
||||
{
|
||||
mutable_turn.count_in_original--;
|
||||
}
|
||||
else if (original.m_has_interiors)
|
||||
{
|
||||
mutable_turn.count_in_original++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// It is an exterior ring and there are no interior rings.
|
||||
// Then we are completely ready with this turn
|
||||
mutable_turn.within_original = true;
|
||||
mutable_turn.count_in_original = 1;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private :
|
||||
Turns& m_mutable_turns;
|
||||
Strategy const& m_strategy;
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_ORIGINAL_VISITOR
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
// Boost.Geometry (aka GGL, Generic Geometry Library)
|
||||
|
||||
// Copyright (c) 2012-2020 Barend Gehrels, Amsterdam, the Netherlands.
|
||||
// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.
|
||||
|
||||
// This file was modified by Oracle on 2016-2022.
|
||||
// Modifications copyright (c) 2016-2022 Oracle and/or its affiliates.
|
||||
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
|
||||
|
||||
// Use, modification and distribution is subject to the Boost Software License,
|
||||
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
|
||||
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR_HPP
|
||||
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR_HPP
|
||||
|
||||
#include <boost/geometry/core/assert.hpp>
|
||||
#include <boost/geometry/core/config.hpp>
|
||||
|
||||
#include <boost/geometry/algorithms/comparable_distance.hpp>
|
||||
#include <boost/geometry/algorithms/covered_by.hpp>
|
||||
#include <boost/geometry/algorithms/detail/disjoint/point_box.hpp>
|
||||
#include <boost/geometry/algorithms/detail/disjoint/box_box.hpp>
|
||||
#include <boost/geometry/algorithms/detail/dummy_geometries.hpp>
|
||||
#include <boost/geometry/algorithms/detail/buffer/buffer_policies.hpp>
|
||||
#include <boost/geometry/geometries/box.hpp>
|
||||
|
||||
|
||||
namespace boost { namespace geometry
|
||||
{
|
||||
|
||||
#ifndef DOXYGEN_NO_DETAIL
|
||||
|
||||
namespace detail { namespace buffer
|
||||
{
|
||||
|
||||
template
|
||||
<
|
||||
typename CsTag,
|
||||
typename Turns,
|
||||
typename Pieces,
|
||||
typename DistanceStrategy,
|
||||
typename UmbrellaStrategy
|
||||
|
||||
>
|
||||
class turn_in_piece_visitor
|
||||
{
|
||||
Turns& m_turns; // because partition is currently operating on const input only
|
||||
Pieces const& m_pieces; // to check for piece-type
|
||||
DistanceStrategy const& m_distance_strategy; // to check if point is on original or one_sided
|
||||
UmbrellaStrategy const& m_umbrella_strategy;
|
||||
|
||||
template <typename Operation, typename Piece>
|
||||
inline bool skip(Operation const& op, Piece const& piece) const
|
||||
{
|
||||
if (op.piece_index == piece.index)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
Piece const& pc = m_pieces[op.piece_index];
|
||||
if (pc.left_index == piece.index || pc.right_index == piece.index)
|
||||
{
|
||||
if (pc.type == strategy::buffer::buffered_flat_end)
|
||||
{
|
||||
// If it is a flat end, don't compare against its neighbor:
|
||||
// it will always be located on one of the helper segments
|
||||
return true;
|
||||
}
|
||||
if (pc.type == strategy::buffer::buffered_concave)
|
||||
{
|
||||
// If it is concave, the same applies: the IP will be
|
||||
// located on one of the helper segments
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename NumericType>
|
||||
inline bool is_one_sided(NumericType const& left, NumericType const& right) const
|
||||
{
|
||||
static NumericType const zero = 0;
|
||||
return geometry::math::equals(left, zero)
|
||||
|| geometry::math::equals(right, zero);
|
||||
}
|
||||
|
||||
template <typename Point>
|
||||
inline bool has_zero_distance_at(Point const& point) const
|
||||
{
|
||||
return is_one_sided(m_distance_strategy.apply(point, point,
|
||||
strategy::buffer::buffer_side_left),
|
||||
m_distance_strategy.apply(point, point,
|
||||
strategy::buffer::buffer_side_right));
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
inline turn_in_piece_visitor(Turns& turns, Pieces const& pieces,
|
||||
DistanceStrategy const& distance_strategy,
|
||||
UmbrellaStrategy const& umbrella_strategy)
|
||||
: m_turns(turns)
|
||||
, m_pieces(pieces)
|
||||
, m_distance_strategy(distance_strategy)
|
||||
, m_umbrella_strategy(umbrella_strategy)
|
||||
{}
|
||||
|
||||
template <typename Turn, typename Piece>
|
||||
inline bool apply(Turn const& turn, Piece const& piece)
|
||||
{
|
||||
if (! turn.is_turn_traversable)
|
||||
{
|
||||
// Already handled
|
||||
return true;
|
||||
}
|
||||
|
||||
if (piece.type == strategy::buffer::buffered_flat_end
|
||||
|| piece.type == strategy::buffer::buffered_concave)
|
||||
{
|
||||
// Turns cannot be located within flat-end or concave pieces
|
||||
return true;
|
||||
}
|
||||
|
||||
if (skip(turn.operations[0], piece) || skip(turn.operations[1], piece))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return apply(turn, piece, piece.m_piece_border);
|
||||
}
|
||||
|
||||
template <typename Turn, typename Piece, typename Border>
|
||||
inline bool apply(Turn const& turn, Piece const& piece, Border const& border)
|
||||
{
|
||||
if (! geometry::covered_by(turn.point, border.m_envelope, m_umbrella_strategy))
|
||||
{
|
||||
// Easy check: if turn is not in the (expanded) envelope
|
||||
return true;
|
||||
}
|
||||
|
||||
if (piece.type == geometry::strategy::buffer::buffered_empty_side)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (piece.type == geometry::strategy::buffer::buffered_point)
|
||||
{
|
||||
// Optimization for a buffer around points: if distance from center
|
||||
// is not between min/max radius, it is either inside or outside,
|
||||
// and more expensive checks are not necessary.
|
||||
auto const d = geometry::comparable_distance(piece.m_center, turn.point,
|
||||
m_umbrella_strategy);
|
||||
|
||||
if (d < border.m_min_comparable_radius)
|
||||
{
|
||||
Turn& mutable_turn = m_turns[turn.turn_index];
|
||||
mutable_turn.is_turn_traversable = false;
|
||||
return true;
|
||||
}
|
||||
if (d > border.m_max_comparable_radius)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if buffer is one-sided (at this point), because then a point
|
||||
// on the original border is not considered as within.
|
||||
bool const one_sided = has_zero_distance_at(turn.point);
|
||||
|
||||
typename Border::state_type state;
|
||||
if (! border.point_on_piece(turn.point, one_sided,
|
||||
turn.is_linear_end_point, state))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (state.is_inside() && ! state.is_on_boundary())
|
||||
{
|
||||
Turn& mutable_turn = m_turns[turn.turn_index];
|
||||
mutable_turn.is_turn_traversable = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
}} // namespace detail::buffer
|
||||
#endif // DOXYGEN_NO_DETAIL
|
||||
|
||||
|
||||
}} // namespace boost::geometry
|
||||
|
||||
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR_HPP
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user