diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ae65e41 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,27 @@ +name: PacketForge checks +on: + push: + pull_request: +permissions: + contents: read +jobs: + build-and-test: + runs-on: ubuntu-latest + strategy: + matrix: + sanitizers: ["OFF", "ON"] + steps: + - uses: actions/checkout@v4 + - name: Install build dependencies + run: sudo apt-get update && sudo apt-get install -y build-essential cmake libpcap-dev python3 + - name: Configure + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DPACKETFORGE_SANITIZERS=${{ matrix.sanitizers }} + - name: Build + run: cmake --build build -j2 + - name: Test + env: + ASAN_OPTIONS: detect_leaks=1 + UBSAN_OPTIONS: halt_on_error=1 + run: ctest --test-dir build --output-on-failure + - name: Confirm deterministic fixtures + run: python3 scripts/generate_fixtures.py && git diff --exit-code -- samples/ diff --git a/.gitignore b/.gitignore index 2123540..764dee9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ +/build*/ +/reports/ *.o *.out -sniffer +/sniffer +/forwarder +/packetforge +__pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..14b80d2 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.16) +project(PacketForge LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +option(PACKETFORGE_SANITIZERS "Enable AddressSanitizer and UndefinedBehaviorSanitizer" OFF) +if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "PacketForge currently targets Linux, including WSL2") +endif() +find_path(PCAP_INCLUDE_DIR pcap/pcap.h REQUIRED) +find_library(PCAP_LIBRARY pcap REQUIRED) +add_library(packetforge_core src/parsers/packet.cpp src/capture/pcap.cpp src/capture/live.cpp + src/detection/config.cpp src/detection/detection.cpp src/flows/flows.cpp + src/statistics/statistics.cpp src/statistics/analysis.cpp src/reporting/reporting.cpp src/cli.cpp) +target_include_directories(packetforge_core PUBLIC include) +target_include_directories(packetforge_core SYSTEM PUBLIC third_party ${PCAP_INCLUDE_DIR}) +target_link_libraries(packetforge_core PUBLIC ${PCAP_LIBRARY}) +target_compile_options(packetforge_core PUBLIC -Wall -Wextra -Wpedantic -Wconversion -Wshadow) +if(PACKETFORGE_SANITIZERS) + target_compile_options(packetforge_core PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(packetforge_core PUBLIC -fsanitize=address,undefined) +endif() +add_executable(packetforge src/main.cpp) +target_link_libraries(packetforge PRIVATE packetforge_core) +add_executable(sniffer src/sniffer.cpp) +target_link_libraries(sniffer PRIVATE packetforge_core) +add_executable(forwarder src/forwarder.cpp) +target_link_libraries(forwarder PRIVATE packetforge_core) +include(CTest) +if(BUILD_TESTING) + add_executable(packetforge_tests tests/unit.cpp) + target_link_libraries(packetforge_tests PRIVATE packetforge_core) + add_test(NAME unit COMMAND packetforge_tests) + add_test(NAME interfaces COMMAND packetforge interfaces) + set_tests_properties(interfaces PROPERTIES LABELS "host") + find_package(Python3 COMPONENTS Interpreter REQUIRED) + add_test(NAME integration COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/integration.py $ ${CMAKE_SOURCE_DIR}) +endif() +install(TARGETS packetforge RUNTIME DESTINATION bin) +install(FILES config/rules.json DESTINATION share/packetforge) diff --git a/PROGRESS.md b/PROGRESS.md new file mode 100644 index 0000000..106ceba --- /dev/null +++ b/PROGRESS.md @@ -0,0 +1,53 @@ +# PacketForge implementation progress + +Author: Mayank Kumar Karn. Implemented and locally verified on 2026-10-21. +Baseline GitHub commit: `8fd6286`. Feature branch: `feature/packetforge-analyzer-ids`. + +## Completed + +- [x] Inspect every original file and Git history; compile both original programs. +- [x] Preserve the original GitHub history and leave the unrelated local copy untouched. +- [x] Record original issues and corrections in docs/AUDIT.md. +- [x] C++17 bounded Ethernet/VLAN/ARP/IPv4/IPv6/TCP/UDP/ICMP parser. +- [x] Shared live AF_PACKET and offline libpcap pipeline, CLI and compatibility wrappers. +- [x] Classic PCAP, stored timestamps, explicit unsupported formats and safe errors. +- [x] Bounded directional flows, idle expiry, statistics and visible capacity counters. +- [x] Five configurable IDS rules, windows, exclusions, cooldowns and structured evidence. +- [x] Accurate Firewall Policy Simulation with WOULD_ALLOW / WOULD_BLOCK. +- [x] JSON, alerts/flows CSV and standalone escaped HTML reports. +- [x] Deterministic synthetic fixtures and documented expected results. +- [x] Clean Release CMake build with GCC 15.2.0; no compiler warnings observed. +- [x] All 3 CTest targets passed on host; 10,153 unit assertions include 10,000 random parser inputs. +- [x] 68 CLI/fixture subprocess checks plus JSON/CSV/HTML/config assertions passed without root. +- [x] ASan/UBSan clean build and offline tests passed; exact leak-check limitation below. +- [x] Real live capture verified in isolated WSL2 user/network namespace: UDP frames, + count and idle-duration limits, Ctrl+C, Ethernet binding and explicit promiscuous membership. +- [x] HTML opened in Chromium and screenshot visually inspected. +- [x] Architecture, protocols, rules, testing and interview documentation. +- [x] Interview preparation: 60-second intro, 3-minute explanation, 5-minute demo, + 20 technical questions and implementation challenges. +- [x] Automated GitHub Actions standard/sanitizer workflow added. + +## Explicit limits + +- LeakSanitizer cannot run under the restricted runner's ptrace; local sanitizer + evidence uses `detect_leaks=0`. AddressSanitizer and UBSan passed. This is not a + claim that leak checking passed. +- Live capture was tested with real kernel frames on private loopback and a private + veth interface, not every physical NIC or Windows-side WSL traffic path. +- No PCAPNG, stream/fragment reassembly, DNS parsing, checksum validation, payload + inspection, firewall enforcement or production throughput guarantee. +- Bounded state may miss evidence; reports disclose dropped/evicted/omitted counts. +- Remote CI status and push evidence are recorded at delivery; a workflow file alone + is not a claim that GitHub Actions ran successfully. + +## Evidence and commits + +Raw build/test/sanitizer output and a real report screenshot are in `docs/evidence/`. +Working offline reports are generated under ignored `reports/`. Run `scripts/demo.sh` +for a fresh, repeatable demonstration. `docs/TESTING.md` explains each check. + +- `42fd73c`: initial audit. +- `fe625f4`: bounded parser and live/offline capture pipeline. +- `7af198a`: IDS, flows, statistics, reports and expanded tests. +- Final documentation/validation commit follows these stages; see Git history. diff --git a/README.md b/README.md index 4cc12cd..ce7f8c2 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,189 @@ -# PacketForge — Linux Network Packet Analyzer & L3 Forwarding Engine - -A raw-socket packet analyzer built in C++ that captures live network traffic, parses -Ethernet, IPv4, TCP, UDP, and ARP headers, and includes a rule-based L3 forwarding -engine that filters packets by IP/port — simulating basic firewall/router logic. - -## Features -- Raw socket packet capture (AF_PACKET, SOCK_RAW) -- Ethernet header parsing (src/dst MAC, EtherType) -- IPv4 header parsing (src/dst IP, protocol, TTL) -- TCP/UDP header parsing (src/dst ports) -- ARP and ICMP detection -- Rule-based L3 forwarding engine (ALLOW/DROP decisions by IP/port) -- Live packet statistics (total, allowed, dropped) - -## Project Structure -PacketForge/ -- src/sniffer.cpp -> packet capture + header parsing -- src/forwarder.cpp -> sniffer + rule-based forwarding engine -- include/headers.hpp -> Ethernet/IP/TCP/UDP struct definitions -- include/rules.hpp -> rule table + Action enum - -## Build - -Sniffer only: -g++ src/sniffer.cpp -o sniffer - -Forwarding engine: -g++ src/forwarder.cpp -o forwarder - -## Run -Requires root (raw sockets need CAP_NET_RAW): - -sudo ./sniffer -sudo ./forwarder - -## Example Output — Sniffer ---- Packet (98 bytes) --- -Src MAC: 00:15:5d:6e:42:c7 -Dst MAC: 00:15:5d:6e:47:2f -EtherType: 0x0800 -Src IP: 192.168.1.10 -Dst IP: 142.250.193.14 -Protocol: 6 (TCP) -Src Port: 52341 -Dst Port: 443 - -## Forwarding Engine -forwarder.cpp inspects each packet's source/destination IP and port, checks it -against a configurable rule table, and decides ALLOW or DROP. - -Rule table example: -- any -> any : port 22 -> DROP (block SSH) -- any -> any : port 445 -> DROP (block SMB) -- any -> any : default -> ALLOW - -Example output: -Src: 127.0.0.1 -> Dst: 127.0.0.1:22 | Protocol: 6 | Decision: DROP -Src: 172.31.13.131 -> Dst: 192.178.134.138:80 | Protocol: 6 | Decision: ALLOW - -[Stats] Total: 20 | Allowed: 18 | Dropped: 2 - -## Roadmap (V3) -- IPv6 support -- Multithreaded packet capture -- Real packet retransmission (actual forwarding, not just decision logging) -- DHCP/ARP-based dynamic rule updates - -## Tech Stack -C++, POSIX raw sockets, Linux networking stack - -## Author -Mayank Kumar Karn +# PacketForge + +**A passive C++ network packet analyzer and lightweight, explainable intrusion detection system.** + +Author: **Mayank Kumar Karn** · C++17 · Linux / Kali / Ubuntu · CMake + +PacketForge captures frames with Linux `AF_PACKET`, reads standard Ethernet PCAP +files with libpcap, decodes protocol metadata safely, tracks directional flows, +and reports suspicious activity using configurable rules. The complete offline +demonstration runs without root or internet access. + +This project grew from the original PacketForge raw-socket sniffer and first-match +policy demonstration. The original Git history is preserved; the engineering review +is in [docs/AUDIT.md](docs/AUDIT.md). It is an educational investigation tool, not a +replacement for Wireshark, tcpdump, Snort or Suricata. + +## Implemented features + +- Bounded Ethernet II, up to two 802.1Q/802.1ad VLAN tags, Ethernet/IPv4 ARP, + IPv4 including options, IPv6 with common extension headers, TCP, UDP, ICMP and + basic ICMPv6 metadata decoding. +- Explicit `ok`, `truncated`, `malformed` and `unsupported` parser results. + Non-initial IP fragments never supply transport ports. No network-buffer struct casts. +- Live interface selection, count/duration limits, Ctrl+C/SIGTERM shutdown, + socket-scoped opt-in promiscuous mode, kernel capture timestamps and drop counters. +- Classic PCAP with microsecond/nanosecond timestamps and either byte order. + PCAPNG, non-Ethernet link types and nonchronological captures are explicitly rejected. +- Bounded directional TCP/UDP five-tuples, packet/byte counts, timestamps, TCP flags, + duration, idle expiry, capacity eviction and visible retention counters. +- Five configurable metadata rules: possible TCP SYN port scans, high SYN rate, + high ICMP echo rate, sensitive service observations and connection concentration. +- Sliding windows, exact-IP exclusions, per-rule severity, thresholds, cooldowns, + deduplication, rule counters and bounded detector state. +- Protocol counts, rates, top talkers/ports, unique and active flows, alert totals. +- Consistent alert evidence, timestamps, limitations, investigation recommendations + and the justified T1046 reference for possible service discovery. +- JSON, alerts/flows CSV, and standalone HTML investigation reports. All generated + reports contain metadata, never packet payloads. HTML is escaped; CSV neutralizes + spreadsheet formulas; existing output files are not overwritten. +- **Firewall Policy Simulation** prints `WOULD_ALLOW` / `WOULD_BLOCK` using the + original first-match concept. It does **not** drop, forward or modify traffic. + +## Build on Kali / Ubuntu + +```bash +sudo apt update +sudo apt install build-essential cmake libpcap-dev python3 libcap2-bin iproute2 +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j2 +ctest --test-dir build --output-on-failure +``` + +Python is only used by development tests and fixture generation. Runtime dependencies +are the C++ runtime and libpcap. The MIT-licensed nlohmann JSON header is vendored and +pinned, so CMake never downloads dependencies. To build without development tests, +add `-DBUILD_TESTING=OFF`. + +## Five-minute offline demonstration + +```bash +./build/packetforge --help +./build/packetforge analyze --pcap samples/demo.pcap +./build/packetforge analyze --pcap samples/portscan.pcap --ids +./build/packetforge analyze --pcap samples/synrate.pcap +./build/packetforge analyze --pcap samples/malformed.pcap --verbose +./build/packetforge analyze --pcap samples/sensitive.pcap --policy +./build/packetforge analyze --pcap samples/mixed.pcap \ + --rules config/rules.json --report all --output reports/interview +``` + +Open `reports/interview.html` in a local browser. The same prefix creates +`interview.json`, `interview-alerts.csv` and `interview-flows.csv`. +Choose a new prefix for a repeat run. Without `--output`, the filename contains a +unique export timestamp. `scripts/demo.sh` creates a new demonstration directory. + +Actual default-fixture alert examples: + +```text +[MEDIUM] POSSIBLE_TCP_PORT_SCAN | 2023-11-14T22:13:20.550000000Z | 192.0.2.10 -> 198.51.100.20 | observed=12 threshold=12 window=10s +[MEDIUM] HIGH_TCP_SYN_RATE | 2023-11-14T22:13:24.950000000Z | 192.0.2.10 -> 198.51.100.20 | observed=100 threshold=100 window=10s +``` + +The normal mixed fixture contains 9 packets and raises no default alerts. The SYN +rate fixture intentionally repeats an attempt to distinguish packet rate from +unique connection attempts. These are deterministic synthetic captures using +reserved documentation addresses, with no third-party traffic or credentials. +See [samples/README.md](samples/README.md) for every expected outcome. + +## Report preview + +![PacketForge standalone investigation report](docs/evidence/report-preview.png) + +The preview is rendered from the synthetic mixed-protocol report. No external +fonts, scripts, images, services or internet connection are needed by the HTML. + +## Live capture + +Only inspect an interface or capture file you are authorized to monitor. + +```bash +./build/packetforge interfaces +sudo ./build/packetforge capture --interface eth0 --count 100 +sudo ./build/packetforge capture --interface eth0 --duration 30 --report html +``` + +An alternative to running the application as root on a Linux filesystem is: + +```bash +sudo setcap cap_net_raw=ep ./build/packetforge +./build/packetforge capture --interface eth0 --count 100 +# Remove the capability when it is no longer needed: +sudo setcap -r ./build/packetforge +``` + +Do not grant capabilities to a binary that untrusted users can replace. Prefer a +Linux home-directory checkout when using file capabilities; Windows-mounted WSL +filesystems may not support them. Rebuilding/replacing a binary can remove its +capabilities. Native Linux or a Linux VM is recommended for predictable NIC +visibility. WSL2 can capture interfaces in its Linux environment, but this does not +mean it sees every Windows interface or all LAN traffic. Wi-Fi monitor mode is not +implemented. Loopback may expose both outgoing and incoming copies. + +No promiscuous mode is requested unless `--promiscuous` is supplied. Capture is +passive: there is no packet injection, retransmission, firewall modification, +NFQUEUE, credential interception, persistence or stealth functionality. + +## CLI reference + +| Command / flag | Behavior | +| --- | --- | +| `interfaces` | Enumerate Linux interface indices and names | +| `capture --interface NAME` | Start passive AF_PACKET capture | +| `analyze --pcap FILE` | Read chronological classic Ethernet PCAP | +| `--count N` | Stop after N packets; positive integer | +| `--duration SECONDS` | Live-only elapsed-time limit; fractions allowed, maximum 86400 | +| `--ids`, `--no-ids` | IDS is enabled by default; explicitly enable or disable | +| `--rules FILE` | Load validated JSON overrides; built-in defaults otherwise | +| `--policy` | Print Firewall Policy Simulation decisions | +| `--verbose` | Print metadata for each packet; no payloads | +| `--quiet` | Suppress immediate alerts and periodic status; keep summary/reports | +| `--report json\|csv\|html\|all` | Export investigation artifacts | +| `--output PREFIX` | Output path prefix, requires `--report`; refuse existing files | +| `--promiscuous` | Live-only socket membership, released when socket closes | +| `--help` | Full command help | + +Exit code 0 means successful analysis or graceful live stop, including suspicious +traffic. Exit code 2 means invalid arguments/configuration or a capture/report error. +Malformed individual packets are counted and analysis continues. Corrupt PCAP +containers cause an error. The application does not silently sort huge captures: +nonchronological files must be sorted externally before use. + +The historical `sniffer` and `forwarder` CMake targets remain as compatibility +entry points: `./build/sniffer --interface eth0` and +`./build/forwarder --interface eth0`. The latter enables **simulation**. The old +single-file `g++ src/sniffer.cpp` command is superseded by CMake. + +## Rules and limitations + +[config/rules.json](config/rules.json) contains demonstration defaults, not universal +attack thresholds. Alerts trigger at **count >= threshold** within `(now-window, now]`. +A port-scan threshold cannot be set below two distinct ports. A sensitive service +observation is informational, and a SYN-rate alert does not confirm denial of service. +Tune using an authorized traffic baseline; see [DETECTION_RULES.md](docs/DETECTION_RULES.md). + +There is no TCP stream reconstruction, IP fragment reassembly, DNS query parser, +DNS tunneling detector, payload inspection, decryption, checksum validation or +production throughput claim. DNS traffic is represented as UDP metadata only. +Bounded tables can omit evidence; reports expose dropped rule events/keys, +flow evictions, omitted talker observations and unretained alerts. Unique flow +counts become a labeled lower bound when their identity budget is exhausted. + +Protocol counters overlap layers. Byte counts mean captured/observed frame bytes; +wire lengths are tracked separately. Rates cover the first-to-last packet interval +and are undefined for zero-duration observations. Frame check sequences, NIC +segmentation/coalescing offloads, capture loss and capture position affect results. + +Reports contain IP addresses, MAC-derived packet metadata and service relationships; +handle them as investigation data. Reports are created with POSIX mode 0600 where +the filesystem supports it. No real packet captures are committed to this repository. + +## Engineering documentation + +- [Architecture and resource bounds](docs/ARCHITECTURE.md) +- [Protocol decoding and validation](docs/PROTOCOLS.md) +- [Detection algorithms and tuning](docs/DETECTION_RULES.md) +- [Tests, sanitizers and live verification](docs/TESTING.md) +- [Interview explanations and demo](docs/INTERVIEW_PREP.md) +- [Initial audit and corrections](docs/AUDIT.md) +- [Implementation status](PROGRESS.md) diff --git a/config/rules.json b/config/rules.json new file mode 100644 index 0000000..2780d0a --- /dev/null +++ b/config/rules.json @@ -0,0 +1,84 @@ +{ + "rules": { + "POSSIBLE_TCP_PORT_SCAN": { + "enabled": true, + "threshold": 12, + "window_seconds": 10, + "cooldown_seconds": 30, + "severity": "MEDIUM", + "exclude_sources": [], + "exclude_destinations": [] + }, + "HIGH_TCP_SYN_RATE": { + "enabled": true, + "threshold": 100, + "window_seconds": 10, + "cooldown_seconds": 30, + "severity": "MEDIUM", + "exclude_sources": [], + "exclude_destinations": [] + }, + "HIGH_ICMP_ECHO_RATE": { + "enabled": true, + "threshold": 50, + "window_seconds": 10, + "cooldown_seconds": 30, + "severity": "LOW", + "exclude_sources": [], + "exclude_destinations": [] + }, + "SENSITIVE_SERVICE_TRAFFIC": { + "enabled": true, + "threshold": 1, + "window_seconds": 10, + "cooldown_seconds": 60, + "severity": "INFO", + "exclude_sources": [], + "exclude_destinations": [], + "ports": [ + 22, + 23, + 445, + 3389 + ] + }, + "CONNECTION_CONCENTRATION": { + "enabled": true, + "threshold": 40, + "window_seconds": 10, + "cooldown_seconds": 30, + "severity": "LOW", + "exclude_sources": [], + "exclude_destinations": [] + } + }, + "limits": { + "max_flows": 4096, + "max_unique_flows": 65536, + "max_talkers": 4096, + "max_rule_keys": 1024, + "max_rule_events": 50000, + "max_alerts": 10000, + "flow_timeout_seconds": 60 + }, + "policy": [ + { + "source": "any", + "destination": "any", + "destination_port": 22, + "action": "WOULD_BLOCK" + }, + { + "source": "any", + "destination": "any", + "destination_port": 445, + "action": "WOULD_BLOCK" + }, + { + "source": "any", + "destination": "any", + "destination_port": -1, + "action": "WOULD_ALLOW" + } + ] +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..a5fb7ff --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,132 @@ +# PacketForge architecture + +## Shared pipeline + +```mermaid +flowchart LR + A[AF_PACKET recvmsg] --> P[Bounded decoder] + B[libpcap classic PCAP] --> P + P --> M[Decoded Packet metadata] + M --> S[Statistics] + M --> F[Directional flow table] + M --> D[Sliding-window IDS] + M --> W[Optional policy simulation] + D --> T[Terminal observations] + S --> R[Report snapshot] + F --> R + D --> R + R --> J[JSON / CSV / standalone HTML] +``` + +Both capture sources invoke the same `PacketConsumer`. No detection implementation +is duplicated between live and offline modes. Offline processing uses recorded +capture timestamps, so replay speed does not affect rules. + +## Components + +| Component | Files | Responsibility | +| --- | --- | --- | +| Entry points | `src/main.cpp`, `src/sniffer.cpp`, `src/forwarder.cpp` | Main CLI and legacy wrappers | +| CLI | `src/cli.cpp` | Validate arguments, choose mode, print metadata, orchestrate exports | +| Capture | `src/capture/live.cpp`, `pcap.cpp` | Socket/pcap ownership, limits, callbacks | +| Parser | `src/parsers/packet.cpp`, `include/packetforge/packet.hpp` | Bounded byte decoding and host-order metadata | +| Rules | `src/detection/config.cpp`, `config/rules.json` | Strict validated JSON and safe defaults | +| IDS | `src/detection/detection.cpp` | Metadata windows, evidence, cooldowns and counters | +| Flows | `src/flows/flows.cpp` | Directional five-tuples and retention | +| Statistics | `src/statistics/` | Counters, top addresses/ports, shared analysis snapshot | +| Policy | `include/rules.hpp` | Original first-match concept with simulation labels | +| Reporting | `src/reporting/reporting.cpp` | JSON serialization, CSV/HTML escaping, exclusive file creation | + +## Capture ownership and shutdown + +Live capture owns a close-on-exec AF_PACKET socket through a noncopyable RAII wrapper. +It binds to an explicit Linux interface. Only Ethernet and Linux loopback hardware +types are accepted. `recvmsg(MSG_TRUNC)` distinguishes received wire length from the +buffer capacity. `PACKET_AUXDATA` restores a VLAN tag stripped by hardware when +provided by the kernel. `SO_TIMESTAMPNS` supplies kernel receive timestamps. +Promiscuous membership is scoped to the socket and released by close. + +A minimal signal handler only sets `volatile sig_atomic_t`; polling checks it. +SIGINT and SIGTERM restore previous handlers on exit. `poll` wakes at most every +100 ms to enforce duration limits, even on idle interfaces. Capture timestamps +are clamped to the last live timestamp if wall-clock time moves backwards; +duration uses `steady_clock`. Packet processing/export time can add shutdown +latency. Kernel drop counts are read using `PACKET_STATISTICS`. + +The PCAP reader owns `pcap_t` with `unique_ptr` and `pcap_close`. It requests +nanosecond timestamp precision, checks the classic-file magic and Ethernet link +kind, validates capture/wire metadata, and streams one frame at a time. It rejects +decreasing timestamps instead of silently adjusting evidence or loading an +unbounded file for sorting. Equal timestamps are valid. Container corruption +aborts the run; malformed packet contents are ordinary parser results. + +## Packet ownership and safety + +The parser borrows a buffer only during `parse_packet`; the returned `Packet` +contains copied strings and scalar values, never pointers into capture memory. +The decoder checks offset and remaining length before every field read. Reads are +explicit big-endian byte assembly. After parsing IP lengths, the decoder's limit +is reduced to that IP packet, so Ethernet padding cannot supply missing headers. +Parsing exceptions are internal fixed-size status markers caught at the boundary; +resource failures such as allocation errors propagate to the CLI. + +No packet payload is stored in analysis state. No packet structs are cast over +untrusted input. Socket API structures are ordinary kernel ABI structures, not +packet overlays. Alignment and compiler struct padding therefore cannot affect +network parsing. + +## Flows and storage bounds + +A key is `(source IP, destination IP, source port, destination port, protocol)`. +Traffic in the reverse direction is a separate row. Packet count, observed/wire +bytes, first/last times and bitwise TCP flag observations are tracked. A row is +neither a TCP connection state machine nor a reconstructed stream. Fragmented +packets are excluded, including initial fragments, to avoid partial flow evidence. +ICMP and ARP contribute to statistics but do not create transport five-tuples. + +Default bounds: + +| State | Bound | Behavior at capacity | +| --- | ---: | --- | +| Active flows | 4096 | Archive least recently observed row; increment eviction counter | +| Archived flows | 4096 | Discard oldest archived row; count discards | +| Unique five-tuples | 65536 | Stop retaining new identities; label total a lower bound | +| Source and destination counters | 4096 each | Retain existing identities; count omitted observations | +| Destination-port counters | 65536 possible ports | Naturally bounded numeric key space | +| Rule keys | 1024 per rule | Skip new keys; count omissions | +| Rule events | 50000 per rule | Skip new evidence; count omissions | +| Retained alert objects | 10000 | Keep total counters and emitted alerts, discard additional stored objects | + +Flows expire after 60 seconds of inactivity by default. Maintenance is checked +once per timestamp second, with forced final expiry after live capture. Offline +active means active at the last observed timestamp, not active in the present day. +IDS keys remain until both their observation window and cooldown are no longer +needed. Reports expose capacity loss; bounded storage implies possible false negatives. +Top talkers are exact only within retained identities, and may omit a later busy +source if the identity budget is already full. + +## Detection execution and performance + +Each enabled rule has its own keyed deque of timestamped events. At an observation, +old events outside `(now-window, now]` are removed before counting. Distinct port +or attempt sets are built from retained events. Retransmissions count for SYN rate, +but identical `(destination, source port, destination port, sequence)` attempts +are deduplicated for concentration. Evidence samples are capped at 32 ports. + +The implementation is single-threaded for deterministic reasoning and tests. +Parsing is proportional to a bounded header chain; flow lookup uses ordered maps. +Distinct evidence counting is linear/log-linear in a key's retained window, and +capacity eviction scans the bounded active-flow table. This is appropriate for a +small educational sensor, not an optimized line-rate engine. Future work should +profile first, then consider incremental counters, indexed expiry, PACKET_MMAP, +flow-affine workers and streaming report sinks. No throughput numbers are claimed. + +## Report trust boundaries + +JSON uses a maintained serializer. HTML escapes every dynamic string and includes +a restrictive Content Security Policy; it contains no scripts or remote assets. +CSV quotes all fields, doubles embedded quotes and prefixes formula-triggering +values with an apostrophe. Files are created exclusively with `O_EXCL` and mode +0600; existing files and symlinks are not overwritten. A multi-file export is not +transactional: a later I/O failure may leave earlier files or a partial failed file, +which is reported as an error. No autosending or external upload is performed. diff --git a/docs/AUDIT.md b/docs/AUDIT.md new file mode 100644 index 0000000..5990944 --- /dev/null +++ b/docs/AUDIT.md @@ -0,0 +1,58 @@ +# PacketForge repository audit + +Audited baseline: `8fd6286f6c3d2e04731b5e49b85b52086ac6f984` on GitHub `main`. +Author: Mayank Kumar Karn. Audit date: 2026-10-21. + +The GitHub repository contains six commits. The latest relocates `forwarder.cpp` +and `rules.hpp` into `src/` and `include/`. A separate pre-existing local copy in +`ctf/PacketForge` has an unborn Git branch and untracked files; it was left untouched. +This work continues the GitHub history on `feature/packetforge-analyzer-ids`. + +## Baseline verification + +Both documented direct compiler builds succeeded with GCC 15.2.0 and +`-std=c++17 -Wall -Wextra`. Original binaries were built in `/tmp`; they were not +run against live traffic during the audit. All six source/documentation files and +`.gitignore` were inspected before editing. No CMake, test suite, configuration +loader, offline reader, reports, or IDS engine exists at baseline. + +| Area | Verified finding | Correction plan | +| --- | --- | --- | +| Ethernet | Direct `EthHeader*` buffer cast, no minimum size check; only Ethernet II assumed | Bounded byte decoding and VLAN tags | +| IPv4 | IHL is calculated (not fixed at 20), but version, minimum IHL, total length, capture boundaries and fragments are unchecked | Validate before reading; distinguish wire/captured lengths | +| TCP/UDP | Unchecked structure casts; TCP offset and UDP length ignored | Explicit network-order reads and transport bounds | +| ARP/ICMP | EtherType/protocol detection only; no ARP addresses or ICMP type/code extraction | Decode supported fields | +| IPv6 | Absent | Bounded base/extension parsing with explicit unsupported cases | +| Capture | Real AF_PACKET socket receives frames; no bind, duration/count controls, signal handler or RAII | Explicit interface, limits, passive socket, graceful shutdown | +| Policy | First-match source/destination/port rules are useful educational logic | Preserve simulation using WOULD_ALLOW / WOULD_BLOCK | +| Enforcement | `forwarder.cpp` never forwards, retransmits or drops anything; README calls it a forwarding engine and labels decisions DROP | Correct code/output/docs; no enforcement | +| Rules | Mutable inline hardcoded table; “configurable” means editing/recompiling C++ | Validated external JSON rules and policy | +| Stats | Total and policy-decision counters only; reporting skipped for non-IPv4 | Shared protocol, flow, rate and alert statistics | +| Build/tests | Two manual g++ commands; no automated checks or PCAP workflow | CMake, CTest, synthetic fixtures, sanitizer builds | +| Privacy | No payload display, injection or persistence | Preserve passive metadata-only behavior | + +## Preservation + +The original implementations remain available at the audited Git commit. +`src/sniffer.cpp` and `src/forwarder.cpp` will become compatibility entry points into +the shared pipeline. `include/headers.hpp` will expose decoded packet types instead +of unsafe on-wire struct layouts. `include/rules.hpp` will preserve first-match +policy evaluation with accurate simulation names. Subsequent implementation and +validation details are recorded in `PROGRESS.md` and `docs/TESTING.md`. + +## Implemented corrections + +The new CMake pipeline replaces buffer overlays with bounded decoding and uses +libpcap for offline capture. `sniffer.cpp` and `forwarder.cpp` are compatibility +entry points to the same CLI; the latter explicitly selects policy simulation. +The original first-match behavior now loads validated configuration and produces +WOULD_ALLOW/WOULD_BLOCK. No enforcement was added. `headers.hpp` redirects to safe +metadata types. IPv4 IHL support was retained and validated, rather than incorrectly +claiming the baseline always used a fixed 20-byte IP header. + +Bounded flows, protocol/talker statistics, five explainable IDS rules, structured +alerts and local JSON/CSV/HTML reports now exist. Synthetic fixture generation, +unit/integration/live tests and sanitizer configuration replace the previous absence +of tests. README and interview documentation describe actual capabilities and +explicitly exclude forwarding, stream reconstruction, DNS inspection and PCAPNG. +See `docs/TESTING.md` and its linked raw logs for executed validation and limitations. diff --git a/docs/DETECTION_RULES.md b/docs/DETECTION_RULES.md new file mode 100644 index 0000000..1c79618 --- /dev/null +++ b/docs/DETECTION_RULES.md @@ -0,0 +1,187 @@ +# PacketForge detection rules + +PacketForge uses transparent metadata thresholds, not a trained anomaly model, +malware signature database or attack-confirmation engine. IDS is enabled by default. +Use `--no-ids` to disable it. Every alert includes the exact observed count, +threshold, window, packet-derived evidence and a limitation statement. + +## Demonstration defaults + +| Rule ID | Grouping and count | Threshold / window | Cooldown | Severity | +| --- | --- | --- | --- | --- | +| `POSSIBLE_TCP_PORT_SCAN` | Source + destination; distinct TCP SYN destination ports | 12 / 10 s | 30 s | MEDIUM | +| `HIGH_TCP_SYN_RATE` | Source + destination; TCP SYN initiation packets | 100 / 10 s | 30 s | MEDIUM | +| `HIGH_ICMP_ECHO_RATE` | Source + destination; ICMPv4/v6 echo requests | 50 / 10 s | 30 s | LOW | +| `SENSITIVE_SERVICE_TRAFFIC` | Source + destination + protocol + service port; observed TCP/UDP packets | 1 / 10 s | 60 s | INFO | +| `CONNECTION_CONCENTRATION` | Source; distinct attempted connections across observed destinations | 40 / 10 s | 30 s | LOW | + +The sensitive ports are 22 (commonly SSH), 23 (Telnet), 445 (SMB) and 3389 (RDP). +Either source or destination service port can match; if both match, the destination +port determines the observation key. A port number is not proof of application +identity. Access to a sensitive service is not automatically malicious. + +Severity describes the rule's investigation priority, not probability of compromise. +MEDIUM defaults indicate patterns worth validating; LOW allows common operational +explanations; INFO records access observations. HIGH is available for a carefully +tuned local rule but no demonstration rule assigns it by default. + +## Window and alert semantics + +A window is `(t - window_seconds, t]`. At time t, observations exactly on the left +boundary expire. Counts trigger at **greater than or equal to** the threshold. +Timestamps come from the PCAP when offline, so fast or slow replay has the same +result. Equal timestamps are accepted. Backwards timestamps are rejected. + +The first threshold crossing emits an alert. During cooldown, additional qualifying +observations update evidence/counters but do not emit another alert. Once cooldown +expires, an ongoing qualifying pattern can emit again on the next matching packet. +Cooldown zero means one alert per above-threshold episode, rearmed after the +observed count falls below threshold or the window fully expires. No background +alert is emitted without a packet. Expiry retains a key until its cooldown is +no longer needed. Global per-rule state caps can omit evidence and cause missed +detections; counters explicitly show this. + +Only supported, successfully decoded, unfragmented transport metadata reaches +rules. Non-initial and initial fragments are excluded from IDS. A syntactically +valid frame with unverified checksums can still contribute; checksum validation +is outside the implementation. + +## A. Possible TCP SYN port scan + +A candidate has SYN set and ACK, FIN and RST clear. Record destination ports in the +source/destination window. Repeated attempts to one port do not increase the +number of distinct ports. A single connection can never trigger the default rule, +and a configured threshold below two is rejected. + +Example: `samples/portscan.pcap` contains 13 SYNs toward ports 1000–1012. The first +alert occurs on port 1011: 12 distinct destination ports in the 10-second window. +The evidence includes the distinct count, packet count and a sorted sample of up +to 32 ports. [MITRE ATT&CK T1046](https://attack.mitre.org/techniques/T1046/) +provides context for service discovery, not proof that the observed source is an adversary. + +False positives: vulnerability scanners, inventory tools, authorized testing and +NAT aggregation. Limitations: slow scans outside the window, ACK/FIN scans, +distributed scans and missing capture paths can evade this rule. + +## B. Elevated TCP SYN rate + +Count every matching SYN initiation packet in the source/destination window, +including retransmissions and capture duplicates. `samples/synrate.pcap` contains +101 copies of one attempt within five seconds. It raises one `HIGH_TCP_SYN_RATE` +alert at count 100; it does not raise connection concentration or a port-scan alert. + +This is a burst/rate heuristic, not evidence of server resource exhaustion or a +confirmed SYN flood. Busy clients, unreachable services and duplicate loopback +observations can explain high counts. PacketForge does not calculate handshake +completion ratios or server SYN backlog occupancy. + +## C. Elevated ICMP echo activity + +Count only echo requests (IPv4 type 8/code 0, IPv6 type 128/code 0). Replies and +other ICMP messages do not count. `samples/icmp_rate.pcap` triggers at request 50. +Monitoring, diagnostics and reachability checks can produce the same behavior. +Packet count alone cannot establish malicious intent or denial of service. + +## D. Sensitive service observation + +Match either TCP/UDP service port against the configured set and count packets +per directional endpoint/protocol/service key. The default threshold emits an +informational observation on the first packet, then applies a 60-second cooldown. +A reverse-direction reply is a different observation key and may emit separately. +No service banner, authentication attempt, credential or payload is inspected. + +## E. Connection concentration + +For SYN initiations, count distinct tuples +`(destination IP, source port, destination port, TCP sequence number)` per source. +An identical retransmission does not become a new attempt. Changing initial +sequence numbers or ports may represent a new attempt, but this remains an +approximation without a TCP state machine. Multiple destination hosts can contribute. + +When an enabled, nonexcluded port-scan rule would recognize a destination's port +diversity within the concentration rule's evidence window, the concentration +observation is suppressed and `scan_overlap_suppressed` increments. This avoids +reporting the same scan-shaped evidence under two rule names at the default +thresholds. The rules retain separate windows; custom windows can suppress +concentration even if the shorter scan window does not currently trigger. An +already-issued observation is not retroactively withdrawn if traffic later evolves +into a scan. Choose aligned windows when comparing these rules. + +`samples/concentration.pcap` uses 41 distinct source ports toward one destination +service. It triggers concentration at 40 attempts, without the SYN-rate or +port-scan rule. Load balancers, proxy servers and application connection churn are +plausible benign explanations. + +## Configuration + +```bash +./build/packetforge analyze --pcap samples/portscan.pcap --rules config/rules.json +``` + +A custom JSON file can override only the settings you need; omitted settings retain +built-in defaults. The complete default file is included in `config/rules.json`. + +```json +{ + "rules": { + "POSSIBLE_TCP_PORT_SCAN": { + "enabled": true, + "threshold": 20, + "window_seconds": 15, + "cooldown_seconds": 60, + "severity": "MEDIUM", + "exclude_sources": ["192.0.2.99"], + "exclude_destinations": [] + }, + "SENSITIVE_SERVICE_TRAFFIC": { + "ports": [22, 445, 3389], + "severity": "INFO" + } + } +} +``` + +Exclusions accept exact IPv4/IPv6 literals only; IPv6 text is canonicalized. +CIDR, DNS names, regexes and wildcards in exclusions are unsupported. Policy address +fields separately accept the literal `any`. Unknown keys and rule IDs, duplicate +JSON keys, wrong types, negative counts, invalid severity, invalid IPs and excessive +nesting/file size are rejected. JSON comments are unsupported. + +Validation limits: configuration <= 1 MiB, nesting <= 32, thresholds 1–10000 +(scan >= 2), windows 1–3600 s, cooldown 0–86400 s, sensitive port list 1–1024 +entries in 1–65535. Thresholds cannot exceed the per-rule event budget. Resource +settings have explicit upper/lower bounds; see the loader for their exact ranges. + +## Alert schema + +Each object contains `alert_id`, `rule_id`, `title`, ISO UTC and nanosecond timestamps, +severity, source/destination and triggering ports, `detection_window_seconds`, +`observed_count`, `threshold`, structured `evidence`, `confidence`, `limitations`, +`recommendation` and nullable `mitre_technique`. IDs increase within one run, not +across a global alert database. For concentration spanning several destinations, +the destination text says so, and evidence includes the destination count; trigger +ports belong to the triggering packet. Reports also include the effective rules. + +Per-rule counters expose matched packets, emitted alerts, cooldown suppression, +scan-overlap suppression, dropped keys/events and retained state. Total alert +counts continue beyond the retained-report alert cap. Nothing is labeled a confirmed +compromise. Investigators should correlate with approved activity and endpoint logs. + +## Firewall Policy Simulation + +The `policy` array is ordered, first match wins, with source/destination addresses, +`destination_port` (-1 means any), and `WOULD_ALLOW` or `WOULD_BLOCK`. If no rule +matches, the result is `WOULD_ALLOW`. Port-specific rules require decoded TCP/UDP +ports. The original demonstration defaults would block destination ports 22/445. +This evaluation only prints observations; the operating system's traffic path is +unaffected. No forwarding, routing, iptables, nftables or NFQUEUE enforcement exists. + +## Practical tuning + +Start with representative authorized benign captures, check rates by workload, +then measure alert volume on known tests. Raise thresholds or narrow scope for +busy infrastructure; use exclusions sparingly because they create blind spots. +Keep an auditable copy of the effective config with each report. Test threshold +boundaries and time-window expiry after a rule change. Lowering thresholds may +improve sensitivity at the cost of more false positives. Raising them may miss +slow, distributed or low-volume activity. No universal default is defensible. diff --git a/docs/INTERVIEW_PREP.md b/docs/INTERVIEW_PREP.md new file mode 100644 index 0000000..ea2db3c --- /dev/null +++ b/docs/INTERVIEW_PREP.md @@ -0,0 +1,357 @@ +# PacketForge interview preparation + +Author: Mayank Kumar Karn. These scripts describe implemented behavior. Adapt the +motivation to your real experience and explain only code and results you understand. +The project evolved from the original raw-socket sniffer and policy demonstration +with coding-assistant support; avoid presenting generated work as entirely handwritten. + +## 60-second introduction + +“PacketForge is my C++17 network packet analyzer and lightweight intrusion detection +project for Linux. I started with raw-socket capture to understand what Ethernet, +IP and transport headers actually contain, then developed a shared analysis pipeline +for both live traffic and offline PCAP files. + +“The key engineering focus is safe parsing: every field is bounds-checked, IP options +and VLAN tags are handled, and non-initial fragments never get interpreted as TCP +ports. I track bounded directional flows and detect five metadata patterns using +configurable sliding windows, including possible SYN port scans and elevated SYN +activity. Alerts explain the observed count, threshold, timeframe and limitations. + +“I can demonstrate the entire IDS offline with synthetic captures and export JSON, +CSV and HTML reports. The project includes automated boundary tests and sanitizer +checks. It is a passive educational NIDS: its firewall feature simulates decisions +and does not block traffic.” + +## Three-minute technical explanation + +**First minute — capture and parsing.** + +“Live capture creates an AF_PACKET/SOCK_RAW socket and binds it to an explicitly +selected interface. The kernel gives it copies of observed frames. A RAII wrapper +closes the descriptor; poll enforces limits, and the signal handler only sets a +flag. Offline capture uses libpcap and recorded timestamps. Both feed exactly the +same parser and analysis function, which makes the detection demo reproducible. + +“I replaced structure casts over untrusted data with bounded byte reads. Ethernet +is normally 14 bytes, but VLAN tags change the IP offset. IPv4 IHL changes its +header size, so assuming 20 bytes is unsafe. IP total length also limits transport +parsing: Ethernet padding must not become a fake TCP header. The parser separates +truncated capture data, internally malformed fields and unsupported protocols.” + +**Second minute — state and detection.** + +“TCP/UDP flows use a directional five-tuple. Each record counts packets and captured +bytes, first and last observation times and TCP flags. That is metadata grouping, +not TCP stream reconstruction. Idle timeout and capacity eviction bound storage. + +“The port-scan rule groups SYN initiations by source and destination, counts distinct +destination ports in a sliding time window, and alerts at the configured threshold. +Repeated SYNs to one port do not count as a multi-port scan. The high-SYN rule counts +packets including retries, while connection concentration deduplicates identical +attempt tuples. ICMP echo activity and sensitive service observations use similar +metadata windows. Cooldowns and scan-overlap suppression reduce redundant alerts. +All state has caps and loss counters, so bounded memory has an explicit detection +tradeoff rather than an invisible claim of completeness.” + +**Third minute — evidence, validation and limits.** + +“An alert includes UTC timestamps, severity, endpoints, counts, thresholds, evidence, +limitations and a suggested investigation step. Only the possible service-discovery +rule maps to MITRE T1046. I deliberately say ‘possible scan’ or ‘elevated SYN rate’ +instead of asserting compromise or denial of service. + +“My deterministic captures use reserved addresses, with benign and suspicious +examples. Tests cover parser boundaries, byte order, VLANs, fragmentation, window +expiry, cooldowns, configuration errors and exports. Sanitizers check memory and +undefined behavior. Live tests run in an isolated Linux network namespace. + +“JSON supports further analysis; CSV exports alerts and flows; the HTML report +works entirely offline and escapes untrusted values. Current limits include no +IP reassembly, TCP reconstruction, DNS analysis, decryption or high-throughput +claim. The historical ‘forwarder’ is honestly labeled Firewall Policy Simulation: +observing a socket copy cannot enforce a DROP decision on the original traffic.” + +## Five-minute terminal demonstration + +Prepare a release build and a fresh output prefix before the interview. No root, +network connection, scanner or target machine is needed. + +1. **0:00–0:40 — Show scope and normal traffic.** + + ```bash + ./build/packetforge --help + ./build/packetforge analyze --pcap samples/demo.pcap + ``` + + Explain nine packets across several layers, no default alerts, and the distinction + between overlapping protocol counters and total frames. + +2. **0:40–1:40 — Show two different TCP behaviors.** + + ```bash + ./build/packetforge analyze --pcap samples/portscan.pcap --ids + ./build/packetforge analyze --pcap samples/synrate.pcap + ``` + + Point to 12 distinct ports versus 100 SYN packets. Explain why repeated attempts + do not become distinct ports and why high SYN activity is not automatically DoS. + +3. **1:40–2:30 — Show safe failure and honest policy.** + + ```bash + ./build/packetforge analyze --pcap samples/malformed.pcap --verbose + ./build/packetforge analyze --pcap samples/sensitive.pcap --policy + ``` + + Explain truncated versus malformed, and that WOULD_BLOCK changes no traffic. + +4. **2:30–3:40 — Show the evidence report.** + + ```bash + ./build/packetforge analyze --pcap samples/mixed.pcap \ + --rules config/rules.json --report all --output reports/interview-demo + ``` + + Open the local HTML, inspect an alert's evidence, threshold and limitation, + then show the machine-readable JSON and flow CSV. + +5. **3:40–5:00 — Show engineering validation.** + + ```bash + ctest --test-dir build --output-on-failure + cat config/rules.json + ``` + + Discuss timestamp-driven windows, state budgets and the testing evidence. If + interface enumeration is blocked by a restricted runner, use `-LE host` for + the offline tests and explain the environment difference. Do not claim the + absence of alerts proves that a capture is safe. + +`scripts/demo.sh` runs the analyses with a fresh report directory automatically. + +## Twenty realistic technical questions + +### 1. What is PacketForge, and what problem does it solve? + +It is a passive Linux network analyzer and lightweight network IDS. It turns +captured protocol metadata into flow/statistical summaries and explainable +observations. Its main educational problem is connecting low-level networking, +safe systems programming and defensible detection. It is not a production SOC +platform or a blocking IPS. + +### 2. Why did you build it, and why C++ rather than Python? + +A defensible motivation is learning Linux capture APIs, byte layout, resource +ownership and stateful metadata detection by building them. C++ provides direct +socket/libpcap integration, explicit types and predictable object lifetime. Python +would be excellent for prototyping and analytics; it is used here only for fixture +and test tooling. C++ is not automatically fast or safe: correctness and profiling +still matter, and unsafe pointer casts were a major problem in the original code. + +### 3. Why raw sockets, what is AF_PACKET, and what is CAP_NET_RAW? + +AF_PACKET is Linux's link-layer packet socket family. SOCK_RAW includes the link +header; ETH_P_ALL subscribes to all Ethernet protocol types on the selected +interface. CAP_NET_RAW authorizes raw/packet socket creation in the relevant user +namespace. It is narrower than full root privileges but still sensitive. This is +different from AF_INET raw sockets, which operate around the network layer. PacketForge +keeps AF_PACKET for educational value and uses libpcap for portable file parsing. + +### 4. How does a packet get from the network into your code? + +The NIC/driver passes data into the kernel. A bound packet socket receives observed +frame copies. PacketForge polls the socket, calls recvmsg, records capture/wire +length and a kernel timestamp, then passes a bounded byte view into the parser. +The decoded metadata goes into statistics, flows and IDS. Processing is single-threaded; +there is no guarantee of lossless capture at high load, so kernel drops are reported. + +### 5. What is the difference between a frame, packet, segment and datagram? + +An Ethernet frame is the link-layer unit with MAC addressing and EtherType. Its +payload may be an IP packet with network-layer addresses. An IP payload may carry +a TCP segment or UDP datagram with transport ports. UDP is message-oriented; TCP +is a byte stream despite arriving in segments. “Packet” is also used loosely for +all these units, but parser offsets require the layer distinction. + +### 6. How do Ethernet, IPv4 and IPv6 headers differ? + +Ethernet identifies local link endpoints through MAC addresses; switches use those +addresses. IPv4 identifies routed network endpoints, has a variable header through +IHL/options, and carries total length, TTL, protocol and fragmentation fields. +IPv6 has a fixed 40-byte base header plus possible extensions, a payload length, +next-header chain and hop limit. VLAN tags extend the Ethernet header and change +where IP begins. Routers can replace link headers while IP packets move between links. + +### 7. What do TCP and UDP headers contribute? + +Both identify transport endpoints with ports. TCP also carries sequence and +acknowledgment numbers, a data offset, control flags and receive window, supporting +reliability and ordered delivery in the TCP implementation. UDP has an eight-byte +header with ports, length and checksum and does not itself guarantee delivery, +order or retransmission. PacketForge extracts metadata; it does not implement either +transport protocol or verify their checksums. + +### 8. Explain the TCP three-way handshake and SYN, ACK, FIN and RST. + +A client sends SYN with initial sequence x. A listening server replies SYN/ACK +with its own initial sequence y and acknowledgment x+1. The client acknowledges +y+1. SYN consumes sequence space. ACK makes the acknowledgment field meaningful. +FIN signals an orderly end to one sending direction and also consumes sequence +space. RST abruptly rejects/resets a connection. PacketForge's initiation rules +count SYN without ACK/FIN/RST; seeing that packet alone does not prove establishment. + +### 9. What is the difference between IDS and IPS? Host IDS versus network IDS? + +An IDS detects and reports; an IPS is positioned to prevent or block traffic/actions. +A network IDS examines traffic at an observation point; a host IDS examines endpoint +activity such as processes, files and logs. PacketForge is a network metadata IDS. +It sees only what reaches its selected capture point and does not monitor process +or filesystem behavior. Detection alone provides no enforcement authority. + +### 10. Signature detection versus anomaly detection: which is this? + +Signatures match known patterns, such as an exploit byte sequence or a structured +known-bad indicator. Anomaly detection compares behavior to an expected baseline, +which may be statistical or learned. PacketForge implements rule-based behavioral +threshold heuristics; it is neither a payload signature engine nor a trained anomaly +model. Its thresholds are configured manually and should be tuned against a baseline. + +### 11. How exactly do you detect a possible port scan? + +Select SYN initiation metadata, group by source/destination, expire events outside +`(now-10s, now]`, and count unique destination ports. The demonstration threshold is +12. A repeated SYN to one service does not increase that count. An alert records +what was observed and applies a per-key cooldown. This detects one narrow scan +pattern and misses many slow, distributed or non-SYN scans. T1046 supplies service- +discovery context rather than attribution. + +### 12. How are high SYN rate and connection concentration different? + +SYN rate counts packets, including retransmissions. Concentration counts distinct +attempt identities, including destination, ports and initial sequence, across the +source's observed destinations. Thus retries can produce a SYN-rate observation +without concentration. Neither verifies handshake completion. Scan-shaped port +diversity is suppressed for concentration to reduce duplicate explanations. + +### 13. How does threshold tuning change false positives and false negatives? + +Lower thresholds or longer windows can catch subtler behavior but also legitimate +bursts. Higher thresholds reduce noise but miss lower-rate activity. NAT can merge +many users behind one observed source. Authorized scanning, monitoring and connection +pools need context. Test benign and known suspicious fixtures, then use representative +authorized traffic, explicit exclusions and documented effective configuration. + +### 14. Why does returning DROP not block a packet? + +AF_PACKET receives a copy for observation; returning an enum only changes local +application control flow. It does not tell the forwarding stack to discard the +original. The original forwarder logged ALLOW/DROP without enforcement. PacketForge +now reports WOULD_ALLOW/WOULD_BLOCK and calls it simulation. Actual enforcement +would require a separate, explicitly designed integration such as a kernel filter +or NFQUEUE, which this project does not implement. + +### 15. How do you prevent buffer overreads, and what is network byte order? + +Every read verifies offset and required bytes against captured bounds, using +subtraction to avoid offset-addition overflow. IP length narrows the transport +boundary. The parser reads bytes into host-order integers, rather than casting +unaligned network memory to compiler-laid-out structs. Network byte order is big- +endian; for example bytes 0x01 0xbb represent port 443. Header length fields are +validated before advancing. Tests and sanitizers provide evidence, not a formal +proof that all possible bugs are absent. + +### 16. How does offline PCAP analysis work, including timestamps? + +libpcap reads the global header, link type and packet records. Each record supplies +captured length, original length and timestamp. PacketForge supports classic +Ethernet PCAP, requests nanosecond precision and feeds each record through the same +pipeline as live capture. Windows use recorded time, not the speed of the replay. +Equal times are allowed, decreasing times cause an explicit error. PCAPNG is +rejected even though libpcap can read some PCAPNG files. + +### 17. What happens with fragmented IP packets and IPv6 extensions? + +IPv4 IHL is variable and fragmentation can separate transport bytes across packets. +A nonzero fragment offset means this is not the start of the transport header, so +ports must not be guessed. Initial fragments are parsed only if a whole header +fits, then excluded from flows/IDS along with all fragments. IPv6 extensions are +walked with bounded lengths and depth; unsupported ESP/jumbograms are explicit. +There is no reassembly or overlapping-fragment evasion defense. + +### 18. Why not simply use Wireshark, Snort or Suricata? + +For operational investigations and production detection I would use mature tools. +Wireshark offers deep protocol inspection and interactive analysis; Snort/Suricata +provide mature rule ecosystems and production sensor features. PacketForge is small +enough to explain and test end to end. Its value is demonstrating implementation +tradeoffs, memory safety and transparent heuristics, not replacing those tools or +claiming equivalent protocol coverage and performance. + +### 19. What are the main limitations, and how would it scale? + +There is no application parsing, payload inspection, checksum validation, reassembly, +decryption, distributed correlation or high-speed capture guarantee. Detection +depends on visibility, timestamps, offloads and tuned thresholds. Bounded state +can omit evidence, and top talkers can be incomplete after saturation. To scale, +profile first; consider PACKET_MMAP/ring capture, fewer allocations, incremental +window counters, indexed expiry, flow-affine workers and streaming exports. Preserve +time ordering per key and expose overload counters. Do not promise line-rate +performance without measurements on specified hardware and traffic. + +### 20. What did you implement personally, and how can you prove your understanding? + +Give an accurate contribution history: the repository began with the raw-socket +sniffer, header structures and first-match rule concept; this revision expanded +those concepts with coding-assistant support. Point to Git commits, the initial +audit and executed tests. Explain one parser boundary, modify a threshold, predict +a fixture's output and run the test. Claim design, review, testing and code work +only to the extent you actually performed and can defend it. Understanding the +implementation is more persuasive than claiming every line was written unaided. + +## Implementation challenges to discuss + +**Captured length versus protocol length.** A buffer can be long enough overall +while its IP payload is too short for TCP. The decoder now restricts reads to the +validated IP boundary, preventing Ethernet padding from disguising a missing header. +A unit test specifically exercises this. + +**VLAN tags and options shift offsets.** Fixed offsets work only on simple packets. +The parser advances through at most two VLAN tags, validates IPv4 IHL, and walks +bounded IPv6 extensions. Tests deliberately insert VLAN and option bytes. + +**Fragmented traffic can create fake ports.** Reading transport fields from a later +fragment interprets arbitrary payload as a header. PacketForge explicitly skips +non-initial fragments and excludes all fragments from IDS/flow grouping, trading +coverage for an honest, safe implementation without reassembly. + +**Replay time differs from capture time.** Using wall-clock time during PCAP replay +would make alerts depend on CPU speed. Stored timestamps drive windows, exact left- +boundary expiry is tested, and nonchronological files produce a useful error. + +**Rule definitions can overlap.** SYN rate measures packets, concentration estimates +new attempts, and port scans measure port diversity. Separate fixtures expose those +differences; concentration deduplicates retransmissions and suppresses scan-shaped +evidence. Explain custom-window limitations rather than claiming perfect correlation. + +**Bounded memory changes observability.** Keeping every flow or address forever is +unsafe for long-running capture. Budgets, idle expiry and eviction prevent unbounded +state; saturation counters and lower-bound labels make the loss visible. + +**Environment restrictions are different from program failures.** Interface access +and live capabilities can be blocked by a runner. Live behavior was tested in an +isolated WSL Linux user/network namespace with normal local UDP sockets. The ordinary +user's host sudo needs a password; no such password was collected or stored. + +**Safe reports still need input validation.** Captured addresses are formatted from +bytes, but filenames/configuration can also contain markup. All HTML dynamic values +are escaped, CSV formula starts are neutralized and files are created exclusively. +The integration suite checks a malicious filename and overwrite refusal. + +## Before the interview + +Read `packet.cpp`, explain `need()` and the IP boundary, then change one unit test +and predict its result. Read one rule from config through alert creation. Re-run the +offline demo and inspect the JSON evidence. Know which limitations are intentional. +Use `docs/TESTING.md` for exact executed validation and environment caveats; never +quote invented pass counts, performance benchmarks or production deployment claims. diff --git a/docs/PROTOCOLS.md b/docs/PROTOCOLS.md new file mode 100644 index 0000000..4a256d9 --- /dev/null +++ b/docs/PROTOCOLS.md @@ -0,0 +1,116 @@ +# PacketForge protocol decoding + +All multibyte wire fields are decoded in network byte order (most significant byte +first). Captured length is the number of bytes actually available; wire length is +the original frame length reported by the capture source. Parsing never treats +wire length as permission to access uncaptured bytes. + +## Result categories + +- `ok`: supported metadata was decoded, or a deliberately skipped non-initial + fragment/no-next-header packet was safely classified. +- `truncated`: the available capture ends before a required declared header/body. +- `malformed`: contradictory protocol lengths/fields, including IP lengths beyond + reported wire size, invalid offsets or invalid capture/wire length combinations. +- `unsupported`: valid-looking content outside implemented formats, such as LLC, + unknown EtherTypes/IP protocols, ESP or excessive extension depth. + +The separate `capture_truncated` flag records `caplen < wirelen`, even when all +metadata lies inside the capture and only padding/payload is missing. Statistics +count capture truncation independently of the primary parse result. A packet may +therefore contribute to both a truncation counter and a malformed counter. + +## Ethernet and VLAN + +Ethernet II requires 14 bytes: destination MAC (6), source MAC (6), EtherType (2). +Both MACs are formatted in canonical hexadecimal. EtherTypes 0x8100 and 0x88a8 +advance through a four-byte tag containing TCI and the next EtherType. The low +12 TCI bits become the VLAN ID. Two tags are supported; a third is explicitly +unsupported. IEEE 802.3 length/LLC frames are not decoded. FCS is not validated. + +Live NIC VLAN offload may remove a tag from received bytes. When Linux supplies +valid `PACKET_AUXDATA` VLAN metadata, the capture adapter restores that tag before +shared parsing, updating both observed and wire lengths. Other offload effects +are not normalized. + +## ARP + +The initial eight bytes declare hardware/protocol types, address lengths and +opcode. The decoder checks the full variable-size layout before reading addresses. +Ethernet/IPv4 ARP (hardware type 1, protocol 0x0800, lengths 6 and 4) supports +sender/target hardware and protocol addresses plus opcode. Other address formats +are explicitly unsupported. ARP source/destination statistics use protocol addresses. +ARP spoofing detection is not implemented. + +## IPv4 + +The decoder requires version 4 and IHL >= 5 words. It validates the complete +variable-length header, total length >= IHL, and the packet boundary against both +wire and captured lengths. It extracts version, IHL, total length, TTL, protocol, +source/destination, identification, DF/MF and fragment offset in **bytes**. +Options are bounded and skipped, not interpreted. + +Reserved fragmentation flags and contradictory DF/fragment flags are rejected. +A non-final fragment payload must be a multiple of eight bytes. Non-initial +fragments return without reading transport headers. An initial fragment can yield +transport metadata only when a whole transport header fits; short initial fragment +headers are classified unsupported. A UDP length may exceed the fragment payload +because it refers to the original datagram. IDS and flows exclude all fragmented +packets. There is no reassembly, overlapping-fragment analysis or checksum validation. + +## IPv6 + +The base header is 40 bytes. PacketForge extracts addresses, version, payload +length, original next-header and hop limit, and bounds the declared payload. +The current upper-layer protocol is distinct from the original next-header value. + +Hop-by-Hop, Routing and Destination Options use `(HdrExtLen + 1) * 8` bytes; +Authentication Header uses `(PayloadLen + 2) * 4`, with its fixed-field minimum +validated. Fragment headers are eight bytes. The chain is limited to eight +extensions, Hop-by-Hop must be first, and duplicate fragment headers/reserved +fragment fields are rejected. Option contents, routing semantics and authentication +are not verified. ESP and unknown extensions are unsupported. + +Fragment offsets/M flag/identification are extracted. Non-initial fragments do not +supply transport fields. Atomic fragments (offset zero, M clear) may be decoded +normally. No Next Header (59) terminates decoding. Jumbograms are unsupported. +ICMPv6 supports type/code and echo request/reply classification, not full neighbor +discovery or router-advertisement interpretation. + +## TCP + +A minimum 20-byte TCP header must fit inside the IP payload. The data offset is +measured in 32-bit words; values below 5 or headers beyond the IP boundary are +invalid. Source/destination ports, sequence and acknowledgment numbers, header +length, flags and window are copied to host-order fields. TCP options are skipped +within validated boundaries. The six classic flag bits are FIN=0x01, SYN=0x02, +RST=0x04, PSH=0x08, ACK=0x10, URG=0x20. + +A detection initiation is SYN set with ACK, FIN and RST clear. That does not prove a +successful handshake. The parser performs no TCP checksum verification, connection +state tracking, sequence acceptance, retransmission reconstruction or application +stream reassembly. + +## UDP and ICMP + +UDP requires eight bytes, with length >= 8 and length no greater than the IP +payload for an unfragmented datagram. Ports and datagram length are extracted. +UDP checksums and application protocols are not validated. Port 53 is not proof +of a DNS application, and fixture DNS messages are counted as UDP only. + +ICMPv4 protocol 1 and ICMPv6 next-header 58 require the common four-byte header. +Echo request/reply messages require eight bytes and code zero. Echo types are +8/0 for IPv4 and 128/129 for IPv6. Other ICMP types receive basic type/code +classification; embedded error packets are not recursively decoded. + +## Primary references + +- [Linux packet sockets](https://man7.org/linux/man-pages/man7/packet.7.html) +- [IPv4 — RFC 791](https://www.rfc-editor.org/rfc/rfc791) +- [IPv6 — RFC 8200](https://www.rfc-editor.org/rfc/rfc8200) +- [TCP — RFC 9293](https://www.rfc-editor.org/rfc/rfc9293) +- [UDP — RFC 768](https://www.rfc-editor.org/rfc/rfc768) +- [ARP — RFC 826](https://www.rfc-editor.org/rfc/rfc826) +- [ICMP — RFC 792](https://www.rfc-editor.org/rfc/rfc792) +- [ICMPv6 — RFC 4443](https://www.rfc-editor.org/rfc/rfc4443) +- [libpcap source and documentation](https://github.com/the-tcpdump-group/libpcap) diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..d9d06f9 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,150 @@ +# PacketForge testing and verification + +## Ordinary development checks + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build -j2 +ctest --test-dir build --output-on-failure +./build/packetforge_tests +python3 tests/integration.py ./build/packetforge . +``` + +CTest has three named tests: `unit`, `interfaces` (label `host`) and `integration`. +The first contains many individual assertions; the integration test launches the +CLI repeatedly and validates outputs. A CTest test count is not the same as an +assertion count. The interface test needs ordinary Linux network-interface access, +which some execution sandboxes deny. In those runners, the entirely offline suite is: + +```bash +ctest --test-dir build -LE host --output-on-failure +``` + +A repeatable clean-build runner records actual compiler/test output: + +```bash +python3 scripts/verify.py --build-dir build-verify +``` + +It overwrites its own development log in `docs/evidence/build-and-tests.txt`, not +investigation reports. Build logs are evidence of the recorded environment, not +a claim that every distribution/compiler combination has been tested. + +## What is tested + +`tests/unit.cpp` covers Ethernet and MAC addresses, single/double VLAN tags and tag +limits, variable IPv4 IHL, IPv6 and extension/fragment metadata, TCP flags/offsets, +UDP length validation, ARP address layouts, ICMPv4/v6 echoes, network byte order, +every truncated prefix of a valid TCP frame, IP/transport boundary contradictions, +IPv4 fragments, unsupported protocols and empty buffers. A deterministic seeded +loop exercises 10,000 random byte buffers under the same parser. This is a smoke +fuzz test, not an exhaustive fuzz campaign or formal verification. + +State tests cover directional grouping, counters/duration, idle expiry, active and +archive caps, unique-count saturation, threshold boundaries, repeated-port/attempt +deduplication, window expiry, cooldowns, zero-cooldown episodes, rule exclusions, +SYN/ICMP rules, concentration, scan overlap, state-budget loss, timestamp rejection, +maximum timestamp arithmetic, simulation and serializer escaping. + +`tests/integration.py` analyzes every ordinary fixture against expected counts and +classifications, checks benign cases, complete alert fields, CSV parsing, JSON +round trips, HTML escaping/CSP, file overwrite refusal, disabled rules, literal-IP +exclusions, malformed JSON, duplicate/unknown keys, wrong types, invalid numeric +bounds, unsupported PCAPNG/link types, corrupt files, timestamp ordering/precision, +byte order, empty captures and CLI argument validation. It runs as an ordinary user +and uses temporary output directories. No internet or real capture is involved. + +## Sanitizers + +```bash +cmake -S . -B build-sanitize -DCMAKE_BUILD_TYPE=Debug -DPACKETFORGE_SANITIZERS=ON +cmake --build build-sanitize -j2 +ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=halt_on_error=1 \ + ctest --test-dir build-sanitize --output-on-failure +``` + +ASan instruments address accesses; UBSan detects selected undefined operations. +Keep `UBSAN_OPTIONS=halt_on_error=1` so an undefined-behavior finding fails the run. +Never run a capability-granted or privileged sanitizer binary as the normal testing +workflow. Offline tests need neither root nor CAP_NET_RAW. + +The restricted development runner uses process tracing, which prevents LeakSanitizer +from inspecting threads. In that runner, the executed supported command was: + +```bash +ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 \ + python3 scripts/verify.py --build-dir /tmp/packetforge-sanitize --sanitize +``` + +This still enables AddressSanitizer and UndefinedBehaviorSanitizer, but **does not +perform leak checking**. The original `detect_leaks=1` sandbox run failed with: + +```text +LeakSanitizer has encountered a fatal error. +LeakSanitizer does not work under ptrace (strace, gdb, etc) +``` + +Host verification results, if performed after that, are recorded separately below. +No tool/environment failure is counted as a passing test. + +## Isolated live-capture tests + +The opt-in live test creates a private user and network namespace. It sends a few +ordinary UDP datagrams only to its own loopback receiver and creates a temporary +veth pair inside that namespace. It does not scan another host, inject raw packets, +change the host firewall or inspect unrelated traffic. Namespace destruction removes +its devices. It needs Linux unprivileged user namespaces and `iproute2`: + +```bash +unshare --user --map-root-user --net \ + env PACKETFORGE_ISOLATED_TEST=1 python3 tests/live_capture.py build/packetforge +``` + +Checks include real AF_PACKET UDP capture, a four-packet count limit, captured/wire +lengths, idle duration exit, graceful SIGINT, JSON metadata, interface listing, +Ethernet device binding and explicit promiscuous socket membership. This validates +live Linux behavior in WSL2; it is not a test of every physical NIC, VLAN offload +implementation or access to Windows host traffic. Some distributions disable user +namespaces; there, use an authorized native Linux VM with appropriate capabilities. +The ordinary WSL host's password-requiring sudo was not used. + +## HTML verification + +The generated `reports/investigation.html` was opened with headless Chromium using +a local `file:` URL. Its screenshot is `docs/evidence/report-preview.png`. The +image was visually inspected for readable layout, counters and protocol/top-talker +sections. Integration tests check escaping, no scripts, CSP and required report +content. This is a Chromium rendering check, not a cross-browser accessibility audit. + +## Recorded results + +Final local results and raw command output are kept in `docs/evidence/`: + +- `build-and-tests.txt`: clean Release build and offline CTest/integration output. +- `sanitizers.txt`: clean ASan/UBSan build and offline results; restricted-runner leak + checking disabled as explained above. +- `report-preview.png`: actual rendered report screenshot. +- Additional host/live/demo logs are recorded when the final delivery checks run. + +The GitHub Actions workflow adds standard and sanitizer builds on Ubuntu and checks +fixture regeneration. A workflow file is not proof that remote CI passed; consult +the actual workflow run associated with the delivered branch. + +### Final local delivery run (2026-10-21) + +Clean GCC 15.2.0 Release build: passed without compiler warnings. Host CTest: +**3/3 passed** (`unit`, `interfaces`, `integration`). Unit binary: **10,153 checks**, +including 10,000 randomized inputs. Integration driver: **68 subprocess checks** +plus serialization/configuration/fixture assertions. Clean Debug ASan/UBSan build: +**2/2 offline CTest targets passed**, with `ASAN_OPTIONS=detect_leaks=0` and +`UBSAN_OPTIONS=halt_on_error=1`; separate direct unit/integration invocations passed. + +The isolated WSL2 live test passed: four real UDP frame observations, 288 captured +and wire bytes, zero malformed/truncated frames, zero kernel drops, and one +transport flow. Count, duration, SIGINT, Ethernet binding and opt-in promiscuous +checks all succeeded. Loopback can supply both outgoing and incoming copies; +four observations do not imply four distinct UDP transmissions. + +The report screenshot was generated by Chromium (1440 × 1300) from the actual +mixed-protocol HTML report and visually inspected. The normal demo has 9 packets +and no IDS alerts. Port-scan and SYN-rate fixtures emit one expected alert each. diff --git a/docs/evidence/build-and-tests.txt b/docs/evidence/build-and-tests.txt new file mode 100644 index 0000000..99ae98e --- /dev/null +++ b/docs/evidence/build-and-tests.txt @@ -0,0 +1,51 @@ +$ cmake -S /mnt/c/Users/mayank/Downloads/PacketForge -B /tmp/packetforge-release -DCMAKE_BUILD_TYPE=Release -DPACKETFORGE_SANITIZERS=OFF +-- The CXX compiler identification is GNU 15.2.0 +-- Detecting CXX compiler ABI info +-- Detecting CXX compiler ABI info - done +-- Check for working CXX compiler: /usr/bin/c++ - skipped +-- Detecting CXX compile features +-- Detecting CXX compile features - done +-- Found Python3: /home/mayhack/.local/bin/python3.11 (found version "3.11.16") found components: Interpreter +-- Configuring done (0.3s) +-- Generating done (0.0s) +-- Build files have been written to: /tmp/packetforge-release +$ cmake --build /tmp/packetforge-release --clean-first -j 2 +[ 5%] Building CXX object CMakeFiles/packetforge_core.dir/src/parsers/packet.cpp.o +[ 10%] Building CXX object CMakeFiles/packetforge_core.dir/src/capture/pcap.cpp.o +[ 15%] Building CXX object CMakeFiles/packetforge_core.dir/src/capture/live.cpp.o +[ 21%] Building CXX object CMakeFiles/packetforge_core.dir/src/detection/config.cpp.o +[ 26%] Building CXX object CMakeFiles/packetforge_core.dir/src/detection/detection.cpp.o +[ 31%] Building CXX object CMakeFiles/packetforge_core.dir/src/flows/flows.cpp.o +[ 36%] Building CXX object CMakeFiles/packetforge_core.dir/src/statistics/statistics.cpp.o +[ 42%] Building CXX object CMakeFiles/packetforge_core.dir/src/statistics/analysis.cpp.o +[ 47%] Building CXX object CMakeFiles/packetforge_core.dir/src/reporting/reporting.cpp.o +[ 52%] Building CXX object CMakeFiles/packetforge_core.dir/src/cli.cpp.o +[ 57%] Linking CXX static library libpacketforge_core.a +[ 57%] Built target packetforge_core +[ 68%] Building CXX object CMakeFiles/packetforge.dir/src/main.cpp.o +[ 68%] Building CXX object CMakeFiles/sniffer.dir/src/sniffer.cpp.o +[ 73%] Linking CXX executable sniffer +[ 78%] Linking CXX executable packetforge +[ 78%] Built target packetforge +[ 78%] Built target sniffer +[ 84%] Building CXX object CMakeFiles/packetforge_tests.dir/tests/unit.cpp.o +[ 89%] Building CXX object CMakeFiles/forwarder.dir/src/forwarder.cpp.o +[ 94%] Linking CXX executable forwarder +[ 94%] Built target forwarder +[100%] Linking CXX executable packetforge_tests +[100%] Built target packetforge_tests +$ ctest --test-dir /tmp/packetforge-release -LE host --output-on-failure +Internal ctest changing into directory: /tmp/packetforge-release +Test project /tmp/packetforge-release + Start 1: unit +1/2 Test #1: unit ............................. Passed 0.02 sec + Start 3: integration +2/2 Test #3: integration ...................... Passed 0.60 sec + +100% tests passed, 0 tests failed out of 2 + +Total Test time (real) = 0.62 sec +$ /tmp/packetforge-release/packetforge_tests +10153 checks passed +$ /usr/bin/python3 /mnt/c/Users/mayank/Downloads/PacketForge/tests/integration.py /tmp/packetforge-release/packetforge /mnt/c/Users/mayank/Downloads/PacketForge +68 CLI/fixture subprocess checks passed; JSON, CSV, HTML and config assertions passed diff --git a/docs/evidence/host-tests.txt b/docs/evidence/host-tests.txt new file mode 100644 index 0000000..3ab7d62 --- /dev/null +++ b/docs/evidence/host-tests.txt @@ -0,0 +1,19 @@ +[OUTPUT] +Internal ctest changing into directory: /tmp/packetforge-release + +[HANDLER_OUTPUT] +Test project /tmp/packetforge-release + + Start 1: unit +1/3 Test #1: unit ............................. Passed 0.04 sec + Start 2: interfaces +2/3 Test #2: interfaces ....................... Passed 0.01 sec + Start 3: integration +3/3 Test #3: integration ...................... Passed 0.72 sec + +100% tests passed, 0 tests failed out of 3 + +Label Time Summary: +host = 0.01 sec*proc (1 test) + +Total Test time (real) = 0.77 sec diff --git a/docs/evidence/offline-demo.txt b/docs/evidence/offline-demo.txt new file mode 100644 index 0000000..f3ffcea --- /dev/null +++ b/docs/evidence/offline-demo.txt @@ -0,0 +1,82 @@ +PacketForge | analyze | samples/demo.pcap | IDS enabled + +PacketForge | Investigation summary +Packets: 9 | Observed bytes: 498 | Wire bytes: 498 +Truncated: 0 | Malformed: 0 | Unsupported: 0 +Protocols: ARP=1 Ethernet=9 ICMP=3 IPv4=7 IPv6=1 TCP=4 UDP=1 +Observation interval: 0.400 s | Packets/s: 22.5 | Bytes/s: 1245.0 +Unique directional flows: 3 | Active: 3 | IDS alerts: 0 +top_sources: 192.0.2.10=7 198.51.100.20=1 2001:db8::1=1 +top_destinations: 198.51.100.20=6 192.0.2.10=1 192.0.2.20=1 2001:db8::2=1 +destination_ports: 443=3 53=1 40000=1 +PacketForge | analyze | samples/portscan.pcap | IDS enabled +[MEDIUM] POSSIBLE_TCP_PORT_SCAN | 2023-11-14T22:13:20.550000000Z | 192.0.2.10 -> 198.51.100.20 | observed=12 threshold=12 window=10s + +PacketForge | Investigation summary +Packets: 13 | Observed bytes: 702 | Wire bytes: 702 +Truncated: 0 | Malformed: 0 | Unsupported: 0 +Protocols: Ethernet=13 IPv4=13 TCP=13 +Observation interval: 0.600 s | Packets/s: 21.666666666666668 | Bytes/s: 1170.0 +Unique directional flows: 13 | Active: 13 | IDS alerts: 1 +top_sources: 192.0.2.10=13 +top_destinations: 198.51.100.20=13 +destination_ports: 1000=1 1001=1 1002=1 1003=1 1004=1 1005=1 1006=1 1007=1 1008=1 1009=1 + POSSIBLE_TCP_PORT_SCAN: 1 +PacketForge | analyze | samples/synrate.pcap | IDS enabled +[MEDIUM] HIGH_TCP_SYN_RATE | 2023-11-14T22:13:24.950000000Z | 192.0.2.10 -> 198.51.100.20 | observed=100 threshold=100 window=10s + +PacketForge | Investigation summary +Packets: 101 | Observed bytes: 5454 | Wire bytes: 5454 +Truncated: 0 | Malformed: 0 | Unsupported: 0 +Protocols: Ethernet=101 IPv4=101 TCP=101 +Observation interval: 5.000 s | Packets/s: 20.2 | Bytes/s: 1090.8 +Unique directional flows: 1 | Active: 1 | IDS alerts: 1 +top_sources: 192.0.2.10=101 +top_destinations: 198.51.100.20=101 +destination_ports: 443=101 + HIGH_TCP_SYN_RATE: 1 +PacketForge | analyze | samples/malformed.pcap | IDS enabled +2023-11-14T22:13:20.000000000Z Ethernet-other []:0 -> []:0 cap=25 wire=54 status=truncated mac=02:00:00:00:00:01->02:00:00:00:00:02 ethertype=2048 (captured header incomplete) +2023-11-14T22:13:20.100000000Z Ethernet-other []:0 -> []:0 cap=54 wire=54 status=malformed mac=02:00:00:00:00:01->02:00:00:00:00:02 ethertype=2048 (invalid IPv4 version or IHL) + +PacketForge | Investigation summary +Packets: 2 | Observed bytes: 79 | Wire bytes: 108 +Truncated: 1 | Malformed: 1 | Unsupported: 0 +Protocols: Ethernet=2 +Observation interval: 0.100 s | Packets/s: 20.0 | Bytes/s: 790.0 +Unique directional flows: 0 | Active: 0 | IDS alerts: 0 +top_sources: +top_destinations: +destination_ports: +PacketForge | analyze | samples/sensitive.pcap | IDS enabled +Firewall Policy Simulation: no traffic is blocked or forwarded +[INFO] SENSITIVE_SERVICE_TRAFFIC | 2023-11-14T22:13:20.000000000Z | 192.0.2.10 -> 198.51.100.20 | observed=1 threshold=1 window=10s +Source: 192.0.2.10 | Destination: [198.51.100.20]:22 | Policy: WOULD_BLOCK + +PacketForge | Investigation summary +Packets: 1 | Observed bytes: 54 | Wire bytes: 54 +Truncated: 0 | Malformed: 0 | Unsupported: 0 +Protocols: Ethernet=1 IPv4=1 TCP=1 +Observation interval: 0.000 s | Packets/s: n/a | Bytes/s: n/a +Unique directional flows: 1 | Active: 1 | IDS alerts: 1 +top_sources: 192.0.2.10=1 +top_destinations: 198.51.100.20=1 +destination_ports: 22=1 + SENSITIVE_SERVICE_TRAFFIC: 1 +PacketForge | analyze | samples/mixed.pcap | IDS enabled +[MEDIUM] POSSIBLE_TCP_PORT_SCAN | 2023-11-14T22:13:21.800000000Z | 192.0.2.10 -> 198.51.100.20 | observed=12 threshold=12 window=10s + +PacketForge | Investigation summary +Packets: 21 | Observed bytes: 1147 | Wire bytes: 1147 +Truncated: 0 | Malformed: 0 | Unsupported: 0 +Protocols: ARP=1 Ethernet=21 ICMP=2 IPv4=19 IPv6=1 TCP=17 UDP=1 +Observation interval: 2.000 s | Packets/s: 10.5 | Bytes/s: 573.5 +Unique directional flows: 16 | Active: 16 | IDS alerts: 1 +top_sources: 192.0.2.10=19 198.51.100.20=1 2001:db8::1=1 +top_destinations: 198.51.100.20=18 192.0.2.10=1 192.0.2.20=1 2001:db8::2=1 +destination_ports: 443=3 53=1 1000=1 1001=1 1002=1 1003=1 1004=1 1005=1 1006=1 1007=1 + POSSIBLE_TCP_PORT_SCAN: 1 +Report: reports/demo-dpOhHa/investigation.json +Report: reports/demo-dpOhHa/investigation.html +Report: reports/demo-dpOhHa/investigation-alerts.csv +Report: reports/demo-dpOhHa/investigation-flows.csv diff --git a/docs/evidence/report-preview.png b/docs/evidence/report-preview.png new file mode 100644 index 0000000..9313074 Binary files /dev/null and b/docs/evidence/report-preview.png differ diff --git a/docs/evidence/sanitizers.txt b/docs/evidence/sanitizers.txt new file mode 100644 index 0000000..c50bd8e --- /dev/null +++ b/docs/evidence/sanitizers.txt @@ -0,0 +1,47 @@ +Environment: ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 +LeakSanitizer disabled because the restricted runner uses ptrace. + +$ cmake -S /mnt/c/Users/mayank/Downloads/PacketForge -B /tmp/packetforge-sanitize -DCMAKE_BUILD_TYPE=Debug -DPACKETFORGE_SANITIZERS=ON +-- Configuring done (0.2s) +-- Generating done (0.1s) +-- Build files have been written to: /tmp/packetforge-sanitize +$ cmake --build /tmp/packetforge-sanitize --clean-first -j 2 +[ 5%] Building CXX object CMakeFiles/packetforge_core.dir/src/parsers/packet.cpp.o +[ 10%] Building CXX object CMakeFiles/packetforge_core.dir/src/capture/pcap.cpp.o +[ 15%] Building CXX object CMakeFiles/packetforge_core.dir/src/capture/live.cpp.o +[ 21%] Building CXX object CMakeFiles/packetforge_core.dir/src/detection/config.cpp.o +[ 26%] Building CXX object CMakeFiles/packetforge_core.dir/src/detection/detection.cpp.o +[ 31%] Building CXX object CMakeFiles/packetforge_core.dir/src/flows/flows.cpp.o +[ 36%] Building CXX object CMakeFiles/packetforge_core.dir/src/statistics/statistics.cpp.o +[ 42%] Building CXX object CMakeFiles/packetforge_core.dir/src/statistics/analysis.cpp.o +[ 47%] Building CXX object CMakeFiles/packetforge_core.dir/src/reporting/reporting.cpp.o +[ 52%] Building CXX object CMakeFiles/packetforge_core.dir/src/cli.cpp.o +[ 57%] Linking CXX static library libpacketforge_core.a +[ 57%] Built target packetforge_core +[ 68%] Building CXX object CMakeFiles/packetforge.dir/src/main.cpp.o +[ 68%] Building CXX object CMakeFiles/sniffer.dir/src/sniffer.cpp.o +[ 73%] Linking CXX executable sniffer +[ 78%] Linking CXX executable packetforge +[ 78%] Built target packetforge +[ 78%] Built target sniffer +[ 84%] Building CXX object CMakeFiles/packetforge_tests.dir/tests/unit.cpp.o +[ 89%] Building CXX object CMakeFiles/forwarder.dir/src/forwarder.cpp.o +[ 94%] Linking CXX executable forwarder +[ 94%] Built target forwarder +[100%] Linking CXX executable packetforge_tests +[100%] Built target packetforge_tests +$ ctest --test-dir /tmp/packetforge-sanitize -LE host --output-on-failure +Internal ctest changing into directory: /tmp/packetforge-sanitize +Test project /tmp/packetforge-sanitize + Start 1: unit +1/2 Test #1: unit ............................. Passed 0.37 sec + Start 3: integration +2/2 Test #3: integration ...................... Passed 2.32 sec + +100% tests passed, 0 tests failed out of 2 + +Total Test time (real) = 2.69 sec +$ /tmp/packetforge-sanitize/packetforge_tests +10153 checks passed +$ /usr/bin/python3 /mnt/c/Users/mayank/Downloads/PacketForge/tests/integration.py /tmp/packetforge-sanitize/packetforge /mnt/c/Users/mayank/Downloads/PacketForge +68 CLI/fixture subprocess checks passed; JSON, CSV, HTML and config assertions passed diff --git a/include/headers.hpp b/include/headers.hpp index 279faa5..61a398f 100644 --- a/include/headers.hpp +++ b/include/headers.hpp @@ -1,40 +1,4 @@ #pragma once -#include - -struct EthHeader { - uint8_t dst_mac[6]; - uint8_t src_mac[6]; - uint16_t ethertype; -}; - -struct IPHeader { - uint8_t ver_ihl; - uint8_t tos; - uint16_t total_len; - uint16_t id; - uint16_t flags_fo; - uint8_t ttl; - uint8_t protocol; - uint16_t checksum; - uint32_t src_ip; - uint32_t dst_ip; -}; - -struct TCPHeader { - uint16_t src_port; - uint16_t dst_port; - uint32_t seq; - uint32_t ack; - uint8_t data_offset; - uint8_t flags; - uint16_t window; - uint16_t checksum; - uint16_t urgent_ptr; -}; - -struct UDPHeader { - uint16_t src_port; - uint16_t dst_port; - uint16_t length; - uint16_t checksum; -}; +// Compatibility include. PacketForge now decodes bounded bytes into host-order values. +// The original on-wire struct layouts remain in Git history at 8fd6286. +#include "packetforge/packet.hpp" diff --git a/include/packetforge/analysis.hpp b/include/packetforge/analysis.hpp new file mode 100644 index 0000000..c27da41 --- /dev/null +++ b/include/packetforge/analysis.hpp @@ -0,0 +1,24 @@ +#pragma once +#include "capture.hpp" +#include "detection.hpp" +#include "flows.hpp" +#include "statistics.hpp" +#include +namespace packetforge { +class Analysis { + Config config_; + bool ids_; + Timestamp previous_=-1; +public: + Statistics statistics; + FlowTable flows; + DetectionEngine detection; + std::vector alerts; + std::map alert_counts; + std::uint64_t total_alerts=0,alerts_not_retained=0; + Analysis(const Config& config,bool ids) : config_(config),ids_(ids),statistics(config.max_talkers),flows(config),detection(config) {} + void observe(const Packet& packet,const std::function& emit = {}); + Json report(const std::string& mode,const std::string& source,const CaptureResult& capture) const; + void summary(std::ostream& out) const; +}; +} diff --git a/include/packetforge/capture.hpp b/include/packetforge/capture.hpp new file mode 100644 index 0000000..4103958 --- /dev/null +++ b/include/packetforge/capture.hpp @@ -0,0 +1,21 @@ +#pragma once +#include "packet.hpp" +#include +#include +namespace packetforge { +using PacketConsumer = std::function; +struct CaptureOptions { + std::string interface; + std::uint64_t count = 0; + double duration = 0; + bool promiscuous = false; +}; +struct CaptureResult { + std::uint64_t packets = 0, kernel_drops = 0; + bool interrupted = false; +}; +void list_interfaces(); +CaptureResult analyze_pcap(const std::string& path, const PacketConsumer& consume, std::uint64_t limit = 0); +CaptureResult capture_live(const CaptureOptions& options, const PacketConsumer& consume, + const std::function& tick = {}); +} diff --git a/include/packetforge/cli.hpp b/include/packetforge/cli.hpp new file mode 100644 index 0000000..b5f6bde --- /dev/null +++ b/include/packetforge/cli.hpp @@ -0,0 +1,2 @@ +#pragma once +namespace packetforge { int run_cli(int argc, char** argv, bool legacy_capture = false, bool policy = false); } diff --git a/include/packetforge/config.hpp b/include/packetforge/config.hpp new file mode 100644 index 0000000..41b82ee --- /dev/null +++ b/include/packetforge/config.hpp @@ -0,0 +1,33 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +namespace packetforge { +using Json = nlohmann::json; +struct RuleConfig { + bool enabled = true; + std::size_t threshold = 1; + std::int64_t window_seconds = 10, cooldown_seconds = 30; + std::string severity = "MEDIUM"; + std::set ports; + std::set exclude_sources, exclude_destinations; +}; +struct PolicyRule { + std::string source = "any", destination = "any", action = "WOULD_ALLOW"; + int destination_port = -1; +}; +struct Config { + std::map rules; + std::vector policy; + std::size_t max_flows = 4096, max_unique_flows = 65536, max_talkers = 4096; + std::size_t max_rule_keys = 1024, max_rule_events = 50000, max_alerts = 10000; + std::int64_t flow_timeout_seconds = 60; + static Config defaults(); + static Config load(const std::string& path); + Json json() const; +}; +} diff --git a/include/packetforge/detection.hpp b/include/packetforge/detection.hpp new file mode 100644 index 0000000..b15b84c --- /dev/null +++ b/include/packetforge/detection.hpp @@ -0,0 +1,33 @@ +#pragma once +#include "config.hpp" +#include "packet.hpp" +#include +#include +#include +namespace packetforge { +class DetectionEngine { + struct Event { Timestamp time; std::uint16_t port; std::string destination, attempt; }; + struct State { + std::deque events; + Timestamp last_seen=0,last_alert=0; + bool alerted=false, above=false; + }; + struct Runtime { + std::map states; + std::size_t events=0; + std::uint64_t matched=0,alerts=0,cooldown_suppressed=0,scan_suppressed=0,dropped_events=0,dropped_keys=0; + }; + Config config_; + std::map runtime_; + Timestamp last_sweep_=-1; + std::uint64_t next_id_=1; + void trim(State& state, Runtime& runtime, Timestamp now, const RuleConfig& rule); +public: + explicit DetectionEngine(const Config& config) : config_(config) { + for (const auto& [id,rule]:config.rules) { (void)rule; runtime_.emplace(id,Runtime{}); } + } + void expire(Timestamp now); + std::vector observe(const Packet& packet); + Json counters() const; +}; +} diff --git a/include/packetforge/flows.hpp b/include/packetforge/flows.hpp new file mode 100644 index 0000000..0c7f2cd --- /dev/null +++ b/include/packetforge/flows.hpp @@ -0,0 +1,40 @@ +#pragma once +#include "config.hpp" +#include "packet.hpp" +#include +#include +#include +#include +namespace packetforge { +struct FlowKey { + std::string source, destination; + std::uint16_t source_port = 0, destination_port = 0; + std::uint8_t protocol = 0; + auto tuple() const { return std::tie(source,destination,source_port,destination_port,protocol); } + bool operator<(const FlowKey& other) const { return tuple() active_; + std::deque closed_; + std::set unique_; + Timestamp last_sweep_=-1; + void archive(std::map::iterator entry); +public: + std::uint64_t evictions=0, expired=0, archives_discarded=0; + bool unique_saturated=false; + explicit FlowTable(const Config& config) : config_(config) {} + void observe(const Packet& packet); + void expire(Timestamp now, bool force=false); + std::size_t active_count() const { return active_.size(); } + std::size_t unique_count() const { return unique_.size(); } + Json json() const; +}; +} diff --git a/include/packetforge/packet.hpp b/include/packetforge/packet.hpp new file mode 100644 index 0000000..eb0b978 --- /dev/null +++ b/include/packetforge/packet.hpp @@ -0,0 +1,44 @@ +#pragma once +#include +#include +#include +#include + +namespace packetforge { +using Timestamp = std::int64_t; // Unix nanoseconds; PCAP timestamps drive offline windows. +constexpr Timestamp second = 1000000000LL; +enum class ParseStatus { ok, truncated, malformed, unsupported }; +const char* status_name(ParseStatus status); + +// Decoded host-order values, never overlays of an untrusted network buffer. +struct Packet { + Timestamp timestamp = 0; + std::uint32_t captured_length = 0, wire_length = 0; + ParseStatus status = ParseStatus::ok; + std::string detail; + bool capture_truncated = false, ethernet = false, arp = false; + bool ipv4 = false, ipv6 = false, transport = false, fragmented = false; + std::string source_mac, destination_mac, source, destination; + std::uint16_t ethertype = 0; + std::vector vlan_ids; + std::uint8_t version = 0, ip_header_length = 0, ttl = 0, protocol = 0, next_header = 0; + std::uint16_t ip_total_length = 0, ipv6_payload_length = 0; + std::uint16_t fragment_offset = 0, ip_id = 0; + std::uint32_t ipv6_fragment_id = 0; + bool more_fragments = false, dont_fragment = false; + std::uint16_t source_port = 0, destination_port = 0; + std::uint32_t sequence = 0, acknowledgment = 0; + std::uint8_t tcp_header_length = 0, tcp_flags = 0; + std::uint16_t tcp_window = 0, udp_length = 0; + std::uint8_t icmp_type = 0, icmp_code = 0; + bool echo_request = false, echo_reply = false; + std::uint16_t arp_opcode = 0; + std::string arp_sender_hardware, arp_target_hardware; + bool syn_attempt() const { return transport && protocol == 6 && (tcp_flags & 0x02) && !(tcp_flags & 0x15); } + std::string protocol_name() const; +}; +Packet parse_packet(const std::uint8_t* bytes, std::size_t captured, + std::uint32_t wire_length, Timestamp timestamp); +std::string iso_time(Timestamp timestamp); +Timestamp now_timestamp(); +} diff --git a/include/packetforge/reporting.hpp b/include/packetforge/reporting.hpp new file mode 100644 index 0000000..a25ee35 --- /dev/null +++ b/include/packetforge/reporting.hpp @@ -0,0 +1,10 @@ +#pragma once +#include "config.hpp" +#include +#include +namespace packetforge { +std::string html_escape(const std::string& value); +std::string csv_field(const std::string& value); +std::string html_report(const Json& data); +std::vector write_reports(const Json& data,const std::string& format,const std::string& prefix); +} diff --git a/include/packetforge/statistics.hpp b/include/packetforge/statistics.hpp new file mode 100644 index 0000000..8a0e3cf --- /dev/null +++ b/include/packetforge/statistics.hpp @@ -0,0 +1,20 @@ +#pragma once +#include "config.hpp" +#include "packet.hpp" +#include +namespace packetforge { +class Statistics { + std::size_t max_talkers_; + void talker(std::map& table,const std::string& address,std::uint64_t& omitted); +public: + std::uint64_t packets=0,observed_bytes=0,wire_bytes=0,truncated=0,malformed=0,unsupported=0; + std::uint64_t omitted_sources=0,omitted_destinations=0; + Timestamp first=0,last=0; + std::map protocols,sources,destinations; + std::map ports; + explicit Statistics(std::size_t maximum) : max_talkers_(maximum) {} + void observe(const Packet& p); + double duration() const; + Json json() const; +}; +} diff --git a/include/rules.hpp b/include/rules.hpp index e360e03..1898ffc 100644 --- a/include/rules.hpp +++ b/include/rules.hpp @@ -1,20 +1,15 @@ #pragma once -#include -#include -#include - -enum class Action { ALLOW, DROP }; - -struct Rule { - std::string src_ip; // "any" = match all - std::string dst_ip; // "any" = match all - int dst_port; // -1 = match all - Action action; -}; - -// Simple rule table — checked top to bottom, first match wins -inline std::vector ruleTable = { - { "any", "any", 22, Action::DROP }, // block SSH traffic - { "any", "any", 445, Action::DROP }, // block SMB (common attack port) - { "any", "any", -1, Action::ALLOW } // default: allow everything else -}; +#include "packetforge/config.hpp" +#include "packetforge/packet.hpp" +namespace packetforge { +// Original first-match source/destination/port logic, now explicitly simulation. +inline std::string evaluate_policy(const Packet& packet, const std::vector& rules) { + for (const auto& rule : rules) { + if ((rule.source == "any" || rule.source == packet.source) + && (rule.destination == "any" || rule.destination == packet.destination) + && (rule.destination_port == -1 || (packet.transport && (packet.protocol == 6 || packet.protocol == 17) + && rule.destination_port == packet.destination_port))) return rule.action; + } + return "WOULD_ALLOW"; +} +} diff --git a/samples/README.md b/samples/README.md new file mode 100644 index 0000000..832fa4c --- /dev/null +++ b/samples/README.md @@ -0,0 +1,48 @@ +# Synthetic PacketForge captures + +Every capture was generated locally by `python3 scripts/generate_fixtures.py` using +only the Python standard library. The script writes files and never sends packets. +Source ranges are RFC 5737 documentation IPv4 ranges and `2001:db8::/32` for IPv6; +MAC addresses are synthetic locally administered values. There are no real users, +credentials, third-party captures or runtime packet-building dependencies. + +Timestamps begin at 2023-11-14T22:13:20Z. Files use classic Ethernet PCAP, mostly +little-endian with microsecond timestamp resolution. Protocol checksums are +constructed for normal IP/TCP/ICMP messages; zero IPv4 UDP checksums are legal. +The normal TCP example shows SYN, SYN/ACK, ACK and FIN/ACK metadata, without claiming +a complete session or application exchange. DNS contains a harmless `example.test` +query; PacketForge treats it as UDP metadata, not decoded DNS. + +| Fixture | Packets | Default alerts / expected behavior | +| --- | ---: | --- | +| `normal_tcp.pcap` | 4 | None; 2 directional flows | +| `normal_udp_dns.pcap` | 2 | None; UDP including one port-53 query | +| `arp.pcap` | 1 | None; Ethernet/IPv4 ARP request | +| `icmp.pcap` | 2 | None; echo request and reply | +| `ipv6.pcap` | 1 | None; ICMPv6 echo request | +| `demo.pcap` | 9 | None; benign mixed traffic | +| `portscan.pcap` | 13 | One POSSIBLE_TCP_PORT_SCAN, observed count 12 | +| `synrate.pcap` | 101 | One HIGH_TCP_SYN_RATE, observed count 100; repeated same attempt | +| `icmp_rate.pcap` | 51 | One HIGH_ICMP_ECHO_RATE, observed count 50 | +| `concentration.pcap` | 41 | One CONNECTION_CONCENTRATION, observed count 40 | +| `sensitive.pcap` | 1 | One INFO SENSITIVE_SERVICE_TRAFFIC; policy WOULD_BLOCK for port 22 | +| `malformed.pcap` | 2 | No alerts; 1 truncated capture, 1 invalid IPv4 IHL | +| `mixed.pcap` | 21 | One POSSIBLE_TCP_PORT_SCAN; ARP, IPv4, IPv6, TCP, UDP, ICMP | +| `nanosecond.pcap` | 1 | Timestamp ends `.123456789Z` | +| `big_endian.pcap` | 1 | Valid alternate-byte-order PCAP | +| `empty.pcap` | 0 | Valid empty capture; rates null/not applicable | +| `out_of_order.pcap` | 2 | Error: nonchronological timestamps; no successful report | +| `unsupported_link.pcap` | 1 | Error: non-Ethernet link type | + +`expected.json` is consumed by integration tests for ordinary analyses. The special +byte-order, timestamp and error fixtures are asserted separately. Integration tests +also construct a short/corrupt file and PCAPNG magic in a temporary directory. + +```bash +python3 scripts/generate_fixtures.py +./build/packetforge analyze --pcap samples/mixed.pcap --report all +``` + +Randomized and crafted unit tests cover additional VLAN, options, extension-header, +fragmentation and invalid-length cases directly, rather than requiring a PCAP file +for every byte-level mutation. diff --git a/samples/arp.pcap b/samples/arp.pcap new file mode 100644 index 0000000..c94affe Binary files /dev/null and b/samples/arp.pcap differ diff --git a/samples/big_endian.pcap b/samples/big_endian.pcap new file mode 100644 index 0000000..422089b Binary files /dev/null and b/samples/big_endian.pcap differ diff --git a/samples/concentration.pcap b/samples/concentration.pcap new file mode 100644 index 0000000..59f42e1 Binary files /dev/null and b/samples/concentration.pcap differ diff --git a/samples/demo.pcap b/samples/demo.pcap new file mode 100644 index 0000000..9faa2be Binary files /dev/null and b/samples/demo.pcap differ diff --git a/samples/empty.pcap b/samples/empty.pcap new file mode 100644 index 0000000..4f9600e Binary files /dev/null and b/samples/empty.pcap differ diff --git a/samples/expected.json b/samples/expected.json new file mode 100644 index 0000000..4713b9b --- /dev/null +++ b/samples/expected.json @@ -0,0 +1,66 @@ +{ + "normal_tcp.pcap": { + "packets": 4, + "alerts": [] + }, + "normal_udp_dns.pcap": { + "packets": 2, + "alerts": [] + }, + "arp.pcap": { + "packets": 1, + "alerts": [] + }, + "icmp.pcap": { + "packets": 2, + "alerts": [] + }, + "portscan.pcap": { + "packets": 13, + "alerts": [ + "POSSIBLE_TCP_PORT_SCAN" + ] + }, + "synrate.pcap": { + "packets": 101, + "alerts": [ + "HIGH_TCP_SYN_RATE" + ] + }, + "icmp_rate.pcap": { + "packets": 51, + "alerts": [ + "HIGH_ICMP_ECHO_RATE" + ] + }, + "concentration.pcap": { + "packets": 41, + "alerts": [ + "CONNECTION_CONCENTRATION" + ] + }, + "sensitive.pcap": { + "packets": 1, + "alerts": [ + "SENSITIVE_SERVICE_TRAFFIC" + ] + }, + "ipv6.pcap": { + "packets": 1, + "alerts": [] + }, + "demo.pcap": { + "packets": 9, + "alerts": [] + }, + "malformed.pcap": { + "packets": 2, + "alerts": [] + }, + "mixed.pcap": { + "packets": 21, + "alerts": [ + "POSSIBLE_TCP_PORT_SCAN" + ] + } +} diff --git a/samples/icmp.pcap b/samples/icmp.pcap new file mode 100644 index 0000000..a5490ff Binary files /dev/null and b/samples/icmp.pcap differ diff --git a/samples/icmp_rate.pcap b/samples/icmp_rate.pcap new file mode 100644 index 0000000..45cd0ed Binary files /dev/null and b/samples/icmp_rate.pcap differ diff --git a/samples/ipv6.pcap b/samples/ipv6.pcap new file mode 100644 index 0000000..217ee31 Binary files /dev/null and b/samples/ipv6.pcap differ diff --git a/samples/malformed.pcap b/samples/malformed.pcap new file mode 100644 index 0000000..ad2ec6a Binary files /dev/null and b/samples/malformed.pcap differ diff --git a/samples/mixed.pcap b/samples/mixed.pcap new file mode 100644 index 0000000..416593f Binary files /dev/null and b/samples/mixed.pcap differ diff --git a/samples/nanosecond.pcap b/samples/nanosecond.pcap new file mode 100644 index 0000000..4d9ee40 Binary files /dev/null and b/samples/nanosecond.pcap differ diff --git a/samples/normal_tcp.pcap b/samples/normal_tcp.pcap new file mode 100644 index 0000000..2a04851 Binary files /dev/null and b/samples/normal_tcp.pcap differ diff --git a/samples/normal_udp_dns.pcap b/samples/normal_udp_dns.pcap new file mode 100644 index 0000000..6249f6f Binary files /dev/null and b/samples/normal_udp_dns.pcap differ diff --git a/samples/out_of_order.pcap b/samples/out_of_order.pcap new file mode 100644 index 0000000..0e0a17d Binary files /dev/null and b/samples/out_of_order.pcap differ diff --git a/samples/portscan.pcap b/samples/portscan.pcap new file mode 100644 index 0000000..38ecbfa Binary files /dev/null and b/samples/portscan.pcap differ diff --git a/samples/sensitive.pcap b/samples/sensitive.pcap new file mode 100644 index 0000000..91bdfe5 Binary files /dev/null and b/samples/sensitive.pcap differ diff --git a/samples/synrate.pcap b/samples/synrate.pcap new file mode 100644 index 0000000..ebed516 Binary files /dev/null and b/samples/synrate.pcap differ diff --git a/samples/unsupported_link.pcap b/samples/unsupported_link.pcap new file mode 100644 index 0000000..1efc98f Binary files /dev/null and b/samples/unsupported_link.pcap differ diff --git a/scripts/demo.sh b/scripts/demo.sh new file mode 100644 index 0000000..64e9d1b --- /dev/null +++ b/scripts/demo.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +binary="${1:-./build/packetforge}" +mkdir -p reports +report_dir=$(mktemp -d reports/demo-XXXXXX) +"$binary" analyze --pcap samples/demo.pcap +"$binary" analyze --pcap samples/portscan.pcap --ids +"$binary" analyze --pcap samples/synrate.pcap +"$binary" analyze --pcap samples/malformed.pcap --verbose +"$binary" analyze --pcap samples/sensitive.pcap --policy +"$binary" analyze --pcap samples/mixed.pcap --rules config/rules.json --report all --output "$report_dir/investigation" diff --git a/scripts/generate_fixtures.py b/scripts/generate_fixtures.py new file mode 100644 index 0000000..e895590 --- /dev/null +++ b/scripts/generate_fixtures.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Deterministic, synthetic classic PCAPs. Python standard library only; no traffic sent.""" +import ipaddress +import json +from pathlib import Path +import struct + +ROOT = Path(__file__).resolve().parents[1] +BASE = 1700000000 + +def checksum(data): + if len(data) % 2: + data += b'\0' + value = sum(struct.unpack('!%dH' % (len(data)//2), data)) + while value >> 16: + value = (value & 65535) + (value >> 16) + return (~value) & 65535 + +def ethernet(payload, kind=0x0800, vlan=None): + macs = bytes.fromhex('020000000002020000000001') + if vlan is not None: + return macs + struct.pack('!HHH', 0x8100, vlan, kind) + payload + return macs + struct.pack('!H', kind) + payload + +def ipv4(payload, proto=6, src='192.0.2.10', dst='198.51.100.20', flags=0, options=b''): + source, destination = ipaddress.ip_address(src).packed, ipaddress.ip_address(dst).packed + header = struct.pack('!BBHHHBBH4s4s', 0x45 + len(options)//4, 0, 20+len(options)+len(payload), 1, flags, 64, proto, 0, source, destination) + options + header = header[:10] + struct.pack('!H', checksum(header)) + header[12:] + return header + payload + +def tcp(port=443, sport=40000, flags=2, seq=1, ack=0, src='192.0.2.10', dst='198.51.100.20'): + segment = struct.pack('!HHIIBBHHH', sport, port, seq, ack, 0x50, flags, 65535, 0, 0) + pseudo = ipaddress.ip_address(src).packed + ipaddress.ip_address(dst).packed + struct.pack('!BBH',0,6,len(segment)) + segment = segment[:16] + struct.pack('!H',checksum(pseudo+segment)) + segment[18:] + return ethernet(ipv4(segment,src=src,dst=dst)) + +def udp(payload=b'hello', port=5353): + # A zero UDP checksum is legal for IPv4. + segment=struct.pack('!HHHH',42000,port,len(payload)+8,0)+payload + return ethernet(ipv4(segment,17)) + +def icmp(reply=False): + body=struct.pack('!BBHHH',0 if reply else 8,0,0,1,1)+b'PacketForge' + body=body[:2]+struct.pack('!H',checksum(body))+body[4:] + return ethernet(ipv4(body,1)) + +def arp(): + body=struct.pack('!HHBBH',1,0x0800,6,4,1)+bytes.fromhex('020000000001')+ipaddress.ip_address('192.0.2.10').packed + body+=bytes(6)+ipaddress.ip_address('192.0.2.20').packed + return ethernet(body,0x0806) + +def ipv6(): + src=ipaddress.ip_address('2001:db8::1').packed; dst=ipaddress.ip_address('2001:db8::2').packed + body=struct.pack('!BBHHH',128,0,0,1,1) + pseudo=src+dst+struct.pack('!I3xB',len(body),58) + body=body[:2]+struct.pack('!H',checksum(pseudo+body))+body[4:] + return ethernet(struct.pack('!IHBB',6<<28,len(body),58,64)+src+dst+body,0x86dd) + +def write(name, packets, endian='<', nano=False, linktype=1): + path=ROOT/'samples'/name + with path.open('wb') as output: + output.write(struct.pack(endian+'IHHIIII',0xa1b23c4d if nano else 0xa1b2c3d4,2,4,0,0,262144,linktype)) + for i,entry in enumerate(packets): + packet, wire, offset = entry if isinstance(entry,tuple) else (entry,len(entry),i*100_000_000) + seconds, nanos=divmod(offset,1_000_000_000) + output.write(struct.pack(endian+'IIII',BASE+seconds,nanos if nano else nanos//1000,len(packet),wire)) + output.write(packet) + +def generate(): + (ROOT/'samples').mkdir(exist_ok=True) + normal=[tcp(),tcp(40000,443,0x12,seq=500,ack=2,src='198.51.100.20',dst='192.0.2.10'),tcp(flags=0x10,seq=2,ack=501),tcp(flags=0x11,seq=2,ack=501)] + dns=struct.pack('!HHHHHH',1,0x0100,1,0,0,0)+b'\x07example\x04test\0'+struct.pack('!HH',1,1) + cases={'normal_tcp.pcap':normal,'normal_udp_dns.pcap':[udp(),udp(dns,53)],'arp.pcap':[arp()], + 'icmp.pcap':[icmp(),icmp(True)],'portscan.pcap':[tcp(port=1000+i) for i in range(13)], + 'synrate.pcap':[tcp() for _ in range(101)],'icmp_rate.pcap':[icmp() for _ in range(51)], + 'concentration.pcap':[tcp(sport=40000+i) for i in range(41)],'sensitive.pcap':[tcp(port=22)], + 'ipv6.pcap':[ipv6()], 'demo.pcap':normal+[udp(dns,53),arp(),icmp(),icmp(True),ipv6()]} + # Keep all rate scenarios inside the 10-second demonstration window. + for name,packets in cases.items(): + write(name,[(p,len(p),i*50_000_000) for i,p in enumerate(packets)]) + bad=bytearray(tcp());bad[14]=0x44 + cases['malformed.pcap']=[(tcp()[:25],54,0),(bytes(bad),54,100_000_000)] + write('malformed.pcap',cases['malformed.pcap']) + write('mixed.pcap',normal+[arp(),udp(dns,53),icmp(),ipv6()]+[tcp(port=1000+i) for i in range(13)]) + write('nanosecond.pcap',[(tcp(),54,123456789)],nano=True) + write('big_endian.pcap',[tcp()],endian='>') + write('out_of_order.pcap',[(tcp(),54,1_000_000_000),(tcp(),54,0)]) + write('unsupported_link.pcap',[tcp()],linktype=101) + write('empty.pcap',[]) + expected={name:{'packets':len(packets),'alerts':[]} for name,packets in cases.items()} + expected['portscan.pcap']['alerts']=['POSSIBLE_TCP_PORT_SCAN'] + expected['synrate.pcap']['alerts']=['HIGH_TCP_SYN_RATE'] + expected['icmp_rate.pcap']['alerts']=['HIGH_ICMP_ECHO_RATE'] + expected['concentration.pcap']['alerts']=['CONNECTION_CONCENTRATION'] + expected['sensitive.pcap']['alerts']=['SENSITIVE_SERVICE_TRAFFIC'] + expected['mixed.pcap']={'packets':21,'alerts':['POSSIBLE_TCP_PORT_SCAN']} + (ROOT/'samples'/'expected.json').write_text(json.dumps(expected,indent=2)+'\n') + print(f'Generated synthetic PCAPs in {ROOT / "samples"}') + +if __name__=='__main__': + generate() diff --git a/scripts/verify.py b/scripts/verify.py new file mode 100644 index 0000000..5c0aeaa --- /dev/null +++ b/scripts/verify.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Reproducible clean build and offline validation; preserves real command output.""" +import argparse +from pathlib import Path +import subprocess +import sys + +root=Path(__file__).resolve().parents[1] +parser=argparse.ArgumentParser() +parser.add_argument('--build-dir',default='build-verify') +parser.add_argument('--sanitize',action='store_true') +args=parser.parse_args() +build=Path(args.build_dir).resolve() +logs=root/'docs/evidence' +logs.mkdir(exist_ok=True) +name='sanitizers' if args.sanitize else 'build-and-tests' +commands=[['cmake','-S',str(root),'-B',str(build),'-DCMAKE_BUILD_TYPE='+('Debug' if args.sanitize else 'Release'), + '-DPACKETFORGE_SANITIZERS='+('ON' if args.sanitize else 'OFF')], + ['cmake','--build',str(build),'--clean-first','-j','2'], + ['ctest','--test-dir',str(build),'-LE','host','--output-on-failure'], + [str(build/'packetforge_tests')], + [sys.executable,str(root/'tests/integration.py'),str(build/'packetforge'),str(root)]] +with (logs/(name+'.txt')).open('w') as log: + for command in commands: + line='$ '+' '.join(command)+'\n' + print(line,end='',flush=True);log.write(line);log.flush() + process=subprocess.Popen(command,cwd=root,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) + for line in process.stdout: + print(line,end='',flush=True);log.write(line) + status=process.wait() + if status: + log.write(f'Command failed with exit code {status}\n') + raise SystemExit(status) +print(f'Verification log: {logs/(name+".txt")}') diff --git a/src/capture/live.cpp b/src/capture/live.cpp new file mode 100644 index 0000000..b96c66c --- /dev/null +++ b/src/capture/live.cpp @@ -0,0 +1,116 @@ +#include "packetforge/capture.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace packetforge { +namespace { +volatile std::sig_atomic_t stopped = 0; +void stop(int) { stopped = 1; } +class Socket { + int fd_; +public: + explicit Socket(int fd) : fd_(fd) {} + ~Socket() { if (fd_ >= 0) ::close(fd_); } + Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; + int get() const { return fd_; } +}; +struct Signals { + struct sigaction old_int{}, old_term{}; + Signals() { + stopped = 0; struct sigaction action{}; action.sa_handler = stop; sigemptyset(&action.sa_mask); + if (sigaction(SIGINT, &action, &old_int) < 0) throw std::runtime_error("cannot install SIGINT handler"); + if (sigaction(SIGTERM, &action, &old_term) < 0) { + sigaction(SIGINT, &old_int, nullptr); throw std::runtime_error("cannot install SIGTERM handler"); + } + } + ~Signals() { sigaction(SIGINT, &old_int, nullptr); sigaction(SIGTERM, &old_term, nullptr); } +}; +void check(int rc, const char* message) { if (rc < 0) throw std::runtime_error(std::string(message)+": "+std::strerror(errno)); } +} +void list_interfaces() { + struct if_nameindex* interfaces = if_nameindex(); + if (!interfaces) throw std::runtime_error("could not enumerate interfaces"); + std::cout << "PacketForge | available capture interfaces\n"; + for (auto* i = interfaces; i->if_index; ++i) std::cout << i->if_index << "\t" << i->if_name << '\n'; + if_freenameindex(interfaces); +} +CaptureResult capture_live(const CaptureOptions& options, const PacketConsumer& consume, const std::function& tick) { + const auto index = if_nametoindex(options.interface.c_str()); + if (!index) throw std::runtime_error("unknown interface: " + options.interface + "; use packetforge interfaces"); + Socket socket(::socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_ALL))); + if (socket.get() < 0) throw std::runtime_error(std::string("AF_PACKET capture: ") + std::strerror(errno) + + ". Live capture requires CAP_NET_RAW (or sudo) on an authorized Linux interface; offline analysis needs neither."); + ifreq request{}; std::strncpy(request.ifr_name, options.interface.c_str(), IFNAMSIZ-1); + check(ioctl(socket.get(), SIOCGIFHWADDR, &request), "interface hardware type"); + if (request.ifr_hwaddr.sa_family != ARPHRD_ETHER && request.ifr_hwaddr.sa_family != ARPHRD_LOOPBACK) + throw std::runtime_error("capture requires Ethernet or Linux loopback link framing"); + sockaddr_ll address{}; address.sll_family = AF_PACKET; address.sll_protocol = htons(ETH_P_ALL); + address.sll_ifindex = static_cast(index); + check(bind(socket.get(), reinterpret_cast(&address), sizeof(address)), "bind interface"); + int enabled = 1; + check(setsockopt(socket.get(), SOL_PACKET, PACKET_AUXDATA, &enabled, sizeof(enabled)), "PACKET_AUXDATA"); + check(setsockopt(socket.get(), SOL_SOCKET, SO_TIMESTAMPNS, &enabled, sizeof(enabled)), "SO_TIMESTAMPNS"); + if (options.promiscuous) { + packet_mreq membership{}; membership.mr_ifindex = static_cast(index); membership.mr_type = PACKET_MR_PROMISC; + check(setsockopt(socket.get(), SOL_PACKET, PACKET_ADD_MEMBERSHIP, &membership, sizeof(membership)), "promiscuous membership"); + } + Signals signals; CaptureResult result; + std::array buffer{}; + const auto begin = std::chrono::steady_clock::now(); auto last_tick = begin; + Timestamp last_timestamp = 0; + while (!stopped && (!options.count || result.packets < options.count)) { + const auto now = std::chrono::steady_clock::now(); + if (options.duration > 0 && std::chrono::duration(now-begin).count() >= options.duration) break; + if (tick && now-last_tick >= std::chrono::seconds(1)) { tick(); last_tick = now; } + pollfd poller{socket.get(), POLLIN, 0}; const int ready = poll(&poller, 1, 100); + if (ready < 0 && errno == EINTR) continue; + check(ready, "capture poll"); if (!ready) continue; + if (poller.revents & (POLLERR | POLLHUP | POLLNVAL)) throw std::runtime_error("capture socket disconnected"); + iovec iov{buffer.data(), buffer.size()-4}; + alignas(cmsghdr) std::array control{}; + msghdr message{}; message.msg_iov = &iov; message.msg_iovlen = 1; + message.msg_control = control.data(); message.msg_controllen = control.size(); + const auto received = recvmsg(socket.get(), &message, MSG_TRUNC); + if (received < 0 && errno == EINTR) continue; + if (received < 0) check(-1, "recvmsg"); + auto wire = static_cast(received); + auto captured = std::min(static_cast(received), iov.iov_len); + Timestamp timestamp = now_timestamp(); + for (auto* c = CMSG_FIRSTHDR(&message); c; c = CMSG_NXTHDR(&message,c)) { + if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SO_TIMESTAMPNS && c->cmsg_len >= CMSG_LEN(sizeof(timespec))) { + timespec ts{}; std::memcpy(&ts, CMSG_DATA(c), sizeof(ts)); timestamp = ts.tv_sec*second + ts.tv_nsec; + } + if (c->cmsg_level == SOL_PACKET && c->cmsg_type == PACKET_AUXDATA && c->cmsg_len >= CMSG_LEN(sizeof(tpacket_auxdata))) { + tpacket_auxdata aux{}; std::memcpy(&aux, CMSG_DATA(c), sizeof(aux)); + if ((aux.tp_status & TP_STATUS_VLAN_VALID) && captured >= 14) { + std::memmove(buffer.data()+16, buffer.data()+12, captured-12); + const std::uint16_t tpid = (aux.tp_status & TP_STATUS_VLAN_TPID_VALID) ? aux.tp_vlan_tpid : 0x8100; + buffer[12] = static_cast(tpid >> 8); buffer[13] = static_cast(tpid); + buffer[14] = static_cast(aux.tp_vlan_tci >> 8); buffer[15] = static_cast(aux.tp_vlan_tci); + captured += 4; wire += 4; + } + } + } + // A wall-clock correction must not run sliding windows backwards. + timestamp = std::max(timestamp, last_timestamp); last_timestamp = timestamp; + consume(parse_packet(buffer.data(), captured, wire, timestamp)); ++result.packets; + } + tpacket_stats stats{}; socklen_t length = sizeof(stats); + if (getsockopt(socket.get(), SOL_PACKET, PACKET_STATISTICS, &stats, &length) == 0) result.kernel_drops = stats.tp_drops; + result.interrupted = stopped != 0; return result; +} +} diff --git a/src/capture/pcap.cpp b/src/capture/pcap.cpp new file mode 100644 index 0000000..cb8e305 --- /dev/null +++ b/src/capture/pcap.cpp @@ -0,0 +1,43 @@ +#include "packetforge/capture.hpp" +#include +#include +#include +#include +#include +#include +#include +namespace packetforge { +CaptureResult analyze_pcap(const std::string& path, const PacketConsumer& consume, std::uint64_t limit) { + // Deliberately support classic PCAP only, despite libpcap accepting some PCAPNG files. + std::ifstream input(path, std::ios::binary); std::array magic{}; + if (!input.read(reinterpret_cast(magic.data()), 4)) throw std::runtime_error("cannot read PCAP header: " + path); + const bool classic = magic == std::array{0xd4,0xc3,0xb2,0xa1} + || magic == std::array{0xa1,0xb2,0xc3,0xd4} + || magic == std::array{0x4d,0x3c,0xb2,0xa1} + || magic == std::array{0xa1,0xb2,0x3c,0x4d}; + if (!classic) throw std::runtime_error("only standard PCAP is supported; PCAPNG is not supported"); + char error[PCAP_ERRBUF_SIZE]{}; + std::unique_ptr handle( + pcap_open_offline_with_tstamp_precision(path.c_str(), PCAP_TSTAMP_PRECISION_NANO, error), pcap_close); + if (!handle) throw std::runtime_error(std::string("PCAP: ") + error); + if (pcap_datalink(handle.get()) != DLT_EN10MB) throw std::runtime_error("unsupported PCAP link type; Ethernet (DLT_EN10MB) required"); + CaptureResult result; Timestamp previous = -1; + while (!limit || result.packets < limit) { + pcap_pkthdr* header = nullptr; const u_char* bytes = nullptr; + const int status = pcap_next_ex(handle.get(), &header, &bytes); + if (status == -2) break; + if (status == -1) throw std::runtime_error(std::string("PCAP read error: ") + pcap_geterr(handle.get())); + if (status == 0) continue; + const auto secs = header->ts.tv_sec, nanos = header->ts.tv_usec; + if (secs < 0 || nanos < 0 || nanos >= second || secs > (std::numeric_limits::max()-nanos)/second) + throw std::runtime_error("PCAP timestamp outside supported Unix nanosecond range"); + const Timestamp timestamp = secs * second + nanos; + if (timestamp < previous) throw std::runtime_error("PCAP timestamps are not chronological; sort capture before analysis"); + previous = timestamp; + if (header->caplen > 16U*1024U*1024U || header->caplen > header->len) + throw std::runtime_error("invalid PCAP captured/wire length"); + consume(parse_packet(bytes, header->caplen, header->len, timestamp)); ++result.packets; + } + return result; +} +} diff --git a/src/cli.cpp b/src/cli.cpp new file mode 100644 index 0000000..84acb03 --- /dev/null +++ b/src/cli.cpp @@ -0,0 +1,138 @@ +#include "packetforge/cli.hpp" +#include "packetforge/analysis.hpp" +#include "packetforge/reporting.hpp" +#include "rules.hpp" +#include +#include +#include +#include +#include +#include +namespace packetforge { +namespace { +std::uint64_t number(const std::string& text) { + std::uint64_t value=0; const auto parsed=std::from_chars(text.data(),text.data()+text.size(),value); + if (parsed.ec!=std::errc{} || parsed.ptr!=text.data()+text.size() || value==0 || value>1000000000) + throw std::runtime_error("expected positive integer <= 1000000000: "+text); + return value; +} +double duration(const std::string& text) { + double value=0; const auto parsed=std::from_chars(text.data(),text.data()+text.size(),value); + if (parsed.ec!=std::errc{} || parsed.ptr!=text.data()+text.size() || !std::isfinite(value) || value<=0 || value>86400) + throw std::runtime_error("duration must be a number in (0, 86400] seconds"); + return value; +} +void help() { + std::cout << "PacketForge | Network Packet Analyzer & Intrusion Detection System\n" + "Author: Mayank Kumar Karn\n\n" + "Usage:\n packetforge interfaces\n" + " packetforge capture --interface NAME [--count N] [--duration SECONDS]\n" + " packetforge analyze --pcap FILE [--count N]\n\n" + "Analysis options:\n" + " --ids / --no-ids Enable (default) or disable metadata detection\n" + " --rules FILE Validated JSON overrides for rules, limits and policy\n" + " --policy Print Firewall Policy Simulation decisions\n" + " --verbose Packet metadata for each observed frame\n" + " --quiet Suppress immediate alerts; retain final summary/reports\n" + " --report FORMAT json, csv, html, or all\n" + " --output PREFIX Report path prefix (existing files are never overwritten)\n" + "Capture-only options:\n" + " --promiscuous Explicitly request socket-scoped promiscuous membership\n" + " --duration SECONDS Positive duration, up to 86400 seconds\n" + " --help Show this help\n\n" + "Offline analysis supports classic Ethernet PCAP without root or internet.\n" + "Live AF_PACKET capture needs CAP_NET_RAW on an authorized Linux interface.\n" + "PacketForge observes metadata; it never blocks, forwards or injects packets.\n" + "Compatibility: sniffer --interface NAME; forwarder --interface NAME (simulation).\n"; +} +} +int run_cli(int argc,char** argv,bool legacy,bool policy) { + try { + if (argc<2) { help(); return legacy ? 2 : 0; } + if (std::string(argv[1])=="--help") { if (argc!=2) throw std::runtime_error("--help takes no arguments"); help(); return 0; } + const std::string command=legacy ? "capture" : argv[1]; + std::string path,rules_path,report_format,output; + CaptureOptions options; bool verbose=false,ids=true,quiet=false; + std::set seen; + for (int i=legacy ? 1 : 2;i=argc) throw std::runtime_error("missing value for "+arg); return std::string(argv[i]); }; + if (arg=="--interface") options.interface=value(); + else if (arg=="--pcap") path=value(); + else if (arg=="--count") options.count=number(value()); + else if (arg=="--duration") options.duration=duration(value()); + else if (arg=="--promiscuous") options.promiscuous=true; + else if (arg=="--verbose") verbose=true; + else if (arg=="--quiet") quiet=true; + else if (arg=="--ids") ids=true; + else if (arg=="--no-ids") ids=false; + else if (arg=="--policy") policy=true; + else if (arg=="--rules") rules_path=value(); + else if (arg=="--report") report_format=value(); + else if (arg=="--output") output=value(); + else if (arg=="--help" && argc==(legacy ? 2 : 3)) { help(); return 0; } + else throw std::runtime_error("unknown option: "+arg); + } + if (command=="interfaces") { + if (argc!=2) throw std::runtime_error("interfaces takes no options"); + list_interfaces(); return 0; + } + if (command!="capture" && command!="analyze") throw std::runtime_error("unknown command: "+command); + if (command=="capture" && (options.interface.empty() || seen.count("--pcap"))) throw std::runtime_error("capture requires --interface and does not accept --pcap"); + if (command=="analyze" && (path.empty() || seen.count("--interface") || seen.count("--duration") || options.promiscuous)) + throw std::runtime_error("analyze requires --pcap; capture-only options are invalid"); + if (seen.count("--ids") && seen.count("--no-ids")) throw std::runtime_error("--ids and --no-ids conflict"); + if (!report_format.empty() && report_format!="json" && report_format!="csv" && report_format!="html" && report_format!="all") + throw std::runtime_error("--report must be json, csv, html or all"); + if (seen.count("--report") && report_format.empty()) throw std::runtime_error("empty report format"); + if (seen.count("--output") && (report_format.empty() || output.empty())) throw std::runtime_error("--output requires a nonempty prefix and --report"); + if (seen.count("--rules") && rules_path.empty()) throw std::runtime_error("empty rules path"); + const auto config=rules_path.empty() ? Config::defaults() : Config::load(rules_path); + Analysis analysis(config,ids); + const auto source=command=="capture" ? options.interface : path; + std::cout << "PacketForge | " << command << " | " << source << " | IDS " << (ids ? "enabled" : "disabled") << '\n'; + if (command=="capture") std::cout << "Capture: " << (options.promiscuous ? "promiscuous" : "non-promiscuous") << "; Ctrl+C stops gracefully\n"; + if (policy) std::cout << "Firewall Policy Simulation: no traffic is blocked or forwarded\n"; + auto emit=[&](const Json& alert) { + if (!quiet) std::cout << '[' << alert.at("severity").get() << "] " << alert.at("rule_id").get() << " | " + << alert.at("timestamp").get() << " | " << alert.at("source").get() << " -> " + << alert.at("destination").get() << " | observed=" << alert.at("observed_count") << " threshold=" + << alert.at("threshold") << " window=" << alert.at("detection_window_seconds") << "s\n"; + }; + auto consume=[&](const Packet& p) { + analysis.observe(p,emit); + if (verbose) { + std::cout << iso_time(p.timestamp) << ' ' << p.protocol_name() << " [" << p.source << "]:" << p.source_port + << " -> [" << p.destination << "]:" << p.destination_port << " cap=" << p.captured_length << " wire=" << p.wire_length + << " status=" << status_name(p.status); + if (p.ethernet) std::cout << " mac=" << p.source_mac << "->" << p.destination_mac << " ethertype=" << p.ethertype; + for (auto vlan:p.vlan_ids) std::cout << " vlan=" << vlan; + if (p.ipv4 || p.ipv6) std::cout << " ttl/hop=" << unsigned(p.ttl) << " protocol=" << unsigned(p.protocol); + if (p.fragmented) std::cout << " fragment_offset=" << p.fragment_offset << " more_fragments=" << p.more_fragments; + if (p.arp) std::cout << " arp_opcode=" << p.arp_opcode << " sender_hw=" << p.arp_sender_hardware << " target_hw=" << p.arp_target_hardware; + if (p.transport && (p.protocol==1 || p.protocol==58)) std::cout << " type=" << unsigned(p.icmp_type) << " code=" << unsigned(p.icmp_code); + if (p.protocol==6 && p.transport) std::cout << " flags=" << unsigned(p.tcp_flags) << " seq=" << p.sequence << " ack=" << p.acknowledgment; + if (!p.detail.empty()) std::cout << " (" << p.detail << ')'; + std::cout << '\n'; + } + if (policy && p.status==ParseStatus::ok && !p.source.empty()) std::cout << "Source: " << p.source << " | Destination: [" << p.destination << "]:" + << p.destination_port << " | Policy: " << evaluate_policy(p,config.policy) << '\n'; + }; + auto tick=[&]() { + const auto now=std::max(now_timestamp(),analysis.statistics.last); analysis.flows.expire(now); analysis.detection.expire(now); + if (!quiet) std::cout << "[capture] packets=" << analysis.statistics.packets << " bytes=" << analysis.statistics.observed_bytes + << " active_flows=" << analysis.flows.active_count() << " alerts=" << analysis.total_alerts << std::endl; + }; + const auto result=command=="capture" ? capture_live(options,consume,tick) : analyze_pcap(path,consume,options.count); + if (command=="capture") analysis.flows.expire(std::max(now_timestamp(),analysis.statistics.last),true); + analysis.summary(std::cout); + if (command=="capture") std::cout << "Kernel capture drops: " << result.kernel_drops << " | Interrupted: " << (result.interrupted ? "yes" : "no") << '\n'; + if (!report_format.empty()) { + if (output.empty()) output="reports/packetforge-"+std::to_string(now_timestamp()); + for (const auto& report:write_reports(analysis.report(command,source,result),report_format,output)) std::cout << "Report: " << report << '\n'; + } + return 0; + } catch (const std::exception& error) { std::cerr << "PacketForge error: " << error.what() << '\n'; return 2; } +} +} diff --git a/src/detection/config.cpp b/src/detection/config.cpp new file mode 100644 index 0000000..b797d59 --- /dev/null +++ b/src/detection/config.cpp @@ -0,0 +1,125 @@ +#include "packetforge/config.hpp" +#include +#include +#include +namespace packetforge { +namespace { +void keys(const Json& value, const std::set& allowed, const std::string& context) { + if (!value.is_object()) throw std::runtime_error(context + " must be an object"); + for (auto it=value.begin(); it!=value.end(); ++it) + if (!allowed.count(it.key())) throw std::runtime_error("unknown " + context + " setting: " + it.key()); +} +std::int64_t integer(const Json& value, std::int64_t low, std::int64_t high, const std::string& name) { + if (!value.is_number_integer() || (value.is_number_unsigned() && value.get() > static_cast(high))) + throw std::runtime_error(name + " must be an integer in range"); + const auto result = value.get(); + if (result < low || result > high) throw std::runtime_error(name + " outside range " + std::to_string(low)+".."+std::to_string(high)); + return result; +} +std::string ip(const Json& value) { + if (!value.is_string()) throw std::runtime_error("IP exclusions/policy addresses must be strings"); + const auto text=value.get(); unsigned char buffer[16]{}; char out[INET6_ADDRSTRLEN]{}; + const int family = text.find(':') == std::string::npos ? AF_INET : AF_INET6; + if (inet_pton(family,text.c_str(),buffer)!=1) throw std::runtime_error("invalid literal IP address: "+text); + inet_ntop(family,buffer,out,sizeof(out)); return out; +} +std::set exclusions(const Json& value) { + if (!value.is_array() || value.size()>4096) throw std::runtime_error("exclusions must be an array of at most 4096 IPs"); + std::set result; for (const auto& entry:value) result.insert(ip(entry)); return result; +} +} +Config Config::defaults() { + Config c; + c.rules["POSSIBLE_TCP_PORT_SCAN"] = {true,12,10,30,"MEDIUM",{},{},{}}; + c.rules["HIGH_TCP_SYN_RATE"] = {true,100,10,30,"MEDIUM",{},{},{}}; + c.rules["HIGH_ICMP_ECHO_RATE"] = {true,50,10,30,"LOW",{},{},{}}; + c.rules["SENSITIVE_SERVICE_TRAFFIC"] = {true,1,10,60,"INFO",{22,23,445,3389},{},{}}; + c.rules["CONNECTION_CONCENTRATION"] = {true,40,10,30,"LOW",{},{},{}}; + c.policy = {{"any","any","WOULD_BLOCK",22},{"any","any","WOULD_BLOCK",445},{"any","any","WOULD_ALLOW",-1}}; + return c; +} +Config Config::load(const std::string& path) { + Config config=defaults(); std::ifstream file(path, std::ios::binary); + if (!file) throw std::runtime_error("cannot open rules file: "+path); + file.seekg(0,std::ios::end); if (file.tellg()>1024*1024) throw std::runtime_error("rules file exceeds 1 MiB"); file.seekg(0); + Json root; + // Reject duplicate JSON keys; silently taking the last value is dangerous for rules. + std::vector> object_keys; + auto callback=[&](int depth, Json::parse_event_t event, Json& parsed) { + if (depth>32) throw std::runtime_error("configuration nesting exceeds limit"); + if (event==Json::parse_event_t::object_start) object_keys.emplace_back(); + if (event==Json::parse_event_t::key && !object_keys.back().insert(parsed.get()).second) + throw std::runtime_error("duplicate JSON key: "+parsed.get()); + if (event==Json::parse_event_t::object_end) object_keys.pop_back(); + if (object_keys.size()>32) throw std::runtime_error("configuration nesting exceeds limit"); + return true; + }; + root=Json::parse(file,callback); + keys(root,{"rules","limits","policy"},"configuration"); + if (root.contains("limits")) { + const auto& limits=root.at("limits"); + keys(limits,{"max_flows","max_unique_flows","max_talkers","max_rule_keys","max_rule_events","max_alerts","flow_timeout_seconds"},"limits"); + auto set=[&](const char* name,std::size_t& target,std::int64_t maximum) { + if (limits.contains(name)) target=static_cast(integer(limits.at(name),1,maximum,name)); + }; + set("max_flows",config.max_flows,100000); set("max_unique_flows",config.max_unique_flows,1000000); + set("max_talkers",config.max_talkers,100000); set("max_rule_keys",config.max_rule_keys,10000); + set("max_rule_events",config.max_rule_events,1000000); set("max_alerts",config.max_alerts,100000); + if (limits.contains("flow_timeout_seconds")) config.flow_timeout_seconds=integer(limits.at("flow_timeout_seconds"),1,86400,"flow_timeout_seconds"); + } + if (root.contains("rules")) { + std::set names; for (const auto& item:config.rules) names.insert(item.first); + keys(root.at("rules"),names,"rules"); + for (auto it=root.at("rules").begin(); it!=root.at("rules").end(); ++it) { + const auto& object=it.value(); auto& rule=config.rules.at(it.key()); + keys(object,{"enabled","threshold","window_seconds","cooldown_seconds","severity","ports","exclude_sources","exclude_destinations"},it.key()); + if (object.contains("enabled")) { if (!object.at("enabled").is_boolean()) throw std::runtime_error("enabled must be boolean"); rule.enabled=object.at("enabled").get(); } + if (object.contains("threshold")) rule.threshold=static_cast(integer(object.at("threshold"),1,10000,"threshold")); + if (object.contains("window_seconds")) rule.window_seconds=integer(object.at("window_seconds"),1,3600,"window_seconds"); + if (object.contains("cooldown_seconds")) rule.cooldown_seconds=integer(object.at("cooldown_seconds"),0,86400,"cooldown_seconds"); + if (object.contains("severity")) rule.severity=object.at("severity").get(); + if (!std::set{"INFO","LOW","MEDIUM","HIGH"}.count(rule.severity)) throw std::runtime_error("invalid severity: "+rule.severity); + if (object.contains("ports")) { + if (it.key()!="SENSITIVE_SERVICE_TRAFFIC") throw std::runtime_error("ports is only valid for SENSITIVE_SERVICE_TRAFFIC"); + const auto& ports=object.at("ports"); + if (!ports.is_array() || ports.empty() || ports.size()>1024) throw std::runtime_error("ports must contain 1..1024 integers"); + rule.ports.clear(); for (const auto& port:ports) rule.ports.insert(static_cast(integer(port,1,65535,"port"))); + } + if (object.contains("exclude_sources")) rule.exclude_sources=exclusions(object.at("exclude_sources")); + if (object.contains("exclude_destinations")) rule.exclude_destinations=exclusions(object.at("exclude_destinations")); + if (rule.threshold>config.max_rule_events) throw std::runtime_error("rule threshold exceeds max_rule_events"); + if (it.key()=="POSSIBLE_TCP_PORT_SCAN" && rule.threshold<2) throw std::runtime_error("port-scan threshold must be >= 2"); + } + } + for (const auto& [id,rule]:config.rules) + if (rule.enabled && rule.threshold>config.max_rule_events) throw std::runtime_error(id+" threshold exceeds max_rule_events"); + if (root.contains("policy")) { + if (!root.at("policy").is_array() || root.at("policy").size()>1024) throw std::runtime_error("policy must be an array of at most 1024 rules"); + config.policy.clear(); + for (const auto& item:root.at("policy")) { + keys(item,{"source","destination","destination_port","action"},"policy"); PolicyRule rule; + if (item.contains("source") && item.at("source")!="any") rule.source=ip(item.at("source")); + if (item.contains("destination") && item.at("destination")!="any") rule.destination=ip(item.at("destination")); + if (item.contains("destination_port")) rule.destination_port=static_cast(integer(item.at("destination_port"),-1,65535,"destination_port")); + rule.action=item.at("action").get(); + if (rule.action!="WOULD_ALLOW" && rule.action!="WOULD_BLOCK") throw std::runtime_error("policy action must be WOULD_ALLOW or WOULD_BLOCK"); + config.policy.push_back(rule); + } + } + return config; +} +Json Config::json() const { + Json result; result["rules"]=Json::object(); + for (const auto& [id,r]:rules) { + result["rules"][id]={{"enabled",r.enabled},{"threshold",r.threshold},{"window_seconds",r.window_seconds}, + {"cooldown_seconds",r.cooldown_seconds},{"severity",r.severity}, + {"exclude_sources",r.exclude_sources},{"exclude_destinations",r.exclude_destinations}}; + if (id=="SENSITIVE_SERVICE_TRAFFIC") result["rules"][id]["ports"]=r.ports; + } + result["limits"]={{"max_flows",max_flows},{"max_unique_flows",max_unique_flows},{"max_talkers",max_talkers}, + {"max_rule_keys",max_rule_keys},{"max_rule_events",max_rule_events},{"max_alerts",max_alerts},{"flow_timeout_seconds",flow_timeout_seconds}}; + result["policy"]=Json::array(); + for (const auto& r:policy) result["policy"].push_back({{"source",r.source},{"destination",r.destination},{"destination_port",r.destination_port},{"action",r.action}}); + return result; +} +} diff --git a/src/detection/detection.cpp b/src/detection/detection.cpp new file mode 100644 index 0000000..9f7a99b --- /dev/null +++ b/src/detection/detection.cpp @@ -0,0 +1,104 @@ +#include "packetforge/detection.hpp" +#include +#include +#include +namespace packetforge { +void DetectionEngine::trim(State& state, Runtime& runtime, Timestamp now, const RuleConfig& rule) { + // Half-open window (now-window, now]; events at the left boundary expire. + while (!state.events.empty() && now-state.events.front().time>=rule.window_seconds*second) { + state.events.pop_front(); --runtime.events; + } +} +void DetectionEngine::expire(Timestamp now) { + if (last_sweep_>=0 && now-last_sweep_second,runtime,now,rule); + if (it->second.events.empty() && (!it->second.alerted || now-it->second.last_alert>=rule.cooldown_seconds*second)) + it=runtime.states.erase(it); + else ++it; + } + } +} +std::vector DetectionEngine::observe(const Packet& p) { + expire(p.timestamp); std::vector alerts; + if (p.status!=ParseStatus::ok || !p.transport || p.fragmented) return alerts; + for (const auto& [id,rule]:config_.rules) { + if (!rule.enabled || rule.exclude_sources.count(p.source) || rule.exclude_destinations.count(p.destination)) continue; + const bool sensitive=id=="SENSITIVE_SERVICE_TRAFFIC", concentration=id=="CONNECTION_CONCENTRATION"; + if (sensitive) { + if ((p.protocol!=6 && p.protocol!=17) || (!rule.ports.count(p.source_port) && !rule.ports.count(p.destination_port))) continue; + } else if (id=="HIGH_ICMP_ECHO_RATE") { if (!p.echo_request) continue; } + else if (!p.syn_attempt()) continue; + auto& runtime=runtime_.at(id); ++runtime.matched; + const auto service_port=rule.ports.count(p.destination_port) ? p.destination_port : p.source_port; + std::string key=concentration ? p.source : p.source+"|"+p.destination; + if (sensitive) key+="|"+std::to_string(p.protocol)+"|"+std::to_string(service_port); + auto found=runtime.states.find(key); + if (found==runtime.states.end()) { + if (runtime.states.size()>=config_.max_rule_keys) { ++runtime.dropped_keys; continue; } + found=runtime.states.emplace(key,State{}).first; + } + auto& state=found->second; trim(state,runtime,p.timestamp,rule); state.last_seen=p.timestamp; + if (runtime.events>=config_.max_rule_events) { ++runtime.dropped_events; continue; } + const auto attempt=p.destination+"|"+std::to_string(p.source_port)+"|"+std::to_string(p.destination_port)+"|"+std::to_string(p.sequence); + state.events.push_back({p.timestamp,p.destination_port,p.destination,attempt}); ++runtime.events; + std::set ports; + std::set attempts,destinations; + std::map> ports_by_host; + for (const auto& event:state.events) { + ports.insert(event.port); destinations.insert(event.destination); + if (concentration) { attempts.insert(event.attempt); ports_by_host[event.destination].insert(event.port); } + } + const std::size_t count=id=="POSSIBLE_TCP_PORT_SCAN" ? ports.size() : concentration ? attempts.size() : state.events.size(); + if (count=scan.threshold) scan_shape=true; + if (scan_shape) { ++runtime.scan_suppressed; continue; } + } + if (state.alerted && (p.timestamp-state.last_alert(0,p.timestamp-rule.window_seconds*second))}, + {"window_end",iso_time(p.timestamp)},{"window_interval","(start, end]"}}; + if (concentration) evidence["distinct_connection_attempts"]=attempts.size(); + if (sensitive) evidence["observed_service_port"]=service_port; + if (p.protocol==6) evidence["trigger_tcp_flags"]=p.tcp_flags; + const std::string limitation=sensitive ? "Informational observation only. Service access can be authorized; port number does not prove application identity." + : id=="HIGH_ICMP_ECHO_RATE" ? "Heuristic only. Monitoring and diagnostics can generate echo bursts." + : id=="HIGH_TCP_SYN_RATE" ? "Heuristic only. Retransmissions, busy clients and capture duplicates can raise SYN counts; this does not confirm denial of service." + : "Heuristic only. Authorized scanning, retries, NAT aggregation and incomplete visibility can produce similar metadata; no compromise is confirmed."; + alerts.push_back({{"alert_id",alert_id.str()},{"rule_id",id},{"title",title},{"timestamp",iso_time(p.timestamp)}, + {"timestamp_ns",p.timestamp},{"severity",rule.severity},{"source",p.source}, + {"destination",concentration && destinations.size()>1 ? "multiple observed destinations" : p.destination}, + {"source_port",p.source_port},{"destination_port",p.destination_port},{"detection_window_seconds",rule.window_seconds}, + {"observed_count",count},{"threshold",rule.threshold},{"evidence",evidence},{"confidence","metadata heuristic"}, + {"limitations",limitation},{"recommendation",sensitive ? "Confirm that service access matches policy and inspect authorized service logs." + : "Validate against the traffic baseline, approved scans and endpoint/service logs before responding."}, + {"mitre_technique",id=="POSSIBLE_TCP_PORT_SCAN" ? Json("T1046 - Network Service Discovery") : Json(nullptr)}}); + } + return alerts; +} +Json DetectionEngine::counters() const { + Json counters=Json::object(); + for (const auto& [id,runtime]:runtime_) counters[id]={{"matched_packets",runtime.matched},{"alerts",runtime.alerts}, + {"cooldown_suppressed",runtime.cooldown_suppressed},{"scan_overlap_suppressed",runtime.scan_suppressed}, + {"dropped_events",runtime.dropped_events},{"dropped_keys",runtime.dropped_keys}, + {"retained_events",runtime.events},{"retained_keys",runtime.states.size()}}; + return counters; +} +} diff --git a/src/flows/flows.cpp b/src/flows/flows.cpp new file mode 100644 index 0000000..3ece9a8 --- /dev/null +++ b/src/flows/flows.cpp @@ -0,0 +1,48 @@ +#include "packetforge/flows.hpp" +#include +namespace packetforge { +Json Flow::json() const { + return {{"source",key.source},{"destination",key.destination},{"source_port",key.source_port}, + {"destination_port",key.destination_port},{"protocol",key.protocol},{"packets",packets}, + {"observed_bytes",observed_bytes},{"wire_bytes",wire_bytes},{"first_seen",iso_time(first)}, + {"last_seen",iso_time(last)},{"first_seen_ns",first},{"last_seen_ns",last}, + {"duration_seconds",static_cast(last-first)/second},{"tcp_flags",tcp_flags}, + {"direction","source_to_destination"}}; +} +void FlowTable::archive(std::map::iterator entry) { + if (closed_.size()==config_.max_flows) { closed_.pop_front(); ++archives_discarded; } + closed_.push_back(entry->second); active_.erase(entry); +} +void FlowTable::expire(Timestamp now, bool force) { + if (!force && last_sweep_>=0 && now-last_sweep_second.last>=config_.flow_timeout_seconds*second) { auto old=it++; archive(old); ++expired; } + else ++it; + } +} +void FlowTable::observe(const Packet& p) { + expire(p.timestamp); + if (p.status!=ParseStatus::ok || !p.transport || p.fragmented || (p.protocol!=6 && p.protocol!=17)) return; + FlowKey key{p.source,p.destination,p.source_port,p.destination_port,p.protocol}; + if (!unique_.count(key)) { + if (unique_.size()second; ++f.packets; f.observed_bytes+=p.captured_length; f.wire_bytes+=p.wire_length; + f.last=p.timestamp; f.tcp_flags|=p.tcp_flags; +} +Json FlowTable::json() const { + Json flows=Json::array(); + for (const auto& flow:closed_) { auto j=flow.json(); j["active"]=false; flows.push_back(std::move(j)); } + for (const auto& [key,flow]:active_) { (void)key; auto j=flow.json(); j["active"]=true; flows.push_back(std::move(j)); } + return flows; +} +} diff --git a/src/forwarder.cpp b/src/forwarder.cpp index a10d940..7c543d3 100644 --- a/src/forwarder.cpp +++ b/src/forwarder.cpp @@ -1,88 +1,3 @@ -#include -#include -#include -#include -#include -#include -#include -#include "../include/headers.hpp" -#include "../include/rules.hpp" - -void print_mac(uint8_t* mac) { - printf("%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -} - -// Check packet against rule table, return matching action -Action checkRules(const std::string& src_ip, const std::string& dst_ip, int dst_port) { - for (auto& rule : ruleTable) { - bool src_match = (rule.src_ip == "any" || rule.src_ip == src_ip); - bool dst_match = (rule.dst_ip == "any" || rule.dst_ip == dst_ip); - bool port_match = (rule.dst_port == -1 || rule.dst_port == dst_port); - - if (src_match && dst_match && port_match) { - return rule.action; - } - } - return Action::ALLOW; // fallback -} - -int main() { - int sock = socket(AF_PACKET, SOCK_RAW, htons(0x0003)); // ETH_P_ALL - - if (sock < 0) { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return 1; - } - - std::cout << "PacketForge running. Listening + filtering... (Ctrl+C to stop)\n" << std::endl; - - unsigned char buffer[65536]; - long total = 0, allowed = 0, dropped = 0; - - while (true) { - int data_size = recvfrom(sock, buffer, sizeof(buffer), 0, nullptr, nullptr); - if (data_size < 0) break; - - total++; - EthHeader* eth = (EthHeader*)buffer; - uint16_t ethertype = ntohs(eth->ethertype); - - if (ethertype != 0x0800) continue; // only handle IPv4 for forwarding - - IPHeader* ip = (IPHeader*)(buffer + sizeof(EthHeader)); - int ip_header_len = (ip->ver_ihl & 0x0F) * 4; - - struct in_addr src, dst; - src.s_addr = ip->src_ip; - dst.s_addr = ip->dst_ip; - std::string src_ip = inet_ntoa(src); - std::string dst_ip = inet_ntoa(dst); - - int dst_port = -1; - unsigned char* transport = buffer + sizeof(EthHeader) + ip_header_len; - - if (ip->protocol == 6) { - TCPHeader* tcp = (TCPHeader*)transport; - dst_port = ntohs(tcp->dst_port); - } else if (ip->protocol == 17) { - UDPHeader* udp = (UDPHeader*)transport; - dst_port = ntohs(udp->dst_port); - } - - Action decision = checkRules(src_ip, dst_ip, dst_port); - - printf("Src: %s -> Dst: %s:%d | Protocol: %d | Decision: %s\n", - src_ip.c_str(), dst_ip.c_str(), dst_port, ip->protocol, - decision == Action::ALLOW ? "ALLOW" : "DROP"); - - if (decision == Action::ALLOW) allowed++; - else dropped++; - - if (total % 20 == 0) { - printf("\n[Stats] Total: %ld | Allowed: %ld | Dropped: %ld\n\n", total, allowed, dropped); - } - } - - close(sock); - return 0; -} +#include "packetforge/cli.hpp" +// Historical name only: policy simulation observes packets and never forwards/blocks. +int main(int argc, char** argv) { return packetforge::run_cli(argc, argv, true, true); } diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..e7bb449 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,2 @@ +#include "packetforge/cli.hpp" +int main(int argc, char** argv) { return packetforge::run_cli(argc, argv); } diff --git a/src/parsers/packet.cpp b/src/parsers/packet.cpp new file mode 100644 index 0000000..b9afbaa --- /dev/null +++ b/src/parsers/packet.cpp @@ -0,0 +1,180 @@ +#include "packetforge/packet.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace packetforge { +namespace { +struct Failure { ParseStatus status; const char* reason; }; +class Decoder { + const std::uint8_t* data_; + std::size_t end_; +public: + Decoder(const std::uint8_t* data, std::size_t size) : data_(data), end_(size) {} + void need(std::size_t offset, std::size_t length) const { + if (offset > end_ || length > end_ - offset) + throw Failure{ParseStatus::truncated, "captured header incomplete"}; + } + void limit(std::size_t end) { end_ = std::min(end_, end); } + std::uint8_t u8(std::size_t i) const { need(i, 1); return data_[i]; } + std::uint16_t u16(std::size_t i) const { + need(i, 2); return static_cast((data_[i] << 8) | data_[i+1]); + } + std::uint32_t u32(std::size_t i) const { + need(i, 4); return (std::uint32_t(data_[i]) << 24) | (std::uint32_t(data_[i+1]) << 16) + | (std::uint32_t(data_[i+2]) << 8) | data_[i+3]; + } + std::string mac(std::size_t i) const { + need(i, 6); char out[18]; + std::snprintf(out, sizeof(out), "%02x:%02x:%02x:%02x:%02x:%02x", data_[i], data_[i+1], + data_[i+2], data_[i+3], data_[i+4], data_[i+5]); + return out; + } + std::string ip(std::size_t i, bool v6) const { + need(i, v6 ? 16 : 4); char out[INET6_ADDRSTRLEN]{}; + inet_ntop(v6 ? AF_INET6 : AF_INET, data_ + i, out, sizeof(out)); return out; + } +}; +void malformed(bool condition, const char* reason) { + if (condition) throw Failure{ParseStatus::malformed, reason}; +} +void unsupported(const char* reason) { throw Failure{ParseStatus::unsupported, reason}; } +} +const char* status_name(ParseStatus status) { + switch (status) { + case ParseStatus::ok: return "ok"; + case ParseStatus::truncated: return "truncated"; + case ParseStatus::malformed: return "malformed"; + case ParseStatus::unsupported: return "unsupported"; + } + return "unsupported"; +} +std::string Packet::protocol_name() const { + if (arp) return "ARP"; + if (ipv4 || ipv6) { + if (protocol == 6) return "TCP"; + if (protocol == 17) return "UDP"; + if (protocol == 1 || protocol == 58) return "ICMP"; + return ipv6 ? "IPv6-other" : "IPv4-other"; + } + return "Ethernet-other"; +} +Packet parse_packet(const std::uint8_t* data, std::size_t size, std::uint32_t wire, Timestamp ts) { + Packet p; p.timestamp = ts; p.wire_length = wire; + p.captured_length = static_cast(std::min(size, UINT32_MAX)); + p.capture_truncated = size < wire; + Decoder b(data, size); + try { + malformed(size > wire || size > UINT32_MAX || (!data && size), "invalid capture/wire length"); + b.need(0, 14); p.ethernet = true; + p.destination_mac = b.mac(0); p.source_mac = b.mac(6); p.ethertype = b.u16(12); + std::size_t o = 14; + while (p.ethertype == 0x8100 || p.ethertype == 0x88a8) { + if (p.vlan_ids.size() == 2) unsupported("more than two VLAN tags"); + b.need(o, 4); p.vlan_ids.push_back(b.u16(o) & 0x0fff); + p.ethertype = b.u16(o+2); o += 4; + } + if (p.ethertype == 0x0806) { + b.need(o, 8); p.arp_opcode = b.u16(o+6); + const auto hlen = b.u8(o+4), plen = b.u8(o+5); + b.need(o+8, 2U * hlen + 2U * plen); + if (b.u16(o) != 1 || b.u16(o+2) != 0x0800 || hlen != 6 || plen != 4) + unsupported("ARP address format is not Ethernet/IPv4"); + p.arp = true; p.arp_sender_hardware = b.mac(o+8); p.source = b.ip(o+14, false); + p.arp_target_hardware = b.mac(o+18); p.destination = b.ip(o+24, false); + return p; + } + std::size_t end = 0; + if (p.ethertype == 0x0800) { + b.need(o, 20); p.version = b.u8(o) >> 4; p.ip_header_length = (b.u8(o) & 15) * 4; + malformed(p.version != 4 || p.ip_header_length < 20, "invalid IPv4 version or IHL"); + p.ip_total_length = b.u16(o+2); + malformed(p.ip_total_length < p.ip_header_length, "IPv4 total length smaller than header"); + malformed(p.ip_total_length > wire - o, "IPv4 total length exceeds wire frame"); + b.need(o, p.ip_header_length); p.ipv4 = true; + p.source = b.ip(o+12, false); p.destination = b.ip(o+16, false); + p.ttl = b.u8(o+8); p.protocol = b.u8(o+9); p.next_header = p.protocol; p.ip_id = b.u16(o+4); + const auto fragment = b.u16(o+6); + p.fragment_offset = static_cast((fragment & 0x1fff) * 8); + p.more_fragments = (fragment & 0x2000) != 0; p.dont_fragment = (fragment & 0x4000) != 0; + p.fragmented = p.more_fragments || p.fragment_offset != 0; + malformed((fragment & 0x8000) || (p.dont_fragment && p.fragmented), "invalid IPv4 fragmentation flags"); + malformed(p.more_fragments && ((p.ip_total_length - p.ip_header_length) % 8 != 0), + "non-final IPv4 fragment payload not multiple of eight"); + end = o + p.ip_total_length; b.need(o, p.ip_total_length); b.limit(end); o += p.ip_header_length; + if (p.fragment_offset) { p.detail = "non-initial IPv4 fragment; transport skipped"; return p; } + } else if (p.ethertype == 0x86dd) { + b.need(o, 40); p.version = b.u8(o) >> 4; + malformed(p.version != 6, "invalid IPv6 version"); p.ipv6 = true; + p.source = b.ip(o+8, true); p.destination = b.ip(o+24, true); + p.ipv6_payload_length = b.u16(o+4); p.next_header = b.u8(o+6); p.protocol = p.next_header; p.ttl = b.u8(o+7); + if (p.ipv6_payload_length == 0 && p.protocol != 59) unsupported("IPv6 jumbograms/zero-length payload unsupported"); + malformed(40U + p.ipv6_payload_length > wire - o, "IPv6 payload exceeds wire frame"); + end = o + 40 + p.ipv6_payload_length; b.need(o, 40 + p.ipv6_payload_length); b.limit(end); o += 40; + unsigned extensions = 0; bool seen_fragment = false; + while (p.protocol == 0 || p.protocol == 43 || p.protocol == 60 || p.protocol == 44 || p.protocol == 51) { + if (++extensions > 8) unsupported("IPv6 extension chain limit reached"); + malformed(p.protocol == 0 && extensions != 1, "hop-by-hop header must be first"); + if (end - o < 2) throw Failure{ParseStatus::malformed, "IPv6 extension exceeds payload"}; + std::size_t length = (std::size_t(b.u8(o+1)) + 1) * 8; + if (p.protocol == 51) { + length = (std::size_t(b.u8(o+1)) + 2) * 4; + malformed(length < 12, "IPv6 AH header smaller than fixed fields"); + } + if (p.protocol == 44) { + malformed(seen_fragment, "duplicate IPv6 fragment header"); seen_fragment = true; length = 8; + malformed(end - o < length, "IPv6 fragment exceeds payload"); b.need(o, length); + const auto bits = b.u16(o+2); + malformed((bits & 6) != 0 || b.u8(o+1) != 0, "invalid IPv6 fragment reserved bits"); + p.fragment_offset = bits & 0xfff8; p.more_fragments = bits & 1; + p.fragmented = p.fragment_offset != 0 || p.more_fragments; p.ipv6_fragment_id = b.u32(o+4); + malformed(p.more_fragments && ((end-o-8) % 8 != 0), "non-final IPv6 fragment length"); + } + malformed(length > end - o, "IPv6 extension exceeds payload"); b.need(o, length); + p.protocol = b.u8(o); o += length; + if (p.fragment_offset) { p.detail = "non-initial IPv6 fragment; transport skipped"; return p; } + } + if (p.protocol == 59) { p.detail = "IPv6 no next header"; return p; } + } else { unsupported(p.ethertype <= 1500 ? "IEEE 802.3 LLC unsupported" : "EtherType unsupported"); } + const auto remaining = end - o; + auto require_transport = [&](std::size_t n) { + if (remaining < n && p.fragmented) unsupported("initial fragment lacks complete transport header"); + malformed(remaining < n, "transport header exceeds IP payload"); b.need(o, n); + }; + if (p.protocol == 6) { + require_transport(20); p.tcp_header_length = (b.u8(o+12) >> 4) * 4; + malformed(p.tcp_header_length < 20, "invalid TCP data offset"); require_transport(p.tcp_header_length); + p.source_port = b.u16(o); p.destination_port = b.u16(o+2); + p.sequence = b.u32(o+4); p.acknowledgment = b.u32(o+8); + p.tcp_flags = b.u8(o+13); p.tcp_window = b.u16(o+14); p.transport = true; + } else if (p.protocol == 17) { + require_transport(8); p.udp_length = b.u16(o+4); + malformed(p.udp_length < 8 || (!p.fragmented && p.udp_length > remaining), "invalid UDP length"); + p.source_port = b.u16(o); p.destination_port = b.u16(o+2); p.transport = true; + } else if ((p.ipv4 && p.protocol == 1) || (p.ipv6 && p.protocol == 58)) { + require_transport(4); p.icmp_type = b.u8(o); p.icmp_code = b.u8(o+1); + p.echo_request = p.icmp_code == 0 && p.icmp_type == (p.ipv6 ? 128 : 8); + p.echo_reply = p.icmp_code == 0 && p.icmp_type == (p.ipv6 ? 129 : 0); + if (p.echo_request || p.echo_reply) require_transport(8); + p.transport = true; + } else unsupported("IP protocol/extension unsupported (including ESP)"); + } catch (const Failure& error) { p.status = error.status; p.detail = error.reason; p.transport = false; } + return p; +} +Timestamp now_timestamp() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} +std::string iso_time(Timestamp timestamp) { + const auto whole = timestamp / second; + const std::time_t seconds = static_cast(whole); + std::tm tm{}; if (!gmtime_r(&seconds, &tm)) return "invalid timestamp"; + std::ostringstream out; + out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%S") << '.' << std::setw(9) << std::setfill('0') + << (timestamp % second) << 'Z'; return out.str(); +} +} diff --git a/src/reporting/reporting.cpp b/src/reporting/reporting.cpp new file mode 100644 index 0000000..b89f912 --- /dev/null +++ b/src/reporting/reporting.cpp @@ -0,0 +1,125 @@ +#include "packetforge/reporting.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +namespace packetforge { +std::string html_escape(const std::string& value) { + std::string result; + for (char c:value) switch (c) { + case '&':result+="&";break; case '<':result+="<";break; case '>':result+=">";break; + case '"':result+=""";break; case '\'':result+="'";break; default:result+=c; + } + return result; +} +std::string csv_field(const std::string& value) { + std::string result="\""; + // Prevent spreadsheet formula execution as well as ordinary CSV quoting. + if (!value.empty() && (value[0]=='=' || value[0]=='+' || value[0]=='-' || value[0]=='@' || value[0]=='\t' || value[0]=='\r' || value[0]=='\n')) result+='\''; + for (char c:value) { if (c=='"') result+='"'; result+=c; } result+='"'; return result; +} +namespace { +std::string value(const Json& j) { return j.is_string() ? j.get() : j.dump(); } +std::string table(const Json& rows,const std::vector& columns) { + std::ostringstream out; out << "
"; + for (const auto& column:columns) out << ""; + out << ""; + for (const auto& row:rows) { + out << ""; for (const auto& column:columns) out << ""; out << ""; + } + out << "
" << html_escape(column) << "
" << html_escape(value(row.at(column))) << "
"; return out.str(); +} +std::string csv(const Json& rows,const std::vector& columns) { + std::ostringstream out; + for (std::size_t i=0;i + +PacketForge — Investigation Report

Network security investigation

PacketForge

Passive packet analysis · Explainable intrusion detection

)HTML"; + out << "

Mode: " << html_escape(value(metadata.at("mode"))) << " · Source: " << html_escape(value(metadata.at("source"))) << "

" + << "

" << html_escape(value(metadata.at("first_packet"))) << " → " << html_escape(value(metadata.at("last_packet"))) << "

"; + out << "
"; + for (const auto& key:{"packets","observed_bytes","unique_flows","total_ids_alerts"}) + out << "
" << key << "" << html_escape(value(stats.at(key))) << "
"; + out << "

Protocol distribution

Layer counters overlap; Ethernet, IP and transport counts are not additive.

"; + const double total=stats.at("packets").get(); + for (const auto& [name,count]:stats.at("protocols").items()) out << "
" << html_escape(name) << " " << count + << "
"; + out << "

Top sources

" << table(stats.at("top_sources"),{"address","packets"}) + << "

Top destinations

" << table(stats.at("top_destinations"),{"address","packets"}) + << "

Destination ports

" << table(stats.at("destination_ports"),{"port","packets"}) << "

Security observations

"; + if (data.at("alerts").empty()) out << "

No alerts were retained. This does not establish that traffic is safe. IDS enabled: " << metadata.at("ids_enabled") << ".

"; + for (const auto& alert:data.at("alerts")) { + out << "
" << html_escape(value(alert.at("severity"))) << "

" << html_escape(value(alert.at("title"))) + << "

" << html_escape(value(alert.at("alert_id"))) << " · " << html_escape(value(alert.at("rule_id"))) << "

" + << html_escape(value(alert.at("timestamp"))) << " · " << html_escape(value(alert.at("source"))) << " → " << html_escape(value(alert.at("destination"))) + << "

Observed " << alert.at("observed_count") << " / threshold " << alert.at("threshold") << " within " << alert.at("detection_window_seconds") << " seconds.

" + << "
" << html_escape(alert.at("evidence").dump(2)) << "

" << html_escape(value(alert.at("limitations"))) + << "

Recommendation: " << html_escape(value(alert.at("recommendation"))) << "

MITRE: " << html_escape(value(alert.at("mitre_technique"))) << "

"; + } + out << "

Directional flows

" << table(data.at("flows"),{"source","source_port","destination","destination_port","protocol","packets","observed_bytes","duration_seconds","active"}); + for (const auto& section:{"statistics","metadata","rules","rule_counters"}) + out << "

" << section << "

" << html_escape(data.at(section).dump(2)) << "
"; + out << "

Investigation limitations

    "; + for (const auto& limitation:data.at("limitations")) out << "
  • " << html_escape(value(limitation)) << "
  • "; + out << "
PacketForge · Mayank Kumar Karn
Exported " << html_escape(value(metadata.at("export_timestamp"))) + << " · Standalone offline report
"; return out.str(); +} +std::vector write_reports(const Json& data,const std::string& format,const std::string& prefix) { + if (format!="json" && format!="csv" && format!="html" && format!="all") throw std::runtime_error("invalid report format"); + std::vector> files; + if (format=="json" || format=="all") files.emplace_back(prefix+".json",data.dump(2)+"\n"); + if (format=="html" || format=="all") files.emplace_back(prefix+".html",html_report(data)); + if (format=="csv" || format=="all") { + files.emplace_back(prefix+"-alerts.csv",csv(data.at("alerts"),{"alert_id","rule_id","title","timestamp","severity","source","destination","source_port","destination_port","detection_window_seconds","observed_count","threshold","evidence","confidence","limitations","recommendation","mitre_technique"})); + files.emplace_back(prefix+"-flows.csv",csv(data.at("flows"),{"source","destination","source_port","destination_port","protocol","packets","observed_bytes","wire_bytes","first_seen","last_seen","duration_seconds","tcp_flags","active"})); + } + // Refuse overwrites so reports cannot accidentally destroy an input/config file. + for (const auto& [path,content]:files) { (void)content; if (std::filesystem::exists(path)) throw std::runtime_error("report already exists: "+path+"; choose another --output prefix"); } + std::vector paths; + for (const auto& [path,content]:files) { + const auto parent=std::filesystem::path(path).parent_path(); if (!parent.empty()) std::filesystem::create_directories(parent); + // Exclusive creation closes the race between the preflight check and writing. + // Investigation metadata is private to the owner on POSIX filesystems. + const int fd=::open(path.c_str(),O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,0600); + if (fd<0) throw std::runtime_error("cannot create report: "+path+": "+std::strerror(errno)); + struct File { int fd; ~File() { if (fd>=0) ::close(fd); } } file{fd}; + std::size_t offset=0; + while (offset(written); + } + const int closed=::close(fd); file.fd=-1; + if (closed<0) throw std::runtime_error("report close failed: "+path); + paths.push_back(path); + } + return paths; +} +} diff --git a/src/sniffer.cpp b/src/sniffer.cpp index 7c2f154..4380785 100644 --- a/src/sniffer.cpp +++ b/src/sniffer.cpp @@ -1,85 +1,3 @@ -#include -#include -#include -#include -#include -#include -#include -#include "../include/headers.hpp" - -void print_mac(uint8_t* mac) { - printf("%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -} - -int main() { - int sock = socket(AF_PACKET, SOCK_RAW, htons(0x0003)); // ETH_P_ALL - - if (sock < 0) { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return 1; - } - - std::cout << "Raw socket created. Listening for packets... (Ctrl+C to stop)\n" << std::endl; - - unsigned char buffer[65536]; - - while (true) { - int data_size = recvfrom(sock, buffer, sizeof(buffer), 0, nullptr, nullptr); - - if (data_size < 0) { - std::cerr << "recvfrom failed: " << strerror(errno) << std::endl; - break; - } - - EthHeader* eth = (EthHeader*)buffer; - uint16_t ethertype = ntohs(eth->ethertype); - - printf("--- Packet (%d bytes) ---\n", data_size); - printf("Src MAC: "); print_mac(eth->src_mac); printf("\n"); - printf("Dst MAC: "); print_mac(eth->dst_mac); printf("\n"); - printf("EtherType: 0x%04x\n", ethertype); - - if (ethertype == 0x0800) { // IPv4 - IPHeader* ip = (IPHeader*)(buffer + sizeof(EthHeader)); - int ip_header_len = (ip->ver_ihl & 0x0F) * 4; - - struct in_addr src, dst; - src.s_addr = ip->src_ip; - dst.s_addr = ip->dst_ip; - - printf("Src IP: %s\n", inet_ntoa(src)); - printf("Dst IP: %s\n", inet_ntoa(dst)); - printf("Protocol: %d ", ip->protocol); - - unsigned char* transport = buffer + sizeof(EthHeader) + ip_header_len; - - if (ip->protocol == 6) { // TCP - TCPHeader* tcp = (TCPHeader*)transport; - printf("(TCP)\n"); - printf("Src Port: %d\n", ntohs(tcp->src_port)); - printf("Dst Port: %d\n", ntohs(tcp->dst_port)); - } - else if (ip->protocol == 17) { // UDP - UDPHeader* udp = (UDPHeader*)transport; - printf("(UDP)\n"); - printf("Src Port: %d\n", ntohs(udp->src_port)); - printf("Dst Port: %d\n", ntohs(udp->dst_port)); - } - else if (ip->protocol == 1) { - printf("(ICMP)\n"); - } - else { - printf("(Other)\n"); - } - } - else if (ethertype == 0x0806) { - printf("ARP packet\n"); - } - - printf("\n"); - } - - close(sock); - return 0; -} - +#include "packetforge/cli.hpp" +// Preserve the original teaching entry point using the safe, shared pipeline. +int main(int argc, char** argv) { return packetforge::run_cli(argc, argv, true); } diff --git a/src/statistics/analysis.cpp b/src/statistics/analysis.cpp new file mode 100644 index 0000000..1ecb9c6 --- /dev/null +++ b/src/statistics/analysis.cpp @@ -0,0 +1,59 @@ +#include "packetforge/analysis.hpp" +#include +#include +#include +namespace packetforge { +void Analysis::observe(const Packet& p,const std::function& emit) { + if (p.timestamp<0 || p.timestamp()]; + if (emit) emit(alert); + if (alerts.size()() : item["port"].dump()) << '=' << item["packets"]; + out << '\n'; + } + for (const auto& [id,count]:alert_counts) out << " " << id << ": " << count << '\n'; + if (flows.evictions || flows.archives_discarded || statistics.omitted_sources || statistics.omitted_destinations || alerts_not_retained) + out << "Warning: retention limits reached; review report counters for omitted evidence.\n"; + const auto counters=detection.counters(); + for (const auto& [id,counter]:counters.items()) + if (counter["dropped_keys"].get() || counter["dropped_events"].get()) + out << "Warning: " << id << " hit a state limit; detections can be missed.\n"; +} +} diff --git a/src/statistics/statistics.cpp b/src/statistics/statistics.cpp new file mode 100644 index 0000000..ccd6fff --- /dev/null +++ b/src/statistics/statistics.cpp @@ -0,0 +1,48 @@ +#include "packetforge/statistics.hpp" +#include +namespace packetforge { +void Statistics::talker(std::map& table,const std::string& address,std::uint64_t& omitted) { + if (address.empty()) return; + auto it=table.find(address); + if (it!=table.end()) ++it->second; + else if (table.size()(last-first)/second : 0; } +Json Statistics::json() const { + auto top=[](const auto& values) { + std::vector> rows(values.begin(),values.end()); + std::sort(rows.begin(),rows.end(),[](const auto& a,const auto& b) { return a.second!=b.second ? a.second>b.second : a.first(rows.size(),10);++i) out.push_back({{"address",rows[i].first},{"packets",rows[i].second}}); + return out; + }; + Json destination_ports=Json::array(); + std::vector> ranked(ports.begin(),ports.end()); + std::sort(ranked.begin(),ranked.end(),[](const auto& a,const auto& b) { return a.second!=b.second ? a.second>b.second : a.first(ranked.size(),10);++i) destination_ports.push_back({{"port",ranked[i].first},{"packets",ranked[i].second}}); + const auto seconds=duration(); + return {{"packets",packets},{"observed_bytes",observed_bytes},{"wire_bytes",wire_bytes},{"truncated",truncated}, + {"malformed",malformed},{"unsupported",unsupported},{"duration_seconds",seconds}, + {"packets_per_second",seconds>0 ? Json(static_cast(packets)/seconds) : Json(nullptr)}, + {"bytes_per_second",seconds>0 ? Json(static_cast(observed_bytes)/seconds) : Json(nullptr)}, + {"protocols",protocols},{"top_sources",top(sources)},{"top_destinations",top(destinations)}, + {"destination_ports",destination_ports},{"omitted_source_observations",omitted_sources}, + {"omitted_destination_observations",omitted_destinations}}; +} +} diff --git a/tests/integration.py b/tests/integration.py new file mode 100644 index 0000000..169bd75 --- /dev/null +++ b/tests/integration.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""End-to-end offline checks; no root, third-party Python packages or network needed.""" +import csv +import json +from pathlib import Path +import subprocess +import sys +import tempfile + +binary = Path(sys.argv[1]).resolve() +root = Path(sys.argv[2]).resolve() +checks = 0 + +def run(args, code=0): + global checks + result = subprocess.run([str(binary)] + list(map(str,args)), capture_output=True, text=True) + checks += 1 + assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr) + return result + +run(['--help']) +for args in [['analyze'], ['analyze','--pcap','missing.pcap'], ['capture','--count','-1'], ['wat'], + ['analyze','--pcap',root/'samples/demo.pcap','--duration','1'], + ['capture','--interface','lo','--duration','nan'],['capture','--interface','lo','--duration','0'], + ['analyze','--pcap',root/'samples/demo.pcap','--count','1x'], + ['analyze','--pcap',root/'samples/demo.pcap','--ids','--no-ids'], + ['analyze','--pcap',root/'samples/demo.pcap','--ids','--ids'], + ['analyze','--pcap',root/'samples/demo.pcap','--report','pdf'], + ['analyze','--pcap',root/'samples/demo.pcap','--output','foo'], + ['interfaces','--count','1']]: + run(args,2) + +with tempfile.TemporaryDirectory(prefix='packetforge-tests-') as temp: + temp = Path(temp) + expected = json.loads((root/'samples/expected.json').read_text()) + for name, case in expected.items(): + prefix = temp / name + result = run(['analyze','--pcap',root/'samples'/name,'--rules',root/'config/rules.json','--report','all','--output',prefix]) + report = json.loads(Path(str(prefix)+'.json').read_text()) + assert report['statistics']['packets'] == case['packets'], name + assert sorted(a['rule_id'] for a in report['alerts']) == sorted(case['alerts']), (name,report['alerts']) + assert report['metadata']['ids_enabled'] is True + assert report['statistics']['total_ids_alerts'] == len(case['alerts']) + for alert in report['alerts']: + assert alert['observed_count'] >= alert['threshold'] + for key in ['alert_id','rule_id','title','timestamp','severity','source','destination', + 'detection_window_seconds','observed_count','threshold','evidence','confidence', + 'limitations','recommendation','mitre_technique']: + assert key in alert, (name,key) + with Path(str(prefix)+'-alerts.csv').open(newline='') as stream: + rows = list(csv.DictReader(stream)) + assert len(rows) == len(report['alerts']) + if rows: assert json.loads(rows[0]['evidence']) == report['alerts'][0]['evidence'] + with Path(str(prefix)+'-flows.csv').open(newline='') as stream: + assert len(list(csv.DictReader(stream))) == len(report['flows']) + html = Path(str(prefix)+'.html').read_text() + assert '

PacketForge

' in html and 'Investigation limitations' in html + assert '.pcap' + evil.write_bytes((root/'samples/demo.pcap').read_bytes()) + run(['analyze','--pcap',evil,'--report','html','--output',temp/'escaped']) + html=(temp/'escaped.html').read_text() + assert ' +#include +#include +#include +#include +#include +using namespace packetforge; +namespace { +unsigned checks = 0; +void check(bool condition, const char* message) { ++checks; if (!condition) throw std::runtime_error(message); } +void put16(std::vector& b, std::size_t o, std::uint16_t value) { b[o] = static_cast(value >> 8); b[o+1] = static_cast(value); } +std::vector tcp() { + std::vector b(54); put16(b,12,0x0800); b[14]=0x45; put16(b,16,40); b[22]=64; b[23]=6; + b[26]=192; b[28]=2; b[29]=1; b[30]=198; b[31]=51; b[32]=100; b[33]=2; + put16(b,34,12345); put16(b,36,443); b[38]=0x12; b[39]=0x34; b[40]=0x56; b[41]=0x78; + b[46]=0x50; b[47]=2; put16(b,48,4096); return b; +} +Packet parse(const std::vector& b) { return parse_packet(b.data(), b.size(), static_cast(b.size()), 0); } +void parser_tests() { + auto b=tcp(); auto p=parse(b); + check(p.status==ParseStatus::ok && p.ethernet && p.ipv4 && p.transport, "Ethernet IPv4 TCP"); + check(p.source=="192.0.2.1" && p.destination=="198.51.100.2", "addresses"); + check(p.source_port==12345 && p.destination_port==443 && p.sequence==0x12345678 && p.tcp_window==4096, "network order"); + check(p.syn_attempt() && p.tcp_header_length==20 && p.ttl==64, "TCP fields"); + for (std::size_t n=0; n({1,2}) && p.destination_port==443,"double VLAN"); + b.insert(b.begin()+12,{0x81,0,0,3}); check(parse(b).status==ParseStatus::unsupported,"VLAN depth limit"); + b=tcp(); b.resize(42); b[23]=17; put16(b,16,28); put16(b,38,8); p=parse(b); + check(p.transport && p.udp_length==8 && p.destination_port==443,"UDP decode"); + put16(b,38,7); check(parse(b).status==ParseStatus::malformed,"UDP short length"); + put16(b,38,9); check(parse(b).status==ParseStatus::malformed,"UDP long length"); + b=tcp(); b.resize(42); b[23]=1; put16(b,16,28); b[34]=8; b[35]=0; p=parse(b); + check(p.echo_request && p.icmp_code==0 && p.transport,"ICMP request"); + b[34]=0; check(parse(b).echo_reply,"ICMP reply"); + b[35]=1; check(!parse(b).echo_reply,"ICMP echo code validation"); + b.assign(42,0); put16(b,12,0x0806); put16(b,14,1); put16(b,16,0x0800); b[18]=6; b[19]=4; + put16(b,20,1); b[22]=2; b[28]=192; b[30]=2; b[31]=10; b[38]=192; b[40]=2; b[41]=20; p=parse(b); + check(p.arp && p.arp_opcode==1 && p.source=="192.0.2.10" && p.destination=="192.0.2.20","ARP fields"); + check(p.arp_sender_hardware=="02:00:00:00:00:00" && p.arp_target_hardware=="00:00:00:00:00:00","ARP MACs"); + b[19]=16; check(parse(b).status==ParseStatus::truncated,"ARP variable length bounds"); + b.assign(62,0); put16(b,12,0x86dd); b[14]=0x60; put16(b,18,8); b[20]=58; b[21]=64; + b[22]=0x20;b[23]=1;b[24]=0x0d;b[25]=0xb8;b[37]=1; + b[38]=0x20;b[39]=1;b[40]=0x0d;b[41]=0xb8;b[53]=2;b[54]=128; p=parse(b); + check(p.ipv6 && p.echo_request && p.source=="2001:db8::1" && p.destination=="2001:db8::2" && p.ttl==64,"IPv6 ICMP"); + auto ipv6=b; b.insert(b.begin()+54,8,0); b[20]=0; b[54]=58; put16(b,18,16); p=parse(b); + check(p.status==ParseStatus::ok && p.next_header==0 && p.protocol==58 && p.echo_request,"IPv6 hop-by-hop extension"); + b[55]=3; check(parse(b).status==ParseStatus::malformed,"IPv6 extension payload bounds"); + b=ipv6; b.insert(b.begin()+54,8,0); b[20]=44; b[54]=58; put16(b,18,16); put16(b,56,8); p=parse(b); + check(p.fragmented && p.fragment_offset==8 && !p.transport,"IPv6 noninitial fragment"); + put16(b,56,0); p=parse(b); check(!p.fragmented && p.echo_request,"IPv6 atomic fragment"); + b=ipv6; b[20]=50; check(parse(b).status==ParseStatus::unsupported,"IPv6 ESP explicit unsupported"); + b=ipv6; put16(b,18,0); check(parse(b).status==ParseStatus::unsupported,"jumbogram unsupported"); + b=ipv6; b.resize(54); put16(b,18,0); b[20]=59; check(parse(b).status==ParseStatus::ok,"IPv6 no next header"); + b=tcp(); b.resize(58); put16(b,16,44); put16(b,20,0x2000); p=parse(b); + check(p.status==ParseStatus::ok && p.fragmented && p.transport,"complete TCP header in initial fragment"); + b=tcp(); put16(b,20,0x2000); check(parse(b).status==ParseStatus::malformed,"non-final fragment alignment"); + b=tcp(); b.resize(42); b[23]=17; put16(b,16,28); put16(b,20,0x2000); put16(b,38,100); p=parse(b); + check(p.status==ParseStatus::ok && p.fragmented && p.udp_length==100,"fragmented UDP full datagram length"); + b=tcp(); put16(b,16,100); check(parse(b).status==ParseStatus::malformed,"IP total exceeds wire"); + check(parse_packet(b.data(),b.size(),120,0).status==ParseStatus::truncated,"IP total within wire beyond capture"); + b=tcp(); p=parse_packet(b.data(),b.size(),100,0); check(p.capture_truncated && p.transport,"capture truncation distinct from header validity"); + check(parse_packet(b.data(),b.size(),20,0).status==ParseStatus::malformed,"caplen cannot exceed wire length"); + b=tcp(); b[14]=0x65; check(parse(b).status==ParseStatus::malformed,"wrong IPv4 version"); + b=tcp(); put16(b,16,19); check(parse(b).status==ParseStatus::malformed,"IP total below IHL"); + b=tcp(); b[46]=0xf0; check(parse(b).status==ParseStatus::malformed,"TCP options exceed IP payload"); + check(iso_time(1700000000LL*second+123456789)=="2023-11-14T22:13:20.123456789Z","nanosecond timestamp format"); +} +Packet syn(Timestamp time=0,std::uint16_t port=443) { + auto p=parse(tcp());p.timestamp=time;p.destination_port=port;return p; +} +Config only(const std::string& id,std::size_t threshold=3) { + auto c=Config::defaults();for (auto& [name,rule]:c.rules) rule.enabled=name==id; + auto& r=c.rules.at(id);r.threshold=threshold;r.window_seconds=10;r.cooldown_seconds=30;return c; +} +void flow_tests() { + auto c=Config::defaults(); c.max_flows=2;c.max_unique_flows=2;c.flow_timeout_seconds=10; + FlowTable flows(c);auto p=syn();flows.observe(p);p.timestamp=second;flows.observe(p); + check(flows.active_count()==1 && flows.unique_count()==1,"flow grouping"); + auto data=flows.json();check(data[0]["packets"]==2 && data[0]["observed_bytes"]==108 && data[0]["duration_seconds"]==1,"flow counters"); + std::swap(p.source,p.destination);std::swap(p.source_port,p.destination_port);flows.observe(p); + check(flows.active_count()==2 && flows.unique_count()==2,"reverse directional flow"); + p.destination_port=80;flows.observe(p);check(flows.evictions==1 && flows.unique_saturated,"bounded flow eviction and unique saturation"); + flows.expire(11*second,true);check(flows.active_count()==0 && flows.expired==2,"idle expiry boundary"); + check(flows.json().size()==2 && flows.archives_discarded==1,"bounded flow archive"); + p.fragmented=true;flows.observe(p);check(flows.active_count()==0,"fragments not grouped into partial flows"); +} +void detection_tests() { + { + DetectionEngine engine(only("POSSIBLE_TCP_PORT_SCAN")); + check(engine.observe(syn(0,80)).empty(),"one SYN is not scan"); + check(engine.observe(syn(second,80)).empty(),"same port deduplicated"); + check(engine.observe(syn(2*second,81)).empty(),"scan below boundary"); + auto a=engine.observe(syn(3*second,82));check(a.size()==1 && a[0]["observed_count"]==3,"scan threshold inclusive"); + check(a[0]["mitre_technique"]=="T1046 - Network Service Discovery","scan MITRE"); + check(engine.observe(syn(4*second,83)).empty(),"scan cooldown"); + } + { + DetectionEngine engine(only("POSSIBLE_TCP_PORT_SCAN")); + engine.observe(syn(0,80));engine.observe(syn(second,81)); + check(engine.observe(syn(10*second,82)).empty(),"half-open sliding window expires exact left edge"); + check(engine.observe(syn(10*second+1,83)).size()==1,"remaining window threshold"); + } + { + DetectionEngine engine(only("HIGH_TCP_SYN_RATE"));auto p=syn();p.tcp_flags=0x12; + check(engine.observe(p).empty(),"SYN ACK excluded"); + check(engine.observe(syn()).empty() && engine.observe(syn(second)).empty(),"SYN below boundary"); + check(engine.observe(syn(2*second)).size()==1,"SYN threshold"); + check(engine.observe(syn(3*second)).empty(),"SYN cooldown"); + engine.observe(syn(31*second));engine.observe(syn(32*second)); + check(engine.observe(syn(33*second)).size()==1,"SYN cooldown expiry and window reset"); + } + { + DetectionEngine engine(only("HIGH_ICMP_ECHO_RATE"));auto p=syn();p.protocol=1;p.echo_request=true;p.icmp_type=8; + engine.observe(p);p.timestamp=second;engine.observe(p);p.timestamp=2*second; + auto a=engine.observe(p);check(a.size()==1 && a[0]["rule_id"]=="HIGH_ICMP_ECHO_RATE","ICMP threshold"); + p.echo_request=false;p.echo_reply=true;p.timestamp=40*second;check(engine.observe(p).empty(),"echo replies excluded"); + } + { + auto c=only("CONNECTION_CONCENTRATION");DetectionEngine engine(c);auto p=syn(); + for (int i=0;i<10;++i) check(engine.observe(p).empty(),"retransmitted attempt deduplication"); + p.source_port++;engine.observe(p);p.destination="198.51.100.21"; + auto a=engine.observe(p);check(a.size()==1 && a[0]["evidence"]["distinct_destinations"]==2,"concentration across destinations"); + c.rules.at("POSSIBLE_TCP_PORT_SCAN").enabled=true;c.rules.at("POSSIBLE_TCP_PORT_SCAN").threshold=2; + DetectionEngine overlap(c);overlap.observe(syn(0,80));overlap.observe(syn(second,81));a=overlap.observe(syn(2*second,82)); + check(a.empty() && overlap.counters()["CONNECTION_CONCENTRATION"]["scan_overlap_suppressed"]==1,"scan overlap suppressed"); + } + { + auto c=only("SENSITIVE_SERVICE_TRAFFIC",1);DetectionEngine engine(c); + auto p=syn();p.source_port=22;check(engine.observe(p).size()==1,"sensitive source service port"); + check(engine.observe(p).empty(),"sensitive cooldown deduplication"); + c.rules.at("SENSITIVE_SERVICE_TRAFFIC").exclude_sources.insert(p.source);DetectionEngine excluded(c); + check(excluded.observe(p).empty(),"source exclusion"); + } + { + auto c=only("HIGH_TCP_SYN_RATE",2);c.max_rule_keys=1;c.max_rule_events=2;DetectionEngine engine(c); + engine.observe(syn());auto p=syn();p.source="192.0.2.99";engine.observe(p); + check(engine.counters()["HIGH_TCP_SYN_RATE"]["dropped_keys"]==1,"bounded keys visible"); + engine.observe(syn());engine.observe(syn());check(engine.counters()["HIGH_TCP_SYN_RATE"]["dropped_events"]==1,"bounded events visible"); + engine.expire(40*second);check(engine.counters()["HIGH_TCP_SYN_RATE"]["retained_keys"]==0,"expired detector storage reclaimed"); + } + { + auto c=only("HIGH_TCP_SYN_RATE",2);c.rules.at("HIGH_TCP_SYN_RATE").cooldown_seconds=0;DetectionEngine engine(c); + engine.observe(syn());check(engine.observe(syn()).size()==1,"zero cooldown crossing"); + check(engine.observe(syn()).empty(),"zero cooldown deduplicates same threshold episode"); + engine.observe(syn(11*second));check(engine.observe(syn(11*second)).size()==1,"zero cooldown rearm after expiry"); + } + { + DetectionEngine engine(Config::defaults());auto p=syn();p.fragmented=true; + check(engine.observe(p).empty(),"fragmented traffic excluded from IDS"); + p.fragmented=false;p.status=ParseStatus::malformed;check(engine.observe(p).empty(),"malformed traffic excluded from IDS"); + auto c=only("HIGH_TCP_SYN_RATE",1);Analysis analysis(c,true);analysis.observe(syn()); + bool threw=false;try { analysis.observe(syn(-1)); } catch (const std::runtime_error&) { threw=true; } + check(threw,"backwards timestamp rejected"); + FlowTable flows(c);p=syn(std::numeric_limits::max());flows.observe(p); + DetectionEngine maximum(c);check(maximum.observe(p).size()==1,"maximum timestamp arithmetic"); + } +} +void report_tests() { + check(html_escape("&")=="<a x="'">&","HTML escaping"); + check(csv_field("a,\"b\"")=="\"a,\"\"b\"\"\"","CSV quoting"); + check(csv_field("=1+1")=="\"'=1+1\"","CSV formula safety"); + auto c=Config::defaults();Analysis analysis(c,true);analysis.observe(syn()); + const auto report=analysis.report("analyze","",CaptureResult{1,0,false}); + check(Json::parse(report.dump())==report,"JSON roundtrip"); + check(html_report(report).find("<test>")!=std::string::npos,"report escapes metadata"); + check(evaluate_policy(syn(0,22),c.policy)=="WOULD_BLOCK" && evaluate_policy(syn(),c.policy)=="WOULD_ALLOW","first-match simulation"); + auto tiny=only("HIGH_TCP_SYN_RATE",1);tiny.max_alerts=1;tiny.rules.at("HIGH_TCP_SYN_RATE").cooldown_seconds=1; + Analysis bounded(tiny,true);bounded.observe(syn());bounded.observe(syn(2*second)); + check(bounded.alerts.size()==1 && bounded.total_alerts==2 && bounded.alerts_not_retained==1,"bounded alerts retain total counts"); + Statistics stats(1);stats.observe(syn());auto p=syn(second);p.source="192.0.2.99";stats.observe(p); + check(stats.omitted_sources==1 && stats.json()["packets_per_second"]==2,"bounded talkers and rates"); +} +void fuzz_tests() { + std::mt19937 random(0x5046); + for (int iteration=0;iteration<10000;++iteration) { + std::vector bytes(random()%256); + for (auto& byte:bytes) byte=static_cast(random()); + if (bytes.size()>14 && iteration%2==0) { bytes[12]=8;bytes[13]=0; } + const auto a=parse_packet(bytes.data(),bytes.size(),static_cast(bytes.size()+random()%100),0); + check(a.captured_length==bytes.size(),"random parser bounded decode"); + } +} + +} +int main() { try { parser_tests(); protocol_tests(); flow_tests(); detection_tests(); report_tests(); fuzz_tests(); std::cout << checks << " checks passed\n"; return 0; } + catch (const std::exception& e) { std::cerr << "FAIL: " << e.what() << '\n'; return 1; } } diff --git a/third_party/README.md b/third_party/README.md new file mode 100644 index 0000000..c858730 --- /dev/null +++ b/third_party/README.md @@ -0,0 +1,7 @@ +# Vendored dependency + +nlohmann/json 3.12.0, unmodified single header from the official tagged release: +https://github.com/nlohmann/json/releases/tag/v3.12.0 + +MIT license is included in nlohmann/LICENSE.MIT. Vendoring keeps builds and analysis +offline after installing the compiler, CMake and libpcap development package. diff --git a/third_party/nlohmann/LICENSE.MIT b/third_party/nlohmann/LICENSE.MIT new file mode 100644 index 0000000..a1dacc8 --- /dev/null +++ b/third_party/nlohmann/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2025 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/nlohmann/json.hpp b/third_party/nlohmann/json.hpp new file mode 100644 index 0000000..82d69f7 --- /dev/null +++ b/third_party/nlohmann/json.hpp @@ -0,0 +1,25526 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_DIAGNOSTIC_POSITIONS + #define JSON_DIAGNOSTIC_POSITIONS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_DIAGNOSTIC_POSITIONS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#ifdef JSON_HAS_CPP_17 + #include // optional +#endif +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2016 - 2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) + #define JSON_HAS_CPP_23 + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows calling any std function as if (e.g., with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // char_traits +#include // tuple +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& +is_complete_type < +detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template