Compare commits

..

No commits in common. "dev" and "1.12.2" have entirely different histories.
dev ... 1.12.2

210 changed files with 21446 additions and 29006 deletions

View file

@ -1,6 +0,0 @@
CompileFlags:
Add:
- "-std=c++17"
- "-I../ext"
- "-I../ext/prometheus-cpp-lite-1.0/core/include"
- "-I../ext/prometheus-cpp-lite-1.0/simpleapi/include"

View file

@ -1,7 +1,4 @@
on:
pull_request:
push:
workflow_dispatch:
on: [ push ]
jobs:
build_ubuntu:
@ -12,22 +9,23 @@ jobs:
git config --global core.autocrlf input
# git config --global core.eol lf
- name: checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
targets: x86_64-unknown-linux-gnu
target: x86_64-unknown-linux-gnu
override: true
components: rustfmt, clippy
- name: Set up cargo cache
uses: Swatinem/rust-cache@v2
continue-on-error: false
with:
key: ${{ runner.os }}-cargo-${{ hashFiles('rustybits//Cargo.lock') }}
key: ${{ runner.os }}-cargo-${{ hashFiles('zeroidc//Cargo.lock') }}
shared-key: ${{ runner.os }}-cargo-
workspaces: |
rustybits/
zeroidc/
- name: make
run: make
@ -35,14 +33,6 @@ jobs:
run: |
make selftest
./zerotier-selftest
- name: 'Tar files' # keeps permissions (execute)
run: tar -cvf zerotier-one.tar zerotier-one
- name: Archive production artifacts
uses: actions/upload-artifact@v4
with:
name: zerotier-one-ubuntu-x64
path: zerotier-one.tar
retention-days: 7
build_macos:
runs-on: macos-latest
@ -52,42 +42,29 @@ jobs:
git config --global core.autocrlf input
# git config --global core.eol lf
- name: checkout
uses: actions/checkout@v4
- name: Install Rust aarch64
uses: dtolnay/rust-toolchain@stable
uses: actions/checkout@v3
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: aarch64-apple-darwin
components: rustfmt, clippy
- name: Install Rust x86_64
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
target: x86_64-apple-darwin
override: true
components: rustfmt, clippy
- name: Set up cargo cache
uses: Swatinem/rust-cache@v2
continue-on-error: false
with:
key: ${{ runner.os }}-cargo-${{ hashFiles('rustybits//Cargo.lock') }}
key: ${{ runner.os }}-cargo-${{ hashFiles('zeroidc//Cargo.lock') }}
shared-key: ${{ runner.os }}-cargo-
workspaces: |
rustybits/
zeroidc/
- name: make
run: make
- name: selftest
run: |
make selftest
./zerotier-selftest
- name: 'Tar files' # keeps permissions (execute)
run: tar -cvf zerotier-one.tar zerotier-one
- name: Archive production artifacts
uses: actions/upload-artifact@v4
with:
name: zerotier-one-mac
path: zerotier-one.tar
retention-days: 7
build_windows:
runs-on: windows-latest
@ -97,30 +74,25 @@ jobs:
git config --global core.autocrlf true
# git config --global core.eol lf
- name: checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: aarch64-apple-darwin
override: true
components: rustfmt, clippy
- name: Set up cargo cache
uses: Swatinem/rust-cache@v2
continue-on-error: false
with:
key: ${{ runner.os }}-cargo-${{ hashFiles('rustybits//Cargo.lock') }}
key: ${{ runner.os }}-cargo-${{ hashFiles('zeroidc//Cargo.lock') }}
shared-key: ${{ runner.os }}-cargo-
workspaces: |
rustybits/
zeroidc/
- name: setup msbuild
uses: microsoft/setup-msbuild@v2
uses: microsoft/setup-msbuild@v1.1.3
- name: msbuild
run: |
msbuild windows\ZeroTierOne.sln /m /p:Configuration=Release /property:Platform=x64 /t:ZeroTierOne
- name: Archive production artifacts
uses: actions/upload-artifact@v4
with:
name: zerotier-one-windows
path: windows/Build
retention-days: 7
msbuild windows\ZeroTierOne.sln /m /p:Configuration=Release /property:Platform=x64 /t:ZeroTierOne

View file

@ -1,5 +1,4 @@
on:
pull_request:
push:
workflow_dispatch:
@ -45,7 +44,7 @@ jobs:
sudo ./.github/workflows/validate-linux.sh
- name: Archive test results
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: ${{github.sha}}-test-results
path: "*test-results*"

2
.gitignore vendored
View file

@ -124,7 +124,6 @@ attic/world/mkworld
workspace/
workspace2/
zeroidc/target/
tcp-proxy/target
#snapcraft specifics
/parts/
@ -139,4 +138,3 @@ __pycache__
*_source.tar.bz2
snap/.snapcraft
tcp-proxy/tcp-proxy
rustybits/target

View file

@ -1,6 +1,6 @@
# vim: ft=dockerfile
FROM debian:bookworm
FROM debian:bullseye
ARG VERSION
@ -9,9 +9,9 @@ RUN mkdir -p /usr/share/zerotier && \
curl -o /usr/share/zerotier/tmp.asc "https://download.zerotier.com/contact%40zerotier.com.gpg" && \
gpg --no-default-keyring --keyring /usr/share/zerotier/zerotier.gpg --import /usr/share/zerotier/tmp.asc && \
rm -f /usr/share/zerotier/tmp.asc && \
echo "deb [signed-by=/usr/share/zerotier/zerotier.gpg] http://download.zerotier.com/debian/bookworm bookworm main" > /etc/apt/sources.list.d/zerotier.list
echo "deb [signed-by=/usr/share/zerotier/zerotier.gpg] http://download.zerotier.com/debian/bullseye bullseye main" > /etc/apt/sources.list.d/zerotier.list
RUN apt-get update -qq && apt-get install zerotier-one=${VERSION} curl iproute2 net-tools iputils-ping openssl libssl3 -y
RUN apt-get update -qq && apt-get install zerotier-one=${VERSION} curl iproute2 net-tools iputils-ping openssl libssl1.1 -y
RUN rm -rf /var/lib/zerotier-one
COPY entrypoint.sh.release /entrypoint.sh

View file

@ -26,7 +26,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided you
ZeroTier behind the scenes to operate a service not
related to ZeroTier network administration.
* Create Non-Open-Source Commercial Derivative Works
* Create Non-Open-Source Commercial Derviative Works
(2) Link or directly include the Licensed Work in a
commercial or for-profit application or other product
@ -47,7 +47,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided you
services, social welfare, senior care, child care, and
the care of persons with disabilities.
Change Date: 2026-01-01
Change Date: 2025-01-01
Change License: Apache License version 2.0 as published by the Apache
Software Foundation

View file

@ -31,6 +31,3 @@ drone:
@echo "rendering .drone.yaml from .drone.jsonnet"
drone jsonnet --format --stream
drone sign zerotier/ZeroTierOne --save
clang-format:
find node osdep service tcp-proxy controller -iname '*.cpp' -o -iname '*.hpp' | xargs clang-format -i

View file

@ -14,7 +14,6 @@ The version must be incremented in all of the following files:
/debian/changelog
/ext/installfiles/mac/ZeroTier One.pkgproj
/ext/installfiles/windows/ZeroTier One.aip
../DesktopUI/mac-app-template/ZeroTier.app/Contents/Info.plist
The final .AIP file can only be edited on Windows with [Advanced Installer Enterprise](http://www.advancedinstaller.com/). In addition to incrementing the version be sure that a new product code is generated. (The "upgrade code" GUID on the other hand must never change.)

View file

@ -64,7 +64,6 @@ You can control a few settings including the identity used and the authtoken use
- `ZEROTIER_API_SECRET`: replaces the `authtoken.secret` before booting and allows you to manage the control socket's authentication key.
- `ZEROTIER_IDENTITY_PUBLIC`: the `identity.public` file for zerotier-one. Use `zerotier-idtool` to generate one of these for you.
- `ZEROTIER_IDENTITY_SECRET`: the `identity.secret` file for zerotier-one. Use `zerotier-idtool` to generate one of these for you.
- `ZEROTIER_LOCAL_CONF`: Sets the the `local.conf` file content for zerotier-one
### Tips

View file

@ -44,12 +44,6 @@ The base path contains the ZeroTier One service main entry point (`one.cpp`), se
- `windows/`: Visual Studio solution files, Windows service code, and the Windows task bar app UI.
- `zeroidc/`: OIDC implementation used by ZeroTier service to log into SSO-enabled networks. (This part is written in Rust, and more Rust will be appearing in this repository in the future.)
### Contributing
Please do pull requests off of the `dev` branch.
Releases are done by merging `dev` into `main` and then tagging and doing builds.
### Build and Platform Notes
To build on Mac and Linux just type `make`. On FreeBSD and OpenBSD `gmake` (GNU make) is required and can be installed from packages or ports. For Windows there is a Visual Studio solution in `windows/`.
@ -58,7 +52,7 @@ To build on Mac and Linux just type `make`. On FreeBSD and OpenBSD `gmake` (GNU
- Xcode command line tools for macOS 10.13 or newer are required.
- Rust for x86_64 and ARM64 targets *if SSO is enabled in the build*.
- **Linux**
- The minimum compiler versions required are GCC/G++ 8.x or CLANG/CLANG++ 5.x.
- The minimum compiler versions required are GCC/G++ 4.9.3 or CLANG/CLANG++ 3.4.2. (Install `clang` on CentOS 7 as G++ is too old.)
- Linux makefiles automatically detect and prefer clang/clang++ if present as it produces smaller and slightly faster binaries in most cases. You can override by supplying CC and CXX variables on the make command line.
- Rust for x86_64 and ARM64 targets *if SSO is enabled in the build*.
- **Windows**
@ -87,7 +81,7 @@ On most distributions, macOS, and Windows, the installer will start the service
A home folder for your system will automatically be created.
The service is controlled via the JSON API, which by default is available at `127.0.0.1:9993`. It also listens on `0.0.0.0:9993` which is only usable if `allowManagementFrom` is properly configured in `local.conf`. We include a *zerotier-cli* command line utility to make API calls for standard things like joining and leaving networks. The *authtoken.secret* file in the home folder contains the secret token for accessing this API. See [service/README.md](service/README.md) for API documentation.
The service is controlled via the JSON API, which by default is available at 127.0.0.1 port 9993. We include a *zerotier-cli* command line utility to make API calls for standard things like joining and leaving networks. The *authtoken.secret* file in the home folder contains the secret token for accessing this API. See [service/README.md](service/README.md) for API documentation.
Here's where home folders live (by default) on each OS:
@ -175,23 +169,3 @@ Metrics are also available on disk in ZeroTier's working directory:
| zt_peer_packet_errors | node_id | Counter | number of incoming packet errors from a peer |
If there are other metrics you'd like to see tracked, ask us in an Issue or send us a Pull Request!
### HTTP / App server
There is a static http file server suitable for hosting Single Page Apps at http://localhost:9993/app/<app-path>
Use `zerotier-cli info -j` to find your zerotier-one service's homeDir
``` sh
cd $ZT_HOME
sudo mkdir -p app/app1
sudo mkdir -p app/appB
echo '<html><meta charset=utf-8><title>appA</title><body><h1>hello world A' | sudo tee app/appA/index.html
echo '<html><meta charset=utf-8><title>app2</title><body><h1>hello world 2' | sudo tee app/app2/index.html
curl -sL http://localhost:9993/app/appA http://localhost:9993/app/app2
```
Then visit [http://localhost:9993/app/app1/](http://localhost:9993/app/app1/) and [http://localhost:9993/app/appB/](http://localhost:9993/app/appB/)
Requests to paths don't exist return the app root index.html, as is customary for SPAs.
If you want, you can write some javascript that talks to the service or controller [api](https://docs.zerotier.com/service/v1).

View file

@ -1,38 +1,6 @@
ZeroTier Release Notes
======
# 2024-10-23 -- Version 1.14.2
* Fix for missing entitlement on macOS Sequoia.
* Fix for a problem correctly parsing local.conf to enable low bandwidth mode.
* Increment versions of some dependent libraries.
* Other fixes.
# 2024-09-12 -- Version 1.14.1
* Multithreaded packet I/O support! Currently this is just for Linux and must
be enabled in local.conf. It will likely make the largest difference on small
multi-core devices where CPU is a bottleneck and high throughput is desired.
It may be enabled by default in the future but we want it to be thoroughly
tested. It's a little harder than it seems at first glance due to the need
to keep packets in sequence and balance load.
* Several multipath bug fixes.
* Updated the versions on a number of libraries related to OIDC support and HTTP.
* MacOS .app now shows the correct version in its Info.plist manifest.
* Sanitize MAC addresses in JSON format rules parser.
* Some basic information about the platform (OS, CPU architecture) is now reported
to network controllers when networks are joined so it can be displayed to
network admins and in the future used in policy checking and inventory operations.
# 2024-05-02 -- Version 1.14.0
* Linux I/O performance improvements under heavy load
* Improvements to multipath
* Fix for port rebinding "coma" bug after periods offline (some laptop users)
* Fixed a rules engine quirk/ambiguity (GitHub Issue #2200)
* Controller API enhancements: node names and other node meta-data
* Other bug fixes
# 2023-09-12 -- Version 1.12.2
* More improvements to macOS full tunnel mode.
@ -121,7 +89,7 @@ Note that releases are coming few and far between because most of our dev effort
# 2022-04-25 -- Version 1.8.9
* Fixed a long-standing and strange bug that was causing sporadic "phantom" packet authentication failures. Not a security problem but could be behind sporadic reports of link failures under some conditions.
* Fixed a memory leak in SSO/OIDC support.
* Fized a memory leak in SSO/OIDC support.
* Fixed SSO/OIDC display error on CLI.
* Fixed a bug causing nodes to sometimes fail to push certs to each other (primarily affects SSO/OIDC use cases).
* Fixed a deadlock bug on leaving SSO/OIDC managed networks.
@ -372,7 +340,7 @@ We're trying to fix all these issues before the 1.6.0 release. Stay tuned.
# 2017-04-20 -- Version 1.2.4
* Managed routes are now only bifurcated for the default route. This is a change in behavior, though few people will probably notice. Bifurcating all managed routes was causing more trouble than it was worth for most users.
* Up to 2X crypto speedup on x86-64 (except Windows, which will take some porting) and 32-bit ARM platforms due to integration of fast assembly language implementations of Salsa20/12 from the [supercop](http://bench.cr.yp.to/supercop.html) code base. These were written by Daniel J. Bernstein and are in the public domain. My MacBook Pro (Core i5 2.8ghz) now does almost 1.5GiB/sec Salsa20/12 per core and a Raspberry Pi got a 2X boost. 64-bit ARM support and Windows support will take some work but should not be too hard.
* Up to 2X crypto speedup on x86-64 (except Windows, which will take some porting) and 32-bit ARM platforms due to integration of fast assembly language implementations of Salsa20/12 from the [supercop](http://bench.cr.yp.to/supercop.html) code base. These were written by Daniel J. Bernstein and are in the public domain. My Macbook Pro (Core i5 2.8ghz) now does almost 1.5GiB/sec Salsa20/12 per core and a Raspberry Pi got a 2X boost. 64-bit ARM support and Windows support will take some work but should not be too hard.
* Refactored code that manages credentials to greatly reduce memory use in most cases. This may also result in a small performance improvement.
* Reworked and simplified path selection and priority logic to fix path instability and dead path persistence edge cases. There have been some sporadic reports of persistent path instabilities and dead paths hanging around that take minutes to resolve. These have proven difficult to reproduce in house, but hopefully this will fix them. In any case it seems to speed up path establishment in our tests and it makes the code simpler and more readable.
* Eliminated some unused cruft from the code around path management and in the peer class.

View file

@ -7,11 +7,11 @@ includes all source code repositories managed through our GitHub organization.
The following versions of ZeroTier One receive security updates
| Version | Supported |
| -------- | ------------------ |
| 1.14.x | :white_check_mark: |
| 1.12.x | :white_check_mark: |
| < 1.12.0 | :x: |
| Version | Supported |
| ------- | ------------------ |
| 1.10.x | :white_check_mark: |
| 1.8.x | :white_check_mark: |
| < 1.8.0 | :x: |
## Reporting a Vulnerability
@ -23,6 +23,7 @@ please encrypt with our PGP key (see below).
Please include the following information, or as much as you can provide to help us
understand the nature and scope of the issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
@ -31,6 +32,7 @@ understand the nature and scope of the issue:
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
## Preferred Languages
We prefer all communications to be in English.

File diff suppressed because it is too large Load diff

View file

@ -1,141 +0,0 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "DB.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#ifndef ZT_CONTROLLER_CV1_HPP
#define ZT_CONTROLLER_CV1_HPP
#define ZT_CENTRAL_CONTROLLER_COMMIT_THREADS 4
#include "../node/Metrics.hpp"
#include "ConnectionPool.hpp"
#include "PostgreSQL.hpp"
#include <memory>
#include <pqxx/pqxx>
#include <redis++/redis++.h>
namespace smeeclient {
struct SmeeClient;
}
namespace ZeroTier {
struct RedisConfig;
/**
* A controller database driver that talks to PostgreSQL
*
* This is for use with ZeroTier Central. Others are free to build and use it
* but be aware that we might change it at any time.
*/
class CV1 : public DB {
public:
CV1(const Identity& myId, const char* path, int listenPort, RedisConfig* rc);
virtual ~CV1();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json& record, bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch);
virtual AuthInfo getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL);
virtual bool ready()
{
return _ready == 2;
}
protected:
struct _PairHasher {
inline std::size_t operator()(const std::pair<uint64_t, uint64_t>& p) const
{
return (std::size_t)(p.first ^ p.second);
}
};
virtual void _memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool notifyListeners)
{
DB::_memberChanged(old, memberConfig, notifyListeners);
}
virtual void _networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, bool notifyListeners)
{
DB::_networkChanged(old, networkConfig, notifyListeners);
}
private:
void initializeNetworks();
void initializeMembers();
void heartbeat();
void membersDbWatcher();
void _membersWatcher_Postgres();
void networksDbWatcher();
void _networksWatcher_Postgres();
void _membersWatcher_Redis();
void _networksWatcher_Redis();
void commitThread();
void onlineNotificationThread();
void onlineNotification_Postgres();
void onlineNotification_Redis();
uint64_t _doRedisUpdate(sw::redis::Transaction& tx, std::string& controllerId, std::unordered_map<std::pair<uint64_t, uint64_t>, NodeOnlineRecord, _PairHasher>& lastOnline);
void configureSmee();
void notifyNewMember(const std::string& networkID, const std::string& memberID);
enum OverrideMode { ALLOW_PGBOUNCER_OVERRIDE = 0, NO_OVERRIDE = 1 };
std::shared_ptr<ConnectionPool<PostgresConnection> > _pool;
const Identity _myId;
const Address _myAddress;
std::string _myAddressStr;
std::string _connString;
BlockingQueue<std::pair<nlohmann::json, bool> > _commitQueue;
std::thread _heartbeatThread;
std::thread _membersDbWatcher;
std::thread _networksDbWatcher;
std::thread _commitThread[ZT_CENTRAL_CONTROLLER_COMMIT_THREADS];
std::thread _onlineNotificationThread;
std::unordered_map<std::pair<uint64_t, uint64_t>, NodeOnlineRecord, _PairHasher> _lastOnline;
mutable std::mutex _lastOnline_l;
mutable std::mutex _readyLock;
std::atomic<int> _ready, _connected, _run;
mutable volatile bool _waitNoticePrinted;
int _listenPort;
uint8_t _ssoPsk[48];
RedisConfig* _rc;
std::shared_ptr<sw::redis::Redis> _redis;
std::shared_ptr<sw::redis::RedisCluster> _cluster;
bool _redisMemberStatus;
smeeclient::SmeeClient* _smee;
};
} // namespace ZeroTier
#endif // ZT_CONTROLLER_CV1_HPP
#endif // ZT_CONTROLLER_USE_LIBPQ

File diff suppressed because it is too large Load diff

View file

@ -1,112 +0,0 @@
/*
* Copyright (c)2025 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "DB.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#ifndef ZT_CONTROLLER_CV2_HPP
#define ZT_CONTROLLER_CV2_HPP
#define ZT_CENTRAL_CONTROLLER_COMMIT_THREADS 4
#include "../node/Metrics.hpp"
#include "ConnectionPool.hpp"
#include "PostgreSQL.hpp"
#include <memory>
#include <pqxx/pqxx>
#include <redis++/redis++.h>
namespace ZeroTier {
class CV2 : public DB {
public:
CV2(const Identity& myId, const char* path, int listenPort);
virtual ~CV2();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json& record, bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch);
virtual AuthInfo getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL);
virtual bool ready()
{
return _ready == 2;
}
protected:
struct _PairHasher {
inline std::size_t operator()(const std::pair<uint64_t, uint64_t>& p) const
{
return (std::size_t)(p.first ^ p.second);
}
};
virtual void _memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool notifyListeners)
{
DB::_memberChanged(old, memberConfig, notifyListeners);
}
virtual void _networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, bool notifyListeners)
{
DB::_networkChanged(old, networkConfig, notifyListeners);
}
private:
void initializeNetworks();
void initializeMembers();
void heartbeat();
void membersDbWatcher();
void networksDbWatcher();
void commitThread();
void onlineNotificationThread();
// void notifyNewMember(const std::string &networkID, const std::string &memberID);
enum OverrideMode { ALLOW_PGBOUNCER_OVERRIDE = 0, NO_OVERRIDE = 1 };
std::shared_ptr<ConnectionPool<PostgresConnection> > _pool;
const Identity _myId;
const Address _myAddress;
std::string _myAddressStr;
std::string _connString;
BlockingQueue<std::pair<nlohmann::json, bool> > _commitQueue;
std::thread _heartbeatThread;
std::thread _membersDbWatcher;
std::thread _networksDbWatcher;
std::thread _commitThread[ZT_CENTRAL_CONTROLLER_COMMIT_THREADS];
std::thread _onlineNotificationThread;
std::unordered_map<std::pair<uint64_t, uint64_t>, NodeOnlineRecord, _PairHasher> _lastOnline;
mutable std::mutex _lastOnline_l;
mutable std::mutex _readyLock;
std::atomic<int> _ready, _connected, _run;
mutable volatile bool _waitNoticePrinted;
int _listenPort;
uint8_t _ssoPsk[48];
};
} // namespace ZeroTier
#endif // ZT_CONTROLLER_CV2_HPP
#endif // ZT_CONTROLLER_USE_LIBPQ

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,162 +14,162 @@
#ifndef ZT_CONNECTION_POOL_H_
#define ZT_CONNECTION_POOL_H_
#ifndef _DEBUG
#define _DEBUG(x)
#define _DEBUG(x)
#endif
#include "../node/Metrics.hpp"
#include <deque>
#include <exception>
#include <set>
#include <memory>
#include <mutex>
#include <set>
#include <exception>
#include <string>
namespace ZeroTier {
struct ConnectionUnavailable : std::exception {
char const* what() const throw()
{
return "Unable to allocate connection";
};
struct ConnectionUnavailable : std::exception {
char const* what() const throw() {
return "Unable to allocate connection";
};
};
class Connection {
public:
virtual ~Connection() {};
public:
virtual ~Connection() {};
};
class ConnectionFactory {
public:
virtual ~ConnectionFactory() {};
virtual std::shared_ptr<Connection> create() = 0;
public:
virtual ~ConnectionFactory() {};
virtual std::shared_ptr<Connection> create()=0;
};
struct ConnectionPoolStats {
size_t pool_size;
size_t borrowed_size;
size_t pool_size;
size_t borrowed_size;
};
template <class T> class ConnectionPool {
public:
ConnectionPool(size_t max_pool_size, size_t min_pool_size, std::shared_ptr<ConnectionFactory> factory) : m_maxPoolSize(max_pool_size), m_minPoolSize(min_pool_size), m_factory(factory)
{
Metrics::max_pool_size += max_pool_size;
Metrics::min_pool_size += min_pool_size;
while (m_pool.size() < m_minPoolSize) {
m_pool.push_back(m_factory->create());
Metrics::pool_avail++;
}
};
template<class T>
class ConnectionPool {
public:
ConnectionPool(size_t max_pool_size, size_t min_pool_size, std::shared_ptr<ConnectionFactory> factory)
: m_maxPoolSize(max_pool_size)
, m_minPoolSize(min_pool_size)
, m_factory(factory)
{
Metrics::max_pool_size += max_pool_size;
Metrics::min_pool_size += min_pool_size;
while(m_pool.size() < m_minPoolSize){
m_pool.push_back(m_factory->create());
Metrics::pool_avail++;
}
};
ConnectionPoolStats get_stats()
{
std::unique_lock<std::mutex> lock(m_poolMutex);
ConnectionPoolStats get_stats() {
std::unique_lock<std::mutex> lock(m_poolMutex);
ConnectionPoolStats stats;
stats.pool_size = m_pool.size();
stats.borrowed_size = m_borrowed.size();
ConnectionPoolStats stats;
stats.pool_size = m_pool.size();
stats.borrowed_size = m_borrowed.size();
return stats;
};
return stats;
};
~ConnectionPool() {};
~ConnectionPool() {
};
/**
* Borrow
*
* Borrow a connection for temporary use
*
* When done, either (a) call unborrow() to return it, or (b) (if it's bad) just let it go out of scope. This will cause it to automatically be replaced.
* @retval a shared_ptr to the connection object
*/
std::shared_ptr<T> borrow()
{
std::unique_lock<std::mutex> l(m_poolMutex);
/**
* Borrow
*
* Borrow a connection for temporary use
*
* When done, either (a) call unborrow() to return it, or (b) (if it's bad) just let it go out of scope. This will cause it to automatically be replaced.
* @retval a shared_ptr to the connection object
*/
std::shared_ptr<T> borrow() {
std::unique_lock<std::mutex> l(m_poolMutex);
while((m_pool.size() + m_borrowed.size()) < m_minPoolSize) {
std::shared_ptr<Connection> conn = m_factory->create();
m_pool.push_back(conn);
Metrics::pool_avail++;
}
while ((m_pool.size() + m_borrowed.size()) < m_minPoolSize) {
std::shared_ptr<Connection> conn = m_factory->create();
m_pool.push_back(conn);
Metrics::pool_avail++;
}
if(m_pool.size()==0){
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
try {
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.insert(conn);
Metrics::pool_in_use++;
return std::static_pointer_cast<T>(conn);
} catch (std::exception &e) {
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
} else {
for(auto it = m_borrowed.begin(); it != m_borrowed.end(); ++it){
if((*it).unique()) {
// This connection has been abandoned! Destroy it and create a new connection
try {
// If we are able to create a new connection, return it
_DEBUG("Creating new connection to replace discarded connection");
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.erase(it);
m_borrowed.insert(conn);
return std::static_pointer_cast<T>(conn);
} catch(std::exception& e) {
// Error creating a replacement connection
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
}
}
// Nothing available
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
}
if (m_pool.size() == 0) {
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
try {
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.insert(conn);
Metrics::pool_in_use++;
return std::static_pointer_cast<T>(conn);
}
catch (std::exception& e) {
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
}
else {
for (auto it = m_borrowed.begin(); it != m_borrowed.end(); ++it) {
if ((*it).unique()) {
// This connection has been abandoned! Destroy it and create a new connection
try {
// If we are able to create a new connection, return it
_DEBUG("Creating new connection to replace discarded connection");
std::shared_ptr<Connection> conn = m_factory->create();
m_borrowed.erase(it);
m_borrowed.insert(conn);
return std::static_pointer_cast<T>(conn);
}
catch (std::exception& e) {
// Error creating a replacement connection
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
}
}
// Nothing available
Metrics::pool_errors++;
throw ConnectionUnavailable();
}
}
// Take one off the front
std::shared_ptr<Connection> conn = m_pool.front();
m_pool.pop_front();
Metrics::pool_avail--;
// Add it to the borrowed list
m_borrowed.insert(conn);
Metrics::pool_in_use++;
return std::static_pointer_cast<T>(conn);
};
// Take one off the front
std::shared_ptr<Connection> conn = m_pool.front();
m_pool.pop_front();
Metrics::pool_avail--;
// Add it to the borrowed list
m_borrowed.insert(conn);
Metrics::pool_in_use++;
return std::static_pointer_cast<T>(conn);
};
/**
* Unborrow a connection
*
* Only call this if you are returning a working connection. If the connection was bad, just let it go out of scope (so the connection manager can replace it).
* @param the connection
*/
void unborrow(std::shared_ptr<T> conn)
{
// Lock
std::unique_lock<std::mutex> lock(m_poolMutex);
m_borrowed.erase(conn);
Metrics::pool_in_use--;
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
Metrics::pool_avail++;
m_pool.push_back(conn);
}
};
protected:
size_t m_maxPoolSize;
size_t m_minPoolSize;
std::shared_ptr<ConnectionFactory> m_factory;
std::deque<std::shared_ptr<Connection> > m_pool;
std::set<std::shared_ptr<Connection> > m_borrowed;
std::mutex m_poolMutex;
/**
* Unborrow a connection
*
* Only call this if you are returning a working connection. If the connection was bad, just let it go out of scope (so the connection manager can replace it).
* @param the connection
*/
void unborrow(std::shared_ptr<T> conn) {
// Lock
std::unique_lock<std::mutex> lock(m_poolMutex);
m_borrowed.erase(conn);
Metrics::pool_in_use--;
if ((m_pool.size() + m_borrowed.size()) < m_maxPoolSize) {
Metrics::pool_avail++;
m_pool.push_back(conn);
}
};
protected:
size_t m_maxPoolSize;
size_t m_minPoolSize;
std::shared_ptr<ConnectionFactory> m_factory;
std::deque<std::shared_ptr<Connection> > m_pool;
std::set<std::shared_ptr<Connection> > m_borrowed;
std::mutex m_poolMutex;
};
} // namespace ZeroTier
}
#endif

View file

@ -1,64 +0,0 @@
#include "CtlUtil.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#include <iomanip>
#include <sstream>
namespace ZeroTier {
const char* _timestr()
{
time_t t = time(0);
char* ts = ctime(&t);
char* p = ts;
if (! p)
return "";
while (*p) {
if (*p == '\n') {
*p = (char)0;
break;
}
++p;
}
return ts;
}
std::vector<std::string> split(std::string str, char delim)
{
std::istringstream iss(str);
std::vector<std::string> tokens;
std::string item;
while (std::getline(iss, item, delim)) {
tokens.push_back(item);
}
return tokens;
}
std::string url_encode(const std::string& value)
{
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
std::string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char)c);
escaped << std::nouppercase;
}
return escaped.str();
}
} // namespace ZeroTier
#endif

View file

@ -1,16 +0,0 @@
#ifndef ZT_CTLUTIL_HPP
#define ZT_CTLUTIL_HPP
#include <string>
#include <vector>
namespace ZeroTier {
const char* _timestr();
std::vector<std::string> split(std::string str, char delim);
std::string url_encode(const std::string& value);
} // namespace ZeroTier
#endif // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -12,114 +12,77 @@
/****/
#include "DB.hpp"
#include "../node/Metrics.hpp"
#include "EmbeddedNetworkController.hpp"
#include "../node/Metrics.hpp"
#include <algorithm>
#include <chrono>
#include <algorithm>
#include <stdexcept>
using json = nlohmann::json;
namespace ZeroTier {
void DB::initNetwork(nlohmann::json& network)
void DB::initNetwork(nlohmann::json &network)
{
if (! network.count("private"))
network["private"] = true;
if (! network.count("creationTime"))
network["creationTime"] = OSUtils::now();
if (! network.count("name"))
network["name"] = "";
if (! network.count("multicastLimit"))
network["multicastLimit"] = (uint64_t)32;
if (! network.count("enableBroadcast"))
network["enableBroadcast"] = true;
if (! network.count("v4AssignMode"))
network["v4AssignMode"] = { { "zt", false } };
if (! network.count("v6AssignMode"))
network["v6AssignMode"] = { { "rfc4193", false }, { "zt", false }, { "6plane", false } };
if (! network.count("authTokens"))
network["authTokens"] = { {} };
if (! network.count("capabilities"))
network["capabilities"] = nlohmann::json::array();
if (! network.count("tags"))
network["tags"] = nlohmann::json::array();
if (! network.count("routes"))
network["routes"] = nlohmann::json::array();
if (! network.count("ipAssignmentPools"))
network["ipAssignmentPools"] = nlohmann::json::array();
if (! network.count("mtu"))
network["mtu"] = ZT_DEFAULT_MTU;
if (! network.count("remoteTraceTarget"))
network["remoteTraceTarget"] = nlohmann::json();
if (! network.count("removeTraceLevel"))
network["remoteTraceLevel"] = 0;
if (! network.count("rulesSource"))
network["rulesSource"] = "";
if (! network.count("rules")) {
if (!network.count("private")) network["private"] = true;
if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
if (!network.count("name")) network["name"] = "";
if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
if (!network.count("authTokens")) network["authTokens"] = {{}};
if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
if (!network.count("tags")) network["tags"] = nlohmann::json::array();
if (!network.count("routes")) network["routes"] = nlohmann::json::array();
if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0;
if (!network.count("rulesSource")) network["rulesSource"] = "";
if (!network.count("rules")) {
// If unspecified, rules are set to allow anything and behave like a flat L2 segment
network["rules"] = { { { "not", false }, { "or", false }, { "type", "ACTION_ACCEPT" } } };
network["rules"] = {{
{ "not",false },
{ "or", false },
{ "type","ACTION_ACCEPT" }
}};
}
if (! network.count("dns"))
network["dns"] = nlohmann::json::array();
if (! network.count("ssoEnabled"))
network["ssoEnabled"] = false;
if (! network.count("clientId"))
network["clientId"] = "";
if (! network.count("authorizationEndpoint"))
network["authorizationEndpoint"] = "";
if (!network.count("dns")) network["dns"] = nlohmann::json::array();
if (!network.count("ssoEnabled")) network["ssoEnabled"] = false;
if (!network.count("clientId")) network["clientId"] = "";
if (!network.count("authorizationEndpoint")) network["authorizationEndpoint"] = "";
network["objtype"] = "network";
}
void DB::initMember(nlohmann::json& member)
void DB::initMember(nlohmann::json &member)
{
if (! member.count("authorized"))
member["authorized"] = false;
if (! member.count("ssoExempt"))
member["ssoExempt"] = false;
if (! member.count("ipAssignments"))
member["ipAssignments"] = nlohmann::json::array();
if (! member.count("activeBridge"))
member["activeBridge"] = false;
if (! member.count("tags"))
member["tags"] = nlohmann::json::array();
if (! member.count("capabilities"))
member["capabilities"] = nlohmann::json::array();
if (! member.count("creationTime"))
member["creationTime"] = OSUtils::now();
if (! member.count("noAutoAssignIps"))
member["noAutoAssignIps"] = false;
if (! member.count("revision"))
member["revision"] = 0ULL;
if (! member.count("lastDeauthorizedTime"))
member["lastDeauthorizedTime"] = 0ULL;
if (! member.count("lastAuthorizedTime"))
member["lastAuthorizedTime"] = 0ULL;
if (! member.count("lastAuthorizedCredentialType"))
member["lastAuthorizedCredentialType"] = nlohmann::json();
if (! member.count("lastAuthorizedCredential"))
member["lastAuthorizedCredential"] = nlohmann::json();
if (! member.count("authenticationExpiryTime"))
member["authenticationExpiryTime"] = 0LL;
if (! member.count("vMajor"))
member["vMajor"] = -1;
if (! member.count("vMinor"))
member["vMinor"] = -1;
if (! member.count("vRev"))
member["vRev"] = -1;
if (! member.count("vProto"))
member["vProto"] = -1;
if (! member.count("remoteTraceTarget"))
member["remoteTraceTarget"] = nlohmann::json();
if (! member.count("removeTraceLevel"))
member["remoteTraceLevel"] = 0;
if (!member.count("authorized")) member["authorized"] = false;
if (!member.count("ssoExempt")) member["ssoExempt"] = false;
if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
if (!member.count("activeBridge")) member["activeBridge"] = false;
if (!member.count("tags")) member["tags"] = nlohmann::json::array();
if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
if (!member.count("revision")) member["revision"] = 0ULL;
if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
if (!member.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = 0LL;
if (!member.count("vMajor")) member["vMajor"] = -1;
if (!member.count("vMinor")) member["vMinor"] = -1;
if (!member.count("vRev")) member["vRev"] = -1;
if (!member.count("vProto")) member["vProto"] = -1;
if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
if (!member.count("removeTraceLevel")) member["remoteTraceLevel"] = 0;
member["objtype"] = "member";
}
void DB::cleanNetwork(nlohmann::json& network)
void DB::cleanNetwork(nlohmann::json &network)
{
network.erase("clock");
network.erase("authorizedMemberCount");
@ -128,25 +91,21 @@ void DB::cleanNetwork(nlohmann::json& network)
network.erase("lastModified");
}
void DB::cleanMember(nlohmann::json& member)
void DB::cleanMember(nlohmann::json &member)
{
member.erase("clock");
member.erase("physicalAddr");
member.erase("recentLog");
member.erase("lastModified");
member.erase("lastRequestMetaData");
member.erase("authenticationURL"); // computed
member.erase("authenticationClientID"); // computed
member.erase("authenticationURL"); // computed
member.erase("authenticationClientID"); // computed
}
DB::DB()
{
}
DB::~DB()
{
}
DB::DB() {}
DB::~DB() {}
bool DB::get(const uint64_t networkId, nlohmann::json& network)
bool DB::get(const uint64_t networkId,nlohmann::json &network)
{
waitForReady();
Metrics::db_get_network++;
@ -165,7 +124,7 @@ bool DB::get(const uint64_t networkId, nlohmann::json& network)
return true;
}
bool DB::get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member)
bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
{
waitForReady();
Metrics::db_get_network_and_member++;
@ -188,7 +147,7 @@ bool DB::get(const uint64_t networkId, nlohmann::json& network, const uint64_t m
return true;
}
bool DB::get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member, NetworkSummaryInfo& info)
bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
{
waitForReady();
Metrics::db_get_network_and_member_and_summary++;
@ -203,7 +162,7 @@ bool DB::get(const uint64_t networkId, nlohmann::json& network, const uint64_t m
{
std::shared_lock<std::shared_mutex> l2(nw->lock);
network = nw->config;
_fillSummaryInfo(nw, info);
_fillSummaryInfo(nw,info);
auto m = nw->members.find(memberId);
if (m == nw->members.end())
return false;
@ -212,7 +171,7 @@ bool DB::get(const uint64_t networkId, nlohmann::json& network, const uint64_t m
return true;
}
bool DB::get(const uint64_t networkId, nlohmann::json& network, std::vector<nlohmann::json>& members)
bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
{
waitForReady();
Metrics::db_get_member_list++;
@ -227,23 +186,23 @@ bool DB::get(const uint64_t networkId, nlohmann::json& network, std::vector<nloh
{
std::shared_lock<std::shared_mutex> l2(nw->lock);
network = nw->config;
for (auto m = nw->members.begin(); m != nw->members.end(); ++m) {
for(auto m=nw->members.begin();m!=nw->members.end();++m) {
members.push_back(m->second);
}
}
return true;
}
void DB::networks(std::set<uint64_t>& networks)
void DB::networks(std::set<uint64_t> &networks)
{
waitForReady();
Metrics::db_get_network_list++;
Metrics::db_get_member_list++;
std::shared_lock<std::shared_mutex> l(_networks_l);
for (auto n = _networks.begin(); n != _networks.end(); ++n)
for(auto n=_networks.begin();n!=_networks.end();++n)
networks.insert(n->first);
}
void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool notifyListeners)
void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners)
{
Metrics::db_member_change++;
uint64_t memberId = 0;
@ -253,9 +212,9 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
std::shared_ptr<_Network> nw;
if (old.is_object()) {
memberId = OSUtils::jsonIntHex(old["id"], 0ULL);
networkId = OSUtils::jsonIntHex(old["nwid"], 0ULL);
if ((memberId) && (networkId)) {
memberId = OSUtils::jsonIntHex(old["id"],0ULL);
networkId = OSUtils::jsonIntHex(old["nwid"],0ULL);
if ((memberId)&&(networkId)) {
{
std::unique_lock<std::shared_mutex> l(_networks_l);
auto nw2 = _networks.find(networkId);
@ -265,17 +224,17 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
}
if (nw) {
std::unique_lock<std::shared_mutex> l(nw->lock);
if (OSUtils::jsonBool(old["activeBridge"], false)) {
if (OSUtils::jsonBool(old["activeBridge"],false)) {
nw->activeBridgeMembers.erase(memberId);
}
wasAuth = OSUtils::jsonBool(old["authorized"], false);
wasAuth = OSUtils::jsonBool(old["authorized"],false);
if (wasAuth) {
nw->authorizedMembers.erase(memberId);
}
json& ips = old["ipAssignments"];
json &ips = old["ipAssignments"];
if (ips.is_array()) {
for (unsigned long i = 0; i < ips.size(); ++i) {
json& ipj = ips[i];
for(unsigned long i=0;i<ips.size();++i) {
json &ipj = ips[i];
if (ipj.is_string()) {
const std::string ips = ipj;
InetAddress ipa(ips.c_str());
@ -289,14 +248,14 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
}
if (memberConfig.is_object()) {
if (! nw) {
memberId = OSUtils::jsonIntHex(memberConfig["id"], 0ULL);
networkId = OSUtils::jsonIntHex(memberConfig["nwid"], 0ULL);
if ((! memberId) || (! networkId))
if (!nw) {
memberId = OSUtils::jsonIntHex(memberConfig["id"],0ULL);
networkId = OSUtils::jsonIntHex(memberConfig["nwid"],0ULL);
if ((!memberId)||(!networkId))
return;
std::unique_lock<std::shared_mutex> l(_networks_l);
std::shared_ptr<_Network>& nw2 = _networks[networkId];
if (! nw2)
std::shared_ptr<_Network> &nw2 = _networks[networkId];
if (!nw2)
nw2.reset(new _Network);
nw = nw2;
}
@ -306,18 +265,18 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
nw->members[memberId] = memberConfig;
if (OSUtils::jsonBool(memberConfig["activeBridge"], false)) {
if (OSUtils::jsonBool(memberConfig["activeBridge"],false)) {
nw->activeBridgeMembers.insert(memberId);
}
isAuth = OSUtils::jsonBool(memberConfig["authorized"], false);
isAuth = OSUtils::jsonBool(memberConfig["authorized"],false);
if (isAuth) {
Metrics::member_auths++;
nw->authorizedMembers.insert(memberId);
}
json& ips = memberConfig["ipAssignments"];
json &ips = memberConfig["ipAssignments"];
if (ips.is_array()) {
for (unsigned long i = 0; i < ips.size(); ++i) {
json& ipj = ips[i];
for(unsigned long i=0;i<ips.size();++i) {
json &ipj = ips[i];
if (ipj.is_string()) {
const std::string ips = ipj;
InetAddress ipa(ips.c_str());
@ -327,8 +286,8 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
}
}
if (! isAuth) {
const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"], 0ULL);
if (!isAuth) {
const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"],0ULL);
if (ldt > nw->mostRecentDeauthTime)
nw->mostRecentDeauthTime = ldt;
}
@ -336,12 +295,11 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
if (notifyListeners) {
std::unique_lock<std::shared_mutex> ll(_changeListeners_l);
for (auto i = _changeListeners.begin(); i != _changeListeners.end(); ++i) {
(*i)->onNetworkMemberUpdate(this, networkId, memberId, memberConfig);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkMemberUpdate(this,networkId,memberId,memberConfig);
}
}
}
else if (memberId) {
} else if (memberId) {
if (nw) {
std::unique_lock<std::shared_mutex> l(nw->lock);
nw->members.erase(memberId);
@ -349,7 +307,7 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
if (networkId) {
std::unique_lock<std::shared_mutex> l(_networks_l);
auto er = _networkByMember.equal_range(memberId);
for (auto i = er.first; i != er.second; ++i) {
for(auto i=er.first;i!=er.second;++i) {
if (i->second == networkId) {
_networkByMember.erase(i);
break;
@ -359,45 +317,40 @@ void DB::_memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool
}
if (notifyListeners) {
if (networkId != 0 && memberId != 0 && old.is_object() && ! memberConfig.is_object()) {
if(networkId != 0 && memberId != 0 && old.is_object() && !memberConfig.is_object()) {
// member delete
Metrics::member_count--;
}
else if (networkId != 0 && memberId != 0 && ! old.is_object() && memberConfig.is_object()) {
} else if (networkId != 0 && memberId != 0 && !old.is_object() && memberConfig.is_object()) {
// new member
Metrics::member_count++;
}
if (! wasAuth && isAuth) {
if (!wasAuth && isAuth) {
Metrics::member_auths++;
}
else if (wasAuth && ! isAuth) {
} else if (wasAuth && !isAuth) {
Metrics::member_deauths++;
}
else {
} else {
Metrics::member_changes++;
}
}
if ((notifyListeners) && ((wasAuth) && (! isAuth) && (networkId) && (memberId))) {
if ((notifyListeners)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) {
std::unique_lock<std::shared_mutex> ll(_changeListeners_l);
for (auto i = _changeListeners.begin(); i != _changeListeners.end(); ++i) {
(*i)->onNetworkMemberDeauthorize(this, networkId, memberId);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkMemberDeauthorize(this,networkId,memberId);
}
}
}
void DB::_networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, bool notifyListeners)
void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners)
{
Metrics::db_network_change++;
if (notifyListeners) {
if (old.is_object() && old.contains("id") && networkConfig.is_object() && networkConfig.contains("id")) {
Metrics::network_changes++;
}
else if (! old.is_object() && networkConfig.is_object() && networkConfig.contains("id")) {
} else if (!old.is_object() && networkConfig.is_object() && networkConfig.contains("id")) {
Metrics::network_count++;
}
else if (old.is_object() && old.contains("id") && ! networkConfig.is_object()) {
} else if (old.is_object() && old.contains("id") && !networkConfig.is_object()) {
Metrics::network_count--;
}
}
@ -409,8 +362,8 @@ void DB::_networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, boo
std::shared_ptr<_Network> nw;
{
std::unique_lock<std::shared_mutex> l(_networks_l);
std::shared_ptr<_Network>& nw2 = _networks[networkId];
if (! nw2)
std::shared_ptr<_Network> &nw2 = _networks[networkId];
if (!nw2)
nw2.reset(new _Network);
nw = nw2;
}
@ -420,52 +373,32 @@ void DB::_networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, boo
}
if (notifyListeners) {
std::unique_lock<std::shared_mutex> ll(_changeListeners_l);
for (auto i = _changeListeners.begin(); i != _changeListeners.end(); ++i) {
(*i)->onNetworkUpdate(this, networkId, networkConfig);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkUpdate(this,networkId,networkConfig);
}
}
}
}
else if (old.is_object()) {
} else if (old.is_object()) {
const std::string ids = old["id"];
const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
if (networkId) {
try {
// deauth all members on the network
nlohmann::json network;
std::vector<nlohmann::json> members;
this->get(networkId, network, members);
for (auto i = members.begin(); i != members.end(); ++i) {
const std::string nodeID = (*i)["id"];
const uint64_t memberId = Utils::hexStrToU64(nodeID.c_str());
std::unique_lock<std::shared_mutex> ll(_changeListeners_l);
for (auto j = _changeListeners.begin(); j != _changeListeners.end(); ++j) {
(*j)->onNetworkMemberDeauthorize(this, networkId, memberId);
}
}
}
catch (std::exception& e) {
std::cerr << "Error deauthorizing members on network delete: " << e.what() << std::endl;
}
// delete the network
std::unique_lock<std::shared_mutex> l(_networks_l);
_networks.erase(networkId);
}
}
}
void DB::_fillSummaryInfo(const std::shared_ptr<_Network>& nw, NetworkSummaryInfo& info)
void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
{
for (auto ab = nw->activeBridgeMembers.begin(); ab != nw->activeBridgeMembers.end(); ++ab)
for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
info.activeBridges.push_back(Address(*ab));
std::sort(info.activeBridges.begin(), info.activeBridges.end());
for (auto ip = nw->allocatedIps.begin(); ip != nw->allocatedIps.end(); ++ip)
std::sort(info.activeBridges.begin(),info.activeBridges.end());
for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
info.allocatedIps.push_back(*ip);
std::sort(info.allocatedIps.begin(), info.allocatedIps.end());
std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
info.totalMemberCount = (unsigned long)nw->members.size();
info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,36 +14,49 @@
#ifndef ZT_CONTROLLER_DB_HPP
#define ZT_CONTROLLER_DB_HPP
// #define ZT_CONTROLLER_USE_LIBPQ
//#define ZT_CONTROLLER_USE_LIBPQ
#include "../node/Constants.hpp"
#include "../node/Identity.hpp"
#include "../node/InetAddress.hpp"
#include "../osdep/BlockingQueue.hpp"
#include "../osdep/OSUtils.hpp"
#include "../osdep/BlockingQueue.hpp"
#include <atomic>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include <prometheus/simpleapi.h>
#include <set>
#include <shared_mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <atomic>
#include <shared_mutex>
#include <set>
#include <map>
#include <nlohmann/json.hpp>
#include <prometheus/simpleapi.h>
#define ZT_MEMBER_AUTH_TIMEOUT_NOTIFY_BEFORE 25000
namespace ZeroTier {
namespace ZeroTier
{
struct AuthInfo {
public:
AuthInfo() : enabled(false), version(0), authenticationURL(), authenticationExpiryTime(0), issuerURL(), centralAuthURL(), ssoNonce(), ssoState(), ssoClientID(), ssoProvider("default")
{
}
struct AuthInfo
{
public:
AuthInfo()
: enabled(false)
, version(0)
, authenticationURL()
, authenticationExpiryTime(0)
, issuerURL()
, centralAuthURL()
, ssoNonce()
, ssoState()
, ssoClientID()
, ssoProvider("default")
{}
bool enabled;
uint64_t version;
@ -60,35 +73,22 @@ struct AuthInfo {
/**
* Base class with common infrastructure for all controller DB implementations
*/
class DB {
#ifdef ZT_CONTROLLER_USE_LIBPQ
friend class MemberNotificationReceiver;
friend class NetworkNotificationReceiver;
#endif
public:
class ChangeListener {
public:
ChangeListener()
{
}
virtual ~ChangeListener()
{
}
virtual void onNetworkUpdate(const void* db, uint64_t networkId, const nlohmann::json& network)
{
}
virtual void onNetworkMemberUpdate(const void* db, uint64_t networkId, uint64_t memberId, const nlohmann::json& member)
{
}
virtual void onNetworkMemberDeauthorize(const void* db, uint64_t networkId, uint64_t memberId)
{
}
class DB
{
public:
class ChangeListener
{
public:
ChangeListener() {}
virtual ~ChangeListener() {}
virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network) {}
virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member) {}
virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId) {}
};
struct NetworkSummaryInfo {
NetworkSummaryInfo() : authorizedMemberCount(0), totalMemberCount(0), mostRecentDeauthTime(0)
{
}
struct NetworkSummaryInfo
{
NetworkSummaryInfo() : authorizedMemberCount(0),totalMemberCount(0),mostRecentDeauthTime(0) {}
std::vector<Address> activeBridges;
std::vector<InetAddress> allocatedIps;
unsigned long authorizedMemberCount;
@ -96,10 +96,10 @@ class DB {
int64_t mostRecentDeauthTime;
};
static void initNetwork(nlohmann::json& network);
static void initMember(nlohmann::json& member);
static void cleanNetwork(nlohmann::json& network);
static void cleanMember(nlohmann::json& member);
static void initNetwork(nlohmann::json &network);
static void initMember(nlohmann::json &member);
static void cleanNetwork(nlohmann::json &network);
static void cleanMember(nlohmann::json &member);
DB();
virtual ~DB();
@ -113,44 +113,41 @@ class DB {
return (_networks.find(networkId) != _networks.end());
}
bool get(const uint64_t networkId, nlohmann::json& network);
bool get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member);
bool get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member, NetworkSummaryInfo& info);
bool get(const uint64_t networkId, nlohmann::json& network, std::vector<nlohmann::json>& members);
bool get(const uint64_t networkId,nlohmann::json &network);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info);
bool get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members);
void networks(std::set<uint64_t>& networks);
void networks(std::set<uint64_t> &networks);
template <typename F> inline void each(F f)
template<typename F>
inline void each(F f)
{
nlohmann::json nullJson;
std::unique_lock<std::shared_mutex> lck(_networks_l);
for (auto nw = _networks.begin(); nw != _networks.end(); ++nw) {
f(nw->first, nw->second->config, 0, nullJson); // first provide network with 0 for member ID
for (auto m = nw->second->members.begin(); m != nw->second->members.end(); ++m) {
f(nw->first, nw->second->config, m->first, m->second);
for(auto nw=_networks.begin();nw!=_networks.end();++nw) {
f(nw->first,nw->second->config,0,nullJson); // first provide network with 0 for member ID
for(auto m=nw->second->members.begin();m!=nw->second->members.end();++m) {
f(nw->first,nw->second->config,m->first,m->second);
}
}
}
virtual bool save(nlohmann::json& record, bool notifyListeners) = 0;
virtual bool save(nlohmann::json &record,bool notifyListeners) = 0;
virtual void eraseNetwork(const uint64_t networkId) = 0;
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId) = 0;
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress) = 0;
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch) = 0;
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId) = 0;
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress) = 0;
virtual AuthInfo getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL)
{
return AuthInfo();
}
virtual AuthInfo getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL) { return AuthInfo(); }
inline void addListener(DB::ChangeListener* const listener)
inline void addListener(DB::ChangeListener *const listener)
{
std::unique_lock<std::shared_mutex> l(_changeListeners_l);
_changeListeners.push_back(listener);
}
protected:
static inline bool _compareRecords(const nlohmann::json& a, const nlohmann::json& b)
protected:
static inline bool _compareRecords(const nlohmann::json &a,const nlohmann::json &b)
{
if (a.is_object() == b.is_object()) {
if (a.is_object()) {
@ -158,10 +155,10 @@ class DB {
return false;
auto amap = a.get<nlohmann::json::object_t>();
auto bmap = b.get<nlohmann::json::object_t>();
for (auto ai = amap.begin(); ai != amap.end(); ++ai) {
if (ai->first != "revision") { // ignore revision, compare only non-revision-counter fields
for(auto ai=amap.begin();ai!=amap.end();++ai) {
if (ai->first != "revision") { // ignore revision, compare only non-revision-counter fields
auto bi = bmap.find(ai->first);
if ((bi == bmap.end()) || (bi->second != ai->second))
if ((bi == bmap.end())||(bi->second != ai->second))
return false;
}
}
@ -172,30 +169,29 @@ class DB {
return false;
}
struct _Network {
_Network() : mostRecentDeauthTime(0)
{
}
struct _Network
{
_Network() : mostRecentDeauthTime(0) {}
nlohmann::json config;
std::unordered_map<uint64_t, nlohmann::json> members;
std::unordered_map<uint64_t,nlohmann::json> members;
std::unordered_set<uint64_t> activeBridgeMembers;
std::unordered_set<uint64_t> authorizedMembers;
std::unordered_set<InetAddress, InetAddress::Hasher> allocatedIps;
std::unordered_set<InetAddress,InetAddress::Hasher> allocatedIps;
int64_t mostRecentDeauthTime;
std::shared_mutex lock;
};
virtual void _memberChanged(nlohmann::json& old, nlohmann::json& memberConfig, bool notifyListeners);
virtual void _networkChanged(nlohmann::json& old, nlohmann::json& networkConfig, bool notifyListeners);
void _fillSummaryInfo(const std::shared_ptr<_Network>& nw, NetworkSummaryInfo& info);
virtual void _memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners);
virtual void _networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners);
void _fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info);
std::vector<DB::ChangeListener*> _changeListeners;
std::unordered_map<uint64_t, std::shared_ptr<_Network> > _networks;
std::unordered_multimap<uint64_t, uint64_t> _networkByMember;
std::vector<DB::ChangeListener *> _changeListeners;
std::unordered_map< uint64_t,std::shared_ptr<_Network> > _networks;
std::unordered_multimap< uint64_t,uint64_t > _networkByMember;
mutable std::shared_mutex _changeListeners_l;
mutable std::shared_mutex _networks_l;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -15,54 +15,56 @@
namespace ZeroTier {
DBMirrorSet::DBMirrorSet(DB::ChangeListener* listener) : _listener(listener), _running(true), _syncCheckerThread(), _dbs(), _dbs_l()
DBMirrorSet::DBMirrorSet(DB::ChangeListener *listener)
: _listener(listener)
, _running(true)
, _syncCheckerThread()
, _dbs()
, _dbs_l()
{
_syncCheckerThread = std::thread([this]() {
for (;;) {
for (int i = 0; i < 120; ++i) { // 1 minute delay between checks
if (! _running)
for(;;) {
for(int i=0;i<120;++i) { // 1 minute delay between checks
if (!_running)
return;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::vector<std::shared_ptr<DB> > dbs;
std::vector< std::shared_ptr<DB> > dbs;
{
std::unique_lock<std::shared_mutex> l(_dbs_l);
if (_dbs.size() <= 1)
continue; // no need to do this if there's only one DB, so skip the iteration
continue; // no need to do this if there's only one DB, so skip the iteration
dbs = _dbs;
}
for (auto db = dbs.begin(); db != dbs.end(); ++db) {
(*db)->each([&dbs, &db](uint64_t networkId, const nlohmann::json& network, uint64_t memberId, const nlohmann::json& member) {
for(auto db=dbs.begin();db!=dbs.end();++db) {
(*db)->each([&dbs,&db](uint64_t networkId,const nlohmann::json &network,uint64_t memberId,const nlohmann::json &member) {
try {
if (network.is_object()) {
if (memberId == 0) {
for (auto db2 = dbs.begin(); db2 != dbs.end(); ++db2) {
for(auto db2=dbs.begin();db2!=dbs.end();++db2) {
if (db->get() != db2->get()) {
nlohmann::json nw2;
if ((! (*db2)->get(networkId, nw2)) || ((nw2.is_object()) && (OSUtils::jsonInt(nw2["revision"], 0) < OSUtils::jsonInt(network["revision"], 0)))) {
if ((!(*db2)->get(networkId,nw2))||((nw2.is_object())&&(OSUtils::jsonInt(nw2["revision"],0) < OSUtils::jsonInt(network["revision"],0)))) {
nw2 = network;
(*db2)->save(nw2, false);
(*db2)->save(nw2,false);
}
}
}
}
else if (member.is_object()) {
for (auto db2 = dbs.begin(); db2 != dbs.end(); ++db2) {
} else if (member.is_object()) {
for(auto db2=dbs.begin();db2!=dbs.end();++db2) {
if (db->get() != db2->get()) {
nlohmann::json nw2, m2;
if ((! (*db2)->get(networkId, nw2, memberId, m2)) || ((m2.is_object()) && (OSUtils::jsonInt(m2["revision"], 0) < OSUtils::jsonInt(member["revision"], 0)))) {
nlohmann::json nw2,m2;
if ((!(*db2)->get(networkId,nw2,memberId,m2))||((m2.is_object())&&(OSUtils::jsonInt(m2["revision"],0) < OSUtils::jsonInt(member["revision"],0)))) {
m2 = member;
(*db2)->save(m2, false);
(*db2)->save(m2,false);
}
}
}
}
}
}
catch (...) {
} // skip entries that generate JSON errors
} catch ( ... ) {} // skip entries that generate JSON errors
});
}
}
@ -78,58 +80,58 @@ DBMirrorSet::~DBMirrorSet()
bool DBMirrorSet::hasNetwork(const uint64_t networkId) const
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->hasNetwork(networkId))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId, nlohmann::json& network)
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
if ((*d)->get(networkId, network)) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network)) {
return true;
}
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member)
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
if ((*d)->get(networkId, network, memberId, member))
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,memberId,member))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member, DB::NetworkSummaryInfo& info)
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,DB::NetworkSummaryInfo &info)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
if ((*d)->get(networkId, network, memberId, member, info))
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,memberId,member,info))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId, nlohmann::json& network, std::vector<nlohmann::json>& members)
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
if ((*d)->get(networkId, network, members))
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,members))
return true;
}
return false;
}
AuthInfo DBMirrorSet::getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL)
AuthInfo DBMirrorSet::getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
AuthInfo info = (*d)->getSSOAuthInfo(member, redirectURL);
if (info.enabled) {
return info;
@ -138,10 +140,10 @@ AuthInfo DBMirrorSet::getSSOAuthInfo(const nlohmann::json& member, const std::st
return AuthInfo();
}
void DBMirrorSet::networks(std::set<uint64_t>& networks)
void DBMirrorSet::networks(std::set<uint64_t> &networks)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->networks(networks);
}
}
@ -150,7 +152,7 @@ bool DBMirrorSet::waitForReady()
{
bool r = false;
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
r |= (*d)->waitForReady();
}
return r;
@ -159,31 +161,30 @@ bool DBMirrorSet::waitForReady()
bool DBMirrorSet::isReady()
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
if (! (*d)->isReady())
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (!(*d)->isReady())
return false;
}
return true;
}
bool DBMirrorSet::save(nlohmann::json& record, bool notifyListeners)
bool DBMirrorSet::save(nlohmann::json &record,bool notifyListeners)
{
std::vector<std::shared_ptr<DB> > dbs;
std::vector< std::shared_ptr<DB> > dbs;
{
std::unique_lock<std::shared_mutex> l(_dbs_l);
dbs = _dbs;
}
if (notifyListeners) {
for (auto d = dbs.begin(); d != dbs.end(); ++d) {
if ((*d)->save(record, true))
for(auto d=dbs.begin();d!=dbs.end();++d) {
if ((*d)->save(record,true))
return true;
}
return false;
}
else {
} else {
bool modified = false;
for (auto d = dbs.begin(); d != dbs.end(); ++d) {
modified |= (*d)->save(record, false);
for(auto d=dbs.begin();d!=dbs.end();++d) {
modified |= (*d)->save(record,false);
}
return modified;
}
@ -192,59 +193,54 @@ bool DBMirrorSet::save(nlohmann::json& record, bool notifyListeners)
void DBMirrorSet::eraseNetwork(const uint64_t networkId)
{
std::unique_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->eraseNetwork(networkId);
}
}
void DBMirrorSet::eraseMember(const uint64_t networkId, const uint64_t memberId)
void DBMirrorSet::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
std::unique_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
(*d)->eraseMember(networkId, memberId);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->eraseMember(networkId,memberId);
}
}
void DBMirrorSet::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch)
void DBMirrorSet::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
std::shared_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
(*d)->nodeIsOnline(networkId, memberId, physicalAddress, osArch);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->nodeIsOnline(networkId,memberId,physicalAddress);
}
}
void DBMirrorSet::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
{
this->nodeIsOnline(networkId, memberId, physicalAddress, "unknown/unknown");
}
void DBMirrorSet::onNetworkUpdate(const void* db, uint64_t networkId, const nlohmann::json& network)
void DBMirrorSet::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
{
nlohmann::json record(network);
std::unique_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (d->get() != db) {
(*d)->save(record, false);
(*d)->save(record,false);
}
}
_listener->onNetworkUpdate(this, networkId, network);
_listener->onNetworkUpdate(this,networkId,network);
}
void DBMirrorSet::onNetworkMemberUpdate(const void* db, uint64_t networkId, uint64_t memberId, const nlohmann::json& member)
void DBMirrorSet::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
{
nlohmann::json record(member);
std::unique_lock<std::shared_mutex> l(_dbs_l);
for (auto d = _dbs.begin(); d != _dbs.end(); ++d) {
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (d->get() != db) {
(*d)->save(record, false);
(*d)->save(record,false);
}
}
_listener->onNetworkMemberUpdate(this, networkId, memberId, member);
_listener->onNetworkMemberUpdate(this,networkId,memberId,member);
}
void DBMirrorSet::onNetworkMemberDeauthorize(const void* db, uint64_t networkId, uint64_t memberId)
void DBMirrorSet::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
{
_listener->onNetworkMemberDeauthorize(this, networkId, memberId);
_listener->onNetworkMemberDeauthorize(this,networkId,memberId);
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -16,58 +16,58 @@
#include "DB.hpp"
#include <memory>
#include <set>
#include <shared_mutex>
#include <thread>
#include <vector>
#include <memory>
#include <shared_mutex>
#include <set>
#include <thread>
namespace ZeroTier {
class DBMirrorSet : public DB::ChangeListener {
public:
DBMirrorSet(DB::ChangeListener* listener);
class DBMirrorSet : public DB::ChangeListener
{
public:
DBMirrorSet(DB::ChangeListener *listener);
virtual ~DBMirrorSet();
bool hasNetwork(const uint64_t networkId) const;
bool get(const uint64_t networkId, nlohmann::json& network);
bool get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member);
bool get(const uint64_t networkId, nlohmann::json& network, const uint64_t memberId, nlohmann::json& member, DB::NetworkSummaryInfo& info);
bool get(const uint64_t networkId, nlohmann::json& network, std::vector<nlohmann::json>& members);
bool get(const uint64_t networkId,nlohmann::json &network);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,DB::NetworkSummaryInfo &info);
bool get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members);
void networks(std::set<uint64_t>& networks);
void networks(std::set<uint64_t> &networks);
bool waitForReady();
bool isReady();
bool save(nlohmann::json& record, bool notifyListeners);
bool save(nlohmann::json &record,bool notifyListeners);
void eraseNetwork(const uint64_t networkId);
void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch);
void eraseMember(const uint64_t networkId,const uint64_t memberId);
void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
// These are called by various DB instances when changes occur.
virtual void onNetworkUpdate(const void* db, uint64_t networkId, const nlohmann::json& network);
virtual void onNetworkMemberUpdate(const void* db, uint64_t networkId, uint64_t memberId, const nlohmann::json& member);
virtual void onNetworkMemberDeauthorize(const void* db, uint64_t networkId, uint64_t memberId);
virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network);
virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member);
virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId);
AuthInfo getSSOAuthInfo(const nlohmann::json& member, const std::string& redirectURL);
AuthInfo getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL);
inline void addDB(const std::shared_ptr<DB>& db)
inline void addDB(const std::shared_ptr<DB> &db)
{
db->addListener(this);
std::unique_lock<std::shared_mutex> l(_dbs_l);
_dbs.push_back(db);
}
private:
DB::ChangeListener* const _listener;
private:
DB::ChangeListener *const _listener;
std::atomic_bool _running;
std::thread _syncCheckerThread;
std::vector<std::shared_ptr<DB> > _dbs;
std::vector< std::shared_ptr< DB > > _dbs;
mutable std::shared_mutex _dbs_l;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,109 +14,112 @@
#ifndef ZT_SQLITENETWORKCONTROLLER_HPP
#define ZT_SQLITENETWORKCONTROLLER_HPP
#include "../node/Address.hpp"
#include "../node/Constants.hpp"
#include "../node/InetAddress.hpp"
#include "../node/NetworkController.hpp"
#include "../node/Utils.hpp"
#include "../osdep/BlockingQueue.hpp"
#include "../osdep/OSUtils.hpp"
#include "../osdep/Thread.hpp"
#include "DB.hpp"
#include "DBMirrorSet.hpp"
#include <atomic>
#include <cpp-httplib/httplib.h>
#include <list>
#include <map>
#include <nlohmann/json.hpp>
#include <set>
#include <stdint.h>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <list>
#include <thread>
#include <unordered_map>
#include <vector>
#include <atomic>
#include "../node/Constants.hpp"
#include "../node/NetworkController.hpp"
#include "../node/Utils.hpp"
#include "../node/Address.hpp"
#include "../node/InetAddress.hpp"
#include "../osdep/OSUtils.hpp"
#include "../osdep/Thread.hpp"
#include "../osdep/BlockingQueue.hpp"
#include <nlohmann/json.hpp>
#include <cpp-httplib/httplib.h>
#include "DB.hpp"
#include "DBMirrorSet.hpp"
namespace ZeroTier {
class Node;
struct RedisConfig;
class EmbeddedNetworkController
: public NetworkController
, public DB::ChangeListener {
public:
class EmbeddedNetworkController : public NetworkController,public DB::ChangeListener
{
public:
/**
* @param node Parent node
* @param dbPath Database path (file path or database credentials)
*/
EmbeddedNetworkController(Node* node, const char* ztPath, const char* dbPath, int listenPort, RedisConfig* rc);
EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, RedisConfig *rc);
virtual ~EmbeddedNetworkController();
virtual void init(const Identity& signingId, Sender* sender);
virtual void init(const Identity &signingId,Sender *sender);
void setSSORedirectURL(const std::string& url);
void setSSORedirectURL(const std::string &url);
virtual void request(uint64_t nwid, const InetAddress& fromAddr, uint64_t requestPacketId, const Identity& identity, const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>& metaData);
virtual void request(
uint64_t nwid,
const InetAddress &fromAddr,
uint64_t requestPacketId,
const Identity &identity,
const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
void configureHTTPControlPlane(httplib::Server& s, httplib::Server& sV6, const std::function<void(const httplib::Request&, httplib::Response&, std::string)>);
void configureHTTPControlPlane(
httplib::Server &s,
httplib::Server &sV6,
const std::function<void(const httplib::Request&, httplib::Response&, std::string)>);
void handleRemoteTrace(const ZT_RemoteTrace& rt);
void handleRemoteTrace(const ZT_RemoteTrace &rt);
virtual void onNetworkUpdate(const void* db, uint64_t networkId, const nlohmann::json& network);
virtual void onNetworkMemberUpdate(const void* db, uint64_t networkId, uint64_t memberId, const nlohmann::json& member);
virtual void onNetworkMemberDeauthorize(const void* db, uint64_t networkId, uint64_t memberId);
virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network);
virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member);
virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId);
private:
void _request(uint64_t nwid, const InetAddress& fromAddr, uint64_t requestPacketId, const Identity& identity, const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>& metaData);
private:
void _request(uint64_t nwid,const InetAddress &fromAddr,uint64_t requestPacketId,const Identity &identity,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
void _startThreads();
void _ssoExpiryThread();
std::string networkUpdateFromPostData(uint64_t networkID, const std::string& body);
std::string networkUpdateFromPostData(uint64_t networkID, const std::string &body);
struct _RQEntry {
struct _RQEntry
{
uint64_t nwid;
uint64_t requestPacketId;
InetAddress fromAddr;
Identity identity;
Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData;
enum { RQENTRY_TYPE_REQUEST = 0 } type;
enum {
RQENTRY_TYPE_REQUEST = 0
} type;
};
struct _MemberStatusKey {
_MemberStatusKey() : networkId(0), nodeId(0)
{
}
_MemberStatusKey(const uint64_t nwid, const uint64_t nid) : networkId(nwid), nodeId(nid)
{
}
struct _MemberStatusKey
{
_MemberStatusKey() : networkId(0),nodeId(0) {}
_MemberStatusKey(const uint64_t nwid,const uint64_t nid) : networkId(nwid),nodeId(nid) {}
uint64_t networkId;
uint64_t nodeId;
inline bool operator==(const _MemberStatusKey& k) const
{
return ((k.networkId == networkId) && (k.nodeId == nodeId));
}
inline bool operator<(const _MemberStatusKey& k) const
{
return (k.networkId < networkId) || ((k.networkId == networkId) && (k.nodeId < nodeId));
}
inline bool operator==(const _MemberStatusKey &k) const { return ((k.networkId == networkId)&&(k.nodeId == nodeId)); }
inline bool operator<(const _MemberStatusKey &k) const { return (k.networkId < networkId) || ((k.networkId == networkId)&&(k.nodeId < nodeId)); }
};
struct _MemberStatus {
_MemberStatus() : lastRequestTime(0), authenticationExpiryTime(-1), vMajor(-1), vMinor(-1), vRev(-1), vProto(-1)
{
}
struct _MemberStatus
{
_MemberStatus() : lastRequestTime(0),authenticationExpiryTime(-1),vMajor(-1),vMinor(-1),vRev(-1),vProto(-1) {}
int64_t lastRequestTime;
int64_t authenticationExpiryTime;
int vMajor, vMinor, vRev, vProto;
int vMajor,vMinor,vRev,vProto;
Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> lastRequestMetaData;
Identity identity;
inline bool online(const int64_t now) const
{
return ((now - lastRequestTime) < (ZT_NETWORK_AUTOCONF_DELAY * 2));
}
inline bool online(const int64_t now) const { return ((now - lastRequestTime) < (ZT_NETWORK_AUTOCONF_DELAY * 2)); }
};
struct _MemberStatusHash {
inline std::size_t operator()(const _MemberStatusKey& networkIdNodeId) const
struct _MemberStatusHash
{
inline std::size_t operator()(const _MemberStatusKey &networkIdNodeId) const
{
return (std::size_t)(networkIdNodeId.networkId + networkIdNodeId.nodeId);
}
@ -124,26 +127,26 @@ class EmbeddedNetworkController
const int64_t _startTime;
int _listenPort;
Node* const _node;
Node *const _node;
std::string _ztPath;
std::string _path;
Identity _signingId;
std::string _signingIdAddressString;
NetworkController::Sender* _sender;
NetworkController::Sender *_sender;
DBMirrorSet _db;
BlockingQueue<_RQEntry*> _queue;
BlockingQueue< _RQEntry * > _queue;
std::vector<std::thread> _threads;
std::mutex _threads_l;
std::unordered_map<_MemberStatusKey, _MemberStatus, _MemberStatusHash> _memberStatus;
std::unordered_map< _MemberStatusKey,_MemberStatus,_MemberStatusHash > _memberStatus;
std::mutex _memberStatus_l;
std::set<std::pair<int64_t, _MemberStatusKey> > _expiringSoon;
std::set< std::pair<int64_t, _MemberStatusKey> > _expiringSoon;
std::mutex _expiringSoon_l;
RedisConfig* _rc;
RedisConfig *_rc;
std::string _ssoRedirectURL;
bool _ssoExpiryRunning;
@ -151,30 +154,30 @@ class EmbeddedNetworkController
#ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
prometheus::simpleapi::benchmark_family_t _member_status_lookup;
prometheus::simpleapi::counter_family_t _member_status_lookup_count;
prometheus::simpleapi::counter_family_t _member_status_lookup_count;
prometheus::simpleapi::benchmark_family_t _node_is_online;
prometheus::simpleapi::counter_family_t _node_is_online_count;
prometheus::simpleapi::counter_family_t _node_is_online_count;
prometheus::simpleapi::benchmark_family_t _get_and_init_member;
prometheus::simpleapi::counter_family_t _get_and_init_member_count;
prometheus::simpleapi::counter_family_t _get_and_init_member_count;
prometheus::simpleapi::benchmark_family_t _have_identity;
prometheus::simpleapi::counter_family_t _have_identity_count;
prometheus::simpleapi::counter_family_t _have_identity_count;
prometheus::simpleapi::benchmark_family_t _determine_auth;
prometheus::simpleapi::counter_family_t _determine_auth_count;
prometheus::simpleapi::counter_family_t _determine_auth_count;
prometheus::simpleapi::benchmark_family_t _sso_check;
prometheus::simpleapi::counter_family_t _sso_check_count;
prometheus::simpleapi::counter_family_t _sso_check_count;
prometheus::simpleapi::benchmark_family_t _auth_check;
prometheus::simpleapi::counter_family_t _auth_check_count;
prometheus::simpleapi::counter_family_t _auth_check_count;
prometheus::simpleapi::benchmark_family_t _json_schlep;
prometheus::simpleapi::counter_family_t _json_schlep_count;
prometheus::simpleapi::counter_family_t _json_schlep_count;
prometheus::simpleapi::benchmark_family_t _issue_certificate;
prometheus::simpleapi::counter_family_t _issue_certificate_count;
prometheus::simpleapi::counter_family_t _issue_certificate_count;
prometheus::simpleapi::benchmark_family_t _save_member;
prometheus::simpleapi::counter_family_t _save_member_count;
prometheus::simpleapi::counter_family_t _save_member_count;
prometheus::simpleapi::benchmark_family_t _send_netconf;
prometheus::simpleapi::counter_family_t _send_netconf_count;
prometheus::simpleapi::counter_family_t _send_netconf_count;
#endif
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -15,49 +15,51 @@
#include "../node/Metrics.hpp"
namespace ZeroTier {
namespace ZeroTier
{
FileDB::FileDB(const char* path) : DB(), _path(path), _networksPath(_path + ZT_PATH_SEPARATOR_S + "network"), _tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"), _running(true)
FileDB::FileDB(const char *path) :
DB(),
_path(path),
_networksPath(_path + ZT_PATH_SEPARATOR_S + "network"),
_tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"),
_running(true)
{
OSUtils::mkdir(_path.c_str());
OSUtils::lockDownFile(_path.c_str(), true);
OSUtils::lockDownFile(_path.c_str(),true);
OSUtils::mkdir(_networksPath.c_str());
OSUtils::mkdir(_tracePath.c_str());
std::vector<std::string> networks(OSUtils::listDirectory(_networksPath.c_str(), false));
std::vector<std::string> networks(OSUtils::listDirectory(_networksPath.c_str(),false));
std::string buf;
for (auto n = networks.begin(); n != networks.end(); ++n) {
for(auto n=networks.begin();n!=networks.end();++n) {
buf.clear();
if ((n->length() == 21) && (OSUtils::readFile((_networksPath + ZT_PATH_SEPARATOR_S + *n).c_str(), buf))) {
if ((n->length() == 21)&&(OSUtils::readFile((_networksPath + ZT_PATH_SEPARATOR_S + *n).c_str(),buf))) {
try {
nlohmann::json network(OSUtils::jsonParse(buf));
const std::string nwids = network["id"];
if (nwids.length() == 16) {
nlohmann::json nullJson;
_networkChanged(nullJson, network, false);
_networkChanged(nullJson,network,false);
Metrics::network_count++;
std::string membersPath(_networksPath + ZT_PATH_SEPARATOR_S + nwids + ZT_PATH_SEPARATOR_S "member");
std::vector<std::string> members(OSUtils::listDirectory(membersPath.c_str(), false));
for (auto m = members.begin(); m != members.end(); ++m) {
std::vector<std::string> members(OSUtils::listDirectory(membersPath.c_str(),false));
for(auto m=members.begin();m!=members.end();++m) {
buf.clear();
if ((m->length() == 15) && (OSUtils::readFile((membersPath + ZT_PATH_SEPARATOR_S + *m).c_str(), buf))) {
if ((m->length() == 15)&&(OSUtils::readFile((membersPath + ZT_PATH_SEPARATOR_S + *m).c_str(),buf))) {
try {
nlohmann::json member(OSUtils::jsonParse(buf));
const std::string addrs = member["id"];
if (addrs.length() == 10) {
nlohmann::json nullJson2;
_memberChanged(nullJson2, member, false);
_memberChanged(nullJson2,member,false);
Metrics::member_count++;
}
}
catch (...) {
}
} catch ( ... ) {}
}
}
}
}
catch (...) {
}
} catch ( ... ) {}
}
}
}
@ -69,109 +71,97 @@ FileDB::~FileDB()
_running = false;
_online_l.unlock();
_onlineUpdateThread.join();
}
catch (...) {
}
} catch ( ... ) {}
}
bool FileDB::waitForReady()
{
return true;
}
bool FileDB::isReady()
{
return true;
}
bool FileDB::waitForReady() { return true; }
bool FileDB::isReady() { return true; }
bool FileDB::save(nlohmann::json& record, bool notifyListeners)
bool FileDB::save(nlohmann::json &record,bool notifyListeners)
{
char p1[4096], p2[4096], pb[4096];
char p1[4096],p2[4096],pb[4096];
bool modified = false;
try {
const std::string objtype = record["objtype"];
if (objtype == "network") {
const uint64_t nwid = OSUtils::jsonIntHex(record["id"], 0ULL);
const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (nwid) {
nlohmann::json old;
get(nwid, old);
if ((! old.is_object()) || (! _compareRecords(old, record))) {
record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
OSUtils::ztsnprintf(p1, sizeof(p1), "%s" ZT_PATH_SEPARATOR_S "%.16llx.json", _networksPath.c_str(), nwid);
if (! OSUtils::writeFile(p1, OSUtils::jsonDump(record, -1))) {
fprintf(stderr, "WARNING: controller unable to write to path: %s" ZT_EOL_S, p1);
get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
}
_networkChanged(old, record, notifyListeners);
_networkChanged(old,record,notifyListeners);
modified = true;
}
}
}
else if (objtype == "member") {
const uint64_t id = OSUtils::jsonIntHex(record["id"], 0ULL);
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"], 0ULL);
if ((id) && (nwid)) {
nlohmann::json network, old;
get(nwid, network, id, old);
if ((! old.is_object()) || (! _compareRecords(old, record))) {
record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
OSUtils::ztsnprintf(pb, sizeof(pb), "%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member", _networksPath.c_str(), (unsigned long long)nwid);
OSUtils::ztsnprintf(p1, sizeof(p1), "%s" ZT_PATH_SEPARATOR_S "%.10llx.json", pb, (unsigned long long)id);
if (! OSUtils::writeFile(p1, OSUtils::jsonDump(record, -1))) {
OSUtils::ztsnprintf(p2, sizeof(p2), "%s" ZT_PATH_SEPARATOR_S "%.16llx", _networksPath.c_str(), (unsigned long long)nwid);
} else if (objtype == "member") {
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
if ((id)&&(nwid)) {
nlohmann::json network,old;
get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid);
OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id);
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid);
OSUtils::mkdir(p2);
OSUtils::mkdir(pb);
if (! OSUtils::writeFile(p1, OSUtils::jsonDump(record, -1))) {
fprintf(stderr, "WARNING: controller unable to write to path: %s" ZT_EOL_S, p1);
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
}
}
_memberChanged(old, record, notifyListeners);
_memberChanged(old,record,notifyListeners);
modified = true;
}
}
}
}
catch (...) {
} // drop invalid records missing fields
} catch ( ... ) {} // drop invalid records missing fields
return modified;
}
void FileDB::eraseNetwork(const uint64_t networkId)
{
nlohmann::json network, nullJson;
get(networkId, network);
nlohmann::json network,nullJson;
get(networkId,network);
char p[16384];
OSUtils::ztsnprintf(p, sizeof(p), "%s" ZT_PATH_SEPARATOR_S "%.16llx.json", _networksPath.c_str(), networkId);
OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId);
OSUtils::rm(p);
OSUtils::ztsnprintf(p, sizeof(p), "%s" ZT_PATH_SEPARATOR_S "%.16llx", _networksPath.c_str(), (unsigned long long)networkId);
OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)networkId);
OSUtils::rmDashRf(p);
_networkChanged(network, nullJson, true);
_networkChanged(network,nullJson,true);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online.erase(networkId);
}
void FileDB::eraseMember(const uint64_t networkId, const uint64_t memberId)
void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
nlohmann::json network, member, nullJson;
get(networkId, network, memberId, member);
nlohmann::json network,member,nullJson;
get(networkId,network,memberId,member);
char p[4096];
OSUtils::ztsnprintf(p, sizeof(p), "%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json", _networksPath.c_str(), networkId, memberId);
OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json",_networksPath.c_str(),networkId,memberId);
OSUtils::rm(p);
_memberChanged(member, nullJson, true);
_memberChanged(member,nullJson,true);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online[networkId].erase(memberId);
}
void FileDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch)
void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
char mid[32], atmp[64];
OSUtils::ztsnprintf(mid, sizeof(mid), "%.10llx", (unsigned long long)memberId);
char mid[32],atmp[64];
OSUtils::ztsnprintf(mid,sizeof(mid),"%.10llx",(unsigned long long)memberId);
physicalAddress.toString(atmp);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online[networkId][memberId][OSUtils::now()] = physicalAddress;
}
void FileDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
{
this->nodeIsOnline(networkId, memberId, physicalAddress, "unknown/unknown");
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -16,31 +16,32 @@
#include "DB.hpp"
namespace ZeroTier {
namespace ZeroTier
{
class FileDB : public DB {
public:
FileDB(const char* path);
class FileDB : public DB
{
public:
FileDB(const char *path);
virtual ~FileDB();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json& record, bool notifyListeners);
virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch);
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
protected:
protected:
std::string _path;
std::string _networksPath;
std::string _tracePath;
std::thread _onlineUpdateThread;
std::map<uint64_t, std::map<uint64_t, std::map<int64_t, InetAddress> > > _online;
std::map< uint64_t,std::map<uint64_t,std::map<int64_t,InetAddress> > > _online;
std::mutex _online_l;
bool _running;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -13,52 +13,51 @@
#include "LFDB.hpp"
#include "../ext/cpp-httplib/httplib.h"
#include "../osdep/OSUtils.hpp"
#include <thread>
#include <chrono>
#include <iostream>
#include <sstream>
#include <thread>
namespace ZeroTier {
#include "../osdep/OSUtils.hpp"
#include "../ext/cpp-httplib/httplib.h"
LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, const char* lfOwnerPublic, const char* lfNodeHost, int lfNodePort, bool storeOnlineState)
: DB()
, _myId(myId)
, _lfOwnerPrivate((lfOwnerPrivate) ? lfOwnerPrivate : "")
, _lfOwnerPublic((lfOwnerPublic) ? lfOwnerPublic : "")
, _lfNodeHost((lfNodeHost) ? lfNodeHost : "127.0.0.1")
, _lfNodePort(((lfNodePort > 0) && (lfNodePort < 65536)) ? lfNodePort : 9980)
, _running(true)
, _ready(false)
, _storeOnlineState(storeOnlineState)
namespace ZeroTier
{
LFDB::LFDB(const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
DB(),
_myId(myId),
_lfOwnerPrivate((lfOwnerPrivate) ? lfOwnerPrivate : ""),
_lfOwnerPublic((lfOwnerPublic) ? lfOwnerPublic : ""),
_lfNodeHost((lfNodeHost) ? lfNodeHost : "127.0.0.1"),
_lfNodePort(((lfNodePort > 0)&&(lfNodePort < 65536)) ? lfNodePort : 9980),
_running(true),
_ready(false),
_storeOnlineState(storeOnlineState)
{
_syncThread = std::thread([this]() {
char controllerAddress[24];
const uint64_t controllerAddressInt = _myId.address().toInt();
_myId.address().toString(controllerAddress);
std::string networksSelectorName("com.zerotier.controller.lfdb:");
networksSelectorName.append(controllerAddress);
networksSelectorName.append("/network");
std::string networksSelectorName("com.zerotier.controller.lfdb:"); networksSelectorName.append(controllerAddress); networksSelectorName.append("/network");
// LF record masking key is the first 32 bytes of SHA512(controller private key) in hex,
// hiding record values from anything but the controller or someone who has its key.
uint8_t sha512pk[64];
_myId.sha512PrivateKey(sha512pk);
char maskingKey[128];
Utils::hex(sha512pk, 32, maskingKey);
char maskingKey [128];
Utils::hex(sha512pk,32,maskingKey);
httplib::Client htcli(_lfNodeHost.c_str(), _lfNodePort);
httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort);
int64_t timeRangeStart = 0;
while (_running.load()) {
{
std::lock_guard<std::mutex> sl(_state_l);
for (auto ns = _state.begin(); ns != _state.end(); ++ns) {
for(auto ns=_state.begin();ns!=_state.end();++ns) {
if (ns->second.dirty) {
nlohmann::json network;
if (get(ns->first, network)) {
nlohmann::json newrec, selector0;
if (get(ns->first,network)) {
nlohmann::json newrec,selector0;
selector0["Name"] = networksSelectorName;
selector0["Ordinal"] = ns->first;
newrec["Selectors"].push_back(selector0);
@ -67,34 +66,30 @@ LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, c
newrec["MaskingKey"] = maskingKey;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord", newrec.dump(), "application/json");
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ns->second.dirty = false;
// printf("SET network %.16llx %s\n",ns->first,resp->body.c_str());
}
else {
fprintf(stderr, "ERROR: LFDB: %d from node (create/update network): %s" ZT_EOL_S, resp->status, resp->body.c_str());
//printf("SET network %.16llx %s\n",ns->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update network): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
else {
fprintf(stderr, "ERROR: LFDB: node is offline" ZT_EOL_S);
}
}
catch (std::exception& e) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update network): %s" ZT_EOL_S, e.what());
}
catch (...) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update network): unknown exception" ZT_EOL_S);
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): unknown exception" ZT_EOL_S);
}
}
}
for (auto ms = ns->second.members.begin(); ms != ns->second.members.end(); ++ms) {
if ((_storeOnlineState) && (ms->second.lastOnlineDirty) && (ms->second.lastOnlineAddress)) {
nlohmann::json newrec, selector0, selector1, selectors, ip;
char tmp[1024], tmp2[128];
OSUtils::ztsnprintf(tmp, sizeof(tmp), "com.zerotier.controller.lfdb:%s/network/%.16llx/online", controllerAddress, (unsigned long long)ns->first);
for(auto ms=ns->second.members.begin();ms!=ns->second.members.end();++ms) {
if ((_storeOnlineState)&&(ms->second.lastOnlineDirty)&&(ms->second.lastOnlineAddress)) {
nlohmann::json newrec,selector0,selector1,selectors,ip;
char tmp[1024],tmp2[128];
OSUtils::ztsnprintf(tmp,sizeof(tmp),"com.zerotier.controller.lfdb:%s/network/%.16llx/online",controllerAddress,(unsigned long long)ns->first);
ms->second.lastOnlineAddress.toIpString(tmp2);
selector0["Name"] = tmp;
selector0["Ordinal"] = ms->first;
@ -103,18 +98,18 @@ LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, c
selectors.push_back(selector0);
selectors.push_back(selector1);
newrec["Selectors"] = selectors;
const uint8_t* const rawip = (const uint8_t*)ms->second.lastOnlineAddress.rawIpData();
switch (ms->second.lastOnlineAddress.ss_family) {
const uint8_t *const rawip = (const uint8_t *)ms->second.lastOnlineAddress.rawIpData();
switch(ms->second.lastOnlineAddress.ss_family) {
case AF_INET:
for (int j = 0; j < 4; ++j)
for(int j=0;j<4;++j)
ip.push_back((unsigned int)rawip[j]);
break;
case AF_INET6:
for (int j = 0; j < 16; ++j)
for(int j=0;j<16;++j)
ip.push_back((unsigned int)rawip[j]);
break;
default:
ip = tmp2; // should never happen since only IP transport is currently supported
ip = tmp2; // should never happen since only IP transport is currently supported
break;
}
newrec["Value"] = ip;
@ -123,32 +118,28 @@ LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, c
newrec["Timestamp"] = ms->second.lastOnlineTime;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord", newrec.dump(), "application/json");
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ms->second.lastOnlineDirty = false;
// printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
}
else {
fprintf(stderr, "ERROR: LFDB: %d from node (create/update member online status): %s" ZT_EOL_S, resp->status, resp->body.c_str());
//printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update member online status): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
else {
fprintf(stderr, "ERROR: LFDB: node is offline" ZT_EOL_S);
}
}
catch (std::exception& e) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update member online status): %s" ZT_EOL_S, e.what());
}
catch (...) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update member online status): unknown exception" ZT_EOL_S);
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): unknown exception" ZT_EOL_S);
}
}
if (ms->second.dirty) {
nlohmann::json network, member;
if (get(ns->first, network, ms->first, member)) {
nlohmann::json newrec, selector0, selector1, selectors;
nlohmann::json network,member;
if (get(ns->first,network,ms->first,member)) {
nlohmann::json newrec,selector0,selector1,selectors;
selector0["Name"] = networksSelectorName;
selector0["Ordinal"] = ns->first;
selector1["Name"] = "member";
@ -161,25 +152,21 @@ LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, c
newrec["MaskingKey"] = maskingKey;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord", newrec.dump(), "application/json");
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ms->second.dirty = false;
// printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
}
else {
fprintf(stderr, "ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S, resp->status, resp->body.c_str());
//printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
else {
fprintf(stderr, "ERROR: LFDB: node is offline" ZT_EOL_S);
}
}
catch (std::exception& e) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update member): %s" ZT_EOL_S, e.what());
}
catch (...) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (create/update member): unknown exception" ZT_EOL_S);
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): unknown exception" ZT_EOL_S);
}
}
}
@ -189,161 +176,143 @@ LFDB::LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, c
try {
std::ostringstream query;
query << "{"
"\"Ranges\":[{"
"\"Name\":\""
<< networksSelectorName
<< "\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":["
<< timeRangeStart
<< ",9223372036854775807],"
"\"MaskingKey\":\""
<< maskingKey
<< "\","
"\"Owners\":[\""
<< _lfOwnerPublic
<< "\"]"
"}";
auto resp = htcli.Post("/query", query.str(), "application/json");
query <<
"{"
"\"Ranges\":[{"
"\"Name\":\"" << networksSelectorName << "\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
"\"MaskingKey\":\"" << maskingKey << "\","
"\"Owners\":[\"" << _lfOwnerPublic << "\"]"
"}";
auto resp = htcli.Post("/query",query.str(),"application/json");
if (resp) {
if (resp->status == 200) {
nlohmann::json results(OSUtils::jsonParse(resp->body));
if ((results.is_array()) && (! results.empty())) {
for (std::size_t ri = 0; ri < results.size(); ++ri) {
nlohmann::json& rset = results[ri];
if ((rset.is_array()) && (! rset.empty())) {
nlohmann::json& result = rset[0];
if ((results.is_array())&&(!results.empty())) {
for(std::size_t ri=0;ri<results.size();++ri) {
nlohmann::json &rset = results[ri];
if ((rset.is_array())&&(!rset.empty())) {
nlohmann::json &result = rset[0];
if (result.is_object()) {
nlohmann::json& record = result["Record"];
nlohmann::json &record = result["Record"];
if (record.is_object()) {
const std::string recordValue = result["Value"];
// printf("GET network %s\n",recordValue.c_str());
//printf("GET network %s\n",recordValue.c_str());
nlohmann::json network(OSUtils::jsonParse(recordValue));
if (network.is_object()) {
const std::string idstr = network["id"];
const uint64_t id = Utils::hexStrToU64(idstr.c_str());
if ((id >> 24) == controllerAddressInt) { // sanity check
if ((id >> 24) == controllerAddressInt) { // sanity check
nlohmann::json oldNetwork;
if ((timeRangeStart > 0) && (get(id, oldNetwork))) {
if ((timeRangeStart > 0)&&(get(id,oldNetwork))) {
const uint64_t revision = network["revision"];
const uint64_t prevRevision = oldNetwork["revision"];
if (prevRevision < revision) {
_networkChanged(oldNetwork, network, timeRangeStart > 0);
_networkChanged(oldNetwork,network,timeRangeStart > 0);
}
}
else {
} else {
nlohmann::json nullJson;
_networkChanged(nullJson, network, timeRangeStart > 0);
_networkChanged(nullJson,network,timeRangeStart > 0);
}
}
}
}
}
}
}
}
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (check for network updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
else {
fprintf(stderr, "ERROR: LFDB: %d from node (check for network updates): %s" ZT_EOL_S, resp->status, resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
else {
fprintf(stderr, "ERROR: LFDB: node is offline" ZT_EOL_S);
}
}
catch (std::exception& e) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (check for network updates): %s" ZT_EOL_S, e.what());
}
catch (...) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (check for network updates): unknown exception" ZT_EOL_S);
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): unknown exception" ZT_EOL_S);
}
try {
std::ostringstream query;
query << "{"
"\"Ranges\":[{"
"\"Name\":\""
<< networksSelectorName
<< "\","
"\"Range\":[0,18446744073709551615]"
"},{"
"\"Name\":\"member\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":["
<< timeRangeStart
<< ",9223372036854775807],"
"\"MaskingKey\":\""
<< maskingKey
<< "\","
"\"Owners\":[\""
<< _lfOwnerPublic
<< "\"]"
"}";
auto resp = htcli.Post("/query", query.str(), "application/json");
query <<
"{"
"\"Ranges\":[{"
"\"Name\":\"" << networksSelectorName << "\","
"\"Range\":[0,18446744073709551615]"
"},{"
"\"Name\":\"member\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
"\"MaskingKey\":\"" << maskingKey << "\","
"\"Owners\":[\"" << _lfOwnerPublic << "\"]"
"}";
auto resp = htcli.Post("/query",query.str(),"application/json");
if (resp) {
if (resp->status == 200) {
nlohmann::json results(OSUtils::jsonParse(resp->body));
if ((results.is_array()) && (! results.empty())) {
for (std::size_t ri = 0; ri < results.size(); ++ri) {
nlohmann::json& rset = results[ri];
if ((rset.is_array()) && (! rset.empty())) {
nlohmann::json& result = rset[0];
if ((results.is_array())&&(!results.empty())) {
for(std::size_t ri=0;ri<results.size();++ri) {
nlohmann::json &rset = results[ri];
if ((rset.is_array())&&(!rset.empty())) {
nlohmann::json &result = rset[0];
if (result.is_object()) {
nlohmann::json& record = result["Record"];
nlohmann::json &record = result["Record"];
if (record.is_object()) {
const std::string recordValue = result["Value"];
// printf("GET member %s\n",recordValue.c_str());
//printf("GET member %s\n",recordValue.c_str());
nlohmann::json member(OSUtils::jsonParse(recordValue));
if (member.is_object()) {
const std::string nwidstr = member["nwid"];
const std::string idstr = member["id"];
const uint64_t nwid = Utils::hexStrToU64(nwidstr.c_str());
const uint64_t id = Utils::hexStrToU64(idstr.c_str());
if ((id) && ((nwid >> 24) == controllerAddressInt)) { // sanity check
if ((id)&&((nwid >> 24) == controllerAddressInt)) { // sanity check
nlohmann::json network, oldMember;
if ((timeRangeStart > 0) && (get(nwid, network, id, oldMember))) {
nlohmann::json network,oldMember;
if ((timeRangeStart > 0)&&(get(nwid,network,id,oldMember))) {
const uint64_t revision = member["revision"];
const uint64_t prevRevision = oldMember["revision"];
if (prevRevision < revision)
_memberChanged(oldMember, member, timeRangeStart > 0);
}
else if (hasNetwork(nwid)) {
_memberChanged(oldMember,member,timeRangeStart > 0);
} else if (hasNetwork(nwid)) {
nlohmann::json nullJson;
_memberChanged(nullJson, member, timeRangeStart > 0);
_memberChanged(nullJson,member,timeRangeStart > 0);
}
}
}
}
}
}
}
}
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (check for member updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
else {
fprintf(stderr, "ERROR: LFDB: %d from node (check for member updates): %s" ZT_EOL_S, resp->status, resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
else {
fprintf(stderr, "ERROR: LFDB: node is offline" ZT_EOL_S);
}
}
catch (std::exception& e) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (check for member updates): %s" ZT_EOL_S, e.what());
}
catch (...) {
fprintf(stderr, "ERROR: LFDB: unexpected exception querying node (check for member updates): unknown exception" ZT_EOL_S);
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): unknown exception" ZT_EOL_S);
}
timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
_ready.store(true);
for (int k = 0; k < 4; ++k) { // 2s delay between queries for remotely modified networks or members
if (! _running.load())
for(int k=0;k<4;++k) { // 2s delay between queries for remotely modified networks or members
if (!_running.load())
return;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
@ -359,7 +328,7 @@ LFDB::~LFDB()
bool LFDB::waitForReady()
{
while (! _ready.load()) {
while (!_ready.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return true;
@ -370,18 +339,18 @@ bool LFDB::isReady()
return (_ready.load());
}
bool LFDB::save(nlohmann::json& record, bool notifyListeners)
bool LFDB::save(nlohmann::json &record,bool notifyListeners)
{
bool modified = false;
const std::string objtype = record["objtype"];
if (objtype == "network") {
const uint64_t nwid = OSUtils::jsonIntHex(record["id"], 0ULL);
const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (nwid) {
nlohmann::json old;
get(nwid, old);
if ((! old.is_object()) || (! _compareRecords(old, record))) {
record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
_networkChanged(old, record, notifyListeners);
get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_networkChanged(old,record,notifyListeners);
{
std::lock_guard<std::mutex> l(_state_l);
_state[nwid].dirty = true;
@ -389,16 +358,15 @@ bool LFDB::save(nlohmann::json& record, bool notifyListeners)
modified = true;
}
}
}
else if (objtype == "member") {
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"], 0ULL);
const uint64_t id = OSUtils::jsonIntHex(record["id"], 0ULL);
if ((id) && (nwid)) {
nlohmann::json network, old;
get(nwid, network, id, old);
if ((! old.is_object()) || (! _compareRecords(old, record))) {
record["revision"] = OSUtils::jsonInt(record["revision"], 0ULL) + 1ULL;
_memberChanged(old, record, notifyListeners);
} else if (objtype == "member") {
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
if ((id)&&(nwid)) {
nlohmann::json network,old;
get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_memberChanged(old,record,notifyListeners);
{
std::lock_guard<std::mutex> l(_state_l);
_state[nwid].members[id].dirty = true;
@ -415,12 +383,12 @@ void LFDB::eraseNetwork(const uint64_t networkId)
// TODO
}
void LFDB::eraseMember(const uint64_t networkId, const uint64_t memberId)
void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
// TODO
}
void LFDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch)
void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
std::lock_guard<std::mutex> l(_state_l);
auto nw = _state.find(networkId);
@ -435,9 +403,4 @@ void LFDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const
}
}
void LFDB::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress)
{
this->nodeIsOnline(networkId, memberId, physicalAddress, "unknown/unknown");
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -16,18 +16,19 @@
#include "DB.hpp"
#include <atomic>
#include <mutex>
#include <string>
#include <unordered_map>
#include <atomic>
namespace ZeroTier {
/**
* DB implementation for controller that stores data in LF
*/
class LFDB : public DB {
public:
class LFDB : public DB
{
public:
/**
* @param myId This controller's identity
* @param path Base path for ZeroTier node itself
@ -37,41 +38,44 @@ class LFDB : public DB {
* @param lfNodePort LF node http (not https) port
* @param storeOnlineState If true, store online/offline state and IP info in LF (a lot of data, only for private networks!)
*/
LFDB(const Identity& myId, const char* path, const char* lfOwnerPrivate, const char* lfOwnerPublic, const char* lfNodeHost, int lfNodePort, bool storeOnlineState);
LFDB(const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState);
virtual ~LFDB();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json& record, bool notifyListeners);
virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress& physicalAddress, const char* osArch);
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
protected:
protected:
const Identity _myId;
std::string _lfOwnerPrivate, _lfOwnerPublic;
std::string _lfOwnerPrivate,_lfOwnerPublic;
std::string _lfNodeHost;
int _lfNodePort;
struct _MemberState {
_MemberState() : lastOnlineAddress(), lastOnlineTime(0), dirty(false), lastOnlineDirty(false)
{
}
struct _MemberState
{
_MemberState() :
lastOnlineAddress(),
lastOnlineTime(0),
dirty(false),
lastOnlineDirty(false) {}
InetAddress lastOnlineAddress;
int64_t lastOnlineTime;
bool dirty;
bool lastOnlineDirty;
};
struct _NetworkState {
_NetworkState() : members(), dirty(false)
{
}
std::unordered_map<uint64_t, _MemberState> members;
struct _NetworkState
{
_NetworkState() :
members(),
dirty(false) {}
std::unordered_map<uint64_t,_MemberState> members;
bool dirty;
};
std::unordered_map<uint64_t, _NetworkState> _state;
std::unordered_map<uint64_t,_NetworkState> _state;
std::mutex _state_l;
std::atomic_bool _running;
@ -80,6 +84,6 @@ class LFDB : public DB {
bool _storeOnlineState;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,97 +1,187 @@
/*
* Copyright (c)2025 ZeroTier, Inc.
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#ifdef ZT_CONTROLLER_USE_LIBPQ
#ifndef ZT_CONTROLLER_POSTGRESQL_HPP
#define ZT_CONTROLLER_POSTGRESQL_HPP
#include "ConnectionPool.hpp"
#include "DB.hpp"
#include <memory>
#ifdef ZT_CONTROLLER_USE_LIBPQ
#ifndef ZT_CONTROLLER_LIBPQ_HPP
#define ZT_CONTROLLER_LIBPQ_HPP
#define ZT_CENTRAL_CONTROLLER_COMMIT_THREADS 4
#include "ConnectionPool.hpp"
#include <pqxx/pqxx>
namespace ZeroTier {
#include <memory>
#include <redis++/redis++.h>
#include "../node/Metrics.hpp"
extern "C" {
typedef struct pg_conn PGconn;
}
namespace ZeroTier {
struct RedisConfig;
class PostgresConnection : public Connection {
public:
virtual ~PostgresConnection()
{
public:
virtual ~PostgresConnection() {
}
std::shared_ptr<pqxx::connection> c;
int a;
};
class PostgresConnFactory : public ConnectionFactory {
public:
PostgresConnFactory(std::string& connString) : m_connString(connString)
public:
PostgresConnFactory(std::string &connString)
: m_connString(connString)
{
}
virtual std::shared_ptr<Connection> create()
{
virtual std::shared_ptr<Connection> create() {
Metrics::conn_counter++;
auto c = std::shared_ptr<PostgresConnection>(new PostgresConnection());
c->c = std::make_shared<pqxx::connection>(m_connString);
return std::static_pointer_cast<Connection>(c);
}
private:
private:
std::string m_connString;
};
class PostgreSQL;
class MemberNotificationReceiver : public pqxx::notification_receiver {
public:
MemberNotificationReceiver(DB* p, pqxx::connection& c, const std::string& channel);
virtual ~MemberNotificationReceiver()
{
public:
MemberNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel);
virtual ~MemberNotificationReceiver() {
fprintf(stderr, "MemberNotificationReceiver destroyed\n");
}
virtual void operator()(const std::string& payload, int backendPid);
private:
DB* _psql;
virtual void operator() (const std::string &payload, int backendPid);
private:
PostgreSQL *_psql;
};
class NetworkNotificationReceiver : public pqxx::notification_receiver {
public:
NetworkNotificationReceiver(DB* p, pqxx::connection& c, const std::string& channel);
virtual ~NetworkNotificationReceiver()
{
public:
NetworkNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel);
virtual ~NetworkNotificationReceiver() {
fprintf(stderr, "NetworkNotificationReceiver destroyed\n");
};
virtual void operator()(const std::string& payload, int packend_pid);
private:
DB* _psql;
virtual void operator() (const std::string &payload, int packend_pid);
private:
PostgreSQL *_psql;
};
struct NodeOnlineRecord {
uint64_t lastSeen;
InetAddress physicalAddress;
std::string osArch;
/**
* A controller database driver that talks to PostgreSQL
*
* This is for use with ZeroTier Central. Others are free to build and use it
* but be aware that we might change it at any time.
*/
class PostgreSQL : public DB
{
friend class MemberNotificationReceiver;
friend class NetworkNotificationReceiver;
public:
PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc);
virtual ~PostgreSQL();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress);
virtual AuthInfo getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL);
protected:
struct _PairHasher
{
inline std::size_t operator()(const std::pair<uint64_t,uint64_t> &p) const { return (std::size_t)(p.first ^ p.second); }
};
virtual void _memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners) {
DB::_memberChanged(old, memberConfig, notifyListeners);
}
virtual void _networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners) {
DB::_networkChanged(old, networkConfig, notifyListeners);
}
private:
void initializeNetworks();
void initializeMembers();
void heartbeat();
void membersDbWatcher();
void _membersWatcher_Postgres();
void networksDbWatcher();
void _networksWatcher_Postgres();
void _membersWatcher_Redis();
void _networksWatcher_Redis();
void commitThread();
void onlineNotificationThread();
void onlineNotification_Postgres();
void onlineNotification_Redis();
uint64_t _doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline);
enum OverrideMode {
ALLOW_PGBOUNCER_OVERRIDE = 0,
NO_OVERRIDE = 1
};
std::shared_ptr<ConnectionPool<PostgresConnection> > _pool;
const Identity _myId;
const Address _myAddress;
std::string _myAddressStr;
std::string _connString;
BlockingQueue< std::pair<nlohmann::json,bool> > _commitQueue;
std::thread _heartbeatThread;
std::thread _membersDbWatcher;
std::thread _networksDbWatcher;
std::thread _commitThread[ZT_CENTRAL_CONTROLLER_COMMIT_THREADS];
std::thread _onlineNotificationThread;
std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > _lastOnline;
mutable std::mutex _lastOnline_l;
mutable std::mutex _readyLock;
std::atomic<int> _ready, _connected, _run;
mutable volatile bool _waitNoticePrinted;
int _listenPort;
uint8_t _ssoPsk[48];
RedisConfig *_rc;
std::shared_ptr<sw::redis::Redis> _redis;
std::shared_ptr<sw::redis::RedisCluster> _cluster;
bool _redisMemberStatus;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif // ZT_CONTROLLER_POSTGRESQL_HPP
#endif // ZT_CONTROLLER_LIBPQ_HPP
#endif // ZT_CONTROLLER_USE_LIBPQ
#endif // ZT_CONTROLLER_USE_LIBPQ

View file

@ -5,11 +5,11 @@
namespace ZeroTier {
struct RedisConfig {
std::string hostname;
int port;
std::string password;
bool clusterMode;
std::string hostname;
int port;
std::string password;
bool clusterMode;
};
} // namespace ZeroTier
}
#endif

18
debian/changelog vendored
View file

@ -1,21 +1,3 @@
zerotier-one (1.14.2) unstable; urgency=medium
* See RELEASE-NOTES.md for release notes.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Wed, 23 Oct 2024 01:00:00 -0700
zerotier-one (1.14.1) unstable; urgency=medium
* See RELEASE-NOTES.md for release notes.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Wed, 11 Sep 2024 01:00:00 -0700
zerotier-one (1.14.0) unstable; urgency=medium
* See RELEASE-NOTES.md for release notes.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Tue, 19 Mar 2024 01:00:00 -0700
zerotier-one (1.12.2) unstable; urgency=medium
* See RELEASE-NOTES.md for release notes.

2
debian/copyright vendored
View file

@ -12,7 +12,7 @@ License: ZeroTier BSL 1.1
Use of this software is governed by the Business Source License included
in the LICENSE.TXT file in the project's root directory.
Change Date: 2026-01-01
Change Date: 2025-01-01
On the date above, in accordance with the Business Source License, use
of this software will be governed by version 2.0 of the Apache License.

View file

@ -3,4 +3,4 @@ Manual Pages and Other Documentation
Use "./build.sh" to build the manual pages.
You'll need either Node.js/npm installed (script will then automatically install the npm *marked-man* package) or */usr/bin/ronn*. The latter is a Ruby program packaged on some distributions as *rubygem-ronn* or *ruby-ronn* or installable as *gem install ronn*. The Node *marked-man* package and *ronn* from RubyGems are two roughly equivalent alternatives for compiling Markdown into roff/man format.
You'll need either NodeJS/npm installed (script will then automatically install the npm *marked-man* package) or */usr/bin/ronn*. The latter is a Ruby program packaged on some distributions as *rubygem-ronn* or *ruby-ronn* or installable as *gem install ronn*. The Node *marked-man* package and *ronn* from rubygems are two roughly equivalent alternatives for compiling MarkDown into roff/man format.

View file

@ -9,16 +9,15 @@ mkztfile() {
file=$1
mode=$2
content=$3
echo "creating $file"
mkdir -p /var/lib/zerotier-one
echo -n "$content" > "/var/lib/zerotier-one/$file"
echo "$content" > "/var/lib/zerotier-one/$file"
chmod "$mode" "/var/lib/zerotier-one/$file"
}
if [ "x$ZEROTIER_API_SECRET" != "x" ]
then
mkztfile authtoken.secret 0600 "$ZEROTIER_API_SECRET"
mkztfile metricstoken.secret 0600 "$ZEROTIER_API_SECRET"
fi
if [ "x$ZEROTIER_IDENTITY_PUBLIC" != "x" ]
@ -31,11 +30,6 @@ then
mkztfile identity.secret 0600 "$ZEROTIER_IDENTITY_SECRET"
fi
if [ "x$ZEROTIER_LOCAL_CONF" != "x" ]
then
mkztfile local.conf 0644 "$ZEROTIER_LOCAL_CONF"
fi
mkztfile zerotier-one.port 0600 "9993"
killzerotier() {

View file

@ -1,16 +1,11 @@
# Dockerfile for ZeroTier Central Controllers
FROM registry.zerotier.com/zerotier/ctlbuild:2025-05-13-01 AS builder
FROM registry.zerotier.com/zerotier/ctlbuild:latest as builder
MAINTAINER Adam Ierymekno <adam.ierymenko@zerotier.com>, Grant Limberg <grant.limberg@zerotier.com>
ADD . /ZeroTierOne
RUN export PATH=$PATH:~/.cargo/bin && cd ZeroTierOne && make clean && make central-controller -j8
FROM golang:bookworm AS go_base
RUN go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
FROM registry.zerotier.com/zerotier/ctlrun:2025-05-13-01
FROM registry.zerotier.com/zerotier/ctlrun:latest
COPY --from=builder /ZeroTierOne/zerotier-one /usr/local/bin/zerotier-one
COPY --from=go_base /go/bin/migrate /usr/local/bin/migrate
COPY ext/central-controller-docker/migrations /migrations
RUN chmod a+x /usr/local/bin/zerotier-one
RUN echo "/usr/local/lib64" > /etc/ld.so.conf.d/usr-local-lib64.conf && ldconfig

View file

@ -1,5 +1,8 @@
# Dockerfile for building ZeroTier Central Controllers
FROM debian:bookworm
FROM ubuntu:jammy as builder
MAINTAINER Adam Ierymekno <adam.ierymenko@zerotier.com>, Grant Limberg <grant.limberg@zerotier.com>
ARG git_branch=master
RUN apt update && apt upgrade -y
RUN apt -y install \
@ -17,7 +20,6 @@ RUN apt -y install \
postgresql-client-common \
curl \
google-perftools \
libgoogle-perftools-dev \
protobuf-compiler
libgoogle-perftools-dev
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

View file

@ -1,17 +1,14 @@
FROM debian:bookworm
FROM ubuntu:jammy
RUN apt update && apt upgrade -y
RUN apt -y install \
netcat-traditional \
postgresql-client \
postgresql-client-common \
libjemalloc2 \
libpq5 \
curl \
binutils \
linux-tools-gke \
perf-tools-unstable \
google-perftools \
gnupg
google-perftools

View file

@ -1,5 +1,9 @@
#!/bin/bash
if [ -z "$ZT_IDENTITY_PATH" ]; then
echo '*** FAILED: ZT_IDENTITY_PATH environment variable is not defined'
exit 1
fi
if [ -z "$ZT_DB_HOST" ]; then
echo '*** FAILED: ZT_DB_HOST environment variable not defined'
exit 1
@ -20,9 +24,6 @@ if [ -z "$ZT_DB_PASSWORD" ]; then
echo '*** FAILED: ZT_DB_PASSWORD environment variable not defined'
exit 1
fi
if [ -z "$ZT_DB_TYPE" ]; then
ZT_DB_TYPE="postgres"
fi
REDIS=""
if [ "$ZT_USE_REDIS" == "true" ]; then
@ -55,14 +56,10 @@ fi
mkdir -p /var/lib/zerotier-one
pushd /var/lib/zerotier-one
if [ -d "$ZT_IDENTITY_PATH" ]; then
echo '*** Using existing ZT identity from path $ZT_IDENTITY_PATH'
ln -s $ZT_IDENTITY_PATH/identity.public identity.public
ln -s $ZT_IDENTITY_PATH/identity.secret identity.secret
if [ -f "$ZT_IDENTITY_PATH/authtoken.secret" ]; then
ln -s $ZT_IDENTITY_PATH/authtoken.secret authtoken.secret
fi
ln -s $ZT_IDENTITY_PATH/identity.public identity.public
ln -s $ZT_IDENTITY_PATH/identity.secret identity.secret
if [ -f "$ZT_IDENTITY_PATH/authtoken.secret" ]; then
ln -s $ZT_IDENTITY_PATH/authtoken.secret authtoken.secret
fi
popd
@ -73,7 +70,7 @@ APP_NAME="controller-$(cat /var/lib/zerotier-one/identity.public | cut -d ':' -f
echo "{
\"settings\": {
\"controllerDbPath\": \"${ZT_DB_TYPE}:host=${ZT_DB_HOST} port=${ZT_DB_PORT} dbname=${ZT_DB_NAME} user=${ZT_DB_USER} password=${ZT_DB_PASSWORD} application_name=${APP_NAME} sslmode=prefer sslcert=${DB_CLIENT_CERT} sslkey=${DB_CLIENT_KEY} sslrootcert=${DB_SERVER_CA}\",
\"controllerDbPath\": \"postgres:host=${ZT_DB_HOST} port=${ZT_DB_PORT} dbname=${ZT_DB_NAME} user=${ZT_DB_USER} password=${ZT_DB_PASSWORD} application_name=${APP_NAME} sslmode=prefer sslcert=${DB_CLIENT_CERT} sslkey=${DB_CLIENT_KEY} sslrootcert=${DB_SERVER_CA}\",
\"portMappingEnabled\": true,
\"softwareUpdate\": \"disable\",
\"interfacePrefixBlacklist\": [
@ -103,24 +100,6 @@ else
done
fi
if [ "$ZT_DB_TYPE" == "cv2" ]; then
echo "Migrating database (if needed)..."
if [ -n "$DB_SERVER_CA" ]; then
/usr/local/bin/migrate -source file:///migrations -database "postgres://$ZT_DB_USER:$ZT_DB_PASSWORD@$ZT_DB_HOST:$ZT_DB_PORT/$ZT_DB_NAME?x-migrations-table=controller_migrations&sslmode=verify-full&sslrootcert=$DB_SERVER_CA&sslcert=$DB_CLIENT_CERT&sslkey=$DB_CLIENT_KEY" up
else
/usr/local/bin/migrate -source file:///migrations -database "postgres://$ZT_DB_USER:$ZT_DB_PASSWORD@$ZT_DB_HOST:$ZT_DB_PORT/$ZT_DB_NAME?x-migrations-table=controller_migrations&sslmode=disable" up
fi
fi
if [ -n "$ZT_TEMPORAL_HOST" ] && [ -n "$ZT_TEMPORAL_PORT" ]; then
echo "waiting for temporal..."
while ! nc -z ${ZT_TEMPORAL_HOST} ${ZT_TEMPORAL_PORT}; do
echo "waiting...";
sleep 1;
done
echo "Temporal is up"
fi
export GLIBCXX_FORCE_NEW=1
export GLIBCPP_FORCE_NEW=1
export LD_PRELOAD="/usr/lib/x86_64-linux-gnu/libjemalloc.so.2"

View file

@ -1,3 +0,0 @@
DROP TABLE IF EXISTS network_memberships_ctl;
DROP TABLE IF EXISTS networks_ctl;
DROP TABLE IF EXISTS controllers_ctl;

View file

@ -1,47 +0,0 @@
-- inits controller db schema
CREATE TABLE IF NOT EXISTS controllers_ctl (
id text NOT NULL PRIMARY KEY,
hostname text,
last_heartbeat timestamp with time zone,
public_identity text NOT NULL,
version text
);
CREATE TABLE IF NOT EXISTS networks_ctl (
id character varying(22) NOT NULL PRIMARY KEY,
name text NOT NULL,
configuration jsonb DEFAULT '{}'::jsonb NOT NULL,
controller_id text REFERENCES controllers_ctl(id),
revision integer DEFAULT 0 NOT NULL,
last_modified timestamp with time zone DEFAULT now(),
creation_time timestamp with time zone DEFAULT now()
);
CREATE TABLE IF NOT EXISTS network_memberships_ctl (
device_id character varying(22) NOT NULL,
network_id character varying(22) NOT NULL REFERENCES networks_ctl(id),
authorized boolean,
active_bridge boolean,
ip_assignments text[],
no_auto_assign_ips boolean,
sso_exempt boolean,
authentication_expiry_time timestamp with time zone,
capabilities jsonb,
creation_time timestamp with time zone DEFAULT now(),
last_modified timestamp with time zone DEFAULT now(),
identity text DEFAULT ''::text,
last_authorized_credential text,
last_authorized_time timestamp with time zone,
last_deauthorized_time timestamp with time zone,
last_seen jsonb DEFAULT '{}'::jsonb NOT NULL, -- in the context of the network
remote_trace_level integer DEFAULT 0 NOT NULL,
remote_trace_target text DEFAULT ''::text NOT NULL,
revision integer DEFAULT 0 NOT NULL,
tags jsonb,
version_major integer DEFAULT 0 NOT NULL,
version_minor integer DEFAULT 0 NOT NULL,
version_revision integer DEFAULT 0 NOT NULL,
version_protocol integer DEFAULT 0 NOT NULL,
PRIMARY KEY (device_id, network_id)
);

View file

@ -1,3 +0,0 @@
ALTER TABLE network_memberships_ctl
DROP COLUMN os,
DROP COLUMN arch;

View file

@ -1,3 +0,0 @@
ALTER TABLE network_memberships_ctl
ADD COLUMN os TEXT NOT NULL DEFAULT 'unknown',
ADD COLUMN arch TEXT NOT NULL DEFAULT 'unknown';

File diff suppressed because it is too large Load diff

View file

@ -701,7 +701,7 @@
<key>USE_HFS+_COMPRESSION</key>
<false/>
<key>VERSION</key>
<string>1.14.2</string>
<string>1.12.2</string>
</dict>
<key>TYPE</key>
<integer>0</integer>

View file

@ -24,10 +24,10 @@
<ROW Property="AiFeatIcoZeroTierOne" Value="ZeroTierIcon.exe" Type="8"/>
<ROW Property="MSIFASTINSTALL" MultiBuildValue="DefaultBuild:2"/>
<ROW Property="Manufacturer" Value="ZeroTier, Inc."/>
<ROW Property="ProductCode" Value="1033:{0143A36C-46C6-458D-AB9B-C8843E089323} " Type="16"/>
<ROW Property="ProductCode" Value="1033:{56528063-D8C2-43F4-97DB-C787E6A2D9DB} " Type="16"/>
<ROW Property="ProductLanguage" Value="1033"/>
<ROW Property="ProductName" Value="ZeroTier One"/>
<ROW Property="ProductVersion" Value="1.14.2" Options="32"/>
<ROW Property="ProductVersion" Value="1.12.2" Options="32"/>
<ROW Property="REBOOT" MultiBuildValue="DefaultBuild:ReallySuppress"/>
<ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND;AI_SETUPEXEPATH;SETUPEXEDIR"/>
<ROW Property="UpgradeCode" Value="{B0E2A5F3-88B6-4E77-B922-CB4739B4C4C8}"/>
@ -62,7 +62,7 @@
<ROW Directory="regid.201001.com.zerotier_Dir" Directory_Parent="CommonAppDataFolder" DefaultDir="REGID2~1.ZER|regid.2010-01.com.zerotier" DirectoryOptions="12"/>
</COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.MsiCompsComponent">
<ROW Component="AI_CustomARPName" ComponentId="{DFE7A60C-C2B9-41F6-9171-8955BA30E556}" Directory_="APPDIR" Attributes="4" KeyPath="DisplayName" Options="1"/>
<ROW Component="AI_CustomARPName" ComponentId="{A0629900-689C-4BD7-9315-85F05804DF03}" Directory_="APPDIR" Attributes="4" KeyPath="DisplayName" Options="1"/>
<ROW Component="AI_DisableModify" ComponentId="{46FFA8C5-A0CB-4E05-9AD3-911D543DE8CA}" Directory_="APPDIR" Attributes="4" KeyPath="NoModify" Options="1"/>
<ROW Component="AI_ExePath" ComponentId="{8E02B36C-7A19-429B-A93E-77A9261AC918}" Directory_="APPDIR" Attributes="4" KeyPath="AI_ExePath"/>
<ROW Component="APPDIR" ComponentId="{4DD7907D-D7FE-4CD6-B1A0-B5C1625F5133}" Directory_="APPDIR" Attributes="0"/>
@ -124,7 +124,7 @@
<ROW Path="&lt;AI_DICTS&gt;ui_en.ail"/>
</COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.DigCertStoreComponent">
<ROW TimeStampUrl="http://timestamp.digicert.com" SignerDescription="ZeroTier One" DescriptionUrl="https://www.zerotier.com/" SignOptions="7" SignTool="5" UseSha256="1" KVTenantId="5300bf3b-0eff-4a5f-a63f-821e22ed1730" KVAppId="5f94d77e-b795-41fd-afe7-ec913b03c1d3" KVName="ZeroTier-CS" KVCertName="ZT-EV-CS-2024" KVCertVersion="64807be24d57468e895e2e577f430de2"/>
<ROW TimeStampUrl="http://timestamp.digicert.com" SignerDescription="ZeroTier One" DescriptionUrl="https://www.zerotier.com/" SignOptions="7" SignTool="5" UseSha256="1" KVTenantId="5300bf3b-0eff-4a5f-a63f-821e22ed1730" KVAppId="5f94d77e-b795-41fd-afe7-ec913b03c1d3" KVName="ZeroTier-CS" KVCertName="ZT-EV-CS" KVCertVersion="442c2d6f77874ff99eed4b36f5cb401c"/>
</COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.FirewallExceptionComponent">
<ROW FirewallException="ZeroTierOneUDP9993" Direction="1" Action="1" DisplayName="ZeroTier UDP/9993 In" GroupName="ZeroTierOne" Enabled="1" Scope="*" Condition="1" Profiles="7" Port="9993" Protocol="UDP"/>
@ -501,7 +501,7 @@
<ROW XmlElement="swidbuild" ParentElement="swidnumeric" Name="swid:build" Condition="1" Order="2" Flags="14" Text="2" UpdateIndexInParent="0"/>
<ROW XmlElement="swidentitlement_required_indicator" ParentElement="swidsoftware_identification_tag" Name="swid:entitlement_required_indicator" Condition="1" Order="0" Flags="14" Text="false" UpdateIndexInParent="0"/>
<ROW XmlElement="swidmajor" ParentElement="swidnumeric" Name="swid:major" Condition="1" Order="0" Flags="14" Text="1" UpdateIndexInParent="0"/>
<ROW XmlElement="swidminor" ParentElement="swidnumeric" Name="swid:minor" Condition="1" Order="1" Flags="14" Text="14" UpdateIndexInParent="0"/>
<ROW XmlElement="swidminor" ParentElement="swidnumeric" Name="swid:minor" Condition="1" Order="1" Flags="14" Text="12" UpdateIndexInParent="0"/>
<ROW XmlElement="swidname" ParentElement="swidproduct_version" Name="swid:name" Condition="1" Order="0" Flags="14" Text="[ProductVersion]" UpdateIndexInParent="0"/>
<ROW XmlElement="swidname_1" ParentElement="swidsoftware_creator" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc." UpdateIndexInParent="0"/>
<ROW XmlElement="swidname_2" ParentElement="swidsoftware_licensor" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc." UpdateIndexInParent="0"/>

View file

@ -8,7 +8,6 @@
namespace prometheus {
// структура, в которую копируются значения метрик перед их сериализацией
struct ClientMetric {
// Label

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -84,7 +84,7 @@ extern "C" {
/**
* Minimum UDP payload size allowed
*/
#define ZT_MIN_PHYSMTU 510
#define ZT_MIN_PHYSMTU 1400
/**
* Maximum physical interface name length. This number is gigantic because of Windows.
@ -1347,16 +1347,8 @@ typedef struct
*/
char ifname[ZT_MAX_PHYSIFNAME];
/**
* Pointer to PhySocket object for this path
*/
uint64_t localSocket;
/**
* Local port corresponding to this path's localSocket
*/
uint16_t localPort;
/**
* Is path expired?
*/

View file

@ -111,44 +111,6 @@ namespace {
bool finishInitializing();
};
//
// RAII construct for calling AttachCurrentThread and DetachCurrent automatically
//
struct ScopedJNIThreadAttacher {
JavaVM *jvm;
JNIEnv **env_p;
jint getEnvRet;
ScopedJNIThreadAttacher(JavaVM *jvmIn, JNIEnv **env_pIn, jint getEnvRetIn) :
jvm(jvmIn),
env_p(env_pIn),
getEnvRet(getEnvRetIn) {
if (getEnvRet != JNI_EDETACHED) {
return;
}
jint attachCurrentThreadRet;
if ((attachCurrentThreadRet = jvm->AttachCurrentThread(env_p, NULL)) != JNI_OK) {
LOGE("Error calling AttachCurrentThread: %d", attachCurrentThreadRet);
assert(false && "Error calling AttachCurrentThread");
}
}
~ScopedJNIThreadAttacher() {
if (getEnvRet != JNI_EDETACHED) {
return;
}
jint detachCurrentThreadRet;
if ((detachCurrentThreadRet = jvm->DetachCurrentThread()) != JNI_OK) {
LOGE("Error calling DetachCurrentThread: %d", detachCurrentThreadRet);
assert(false && "Error calling DetachCurrentThread");
}
}
};
/*
* This must return 0 on success. It can return any OS-dependent error code
@ -232,25 +194,7 @@ namespace {
assert(ref);
assert(ref->node == node);
JNIEnv *env;
jint getEnvRet;
assert(ref->jvm);
getEnvRet = ref->jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
if (!(getEnvRet == JNI_OK || getEnvRet == JNI_EDETACHED)) {
LOGE("Error calling GetEnv: %d", getEnvRet);
assert(false && "Error calling GetEnv");
}
//
// Thread might actually be detached.
//
// e.g:
// https://github.com/zerotier/ZeroTierOne/blob/91e7ce87f09ac1cfdeaf6ff22c3cedcd93574c86/node/Switch.cpp#L519
//
// Make sure to attach if needed
//
ScopedJNIThreadAttacher attacher{ref->jvm, &env, getEnvRet};
GETENV(env, ref->jvm);
if (env->ExceptionCheck()) {
LOGE("Unhandled pending exception");

View file

@ -9,11 +9,10 @@ ifeq ($(origin CXX),default)
CXX:=$(shell if [ -e /opt/rh/devtoolset-8/root/usr/bin/g++ ]; then echo /opt/rh/devtoolset-8/root/usr/bin/g++; else echo $(CXX); fi)
endif
INCLUDES?=-Irustybits/target -isystem ext -Iext/prometheus-cpp-lite-1.0/core/include -Iext-prometheus-cpp-lite-1.0/3rdparty/http-client-lite/include -Iext/prometheus-cpp-lite-1.0/simpleapi/include
INCLUDES?=-Izeroidc/target -isystem ext -Iext/prometheus-cpp-lite-1.0/core/include -Iext-prometheus-cpp-lite-1.0/3rdparty/http-client-lite/include -Iext/prometheus-cpp-lite-1.0/simpleapi/include
DEFS?=
LDLIBS?=
DESTDIR?=
EXTRA_DEPS?=
include objects.mk
ONE_OBJS+=osdep/LinuxEthernetTap.o
@ -62,7 +61,7 @@ ifeq ($(ZT_DEBUG),1)
override CFLAGS+=-Wall -Wno-deprecated -g -O -pthread $(INCLUDES) $(DEFS)
override CXXFLAGS+=-Wall -Wno-deprecated -g -O -std=c++17 -pthread $(INCLUDES) $(DEFS)
ZT_TRACE=1
ZT_CARGO_FLAGS=
RUSTFLAGS=
# The following line enables optimization for the crypto code, since
# C25519 in particular is almost UNUSABLE in -O0 even on a 3ghz box!
node/Salsa20.o node/SHA512.o node/C25519.o node/Poly1305.o: CXXFLAGS=-Wall -O2 -g -pthread $(INCLUDES) $(DEFS)
@ -71,8 +70,8 @@ else
override CFLAGS+=-Wall -Wno-deprecated -pthread $(INCLUDES) -DNDEBUG $(DEFS)
CXXFLAGS?=-O3 -fstack-protector
override CXXFLAGS+=-Wall -Wno-deprecated -std=c++17 -pthread $(INCLUDES) -DNDEBUG $(DEFS)
LDFLAGS?=-pie -Wl,-z,relro,-z,now
ZT_CARGO_FLAGS=--release
LDFLAGS=-pie -Wl,-z,relro,-z,now
RUSTFLAGS=--release
endif
ifeq ($(ZT_QNAP), 1)
@ -296,9 +295,9 @@ ifeq ($(ZT_SSO_SUPPORTED), 1)
ifeq ($(ZT_EMBEDDED),)
override DEFS+=-DZT_SSO_SUPPORTED=1
ifeq ($(ZT_DEBUG),1)
LDLIBS+=rustybits/target/debug/libzeroidc.a -ldl -lssl -lcrypto
LDLIBS+=zeroidc/target/debug/libzeroidc.a -ldl -lssl -lcrypto
else
LDLIBS+=rustybits/target/release/libzeroidc.a -ldl -lssl -lcrypto
LDLIBS+=zeroidc/target/release/libzeroidc.a -ldl -lssl -lcrypto
endif
endif
endif
@ -325,11 +324,6 @@ ifeq ($(ZT_CONTROLLER),1)
override LDLIBS+=-Lext/libpqxx-7.7.3/install/ubuntu22.04/$(EXT_ARCH)/lib -lpqxx -lpq ext/hiredis-1.0.2/lib/ubuntu22.04/$(EXT_ARCH)/libhiredis.a ext/redis-plus-plus-1.3.3/install/ubuntu22.04/$(EXT_ARCH)/lib/libredis++.a -lssl -lcrypto
override DEFS+=-DZT_CONTROLLER_USE_LIBPQ -DZT_NO_PEER_METRICS
override INCLUDES+=-I/usr/include/postgresql -Iext/libpqxx-7.7.3/install/ubuntu22.04/$(EXT_ARCH)/include -Iext/hiredis-1.0.2/include/ -Iext/redis-plus-plus-1.3.3/install/ubuntu22.04/$(EXT_ARCH)/include/sw/
ifeq ($(ZT_DEBUG),1)
override LDLIBS+=rustybits/target/debug/libsmeeclient.a
else
override LDLIBS+=rustybits/target/release/libsmeeclient.a
endif
endif
# ARM32 hell -- use conservative CFLAGS
@ -364,7 +358,7 @@ override CFLAGS+=-fPIC -fPIE
override CXXFLAGS+=-fPIC -fPIE
# Non-executable stack
override LDFLAGS+=-Wl,-z,noexecstack
override ASFLAGS+=--noexecstack
.PHONY: all
all: one
@ -376,7 +370,7 @@ from_builder: FORCE
ln -sf zerotier-one zerotier-idtool
ln -sf zerotier-one zerotier-cli
zerotier-one: $(CORE_OBJS) $(ONE_OBJS) one.o
zerotier-one: $(CORE_OBJS) $(ONE_OBJS) one.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o zerotier-one $(CORE_OBJS) $(ONE_OBJS) one.o $(LDLIBS)
zerotier-idtool: zerotier-one
@ -385,7 +379,7 @@ zerotier-idtool: zerotier-one
zerotier-cli: zerotier-one
ln -sf zerotier-one zerotier-cli
$(ONE_OBJS): zeroidc smeeclient
$(ONE_OBJS): zeroidc
libzerotiercore.a: FORCE
make CFLAGS="-O3 -fstack-protector -fPIC" CXXFLAGS="-O3 -std=c++17 -fstack-protector -fPIC" $(CORE_OBJS)
@ -405,7 +399,7 @@ manpages: FORCE
doc: manpages
clean: FORCE
rm -rf *.a *.so *.o node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/miniupnpc/*.o ext/libnatpmp/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest build-* ZeroTierOneInstaller-* *.deb *.rpm .depend debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one doc/node_modules ext/misc/*.o debian/.debhelper debian/debhelper-build-stamp docker/zerotier-one rustybits/target
rm -rf *.a *.so *.o node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/miniupnpc/*.o ext/libnatpmp/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest build-* ZeroTierOneInstaller-* *.deb *.rpm .depend debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one doc/node_modules ext/misc/*.o debian/.debhelper debian/debhelper-build-stamp docker/zerotier-one zeroidc/target
distclean: clean
@ -431,10 +425,6 @@ central-controller-docker: _buildx FORCE
docker buildx build --platform linux/amd64,linux/arm64 --no-cache -t registry.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP} -f ext/central-controller-docker/Dockerfile --build-arg git_branch=`git name-rev --name-only HEAD` . --push
@echo Image: registry.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP}
centralv2-controller-docker: _buildx FORCE
docker buildx build --platform linux/amd64,linux/arm64 --no-cache -t us-central1-docker.pkg.dev/zerotier-421eb9/docker-images/ztcentral-controller:$(shell git rev-parse --short HEAD) -f ext/central-controller-docker/Dockerfile --build-arg git_branch=`git name-rev --name-only HEAD` . --push
@echo Image: us-central1-docker.pkg.dev/zerotier-421eb9/docker-images/ztcentral-controller:$(shell git rev-parse --short HEAD)
debug: FORCE
make ZT_DEBUG=1 one
make ZT_DEBUG=1 selftest
@ -442,19 +432,13 @@ debug: FORCE
ifeq ($(ZT_SSO_SUPPORTED), 1)
ifeq ($(ZT_EMBEDDED),)
zeroidc: FORCE
export PATH=/${HOME}/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p zeroidc
# export PATH=/root/.cargo/bin:$$PATH; cd zeroidc && cargo build -j1 $(RUSTFLAGS)
export PATH=/${HOME}/.cargo/bin:$$PATH; cd zeroidc && cargo build $(RUSTFLAGS)
endif
else
zeroidc:
endif
ifeq ($(ZT_CONTROLLER), 1)
smeeclient: FORCE
export PATH=/${HOME}/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p smeeclient
else
smeeclient:
endif
# Note: keep the symlinks in /var/lib/zerotier-one to the binaries since these
# provide backward compatibility with old releases where the binaries actually
# lived here. Folks got scripts.

View file

@ -1,8 +1,8 @@
CC=clang
CXX=clang++
TOPDIR=$(shell pwd)
TOPDIR=$(shell PWD)
INCLUDES=-I$(shell pwd)/rustybits/target -isystem $(TOPDIR)/ext -I$(TOPDIR)/ext/prometheus-cpp-lite-1.0/core/include -I$(TOPDIR)/ext-prometheus-cpp-lite-1.0/3rdparty/http-client-lite/include -I$(TOPDIR)/ext/prometheus-cpp-lite-1.0/simpleapi/include
INCLUDES=-I$(shell PWD)/zeroidc/target -isystem $(TOPDIR)/ext -I$(TOPDIR)/ext/prometheus-cpp-lite-1.0/core/include -I$(TOPDIR)/ext-prometheus-cpp-lite-1.0/3rdparty/http-client-lite/include -I$(TOPDIR)/ext/prometheus-cpp-lite-1.0/simpleapi/include
DEFS=
LIBS=
ARCH_FLAGS=-arch x86_64 -arch arm64
@ -12,8 +12,7 @@ PRODUCTSIGN=echo
CODESIGN_APP_CERT=
CODESIGN_INSTALLER_CERT=
NOTARIZE=echo
NOTARIZE_APPLE_ID=null
NOTARIZE_TEAM_ID=null
NOTARIZE_USER_ID=null
ZT_BUILD_PLATFORM=3
ZT_BUILD_ARCHITECTURE=2
@ -39,9 +38,8 @@ ifeq ($(ZT_OFFICIAL_RELEASE),1)
PRODUCTSIGN=productsign
CODESIGN_APP_CERT="Developer ID Application: ZeroTier, Inc (8ZD9JUCZ4V)"
CODESIGN_INSTALLER_CERT="Developer ID Installer: ZeroTier, Inc (8ZD9JUCZ4V)"
NOTARIZE=xcrun notarytool
NOTARIZE_APPLE_ID="adam.ierymenko@gmail.com"
NOTARIZE_TEAM_ID="8ZD9JUCZ4V"
NOTARIZE=xcrun altool
NOTARIZE_USER_ID="adam.ierymenko@gmail.com"
else
DEFS+=-DZT_SOFTWARE_UPDATE_DEFAULT="\"download\""
endif
@ -57,9 +55,9 @@ ONE_OBJS+=ext/libnatpmp/natpmp.o ext/libnatpmp/getgateway.o ext/miniupnpc/connec
ifeq ($(ZT_CONTROLLER),1)
MACOS_VERSION_MIN=10.15
override CXXFLAGS=$(CFLAGS) -std=c++17 -stdlib=libc++
LIBS+=-L/opt/homebrew/lib -L/usr/local/opt/libpqxx/lib -L/usr/local/opt/libpq/lib -L/usr/local/opt/openssl/lib/ -lpqxx -lpq -lssl -lcrypto -lgssapi_krb5 ext/redis-plus-plus-1.1.1/install/macos/lib/libredis++.a ext/hiredis-0.14.1/lib/macos/libhiredis.a rustybits/target/libsmeeclient.a
LIBS+=-L/usr/local/opt/libpqxx/lib -L/usr/local/opt/libpq/lib -L/usr/local/opt/openssl/lib/ -lpqxx -lpq -lssl -lcrypto -lgssapi_krb5 ext/redis-plus-plus-1.1.1/install/macos/lib/libredis++.a ext/hiredis-0.14.1/lib/macos/libhiredis.a
DEFS+=-DZT_CONTROLLER_USE_LIBPQ -DZT_CONTROLLER_USE_REDIS -DZT_CONTROLLER
INCLUDES+=-I/opt/homebrew/include -I/opt/homebrew/opt/libpq/include -I/usr/local/opt/libpq/include -I/usr/local/opt/libpqxx/include -Iext/hiredis-0.14.1/include/ -Iext/redis-plus-plus-1.1.1/install/macos/include/sw/ -Irustybits/target/
INCLUDES+=-I/usr/local/opt/libpq/include -I/usr/local/opt/libpqxx/include -Iext/hiredis-0.14.1/include/ -Iext/redis-plus-plus-1.1.1/install/macos/include/sw/
else
MACOS_VERSION_MIN=10.13
endif
@ -115,12 +113,8 @@ mac-agent: FORCE
osdep/MacDNSHelper.o: osdep/MacDNSHelper.mm
$(CXX) $(CXXFLAGS) -c osdep/MacDNSHelper.mm -o osdep/MacDNSHelper.o
ifeq ($(ZT_CONTROLLER),1)
one: zeroidc smeeclient $(CORE_OBJS) $(ONE_OBJS) one.o mac-agent
else
one: zeroidc $(CORE_OBJS) $(ONE_OBJS) one.o mac-agent
endif
$(CXX) $(CXXFLAGS) -o zerotier-one $(CORE_OBJS) $(ONE_OBJS) one.o $(LIBS) rustybits/target/libzeroidc.a
$(CXX) $(CXXFLAGS) -o zerotier-one $(CORE_OBJS) $(ONE_OBJS) one.o $(LIBS) zeroidc/target/libzeroidc.a
# $(STRIP) zerotier-one
ln -sf zerotier-one zerotier-idtool
ln -sf zerotier-one zerotier-cli
@ -128,21 +122,12 @@ endif
zerotier-one: one
zeroidc: rustybits/target/libzeroidc.a
zeroidc: zeroidc/target/libzeroidc.a
ifeq ($(ZT_CONTROLLER),1)
smeeclient: rustybits/target/libsmeeclient.a
rustybits/target/libsmeeclient.a: FORCE
cd rustybits && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build -p smeeclient --target=x86_64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd rustybits && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build -p smeeclient --target=aarch64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd rustybits && lipo -create target/x86_64-apple-darwin/$(RUST_VARIANT)/libsmeeclient.a target/aarch64-apple-darwin/$(RUST_VARIANT)/libsmeeclient.a -output target/libsmeeclient.a
endif
rustybits/target/libzeroidc.a: FORCE
cd rustybits && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build -p zeroidc --target=x86_64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd rustybits && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build -p zeroidc --target=aarch64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd rustybits && lipo -create target/x86_64-apple-darwin/$(RUST_VARIANT)/libzeroidc.a target/aarch64-apple-darwin/$(RUST_VARIANT)/libzeroidc.a -output target/libzeroidc.a
zeroidc/target/libzeroidc.a: FORCE
cd zeroidc && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build --target=x86_64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd zeroidc && MACOSX_DEPLOYMENT_TARGET=$(MACOS_VERSION_MIN) cargo build --target=aarch64-apple-darwin $(EXTRA_CARGO_FLAGS)
cd zeroidc && lipo -create target/x86_64-apple-darwin/$(RUST_VARIANT)/libzeroidc.a target/aarch64-apple-darwin/$(RUST_VARIANT)/libzeroidc.a -output target/libzeroidc.a
central-controller:
make ARCH_FLAGS="-arch x86_64" ZT_CONTROLLER=1 one
@ -164,7 +149,7 @@ core: libzerotiercore.a
# $(STRIP) zerotier
selftest: $(CORE_OBJS) $(ONE_OBJS) selftest.o
$(CXX) $(CXXFLAGS) -o zerotier-selftest selftest.o $(CORE_OBJS) $(ONE_OBJS) $(LIBS) rustybits/target/libzeroidc.a
$(CXX) $(CXXFLAGS) -o zerotier-selftest selftest.o $(CORE_OBJS) $(ONE_OBJS) $(LIBS) zeroidc/target/libzeroidc.a
$(STRIP) zerotier-selftest
zerotier-selftest: selftest
@ -181,7 +166,7 @@ mac-dist-pkg: FORCE
if [ -f "ZeroTier One Signed.pkg" ]; then mv -f "ZeroTier One Signed.pkg" "ZeroTier One.pkg"; fi
rm -f zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_*
cat ext/installfiles/mac-update/updater.tmpl.sh "ZeroTier One.pkg" >zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_$(ZT_VERSION_MAJOR).$(ZT_VERSION_MINOR).$(ZT_VERSION_REV)_$(ZT_VERSION_BUILD).exe
$(NOTARIZE) submit --apple-id "adam.ierymenko@gmail.com" --team-id "8ZD9JUCZ4V" --wait "ZeroTier One.pkg"
$(NOTARIZE) -t osx -f "ZeroTier One.pkg" --primary-bundle-id com.zerotier.pkg.ZeroTierOne --output-format xml --notarize-app -u $(NOTARIZE_USER_ID)
echo '*** When Apple notifies that the app is notarized, run: xcrun stapler staple "ZeroTier One.pkg"'
# For ZeroTier, Inc. to build official signed packages
@ -198,25 +183,12 @@ _buildx:
@echo docker buildx create --name multiarch --driver docker-container --use
@echo docker buildx inspect --bootstrap
controller-builder: _buildx FORCE
docker buildx build --platform linux/arm64,linux/amd64 --no-cache -t registry.zerotier.com/zerotier/ctlbuild:latest -f ext/central-controller-docker/Dockerfile.builder . --push
controller-run: _buildx FORCE
docker buildx build --platform linux/arm64,linux/amd64 --no-cache -t registry.zerotier.com/zerotier-central/ctlrun:latest -f ext/central-controller-docker/Dockerfile.run_base . --push
central-controller-docker: _buildx FORCE
docker buildx build --platform linux/arm64,linux/amd64 --no-cache -t registry.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP} -f ext/central-controller-docker/Dockerfile --build-arg git_branch=$(shell git name-rev --name-only HEAD) . --push
@echo Image: registry.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP}
centralv2-controller-docker: _buildx FORCE
docker buildx build --platform linux/amd64,linux/arm64 --no-cache -t us-central1-docker.pkg.dev/zerotier-d648c7/central-v2/ztcentral-controller:${TIMESTAMP} -f ext/central-controller-docker/Dockerfile --build-arg git_branch=`git name-rev --name-only HEAD` . --push
@echo Image: us-central1-docker.pkg.dev/zerotier-d648c7/central-v2/ztcentral-controller:${TIMESTAMP}
docker-release: _buildx
docker buildx build --platform linux/386,linux/amd64,linux/arm/v7,linux/arm64,linux/mips64le,linux/ppc64le,linux/s390x -t zerotier/zerotier:${RELEASE_DOCKER_TAG} -t zerotier/zerotier:latest --build-arg VERSION=${RELEASE_VERSION} -f Dockerfile.release . --push
clean:
rm -rf MacEthernetTapAgent *.dSYM build-* *.a *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli zerotier doc/node_modules zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_* rustybits/target/
rm -rf MacEthernetTapAgent *.dSYM build-* *.a *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli zerotier doc/node_modules zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_* zeroidc/target/
distclean: clean

View file

@ -4,16 +4,15 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "AES.hpp"
#include "Constants.hpp"
#include "AES.hpp"
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
@ -32,40 +31,40 @@ namespace ZeroTier {
namespace {
#define s_bmul32(N, x, y, rh, rl) \
uint32_t x0t_##N = (x) & 0x11111111U; \
uint32_t x1t_##N = (x) & 0x22222222U; \
uint32_t x2t_##N = (x) & 0x44444444U; \
uint32_t x3t_##N = (x) & 0x88888888U; \
uint32_t y0t_##N = (y) & 0x11111111U; \
uint32_t y1t_##N = (y) & 0x22222222U; \
uint32_t y2t_##N = (y) & 0x44444444U; \
uint32_t y3t_##N = (y) & 0x88888888U; \
uint64_t z0t_##N = (((uint64_t)x0t_##N * y0t_##N) ^ ((uint64_t)x1t_##N * y3t_##N) ^ ((uint64_t)x2t_##N * y2t_##N) ^ ((uint64_t)x3t_##N * y1t_##N)) & 0x1111111111111111ULL; \
uint64_t z1t_##N = (((uint64_t)x0t_##N * y1t_##N) ^ ((uint64_t)x1t_##N * y0t_##N) ^ ((uint64_t)x2t_##N * y3t_##N) ^ ((uint64_t)x3t_##N * y2t_##N)) & 0x2222222222222222ULL; \
uint64_t z2t_##N = (((uint64_t)x0t_##N * y2t_##N) ^ ((uint64_t)x1t_##N * y1t_##N) ^ ((uint64_t)x2t_##N * y0t_##N) ^ ((uint64_t)x3t_##N * y3t_##N)) & 0x4444444444444444ULL; \
z0t_##N |= z1t_##N; \
z2t_##N |= z0t_##N; \
uint64_t zt_##N = z2t_##N | ((((uint64_t)x0t_##N * y3t_##N) ^ ((uint64_t)x1t_##N * y2t_##N) ^ ((uint64_t)x2t_##N * y1t_##N) ^ ((uint64_t)x3t_##N * y0t_##N)) & 0x8888888888888888ULL); \
(rh) = (uint32_t)(zt_##N >> 32U); \
#define s_bmul32(N, x, y, rh, rl) \
uint32_t x0t_##N = (x) & 0x11111111U; \
uint32_t x1t_##N = (x) & 0x22222222U; \
uint32_t x2t_##N = (x) & 0x44444444U; \
uint32_t x3t_##N = (x) & 0x88888888U; \
uint32_t y0t_##N = (y) & 0x11111111U; \
uint32_t y1t_##N = (y) & 0x22222222U; \
uint32_t y2t_##N = (y) & 0x44444444U; \
uint32_t y3t_##N = (y) & 0x88888888U; \
uint64_t z0t_##N = (((uint64_t)x0t_##N * y0t_##N) ^ ((uint64_t)x1t_##N * y3t_##N) ^ ((uint64_t)x2t_##N * y2t_##N) ^ ((uint64_t)x3t_##N * y1t_##N)) & 0x1111111111111111ULL; \
uint64_t z1t_##N = (((uint64_t)x0t_##N * y1t_##N) ^ ((uint64_t)x1t_##N * y0t_##N) ^ ((uint64_t)x2t_##N * y3t_##N) ^ ((uint64_t)x3t_##N * y2t_##N)) & 0x2222222222222222ULL; \
uint64_t z2t_##N = (((uint64_t)x0t_##N * y2t_##N) ^ ((uint64_t)x1t_##N * y1t_##N) ^ ((uint64_t)x2t_##N * y0t_##N) ^ ((uint64_t)x3t_##N * y3t_##N)) & 0x4444444444444444ULL; \
z0t_##N |= z1t_##N; \
z2t_##N |= z0t_##N; \
uint64_t zt_##N = z2t_##N | ((((uint64_t)x0t_##N * y3t_##N) ^ ((uint64_t)x1t_##N * y2t_##N) ^ ((uint64_t)x2t_##N * y1t_##N) ^ ((uint64_t)x3t_##N * y0t_##N)) & 0x8888888888888888ULL); \
(rh) = (uint32_t)(zt_##N >> 32U); \
(rl) = (uint32_t)zt_##N;
void s_gfmul(const uint64_t hh, const uint64_t hl, uint64_t& y0, uint64_t& y1) noexcept
void s_gfmul(const uint64_t hh, const uint64_t hl, uint64_t &y0, uint64_t &y1) noexcept
{
uint32_t hhh = (uint32_t)(hh >> 32U);
uint32_t hhl = (uint32_t)hh;
uint32_t hlh = (uint32_t)(hl >> 32U);
uint32_t hll = (uint32_t)hl;
uint32_t hhXlh = hhh ^ hlh;
uint32_t hhXll = hhl ^ hll;
uint32_t hhXlh = hhh ^hlh;
uint32_t hhXll = hhl ^hll;
uint64_t yl = Utils::ntoh(y0);
uint64_t yh = Utils::ntoh(y1);
uint32_t cilh = (uint32_t)(yh >> 32U);
uint32_t cill = (uint32_t)yh;
uint32_t cihh = (uint32_t)(yl >> 32U);
uint32_t cihl = (uint32_t)yl;
uint32_t cihXlh = cihh ^ cilh;
uint32_t cihXll = cihl ^ cill;
uint32_t cihXlh = cihh ^cilh;
uint32_t cihXll = cihl ^cill;
uint32_t aah, aal, abh, abl, ach, acl;
s_bmul32(M0, cihh, hhh, aah, aal);
s_bmul32(M1, cihl, hhl, abh, abl);
@ -95,8 +94,8 @@ void s_gfmul(const uint64_t hh, const uint64_t hl, uint64_t& y0, uint64_t& y1) n
cbh ^= bbh ^ abh;
cbl ^= bbl ^ abl;
uint64_t zhh = ((uint64_t)aah << 32U) | aal;
uint64_t zhl = (((uint64_t)abh << 32U) | abl) ^ (((uint64_t)cah << 32U) | cal);
uint64_t zlh = (((uint64_t)bah << 32U) | bal) ^ (((uint64_t)cbh << 32U) | cbl);
uint64_t zhl = (((uint64_t)abh << 32U) | abl) ^(((uint64_t)cah << 32U) | cal);
uint64_t zlh = (((uint64_t)bah << 32U) | bal) ^(((uint64_t)cbh << 32U) | cbl);
uint64_t zll = ((uint64_t)bbh << 32U) | bbl;
zhh = zhh << 1U | zhl >> 63U;
zhl = zhl << 1U | zlh >> 63U;
@ -109,11 +108,11 @@ void s_gfmul(const uint64_t hh, const uint64_t hl, uint64_t& y0, uint64_t& y1) n
y1 = Utils::hton(zhl);
}
} // anonymous namespace
} // anonymous namespace
void AES::GMAC::update(const void* const data, unsigned int len) noexcept
void AES::GMAC::update(const void *const data, unsigned int len) noexcept
{
const uint8_t* in = reinterpret_cast<const uint8_t*>(data);
const uint8_t *in = reinterpret_cast<const uint8_t *>(data);
_len += len;
#ifdef ZT_AES_AESNI
@ -121,14 +120,14 @@ void AES::GMAC::update(const void* const data, unsigned int len) noexcept
p_aesNIUpdate(in, len);
return;
}
#endif // ZT_AES_AESNI
#endif // ZT_AES_AESNI
#ifdef ZT_AES_NEON
if (Utils::ARMCAP.pmull) {
p_armUpdate(in, len);
return;
}
#endif // ZT_AES_NEON
#endif // ZT_AES_NEON
const uint64_t h0 = _aes.p_k.sw.h[0];
const uint64_t h1 = _aes.p_k.sw.h[1];
@ -137,14 +136,14 @@ void AES::GMAC::update(const void* const data, unsigned int len) noexcept
if (_rp) {
for (;;) {
if (! len) {
if (!len) {
return;
}
--len;
_r[_rp++] = *(in++);
if (_rp == 16) {
y0 ^= Utils::loadMachineEndian<uint64_t>(_r);
y1 ^= Utils::loadMachineEndian<uint64_t>(_r + 8);
y0 ^= Utils::loadMachineEndian< uint64_t >(_r);
y1 ^= Utils::loadMachineEndian< uint64_t >(_r + 8);
s_gfmul(h0, h1, y0, y1);
break;
}
@ -152,8 +151,8 @@ void AES::GMAC::update(const void* const data, unsigned int len) noexcept
}
while (len >= 16) {
y0 ^= Utils::loadMachineEndian<uint64_t>(in);
y1 ^= Utils::loadMachineEndian<uint64_t>(in + 8);
y0 ^= Utils::loadMachineEndian< uint64_t >(in);
y1 ^= Utils::loadMachineEndian< uint64_t >(in + 8);
in += 16;
s_gfmul(h0, h1, y0, y1);
len -= 16;
@ -165,7 +164,7 @@ void AES::GMAC::update(const void* const data, unsigned int len) noexcept
for (unsigned int i = 0; i < len; ++i) {
_r[i] = in[i];
}
_rp = len; // len is always less than 16 here
_rp = len; // len is always less than 16 here
}
void AES::GMAC::finish(uint8_t tag[16]) noexcept
@ -175,14 +174,14 @@ void AES::GMAC::finish(uint8_t tag[16]) noexcept
p_aesNIFinish(tag);
return;
}
#endif // ZT_AES_AESNI
#endif // ZT_AES_AESNI
#ifdef ZT_AES_NEON
if (Utils::ARMCAP.pmull) {
p_armFinish(tag);
return;
}
#endif // ZT_AES_NEON
#endif // ZT_AES_NEON
const uint64_t h0 = _aes.p_k.sw.h[0];
const uint64_t h1 = _aes.p_k.sw.h[1];
@ -193,8 +192,8 @@ void AES::GMAC::finish(uint8_t tag[16]) noexcept
while (_rp < 16) {
_r[_rp++] = 0;
}
y0 ^= Utils::loadMachineEndian<uint64_t>(_r);
y1 ^= Utils::loadMachineEndian<uint64_t>(_r + 8);
y0 ^= Utils::loadMachineEndian< uint64_t >(_r);
y1 ^= Utils::loadMachineEndian< uint64_t >(_r + 8);
s_gfmul(h0, h1, y0, y1);
}
@ -202,57 +201,57 @@ void AES::GMAC::finish(uint8_t tag[16]) noexcept
s_gfmul(h0, h1, y0, y1);
uint64_t iv2[2];
Utils::copy<12>(iv2, _iv);
Utils::copy< 12 >(iv2, _iv);
#if __BYTE_ORDER == __BIG_ENDIAN
reinterpret_cast<uint32_t*>(iv2)[3] = 0x00000001;
reinterpret_cast<uint32_t *>(iv2)[3] = 0x00000001;
#else
reinterpret_cast<uint32_t*>(iv2)[3] = 0x01000000;
reinterpret_cast<uint32_t *>(iv2)[3] = 0x01000000;
#endif
_aes.encrypt(iv2, iv2);
Utils::storeMachineEndian<uint64_t>(tag, iv2[0] ^ y0);
Utils::storeMachineEndian<uint64_t>(tag + 8, iv2[1] ^ y1);
Utils::storeMachineEndian< uint64_t >(tag, iv2[0] ^ y0);
Utils::storeMachineEndian< uint64_t >(tag + 8, iv2[1] ^ y1);
}
// AES-CTR ------------------------------------------------------------------------------------------------------------
void AES::CTR::crypt(const void* const input, unsigned int len) noexcept
void AES::CTR::crypt(const void *const input, unsigned int len) noexcept
{
const uint8_t* in = reinterpret_cast<const uint8_t*>(input);
uint8_t* out = _out;
const uint8_t *in = reinterpret_cast<const uint8_t *>(input);
uint8_t *out = _out;
#ifdef ZT_AES_AESNI
if (likely(Utils::CPUID.aes)) {
p_aesNICrypt(in, out, len);
return;
}
#endif // ZT_AES_AESNI
#endif // ZT_AES_AESNI
#ifdef ZT_AES_NEON
if (Utils::ARMCAP.aes) {
p_armCrypt(in, out, len);
return;
}
#endif // ZT_AES_NEON
#endif // ZT_AES_NEON
uint64_t keyStream[2];
uint32_t ctr = Utils::ntoh(reinterpret_cast<uint32_t*>(_ctr)[3]);
uint32_t ctr = Utils::ntoh(reinterpret_cast<uint32_t *>(_ctr)[3]);
unsigned int totalLen = _len;
if ((totalLen & 15U)) {
for (;;) {
if (! len) {
if (!len) {
_len = (totalLen + len);
return;
}
--len;
out[totalLen++] = *(in++);
if (! (totalLen & 15U)) {
_aes.p_encryptSW(reinterpret_cast<const uint8_t*>(_ctr), reinterpret_cast<uint8_t*>(keyStream));
reinterpret_cast<uint32_t*>(_ctr)[3] = Utils::hton(++ctr);
uint8_t* outblk = out + (totalLen - 16);
if (!(totalLen & 15U)) {
_aes.p_encryptSW(reinterpret_cast<const uint8_t *>(_ctr), reinterpret_cast<uint8_t *>(keyStream));
reinterpret_cast<uint32_t *>(_ctr)[3] = Utils::hton(++ctr);
uint8_t *outblk = out + (totalLen - 16);
for (int i = 0; i < 16; ++i) {
outblk[i] ^= reinterpret_cast<uint8_t*>(keyStream)[i];
outblk[i] ^= reinterpret_cast<uint8_t *>(keyStream)[i];
}
break;
}
@ -263,10 +262,10 @@ void AES::CTR::crypt(const void* const input, unsigned int len) noexcept
_len = (totalLen + len);
if (likely(len >= 16)) {
const uint32_t* const restrict rk = _aes.p_k.sw.ek;
const uint32_t ctr0rk0 = Utils::ntoh(reinterpret_cast<const uint32_t*>(_ctr)[0]) ^ rk[0];
const uint32_t ctr1rk1 = Utils::ntoh(reinterpret_cast<const uint32_t*>(_ctr)[1]) ^ rk[1];
const uint32_t ctr2rk2 = Utils::ntoh(reinterpret_cast<const uint32_t*>(_ctr)[2]) ^ rk[2];
const uint32_t *const restrict rk = _aes.p_k.sw.ek;
const uint32_t ctr0rk0 = Utils::ntoh(reinterpret_cast<const uint32_t *>(_ctr)[0]) ^rk[0];
const uint32_t ctr1rk1 = Utils::ntoh(reinterpret_cast<const uint32_t *>(_ctr)[1]) ^rk[1];
const uint32_t ctr2rk2 = Utils::ntoh(reinterpret_cast<const uint32_t *>(_ctr)[2]) ^rk[2];
const uint32_t m8 = 0x000000ff;
const uint32_t m8_8 = 0x0000ff00;
const uint32_t m8_16 = 0x00ff0000;
@ -279,8 +278,8 @@ void AES::CTR::crypt(const void* const input, unsigned int len) noexcept
s2 = ctr2rk2;
s3 = ctr++ ^ rk[3];
const uint64_t in0 = *reinterpret_cast<const uint64_t*>(in);
const uint64_t in1 = *reinterpret_cast<const uint64_t*>(in + 8);
const uint64_t in0 = *reinterpret_cast<const uint64_t *>(in);
const uint64_t in1 = *reinterpret_cast<const uint64_t *>(in + 8);
in += 16;
t0 = Te0[s0 >> 24U] ^ Te1_r((s1 >> 16U) & m8) ^ Te2_r((s2 >> 8U) & m8) ^ Te3_r(s3 & m8) ^ rk[4];
@ -340,12 +339,11 @@ void AES::CTR::crypt(const void* const input, unsigned int len) noexcept
s2 = (Te2_r(t2 >> 24U) & m8_24) ^ (Te3_r((t3 >> 16U) & m8) & m8_16) ^ (Te0[(t0 >> 8U) & m8] & m8_8) ^ (Te1_r(t1 & m8) & m8) ^ rk[58];
s3 = (Te2_r(t3 >> 24U) & m8_24) ^ (Te3_r((t0 >> 16U) & m8) & m8_16) ^ (Te0[(t1 >> 8U) & m8] & m8_8) ^ (Te1_r(t2 & m8) & m8) ^ rk[59];
*reinterpret_cast<uint64_t*>(out) = in0 ^ Utils::hton(((uint64_t)s0 << 32U) | (uint64_t)s1);
*reinterpret_cast<uint64_t*>(out + 8) = in1 ^ Utils::hton(((uint64_t)s2 << 32U) | (uint64_t)s3);
*reinterpret_cast<uint64_t *>(out) = in0 ^ Utils::hton(((uint64_t)s0 << 32U) | (uint64_t)s1);
*reinterpret_cast<uint64_t *>(out + 8) = in1 ^ Utils::hton(((uint64_t)s2 << 32U) | (uint64_t)s3);
out += 16;
} while ((len -= 16) >= 16);
}
else {
} else {
do {
uint32_t s0, s1, s2, s3, t0, t1, t2, t3;
s0 = ctr0rk0;
@ -430,7 +428,7 @@ void AES::CTR::crypt(const void* const input, unsigned int len) noexcept
in += 16;
} while ((len -= 16) >= 16);
}
reinterpret_cast<uint32_t*>(_ctr)[3] = Utils::hton(ctr);
reinterpret_cast<uint32_t *>(_ctr)[3] = Utils::hton(ctr);
}
// Any remaining input is placed in _out. This will be picked up and crypted
@ -456,76 +454,48 @@ void AES::CTR::finish() noexcept
// Software AES and AES key expansion ---------------------------------------------------------------------------------
const uint32_t AES::Te0[256] = { 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a,
0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b,
0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f,
0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f,
0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497,
0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a,
0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3,
0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d,
0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395,
0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76,
0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b,
0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818,
0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85,
0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9,
0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a,
0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a };
const uint32_t AES::Te4[256] = { 0x63636363, 0x7c7c7c7c, 0x77777777, 0x7b7b7b7b, 0xf2f2f2f2, 0x6b6b6b6b, 0x6f6f6f6f, 0xc5c5c5c5, 0x30303030, 0x01010101, 0x67676767, 0x2b2b2b2b, 0xfefefefe, 0xd7d7d7d7, 0xabababab, 0x76767676,
0xcacacaca, 0x82828282, 0xc9c9c9c9, 0x7d7d7d7d, 0xfafafafa, 0x59595959, 0x47474747, 0xf0f0f0f0, 0xadadadad, 0xd4d4d4d4, 0xa2a2a2a2, 0xafafafaf, 0x9c9c9c9c, 0xa4a4a4a4, 0x72727272, 0xc0c0c0c0,
0xb7b7b7b7, 0xfdfdfdfd, 0x93939393, 0x26262626, 0x36363636, 0x3f3f3f3f, 0xf7f7f7f7, 0xcccccccc, 0x34343434, 0xa5a5a5a5, 0xe5e5e5e5, 0xf1f1f1f1, 0x71717171, 0xd8d8d8d8, 0x31313131, 0x15151515,
0x04040404, 0xc7c7c7c7, 0x23232323, 0xc3c3c3c3, 0x18181818, 0x96969696, 0x05050505, 0x9a9a9a9a, 0x07070707, 0x12121212, 0x80808080, 0xe2e2e2e2, 0xebebebeb, 0x27272727, 0xb2b2b2b2, 0x75757575,
0x09090909, 0x83838383, 0x2c2c2c2c, 0x1a1a1a1a, 0x1b1b1b1b, 0x6e6e6e6e, 0x5a5a5a5a, 0xa0a0a0a0, 0x52525252, 0x3b3b3b3b, 0xd6d6d6d6, 0xb3b3b3b3, 0x29292929, 0xe3e3e3e3, 0x2f2f2f2f, 0x84848484,
0x53535353, 0xd1d1d1d1, 0x00000000, 0xedededed, 0x20202020, 0xfcfcfcfc, 0xb1b1b1b1, 0x5b5b5b5b, 0x6a6a6a6a, 0xcbcbcbcb, 0xbebebebe, 0x39393939, 0x4a4a4a4a, 0x4c4c4c4c, 0x58585858, 0xcfcfcfcf,
0xd0d0d0d0, 0xefefefef, 0xaaaaaaaa, 0xfbfbfbfb, 0x43434343, 0x4d4d4d4d, 0x33333333, 0x85858585, 0x45454545, 0xf9f9f9f9, 0x02020202, 0x7f7f7f7f, 0x50505050, 0x3c3c3c3c, 0x9f9f9f9f, 0xa8a8a8a8,
0x51515151, 0xa3a3a3a3, 0x40404040, 0x8f8f8f8f, 0x92929292, 0x9d9d9d9d, 0x38383838, 0xf5f5f5f5, 0xbcbcbcbc, 0xb6b6b6b6, 0xdadadada, 0x21212121, 0x10101010, 0xffffffff, 0xf3f3f3f3, 0xd2d2d2d2,
0xcdcdcdcd, 0x0c0c0c0c, 0x13131313, 0xecececec, 0x5f5f5f5f, 0x97979797, 0x44444444, 0x17171717, 0xc4c4c4c4, 0xa7a7a7a7, 0x7e7e7e7e, 0x3d3d3d3d, 0x64646464, 0x5d5d5d5d, 0x19191919, 0x73737373,
0x60606060, 0x81818181, 0x4f4f4f4f, 0xdcdcdcdc, 0x22222222, 0x2a2a2a2a, 0x90909090, 0x88888888, 0x46464646, 0xeeeeeeee, 0xb8b8b8b8, 0x14141414, 0xdededede, 0x5e5e5e5e, 0x0b0b0b0b, 0xdbdbdbdb,
0xe0e0e0e0, 0x32323232, 0x3a3a3a3a, 0x0a0a0a0a, 0x49494949, 0x06060606, 0x24242424, 0x5c5c5c5c, 0xc2c2c2c2, 0xd3d3d3d3, 0xacacacac, 0x62626262, 0x91919191, 0x95959595, 0xe4e4e4e4, 0x79797979,
0xe7e7e7e7, 0xc8c8c8c8, 0x37373737, 0x6d6d6d6d, 0x8d8d8d8d, 0xd5d5d5d5, 0x4e4e4e4e, 0xa9a9a9a9, 0x6c6c6c6c, 0x56565656, 0xf4f4f4f4, 0xeaeaeaea, 0x65656565, 0x7a7a7a7a, 0xaeaeaeae, 0x08080808,
0xbabababa, 0x78787878, 0x25252525, 0x2e2e2e2e, 0x1c1c1c1c, 0xa6a6a6a6, 0xb4b4b4b4, 0xc6c6c6c6, 0xe8e8e8e8, 0xdddddddd, 0x74747474, 0x1f1f1f1f, 0x4b4b4b4b, 0xbdbdbdbd, 0x8b8b8b8b, 0x8a8a8a8a,
0x70707070, 0x3e3e3e3e, 0xb5b5b5b5, 0x66666666, 0x48484848, 0x03030303, 0xf6f6f6f6, 0x0e0e0e0e, 0x61616161, 0x35353535, 0x57575757, 0xb9b9b9b9, 0x86868686, 0xc1c1c1c1, 0x1d1d1d1d, 0x9e9e9e9e,
0xe1e1e1e1, 0xf8f8f8f8, 0x98989898, 0x11111111, 0x69696969, 0xd9d9d9d9, 0x8e8e8e8e, 0x94949494, 0x9b9b9b9b, 0x1e1e1e1e, 0x87878787, 0xe9e9e9e9, 0xcececece, 0x55555555, 0x28282828, 0xdfdfdfdf,
0x8c8c8c8c, 0xa1a1a1a1, 0x89898989, 0x0d0d0d0d, 0xbfbfbfbf, 0xe6e6e6e6, 0x42424242, 0x68686868, 0x41414141, 0x99999999, 0x2d2d2d2d, 0x0f0f0f0f, 0xb0b0b0b0, 0x54545454, 0xbbbbbbbb, 0x16161616 };
const uint32_t AES::Td0[256] = { 0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f,
0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844,
0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94,
0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c,
0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051,
0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb,
0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a,
0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8,
0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120,
0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef,
0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5,
0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6,
0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f,
0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713,
0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86,
0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742 };
const uint8_t AES::Td4[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
const uint32_t AES::rcon[15] = { 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, 0x6c000000, 0xd8000000, 0xab000000, 0x4d000000, 0x9a000000 };
const uint32_t AES::Te0[256] = {0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153,
0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f,
0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba,
0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d,
0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437,
0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818,
0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878,
0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a};
const uint32_t AES::Te4[256] = {0x63636363, 0x7c7c7c7c, 0x77777777, 0x7b7b7b7b, 0xf2f2f2f2, 0x6b6b6b6b, 0x6f6f6f6f, 0xc5c5c5c5, 0x30303030, 0x01010101, 0x67676767, 0x2b2b2b2b, 0xfefefefe, 0xd7d7d7d7, 0xabababab, 0x76767676, 0xcacacaca, 0x82828282, 0xc9c9c9c9, 0x7d7d7d7d, 0xfafafafa, 0x59595959, 0x47474747, 0xf0f0f0f0, 0xadadadad, 0xd4d4d4d4, 0xa2a2a2a2, 0xafafafaf, 0x9c9c9c9c, 0xa4a4a4a4, 0x72727272, 0xc0c0c0c0, 0xb7b7b7b7, 0xfdfdfdfd, 0x93939393, 0x26262626, 0x36363636, 0x3f3f3f3f, 0xf7f7f7f7, 0xcccccccc, 0x34343434, 0xa5a5a5a5, 0xe5e5e5e5, 0xf1f1f1f1, 0x71717171, 0xd8d8d8d8, 0x31313131,
0x15151515, 0x04040404, 0xc7c7c7c7, 0x23232323, 0xc3c3c3c3, 0x18181818, 0x96969696, 0x05050505, 0x9a9a9a9a, 0x07070707, 0x12121212, 0x80808080, 0xe2e2e2e2, 0xebebebeb, 0x27272727, 0xb2b2b2b2, 0x75757575,
0x09090909, 0x83838383, 0x2c2c2c2c, 0x1a1a1a1a, 0x1b1b1b1b, 0x6e6e6e6e, 0x5a5a5a5a, 0xa0a0a0a0, 0x52525252, 0x3b3b3b3b, 0xd6d6d6d6, 0xb3b3b3b3, 0x29292929, 0xe3e3e3e3, 0x2f2f2f2f, 0x84848484, 0x53535353, 0xd1d1d1d1, 0x00000000, 0xedededed, 0x20202020, 0xfcfcfcfc, 0xb1b1b1b1, 0x5b5b5b5b, 0x6a6a6a6a, 0xcbcbcbcb, 0xbebebebe, 0x39393939, 0x4a4a4a4a, 0x4c4c4c4c, 0x58585858, 0xcfcfcfcf, 0xd0d0d0d0, 0xefefefef, 0xaaaaaaaa, 0xfbfbfbfb, 0x43434343, 0x4d4d4d4d, 0x33333333, 0x85858585, 0x45454545, 0xf9f9f9f9, 0x02020202, 0x7f7f7f7f, 0x50505050, 0x3c3c3c3c, 0x9f9f9f9f,
0xa8a8a8a8, 0x51515151, 0xa3a3a3a3, 0x40404040, 0x8f8f8f8f, 0x92929292, 0x9d9d9d9d, 0x38383838, 0xf5f5f5f5, 0xbcbcbcbc, 0xb6b6b6b6, 0xdadadada, 0x21212121, 0x10101010, 0xffffffff, 0xf3f3f3f3, 0xd2d2d2d2,
0xcdcdcdcd, 0x0c0c0c0c, 0x13131313, 0xecececec, 0x5f5f5f5f, 0x97979797, 0x44444444, 0x17171717, 0xc4c4c4c4, 0xa7a7a7a7, 0x7e7e7e7e, 0x3d3d3d3d, 0x64646464, 0x5d5d5d5d, 0x19191919, 0x73737373, 0x60606060, 0x81818181, 0x4f4f4f4f, 0xdcdcdcdc, 0x22222222, 0x2a2a2a2a, 0x90909090, 0x88888888, 0x46464646, 0xeeeeeeee, 0xb8b8b8b8, 0x14141414, 0xdededede, 0x5e5e5e5e, 0x0b0b0b0b, 0xdbdbdbdb, 0xe0e0e0e0, 0x32323232, 0x3a3a3a3a, 0x0a0a0a0a, 0x49494949, 0x06060606, 0x24242424, 0x5c5c5c5c, 0xc2c2c2c2, 0xd3d3d3d3, 0xacacacac, 0x62626262, 0x91919191, 0x95959595, 0xe4e4e4e4,
0x79797979, 0xe7e7e7e7, 0xc8c8c8c8, 0x37373737, 0x6d6d6d6d, 0x8d8d8d8d, 0xd5d5d5d5, 0x4e4e4e4e, 0xa9a9a9a9, 0x6c6c6c6c, 0x56565656, 0xf4f4f4f4, 0xeaeaeaea, 0x65656565, 0x7a7a7a7a, 0xaeaeaeae, 0x08080808,
0xbabababa, 0x78787878, 0x25252525, 0x2e2e2e2e, 0x1c1c1c1c, 0xa6a6a6a6, 0xb4b4b4b4, 0xc6c6c6c6, 0xe8e8e8e8, 0xdddddddd, 0x74747474, 0x1f1f1f1f, 0x4b4b4b4b, 0xbdbdbdbd, 0x8b8b8b8b, 0x8a8a8a8a, 0x70707070, 0x3e3e3e3e, 0xb5b5b5b5, 0x66666666, 0x48484848, 0x03030303, 0xf6f6f6f6, 0x0e0e0e0e, 0x61616161, 0x35353535, 0x57575757, 0xb9b9b9b9, 0x86868686, 0xc1c1c1c1, 0x1d1d1d1d, 0x9e9e9e9e, 0xe1e1e1e1, 0xf8f8f8f8, 0x98989898, 0x11111111, 0x69696969, 0xd9d9d9d9, 0x8e8e8e8e, 0x94949494, 0x9b9b9b9b, 0x1e1e1e1e, 0x87878787, 0xe9e9e9e9, 0xcececece, 0x55555555, 0x28282828,
0xdfdfdfdf, 0x8c8c8c8c, 0xa1a1a1a1, 0x89898989, 0x0d0d0d0d, 0xbfbfbfbf, 0xe6e6e6e6, 0x42424242, 0x68686868, 0x41414141, 0x99999999, 0x2d2d2d2d, 0x0f0f0f0f, 0xb0b0b0b0, 0x54545454, 0xbbbbbbbb, 0x16161616};
const uint32_t AES::Td0[256] = {0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c,
0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c,
0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1,
0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8,
0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e,
0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6,
0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14,
0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742};
const uint8_t AES::Td4[256] = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d,
0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c,
0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
const uint32_t AES::rcon[15] = {0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, 0x6c000000, 0xd8000000, 0xab000000, 0x4d000000, 0x9a000000};
void AES::p_initSW(const uint8_t* key) noexcept
void AES::p_initSW(const uint8_t *key) noexcept
{
uint32_t* rk = p_k.sw.ek;
uint32_t *rk = p_k.sw.ek;
rk[0] = Utils::loadBigEndian<uint32_t>(key);
rk[1] = Utils::loadBigEndian<uint32_t>(key + 4);
rk[2] = Utils::loadBigEndian<uint32_t>(key + 8);
rk[3] = Utils::loadBigEndian<uint32_t>(key + 12);
rk[4] = Utils::loadBigEndian<uint32_t>(key + 16);
rk[5] = Utils::loadBigEndian<uint32_t>(key + 20);
rk[6] = Utils::loadBigEndian<uint32_t>(key + 24);
rk[7] = Utils::loadBigEndian<uint32_t>(key + 28);
rk[0] = Utils::loadBigEndian< uint32_t >(key);
rk[1] = Utils::loadBigEndian< uint32_t >(key + 4);
rk[2] = Utils::loadBigEndian< uint32_t >(key + 8);
rk[3] = Utils::loadBigEndian< uint32_t >(key + 12);
rk[4] = Utils::loadBigEndian< uint32_t >(key + 16);
rk[5] = Utils::loadBigEndian< uint32_t >(key + 20);
rk[6] = Utils::loadBigEndian< uint32_t >(key + 24);
rk[7] = Utils::loadBigEndian< uint32_t >(key + 28);
for (int i = 0;;) {
uint32_t temp = rk[7];
rk[8] = rk[0] ^ (Te2_r((temp >> 16U) & 0xffU) & 0xff000000U) ^ (Te3_r((temp >> 8U) & 0xffU) & 0x00ff0000U) ^ (Te0[(temp) & 0xffU] & 0x0000ff00U) ^ (Te1_r(temp >> 24U) & 0x000000ffU) ^ rcon[i];
@ -543,7 +513,7 @@ void AES::p_initSW(const uint8_t* key) noexcept
rk += 8;
}
p_encryptSW((const uint8_t*)Utils::ZERO256, (uint8_t*)p_k.sw.h);
p_encryptSW((const uint8_t *)Utils::ZERO256, (uint8_t *)p_k.sw.h);
p_k.sw.h[0] = Utils::ntoh(p_k.sw.h[0]);
p_k.sw.h[1] = Utils::ntoh(p_k.sw.h[1]);
@ -575,17 +545,17 @@ void AES::p_initSW(const uint8_t* key) noexcept
}
}
void AES::p_encryptSW(const uint8_t* in, uint8_t* out) const noexcept
void AES::p_encryptSW(const uint8_t *in, uint8_t *out) const noexcept
{
const uint32_t* const restrict rk = p_k.sw.ek;
const uint32_t *const restrict rk = p_k.sw.ek;
const uint32_t m8 = 0x000000ff;
const uint32_t m8_8 = 0x0000ff00;
const uint32_t m8_16 = 0x00ff0000;
const uint32_t m8_24 = 0xff000000;
uint32_t s0 = Utils::loadBigEndian<uint32_t>(in) ^ rk[0];
uint32_t s1 = Utils::loadBigEndian<uint32_t>(in + 4) ^ rk[1];
uint32_t s2 = Utils::loadBigEndian<uint32_t>(in + 8) ^ rk[2];
uint32_t s3 = Utils::loadBigEndian<uint32_t>(in + 12) ^ rk[3];
uint32_t s0 = Utils::loadBigEndian< uint32_t >(in) ^rk[0];
uint32_t s1 = Utils::loadBigEndian< uint32_t >(in + 4) ^rk[1];
uint32_t s2 = Utils::loadBigEndian< uint32_t >(in + 8) ^rk[2];
uint32_t s3 = Utils::loadBigEndian< uint32_t >(in + 12) ^rk[3];
uint32_t t0, t1, t2, t3;
t0 = Te0[s0 >> 24U] ^ Te1_r((s1 >> 16U) & m8) ^ Te2_r((s2 >> 8U) & m8) ^ Te3_r(s3 & m8) ^ rk[4];
@ -645,20 +615,20 @@ void AES::p_encryptSW(const uint8_t* in, uint8_t* out) const noexcept
s2 = (Te2_r(t2 >> 24U) & m8_24) ^ (Te3_r((t3 >> 16U) & m8) & m8_16) ^ (Te0[(t0 >> 8U) & m8] & m8_8) ^ (Te1_r(t1 & m8) & m8) ^ rk[58];
s3 = (Te2_r(t3 >> 24U) & m8_24) ^ (Te3_r((t0 >> 16U) & m8) & m8_16) ^ (Te0[(t1 >> 8U) & m8] & m8_8) ^ (Te1_r(t2 & m8) & m8) ^ rk[59];
Utils::storeBigEndian<uint32_t>(out, s0);
Utils::storeBigEndian<uint32_t>(out + 4, s1);
Utils::storeBigEndian<uint32_t>(out + 8, s2);
Utils::storeBigEndian<uint32_t>(out + 12, s3);
Utils::storeBigEndian< uint32_t >(out, s0);
Utils::storeBigEndian< uint32_t >(out + 4, s1);
Utils::storeBigEndian< uint32_t >(out + 8, s2);
Utils::storeBigEndian< uint32_t >(out + 12, s3);
}
void AES::p_decryptSW(const uint8_t* in, uint8_t* out) const noexcept
void AES::p_decryptSW(const uint8_t *in, uint8_t *out) const noexcept
{
const uint32_t* restrict rk = p_k.sw.dk;
const uint32_t *restrict rk = p_k.sw.dk;
const uint32_t m8 = 0x000000ff;
uint32_t s0 = Utils::loadBigEndian<uint32_t>(in) ^ rk[0];
uint32_t s1 = Utils::loadBigEndian<uint32_t>(in + 4) ^ rk[1];
uint32_t s2 = Utils::loadBigEndian<uint32_t>(in + 8) ^ rk[2];
uint32_t s3 = Utils::loadBigEndian<uint32_t>(in + 12) ^ rk[3];
uint32_t s0 = Utils::loadBigEndian< uint32_t >(in) ^rk[0];
uint32_t s1 = Utils::loadBigEndian< uint32_t >(in + 4) ^rk[1];
uint32_t s2 = Utils::loadBigEndian< uint32_t >(in + 8) ^rk[2];
uint32_t s3 = Utils::loadBigEndian< uint32_t >(in + 12) ^rk[3];
uint32_t t0, t1, t2, t3;
t0 = Td0[s0 >> 24U] ^ Td1_r((s3 >> 16U) & m8) ^ Td2_r((s2 >> 8U) & m8) ^ Td3_r(s1 & m8) ^ rk[4];
@ -713,15 +683,15 @@ void AES::p_decryptSW(const uint8_t* in, uint8_t* out) const noexcept
t1 = Td0[s1 >> 24U] ^ Td1_r((s0 >> 16U) & m8) ^ Td2_r((s3 >> 8U) & m8) ^ Td3_r(s2 & m8) ^ rk[53];
t2 = Td0[s2 >> 24U] ^ Td1_r((s1 >> 16U) & m8) ^ Td2_r((s0 >> 8U) & m8) ^ Td3_r(s3 & m8) ^ rk[54];
t3 = Td0[s3 >> 24U] ^ Td1_r((s2 >> 16U) & m8) ^ Td2_r((s1 >> 8U) & m8) ^ Td3_r(s0 & m8) ^ rk[55];
s0 = (Td4[t0 >> 24U] << 24U) ^ (Td4[(t3 >> 16U) & m8] << 16U) ^ (Td4[(t2 >> 8U) & m8] << 8U) ^ (Td4[(t1)&m8]) ^ rk[56];
s1 = (Td4[t1 >> 24U] << 24U) ^ (Td4[(t0 >> 16U) & m8] << 16U) ^ (Td4[(t3 >> 8U) & m8] << 8U) ^ (Td4[(t2)&m8]) ^ rk[57];
s2 = (Td4[t2 >> 24U] << 24U) ^ (Td4[(t1 >> 16U) & m8] << 16U) ^ (Td4[(t0 >> 8U) & m8] << 8U) ^ (Td4[(t3)&m8]) ^ rk[58];
s3 = (Td4[t3 >> 24U] << 24U) ^ (Td4[(t2 >> 16U) & m8] << 16U) ^ (Td4[(t1 >> 8U) & m8] << 8U) ^ (Td4[(t0)&m8]) ^ rk[59];
s0 = (Td4[t0 >> 24U] << 24U) ^ (Td4[(t3 >> 16U) & m8] << 16U) ^ (Td4[(t2 >> 8U) & m8] << 8U) ^ (Td4[(t1) & m8]) ^ rk[56];
s1 = (Td4[t1 >> 24U] << 24U) ^ (Td4[(t0 >> 16U) & m8] << 16U) ^ (Td4[(t3 >> 8U) & m8] << 8U) ^ (Td4[(t2) & m8]) ^ rk[57];
s2 = (Td4[t2 >> 24U] << 24U) ^ (Td4[(t1 >> 16U) & m8] << 16U) ^ (Td4[(t0 >> 8U) & m8] << 8U) ^ (Td4[(t3) & m8]) ^ rk[58];
s3 = (Td4[t3 >> 24U] << 24U) ^ (Td4[(t2 >> 16U) & m8] << 16U) ^ (Td4[(t1 >> 8U) & m8] << 8U) ^ (Td4[(t0) & m8]) ^ rk[59];
Utils::storeBigEndian<uint32_t>(out, s0);
Utils::storeBigEndian<uint32_t>(out + 4, s1);
Utils::storeBigEndian<uint32_t>(out + 8, s2);
Utils::storeBigEndian<uint32_t>(out + 12, s3);
Utils::storeBigEndian< uint32_t >(out, s0);
Utils::storeBigEndian< uint32_t >(out + 4, s1);
Utils::storeBigEndian< uint32_t >(out + 8, s2);
Utils::storeBigEndian< uint32_t >(out + 12, s3);
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -15,16 +15,16 @@
#define ZT_AES_HPP
#include "Constants.hpp"
#include "SHA512.hpp"
#include "Utils.hpp"
#include "SHA512.hpp"
// Uncomment to disable all hardware acceleration (usually for testing)
// #define ZT_AES_NO_ACCEL
//#define ZT_AES_NO_ACCEL
#if ! defined(ZT_AES_NO_ACCEL) && defined(ZT_ARCH_X64)
#if !defined(ZT_AES_NO_ACCEL) && defined(ZT_ARCH_X64)
#define ZT_AES_AESNI 1
#endif
#if ! defined(ZT_AES_NO_ACCEL) && defined(ZT_ARCH_ARM_HAS_NEON) && defined(ZT_ARCH_ARM_HAS_CRYPTO)
#if !defined(ZT_AES_NO_ACCEL) && defined(ZT_ARCH_ARM_HAS_NEON) && defined(ZT_ARCH_ARM_HAS_CRYPTO)
#define ZT_AES_NEON 1
#endif
@ -40,8 +40,9 @@ namespace ZeroTier {
* This includes hardware acceleration for certain processors. The software
* mode is fallback and is significantly slower.
*/
class AES {
public:
class AES
{
public:
/**
* @return True if this system has hardware AES acceleration
*/
@ -62,44 +63,39 @@ class AES {
* Create an un-initialized AES instance (must call init() before use)
*/
ZT_INLINE AES() noexcept
{
}
{}
/**
* Create an AES instance with the given key
*
* @param key 256-bit key
*/
explicit ZT_INLINE AES(const void* const key) noexcept
{
this->init(key);
}
explicit ZT_INLINE AES(const void *const key) noexcept
{ this->init(key); }
ZT_INLINE ~AES()
{
Utils::burn(&p_k, sizeof(p_k));
}
{ Utils::burn(&p_k, sizeof(p_k)); }
/**
* Set (or re-set) this AES256 cipher's key
*
* @param key 256-bit / 32-byte key
*/
ZT_INLINE void init(const void* const key) noexcept
ZT_INLINE void init(const void *const key) noexcept
{
#ifdef ZT_AES_AESNI
if (likely(Utils::CPUID.aes)) {
p_init_aesni(reinterpret_cast<const uint8_t*>(key));
p_init_aesni(reinterpret_cast<const uint8_t *>(key));
return;
}
#endif
#ifdef ZT_AES_NEON
if (Utils::ARMCAP.aes) {
p_init_armneon_crypto(reinterpret_cast<const uint8_t*>(key));
p_init_armneon_crypto(reinterpret_cast<const uint8_t *>(key));
return;
}
#endif
p_initSW(reinterpret_cast<const uint8_t*>(key));
p_initSW(reinterpret_cast<const uint8_t *>(key));
}
/**
@ -108,7 +104,7 @@ class AES {
* @param in Input block
* @param out Output block (can be same as input)
*/
ZT_INLINE void encrypt(const void* const in, void* const out) const noexcept
ZT_INLINE void encrypt(const void *const in, void *const out) const noexcept
{
#ifdef ZT_AES_AESNI
if (likely(Utils::CPUID.aes)) {
@ -122,7 +118,7 @@ class AES {
return;
}
#endif
p_encryptSW(reinterpret_cast<const uint8_t*>(in), reinterpret_cast<uint8_t*>(out));
p_encryptSW(reinterpret_cast<const uint8_t *>(in), reinterpret_cast<uint8_t *>(out));
}
/**
@ -131,7 +127,7 @@ class AES {
* @param in Input block
* @param out Output block (can be same as input)
*/
ZT_INLINE void decrypt(const void* const in, void* const out) const noexcept
ZT_INLINE void decrypt(const void *const in, void *const out) const noexcept
{
#ifdef ZT_AES_AESNI
if (likely(Utils::CPUID.aes)) {
@ -145,7 +141,7 @@ class AES {
return;
}
#endif
p_decryptSW(reinterpret_cast<const uint8_t*>(in), reinterpret_cast<uint8_t*>(out));
p_decryptSW(reinterpret_cast<const uint8_t *>(in), reinterpret_cast<uint8_t *>(out));
}
class GMACSIVEncryptor;
@ -154,11 +150,12 @@ class AES {
/**
* Streaming GMAC calculator
*/
class GMAC {
class GMAC
{
friend class GMACSIVEncryptor;
friend class GMACSIVDecryptor;
public:
public:
/**
* @return True if this system has hardware GMAC acceleration
*/
@ -180,9 +177,8 @@ class AES {
*
* @param aes Keyed AES instance to use
*/
ZT_INLINE GMAC(const AES& aes) : _aes(aes)
{
}
ZT_INLINE GMAC(const AES &aes) : _aes(aes)
{}
/**
* Reset and initialize for a new GMAC calculation
@ -196,12 +192,12 @@ class AES {
// We fill the least significant 32 bits in the _iv field with 1 since in GCM mode
// this would hold the counter, but we're not doing GCM. The counter is therefore
// always 1.
#ifdef ZT_AES_AESNI // also implies an x64 processor
*reinterpret_cast<uint64_t*>(_iv) = *reinterpret_cast<const uint64_t*>(iv);
*reinterpret_cast<uint32_t*>(_iv + 8) = *reinterpret_cast<const uint64_t*>(iv + 8);
*reinterpret_cast<uint32_t*>(_iv + 12) = 0x01000000; // 0x00000001 in big-endian byte order
#ifdef ZT_AES_AESNI // also implies an x64 processor
*reinterpret_cast<uint64_t *>(_iv) = *reinterpret_cast<const uint64_t *>(iv);
*reinterpret_cast<uint32_t *>(_iv + 8) = *reinterpret_cast<const uint64_t *>(iv + 8);
*reinterpret_cast<uint32_t *>(_iv + 12) = 0x01000000; // 0x00000001 in big-endian byte order
#else
for (int i = 0; i < 12; ++i) {
for(int i=0;i<12;++i) {
_iv[i] = iv[i];
}
_iv[12] = 0;
@ -219,7 +215,7 @@ class AES {
* @param data Bytes to process
* @param len Length of input
*/
void update(const void* data, unsigned int len) noexcept;
void update(const void *data, unsigned int len) noexcept;
/**
* Process any remaining cached bytes and generate tag
@ -230,19 +226,19 @@ class AES {
*/
void finish(uint8_t tag[16]) noexcept;
private:
private:
#ifdef ZT_AES_AESNI
void p_aesNIUpdate(const uint8_t* in, unsigned int len) noexcept;
void p_aesNIUpdate(const uint8_t *in, unsigned int len) noexcept;
void p_aesNIFinish(uint8_t tag[16]) noexcept;
#endif
#ifdef ZT_AES_NEON
void p_armUpdate(const uint8_t* in, unsigned int len) noexcept;
void p_armUpdate(const uint8_t *in, unsigned int len) noexcept;
void p_armFinish(uint8_t tag[16]) noexcept;
#endif
const AES& _aes;
const AES &_aes;
unsigned int _rp;
unsigned int _len;
uint8_t _r[16]; // remainder
uint8_t _r[16]; // remainder
uint8_t _iv[16];
uint64_t _y[2];
};
@ -253,14 +249,14 @@ class AES {
* NOTE: this doesn't support overflow of the counter in the least significant 32 bits.
* AES-GMAC-CTR doesn't need this, so we don't support it as an optimization.
*/
class CTR {
class CTR
{
friend class GMACSIVEncryptor;
friend class GMACSIVDecryptor;
public:
ZT_INLINE CTR(const AES& aes) noexcept : _aes(aes)
{
}
public:
ZT_INLINE CTR(const AES &aes) noexcept: _aes(aes)
{}
/**
* Initialize this CTR instance to encrypt a new stream
@ -268,10 +264,10 @@ class AES {
* @param iv Unique initialization vector and initial 32-bit counter (least significant 32 bits, big-endian)
* @param output Buffer to which to store output (MUST be large enough for total bytes processed!)
*/
ZT_INLINE void init(const uint8_t iv[16], void* const output) noexcept
ZT_INLINE void init(const uint8_t iv[16], void *const output) noexcept
{
Utils::copy<16>(_ctr, iv);
_out = reinterpret_cast<uint8_t*>(output);
Utils::copy< 16 >(_ctr, iv);
_out = reinterpret_cast<uint8_t *>(output);
_len = 0;
}
@ -282,11 +278,11 @@ class AES {
* @param ic Initial counter (must be in big-endian byte order!)
* @param output Buffer to which to store output (MUST be large enough for total bytes processed!)
*/
ZT_INLINE void init(const uint8_t iv[12], const uint32_t ic, void* const output) noexcept
ZT_INLINE void init(const uint8_t iv[12], const uint32_t ic, void *const output) noexcept
{
Utils::copy<12>(_ctr, iv);
reinterpret_cast<uint32_t*>(_ctr)[3] = ic;
_out = reinterpret_cast<uint8_t*>(output);
Utils::copy< 12 >(_ctr, iv);
reinterpret_cast<uint32_t *>(_ctr)[3] = ic;
_out = reinterpret_cast<uint8_t *>(output);
_len = 0;
}
@ -296,7 +292,7 @@ class AES {
* @param input Input data
* @param len Length of input
*/
void crypt(const void* input, unsigned int len) noexcept;
void crypt(const void *input, unsigned int len) noexcept;
/**
* Finish any remaining bytes if total bytes processed wasn't a multiple of 16
@ -305,16 +301,16 @@ class AES {
*/
void finish() noexcept;
private:
private:
#ifdef ZT_AES_AESNI
void p_aesNICrypt(const uint8_t* in, uint8_t* out, unsigned int len) noexcept;
void p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) noexcept;
#endif
#ifdef ZT_AES_NEON
void p_armCrypt(const uint8_t* in, uint8_t* out, unsigned int len) noexcept;
void p_armCrypt(const uint8_t *in, uint8_t *out, unsigned int len) noexcept;
#endif
const AES& _aes;
const AES &_aes;
uint64_t _ctr[2];
uint8_t* _out;
uint8_t *_out;
unsigned int _len;
};
@ -329,19 +325,19 @@ class AES {
* This supports encryption of a maximum of 2^31 bytes of data per
* call to init().
*/
class GMACSIVEncryptor {
public:
class GMACSIVEncryptor
{
public:
/**
* Create a new AES-GMAC-SIV encryptor keyed with the provided AES instances
*
* @param k0 First of two AES instances keyed with K0
* @param k1 Second of two AES instances keyed with K1
*/
ZT_INLINE GMACSIVEncryptor(const AES& k0, const AES& k1) noexcept
: _gmac(k0)
, _ctr(k1)
{
}
ZT_INLINE GMACSIVEncryptor(const AES &k0, const AES &k1) noexcept :
_gmac(k0),
_ctr(k1)
{}
/**
* Initialize AES-GMAC-SIV
@ -349,7 +345,7 @@ class AES {
* @param iv IV in network byte order (byte order in which it will appear on the wire)
* @param output Pointer to buffer to receive ciphertext, must be large enough for all to-be-processed data!
*/
ZT_INLINE void init(const uint64_t iv, void* const output) noexcept
ZT_INLINE void init(const uint64_t iv, void *const output) noexcept
{
// Output buffer to receive the result of AES-CTR encryption.
_output = output;
@ -357,7 +353,7 @@ class AES {
// Initialize GMAC with 64-bit IV (and remaining 32 bits padded to zero).
_tag[0] = iv;
_tag[1] = 0;
_gmac.init(reinterpret_cast<const uint8_t*>(_tag));
_gmac.init(reinterpret_cast<const uint8_t *>(_tag));
}
/**
@ -371,7 +367,7 @@ class AES {
* @param aad Additional authenticated data
* @param len Length of AAD in bytes
*/
ZT_INLINE void aad(const void* const aad, unsigned int len) noexcept
ZT_INLINE void aad(const void *const aad, unsigned int len) noexcept
{
// Feed ADD into GMAC first
_gmac.update(aad, len);
@ -389,10 +385,8 @@ class AES {
* @param input Plaintext chunk
* @param len Length of plaintext chunk
*/
ZT_INLINE void update1(const void* const input, const unsigned int len) noexcept
{
_gmac.update(input, len);
}
ZT_INLINE void update1(const void *const input, const unsigned int len) noexcept
{ _gmac.update(input, len); }
/**
* Finish first pass, compute CTR IV, initialize second pass.
@ -401,7 +395,7 @@ class AES {
{
// Compute 128-bit GMAC tag.
uint64_t tmp[2];
_gmac.finish(reinterpret_cast<uint8_t*>(tmp));
_gmac.finish(reinterpret_cast<uint8_t *>(tmp));
// Shorten to 64 bits, concatenate with message IV, and encrypt with AES to
// yield the CTR IV and opaque IV/MAC blob. In ZeroTier's use of GMAC-SIV
@ -421,7 +415,7 @@ class AES {
// and so 2^31 should be considered the input limit.
tmp[0] = _tag[0];
tmp[1] = _tag[1] & ZT_CONST_TO_BE_UINT64(0xffffffff7fffffffULL);
_ctr.init(reinterpret_cast<const uint8_t*>(tmp), _output);
_ctr.init(reinterpret_cast<const uint8_t *>(tmp), _output);
}
/**
@ -433,10 +427,8 @@ class AES {
* @param input Plaintext chunk
* @param len Length of plaintext chunk
*/
ZT_INLINE void update2(const void* const input, const unsigned int len) noexcept
{
_ctr.crypt(input, len);
}
ZT_INLINE void update2(const void *const input, const unsigned int len) noexcept
{ _ctr.crypt(input, len); }
/**
* Finish second pass and return a pointer to the opaque 128-bit IV+MAC block
@ -446,14 +438,14 @@ class AES {
*
* @return Pointer to 128-bit opaque IV+MAC (packed into two 64-bit integers)
*/
ZT_INLINE const uint64_t* finish2()
ZT_INLINE const uint64_t *finish2()
{
_ctr.finish();
return _tag;
}
private:
void* _output;
private:
void *_output;
uint64_t _tag[2];
AES::GMAC _gmac;
AES::CTR _ctr;
@ -464,13 +456,13 @@ class AES {
*
* GMAC-SIV decryption is single-pass. AAD (if any) must be processed first.
*/
class GMACSIVDecryptor {
public:
ZT_INLINE GMACSIVDecryptor(const AES& k0, const AES& k1) noexcept
: _ctr(k1)
, _gmac(k0)
{
}
class GMACSIVDecryptor
{
public:
ZT_INLINE GMACSIVDecryptor(const AES &k0, const AES &k1) noexcept:
_ctr(k1),
_gmac(k0)
{}
/**
* Initialize decryptor for a new message
@ -478,18 +470,18 @@ class AES {
* @param tag 128-bit combined IV/MAC originally created by GMAC-SIV encryption
* @param output Buffer in which to write output plaintext (must be large enough!)
*/
ZT_INLINE void init(const uint64_t tag[2], void* const output) noexcept
ZT_INLINE void init(const uint64_t tag[2], void *const output) noexcept
{
uint64_t tmp[2];
tmp[0] = tag[0];
tmp[1] = tag[1] & ZT_CONST_TO_BE_UINT64(0xffffffff7fffffffULL);
_ctr.init(reinterpret_cast<const uint8_t*>(tmp), output);
_ctr.init(reinterpret_cast<const uint8_t *>(tmp), output);
_ctr._aes.decrypt(tag, _ivMac);
tmp[0] = _ivMac[0];
tmp[1] = 0;
_gmac.init(reinterpret_cast<const uint8_t*>(tmp));
_gmac.init(reinterpret_cast<const uint8_t *>(tmp));
_output = output;
_decryptedLen = 0;
@ -501,7 +493,7 @@ class AES {
* @param aad Additional authenticated data
* @param len Length of AAD in bytes
*/
ZT_INLINE void aad(const void* const aad, unsigned int len) noexcept
ZT_INLINE void aad(const void *const aad, unsigned int len) noexcept
{
_gmac.update(aad, len);
len &= 0xfU;
@ -518,7 +510,7 @@ class AES {
* @param input Input ciphertext
* @param len Length of ciphertext
*/
ZT_INLINE void update(const void* const input, const unsigned int len) noexcept
ZT_INLINE void update(const void *const input, const unsigned int len) noexcept
{
_ctr.crypt(input, len);
_decryptedLen += len;
@ -535,48 +527,52 @@ class AES {
uint64_t gmacTag[2];
_gmac.update(_output, _decryptedLen);
_gmac.finish(reinterpret_cast<uint8_t*>(gmacTag));
_gmac.finish(reinterpret_cast<uint8_t *>(gmacTag));
return (gmacTag[0] ^ gmacTag[1]) == _ivMac[1];
}
private:
private:
uint64_t _ivMac[2];
AES::CTR _ctr;
AES::GMAC _gmac;
void* _output;
void *_output;
unsigned int _decryptedLen;
};
private:
private:
static const uint32_t Te0[256];
static const uint32_t Te4[256];
static const uint32_t Td0[256];
static const uint8_t Td4[256];
static const uint32_t rcon[15];
void p_initSW(const uint8_t* key) noexcept;
void p_encryptSW(const uint8_t* in, uint8_t* out) const noexcept;
void p_decryptSW(const uint8_t* in, uint8_t* out) const noexcept;
void p_initSW(const uint8_t *key) noexcept;
void p_encryptSW(const uint8_t *in, uint8_t *out) const noexcept;
void p_decryptSW(const uint8_t *in, uint8_t *out) const noexcept;
union {
union
{
#ifdef ZT_AES_AESNI
struct {
struct
{
__m128i k[28];
__m128i h[4]; // h, hh, hhh, hhhh
__m128i h2[4]; // _mm_xor_si128(_mm_shuffle_epi32(h, 78), h), etc.
__m128i h[4]; // h, hh, hhh, hhhh
__m128i h2[4]; // _mm_xor_si128(_mm_shuffle_epi32(h, 78), h), etc.
} ni;
#endif
#ifdef ZT_AES_NEON
struct {
uint64_t hsw[2]; // in case it has AES but not PMULL, not sure if that ever happens
struct
{
uint64_t hsw[2]; // in case it has AES but not PMULL, not sure if that ever happens
uint8x16_t ek[15];
uint8x16_t dk[15];
uint8x16_t h;
} neon;
#endif
struct {
struct
{
uint64_t h[2];
uint32_t ek[60];
uint32_t dk[60];
@ -584,18 +580,18 @@ class AES {
} p_k;
#ifdef ZT_AES_AESNI
void p_init_aesni(const uint8_t* key) noexcept;
void p_encrypt_aesni(const void* in, void* out) const noexcept;
void p_decrypt_aesni(const void* in, void* out) const noexcept;
void p_init_aesni(const uint8_t *key) noexcept;
void p_encrypt_aesni(const void *in, void *out) const noexcept;
void p_decrypt_aesni(const void *in, void *out) const noexcept;
#endif
#ifdef ZT_AES_NEON
void p_init_armneon_crypto(const uint8_t* key) noexcept;
void p_encrypt_armneon_crypto(const void* in, void* out) const noexcept;
void p_decrypt_armneon_crypto(const void* in, void* out) const noexcept;
void p_init_armneon_crypto(const uint8_t *key) noexcept;
void p_encrypt_armneon_crypto(const void *in, void *out) const noexcept;
void p_decrypt_armneon_crypto(const void *in, void *out) const noexcept;
#endif
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,15 +4,15 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "AES.hpp"
#include "Constants.hpp"
#include "AES.hpp"
#ifdef ZT_AES_AESNI
@ -29,8 +29,7 @@ const __m128i s_sseSwapBytes = _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul")))
#endif
__m128i
p_gmacPCLMUL128(const __m128i h, __m128i y) noexcept
__m128i p_gmacPCLMUL128(const __m128i h, __m128i y) noexcept
{
y = _mm_shuffle_epi8(y, s_sseSwapBytes);
__m128i t1 = _mm_clmulepi64_si128(h, y, 0x00);
@ -56,7 +55,7 @@ p_gmacPCLMUL128(const __m128i h, __m128i y) noexcept
* The performance gain can be significant but regular SSE is already so
* fast it's highly unlikely to be a rate limiting factor except on massive
* servers and network infrastructure stuff. */
#if ! defined(__WINDOWS__) && ((__GNUC__ >= 8) || (__clang_major__ >= 7))
#if !defined(__WINDOWS__) && ((__GNUC__ >= 8) || (__clang_major__ >= 7))
#define ZT_AES_VAES512 1
@ -81,8 +80,12 @@ void p_aesCtrInnerVAES512(unsigned int &len, const uint64_t c0, uint64_t &c1, co
const __m512i kk13 = _mm512_broadcast_i32x4(k[13]);
const __m512i kk14 = _mm512_broadcast_i32x4(k[14]);
do {
__m512i p0 = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(in));
__m512i d0 = _mm512_set_epi64((long long)Utils::hton(c1 + 3ULL), (long long)c0, (long long)Utils::hton(c1 + 2ULL), (long long)c0, (long long)Utils::hton(c1 + 1ULL), (long long)c0, (long long)Utils::hton(c1), (long long)c0);
__m512i p0 = _mm512_loadu_si512(reinterpret_cast<const __m512i *>(in));
__m512i d0 = _mm512_set_epi64(
(long long)Utils::hton(c1 + 3ULL), (long long)c0,
(long long)Utils::hton(c1 + 2ULL), (long long)c0,
(long long)Utils::hton(c1 + 1ULL), (long long)c0,
(long long)Utils::hton(c1), (long long)c0);
c1 += 4;
in += 64;
len -= 64;
@ -101,7 +104,7 @@ void p_aesCtrInnerVAES512(unsigned int &len, const uint64_t c0, uint64_t &c1, co
d0 = _mm512_aesenc_epi128(d0, kk12);
d0 = _mm512_aesenc_epi128(d0, kk13);
d0 = _mm512_aesenclast_epi128(d0, kk14);
_mm512_storeu_si512(reinterpret_cast<__m512i*>(out), _mm512_xor_si512(p0, d0));
_mm512_storeu_si512(reinterpret_cast<__m512i *>(out), _mm512_xor_si512(p0, d0));
out += 64;
} while (likely(len >= 64));
}
@ -129,10 +132,14 @@ void p_aesCtrInnerVAES256(unsigned int &len, const uint64_t c0, uint64_t &c1, co
const __m256i kk13 = _mm256_broadcastsi128_si256(k[13]);
const __m256i kk14 = _mm256_broadcastsi128_si256(k[14]);
do {
__m256i p0 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(in));
__m256i p1 = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(in + 32));
__m256i d0 = _mm256_set_epi64x((long long)Utils::hton(c1 + 1ULL), (long long)c0, (long long)Utils::hton(c1), (long long)c0);
__m256i d1 = _mm256_set_epi64x((long long)Utils::hton(c1 + 3ULL), (long long)c0, (long long)Utils::hton(c1 + 2ULL), (long long)c0);
__m256i p0 = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(in));
__m256i p1 = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(in + 32));
__m256i d0 = _mm256_set_epi64x(
(long long)Utils::hton(c1 + 1ULL), (long long)c0,
(long long)Utils::hton(c1), (long long)c0);
__m256i d1 = _mm256_set_epi64x(
(long long)Utils::hton(c1 + 3ULL), (long long)c0,
(long long)Utils::hton(c1 + 2ULL), (long long)c0);
c1 += 4;
in += 64;
len -= 64;
@ -166,19 +173,18 @@ void p_aesCtrInnerVAES256(unsigned int &len, const uint64_t c0, uint64_t &c1, co
d1 = _mm256_aesenc_epi128(d1, kk13);
d0 = _mm256_aesenclast_epi128(d0, kk14);
d1 = _mm256_aesenclast_epi128(d1, kk14);
_mm256_storeu_si256(reinterpret_cast<__m256i*>(out), _mm256_xor_si256(d0, p0));
_mm256_storeu_si256(reinterpret_cast<__m256i*>(out + 32), _mm256_xor_si256(d1, p1));
_mm256_storeu_si256(reinterpret_cast<__m256i *>(out), _mm256_xor_si256(d0, p0));
_mm256_storeu_si256(reinterpret_cast<__m256i *>(out + 32), _mm256_xor_si256(d1, p1));
out += 64;
} while (likely(len >= 64));
}
#endif // does compiler support AVX2 and AVX512 AES intrinsics?
#endif // does compiler support AVX2 and AVX512 AES intrinsics?
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
__m128i
p_init256_1_aesni(__m128i a, __m128i b) noexcept
__m128i p_init256_1_aesni(__m128i a, __m128i b) noexcept
{
__m128i x, y;
b = _mm_shuffle_epi32(b, 0xff);
@ -195,8 +201,7 @@ p_init256_1_aesni(__m128i a, __m128i b) noexcept
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
__m128i
p_init256_2_aesni(__m128i a, __m128i b) noexcept
__m128i p_init256_2_aesni(__m128i a, __m128i b) noexcept
{
__m128i x, y, z;
y = _mm_aeskeygenassist_si128(a, 0x00);
@ -211,25 +216,25 @@ p_init256_2_aesni(__m128i a, __m128i b) noexcept
return x;
}
} // anonymous namespace
} // anonymous namespace
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul")))
#endif
void AES::GMAC::p_aesNIUpdate(const uint8_t *in, unsigned int len) noexcept
{
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i*>(_y));
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i *>(_y));
// Handle anything left over from a previous run that wasn't a multiple of 16 bytes.
if (_rp) {
for (;;) {
if (! len) {
if (!len) {
return;
}
--len;
_r[_rp++] = *(in++);
if (_rp == 16) {
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i*>(_r))));
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i *>(_r))));
break;
}
}
@ -245,21 +250,17 @@ void AES::GMAC::p_aesNIUpdate(const uint8_t *in, unsigned int len) noexcept
const __m128i hh2 = _aes.p_k.ni.h2[1];
const __m128i hhh2 = _aes.p_k.ni.h2[2];
const __m128i hhhh2 = _aes.p_k.ni.h2[3];
const uint8_t* const end64 = in + (len & ~((unsigned int)63));
const uint8_t *const end64 = in + (len & ~((unsigned int)63));
len &= 63U;
do {
__m128i d1 = _mm_shuffle_epi8(_mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i*>(in))), sb);
__m128i d2 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 16)), sb);
__m128i d3 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 32)), sb);
__m128i d4 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 48)), sb);
__m128i d1 = _mm_shuffle_epi8(_mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))), sb);
__m128i d2 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 16)), sb);
__m128i d3 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 32)), sb);
__m128i d4 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 48)), sb);
in += 64;
__m128i a = _mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh, d1, 0x00), _mm_clmulepi64_si128(hhh, d2, 0x00)), _mm_xor_si128(_mm_clmulepi64_si128(hh, d3, 0x00), _mm_clmulepi64_si128(h, d4, 0x00)));
__m128i b = _mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh, d1, 0x11), _mm_clmulepi64_si128(hhh, d2, 0x11)), _mm_xor_si128(_mm_clmulepi64_si128(hh, d3, 0x11), _mm_clmulepi64_si128(h, d4, 0x11)));
__m128i c = _mm_xor_si128(
_mm_xor_si128(
_mm_xor_si128(_mm_clmulepi64_si128(hhhh2, _mm_xor_si128(_mm_shuffle_epi32(d1, 78), d1), 0x00), _mm_clmulepi64_si128(hhh2, _mm_xor_si128(_mm_shuffle_epi32(d2, 78), d2), 0x00)),
_mm_xor_si128(_mm_clmulepi64_si128(hh2, _mm_xor_si128(_mm_shuffle_epi32(d3, 78), d3), 0x00), _mm_clmulepi64_si128(h2, _mm_xor_si128(_mm_shuffle_epi32(d4, 78), d4), 0x00))),
_mm_xor_si128(a, b));
__m128i c = _mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh2, _mm_xor_si128(_mm_shuffle_epi32(d1, 78), d1), 0x00), _mm_clmulepi64_si128(hhh2, _mm_xor_si128(_mm_shuffle_epi32(d2, 78), d2), 0x00)), _mm_xor_si128(_mm_clmulepi64_si128(hh2, _mm_xor_si128(_mm_shuffle_epi32(d3, 78), d3), 0x00), _mm_clmulepi64_si128(h2, _mm_xor_si128(_mm_shuffle_epi32(d4, 78), d4), 0x00))), _mm_xor_si128(a, b));
a = _mm_xor_si128(_mm_slli_si128(c, 8), a);
b = _mm_xor_si128(_mm_srli_si128(c, 8), b);
c = _mm_srli_epi32(a, 31);
@ -273,18 +274,18 @@ void AES::GMAC::p_aesNIUpdate(const uint8_t *in, unsigned int len) noexcept
}
while (len >= 16) {
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i*>(in))));
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))));
in += 16;
len -= 16;
}
_mm_storeu_si128(reinterpret_cast<__m128i*>(_y), y);
_mm_storeu_si128(reinterpret_cast<__m128i *>(_y), y);
// Any overflow is cached for a later run or finish().
for (unsigned int i = 0; i < len; ++i) {
_r[i] = in[i];
}
_rp = len; // len is always less than 16 here
_rp = len; // len is always less than 16 here
}
#ifdef __GNUC__
@ -292,23 +293,23 @@ __attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul,aes")))
#endif
void AES::GMAC::p_aesNIFinish(uint8_t tag[16]) noexcept
{
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i*>(_y));
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i *>(_y));
// Handle any remaining bytes, padding the last block with zeroes.
if (_rp) {
while (_rp < 16) {
_r[_rp++] = 0;
}
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i*>(_r))));
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i *>(_r))));
}
// Interleave encryption of IV with the final GHASH of y XOR (length * 8).
// Then XOR these together to get the final tag.
const __m128i* const k = _aes.p_k.ni.k;
const __m128i *const k = _aes.p_k.ni.k;
const __m128i h = _aes.p_k.ni.h[0];
y = _mm_xor_si128(y, _mm_set_epi64x(0LL, (long long)Utils::hton((uint64_t)_len << 3U)));
y = _mm_shuffle_epi8(y, s_sseSwapBytes);
__m128i encIV = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i*>(_iv)), k[0]);
__m128i encIV = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(_iv)), k[0]);
__m128i t1 = _mm_clmulepi64_si128(h, y, 0x00);
__m128i t2 = _mm_clmulepi64_si128(h, y, 0x01);
__m128i t3 = _mm_clmulepi64_si128(h, y, 0x10);
@ -358,7 +359,7 @@ void AES::GMAC::p_aesNIFinish(uint8_t tag[16]) noexcept
t4 = _mm_xor_si128(t4, t3);
encIV = _mm_aesenclast_si128(encIV, k[14]);
t4 = _mm_xor_si128(t4, t5);
_mm_storeu_si128(reinterpret_cast<__m128i*>(tag), _mm_xor_si128(_mm_shuffle_epi8(t4, s_sseSwapBytes), encIV));
_mm_storeu_si128(reinterpret_cast<__m128i *>(tag), _mm_xor_si128(_mm_shuffle_epi8(t4, s_sseSwapBytes), encIV));
}
#ifdef __GNUC__
@ -369,7 +370,7 @@ void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) n
const __m128i dd = _mm_set_epi64x(0, (long long)_ctr[0]);
uint64_t c1 = Utils::ntoh(_ctr[1]);
const __m128i* const k = _aes.p_k.ni.k;
const __m128i *const k = _aes.p_k.ni.k;
const __m128i k0 = k[0];
const __m128i k1 = k[1];
const __m128i k2 = k[2];
@ -390,14 +391,14 @@ void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) n
unsigned int totalLen = _len;
if ((totalLen & 15U)) {
for (;;) {
if (unlikely(! len)) {
if (unlikely(!len)) {
_ctr[1] = Utils::hton(c1);
_len = totalLen;
return;
}
--len;
out[totalLen++] = *(in++);
if (! (totalLen & 15U)) {
if (!(totalLen & 15U)) {
__m128i d0 = _mm_insert_epi64(dd, (long long)Utils::hton(c1++), 1);
d0 = _mm_xor_si128(d0, k0);
d0 = _mm_aesenc_si128(d0, k1);
@ -410,7 +411,7 @@ void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) n
d0 = _mm_aesenc_si128(d0, k8);
d0 = _mm_aesenc_si128(d0, k9);
d0 = _mm_aesenc_si128(d0, k10);
__m128i* const outblk = reinterpret_cast<__m128i*>(out + (totalLen - 16));
__m128i *const outblk = reinterpret_cast<__m128i *>(out + (totalLen - 16));
d0 = _mm_aesenc_si128(d0, k11);
const __m128i p0 = _mm_loadu_si128(outblk);
d0 = _mm_aesenc_si128(d0, k12);
@ -426,26 +427,26 @@ void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) n
_len = totalLen + len;
if (likely(len >= 64)) {
#if defined(ZT_AES_VAES512) && defined(ZT_AES_VAES256)
if (Utils::CPUID.vaes && (len >= 256)) {
if (Utils::CPUID.avx512f) {
p_aesCtrInnerVAES512(len, _ctr[0], c1, in, out, k);
}
else {
} else {
p_aesCtrInnerVAES256(len, _ctr[0], c1, in, out, k);
}
goto skip_conventional_aesni_64;
}
#endif
#if ! defined(ZT_AES_VAES512) && defined(ZT_AES_VAES256)
#if !defined(ZT_AES_VAES512) && defined(ZT_AES_VAES256)
if (Utils::CPUID.vaes && (len >= 256)) {
p_aesCtrInnerVAES256(len, _ctr[0], c1, in, out, k);
goto skip_conventional_aesni_64;
}
#endif
const uint8_t* const eof64 = in + (len & ~((unsigned int)63));
const uint8_t *const eof64 = in + (len & ~((unsigned int)63));
len &= 63;
__m128i d0, d1, d2, d3;
do {
@ -514,20 +515,21 @@ void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) n
d1 = _mm_aesenc_si128(d1, k13);
d2 = _mm_aesenc_si128(d2, k13);
d3 = _mm_aesenc_si128(d3, k13);
d0 = _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i*>(in)));
d1 = _mm_xor_si128(_mm_aesenclast_si128(d1, k14), _mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 16)));
d2 = _mm_xor_si128(_mm_aesenclast_si128(d2, k14), _mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 32)));
d3 = _mm_xor_si128(_mm_aesenclast_si128(d3, k14), _mm_loadu_si128(reinterpret_cast<const __m128i*>(in + 48)));
d0 = _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in)));
d1 = _mm_xor_si128(_mm_aesenclast_si128(d1, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 16)));
d2 = _mm_xor_si128(_mm_aesenclast_si128(d2, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 32)));
d3 = _mm_xor_si128(_mm_aesenclast_si128(d3, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 48)));
in += 64;
_mm_storeu_si128(reinterpret_cast<__m128i*>(out), d0);
_mm_storeu_si128(reinterpret_cast<__m128i*>(out + 16), d1);
_mm_storeu_si128(reinterpret_cast<__m128i*>(out + 32), d2);
_mm_storeu_si128(reinterpret_cast<__m128i*>(out + 48), d3);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out), d0);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 16), d1);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 32), d2);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 48), d3);
out += 64;
} while (likely(in != eof64));
}
skip_conventional_aesni_64:
skip_conventional_aesni_64:
while (len >= 16) {
__m128i d0 = _mm_insert_epi64(dd, (long long)Utils::hton(c1++), 1);
d0 = _mm_xor_si128(d0, k0);
@ -544,7 +546,7 @@ skip_conventional_aesni_64:
d0 = _mm_aesenc_si128(d0, k11);
d0 = _mm_aesenc_si128(d0, k12);
d0 = _mm_aesenc_si128(d0, k13);
_mm_storeu_si128(reinterpret_cast<__m128i*>(out), _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i*>(in))));
_mm_storeu_si128(reinterpret_cast<__m128i *>(out), _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))));
in += 16;
len -= 16;
out += 16;
@ -566,8 +568,8 @@ __attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
void AES::p_init_aesni(const uint8_t *key) noexcept
{
__m128i t1, t2, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13;
p_k.ni.k[0] = t1 = _mm_loadu_si128((const __m128i*)key);
p_k.ni.k[1] = k1 = t2 = _mm_loadu_si128((const __m128i*)(key + 16));
p_k.ni.k[0] = t1 = _mm_loadu_si128((const __m128i *)key);
p_k.ni.k[1] = k1 = t2 = _mm_loadu_si128((const __m128i *)(key + 16));
p_k.ni.k[2] = k2 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x01));
p_k.ni.k[3] = k3 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[4] = k4 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x02));
@ -595,7 +597,7 @@ void AES::p_init_aesni(const uint8_t *key) noexcept
p_k.ni.k[26] = _mm_aesimc_si128(k2);
p_k.ni.k[27] = _mm_aesimc_si128(k1);
__m128i h = p_k.ni.k[0]; // _mm_xor_si128(_mm_setzero_si128(),_k.ni.k[0]);
__m128i h = p_k.ni.k[0]; // _mm_xor_si128(_mm_setzero_si128(),_k.ni.k[0]);
h = _mm_aesenc_si128(h, k1);
h = _mm_aesenc_si128(h, k2);
h = _mm_aesenc_si128(h, k3);
@ -629,7 +631,7 @@ __attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
void AES::p_encrypt_aesni(const void *const in, void *const out) const noexcept
{
__m128i tmp = _mm_loadu_si128((const __m128i*)in);
__m128i tmp = _mm_loadu_si128((const __m128i *)in);
tmp = _mm_xor_si128(tmp, p_k.ni.k[0]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[1]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[2]);
@ -644,7 +646,7 @@ void AES::p_encrypt_aesni(const void *const in, void *const out) const noexcept
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[11]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[12]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[13]);
_mm_storeu_si128((__m128i*)out, _mm_aesenclast_si128(tmp, p_k.ni.k[14]));
_mm_storeu_si128((__m128i *)out, _mm_aesenclast_si128(tmp, p_k.ni.k[14]));
}
#ifdef __GNUC__
@ -652,7 +654,7 @@ __attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
void AES::p_decrypt_aesni(const void *in, void *out) const noexcept
{
__m128i tmp = _mm_loadu_si128((const __m128i*)in);
__m128i tmp = _mm_loadu_si128((const __m128i *)in);
tmp = _mm_xor_si128(tmp, p_k.ni.k[14]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[15]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[16]);
@ -667,9 +669,9 @@ void AES::p_decrypt_aesni(const void *in, void *out) const noexcept
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[25]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[26]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[27]);
_mm_storeu_si128((__m128i*)out, _mm_aesdeclast_si128(tmp, p_k.ni.k[0]));
_mm_storeu_si128((__m128i *)out, _mm_aesdeclast_si128(tmp, p_k.ni.k[0]));
}
} // namespace ZeroTier
} // namespace ZeroTier
#endif // ZT_AES_AESNI
#endif // ZT_AES_AESNI

View file

@ -4,15 +4,15 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "AES.hpp"
#include "Constants.hpp"
#include "AES.hpp"
#ifdef ZT_AES_NEON
@ -29,34 +29,34 @@ ZT_INLINE uint8x16_t s_clmul_armneon_crypto(uint8x16_t h, uint8x16_t y, const ui
y = vrbitq_u8(y);
const uint8x16_t p = vreinterpretq_u8_u64(vdupq_n_u64(0x0000000000000087));
t0 = vextq_u8(y, y, 8);
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w"(r0) : "w"(h), "w"(y));
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" : "=w"(r1) : "w"(h), "w"(y));
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w"(t1) : "w"(h), "w"(t0));
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" : "=w"(t0) : "w"(h), "w"(t0));
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w" (r0) : "w" (h), "w" (y));
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" :"=w" (r1) : "w" (h), "w" (y));
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w" (t1) : "w" (h), "w" (t0));
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" :"=w" (t0) : "w" (h), "w" (t0));
t0 = veorq_u8(t0, t1);
t1 = vextq_u8(z, t0, 8);
r0 = veorq_u8(r0, t1);
t1 = vextq_u8(t0, z, 8);
r1 = veorq_u8(r1, t1);
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" : "=w"(t0) : "w"(r1), "w"(p));
__asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" :"=w" (t0) : "w" (r1), "w" (p));
t1 = vextq_u8(t0, z, 8);
r1 = veorq_u8(r1, t1);
t1 = vextq_u8(z, t0, 8);
r0 = veorq_u8(r0, t1);
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w"(t0) : "w"(r1), "w"(p));
__asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" : "=w" (t0) : "w" (r1), "w" (p));
return vrbitq_u8(veorq_u8(r0, t0));
}
} // anonymous namespace
} // anonymous namespace
void AES::GMAC::p_armUpdate(const uint8_t* in, unsigned int len) noexcept
void AES::GMAC::p_armUpdate(const uint8_t *in, unsigned int len) noexcept
{
uint8x16_t y = vld1q_u8(reinterpret_cast<const uint8_t*>(_y));
uint8x16_t y = vld1q_u8(reinterpret_cast<const uint8_t *>(_y));
const uint8x16_t h = _aes.p_k.neon.h;
if (_rp) {
for (;;) {
if (! len) {
for(;;) {
if (!len) {
return;
}
--len;
@ -74,18 +74,18 @@ void AES::GMAC::p_armUpdate(const uint8_t* in, unsigned int len) noexcept
len -= 16;
}
vst1q_u8(reinterpret_cast<uint8_t*>(_y), y);
vst1q_u8(reinterpret_cast<uint8_t *>(_y), y);
for (unsigned int i = 0; i < len; ++i) {
_r[i] = in[i];
}
_rp = len; // len is always less than 16 here
_rp = len; // len is always less than 16 here
}
void AES::GMAC::p_armFinish(uint8_t tag[16]) noexcept
{
uint64_t tmp[2];
uint8x16_t y = vld1q_u8(reinterpret_cast<const uint8_t*>(_y));
uint8x16_t y = vld1q_u8(reinterpret_cast<const uint8_t *>(_y));
const uint8x16_t h = _aes.p_k.neon.h;
if (_rp) {
@ -97,25 +97,25 @@ void AES::GMAC::p_armFinish(uint8_t tag[16]) noexcept
tmp[0] = Utils::hton((uint64_t)_len << 3U);
tmp[1] = 0;
y = s_clmul_armneon_crypto(h, y, reinterpret_cast<const uint8_t*>(tmp));
y = s_clmul_armneon_crypto(h, y, reinterpret_cast<const uint8_t *>(tmp));
Utils::copy<12>(tmp, _iv);
Utils::copy< 12 >(tmp, _iv);
#if __BYTE_ORDER == __BIG_ENDIAN
reinterpret_cast<uint32_t*>(tmp)[3] = 0x00000001;
reinterpret_cast<uint32_t *>(tmp)[3] = 0x00000001;
#else
reinterpret_cast<uint32_t*>(tmp)[3] = 0x01000000;
reinterpret_cast<uint32_t *>(tmp)[3] = 0x01000000;
#endif
_aes.encrypt(tmp, tmp);
uint8x16_t yy = y;
Utils::storeMachineEndian<uint64_t>(tag, tmp[0] ^ reinterpret_cast<const uint64_t*>(&yy)[0]);
Utils::storeMachineEndian<uint64_t>(tag + 8, tmp[1] ^ reinterpret_cast<const uint64_t*>(&yy)[1]);
Utils::storeMachineEndian< uint64_t >(tag, tmp[0] ^ reinterpret_cast<const uint64_t *>(&yy)[0]);
Utils::storeMachineEndian< uint64_t >(tag + 8, tmp[1] ^ reinterpret_cast<const uint64_t *>(&yy)[1]);
}
void AES::CTR::p_armCrypt(const uint8_t* in, uint8_t* out, unsigned int len) noexcept
void AES::CTR::p_armCrypt(const uint8_t *in, uint8_t *out, unsigned int len) noexcept
{
uint8x16_t dd = vrev32q_u8(vld1q_u8(reinterpret_cast<uint8_t*>(_ctr)));
const uint32x4_t one = { 0, 0, 0, 1 };
uint8x16_t dd = vrev32q_u8(vld1q_u8(reinterpret_cast<uint8_t *>(_ctr)));
const uint32x4_t one = {0,0,0,1};
uint8x16_t k0 = _aes.p_k.neon.ek[0];
uint8x16_t k1 = _aes.p_k.neon.ek[1];
@ -136,15 +136,15 @@ void AES::CTR::p_armCrypt(const uint8_t* in, uint8_t* out, unsigned int len) noe
unsigned int totalLen = _len;
if ((totalLen & 15U) != 0) {
for (;;) {
if (unlikely(! len)) {
vst1q_u8(reinterpret_cast<uint8_t*>(_ctr), vrev32q_u8(dd));
if (unlikely(!len)) {
vst1q_u8(reinterpret_cast<uint8_t *>(_ctr), vrev32q_u8(dd));
_len = totalLen;
return;
}
--len;
out[totalLen++] = *(in++);
if ((totalLen & 15U) == 0) {
uint8_t* const otmp = out + (totalLen - 16);
uint8_t *const otmp = out + (totalLen - 16);
uint8x16_t d0 = vrev32q_u8(dd);
uint8x16_t pt = vld1q_u8(otmp);
d0 = vaesmcq_u8(vaeseq_u8(d0, k0));
@ -298,52 +298,46 @@ void AES::CTR::p_armCrypt(const uint8_t* in, uint8_t* out, unsigned int len) noe
out[i] = in[i];
}
vst1q_u8(reinterpret_cast<uint8_t*>(_ctr), vrev32q_u8(dd));
vst1q_u8(reinterpret_cast<uint8_t *>(_ctr), vrev32q_u8(dd));
}
#define ZT_INIT_ARMNEON_CRYPTO_SUBWORD(w) ((uint32_t)s_sbox[w & 0xffU] + ((uint32_t)s_sbox[(w >> 8U) & 0xffU] << 8U) + ((uint32_t)s_sbox[(w >> 16U) & 0xffU] << 16U) + ((uint32_t)s_sbox[(w >> 24U) & 0xffU] << 24U))
#define ZT_INIT_ARMNEON_CRYPTO_ROTWORD(w) (((w) << 8U) | ((w) >> 24U))
#define ZT_INIT_ARMNEON_CRYPTO_NK 8
#define ZT_INIT_ARMNEON_CRYPTO_NB 4
#define ZT_INIT_ARMNEON_CRYPTO_NR 14
#define ZT_INIT_ARMNEON_CRYPTO_NK 8
#define ZT_INIT_ARMNEON_CRYPTO_NB 4
#define ZT_INIT_ARMNEON_CRYPTO_NR 14
void AES::p_init_armneon_crypto(const uint8_t* key) noexcept
void AES::p_init_armneon_crypto(const uint8_t *key) noexcept
{
static const uint8_t s_sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
static const uint8_t s_sbox[256] = {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c,
0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea,
0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
uint64_t h[2];
uint32_t* const w = reinterpret_cast<uint32_t*>(p_k.neon.ek);
uint32_t *const w = reinterpret_cast<uint32_t *>(p_k.neon.ek);
for (unsigned int i = 0; i < ZT_INIT_ARMNEON_CRYPTO_NK; ++i) {
for (unsigned int i=0;i<ZT_INIT_ARMNEON_CRYPTO_NK;++i) {
const unsigned int j = i * 4;
w[i] = ((uint32_t)key[j] << 24U) | ((uint32_t)key[j + 1] << 16U) | ((uint32_t)key[j + 2] << 8U) | (uint32_t)key[j + 3];
}
for (unsigned int i = ZT_INIT_ARMNEON_CRYPTO_NK; i < (ZT_INIT_ARMNEON_CRYPTO_NB * (ZT_INIT_ARMNEON_CRYPTO_NR + 1)); ++i) {
for (unsigned int i=ZT_INIT_ARMNEON_CRYPTO_NK;i<(ZT_INIT_ARMNEON_CRYPTO_NB * (ZT_INIT_ARMNEON_CRYPTO_NR + 1));++i) {
uint32_t t = w[i - 1];
const unsigned int imod = i & (ZT_INIT_ARMNEON_CRYPTO_NK - 1);
if (imod == 0) {
t = ZT_INIT_ARMNEON_CRYPTO_SUBWORD(ZT_INIT_ARMNEON_CRYPTO_ROTWORD(t)) ^ rcon[(i - 1) / ZT_INIT_ARMNEON_CRYPTO_NK];
}
else if (imod == 4) {
} else if (imod == 4) {
t = ZT_INIT_ARMNEON_CRYPTO_SUBWORD(t);
}
w[i] = w[i - ZT_INIT_ARMNEON_CRYPTO_NK] ^ t;
}
for (unsigned int i = 0; i < (ZT_INIT_ARMNEON_CRYPTO_NB * (ZT_INIT_ARMNEON_CRYPTO_NR + 1)); ++i) {
for (unsigned int i=0;i<(ZT_INIT_ARMNEON_CRYPTO_NB * (ZT_INIT_ARMNEON_CRYPTO_NR + 1));++i) {
w[i] = Utils::hton(w[i]);
}
p_k.neon.dk[0] = p_k.neon.ek[14];
for (int i = 1; i < 14; ++i) {
for (int i=1;i<14;++i) {
p_k.neon.dk[i] = vaesimcq_u8(p_k.neon.ek[14 - i]);
}
p_k.neon.dk[14] = p_k.neon.ek[0];
@ -355,9 +349,9 @@ void AES::p_init_armneon_crypto(const uint8_t* key) noexcept
p_k.sw.h[1] = Utils::ntoh(h[1]);
}
void AES::p_encrypt_armneon_crypto(const void* const in, void* const out) const noexcept
void AES::p_encrypt_armneon_crypto(const void *const in, void *const out) const noexcept
{
uint8x16_t tmp = vld1q_u8(reinterpret_cast<const uint8_t*>(in));
uint8x16_t tmp = vld1q_u8(reinterpret_cast<const uint8_t *>(in));
tmp = vaesmcq_u8(vaeseq_u8(tmp, p_k.neon.ek[0]));
tmp = vaesmcq_u8(vaeseq_u8(tmp, p_k.neon.ek[1]));
tmp = vaesmcq_u8(vaeseq_u8(tmp, p_k.neon.ek[2]));
@ -372,12 +366,12 @@ void AES::p_encrypt_armneon_crypto(const void* const in, void* const out) const
tmp = vaesmcq_u8(vaeseq_u8(tmp, p_k.neon.ek[11]));
tmp = vaesmcq_u8(vaeseq_u8(tmp, p_k.neon.ek[12]));
tmp = veorq_u8(vaeseq_u8(tmp, p_k.neon.ek[13]), p_k.neon.ek[14]);
vst1q_u8(reinterpret_cast<uint8_t*>(out), tmp);
vst1q_u8(reinterpret_cast<uint8_t *>(out), tmp);
}
void AES::p_decrypt_armneon_crypto(const void* const in, void* const out) const noexcept
void AES::p_decrypt_armneon_crypto(const void *const in, void *const out) const noexcept
{
uint8x16_t tmp = vld1q_u8(reinterpret_cast<const uint8_t*>(in));
uint8x16_t tmp = vld1q_u8(reinterpret_cast<const uint8_t *>(in));
tmp = vaesimcq_u8(vaesdq_u8(tmp, p_k.neon.dk[0]));
tmp = vaesimcq_u8(vaesdq_u8(tmp, p_k.neon.dk[1]));
tmp = vaesimcq_u8(vaesdq_u8(tmp, p_k.neon.dk[2]));
@ -392,9 +386,9 @@ void AES::p_decrypt_armneon_crypto(const void* const in, void* const out) const
tmp = vaesimcq_u8(vaesdq_u8(tmp, p_k.neon.dk[11]));
tmp = vaesimcq_u8(vaesdq_u8(tmp, p_k.neon.dk[12]));
tmp = veorq_u8(vaesdq_u8(tmp, p_k.neon.dk[13]), p_k.neon.dk[14]);
vst1q_u8(reinterpret_cast<uint8_t*>(out), tmp);
vst1q_u8(reinterpret_cast<uint8_t *>(out), tmp);
}
} // namespace ZeroTier
} // namespace ZeroTier
#endif // ZT_AES_NEON
#endif // ZT_AES_NEON

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,64 +14,49 @@
#ifndef ZT_ADDRESS_HPP
#define ZT_ADDRESS_HPP
#include "Buffer.hpp"
#include "Constants.hpp"
#include "Utils.hpp"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <string>
#include "Constants.hpp"
#include "Utils.hpp"
#include "Buffer.hpp"
namespace ZeroTier {
/**
* A ZeroTier address
*/
class Address {
public:
Address() : _a(0)
{
}
Address(const Address& a) : _a(a._a)
{
}
Address(uint64_t a) : _a(a & 0xffffffffffULL)
{
}
class Address
{
public:
Address() : _a(0) {}
Address(const Address &a) : _a(a._a) {}
Address(uint64_t a) : _a(a & 0xffffffffffULL) {}
/**
* @param bits Raw address -- 5 bytes, big-endian byte order
* @param len Length of array
*/
Address(const void* bits, unsigned int len)
{
setTo(bits, len);
}
Address(const void *bits,unsigned int len) { setTo(bits,len); }
inline Address& operator=(const Address& a)
{
_a = a._a;
return *this;
}
inline Address& operator=(const uint64_t a)
{
_a = (a & 0xffffffffffULL);
return *this;
}
inline Address &operator=(const Address &a) { _a = a._a; return *this; }
inline Address &operator=(const uint64_t a) { _a = (a & 0xffffffffffULL); return *this; }
/**
* @param bits Raw address -- 5 bytes, big-endian byte order
* @param len Length of array
*/
inline void setTo(const void* bits, const unsigned int len)
inline void setTo(const void *bits,const unsigned int len)
{
if (len < ZT_ADDRESS_LENGTH) {
_a = 0;
return;
}
const unsigned char* b = (const unsigned char*)bits;
const unsigned char *b = (const unsigned char *)bits;
uint64_t a = ((uint64_t)*b++) << 32;
a |= ((uint64_t)*b++) << 24;
a |= ((uint64_t)*b++) << 16;
@ -84,12 +69,12 @@ class Address {
* @param bits Buffer to hold 5-byte address in big-endian byte order
* @param len Length of array
*/
inline void copyTo(void* const bits, const unsigned int len) const
inline void copyTo(void *const bits,const unsigned int len) const
{
if (len < ZT_ADDRESS_LENGTH) {
return;
}
unsigned char* b = (unsigned char*)bits;
unsigned char *b = (unsigned char *)bits;
*(b++) = (unsigned char)((_a >> 32) & 0xff);
*(b++) = (unsigned char)((_a >> 24) & 0xff);
*(b++) = (unsigned char)((_a >> 16) & 0xff);
@ -102,9 +87,10 @@ class Address {
*
* @param b Buffer to append to
*/
template <unsigned int C> inline void appendTo(Buffer<C>& b) const
template<unsigned int C>
inline void appendTo(Buffer<C> &b) const
{
unsigned char* p = (unsigned char*)b.appendField(ZT_ADDRESS_LENGTH);
unsigned char *p = (unsigned char *)b.appendField(ZT_ADDRESS_LENGTH);
*(p++) = (unsigned char)((_a >> 32) & 0xff);
*(p++) = (unsigned char)((_a >> 24) & 0xff);
*(p++) = (unsigned char)((_a >> 16) & 0xff);
@ -115,34 +101,22 @@ class Address {
/**
* @return Integer containing address (0 to 2^40)
*/
inline uint64_t toInt() const
{
return _a;
}
inline uint64_t toInt() const { return _a; }
/**
* @return Hash code for use with Hashtable
*/
inline unsigned long hashCode() const
{
return (unsigned long)_a;
}
inline unsigned long hashCode() const { return (unsigned long)_a; }
/**
* @return Hexadecimal string
*/
inline char* toString(char buf[11]) const
{
return Utils::hex10(_a, buf);
}
inline char *toString(char buf[11]) const { return Utils::hex10(_a,buf); }
/**
* @return True if this address is not zero
*/
inline operator bool() const
{
return (_a != 0);
}
inline operator bool() const { return (_a != 0); }
/**
* Check if this address is reserved
@ -153,79 +127,34 @@ class Address {
*
* @return True if address is reserved and may not be used
*/
inline bool isReserved() const
{
return ((! _a) || ((_a >> 32) == ZT_ADDRESS_RESERVED_PREFIX));
}
inline bool isReserved() const { return ((!_a)||((_a >> 32) == ZT_ADDRESS_RESERVED_PREFIX)); }
/**
* @param i Value from 0 to 4 (inclusive)
* @return Byte at said position (address interpreted in big-endian order)
*/
inline uint8_t operator[](unsigned int i) const
{
return (uint8_t)(_a >> (32 - (i * 8)));
}
inline uint8_t operator[](unsigned int i) const { return (uint8_t)(_a >> (32 - (i * 8))); }
inline void zero()
{
_a = 0;
}
inline void zero() { _a = 0; }
inline bool operator==(const uint64_t& a) const
{
return (_a == (a & 0xffffffffffULL));
}
inline bool operator!=(const uint64_t& a) const
{
return (_a != (a & 0xffffffffffULL));
}
inline bool operator>(const uint64_t& a) const
{
return (_a > (a & 0xffffffffffULL));
}
inline bool operator<(const uint64_t& a) const
{
return (_a < (a & 0xffffffffffULL));
}
inline bool operator>=(const uint64_t& a) const
{
return (_a >= (a & 0xffffffffffULL));
}
inline bool operator<=(const uint64_t& a) const
{
return (_a <= (a & 0xffffffffffULL));
}
inline bool operator==(const uint64_t &a) const { return (_a == (a & 0xffffffffffULL)); }
inline bool operator!=(const uint64_t &a) const { return (_a != (a & 0xffffffffffULL)); }
inline bool operator>(const uint64_t &a) const { return (_a > (a & 0xffffffffffULL)); }
inline bool operator<(const uint64_t &a) const { return (_a < (a & 0xffffffffffULL)); }
inline bool operator>=(const uint64_t &a) const { return (_a >= (a & 0xffffffffffULL)); }
inline bool operator<=(const uint64_t &a) const { return (_a <= (a & 0xffffffffffULL)); }
inline bool operator==(const Address& a) const
{
return (_a == a._a);
}
inline bool operator!=(const Address& a) const
{
return (_a != a._a);
}
inline bool operator>(const Address& a) const
{
return (_a > a._a);
}
inline bool operator<(const Address& a) const
{
return (_a < a._a);
}
inline bool operator>=(const Address& a) const
{
return (_a >= a._a);
}
inline bool operator<=(const Address& a) const
{
return (_a <= a._a);
}
inline bool operator==(const Address &a) const { return (_a == a._a); }
inline bool operator!=(const Address &a) const { return (_a != a._a); }
inline bool operator>(const Address &a) const { return (_a > a._a); }
inline bool operator<(const Address &a) const { return (_a < a._a); }
inline bool operator>=(const Address &a) const { return (_a >= a._a); }
inline bool operator<=(const Address &a) const { return (_a <= a._a); }
private:
private:
uint64_t _a;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -25,17 +25,15 @@ namespace ZeroTier {
/**
* Simple atomic counter supporting increment and decrement
*/
class AtomicCounter {
public:
AtomicCounter()
{
_v = 0;
}
class AtomicCounter
{
public:
AtomicCounter() { _v = 0; }
inline int load() const
{
#ifdef __GNUC__
return __sync_or_and_fetch(const_cast<int*>(&_v), 0);
return __sync_or_and_fetch(const_cast<int *>(&_v),0);
#else
return _v.load();
#endif
@ -44,7 +42,7 @@ class AtomicCounter {
inline int operator++()
{
#ifdef __GNUC__
return __sync_add_and_fetch(&_v, 1);
return __sync_add_and_fetch(&_v,1);
#else
return ++_v;
#endif
@ -53,20 +51,15 @@ class AtomicCounter {
inline int operator--()
{
#ifdef __GNUC__
return __sync_sub_and_fetch(&_v, 1);
return __sync_sub_and_fetch(&_v,1);
#else
return --_v;
#endif
}
private:
AtomicCounter(const AtomicCounter&)
{
}
const AtomicCounter& operator=(const AtomicCounter&)
{
return *this;
}
private:
AtomicCounter(const AtomicCounter &) {}
const AtomicCounter &operator=(const AtomicCounter &) { return *this; }
#ifdef __GNUC__
int _v;
@ -75,6 +68,6 @@ class AtomicCounter {
#endif
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -15,10 +15,10 @@
#include "Switch.hpp"
#include <cinttypes> // for PRId64, etc. macros
#include <cmath>
#include <cstdio>
#include <string>
#include <cinttypes> // for PRId64, etc. macros
// FIXME: remove this suppression and actually fix warnings
#ifdef __GNUC__
@ -108,7 +108,7 @@ bool Bond::setAllMtuByTuple(uint16_t mtu, const std::string& ifStr, const std::s
std::map<int64_t, SharedPtr<Bond> >::iterator bondItr = _bonds.begin();
bool found = false;
while (bondItr != _bonds.end()) {
if (bondItr->second->setMtuByTuple(mtu, ifStr, ipStr)) {
if (bondItr->second->setMtuByTuple(mtu,ifStr,ipStr)) {
found = true;
}
++bondItr;
@ -154,13 +154,11 @@ SharedPtr<Bond> Bond::createBond(const RuntimeEnvironment* renv, const SharedPtr
bond = new Bond(renv, _bondPolicyTemplates[_defaultPolicyStr].ptr(), peer);
bond->debug("new default custom bond (based on %s)", bond->getPolicyStrByCode(bond->policy()).c_str());
}
}
else {
} else {
if (! _bondPolicyTemplates[_policyTemplateAssignments[identity]]) {
bond = new Bond(renv, _defaultPolicy, peer);
bond->debug("peer-specific bond, was specified as %s but the bond definition was not found, using default %s", _policyTemplateAssignments[identity].c_str(), getPolicyStrByCode(_defaultPolicy).c_str());
}
else {
} else {
bond = new Bond(renv, _bondPolicyTemplates[_policyTemplateAssignments[identity]].ptr(), peer);
bond->debug("new default bond");
}
@ -229,12 +227,10 @@ SharedPtr<Link> Bond::getLinkBySocket(const std::string& policyAlias, uint64_t l
SharedPtr<Link> s = new Link(ifnameStr, 0, 0, 0, true, ZT_BOND_SLAVE_MODE_PRIMARY, "");
_interfaceToLinkMap[policyAlias].insert(std::pair<std::string, SharedPtr<Link> >(ifnameStr, s));
return s;
}
else {
} else {
return SharedPtr<Link>();
}
}
else {
} else {
return search->second;
}
}
@ -344,7 +340,6 @@ void Bond::nominatePathToBond(const SharedPtr<Path>& path, int64_t now)
_paths[i].ipvPref = sl->ipvPref();
_paths[i].mode = sl->mode();
_paths[i].enabled = sl->enabled();
_paths[i].localPort = _phy->getLocalPort((PhySocket*)((uintptr_t)path->localSocket()));
_paths[i].onlyPathOnLink = ! bFoundCommonLink;
}
}
@ -373,7 +368,6 @@ SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
*/
if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && _paths[_abPathIdx].p) {
// fprintf(stderr, "trying to send via (_abPathIdx=%d) %s\n", _abPathIdx, pathToStr(_paths[_abPathIdx].p).c_str());
return _paths[_abPathIdx].p;
}
}
@ -403,8 +397,7 @@ SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
_rrPacketsSentOnCurrLink = 0;
if (_numBondedPaths == 1 || _rrIdx >= (ZT_MAX_PEER_NETWORK_PATHS - 1)) {
_rrIdx = 0;
}
else {
} else {
int _tempIdx = _rrIdx;
for (int searchCount = 0; searchCount < (_numBondedPaths - 1); searchCount++) {
_tempIdx = (_tempIdx == (_numBondedPaths - 1)) ? 0 : _tempIdx + 1;
@ -434,8 +427,7 @@ SharedPtr<Path> Bond::getAppropriatePath(int64_t now, int32_t flowId)
if (likely(it != _flows.end())) {
it->second->lastActivity = now;
return _paths[it->second->assignedPath].p;
}
else {
} else {
unsigned char entropy;
Utils::getSecureRandom(&entropy, 1);
SharedPtr<Flow> flow = createFlow(ZT_MAX_PEER_NETWORK_PATHS, flowId, entropy, now);
@ -513,8 +505,7 @@ void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId,
_paths[pathIdx].qosStatsIn[packetId] = now;
++(_paths[pathIdx].packetsReceivedSinceLastQoS);
//_paths[pathIdx].packetValiditySamples.push(true);
}
else {
} else {
// debug("QoS buffer full, will not record information");
}
/*
@ -541,8 +532,7 @@ void Bond::recordIncomingPacket(const SharedPtr<Path>& path, uint64_t packetId,
SharedPtr<Flow> flow;
if (! _flows.count(flowId)) {
flow = createFlow(pathIdx, flowId, 0, now);
}
else {
} else {
flow = _flows[flowId];
}
if (flow) {
@ -628,8 +618,7 @@ bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now, bool reass
if (reassign) {
log("attempting to re-assign out-flow %04x previously on idx %d (%u / %zu flows)", flow->id, flow->assignedPath, _paths[_realIdxMap[flow->assignedPath]].assignedFlowCount, _flows.size());
}
else {
} else {
debug("attempting to assign flow for the first time");
}
@ -643,8 +632,7 @@ bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now, bool reass
if (reassign) {
bondedIdx = (flow->assignedPath + offset) % (_numBondedPaths);
}
else {
} else {
bondedIdx = abs((int)((entropy + offset) % (_numBondedPaths)));
}
// debug("idx=%d, offset=%d, randomCap=%f, actualCap=%f", bondedIdx, offset, randomLinkCapacity, _paths[_realIdxMap[bondedIdx]].relativeLinkCapacity);
@ -667,8 +655,7 @@ bool Bond::assignFlowToBondedPath(SharedPtr<Flow>& flow, int64_t now, bool reass
flow->assignPath(_realIdxMap[bondedIdx], now);
++(_paths[_realIdxMap[bondedIdx]].assignedFlowCount);
// debug(" ABLE to find optimal link %f idx %d", _paths[_realIdxMap[bondedIdx]].relativeQuality, bondedIdx);
}
else {
} else {
// We were (unable) to find a path that didn't violate at least one quality requirement, will choose next best option
flow->assignPath(_realIdxMap[nextBestQualIdx], now);
++(_paths[_realIdxMap[nextBestQualIdx]].assignedFlowCount);
@ -728,13 +715,11 @@ void Bond::forgetFlowsWhenNecessary(uint64_t age, bool oldest, int64_t now)
debug("forget flow %04x (age %" PRId64 ") (%u / %zu)", it->first, it->second->age(now), _paths[it->second->assignedPath].assignedFlowCount, (_flows.size() - 1));
_paths[it->second->assignedPath].assignedFlowCount--;
it = _flows.erase(it);
}
else {
} else {
++it;
}
}
}
else if (oldest) { // Remove single oldest by natural expiration
} else if (oldest) { // Remove single oldest by natural expiration
uint64_t maxAge = 0;
while (it != _flows.end()) {
if (it->second->age(now) > maxAge) {
@ -781,8 +766,7 @@ void Bond::processIncomingPathNegotiationRequest(uint64_t now, SharedPtr<Path>&
if (_peer->_id.address().toInt() > RR->node->identity().address().toInt()) {
debug("agree with peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
_negotiatedPathIdx = pathIdx;
}
else {
} else {
debug("ignore petition from peer to use alternate link %s/%s\n", link->ifname().c_str(), pathStr);
}
}
@ -897,8 +881,7 @@ void Bond::sendQOS_MEASUREMENT(void* tPtr, int pathIdx, int64_t localSocket, con
if (atAddress) {
outp.armor(_peer->key(), false, _peer->aesKeysIfSupported());
RR->node->putPacket(tPtr, localSocket, atAddress, outp.data(), outp.size());
}
else {
} else {
RR->sw->send(tPtr, outp, false);
}
Metrics::pkt_qos_out++;
@ -1033,13 +1016,6 @@ void Bond::curateBond(int64_t now, bool rebuildBond)
bool satisfiedUpDelay = (now - _paths[i].lastAliveToggle) >= _upDelay;
// How long since the last QoS was received (Must be less than ZT_PEER_PATH_EXPIRATION since the remote peer's _qosSendInterval isn't known)
bool acceptableQoSAge = (_paths[i].lastQoSReceived == 0 && inTrial) || ((now - _paths[i].lastQoSReceived) < ZT_PEER_EXPIRED_PATH_TRIAL_PERIOD);
// Allow active-backup to operate without the receipt of QoS records
// This may be expanded to the other modes as an option
if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
acceptableQoSAge = true;
}
currEligibility = _paths[i].allowed() && ((acceptableAge && satisfiedUpDelay && acceptableQoSAge) || inTrial);
if (currEligibility) {
@ -1051,11 +1027,12 @@ void Bond::curateBond(int64_t now, bool rebuildBond)
*/
if (currEligibility != _paths[i].eligible) {
if (currEligibility == 0) {
log("link %s is no longer eligible (reason: allowed=%d, age=%d, ud=%d, qos=%d, trial=%d)", pathToStr(_paths[i].p).c_str(), _paths[i].allowed(), acceptableAge, satisfiedUpDelay, acceptableQoSAge, inTrial);
log("link %s is no longer eligible", pathToStr(_paths[i].p).c_str());
}
if (currEligibility == 1) {
log("link %s is eligible", pathToStr(_paths[i].p).c_str());
}
debug("\t[%d] allowed=%d, age=%d, qa=%d, ud=%d, trial=%d", i, _paths[i].allowed(), acceptableAge, acceptableQoSAge, satisfiedUpDelay, inTrial);
dumpPathStatus(now, i);
if (currEligibility) {
rebuildBond = true;
@ -1101,7 +1078,6 @@ void Bond::curateBond(int64_t now, bool rebuildBond)
* Curate the set of paths that are part of the bond proper. Select a set of paths
* per logical link according to eligibility and user-specified constraints.
*/
int updatedBondedPathCount = 0;
if ((_policy == ZT_BOND_POLICY_BALANCE_RR) || (_policy == ZT_BOND_POLICY_BALANCE_XOR) || (_policy == ZT_BOND_POLICY_BALANCE_AWARE)) {
if (! _numBondedPaths) {
rebuildBond = true;
@ -1113,6 +1089,7 @@ void Bond::curateBond(int64_t now, bool rebuildBond)
_paths[i].bonded = false;
}
int updatedBondedPathCount = 0;
// Build map associating paths with local physical links. Will be selected from in next step
std::map<SharedPtr<Link>, std::vector<int> > linkMap;
for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
@ -1214,14 +1191,6 @@ void Bond::curateBond(int64_t now, bool rebuildBond)
}
}
}
if (_policy == ZT_BOND_POLICY_ACTIVE_BACKUP) {
for (int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
if (_paths[i].p && _paths[i].bonded) {
updatedBondedPathCount++;
}
}
_numBondedPaths = updatedBondedPathCount;
}
}
void Bond::estimatePathQuality(int64_t now)
@ -1253,8 +1222,7 @@ void Bond::estimatePathQuality(int64_t now)
if ((now - it->second) >= qosRecordTimeout) {
it = _paths[i].qosStatsOut.erase(it);
++numDroppedQosOutRecords;
}
else {
} else {
++it;
}
}
@ -1282,8 +1250,7 @@ void Bond::estimatePathQuality(int64_t now)
if ((now - it->second) >= qosRecordTimeout) {
it = _paths[i].qosStatsIn.erase(it);
++numDroppedQosInRecords;
}
else {
} else {
++it;
}
}
@ -1360,10 +1327,10 @@ void Bond::estimatePathQuality(int64_t now)
continue;
}
// Compute/Smooth average of real-world observations
if (_paths[i].latencySamples.count() >= ZT_QOS_SHORTTERM_SAMPLE_WIN_MIN_REQ_SIZE) {
if (_paths[i].latencySamples.count() == ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE) {
_paths[i].latency = _paths[i].latencySamples.mean();
}
if (_paths[i].latencySamples.count() >= ZT_QOS_SHORTTERM_SAMPLE_WIN_MIN_REQ_SIZE) {
if (_paths[i].latencySamples.count() == ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE) {
_paths[i].latencyVariance = _paths[i].latencySamples.stddev();
}
@ -1377,7 +1344,6 @@ void Bond::estimatePathQuality(int64_t now)
//_paths[i].packetErrorRatio = 1.0 - (_paths[i].packetValiditySamples.count() ? _paths[i].packetValiditySamples.mean() : 1.0);
// _valid is written elsewhere
_paths[i].p->_relativeQuality = _paths[i].relativeQuality;
_paths[i].p->_localPort = _paths[i].localPort;
}
// Flag links for avoidance
@ -1404,8 +1370,7 @@ void Bond::estimatePathQuality(int64_t now)
shouldAvoid = true;
}
_paths[i].shouldAvoid = shouldAvoid;
}
else {
} else {
if (! shouldAvoid) {
log("no longer avoiding link %s", pathToStr(_paths[i].p).c_str());
_paths[i].shouldAvoid = false;
@ -1503,8 +1468,7 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
{
int prevActiveBackupPathIdx = _abPathIdx;
int nonPreferredPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
bool foundPathOnPrimaryLink = false;
bool foundPreferredPath = false;
bool bFoundPrimaryLink = false;
if (_abPathIdx != ZT_MAX_PEER_NETWORK_PATHS && ! _paths[_abPathIdx].p) {
_abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
@ -1518,8 +1482,7 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
_lastBondStatusLog = now;
if (_abPathIdx == ZT_MAX_PEER_NETWORK_PATHS) {
log("no active link");
}
else if (_paths[_abPathIdx].p) {
} else if (_paths[_abPathIdx].p) {
log("active link is %s, failover queue size is %zu", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
}
if (_abFailoverQueue.empty()) {
@ -1567,16 +1530,15 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
if (! _paths[i].preferred()) {
// Found path on primary link, take note in case we don't find a preferred path
nonPreferredPathIdx = i;
foundPathOnPrimaryLink = true;
bFoundPrimaryLink = true;
}
if (_paths[i].preferred()) {
_abPathIdx = i;
foundPathOnPrimaryLink = true;
bFoundPrimaryLink = true;
if (_paths[_abPathIdx].p) {
SharedPtr<Link> abLink = RR->bc->getLinkBySocket(_policyAlias, _paths[_abPathIdx].p->localSocket());
if (abLink) {
log("found preferred primary link (_abPathIdx=%d), %s", _abPathIdx, pathToStr(_paths[_abPathIdx].p).c_str());
foundPreferredPath = true;
log("found preferred primary link %s", pathToStr(_paths[_abPathIdx].p).c_str());
}
break; // Found preferred path on primary link
}
@ -1584,8 +1546,8 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
}
}
}
if (! foundPreferredPath && foundPathOnPrimaryLink && (nonPreferredPathIdx != ZT_MAX_PEER_NETWORK_PATHS)) {
log("found non-preferred primary link (_abPathIdx=%d)", _abPathIdx);
if (bFoundPrimaryLink && (nonPreferredPathIdx != ZT_MAX_PEER_NETWORK_PATHS)) {
log("found non-preferred primary link");
_abPathIdx = nonPreferredPathIdx;
}
}
@ -1623,13 +1585,12 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
}
if (_paths[(*it)].p && ! _paths[(*it)].eligible) {
SharedPtr<Link> link = RR->bc->getLinkBySocket(_policyAlias, _paths[(*it)].p->localSocket());
if (link) {
log("link %s is ineligible, removing from failover queue (%zu links remain in queue)", pathToStr(_paths[(*it)].p).c_str(), _abFailoverQueue.size());
}
it = _abFailoverQueue.erase(it);
if (link) {
log("link %s is ineligible, removing from failover queue (%zu links remain in queue)", pathToStr(_paths[_abPathIdx].p).c_str(), _abFailoverQueue.size());
}
continue;
}
else {
} else {
++it;
}
}
@ -1693,9 +1654,9 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
}
}
if (! bFoundPathInQueue) {
_abFailoverQueue.push_back(i);
_abFailoverQueue.push_front(i);
log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
addPathToBond(i, 0);
addPathToBond(0, i);
}
}
}
@ -1743,19 +1704,25 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
}
}
if (! bFoundPathInQueue) {
_abFailoverQueue.push_back(i);
_abFailoverQueue.push_front(i);
log("add link %s to failover queue (%zu links in queue)", pathToStr(_paths[i].p).c_str(), _abFailoverQueue.size());
addPathToBond(i, 0);
addPathToBond(0, i);
}
}
}
}
// Sort queue based on performance
std::sort(_abFailoverQueue.begin(), _abFailoverQueue.end(),
[this](const int a, const int b) {
// Sort by failover score in descending order (highest score first)
return _paths[a].failoverScore > _paths[b].failoverScore;
});
if (! _abFailoverQueue.empty()) {
for (int i = 0; i < _abFailoverQueue.size(); i++) {
int value_to_insert = _abFailoverQueue[i];
int hole_position = i;
while (hole_position > 0 && (_abFailoverQueue[hole_position - 1] > value_to_insert)) {
_abFailoverQueue[hole_position] = _abFailoverQueue[hole_position - 1];
hole_position = hole_position - 1;
}
_abFailoverQueue[hole_position] = value_to_insert;
}
}
/**
* Short-circuit if we have no queued paths
@ -1772,8 +1739,7 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
if (! _abFailoverQueue.empty()) {
dequeueNextActiveBackupPath(now);
log("active link switched to %s", pathToStr(_paths[_abPathIdx].p).c_str());
}
else {
} else {
log("failover queue is empty, no links to choose from");
}
}
@ -1819,8 +1785,7 @@ void Bond::processActiveBackupTasks(void* tPtr, int64_t now)
dequeueNextActiveBackupPath(now);
_lastPathNegotiationCheck = now;
log("switch negotiated link %s (select mode: optimize)", pathToStr(_paths[_abPathIdx].p).c_str());
}
else {
} else {
// Try to find a better path and automatically switch to it -- not too often, though.
if ((now - _lastActiveBackupPathChange) > ZT_BOND_OPTIMIZE_INTERVAL) {
if (! _abFailoverQueue.empty()) {
@ -1905,7 +1870,7 @@ void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useT
* Policy defaults
*/
_abPathIdx = ZT_MAX_PEER_NETWORK_PATHS;
_abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_ALWAYS;
_abLinkSelectMethod = ZT_BOND_RESELECTION_POLICY_OPTIMIZE;
_rrPacketsSentOnCurrLink = 0;
_rrIdx = 0;
_packetsPerLink = 64;
@ -1936,7 +1901,7 @@ void Bond::setBondParameters(int policy, SharedPtr<Bond> templateBond, bool useT
}
if (! _isLeaf) {
_policy = ZT_BOND_POLICY_NONE;
_policy = ZT_BOND_POLICY_ACTIVE_BACKUP;
}
// Timer geometry
@ -2024,8 +1989,7 @@ void Bond::dumpInfo(int64_t now, bool force)
_lastSummaryDump = now;
float overhead = (_overheadBytes / (timeSinceLastDump / 1000.0f) / 1000.0f);
_overheadBytes = 0;
log("bond: ready=%d, bp=%d, fi=%" PRIu64 ", mi=%d, ud=%d, dd=%d, flows=%zu, leaf=%d, overhead=%f KB/s, links=(%d/%d)",
isReady(),
log("bond: bp=%d, fi=%" PRIu64 ", mi=%d, ud=%d, dd=%d, flows=%zu, leaf=%d, overhead=%f KB/s, links=(%d/%d)",
_policy,
_failoverInterval,
_monitorInterval,

View file

@ -315,6 +315,7 @@ class Peer;
class Bond {
public:
/**
* Stop bond's internal functions (can be resumed)
*/
@ -908,8 +909,7 @@ class Bond {
_lastAckRateCheck = now;
if (_ackCutoffCount > numToDrain) {
_ackCutoffCount -= numToDrain;
}
else {
} else {
_ackCutoffCount = 0;
}
return (_ackCutoffCount < ZT_ACK_CUTOFF_LIMIT);
@ -928,8 +928,7 @@ class Bond {
uint64_t diff = now - _lastQoSRateCheck;
if ((diff) <= (_qosSendInterval / ZT_MAX_PEER_NETWORK_PATHS)) {
++_qosCutoffCount;
}
else {
} else {
_qosCutoffCount = 0;
}
_lastQoSRateCheck = now;
@ -949,8 +948,7 @@ class Bond {
int diff = now - _lastPathNegotiationReceived;
if ((diff) <= (ZT_PATH_NEGOTIATION_CUTOFF_TIME / ZT_MAX_PEER_NETWORK_PATHS)) {
++_pathNegotiationCutoffCount;
}
else {
} else {
_pathNegotiationCutoffCount = 0;
}
_lastPathNegotiationReceived = now;
@ -1144,7 +1142,6 @@ class Bond {
__attribute__((format(printf, 2, 3)))
#endif
{
// if (_peerId != 0x0 && _peerId != 0x0) { return; }
#ifdef ZT_TRACE
time_t rawtime;
struct tm* timeinfo;
@ -1176,7 +1173,6 @@ class Bond {
__attribute__((format(printf, 2, 3)))
#endif
{
// if (_peerId != 0x0 && _peerId != 0x0) { return; }
#ifdef ZT_DEBUG
time_t rawtime;
struct tm* timeinfo;
@ -1234,7 +1230,6 @@ class Bond {
, packetsReceivedSinceLastQoS(0)
, packetsIn(0)
, packetsOut(0)
, localPort(0)
{
}
@ -1250,20 +1245,17 @@ class Bond {
unsigned int suggestedRefractoryPeriod = refractoryPeriod ? punishment + (refractoryPeriod * 2) : punishment;
refractoryPeriod = std::min(suggestedRefractoryPeriod, (unsigned int)ZT_BOND_MAX_REFRACTORY_PERIOD);
lastRefractoryUpdate = 0;
}
else {
} else {
uint32_t drainRefractory = 0;
if (lastRefractoryUpdate) {
drainRefractory = (now - lastRefractoryUpdate);
}
else {
} else {
drainRefractory = (now - lastAliveToggle);
}
lastRefractoryUpdate = now;
if (refractoryPeriod > drainRefractory) {
refractoryPeriod -= drainRefractory;
}
else {
} else {
refractoryPeriod = 0;
lastRefractoryUpdate = 0;
}
@ -1300,6 +1292,7 @@ class Bond {
*/
inline bool needsToSendQoS(int64_t now, uint64_t qosSendInterval)
{
// fprintf(stderr, "QOS table (%d / %d)\n", packetsReceivedSinceLastQoS, ZT_QOS_TABLE_SIZE);
return ((packetsReceivedSinceLastQoS >= ZT_QOS_TABLE_SIZE) || ((now - lastQoSMeasurement) > qosSendInterval)) && packetsReceivedSinceLastQoS;
}
@ -1371,8 +1364,6 @@ class Bond {
int packetsIn;
int packetsOut;
uint16_t localPort;
// AtomicCounter __refCount;
SharedPtr<Path> p;

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,17 +14,18 @@
#ifndef ZT_BUFFER_HPP
#define ZT_BUFFER_HPP
#include <string.h>
#include <stdint.h>
#include <stdexcept>
#include <string>
#include <algorithm>
#include <utility>
#include "Constants.hpp"
#include "Utils.hpp"
#include <algorithm>
#include <stdexcept>
#include <stdint.h>
#include <string.h>
#include <string>
#include <utility>
#if defined(__GNUC__) && (! defined(ZT_NO_TYPE_PUNNING))
#if defined(__GNUC__) && (!defined(ZT_NO_TYPE_PUNNING))
#define ZT_VAR_MAY_ALIAS __attribute__((__may_alias__))
#else
#define ZT_VAR_MAY_ALIAS
@ -45,57 +46,36 @@ namespace ZeroTier {
*
* @tparam C Total capacity
*/
template <unsigned int C> class Buffer {
template<unsigned int C>
class Buffer
{
// I love me!
template <unsigned int C2> friend class Buffer;
public:
public:
// STL container idioms
typedef unsigned char value_type;
typedef unsigned char* pointer;
typedef const char* const_pointer;
typedef char& reference;
typedef const char& const_reference;
typedef char* iterator;
typedef const char* const_iterator;
typedef unsigned char * pointer;
typedef const char * const_pointer;
typedef char & reference;
typedef const char & const_reference;
typedef char * iterator;
typedef const char * const_iterator;
typedef unsigned int size_type;
typedef int difference_type;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
inline iterator begin()
{
return _b;
}
inline iterator end()
{
return (_b + _l);
}
inline const_iterator begin() const
{
return _b;
}
inline const_iterator end() const
{
return (_b + _l);
}
inline reverse_iterator rbegin()
{
return reverse_iterator(begin());
}
inline reverse_iterator rend()
{
return reverse_iterator(end());
}
inline const_reverse_iterator rbegin() const
{
return const_reverse_iterator(begin());
}
inline const_reverse_iterator rend() const
{
return const_reverse_iterator(end());
}
inline iterator begin() { return _b; }
inline iterator end() { return (_b + _l); }
inline const_iterator begin() const { return _b; }
inline const_iterator end() const { return (_b + _l); }
inline reverse_iterator rbegin() { return reverse_iterator(begin()); }
inline reverse_iterator rend() { return reverse_iterator(end()); }
inline const_reverse_iterator rbegin() const { return const_reverse_iterator(begin()); }
inline const_reverse_iterator rend() const { return const_reverse_iterator(end()); }
Buffer() : _l(0)
Buffer() :
_l(0)
{
}
@ -107,36 +87,37 @@ template <unsigned int C> class Buffer {
_l = l;
}
template <unsigned int C2> Buffer(const Buffer<C2>& b)
template<unsigned int C2>
Buffer(const Buffer<C2> &b)
{
*this = b;
}
Buffer(const void* b, unsigned int l)
Buffer(const void *b,unsigned int l)
{
copyFrom(b, l);
copyFrom(b,l);
}
template <unsigned int C2> inline Buffer& operator=(const Buffer<C2>& b)
template<unsigned int C2>
inline Buffer &operator=(const Buffer<C2> &b)
{
if (unlikely(b._l > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
if (C2 == C) {
memcpy(this, &b, sizeof(Buffer<C>));
}
else {
memcpy(_b, b._b, _l = b._l);
memcpy(this,&b,sizeof(Buffer<C>));
} else {
memcpy(_b,b._b,_l = b._l);
}
return *this;
}
inline void copyFrom(const void* b, unsigned int l)
inline void copyFrom(const void *b,unsigned int l)
{
if (unlikely(l > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
memcpy(_b, b, l);
memcpy(_b,b,l);
_l = l;
}
@ -148,12 +129,12 @@ template <unsigned int C> class Buffer {
return (unsigned char)_b[i];
}
unsigned char& operator[](const unsigned int i)
unsigned char &operator[](const unsigned int i)
{
if (unlikely(i >= _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
return ((unsigned char*)_b)[i];
return ((unsigned char *)_b)[i];
}
/**
@ -169,19 +150,19 @@ template <unsigned int C> class Buffer {
* @return Pointer to field data
* @throws std::out_of_range Field extends beyond data size
*/
unsigned char* field(unsigned int i, unsigned int l)
unsigned char *field(unsigned int i,unsigned int l)
{
if (unlikely((i + l) > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
return (unsigned char*)(_b + i);
return (unsigned char *)(_b + i);
}
const unsigned char* field(unsigned int i, unsigned int l) const
const unsigned char *field(unsigned int i,unsigned int l) const
{
if (unlikely((i + l) > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
return (const unsigned char*)(_b + i);
return (const unsigned char *)(_b + i);
}
/**
@ -191,18 +172,19 @@ template <unsigned int C> class Buffer {
* @param v Value
* @tparam T Integer type (e.g. uint16_t, int64_t)
*/
template <typename T> inline void setAt(unsigned int i, const T v)
template<typename T>
inline void setAt(unsigned int i,const T v)
{
if (unlikely((i + sizeof(T)) > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
#ifdef ZT_NO_TYPE_PUNNING
uint8_t* p = reinterpret_cast<uint8_t*>(_b + i);
for (unsigned int x = 1; x <= sizeof(T); ++x) {
uint8_t *p = reinterpret_cast<uint8_t *>(_b + i);
for(unsigned int x=1;x<=sizeof(T);++x) {
*(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x)));
}
#else
T* const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T*>(_b + i);
T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T *>(_b + i);
*p = Utils::hton(v);
#endif
}
@ -214,21 +196,22 @@ template <unsigned int C> class Buffer {
* @tparam T Integer type (e.g. uint16_t, int64_t)
* @return Integer value
*/
template <typename T> inline T at(unsigned int i) const
template<typename T>
inline T at(unsigned int i) const
{
if (unlikely((i + sizeof(T)) > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
#ifdef ZT_NO_TYPE_PUNNING
T v = 0;
const uint8_t* p = reinterpret_cast<const uint8_t*>(_b + i);
for (unsigned int x = 0; x < sizeof(T); ++x) {
const uint8_t *p = reinterpret_cast<const uint8_t *>(_b + i);
for(unsigned int x=0;x<sizeof(T);++x) {
v <<= 8;
v |= (T) * (p++);
v |= (T)*(p++);
}
return v;
#else
const T* const ZT_VAR_MAY_ALIAS p = reinterpret_cast<const T*>(_b + i);
const T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<const T *>(_b + i);
return Utils::ntoh(*p);
#endif
}
@ -240,18 +223,19 @@ template <unsigned int C> class Buffer {
* @tparam T Integer type (e.g. uint16_t, int64_t)
* @throws std::out_of_range Attempt to append beyond capacity
*/
template <typename T> inline void append(const T v)
template<typename T>
inline void append(const T v)
{
if (unlikely((_l + sizeof(T)) > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
#ifdef ZT_NO_TYPE_PUNNING
uint8_t* p = reinterpret_cast<uint8_t*>(_b + _l);
for (unsigned int x = 1; x <= sizeof(T); ++x) {
uint8_t *p = reinterpret_cast<uint8_t *>(_b + _l);
for(unsigned int x=1;x<=sizeof(T);++x) {
*(p++) = (uint8_t)(v >> (8 * (sizeof(T) - x)));
}
#else
T* const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T*>(_b + _l);
T *const ZT_VAR_MAY_ALIAS p = reinterpret_cast<T *>(_b + _l);
*p = Utils::hton(v);
#endif
_l += sizeof(T);
@ -264,12 +248,12 @@ template <unsigned int C> class Buffer {
* @param n Number of times to append
* @throws std::out_of_range Attempt to append beyond capacity
*/
inline void append(unsigned char c, unsigned int n)
inline void append(unsigned char c,unsigned int n)
{
if (unlikely((_l + n) > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
for (unsigned int i = 0; i < n; ++i) {
for(unsigned int i=0;i<n;++i) {
_b[_l++] = (char)c;
}
}
@ -284,7 +268,7 @@ template <unsigned int C> class Buffer {
if (unlikely((_l + n) > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
Utils::getSecureRandom(_b + _l, n);
Utils::getSecureRandom(_b + _l,n);
_l += n;
}
@ -295,12 +279,12 @@ template <unsigned int C> class Buffer {
* @param l Length
* @throws std::out_of_range Attempt to append beyond capacity
*/
inline void append(const void* b, unsigned int l)
inline void append(const void *b,unsigned int l)
{
if (unlikely((_l + l) > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
memcpy(_b + _l, b, l);
memcpy(_b + _l,b,l);
_l += l;
}
@ -310,13 +294,13 @@ template <unsigned int C> class Buffer {
* @param s C string
* @throws std::out_of_range Attempt to append beyond capacity
*/
inline void appendCString(const char* s)
inline void appendCString(const char *s)
{
for (;;) {
for(;;) {
if (unlikely(_l >= C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
if (! (_b[_l++] = *(s++))) {
if (!(_b[_l++] = *(s++))) {
break;
}
}
@ -329,9 +313,10 @@ template <unsigned int C> class Buffer {
* @tparam C2 Capacity of second buffer (typically inferred)
* @throws std::out_of_range Attempt to append beyond capacity
*/
template <unsigned int C2> inline void append(const Buffer<C2>& b)
template<unsigned int C2>
inline void append(const Buffer<C2> &b)
{
append(b._b, b._l);
append(b._b,b._l);
}
/**
@ -344,12 +329,12 @@ template <unsigned int C> class Buffer {
* @param l Length of field to append
* @return Pointer to beginning of appended field of length 'l'
*/
inline char* appendField(unsigned int l)
inline char *appendField(unsigned int l)
{
if (unlikely((_l + l) > C)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
char* r = _b + _l;
char *r = _b + _l;
_l += l;
return r;
}
@ -394,13 +379,13 @@ template <unsigned int C> class Buffer {
*/
inline void behead(const unsigned int at)
{
if (! at) {
if (!at) {
return;
}
if (unlikely(at > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
::memmove(_b, _b + at, _l -= at);
::memmove(_b,_b + at,_l -= at);
}
/**
@ -410,110 +395,92 @@ template <unsigned int C> class Buffer {
* @param length Length of block to erase
* @throws std::out_of_range Position plus length is beyond size of buffer
*/
inline void erase(const unsigned int at, const unsigned int length)
inline void erase(const unsigned int at,const unsigned int length)
{
const unsigned int endr = at + length;
if (unlikely(endr > _l)) {
throw ZT_EXCEPTION_OUT_OF_BOUNDS;
}
::memmove(_b + at, _b + endr, _l - endr);
::memmove(_b + at,_b + endr,_l - endr);
_l -= length;
}
/**
* Set buffer data length to zero
*/
inline void clear()
{
_l = 0;
}
inline void clear() { _l = 0; }
/**
* Zero buffer up to size()
*/
inline void zero()
{
memset(_b, 0, _l);
}
inline void zero() { memset(_b,0,_l); }
/**
* Zero unused capacity area
*/
inline void zeroUnused()
{
memset(_b + _l, 0, C - _l);
}
inline void zeroUnused() { memset(_b + _l,0,C - _l); }
/**
* Unconditionally and securely zero buffer's underlying memory
*/
inline void burn()
{
Utils::burn(_b, sizeof(_b));
}
inline void burn() { Utils::burn(_b,sizeof(_b)); }
/**
* @return Constant pointer to data in buffer
*/
inline const void* data() const
{
return _b;
}
inline const void *data() const { return _b; }
/**
* @return Non-constant pointer to data in buffer
*/
inline void* unsafeData()
{
return _b;
}
inline void *unsafeData() { return _b; }
/**
* @return Size of data in buffer
*/
inline unsigned int size() const
{
return _l;
}
inline unsigned int size() const { return _l; }
/**
* @return Capacity of buffer
*/
inline unsigned int capacity() const
{
return C;
}
inline unsigned int capacity() const { return C; }
template <unsigned int C2> inline bool operator==(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator==(const Buffer<C2> &b) const
{
return ((_l == b._l) && (! memcmp(_b, b._b, _l)));
return ((_l == b._l)&&(!memcmp(_b,b._b,_l)));
}
template <unsigned int C2> inline bool operator!=(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator!=(const Buffer<C2> &b) const
{
return ((_l != b._l) || (memcmp(_b, b._b, _l)));
return ((_l != b._l)||(memcmp(_b,b._b,_l)));
}
template <unsigned int C2> inline bool operator<(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator<(const Buffer<C2> &b) const
{
return (memcmp(_b, b._b, std::min(_l, b._l)) < 0);
return (memcmp(_b,b._b,std::min(_l,b._l)) < 0);
}
template <unsigned int C2> inline bool operator>(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator>(const Buffer<C2> &b) const
{
return (b < *this);
}
template <unsigned int C2> inline bool operator<=(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator<=(const Buffer<C2> &b) const
{
return ! (b < *this);
return !(b < *this);
}
template <unsigned int C2> inline bool operator>=(const Buffer<C2>& b) const
template<unsigned int C2>
inline bool operator>=(const Buffer<C2> &b) const
{
return ! (*this < b);
return !(*this < b);
}
private:
private:
char ZT_VAR_MAY_ALIAS _b[C];
unsigned int _l;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -18,28 +18,20 @@
namespace ZeroTier {
#define ZT_C25519_PUBLIC_KEY_LEN 64
#define ZT_C25519_PUBLIC_KEY_LEN 64
#define ZT_C25519_PRIVATE_KEY_LEN 64
#define ZT_C25519_SIGNATURE_LEN 96
#define ZT_C25519_SIGNATURE_LEN 96
/**
* A combined Curve25519 ECDH and Ed25519 signature engine
*/
class C25519 {
public:
struct Public {
uint8_t data[ZT_C25519_PUBLIC_KEY_LEN];
};
struct Private {
uint8_t data[ZT_C25519_PRIVATE_KEY_LEN];
};
struct Signature {
uint8_t data[ZT_C25519_SIGNATURE_LEN];
};
struct Pair {
Public pub;
Private priv;
};
class C25519
{
public:
struct Public { uint8_t data[ZT_C25519_PUBLIC_KEY_LEN]; };
struct Private { uint8_t data[ZT_C25519_PRIVATE_KEY_LEN]; };
struct Signature { uint8_t data[ZT_C25519_SIGNATURE_LEN]; };
struct Pair { Public pub; Private priv; };
/**
* Generate a C25519 elliptic curve key pair
@ -47,7 +39,7 @@ class C25519 {
static inline Pair generate()
{
Pair kp;
Utils::getSecureRandom(kp.priv.data, ZT_C25519_PRIVATE_KEY_LEN);
Utils::getSecureRandom(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
_calcPubDH(kp);
_calcPubED(kp);
return kp;
@ -66,17 +58,18 @@ class C25519 {
* @return Key pair where cond(kp) returns true
* @tparam F Type of 'cond'
*/
template <typename F> static inline Pair generateSatisfying(F cond)
template<typename F>
static inline Pair generateSatisfying(F cond)
{
Pair kp;
void* const priv = (void*)kp.priv.data;
Utils::getSecureRandom(priv, ZT_C25519_PRIVATE_KEY_LEN);
_calcPubED(kp); // do Ed25519 key -- bytes 32-63 of pub and priv
void *const priv = (void *)kp.priv.data;
Utils::getSecureRandom(priv,ZT_C25519_PRIVATE_KEY_LEN);
_calcPubED(kp); // do Ed25519 key -- bytes 32-63 of pub and priv
do {
++(((uint64_t*)priv)[1]);
--(((uint64_t*)priv)[2]);
_calcPubDH(kp); // keep regenerating bytes 0-31 until satisfied
} while (! cond(kp));
++(((uint64_t *)priv)[1]);
--(((uint64_t *)priv)[2]);
_calcPubDH(kp); // keep regenerating bytes 0-31 until satisfied
} while (!cond(kp));
return kp;
}
@ -91,11 +84,8 @@ class C25519 {
* @param keybuf Buffer to fill
* @param keylen Number of key bytes to generate
*/
static void agree(const Private& mine, const Public& their, void* keybuf, unsigned int keylen);
static inline void agree(const Pair& mine, const Public& their, void* keybuf, unsigned int keylen)
{
agree(mine.priv, their, keybuf, keylen);
}
static void agree(const Private &mine,const Public &their,void *keybuf,unsigned int keylen);
static inline void agree(const Pair &mine,const Public &their,void *keybuf,unsigned int keylen) { agree(mine.priv,their,keybuf,keylen); }
/**
* Sign a message with a sender's key pair
@ -116,11 +106,8 @@ class C25519 {
* @param len Length of message in bytes
* @param signature Buffer to fill with signature -- MUST be 96 bytes in length
*/
static void sign(const Private& myPrivate, const Public& myPublic, const void* msg, unsigned int len, void* signature);
static inline void sign(const Pair& mine, const void* msg, unsigned int len, void* signature)
{
sign(mine.priv, mine.pub, msg, len, signature);
}
static void sign(const Private &myPrivate,const Public &myPublic,const void *msg,unsigned int len,void *signature);
static inline void sign(const Pair &mine,const void *msg,unsigned int len,void *signature) { sign(mine.priv,mine.pub,msg,len,signature); }
/**
* Sign a message with a sender's key pair
@ -131,16 +118,16 @@ class C25519 {
* @param len Length of message in bytes
* @return Signature
*/
static inline Signature sign(const Private& myPrivate, const Public& myPublic, const void* msg, unsigned int len)
static inline Signature sign(const Private &myPrivate,const Public &myPublic,const void *msg,unsigned int len)
{
Signature sig;
sign(myPrivate, myPublic, msg, len, sig.data);
sign(myPrivate,myPublic,msg,len,sig.data);
return sig;
}
static inline Signature sign(const Pair& mine, const void* msg, unsigned int len)
static inline Signature sign(const Pair &mine,const void *msg,unsigned int len)
{
Signature sig;
sign(mine.priv, mine.pub, msg, len, sig.data);
sign(mine.priv,mine.pub,msg,len,sig.data);
return sig;
}
@ -153,7 +140,7 @@ class C25519 {
* @param signature 96-byte signature
* @return True if signature is valid and the message is authentic and unmodified
*/
static bool verify(const Public& their, const void* msg, unsigned int len, const void* signature);
static bool verify(const Public &their,const void *msg,unsigned int len,const void *signature);
/**
* Verify a message's signature
@ -164,21 +151,21 @@ class C25519 {
* @param signature 96-byte signature
* @return True if signature is valid and the message is authentic and unmodified
*/
static inline bool verify(const Public& their, const void* msg, unsigned int len, const Signature& signature)
static inline bool verify(const Public &their,const void *msg,unsigned int len,const Signature &signature)
{
return verify(their, msg, len, signature.data);
return verify(their,msg,len,signature.data);
}
private:
private:
// derive first 32 bytes of kp.pub from first 32 bytes of kp.priv
// this is the ECDH key
static void _calcPubDH(Pair& kp);
static void _calcPubDH(Pair &kp);
// derive 2nd 32 bytes of kp.pub from 2nd 32 bytes of kp.priv
// this is the Ed25519 sign/verify key
static void _calcPubED(Pair& kp);
static void _calcPubED(Pair &kp);
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -12,60 +12,54 @@
/****/
#include "Capability.hpp"
#include "RuntimeEnvironment.hpp"
#include "Identity.hpp"
#include "Topology.hpp"
#include "Switch.hpp"
#include "Network.hpp"
#include "Node.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
namespace ZeroTier {
int Capability::verify(const RuntimeEnvironment* RR, void* tPtr) const
int Capability::verify(const RuntimeEnvironment *RR,void *tPtr) const
{
try {
// There must be at least one entry, and sanity check for bad chain max length
if ((_maxCustodyChainLength < 1) || (_maxCustodyChainLength > ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
if ((_maxCustodyChainLength < 1)||(_maxCustodyChainLength > ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
return -1;
}
// Validate all entries in chain of custody
Buffer<(sizeof(Capability) * 2)> tmp;
this->serialize(tmp, true);
for (unsigned int c = 0; c < _maxCustodyChainLength; ++c) {
this->serialize(tmp,true);
for(unsigned int c=0;c<_maxCustodyChainLength;++c) {
if (c == 0) {
if ((! _custody[c].to) || (! _custody[c].from) || (_custody[c].from != Network::controllerFor(_nwid))) {
return -1; // the first entry must be present and from the network's controller
if ((!_custody[c].to)||(!_custody[c].from)||(_custody[c].from != Network::controllerFor(_nwid))) {
return -1; // the first entry must be present and from the network's controller
}
}
else {
if (! _custody[c].to) {
return 0; // all previous entries were valid, so we are valid
}
else if ((! _custody[c].from) || (_custody[c].from != _custody[c - 1].to)) {
return -1; // otherwise if we have another entry it must be from the previous holder in the chain
} else {
if (!_custody[c].to) {
return 0; // all previous entries were valid, so we are valid
} else if ((!_custody[c].from)||(_custody[c].from != _custody[c-1].to)) {
return -1; // otherwise if we have another entry it must be from the previous holder in the chain
}
}
const Identity id(RR->topology->getIdentity(tPtr, _custody[c].from));
const Identity id(RR->topology->getIdentity(tPtr,_custody[c].from));
if (id) {
if (! id.verify(tmp.data(), tmp.size(), _custody[c].signature)) {
if (!id.verify(tmp.data(),tmp.size(),_custody[c].signature)) {
return -1;
}
}
else {
RR->sw->requestWhois(tPtr, RR->node->now(), _custody[c].from);
} else {
RR->sw->requestWhois(tPtr,RR->node->now(),_custody[c].from);
return 1;
}
}
// We reached max custody chain length and everything was valid
return 0;
}
catch (...) {
}
} catch ( ... ) {}
return -1;
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,19 +14,19 @@
#ifndef ZT_CAPABILITY_HPP
#define ZT_CAPABILITY_HPP
#include "../include/ZeroTierOne.h"
#include "Address.hpp"
#include "Buffer.hpp"
#include "C25519.hpp"
#include "Constants.hpp"
#include "Credential.hpp"
#include "Identity.hpp"
#include "Utils.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Constants.hpp"
#include "Credential.hpp"
#include "Address.hpp"
#include "C25519.hpp"
#include "Utils.hpp"
#include "Buffer.hpp"
#include "Identity.hpp"
#include "../include/ZeroTierOne.h"
namespace ZeroTier {
class RuntimeEnvironment;
@ -54,17 +54,20 @@ class RuntimeEnvironment;
* handed off between nodes. Limited transferability of capabilities is
* a feature of true capability based security.
*/
class Capability : public Credential {
public:
static inline Credential::Type credentialType()
{
return Credential::CREDENTIAL_TYPE_CAPABILITY;
}
class Capability : public Credential
{
public:
static inline Credential::Type credentialType() { return Credential::CREDENTIAL_TYPE_CAPABILITY; }
Capability() : _nwid(0), _ts(0), _id(0), _maxCustodyChainLength(0), _ruleCount(0)
Capability() :
_nwid(0),
_ts(0),
_id(0),
_maxCustodyChainLength(0),
_ruleCount(0)
{
memset(_rules, 0, sizeof(_rules));
memset(_custody, 0, sizeof(_custody));
memset(_rules,0,sizeof(_rules));
memset(_custody,0,sizeof(_custody));
}
/**
@ -75,57 +78,42 @@ class Capability : public Credential {
* @param rules Network flow rules for this capability
* @param ruleCount Number of flow rules
*/
Capability(uint32_t id, uint64_t nwid, int64_t ts, unsigned int mccl, const ZT_VirtualNetworkRule* rules, unsigned int ruleCount)
: _nwid(nwid)
, _ts(ts)
, _id(id)
, _maxCustodyChainLength((mccl > 0) ? ((mccl < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH) ? mccl : (unsigned int)ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH) : 1)
, _ruleCount((ruleCount < ZT_MAX_CAPABILITY_RULES) ? ruleCount : ZT_MAX_CAPABILITY_RULES)
Capability(uint32_t id,uint64_t nwid,int64_t ts,unsigned int mccl,const ZT_VirtualNetworkRule *rules,unsigned int ruleCount) :
_nwid(nwid),
_ts(ts),
_id(id),
_maxCustodyChainLength((mccl > 0) ? ((mccl < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH) ? mccl : (unsigned int)ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH) : 1),
_ruleCount((ruleCount < ZT_MAX_CAPABILITY_RULES) ? ruleCount : ZT_MAX_CAPABILITY_RULES)
{
if (_ruleCount > 0) {
memcpy(_rules, rules, sizeof(ZT_VirtualNetworkRule) * _ruleCount);
memcpy(_rules,rules,sizeof(ZT_VirtualNetworkRule) * _ruleCount);
}
}
/**
* @return Rules -- see ruleCount() for size of array
*/
inline const ZT_VirtualNetworkRule* rules() const
{
return _rules;
}
inline const ZT_VirtualNetworkRule *rules() const { return _rules; }
/**
* @return Number of rules in rules()
*/
inline unsigned int ruleCount() const
{
return _ruleCount;
}
inline unsigned int ruleCount() const { return _ruleCount; }
/**
* @return ID and evaluation order of this capability in network
*/
inline uint32_t id() const
{
return _id;
}
inline uint32_t id() const { return _id; }
/**
* @return Network ID for which this capability was issued
*/
inline uint64_t networkId() const
{
return _nwid;
}
inline uint64_t networkId() const { return _nwid; }
/**
* @return Timestamp
*/
inline int64_t timestamp() const
{
return _ts;
}
inline int64_t timestamp() const { return _ts; }
/**
* @return Last 'to' address in chain of custody
@ -133,11 +121,10 @@ class Capability : public Credential {
inline Address issuedTo() const
{
Address i2;
for (unsigned int i = 0; i < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH; ++i) {
if (! _custody[i].to) {
for(unsigned int i=0;i<ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH;++i) {
if (!_custody[i].to) {
return i2;
}
else {
} else {
i2 = _custody[i].to;
}
}
@ -157,22 +144,20 @@ class Capability : public Credential {
* @param to Recipient of this signature
* @return True if signature successful and chain of custody appended
*/
inline bool sign(const Identity& from, const Address& to)
inline bool sign(const Identity &from,const Address &to)
{
try {
for (unsigned int i = 0; ((i < _maxCustodyChainLength) && (i < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)); ++i) {
if (! (_custody[i].to)) {
for(unsigned int i=0;((i<_maxCustodyChainLength)&&(i<ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH));++i) {
if (!(_custody[i].to)) {
Buffer<(sizeof(Capability) * 2)> tmp;
this->serialize(tmp, true);
this->serialize(tmp,true);
_custody[i].to = to;
_custody[i].from = from.address();
_custody[i].signature = from.sign(tmp.data(), tmp.size());
_custody[i].signature = from.sign(tmp.data(),tmp.size());
return true;
}
}
}
catch (...) {
}
} catch ( ... ) {}
return false;
}
@ -182,16 +167,17 @@ class Capability : public Credential {
* @param RR Runtime environment to provide for peer lookup, etc.
* @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or chain
*/
int verify(const RuntimeEnvironment* RR, void* tPtr) const;
int verify(const RuntimeEnvironment *RR,void *tPtr) const;
template <unsigned int C> static inline void serializeRules(Buffer<C>& b, const ZT_VirtualNetworkRule* rules, unsigned int ruleCount)
template<unsigned int C>
static inline void serializeRules(Buffer<C> &b,const ZT_VirtualNetworkRule *rules,unsigned int ruleCount)
{
for (unsigned int i = 0; i < ruleCount; ++i) {
for(unsigned int i=0;i<ruleCount;++i) {
// Each rule consists of its 8-bit type followed by the size of that type's
// field followed by field data. The inclusion of the size will allow non-supported
// rules to be ignored but still parsed.
b.append((uint8_t)rules[i].t);
switch ((ZT_VirtualNetworkRuleType)(rules[i].t & 0x3f)) {
switch((ZT_VirtualNetworkRuleType)(rules[i].t & 0x3f)) {
default:
b.append((uint8_t)0);
break;
@ -201,7 +187,7 @@ class Capability : public Credential {
b.append((uint8_t)14);
b.append((uint64_t)rules[i].v.fwd.address);
b.append((uint32_t)rules[i].v.fwd.flags);
b.append((uint16_t)rules[i].v.fwd.length); // unused for redirect
b.append((uint16_t)rules[i].v.fwd.length); // unused for redirect
break;
case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
@ -223,18 +209,18 @@ class Capability : public Credential {
case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
case ZT_NETWORK_RULE_MATCH_MAC_DEST:
b.append((uint8_t)6);
b.append(rules[i].v.mac, 6);
b.append(rules[i].v.mac,6);
break;
case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
b.append((uint8_t)5);
b.append(&(rules[i].v.ipv4.ip), 4);
b.append(&(rules[i].v.ipv4.ip),4);
b.append((uint8_t)rules[i].v.ipv4.mask);
break;
case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
b.append((uint8_t)17);
b.append(rules[i].v.ipv6.ip, 16);
b.append(rules[i].v.ipv6.ip,16);
b.append((uint8_t)rules[i].v.ipv6.mask);
break;
case ZT_NETWORK_RULE_MATCH_IP_TOS:
@ -290,7 +276,7 @@ class Capability : public Credential {
case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
b.append((uint8_t)19);
b.append((uint64_t)rules[i].v.intRange.start);
b.append((uint64_t)(rules[i].v.intRange.start + (uint64_t)rules[i].v.intRange.end)); // more future-proof
b.append((uint64_t)(rules[i].v.intRange.start + (uint64_t)rules[i].v.intRange.end)); // more future-proof
b.append((uint16_t)rules[i].v.intRange.idx);
b.append((uint8_t)rules[i].v.intRange.format);
break;
@ -298,12 +284,13 @@ class Capability : public Credential {
}
}
template <unsigned int C> static inline void deserializeRules(const Buffer<C>& b, unsigned int& p, ZT_VirtualNetworkRule* rules, unsigned int& ruleCount, const unsigned int maxRuleCount)
template<unsigned int C>
static inline void deserializeRules(const Buffer<C> &b,unsigned int &p,ZT_VirtualNetworkRule *rules,unsigned int &ruleCount,const unsigned int maxRuleCount)
{
while ((ruleCount < maxRuleCount) && (p < b.size())) {
while ((ruleCount < maxRuleCount)&&(p < b.size())) {
rules[ruleCount].t = (uint8_t)b[p++];
const unsigned int fieldLen = (unsigned int)b[p++];
switch ((ZT_VirtualNetworkRuleType)(rules[ruleCount].t & 0x3f)) {
switch((ZT_VirtualNetworkRuleType)(rules[ruleCount].t & 0x3f)) {
default:
break;
case ZT_NETWORK_RULE_ACTION_TEE:
@ -315,7 +302,7 @@ class Capability : public Credential {
break;
case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
rules[ruleCount].v.zt = Address(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH).toInt();
rules[ruleCount].v.zt = Address(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH).toInt();
break;
case ZT_NETWORK_RULE_MATCH_VLAN_ID:
rules[ruleCount].v.vlanId = b.template at<uint16_t>(p);
@ -328,22 +315,22 @@ class Capability : public Credential {
break;
case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
case ZT_NETWORK_RULE_MATCH_MAC_DEST:
memcpy(rules[ruleCount].v.mac, b.field(p, 6), 6);
memcpy(rules[ruleCount].v.mac,b.field(p,6),6);
break;
case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
memcpy(&(rules[ruleCount].v.ipv4.ip), b.field(p, 4), 4);
memcpy(&(rules[ruleCount].v.ipv4.ip),b.field(p,4),4);
rules[ruleCount].v.ipv4.mask = (uint8_t)b[p + 4];
break;
case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
memcpy(rules[ruleCount].v.ipv6.ip, b.field(p, 16), 16);
memcpy(rules[ruleCount].v.ipv6.ip,b.field(p,16),16);
rules[ruleCount].v.ipv6.mask = (uint8_t)b[p + 16];
break;
case ZT_NETWORK_RULE_MATCH_IP_TOS:
rules[ruleCount].v.ipTos.mask = (uint8_t)b[p];
rules[ruleCount].v.ipTos.value[0] = (uint8_t)b[p + 1];
rules[ruleCount].v.ipTos.value[1] = (uint8_t)b[p + 2];
rules[ruleCount].v.ipTos.value[0] = (uint8_t)b[p+1];
rules[ruleCount].v.ipTos.value[1] = (uint8_t)b[p+2];
break;
case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
rules[ruleCount].v.ipProtocol = (uint8_t)b[p];
@ -353,8 +340,8 @@ class Capability : public Credential {
break;
case ZT_NETWORK_RULE_MATCH_ICMP:
rules[ruleCount].v.icmp.type = (uint8_t)b[p];
rules[ruleCount].v.icmp.code = (uint8_t)b[p + 1];
rules[ruleCount].v.icmp.flags = (uint8_t)b[p + 2];
rules[ruleCount].v.icmp.code = (uint8_t)b[p+1];
rules[ruleCount].v.icmp.flags = (uint8_t)b[p+2];
break;
case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
@ -393,7 +380,8 @@ class Capability : public Credential {
}
}
template <unsigned int C> inline void serialize(Buffer<C>& b, const bool forSign = false) const
template<unsigned int C>
inline void serialize(Buffer<C> &b,const bool forSign = false) const
{
if (forSign) {
b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
@ -405,20 +393,19 @@ class Capability : public Credential {
b.append(_id);
b.append((uint16_t)_ruleCount);
serializeRules(b, _rules, _ruleCount);
serializeRules(b,_rules,_ruleCount);
b.append((uint8_t)_maxCustodyChainLength);
if (! forSign) {
for (unsigned int i = 0;; ++i) {
if ((i < _maxCustodyChainLength) && (i < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH) && (_custody[i].to)) {
if (!forSign) {
for(unsigned int i=0;;++i) {
if ((i < _maxCustodyChainLength)&&(i < ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)&&(_custody[i].to)) {
_custody[i].to.appendTo(b);
_custody[i].from.appendTo(b);
b.append((uint8_t)1); // 1 == Ed25519 signature
b.append((uint16_t)ZT_C25519_SIGNATURE_LEN); // length of signature
b.append(_custody[i].signature.data, ZT_C25519_SIGNATURE_LEN);
}
else {
b.append((unsigned char)0, ZT_ADDRESS_LENGTH); // zero 'to' terminates chain
b.append((uint8_t)1); // 1 == Ed25519 signature
b.append((uint16_t)ZT_C25519_SIGNATURE_LEN); // length of signature
b.append(_custody[i].signature.data,ZT_C25519_SIGNATURE_LEN);
} else {
b.append((unsigned char)0,ZT_ADDRESS_LENGTH); // zero 'to' terminates chain
break;
}
}
@ -432,7 +419,8 @@ class Capability : public Credential {
}
}
template <unsigned int C> inline unsigned int deserialize(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
{
*this = Capability();
@ -450,34 +438,33 @@ class Capability : public Credential {
if (rc > ZT_MAX_CAPABILITY_RULES) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
}
deserializeRules(b, p, _rules, _ruleCount, rc);
deserializeRules(b,p,_rules,_ruleCount,rc);
_maxCustodyChainLength = (unsigned int)b[p++];
if ((_maxCustodyChainLength < 1) || (_maxCustodyChainLength > ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
if ((_maxCustodyChainLength < 1)||(_maxCustodyChainLength > ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
}
for (unsigned int i = 0;; ++i) {
const Address to(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
for(unsigned int i=0;;++i) {
const Address to(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
if (! to) {
if (!to) {
break;
}
if ((i >= _maxCustodyChainLength) || (i >= ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
if ((i >= _maxCustodyChainLength)||(i >= ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH)) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
}
_custody[i].to = to;
_custody[i].from.setTo(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
_custody[i].from.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
if (b[p++] == 1) {
if (b.template at<uint16_t>(p) != ZT_C25519_SIGNATURE_LEN) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
}
p += 2;
memcpy(_custody[i].signature.data, b.field(p, ZT_C25519_SIGNATURE_LEN), ZT_C25519_SIGNATURE_LEN);
memcpy(_custody[i].signature.data,b.field(p,ZT_C25519_SIGNATURE_LEN),ZT_C25519_SIGNATURE_LEN);
p += ZT_C25519_SIGNATURE_LEN;
}
else {
} else {
p += 2 + b.template at<uint16_t>(p);
}
}
@ -491,21 +478,12 @@ class Capability : public Credential {
}
// Provides natural sort order by ID
inline bool operator<(const Capability& c) const
{
return (_id < c._id);
}
inline bool operator<(const Capability &c) const { return (_id < c._id); }
inline bool operator==(const Capability& c) const
{
return (memcmp(this, &c, sizeof(Capability)) == 0);
}
inline bool operator!=(const Capability& c) const
{
return (memcmp(this, &c, sizeof(Capability)) != 0);
}
inline bool operator==(const Capability &c) const { return (memcmp(this,&c,sizeof(Capability)) == 0); }
inline bool operator!=(const Capability &c) const { return (memcmp(this,&c,sizeof(Capability)) != 0); }
private:
private:
uint64_t _nwid;
int64_t _ts;
uint32_t _id;
@ -522,6 +500,6 @@ class Capability : public Credential {
} _custody[ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH];
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -12,16 +12,15 @@
/****/
#include "CertificateOfMembership.hpp"
#include "RuntimeEnvironment.hpp"
#include "Topology.hpp"
#include "Switch.hpp"
#include "Network.hpp"
#include "Node.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
namespace ZeroTier {
CertificateOfMembership::CertificateOfMembership(uint64_t timestamp, uint64_t timestampMaxDelta, uint64_t nwid, const Identity& issuedTo)
CertificateOfMembership::CertificateOfMembership(uint64_t timestamp,uint64_t timestampMaxDelta,uint64_t nwid,const Identity &issuedTo)
{
_qualifiers[0].id = COM_RESERVED_ID_TIMESTAMP;
_qualifiers[0].value = timestamp;
@ -37,34 +36,34 @@ CertificateOfMembership::CertificateOfMembership(uint64_t timestamp, uint64_t ti
// using the original COM format. Format may be revised in the future to make this cleaner.
uint64_t idHash[6];
issuedTo.publicKeyHash(idHash);
for (unsigned long i = 0; i < 4; ++i) {
for(unsigned long i=0;i<4;++i) {
_qualifiers[i + 3].id = (uint64_t)(i + 3);
_qualifiers[i + 3].value = Utils::ntoh(idHash[i]);
_qualifiers[i + 3].maxDelta = 0xffffffffffffffffULL;
}
_qualifierCount = 7;
memset(_signature.data, 0, ZT_C25519_SIGNATURE_LEN);
memset(_signature.data,0,ZT_C25519_SIGNATURE_LEN);
}
bool CertificateOfMembership::agreesWith(const CertificateOfMembership& other, const Identity& otherIdentity) const
bool CertificateOfMembership::agreesWith(const CertificateOfMembership &other, const Identity &otherIdentity) const
{
if ((_qualifierCount == 0) || (other._qualifierCount == 0)) {
if ((_qualifierCount == 0)||(other._qualifierCount == 0)) {
return false;
}
std::map<uint64_t, uint64_t> otherFields;
for (unsigned int i = 0; i < other._qualifierCount; ++i) {
std::map< uint64_t, uint64_t > otherFields;
for(unsigned int i=0;i<other._qualifierCount;++i) {
otherFields[other._qualifiers[i].id] = other._qualifiers[i].value;
}
bool fullIdentityVerification = false;
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
const uint64_t qid = _qualifiers[i].id;
if ((qid >= 3) && (qid <= 6)) {
if ((qid >= 3)&&(qid <= 6)) {
fullIdentityVerification = true;
}
std::map<uint64_t, uint64_t>::iterator otherQ(otherFields.find(qid));
std::map< uint64_t, uint64_t >::iterator otherQ(otherFields.find(qid));
if (otherQ == otherFields.end()) {
return false;
}
@ -80,8 +79,8 @@ bool CertificateOfMembership::agreesWith(const CertificateOfMembership& other, c
if (fullIdentityVerification) {
uint64_t idHash[6];
otherIdentity.publicKeyHash(idHash);
for (unsigned long i = 0; i < 4; ++i) {
std::map<uint64_t, uint64_t>::iterator otherQ(otherFields.find((uint64_t)(i + 3)));
for(unsigned long i=0;i<4;++i) {
std::map< uint64_t, uint64_t >::iterator otherQ(otherFields.find((uint64_t)(i + 3)));
if (otherQ == otherFields.end()) {
return false;
}
@ -94,47 +93,46 @@ bool CertificateOfMembership::agreesWith(const CertificateOfMembership& other, c
return true;
}
bool CertificateOfMembership::sign(const Identity& with)
bool CertificateOfMembership::sign(const Identity &with)
{
uint64_t buf[ZT_NETWORK_COM_MAX_QUALIFIERS * 3];
unsigned int ptr = 0;
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
buf[ptr++] = Utils::hton(_qualifiers[i].id);
buf[ptr++] = Utils::hton(_qualifiers[i].value);
buf[ptr++] = Utils::hton(_qualifiers[i].maxDelta);
}
try {
_signature = with.sign(buf, ptr * sizeof(uint64_t));
_signature = with.sign(buf,ptr * sizeof(uint64_t));
_signedBy = with.address();
return true;
}
catch (...) {
} catch ( ... ) {
_signedBy.zero();
return false;
}
}
int CertificateOfMembership::verify(const RuntimeEnvironment* RR, void* tPtr) const
int CertificateOfMembership::verify(const RuntimeEnvironment *RR,void *tPtr) const
{
if ((! _signedBy) || (_signedBy != Network::controllerFor(networkId())) || (_qualifierCount > ZT_NETWORK_COM_MAX_QUALIFIERS)) {
if ((!_signedBy)||(_signedBy != Network::controllerFor(networkId()))||(_qualifierCount > ZT_NETWORK_COM_MAX_QUALIFIERS)) {
return -1;
}
const Identity id(RR->topology->getIdentity(tPtr, _signedBy));
if (! id) {
RR->sw->requestWhois(tPtr, RR->node->now(), _signedBy);
const Identity id(RR->topology->getIdentity(tPtr,_signedBy));
if (!id) {
RR->sw->requestWhois(tPtr,RR->node->now(),_signedBy);
return 1;
}
uint64_t buf[ZT_NETWORK_COM_MAX_QUALIFIERS * 3];
unsigned int ptr = 0;
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
buf[ptr++] = Utils::hton(_qualifiers[i].id);
buf[ptr++] = Utils::hton(_qualifiers[i].value);
buf[ptr++] = Utils::hton(_qualifiers[i].maxDelta);
}
return (id.verify(buf, ptr * sizeof(uint64_t), _signature) ? 0 : -1);
return (id.verify(buf,ptr * sizeof(uint64_t),_signature) ? 0 : -1);
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,19 +14,20 @@
#ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP
#define ZT_CERTIFICATEOFMEMBERSHIP_HPP
#include "Address.hpp"
#include "Buffer.hpp"
#include "C25519.hpp"
#include "Constants.hpp"
#include "Credential.hpp"
#include "Identity.hpp"
#include "Utils.hpp"
#include <algorithm>
#include <stdexcept>
#include <stdint.h>
#include <string.h>
#include <string>
#include <stdexcept>
#include <algorithm>
#include "Constants.hpp"
#include "Credential.hpp"
#include "Buffer.hpp"
#include "Address.hpp"
#include "C25519.hpp"
#include "Identity.hpp"
#include "Utils.hpp"
/**
* Maximum number of qualifiers allowed in a COM (absolute max: 65535)
@ -63,12 +64,10 @@ class RuntimeEnvironment;
* This is a memcpy()'able structure and is safe (in a crash sense) to modify
* without locks.
*/
class CertificateOfMembership : public Credential {
public:
static inline Credential::Type credentialType()
{
return Credential::CREDENTIAL_TYPE_COM;
}
class CertificateOfMembership : public Credential
{
public:
static inline Credential::Type credentialType() { return Credential::CREDENTIAL_TYPE_COM; }
/**
* Reserved qualifier IDs
@ -79,7 +78,8 @@ class CertificateOfMembership : public Credential {
* Addition of new required fields requires that code in hasRequiredFields
* be updated as well.
*/
enum ReservedId {
enum ReservedId
{
/**
* Timestamp of certificate
*/
@ -101,9 +101,8 @@ class CertificateOfMembership : public Credential {
/**
* Create an empty certificate of membership
*/
CertificateOfMembership() : _qualifierCount(0)
{
}
CertificateOfMembership() :
_qualifierCount(0) {}
/**
* Create from required fields common to all networks
@ -113,7 +112,7 @@ class CertificateOfMembership : public Credential {
* @param nwid Network ID
* @param issuedTo Certificate recipient
*/
CertificateOfMembership(uint64_t timestamp, uint64_t timestampMaxDelta, uint64_t nwid, const Identity& issuedTo);
CertificateOfMembership(uint64_t timestamp,uint64_t timestampMaxDelta,uint64_t nwid,const Identity &issuedTo);
/**
* Create from binary-serialized COM in buffer
@ -121,33 +120,28 @@ class CertificateOfMembership : public Credential {
* @param b Buffer to deserialize from
* @param startAt Position to start in buffer
*/
template <unsigned int C> CertificateOfMembership(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
CertificateOfMembership(const Buffer<C> &b,unsigned int startAt = 0)
{
deserialize(b, startAt);
deserialize(b,startAt);
}
/**
* @return True if there's something here
*/
inline operator bool() const
{
return (_qualifierCount != 0);
}
inline operator bool() const { return (_qualifierCount != 0); }
/**
* @return Credential ID, always 0 for COMs
*/
inline uint32_t id() const
{
return 0;
}
inline uint32_t id() const { return 0; }
/**
* @return Timestamp for this cert and maximum delta for timestamp
*/
inline int64_t timestamp() const
{
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
if (_qualifiers[i].id == COM_RESERVED_ID_TIMESTAMP) {
return _qualifiers[i].value;
}
@ -160,7 +154,7 @@ class CertificateOfMembership : public Credential {
*/
inline Address issuedTo() const
{
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
if (_qualifiers[i].id == COM_RESERVED_ID_ISSUED_TO) {
return Address(_qualifiers[i].value);
}
@ -173,7 +167,7 @@ class CertificateOfMembership : public Credential {
*/
inline uint64_t networkId() const
{
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
if (_qualifiers[i].id == COM_RESERVED_ID_NETWORK_ID) {
return _qualifiers[i].value;
}
@ -195,7 +189,7 @@ class CertificateOfMembership : public Credential {
* @param otherIdentity Identity of other node
* @return True if certs agree and 'other' may be communicated with
*/
bool agreesWith(const CertificateOfMembership& other, const Identity& otherIdentity) const;
bool agreesWith(const CertificateOfMembership &other, const Identity &otherIdentity) const;
/**
* Sign this certificate
@ -203,7 +197,7 @@ class CertificateOfMembership : public Credential {
* @param with Identity to sign with, must include private key
* @return True if signature was successful
*/
bool sign(const Identity& with);
bool sign(const Identity &with);
/**
* Verify this COM and its signature
@ -212,40 +206,36 @@ class CertificateOfMembership : public Credential {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
*/
int verify(const RuntimeEnvironment* RR, void* tPtr) const;
int verify(const RuntimeEnvironment *RR,void *tPtr) const;
/**
* @return True if signed
*/
inline bool isSigned() const
{
return (_signedBy);
}
inline bool isSigned() const { return (_signedBy); }
/**
* @return Address that signed this certificate or null address if none
*/
inline const Address& signedBy() const
{
return _signedBy;
}
inline const Address &signedBy() const { return _signedBy; }
template <unsigned int C> inline void serialize(Buffer<C>& b) const
template<unsigned int C>
inline void serialize(Buffer<C> &b) const
{
b.append((uint8_t)1);
b.append((uint16_t)_qualifierCount);
for (unsigned int i = 0; i < _qualifierCount; ++i) {
for(unsigned int i=0;i<_qualifierCount;++i) {
b.append(_qualifiers[i].id);
b.append(_qualifiers[i].value);
b.append(_qualifiers[i].maxDelta);
}
_signedBy.appendTo(b);
if (_signedBy) {
b.append(_signature.data, ZT_C25519_SIGNATURE_LEN);
b.append(_signature.data,ZT_C25519_SIGNATURE_LEN);
}
}
template <unsigned int C> inline unsigned int deserialize(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
{
unsigned int p = startAt;
@ -259,12 +249,11 @@ class CertificateOfMembership : public Credential {
unsigned int numq = b.template at<uint16_t>(p);
p += sizeof(uint16_t);
uint64_t lastId = 0;
for (unsigned int i = 0; i < numq; ++i) {
for(unsigned int i=0;i<numq;++i) {
const uint64_t qid = b.template at<uint64_t>(p);
if (qid < lastId) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_BAD_ENCODING;
}
else {
} else {
lastId = qid;
}
if (_qualifierCount < ZT_NETWORK_COM_MAX_QUALIFIERS) {
@ -273,24 +262,23 @@ class CertificateOfMembership : public Credential {
_qualifiers[_qualifierCount].maxDelta = b.template at<uint64_t>(p + 16);
p += 24;
++_qualifierCount;
}
else {
} else {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
}
}
_signedBy.setTo(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
_signedBy.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
if (_signedBy) {
memcpy(_signature.data, b.field(p, ZT_C25519_SIGNATURE_LEN), ZT_C25519_SIGNATURE_LEN);
memcpy(_signature.data,b.field(p,ZT_C25519_SIGNATURE_LEN),ZT_C25519_SIGNATURE_LEN);
p += ZT_C25519_SIGNATURE_LEN;
}
return (p - startAt);
}
inline bool operator==(const CertificateOfMembership& c) const
inline bool operator==(const CertificateOfMembership &c) const
{
if (_signedBy != c._signedBy) {
return false;
@ -298,32 +286,25 @@ class CertificateOfMembership : public Credential {
if (_qualifierCount != c._qualifierCount) {
return false;
}
for (unsigned int i = 0; i < _qualifierCount; ++i) {
const _Qualifier& a = _qualifiers[i];
const _Qualifier& b = c._qualifiers[i];
if ((a.id != b.id) || (a.value != b.value) || (a.maxDelta != b.maxDelta)) {
for(unsigned int i=0;i<_qualifierCount;++i) {
const _Qualifier &a = _qualifiers[i];
const _Qualifier &b = c._qualifiers[i];
if ((a.id != b.id)||(a.value != b.value)||(a.maxDelta != b.maxDelta)) {
return false;
}
}
return (memcmp(_signature.data, c._signature.data, ZT_C25519_SIGNATURE_LEN) == 0);
}
inline bool operator!=(const CertificateOfMembership& c) const
{
return (! (*this == c));
return (memcmp(_signature.data,c._signature.data,ZT_C25519_SIGNATURE_LEN) == 0);
}
inline bool operator!=(const CertificateOfMembership &c) const { return (!(*this == c)); }
private:
struct _Qualifier {
_Qualifier() : id(0), value(0), maxDelta(0)
{
}
private:
struct _Qualifier
{
_Qualifier() : id(0),value(0),maxDelta(0) {}
uint64_t id;
uint64_t value;
uint64_t maxDelta;
inline bool operator<(const _Qualifier& q) const
{
return (id < q.id);
} // sort order
inline bool operator<(const _Qualifier &q) const { return (id < q.id); } // sort order
};
Address _signedBy;
@ -332,6 +313,6 @@ class CertificateOfMembership : public Credential {
C25519::Signature _signature;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -12,43 +12,41 @@
/****/
#include "CertificateOfOwnership.hpp"
#include "RuntimeEnvironment.hpp"
#include "Identity.hpp"
#include "Topology.hpp"
#include "Switch.hpp"
#include "Network.hpp"
#include "Node.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
namespace ZeroTier {
int CertificateOfOwnership::verify(const RuntimeEnvironment* RR, void* tPtr) const
int CertificateOfOwnership::verify(const RuntimeEnvironment *RR,void *tPtr) const
{
if ((! _signedBy) || (_signedBy != Network::controllerFor(_networkId))) {
if ((!_signedBy)||(_signedBy != Network::controllerFor(_networkId))) {
return -1;
}
const Identity id(RR->topology->getIdentity(tPtr, _signedBy));
if (! id) {
RR->sw->requestWhois(tPtr, RR->node->now(), _signedBy);
const Identity id(RR->topology->getIdentity(tPtr,_signedBy));
if (!id) {
RR->sw->requestWhois(tPtr,RR->node->now(),_signedBy);
return 1;
}
try {
Buffer<(sizeof(CertificateOfOwnership) + 64)> tmp;
this->serialize(tmp, true);
return (id.verify(tmp.data(), tmp.size(), _signature) ? 0 : -1);
}
catch (...) {
this->serialize(tmp,true);
return (id.verify(tmp.data(),tmp.size(),_signature) ? 0 : -1);
} catch ( ... ) {
return -1;
}
}
bool CertificateOfOwnership::_owns(const CertificateOfOwnership::Thing& t, const void* v, unsigned int l) const
bool CertificateOfOwnership::_owns(const CertificateOfOwnership::Thing &t,const void *v,unsigned int l) const
{
for (unsigned int i = 0, j = _thingCount; i < j; ++i) {
for(unsigned int i=0,j=_thingCount;i<j;++i) {
if (_thingTypes[i] == (uint8_t)t) {
unsigned int k = 0;
while (k < l) {
if (reinterpret_cast<const uint8_t*>(v)[k] != _thingValues[i][k]) {
if (reinterpret_cast<const uint8_t *>(v)[k] != _thingValues[i][k]) {
break;
}
++k;
@ -61,4 +59,4 @@ bool CertificateOfOwnership::_owns(const CertificateOfOwnership::Thing& t, const
return false;
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,20 +14,20 @@
#ifndef ZT_CERTIFICATEOFOWNERSHIP_HPP
#define ZT_CERTIFICATEOFOWNERSHIP_HPP
#include "Address.hpp"
#include "Buffer.hpp"
#include "C25519.hpp"
#include "Constants.hpp"
#include "Credential.hpp"
#include "Identity.hpp"
#include "InetAddress.hpp"
#include "MAC.hpp"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Constants.hpp"
#include "Credential.hpp"
#include "C25519.hpp"
#include "Address.hpp"
#include "Identity.hpp"
#include "Buffer.hpp"
#include "InetAddress.hpp"
#include "MAC.hpp"
// Max things per CertificateOfOwnership
#define ZT_CERTIFICATEOFOWNERSHIP_MAX_THINGS 16
@ -41,102 +41,84 @@ class RuntimeEnvironment;
/**
* Certificate indicating ownership of a network identifier
*/
class CertificateOfOwnership : public Credential {
public:
static inline Credential::Type credentialType()
{
return Credential::CREDENTIAL_TYPE_COO;
}
class CertificateOfOwnership : public Credential
{
public:
static inline Credential::Type credentialType() { return Credential::CREDENTIAL_TYPE_COO; }
enum Thing { THING_NULL = 0, THING_MAC_ADDRESS = 1, THING_IPV4_ADDRESS = 2, THING_IPV6_ADDRESS = 3 };
enum Thing
{
THING_NULL = 0,
THING_MAC_ADDRESS = 1,
THING_IPV4_ADDRESS = 2,
THING_IPV6_ADDRESS = 3
};
CertificateOfOwnership()
{
memset(reinterpret_cast<void*>(this), 0, sizeof(CertificateOfOwnership));
memset(reinterpret_cast<void *>(this),0,sizeof(CertificateOfOwnership));
}
CertificateOfOwnership(const uint64_t nwid, const int64_t ts, const Address& issuedTo, const uint32_t id)
CertificateOfOwnership(const uint64_t nwid,const int64_t ts,const Address &issuedTo,const uint32_t id)
{
memset(reinterpret_cast<void*>(this), 0, sizeof(CertificateOfOwnership));
memset(reinterpret_cast<void *>(this),0,sizeof(CertificateOfOwnership));
_networkId = nwid;
_ts = ts;
_id = id;
_issuedTo = issuedTo;
}
inline uint64_t networkId() const
{
return _networkId;
}
inline int64_t timestamp() const
{
return _ts;
}
inline uint32_t id() const
{
return _id;
}
inline unsigned int thingCount() const
{
return (unsigned int)_thingCount;
}
inline uint64_t networkId() const { return _networkId; }
inline int64_t timestamp() const { return _ts; }
inline uint32_t id() const { return _id; }
inline unsigned int thingCount() const { return (unsigned int)_thingCount; }
inline Thing thingType(const unsigned int i) const
{
return (Thing)_thingTypes[i];
}
inline const uint8_t* thingValue(const unsigned int i) const
{
return _thingValues[i];
}
inline Thing thingType(const unsigned int i) const { return (Thing)_thingTypes[i]; }
inline const uint8_t *thingValue(const unsigned int i) const { return _thingValues[i]; }
inline const Address& issuedTo() const
{
return _issuedTo;
}
inline const Address &issuedTo() const { return _issuedTo; }
inline bool owns(const InetAddress& ip) const
inline bool owns(const InetAddress &ip) const
{
if (ip.ss_family == AF_INET) {
return this->_owns(THING_IPV4_ADDRESS, &(reinterpret_cast<const struct sockaddr_in*>(&ip)->sin_addr.s_addr), 4);
return this->_owns(THING_IPV4_ADDRESS,&(reinterpret_cast<const struct sockaddr_in *>(&ip)->sin_addr.s_addr),4);
}
if (ip.ss_family == AF_INET6) {
return this->_owns(THING_IPV6_ADDRESS, reinterpret_cast<const struct sockaddr_in6*>(&ip)->sin6_addr.s6_addr, 16);
return this->_owns(THING_IPV6_ADDRESS,reinterpret_cast<const struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
}
return false;
}
inline bool owns(const MAC& mac) const
inline bool owns(const MAC &mac) const
{
uint8_t tmp[6];
mac.copyTo(tmp, 6);
return this->_owns(THING_MAC_ADDRESS, tmp, 6);
mac.copyTo(tmp,6);
return this->_owns(THING_MAC_ADDRESS,tmp,6);
}
inline void addThing(const InetAddress& ip)
inline void addThing(const InetAddress &ip)
{
if (_thingCount >= ZT_CERTIFICATEOFOWNERSHIP_MAX_THINGS) {
return;
}
if (ip.ss_family == AF_INET) {
_thingTypes[_thingCount] = THING_IPV4_ADDRESS;
memcpy(_thingValues[_thingCount], &(reinterpret_cast<const struct sockaddr_in*>(&ip)->sin_addr.s_addr), 4);
memcpy(_thingValues[_thingCount],&(reinterpret_cast<const struct sockaddr_in *>(&ip)->sin_addr.s_addr),4);
++_thingCount;
}
else if (ip.ss_family == AF_INET6) {
} else if (ip.ss_family == AF_INET6) {
_thingTypes[_thingCount] = THING_IPV6_ADDRESS;
memcpy(_thingValues[_thingCount], reinterpret_cast<const struct sockaddr_in6*>(&ip)->sin6_addr.s6_addr, 16);
memcpy(_thingValues[_thingCount],reinterpret_cast<const struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
++_thingCount;
}
}
inline void addThing(const MAC& mac)
inline void addThing(const MAC &mac)
{
if (_thingCount >= ZT_CERTIFICATEOFOWNERSHIP_MAX_THINGS) {
return;
}
_thingTypes[_thingCount] = THING_MAC_ADDRESS;
mac.copyTo(_thingValues[_thingCount], 6);
mac.copyTo(_thingValues[_thingCount],6);
++_thingCount;
}
@ -144,13 +126,13 @@ class CertificateOfOwnership : public Credential {
* @param signer Signing identity, must have private key
* @return True if signature was successful
*/
inline bool sign(const Identity& signer)
inline bool sign(const Identity &signer)
{
if (signer.hasPrivate()) {
Buffer<sizeof(CertificateOfOwnership) + 64> tmp;
_signedBy = signer.address();
this->serialize(tmp, true);
_signature = signer.sign(tmp.data(), tmp.size());
this->serialize(tmp,true);
_signature = signer.sign(tmp.data(),tmp.size());
return true;
}
return false;
@ -161,9 +143,10 @@ class CertificateOfOwnership : public Credential {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature
*/
int verify(const RuntimeEnvironment* RR, void* tPtr) const;
int verify(const RuntimeEnvironment *RR,void *tPtr) const;
template <unsigned int C> inline void serialize(Buffer<C>& b, const bool forSign = false) const
template<unsigned int C>
inline void serialize(Buffer<C> &b,const bool forSign = false) const
{
if (forSign) {
b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
@ -174,27 +157,28 @@ class CertificateOfOwnership : public Credential {
b.append(_flags);
b.append(_id);
b.append((uint16_t)_thingCount);
for (unsigned int i = 0, j = _thingCount; i < j; ++i) {
for(unsigned int i=0,j=_thingCount;i<j;++i) {
b.append((uint8_t)_thingTypes[i]);
b.append(_thingValues[i], ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE);
b.append(_thingValues[i],ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE);
}
_issuedTo.appendTo(b);
_signedBy.appendTo(b);
if (! forSign) {
b.append((uint8_t)1); // 1 == Ed25519
b.append((uint16_t)ZT_C25519_SIGNATURE_LEN); // length of signature
b.append(_signature.data, ZT_C25519_SIGNATURE_LEN);
if (!forSign) {
b.append((uint8_t)1); // 1 == Ed25519
b.append((uint16_t)ZT_C25519_SIGNATURE_LEN); // length of signature
b.append(_signature.data,ZT_C25519_SIGNATURE_LEN);
}
b.append((uint16_t)0); // length of additional fields, currently 0
b.append((uint16_t)0); // length of additional fields, currently 0
if (forSign) {
b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
}
}
template <unsigned int C> inline unsigned int deserialize(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
{
unsigned int p = startAt;
@ -210,27 +194,26 @@ class CertificateOfOwnership : public Credential {
p += 4;
_thingCount = b.template at<uint16_t>(p);
p += 2;
for (unsigned int i = 0, j = _thingCount; i < j; ++i) {
for(unsigned int i=0,j=_thingCount;i<j;++i) {
if (i < ZT_CERTIFICATEOFOWNERSHIP_MAX_THINGS) {
_thingTypes[i] = (uint8_t)b[p++];
memcpy(_thingValues[i], b.field(p, ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE), ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE);
memcpy(_thingValues[i],b.field(p,ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE),ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE);
p += ZT_CERTIFICATEOFOWNERSHIP_MAX_THING_VALUE_SIZE;
}
}
_issuedTo.setTo(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
_issuedTo.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
_signedBy.setTo(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
_signedBy.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
if (b[p++] == 1) {
if (b.template at<uint16_t>(p) != ZT_C25519_SIGNATURE_LEN) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
}
p += 2;
memcpy(_signature.data, b.field(p, ZT_C25519_SIGNATURE_LEN), ZT_C25519_SIGNATURE_LEN);
memcpy(_signature.data,b.field(p,ZT_C25519_SIGNATURE_LEN),ZT_C25519_SIGNATURE_LEN);
p += ZT_C25519_SIGNATURE_LEN;
}
else {
} else {
p += 2 + b.template at<uint16_t>(p);
}
@ -243,22 +226,13 @@ class CertificateOfOwnership : public Credential {
}
// Provides natural sort order by ID
inline bool operator<(const CertificateOfOwnership& coo) const
{
return (_id < coo._id);
}
inline bool operator<(const CertificateOfOwnership &coo) const { return (_id < coo._id); }
inline bool operator==(const CertificateOfOwnership& coo) const
{
return (memcmp(this, &coo, sizeof(CertificateOfOwnership)) == 0);
}
inline bool operator!=(const CertificateOfOwnership& coo) const
{
return (memcmp(this, &coo, sizeof(CertificateOfOwnership)) != 0);
}
inline bool operator==(const CertificateOfOwnership &coo) const { return (memcmp(this,&coo,sizeof(CertificateOfOwnership)) == 0); }
inline bool operator!=(const CertificateOfOwnership &coo) const { return (memcmp(this,&coo,sizeof(CertificateOfOwnership)) != 0); }
private:
bool _owns(const Thing& t, const void* v, unsigned int l) const;
private:
bool _owns(const Thing &t,const void *v,unsigned int l) const;
uint64_t _networkId;
int64_t _ts;
@ -272,6 +246,6 @@ class CertificateOfOwnership : public Credential {
C25519::Signature _signature;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -61,8 +61,8 @@
#ifdef ZT_SSO_SUPPORTED
#define ZT_SSO_ENABLED 1
#endif
#define likely(x) __builtin_expect((x), 1)
#define unlikely(x) __builtin_expect((x), 0)
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
#include <TargetConditionals.h>
#ifndef __UNIX_LIKE__
#define __UNIX_LIKE__
@ -85,9 +85,9 @@
#endif
#include <machine/endian.h>
#ifndef __BYTE_ORDER
#define __BYTE_ORDER _BYTE_ORDER
#define __BYTE_ORDER _BYTE_ORDER
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
#endif
#endif
@ -106,25 +106,25 @@
#pragma warning(disable : 4101)
#undef __UNIX_LIKE__
#undef __BSD__
#include <windows.h>
#include <winsock2.h>
#include <windows.h>
#endif
#ifdef __NetBSD__
#ifndef RTF_MULTICAST
#define RTF_MULTICAST 0x20000000
#define RTF_MULTICAST 0x20000000
#endif
#endif
#if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
#define ZT_ARCH_X64 1
#include <xmmintrin.h>
#include <emmintrin.h>
#include <immintrin.h>
#include <xmmintrin.h>
#endif
#if (defined(__ARM_NEON) || defined(__ARM_NEON__) || defined(ZT_ARCH_ARM_HAS_NEON))
#if (defined(__APPLE__) && ! defined(__LP64__)) || (defined(__ANDROID__) && defined(__arm__))
#if (defined(__APPLE__) && !defined(__LP64__)) || (defined(__ANDROID__) && defined(__arm__))
#ifdef ZT_ARCH_ARM_HAS_NEON
#undef ZT_ARCH_ARM_HAS_NEON
#endif
@ -145,8 +145,7 @@
#endif
// Define ZT_NO_TYPE_PUNNING to disable reckless casts on anything other than x86/x64.
#if (! (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) \
|| defined(__i686__) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__I86__) || defined(__INTEL__) || defined(__386)))
#if (!(defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__I86__) || defined(__INTEL__) || defined(__386)))
#ifndef ZT_NO_TYPE_PUNNING
#define ZT_NO_TYPE_PUNNING 1
#endif
@ -158,23 +157,23 @@
#endif
// Assume little endian if not defined
#if (defined(__APPLE__) || defined(__WINDOWS__)) && (! defined(__BYTE_ORDER))
#if (defined(__APPLE__) || defined(__WINDOWS__)) && (!defined(__BYTE_ORDER))
#undef __BYTE_ORDER
#undef __LITTLE_ENDIAN
#undef __BIG_ENDIAN
#define __BIG_ENDIAN 4321
#define __BIG_ENDIAN 4321
#define __LITTLE_ENDIAN 1234
#define __BYTE_ORDER 1234
#define __BYTE_ORDER 1234
#endif
#ifdef __WINDOWS__
#define ZT_PATH_SEPARATOR '\\'
#define ZT_PATH_SEPARATOR '\\'
#define ZT_PATH_SEPARATOR_S "\\"
#define ZT_EOL_S "\r\n"
#define ZT_EOL_S "\r\n"
#else
#define ZT_PATH_SEPARATOR '/'
#define ZT_PATH_SEPARATOR '/'
#define ZT_PATH_SEPARATOR_S "/"
#define ZT_EOL_S "\n"
#define ZT_EOL_S "\n"
#endif
#ifndef __BYTE_ORDER
@ -183,10 +182,10 @@
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
#ifndef likely
#define likely(x) __builtin_expect((x), 1)
#define likely(x) __builtin_expect((x),1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect((x), 0)
#define unlikely(x) __builtin_expect((x),0)
#endif
#else
#ifndef likely
@ -198,77 +197,11 @@
#endif
#ifdef __WINDOWS__
#define ZT_PACKED_STRUCT(D) __pragma(pack(push, 1)) D __pragma(pack(pop))
#define ZT_PACKED_STRUCT(D) __pragma(pack(push,1)) D __pragma(pack(pop))
#else
#define ZT_PACKED_STRUCT(D) D __attribute__((packed))
#endif
#if defined(_WIN32)
#define ZT_PLATFORM_NAME "windows" // Windows
#elif defined(_WIN64)
#define ZT_PLATFORM_NAME "windows" // Windows
#elif defined(__CYGWIN__)
#define ZT_PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)
#elif defined(__ANDROID__)
#define ZT_PLATFORM_NAME "android" // Android (implies Linux, so it must come first)
#elif defined(__linux__)
#define ZT_PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other
#elif defined(__unix__) || ! defined(__APPLE__) && defined(__MACH__)
#include <sys/param.h>
#if defined(BSD)
#define ZT_PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
#endif
#elif defined(__hpux)
#define ZT_PLATFORM_NAME "hp-ux" // HP-UX
#elif defined(_AIX)
#define ZT_PLATFORM_NAME "aix" // IBM AIX
#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
#include <TargetConditionals.h>
#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR == 1
#define ZT_PLATFORM_NAME "ios_sim" // Apple iOS
#elif defined(TARGET_OS_IPAD) && TARGET_OS_IPAD == 1
#define ZT_PLATFORM_NAME "ios_ipad"
#elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1
#define ZT_PLATFORM_NAME "ios_iphone" // Apple iOS
#elif defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1
#define ZT_PLATFORM_NAME "macos" // Apple OSX
#endif
#elif defined(__sun) && defined(__SVR4)
#define ZT_PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana
#else
#define ZT_PLATFORM_NAME "unknown"
#endif
#ifndef ZT_PLATFORM_NAME
#define ZT_PLATFORM_NAME "unknown"
#endif
#if defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64) || defined(_M_AMD64)
#define ZT_ARCH_NAME "x86_64"
#elif defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_X86_) || defined(_M_IX86) || defined(__X86__) || defined(__I86__) || defined(_M_I86)
#define ZT_ARCH_NAME "x86"
#elif defined(__aarch64__) || defined(__AARCH64EL__) || defined(_M_ARM64)
#define ZT_ARCH_NAME "arm64"
#elif defined(__arm__) || defined(__TARGET_ARCH_ARM) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm) || defined(__thumb__)
#define ZT_ARCH_NAME "arm"
#elif defined(__loongarch__) || defined(_LOONGARCH_ARCH)
#define ZT_ARCH_NAME "loongarch"
#elif defined(__mips__) || defined(__MIPS__)
#define ZT_ARCH_NAME "mips"
#elif defined(__riscv) || defined(__riscv_xlen)
#define ZT_ARCH_NAME "riscv"
#elif defined(__powerpc__) || defined(__powerpc64__) || defined(__ppc__) || defined(__ppc64__) || defined(_M_PPC)
#define ZT_ARCH_NAME "powerpc"
#elif defined(__s390__) || defined(__s390x__) || defined(__zarch__)
#define ZT_ARCH_NAME "s390"
#else
#define ZT_ARCH_NAME "unknown"
#endif
#ifndef ZT_ARCH_NAME
#define ZT_ARCH_NAME "unknown"
#endif
#define ZT_TARGET_NAME (ZT_PLATFORM_NAME "/" ZT_ARCH_NAME)
/**
* Length of a ZeroTier address in bytes
*/
@ -466,11 +399,6 @@
*/
#define ZT_QOS_SHORTTERM_SAMPLE_WIN_SIZE 64
/**
* Number of samples required before statistics summaries are computed
*/
#define ZT_QOS_SHORTTERM_SAMPLE_WIN_MIN_REQ_SIZE 4
/**
* Max allowable time spent in any queue (in ms)
*/
@ -581,23 +509,23 @@
/**
* Drainage constants for VERB_ECHO rate-limiters
*/
#define ZT_ECHO_CUTOFF_LIMIT ((1000 / ZT_CORE_TIMER_TASK_GRANULARITY) * ZT_MAX_PEER_NETWORK_PATHS)
#define ZT_ECHO_CUTOFF_LIMIT ((1000 / ZT_CORE_TIMER_TASK_GRANULARITY) * ZT_MAX_PEER_NETWORK_PATHS)
#define ZT_ECHO_DRAINAGE_DIVISOR (1000 / ZT_ECHO_CUTOFF_LIMIT)
/**
* Drainage constants for VERB_QOS rate-limiters
*/
#define ZT_QOS_CUTOFF_LIMIT ((1000 / ZT_CORE_TIMER_TASK_GRANULARITY) * ZT_MAX_PEER_NETWORK_PATHS)
#define ZT_QOS_CUTOFF_LIMIT ((1000 / ZT_CORE_TIMER_TASK_GRANULARITY) * ZT_MAX_PEER_NETWORK_PATHS)
#define ZT_QOS_DRAINAGE_DIVISOR (1000 / ZT_QOS_CUTOFF_LIMIT)
/**
* Drainage constants for VERB_ACK rate-limiters
*/
#define ZT_ACK_CUTOFF_LIMIT 128
#define ZT_ACK_CUTOFF_LIMIT 128
#define ZT_ACK_DRAINAGE_DIVISOR (1000 / ZT_ACK_CUTOFF_LIMIT)
#define ZT_BOND_DEFAULT_REFRACTORY_PERIOD 8000
#define ZT_BOND_MAX_REFRACTORY_PERIOD 600000
#define ZT_BOND_MAX_REFRACTORY_PERIOD 600000
/**
* Maximum number of direct path pushes within cutoff time
@ -633,6 +561,7 @@
*/
#define ZT_PEER_GENERAL_RATE_LIMIT 1000
/**
* Minimum allowed amount of time between flow/path optimizations (anti-flapping)
*/
@ -709,8 +638,8 @@
* Artificially inflates the failover score for paths which meet
* certain non-performance-related policy ranking criteria.
*/
#define ZT_BOND_FAILOVER_HANDICAP_PREFERRED 500
#define ZT_BOND_FAILOVER_HANDICAP_PRIMARY 1000
#define ZT_BOND_FAILOVER_HANDICAP_PREFERRED 500
#define ZT_BOND_FAILOVER_HANDICAP_PRIMARY 1000
#define ZT_BOND_FAILOVER_HANDICAP_NEGOTIATED 5000
/**
@ -754,14 +683,14 @@
#define ZT_THREAD_MIN_STACK_SIZE 1048576
// Exceptions thrown in core ZT code
#define ZT_EXCEPTION_OUT_OF_BOUNDS 100
#define ZT_EXCEPTION_OUT_OF_MEMORY 101
#define ZT_EXCEPTION_PRIVATE_KEY_REQUIRED 102
#define ZT_EXCEPTION_INVALID_ARGUMENT 103
#define ZT_EXCEPTION_INVALID_IDENTITY 104
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE 200
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW 201
#define ZT_EXCEPTION_OUT_OF_BOUNDS 100
#define ZT_EXCEPTION_OUT_OF_MEMORY 101
#define ZT_EXCEPTION_PRIVATE_KEY_REQUIRED 102
#define ZT_EXCEPTION_INVALID_ARGUMENT 103
#define ZT_EXCEPTION_INVALID_IDENTITY 104
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE 200
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW 201
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN 202
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_BAD_ENCODING 203
#define ZT_EXCEPTION_INVALID_SERIALIZED_DATA_BAD_ENCODING 203
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,36 +14,39 @@
#ifndef ZT_CREDENTIAL_HPP
#define ZT_CREDENTIAL_HPP
#include "Constants.hpp"
#include <string>
#include <memory>
#include <stdexcept>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <string>
#include "Constants.hpp"
namespace ZeroTier {
/**
* Base class for credentials
*/
class Credential {
public:
class Credential
{
public:
/**
* Do not change type code IDs -- these are used in Revocation objects and elsewhere
*/
enum Type {
enum Type
{
CREDENTIAL_TYPE_NULL = 0,
CREDENTIAL_TYPE_COM = 1, // CertificateOfMembership
CREDENTIAL_TYPE_COM = 1, // CertificateOfMembership
CREDENTIAL_TYPE_CAPABILITY = 2,
CREDENTIAL_TYPE_TAG = 3,
CREDENTIAL_TYPE_COO = 4, // CertificateOfOwnership
CREDENTIAL_TYPE_COO = 4, // CertificateOfOwnership
CREDENTIAL_TYPE_REVOCATION = 6
};
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -13,43 +13,45 @@
#ifndef ZT_DNS_HPP
#define ZT_DNS_HPP
#include "../include/ZeroTierOne.h"
#include "Buffer.hpp"
#include "InetAddress.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Buffer.hpp"
#include "InetAddress.hpp"
#include "../include/ZeroTierOne.h"
namespace ZeroTier {
/**
* DNS data serialization methods
*/
class DNS {
public:
template <unsigned int C> static inline void serializeDNS(Buffer<C>& b, const ZT_VirtualNetworkDNS* dns)
{
b.append(dns->domain, 128);
for (unsigned int j = 0; j < ZT_MAX_DNS_SERVERS; ++j) {
InetAddress tmp(dns->server_addr[j]);
tmp.serialize(b);
}
}
public:
template<unsigned int C>
static inline void serializeDNS(Buffer<C> &b, const ZT_VirtualNetworkDNS *dns)
{
b.append(dns->domain, 128);
for(unsigned int j = 0; j < ZT_MAX_DNS_SERVERS; ++j) {
InetAddress tmp(dns->server_addr[j]);
tmp.serialize(b);
}
}
template <unsigned int C> static inline void deserializeDNS(const Buffer<C>& b, unsigned int& p, ZT_VirtualNetworkDNS* dns)
{
char* d = (char*)b.data() + p;
memset(dns, 0, sizeof(ZT_VirtualNetworkDNS));
memcpy(dns->domain, d, 128);
dns->domain[127] = 0;
p += 128;
for (unsigned int j = 0; j < ZT_MAX_DNS_SERVERS; ++j) {
p += reinterpret_cast<InetAddress*>(&(dns->server_addr[j]))->deserialize(b, p);
}
}
template<unsigned int C>
static inline void deserializeDNS(const Buffer<C> &b, unsigned int &p, ZT_VirtualNetworkDNS *dns)
{
char *d = (char*)b.data()+p;
memset(dns, 0, sizeof(ZT_VirtualNetworkDNS));
memcpy(dns->domain, d, 128);
dns->domain[127] = 0;
p += 128;
for (unsigned int j = 0; j < ZT_MAX_DNS_SERVERS; ++j) {
p += reinterpret_cast<InetAddress *>(&(dns->server_addr[j]))->deserialize(b, p);
}
}
};
} // namespace ZeroTier
}
#endif // ZT_DNS_HPP
#endif // ZT_DNS_HPP

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,10 +14,10 @@
#ifndef ZT_DICTIONARY_HPP
#define ZT_DICTIONARY_HPP
#include "Address.hpp"
#include "Buffer.hpp"
#include "Constants.hpp"
#include "Utils.hpp"
#include "Buffer.hpp"
#include "Address.hpp"
#include <stdint.h>
@ -45,48 +45,36 @@ namespace ZeroTier {
*
* @tparam C Dictionary max capacity in bytes
*/
template <unsigned int C> class Dictionary {
public:
Dictionary()
template<unsigned int C>
class Dictionary
{
public:
Dictionary() { memset(_d,0,sizeof(_d)); }
Dictionary(const char *s) { this->load(s); }
Dictionary(const char *s,unsigned int len)
{
memset(_d, 0, sizeof(_d));
}
Dictionary(const char* s)
{
this->load(s);
}
Dictionary(const char* s, unsigned int len)
{
for (unsigned int i = 0; i < C; ++i) {
if ((s) && (i < len)) {
if (! (_d[i] = *s)) {
s = (const char*)0;
}
else {
for(unsigned int i=0;i<C;++i) {
if ((s)&&(i < len)) {
if (!(_d[i] = *s)) {
s = (const char *)0;
} else {
++s;
}
}
else {
} else {
_d[i] = (char)0;
}
}
_d[C - 1] = (char)0;
}
Dictionary(const Dictionary& d)
{
memcpy(_d, d._d, C);
}
Dictionary(const Dictionary &d) { memcpy(_d,d._d,C); }
inline Dictionary& operator=(const Dictionary& d)
inline Dictionary &operator=(const Dictionary &d)
{
memcpy(_d, d._d, C);
memcpy(_d,d._d,C);
return *this;
}
inline operator bool() const
{
return (_d[0] != 0);
}
inline operator bool() const { return (_d[0] != 0); }
/**
* Load a dictionary from a C-string
@ -94,23 +82,21 @@ template <unsigned int C> class Dictionary {
* @param s Dictionary in string form
* @return False if 's' was longer than our capacity
*/
inline bool load(const char* s)
inline bool load(const char *s)
{
for (unsigned int i = 0; i < C; ++i) {
for(unsigned int i=0;i<C;++i) {
if (s) {
if (! (_d[i] = *s)) {
s = (const char*)0;
}
else {
if (!(_d[i] = *s)) {
s = (const char *)0;
} else {
++s;
}
}
else {
} else {
_d[i] = (char)0;
}
}
_d[C - 1] = (char)0;
return (! s);
return (!s);
}
/**
@ -118,7 +104,7 @@ template <unsigned int C> class Dictionary {
*/
inline void clear()
{
memset(_d, 0, sizeof(_d));
memset(_d,0,sizeof(_d));
}
/**
@ -126,12 +112,12 @@ template <unsigned int C> class Dictionary {
*/
inline unsigned int sizeBytes() const
{
for (unsigned int i = 0; i < C; ++i) {
if (! _d[i]) {
for(unsigned int i=0;i<C;++i) {
if (!_d[i]) {
return i;
}
}
return C - 1;
return C-1;
}
/**
@ -156,21 +142,21 @@ template <unsigned int C> class Dictionary {
* @param destlen Size of destination buffer
* @return -1 if not found, or actual number of bytes stored in dest[] minus trailing 0
*/
inline int get(const char* key, char* dest, unsigned int destlen) const
inline int get(const char *key,char *dest,unsigned int destlen) const
{
const char* p = _d;
const char* const eof = p + C;
const char* k;
const char *p = _d;
const char *const eof = p + C;
const char *k;
bool esc;
int j;
if (! destlen) { // sanity check
if (!destlen) { // sanity check
return -1;
}
while (*p) {
k = key;
while ((*k) && (*p)) {
while ((*k)&&(*p)) {
if (*p != *k) {
break;
}
@ -181,14 +167,14 @@ template <unsigned int C> class Dictionary {
}
}
if ((! *k) && (*p == '=')) {
if ((!*k)&&(*p == '=')) {
j = 0;
esc = false;
++p;
while ((*p != 0) && (*p != 13) && (*p != 10)) {
while ((*p != 0)&&(*p != 13)&&(*p != 10)) {
if (esc) {
esc = false;
switch (*p) {
switch(*p) {
case 'r':
dest[j++] = 13;
break;
@ -206,18 +192,16 @@ template <unsigned int C> class Dictionary {
break;
}
if (j == (int)destlen) {
dest[j - 1] = (char)0;
return j - 1;
dest[j-1] = (char)0;
return j-1;
}
}
else if (*p == '\\') {
} else if (*p == '\\') {
esc = true;
}
else {
} else {
dest[j++] = *p;
if (j == (int)destlen) {
dest[j - 1] = (char)0;
return j - 1;
dest[j-1] = (char)0;
return j-1;
}
}
if (++p == eof) {
@ -227,9 +211,8 @@ template <unsigned int C> class Dictionary {
}
dest[j] = (char)0;
return j;
}
else {
while ((*p) && (*p != 13) && (*p != 10)) {
} else {
while ((*p)&&(*p != 13)&&(*p != 10)) {
if (++p == eof) {
dest[0] = (char)0;
return -1;
@ -240,8 +223,7 @@ template <unsigned int C> class Dictionary {
dest[0] = (char)0;
return -1;
}
}
else {
} else {
break;
}
}
@ -259,14 +241,14 @@ template <unsigned int C> class Dictionary {
* @return True if key was found (if false, dest will be empty)
* @tparam BC Buffer capacity (usually inferred)
*/
template <unsigned int BC> inline bool get(const char* key, Buffer<BC>& dest) const
template<unsigned int BC>
inline bool get(const char *key,Buffer<BC> &dest) const
{
const int r = this->get(key, const_cast<char*>(reinterpret_cast<const char*>(dest.data())), BC);
const int r = this->get(key,const_cast<char *>(reinterpret_cast<const char *>(dest.data())),BC);
if (r >= 0) {
dest.setSize((unsigned int)r);
return true;
}
else {
} else {
dest.clear();
return false;
}
@ -279,11 +261,11 @@ template <unsigned int C> class Dictionary {
* @param dfl Default value if not found in dictionary
* @return Boolean value of key or 'dfl' if not found
*/
bool getB(const char* key, bool dfl = false) const
bool getB(const char *key,bool dfl = false) const
{
char tmp[4];
if (this->get(key, tmp, sizeof(tmp)) >= 0) {
return ((*tmp == '1') || (*tmp == 't') || (*tmp == 'T'));
if (this->get(key,tmp,sizeof(tmp)) >= 0) {
return ((*tmp == '1')||(*tmp == 't')||(*tmp == 'T'));
}
return dfl;
}
@ -295,10 +277,10 @@ template <unsigned int C> class Dictionary {
* @param dfl Default value or 0 if unspecified
* @return Decoded hex UInt value or 'dfl' if not found
*/
inline uint64_t getUI(const char* key, uint64_t dfl = 0) const
inline uint64_t getUI(const char *key,uint64_t dfl = 0) const
{
char tmp[128];
if (this->get(key, tmp, sizeof(tmp)) >= 1) {
if (this->get(key,tmp,sizeof(tmp)) >= 1) {
return Utils::hexStrToU64(tmp);
}
return dfl;
@ -311,10 +293,10 @@ template <unsigned int C> class Dictionary {
* @param dfl Default value or 0 if unspecified
* @return Decoded hex UInt value or 'dfl' if not found
*/
inline int64_t getI(const char* key, int64_t dfl = 0) const
inline int64_t getI(const char *key,int64_t dfl = 0) const
{
char tmp[128];
if (this->get(key, tmp, sizeof(tmp)) >= 1) {
if (this->get(key,tmp,sizeof(tmp)) >= 1) {
return Utils::hexStrTo64(tmp);
}
return dfl;
@ -334,10 +316,10 @@ template <unsigned int C> class Dictionary {
* @param vlen Length of value in bytes or -1 to treat value[] as a C-string and look for terminating 0
* @return True if there was enough room to add this key=value pair
*/
inline bool add(const char* key, const char* value, int vlen = -1)
inline bool add(const char *key,const char *value,int vlen = -1)
{
for (unsigned int i = 0; i < C; ++i) {
if (! _d[i]) {
for(unsigned int i=0;i<C;++i) {
if (!_d[i]) {
unsigned int j = i;
if (j > 0) {
@ -348,7 +330,7 @@ template <unsigned int C> class Dictionary {
}
}
const char* p = key;
const char *p = key;
while (*p) {
_d[j++] = *(p++);
if (j == C) {
@ -365,8 +347,8 @@ template <unsigned int C> class Dictionary {
p = value;
int k = 0;
while (((vlen < 0) && (*p)) || (k < vlen)) {
switch (*p) {
while ( ((vlen < 0)&&(*p)) || (k < vlen) ) {
switch(*p) {
case 0:
case 13:
case 10:
@ -377,7 +359,7 @@ template <unsigned int C> class Dictionary {
_d[i] = (char)0;
return false;
}
switch (*p) {
switch(*p) {
case 0:
_d[j++] = '0';
break;
@ -422,42 +404,41 @@ template <unsigned int C> class Dictionary {
/**
* Add a boolean as a '1' or a '0'
*/
inline bool add(const char* key, bool value)
inline bool add(const char *key,bool value)
{
return this->add(key, (value) ? "1" : "0", 1);
return this->add(key,(value) ? "1" : "0",1);
}
/**
* Add a 64-bit integer (unsigned) as a hex value
*/
inline bool add(const char* key, uint64_t value)
inline bool add(const char *key,uint64_t value)
{
char tmp[32];
return this->add(key, Utils::hex(value, tmp), -1);
return this->add(key,Utils::hex(value,tmp),-1);
}
/**
* Add a 64-bit integer (unsigned) as a hex value
*/
inline bool add(const char* key, int64_t value)
inline bool add(const char *key,int64_t value)
{
char tmp[32];
if (value >= 0) {
return this->add(key, Utils::hex((uint64_t)value, tmp), -1);
}
else {
return this->add(key,Utils::hex((uint64_t)value,tmp),-1);
} else {
tmp[0] = '-';
return this->add(key, Utils::hex((uint64_t)(value * -1), tmp + 1), -1);
return this->add(key,Utils::hex((uint64_t)(value * -1),tmp+1),-1);
}
}
/**
* Add a 64-bit integer (unsigned) as a hex value
*/
inline bool add(const char* key, const Address& a)
inline bool add(const char *key,const Address &a)
{
char tmp[32];
return this->add(key, Utils::hex(a.toInt(), tmp), -1);
return this->add(key,Utils::hex(a.toInt(),tmp),-1);
}
/**
@ -465,42 +446,34 @@ template <unsigned int C> class Dictionary {
*
* @tparam BC Buffer capacity (usually inferred)
*/
template <unsigned int BC> inline bool add(const char* key, const Buffer<BC>& value)
template<unsigned int BC>
inline bool add(const char *key,const Buffer<BC> &value)
{
return this->add(key, (const char*)value.data(), (int)value.size());
return this->add(key,(const char *)value.data(),(int)value.size());
}
/**
* @param key Key to check
* @return True if key is present
*/
inline bool contains(const char* key) const
inline bool contains(const char *key) const
{
char tmp[2];
return (this->get(key, tmp, 2) >= 0);
return (this->get(key,tmp,2) >= 0);
}
/**
* @return Value of C template parameter
*/
inline unsigned int capacity() const
{
return C;
}
inline unsigned int capacity() const { return C; }
inline const char* data() const
{
return _d;
}
inline char* unsafeData()
{
return _d;
}
inline const char *data() const { return _d; }
inline char *unsafeData() { return _d; }
private:
private:
char _d[C];
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -16,43 +16,36 @@
#include "Constants.hpp"
#include <algorithm>
#include <stdexcept>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <utility>
#include <stdexcept>
#include <vector>
#include <utility>
#include <algorithm>
namespace ZeroTier {
/**
* A minimal hash table implementation for the ZeroTier core
*/
template <typename K, typename V> class Hashtable {
private:
struct _Bucket {
_Bucket(const K& k, const V& v) : k(k), v(v)
{
}
_Bucket(const K& k) : k(k), v()
{
}
_Bucket(const _Bucket& b) : k(b.k), v(b.v)
{
}
inline _Bucket& operator=(const _Bucket& b)
{
k = b.k;
v = b.v;
return *this;
}
template<typename K,typename V>
class Hashtable
{
private:
struct _Bucket
{
_Bucket(const K &k,const V &v) : k(k),v(v) {}
_Bucket(const K &k) : k(k),v() {}
_Bucket(const _Bucket &b) : k(b.k),v(b.v) {}
inline _Bucket &operator=(const _Bucket &b) { k = b.k; v = b.v; return *this; }
K k;
V v;
_Bucket* next; // must be set manually for each _Bucket
_Bucket *next; // must be set manually for each _Bucket
};
public:
public:
/**
* A simple forward iterator (different from STL)
*
@ -60,12 +53,16 @@ template <typename K, typename V> class Hashtable {
* may rehash and invalidate the iterator. Note the erasing the key will destroy
* the targets of the pointers returned by next().
*/
class Iterator {
public:
class Iterator
{
public:
/**
* @param ht Hash table to iterate over
*/
Iterator(Hashtable& ht) : _idx(0), _ht(&ht), _b(ht._t[0])
Iterator(Hashtable &ht) :
_idx(0),
_ht(&ht),
_b(ht._t[0])
{
}
@ -74,9 +71,9 @@ template <typename K, typename V> class Hashtable {
* @param vptr Pointer to set to point to next value
* @return True if kptr and vptr are set, false if no more entries
*/
inline bool next(K*& kptr, V*& vptr)
inline bool next(K *&kptr,V *&vptr)
{
for (;;) {
for(;;) {
if (_b) {
kptr = &(_b->k);
vptr = &(_b->v);
@ -91,38 +88,44 @@ template <typename K, typename V> class Hashtable {
}
}
private:
private:
unsigned long _idx;
Hashtable* _ht;
_Bucket* _b;
Hashtable *_ht;
_Bucket *_b;
};
// friend class Hashtable<K,V>::Iterator;
//friend class Hashtable<K,V>::Iterator;
/**
* @param bc Initial capacity in buckets (default: 64, must be nonzero)
*/
Hashtable(unsigned long bc = 64) : _t(reinterpret_cast<_Bucket**>(::malloc(sizeof(_Bucket*) * bc))), _bc(bc), _s(0)
Hashtable(unsigned long bc = 64) :
_t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * bc))),
_bc(bc),
_s(0)
{
if (! _t) {
if (!_t) {
throw ZT_EXCEPTION_OUT_OF_MEMORY;
}
for (unsigned long i = 0; i < bc; ++i) {
_t[i] = (_Bucket*)0;
for(unsigned long i=0;i<bc;++i) {
_t[i] = (_Bucket *)0;
}
}
Hashtable(const Hashtable<K, V>& ht) : _t(reinterpret_cast<_Bucket**>(::malloc(sizeof(_Bucket*) * ht._bc))), _bc(ht._bc), _s(ht._s)
Hashtable(const Hashtable<K,V> &ht) :
_t(reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * ht._bc))),
_bc(ht._bc),
_s(ht._s)
{
if (! _t) {
if (!_t) {
throw ZT_EXCEPTION_OUT_OF_MEMORY;
}
for (unsigned long i = 0; i < _bc; ++i) {
_t[i] = (_Bucket*)0;
for(unsigned long i=0;i<_bc;++i) {
_t[i] = (_Bucket *)0;
}
for (unsigned long i = 0; i < _bc; ++i) {
const _Bucket* b = ht._t[i];
for(unsigned long i=0;i<_bc;++i) {
const _Bucket *b = ht._t[i];
while (b) {
_Bucket* nb = new _Bucket(*b);
_Bucket *nb = new _Bucket(*b);
nb->next = _t[i];
_t[i] = nb;
b = b->next;
@ -136,14 +139,14 @@ template <typename K, typename V> class Hashtable {
::free(_t);
}
inline Hashtable& operator=(const Hashtable<K, V>& ht)
inline Hashtable &operator=(const Hashtable<K,V> &ht)
{
this->clear();
if (ht._s) {
for (unsigned long i = 0; i < ht._bc; ++i) {
const _Bucket* b = ht._t[i];
for(unsigned long i=0;i<ht._bc;++i) {
const _Bucket *b = ht._t[i];
while (b) {
this->set(b->k, b->v);
this->set(b->k,b->v);
b = b->next;
}
}
@ -157,14 +160,14 @@ template <typename K, typename V> class Hashtable {
inline void clear()
{
if (_s) {
for (unsigned long i = 0; i < _bc; ++i) {
_Bucket* b = _t[i];
for(unsigned long i=0;i<_bc;++i) {
_Bucket *b = _t[i];
while (b) {
_Bucket* const nb = b->next;
_Bucket *const nb = b->next;
delete b;
b = nb;
}
_t[i] = (_Bucket*)0;
_t[i] = (_Bucket *)0;
}
_s = 0;
}
@ -178,8 +181,8 @@ template <typename K, typename V> class Hashtable {
typename std::vector<K> k;
if (_s) {
k.reserve(_s);
for (unsigned long i = 0; i < _bc; ++i) {
_Bucket* b = _t[i];
for(unsigned long i=0;i<_bc;++i) {
_Bucket *b = _t[i];
while (b) {
k.push_back(b->k);
b = b->next;
@ -195,11 +198,12 @@ template <typename K, typename V> class Hashtable {
* @param v Vector, list, or other compliant container
* @tparam Type of V (generally inferred)
*/
template <typename C> inline void appendKeys(C& v) const
template<typename C>
inline void appendKeys(C &v) const
{
if (_s) {
for (unsigned long i = 0; i < _bc; ++i) {
_Bucket* b = _t[i];
for(unsigned long i=0;i<_bc;++i) {
_Bucket *b = _t[i];
while (b) {
v.push_back(b->k);
b = b->next;
@ -211,15 +215,15 @@ template <typename K, typename V> class Hashtable {
/**
* @return Vector of all entries (pairs of K,V)
*/
inline typename std::vector<std::pair<K, V> > entries() const
inline typename std::vector< std::pair<K,V> > entries() const
{
typename std::vector<std::pair<K, V> > k;
typename std::vector< std::pair<K,V> > k;
if (_s) {
k.reserve(_s);
for (unsigned long i = 0; i < _bc; ++i) {
_Bucket* b = _t[i];
for(unsigned long i=0;i<_bc;++i) {
_Bucket *b = _t[i];
while (b) {
k.push_back(std::pair<K, V>(b->k, b->v));
k.push_back(std::pair<K,V>(b->k,b->v));
b = b->next;
}
}
@ -231,30 +235,27 @@ template <typename K, typename V> class Hashtable {
* @param k Key
* @return Pointer to value or NULL if not found
*/
inline V* get(const K& k)
inline V *get(const K &k)
{
_Bucket* b = _t[_hc(k) % _bc];
_Bucket *b = _t[_hc(k) % _bc];
while (b) {
if (b->k == k) {
return &(b->v);
}
b = b->next;
}
return (V*)0;
}
inline const V* get(const K& k) const
{
return const_cast<Hashtable*>(this)->get(k);
return (V *)0;
}
inline const V *get(const K &k) const { return const_cast<Hashtable *>(this)->get(k); }
/**
* @param k Key
* @param v Value to fill with result
* @return True if value was found and set (if false, v is not modified)
*/
inline bool get(const K& k, V& v) const
inline bool get(const K &k,V &v) const
{
_Bucket* b = _t[_hc(k) % _bc];
_Bucket *b = _t[_hc(k) % _bc];
while (b) {
if (b->k == k) {
v = b->v;
@ -269,9 +270,9 @@ template <typename K, typename V> class Hashtable {
* @param k Key to check
* @return True if key is present
*/
inline bool contains(const K& k) const
inline bool contains(const K &k) const
{
_Bucket* b = _t[_hc(k) % _bc];
_Bucket *b = _t[_hc(k) % _bc];
while (b) {
if (b->k == k) {
return true;
@ -285,17 +286,16 @@ template <typename K, typename V> class Hashtable {
* @param k Key
* @return True if value was present
*/
inline bool erase(const K& k)
inline bool erase(const K &k)
{
const unsigned long bidx = _hc(k) % _bc;
_Bucket* lastb = (_Bucket*)0;
_Bucket* b = _t[bidx];
_Bucket *lastb = (_Bucket *)0;
_Bucket *b = _t[bidx];
while (b) {
if (b->k == k) {
if (lastb) {
lastb->next = b->next;
}
else {
} else {
_t[bidx] = b->next;
}
delete b;
@ -313,12 +313,12 @@ template <typename K, typename V> class Hashtable {
* @param v Value
* @return Reference to value in table
*/
inline V& set(const K& k, const V& v)
inline V &set(const K &k,const V &v)
{
const unsigned long h = _hc(k);
unsigned long bidx = h % _bc;
_Bucket* b = _t[bidx];
_Bucket *b = _t[bidx];
while (b) {
if (b->k == k) {
b->v = v;
@ -332,7 +332,7 @@ template <typename K, typename V> class Hashtable {
bidx = h % _bc;
}
b = new _Bucket(k, v);
b = new _Bucket(k,v);
b->next = _t[bidx];
_t[bidx] = b;
++_s;
@ -343,12 +343,12 @@ template <typename K, typename V> class Hashtable {
* @param k Key
* @return Value, possibly newly created
*/
inline V& operator[](const K& k)
inline V &operator[](const K &k)
{
const unsigned long h = _hc(k);
unsigned long bidx = h % _bc;
_Bucket* b = _t[bidx];
_Bucket *b = _t[bidx];
while (b) {
if (b->k == k) {
return b->v;
@ -371,27 +371,22 @@ template <typename K, typename V> class Hashtable {
/**
* @return Number of entries
*/
inline unsigned long size() const
{
return _s;
}
inline unsigned long size() const { return _s; }
/**
* @return True if table is empty
*/
inline bool empty() const
{
return (_s == 0);
}
inline bool empty() const { return (_s == 0); }
private:
template <typename O> static inline unsigned long _hc(const O& obj)
private:
template<typename O>
static inline unsigned long _hc(const O &obj)
{
return (unsigned long)obj.hashCode();
}
static inline unsigned long _hc(const uint64_t i)
{
return (unsigned long)(i ^ (i >> 32)); // good for network IDs and addresses
return (unsigned long)(i ^ (i >> 32)); // good for network IDs and addresses
}
static inline unsigned long _hc(const uint32_t i)
{
@ -409,15 +404,15 @@ template <typename K, typename V> class Hashtable {
inline void _grow()
{
const unsigned long nc = _bc * 2;
_Bucket** nt = reinterpret_cast<_Bucket**>(::malloc(sizeof(_Bucket*) * nc));
_Bucket **nt = reinterpret_cast<_Bucket **>(::malloc(sizeof(_Bucket *) * nc));
if (nt) {
for (unsigned long i = 0; i < nc; ++i) {
nt[i] = (_Bucket*)0;
for(unsigned long i=0;i<nc;++i) {
nt[i] = (_Bucket *)0;
}
for (unsigned long i = 0; i < _bc; ++i) {
_Bucket* b = _t[i];
for(unsigned long i=0;i<_bc;++i) {
_Bucket *b = _t[i];
while (b) {
_Bucket* const nb = b->next;
_Bucket *const nb = b->next;
const unsigned long nidx = _hc(b->k) % nc;
b->next = nt[nidx];
nt[nidx] = b;
@ -430,11 +425,11 @@ template <typename K, typename V> class Hashtable {
}
}
_Bucket** _t;
_Bucket **_t;
unsigned long _bc;
unsigned long _s;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,105 +4,101 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "Identity.hpp"
#include "Constants.hpp"
#include "SHA512.hpp"
#include "Salsa20.hpp"
#include "Utils.hpp"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "Constants.hpp"
#include "Identity.hpp"
#include "SHA512.hpp"
#include "Salsa20.hpp"
#include "Utils.hpp"
// These can't be changed without a new identity type. They define the
// parameters of the hashcash hashing/searching algorithm.
#define ZT_IDENTITY_GEN_HASHCASH_FIRST_BYTE_LESS_THAN 17
#define ZT_IDENTITY_GEN_MEMORY 2097152
#define ZT_IDENTITY_GEN_MEMORY 2097152
namespace ZeroTier {
// A memory-hard composition of SHA-512 and Salsa20 for hashcash hashing
static inline void _computeMemoryHardHash(const void* publicKey, unsigned int publicKeyBytes, void* digest, void* genmem)
static inline void _computeMemoryHardHash(const void *publicKey,unsigned int publicKeyBytes,void *digest,void *genmem)
{
// Digest publicKey[] to obtain initial digest
SHA512(digest, publicKey, publicKeyBytes);
SHA512(digest,publicKey,publicKeyBytes);
// Initialize genmem[] using Salsa20 in a CBC-like configuration since
// ordinary Salsa20 is randomly seek-able. This is good for a cipher
// but is not what we want for sequential memory-hardness.
memset(genmem, 0, ZT_IDENTITY_GEN_MEMORY);
Salsa20 s20(digest, (char*)digest + 32);
s20.crypt20((char*)genmem, (char*)genmem, 64);
for (unsigned long i = 64; i < ZT_IDENTITY_GEN_MEMORY; i += 64) {
memset(genmem,0,ZT_IDENTITY_GEN_MEMORY);
Salsa20 s20(digest,(char *)digest + 32);
s20.crypt20((char *)genmem,(char *)genmem,64);
for(unsigned long i=64;i<ZT_IDENTITY_GEN_MEMORY;i+=64) {
unsigned long k = i - 64;
*((uint64_t*)((char*)genmem + i)) = *((uint64_t*)((char*)genmem + k));
*((uint64_t*)((char*)genmem + i + 8)) = *((uint64_t*)((char*)genmem + k + 8));
*((uint64_t*)((char*)genmem + i + 16)) = *((uint64_t*)((char*)genmem + k + 16));
*((uint64_t*)((char*)genmem + i + 24)) = *((uint64_t*)((char*)genmem + k + 24));
*((uint64_t*)((char*)genmem + i + 32)) = *((uint64_t*)((char*)genmem + k + 32));
*((uint64_t*)((char*)genmem + i + 40)) = *((uint64_t*)((char*)genmem + k + 40));
*((uint64_t*)((char*)genmem + i + 48)) = *((uint64_t*)((char*)genmem + k + 48));
*((uint64_t*)((char*)genmem + i + 56)) = *((uint64_t*)((char*)genmem + k + 56));
s20.crypt20((char*)genmem + i, (char*)genmem + i, 64);
*((uint64_t *)((char *)genmem + i)) = *((uint64_t *)((char *)genmem + k));
*((uint64_t *)((char *)genmem + i + 8)) = *((uint64_t *)((char *)genmem + k + 8));
*((uint64_t *)((char *)genmem + i + 16)) = *((uint64_t *)((char *)genmem + k + 16));
*((uint64_t *)((char *)genmem + i + 24)) = *((uint64_t *)((char *)genmem + k + 24));
*((uint64_t *)((char *)genmem + i + 32)) = *((uint64_t *)((char *)genmem + k + 32));
*((uint64_t *)((char *)genmem + i + 40)) = *((uint64_t *)((char *)genmem + k + 40));
*((uint64_t *)((char *)genmem + i + 48)) = *((uint64_t *)((char *)genmem + k + 48));
*((uint64_t *)((char *)genmem + i + 56)) = *((uint64_t *)((char *)genmem + k + 56));
s20.crypt20((char *)genmem + i,(char *)genmem + i,64);
}
// Render final digest using genmem as a lookup table
for (unsigned long i = 0; i < (ZT_IDENTITY_GEN_MEMORY / sizeof(uint64_t));) {
unsigned long idx1 = (unsigned long)(Utils::ntoh(((uint64_t*)genmem)[i++]) % (64 / sizeof(uint64_t)));
unsigned long idx2 = (unsigned long)(Utils::ntoh(((uint64_t*)genmem)[i++]) % (ZT_IDENTITY_GEN_MEMORY / sizeof(uint64_t)));
uint64_t tmp = ((uint64_t*)genmem)[idx2];
((uint64_t*)genmem)[idx2] = ((uint64_t*)digest)[idx1];
((uint64_t*)digest)[idx1] = tmp;
s20.crypt20(digest, digest, 64);
for(unsigned long i=0;i<(ZT_IDENTITY_GEN_MEMORY / sizeof(uint64_t));) {
unsigned long idx1 = (unsigned long)(Utils::ntoh(((uint64_t *)genmem)[i++]) % (64 / sizeof(uint64_t)));
unsigned long idx2 = (unsigned long)(Utils::ntoh(((uint64_t *)genmem)[i++]) % (ZT_IDENTITY_GEN_MEMORY / sizeof(uint64_t)));
uint64_t tmp = ((uint64_t *)genmem)[idx2];
((uint64_t *)genmem)[idx2] = ((uint64_t *)digest)[idx1];
((uint64_t *)digest)[idx1] = tmp;
s20.crypt20(digest,digest,64);
}
}
// Hashcash generation halting condition -- halt when first byte is less than
// threshold value.
struct _Identity_generate_cond {
_Identity_generate_cond()
struct _Identity_generate_cond
{
_Identity_generate_cond() {}
_Identity_generate_cond(unsigned char *sb,char *gm) : digest(sb),genmem(gm) {}
inline bool operator()(const C25519::Pair &kp) const
{
}
_Identity_generate_cond(unsigned char* sb, char* gm) : digest(sb), genmem(gm)
{
}
inline bool operator()(const C25519::Pair& kp) const
{
_computeMemoryHardHash(kp.pub.data, ZT_C25519_PUBLIC_KEY_LEN, digest, genmem);
_computeMemoryHardHash(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,digest,genmem);
return (digest[0] < ZT_IDENTITY_GEN_HASHCASH_FIRST_BYTE_LESS_THAN);
}
unsigned char* digest;
char* genmem;
unsigned char *digest;
char *genmem;
};
void Identity::generate()
{
unsigned char digest[64];
char* genmem = new char[ZT_IDENTITY_GEN_MEMORY];
char *genmem = new char[ZT_IDENTITY_GEN_MEMORY];
C25519::Pair kp;
do {
kp = C25519::generateSatisfying(_Identity_generate_cond(digest, genmem));
_address.setTo(digest + 59, ZT_ADDRESS_LENGTH); // last 5 bytes are address
kp = C25519::generateSatisfying(_Identity_generate_cond(digest,genmem));
_address.setTo(digest + 59,ZT_ADDRESS_LENGTH); // last 5 bytes are address
} while (_address.isReserved());
_publicKey = kp.pub;
if (! _privateKey) {
if (!_privateKey) {
_privateKey = new C25519::Private();
}
*_privateKey = kp.priv;
delete[] genmem;
delete [] genmem;
}
bool Identity::locallyValidate() const
@ -112,54 +108,60 @@ bool Identity::locallyValidate() const
}
unsigned char digest[64];
char* genmem = new char[ZT_IDENTITY_GEN_MEMORY];
_computeMemoryHardHash(_publicKey.data, ZT_C25519_PUBLIC_KEY_LEN, digest, genmem);
delete[] genmem;
char *genmem = new char[ZT_IDENTITY_GEN_MEMORY];
_computeMemoryHardHash(_publicKey.data,ZT_C25519_PUBLIC_KEY_LEN,digest,genmem);
delete [] genmem;
unsigned char addrb[5];
_address.copyTo(addrb, 5);
_address.copyTo(addrb,5);
return ((digest[0] < ZT_IDENTITY_GEN_HASHCASH_FIRST_BYTE_LESS_THAN) && (digest[59] == addrb[0]) && (digest[60] == addrb[1]) && (digest[61] == addrb[2]) && (digest[62] == addrb[3]) && (digest[63] == addrb[4]));
return (
(digest[0] < ZT_IDENTITY_GEN_HASHCASH_FIRST_BYTE_LESS_THAN)&&
(digest[59] == addrb[0])&&
(digest[60] == addrb[1])&&
(digest[61] == addrb[2])&&
(digest[62] == addrb[3])&&
(digest[63] == addrb[4]));
}
char* Identity::toString(bool includePrivate, char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const
char *Identity::toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const
{
char* p = buf;
Utils::hex10(_address.toInt(), p);
char *p = buf;
Utils::hex10(_address.toInt(),p);
p += 10;
*(p++) = ':';
*(p++) = '0';
*(p++) = ':';
Utils::hex(_publicKey.data, ZT_C25519_PUBLIC_KEY_LEN, p);
Utils::hex(_publicKey.data,ZT_C25519_PUBLIC_KEY_LEN,p);
p += ZT_C25519_PUBLIC_KEY_LEN * 2;
if ((_privateKey) && (includePrivate)) {
if ((_privateKey)&&(includePrivate)) {
*(p++) = ':';
Utils::hex(_privateKey->data, ZT_C25519_PRIVATE_KEY_LEN, p);
Utils::hex(_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN,p);
p += ZT_C25519_PRIVATE_KEY_LEN * 2;
}
*p = (char)0;
return buf;
}
bool Identity::fromString(const char* str)
bool Identity::fromString(const char *str)
{
if (! str) {
if (!str) {
_address.zero();
return false;
}
char tmp[ZT_IDENTITY_STRING_BUFFER_LENGTH];
if (! Utils::scopy(tmp, sizeof(tmp), str)) {
if (!Utils::scopy(tmp,sizeof(tmp),str)) {
_address.zero();
return false;
}
delete _privateKey;
_privateKey = (C25519::Private*)0;
_privateKey = (C25519::Private *)0;
int fno = 0;
char* saveptr = (char*)0;
for (char* f = Utils::stok(tmp, ":", &saveptr); (f); f = Utils::stok((char*)0, ":", &saveptr)) {
switch (fno++) {
char *saveptr = (char *)0;
for(char *f=Utils::stok(tmp,":",&saveptr);(f);f=Utils::stok((char *)0,":",&saveptr)) {
switch(fno++) {
case 0:
_address = Address(Utils::hexStrToU64(f));
if (_address.isReserved()) {
@ -168,20 +170,20 @@ bool Identity::fromString(const char* str)
}
break;
case 1:
if ((f[0] != '0') || (f[1])) {
if ((f[0] != '0')||(f[1])) {
_address.zero();
return false;
}
break;
case 2:
if (Utils::unhex(f, _publicKey.data, ZT_C25519_PUBLIC_KEY_LEN) != ZT_C25519_PUBLIC_KEY_LEN) {
if (Utils::unhex(f,_publicKey.data,ZT_C25519_PUBLIC_KEY_LEN) != ZT_C25519_PUBLIC_KEY_LEN) {
_address.zero();
return false;
}
break;
case 3:
_privateKey = new C25519::Private();
if (Utils::unhex(f, _privateKey->data, ZT_C25519_PRIVATE_KEY_LEN) != ZT_C25519_PRIVATE_KEY_LEN) {
if (Utils::unhex(f,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN) != ZT_C25519_PRIVATE_KEY_LEN) {
_address.zero();
return false;
}
@ -199,4 +201,4 @@ bool Identity::fromString(const char* str)
return true;
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,16 +14,16 @@
#ifndef ZT_IDENTITY_HPP
#define ZT_IDENTITY_HPP
#include "Address.hpp"
#include "Buffer.hpp"
#include "C25519.hpp"
#include "Constants.hpp"
#include "SHA512.hpp"
#include "Utils.hpp"
#include <stdio.h>
#include <stdlib.h>
#include "Constants.hpp"
#include "Utils.hpp"
#include "Address.hpp"
#include "C25519.hpp"
#include "Buffer.hpp"
#include "SHA512.hpp"
#define ZT_IDENTITY_STRING_BUFFER_LENGTH 384
namespace ZeroTier {
@ -38,49 +38,56 @@ namespace ZeroTier {
* search for a different public key that duplicates an existing address. (See
* code for deriveAddress() for this algorithm.)
*/
class Identity {
public:
Identity() : _privateKey((C25519::Private*)0)
class Identity
{
public:
Identity() :
_privateKey((C25519::Private *)0)
{
}
Identity(const Identity& id) : _address(id._address), _publicKey(id._publicKey), _privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private*)0)
Identity(const Identity &id) :
_address(id._address),
_publicKey(id._publicKey),
_privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private *)0)
{
}
Identity(const char* str) : _privateKey((C25519::Private*)0)
Identity(const char *str) :
_privateKey((C25519::Private *)0)
{
if (! fromString(str)) {
if (!fromString(str)) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
}
}
template <unsigned int C> Identity(const Buffer<C>& b, unsigned int startAt = 0) : _privateKey((C25519::Private*)0)
template<unsigned int C>
Identity(const Buffer<C> &b,unsigned int startAt = 0) :
_privateKey((C25519::Private *)0)
{
deserialize(b, startAt);
deserialize(b,startAt);
}
~Identity()
{
if (_privateKey) {
Utils::burn(_privateKey, sizeof(C25519::Private));
Utils::burn(_privateKey,sizeof(C25519::Private));
delete _privateKey;
}
}
inline Identity& operator=(const Identity& id)
inline Identity &operator=(const Identity &id)
{
_address = id._address;
_publicKey = id._publicKey;
if (id._privateKey) {
if (! _privateKey) {
if (!_privateKey) {
_privateKey = new C25519::Private();
}
*_privateKey = *(id._privateKey);
}
else {
} else {
delete _privateKey;
_privateKey = (C25519::Private*)0;
_privateKey = (C25519::Private *)0;
}
return *this;
}
@ -102,17 +109,14 @@ class Identity {
/**
* @return True if this identity contains a private key
*/
inline bool hasPrivate() const
{
return (_privateKey != (C25519::Private*)0);
}
inline bool hasPrivate() const { return (_privateKey != (C25519::Private *)0); }
/**
* Compute a SHA384 hash of this identity's address and public key(s).
*
*
* @param sha384buf Buffer with 48 bytes of space to receive hash
*/
inline void publicKeyHash(void* sha384buf) const
inline void publicKeyHash(void *sha384buf) const
{
uint8_t address[ZT_ADDRESS_LENGTH];
_address.copyTo(address, ZT_ADDRESS_LENGTH);
@ -125,10 +129,10 @@ class Identity {
* @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
* @return True on success, false if no private key
*/
inline bool sha512PrivateKey(void* sha) const
inline bool sha512PrivateKey(void *sha) const
{
if (_privateKey) {
SHA512(sha, _privateKey->data, ZT_C25519_PRIVATE_KEY_LEN);
SHA512(sha,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
return true;
}
return false;
@ -140,10 +144,10 @@ class Identity {
* @param data Data to sign
* @param len Length of data
*/
inline C25519::Signature sign(const void* data, unsigned int len) const
inline C25519::Signature sign(const void *data,unsigned int len) const
{
if (_privateKey) {
return C25519::sign(*_privateKey, _publicKey, data, len);
return C25519::sign(*_privateKey,_publicKey,data,len);
}
throw ZT_EXCEPTION_PRIVATE_KEY_REQUIRED;
}
@ -157,12 +161,12 @@ class Identity {
* @param siglen Length of signature in bytes
* @return True if signature validates and data integrity checks
*/
inline bool verify(const void* data, unsigned int len, const void* signature, unsigned int siglen) const
inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
{
if (siglen != ZT_C25519_SIGNATURE_LEN) {
return false;
}
return C25519::verify(_publicKey, data, len, signature);
return C25519::verify(_publicKey,data,len,signature);
}
/**
@ -173,9 +177,9 @@ class Identity {
* @param signature Signature
* @return True if signature validates and data integrity checks
*/
inline bool verify(const void* data, unsigned int len, const C25519::Signature& signature) const
inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
{
return C25519::verify(_publicKey, data, len, signature);
return C25519::verify(_publicKey,data,len,signature);
}
/**
@ -187,10 +191,10 @@ class Identity {
* @param key Result parameter to fill with key bytes
* @return Was agreement successful?
*/
inline bool agree(const Identity& id, void* const key) const
inline bool agree(const Identity &id,void *const key) const
{
if (_privateKey) {
C25519::agree(*_privateKey, id._publicKey, key, ZT_SYMMETRIC_KEY_SIZE);
C25519::agree(*_privateKey,id._publicKey,key,ZT_SYMMETRIC_KEY_SIZE);
return true;
}
return false;
@ -199,10 +203,7 @@ class Identity {
/**
* @return This identity's address
*/
inline const Address& address() const
{
return _address;
}
inline const Address &address() const { return _address; }
/**
* Serialize this identity (binary)
@ -211,16 +212,16 @@ class Identity {
* @param includePrivate If true, include private key component (if present) (default: false)
* @throws std::out_of_range Buffer too small
*/
template <unsigned int C> inline void serialize(Buffer<C>& b, bool includePrivate = false) const
template<unsigned int C>
inline void serialize(Buffer<C> &b,bool includePrivate = false) const
{
_address.appendTo(b);
b.append((uint8_t)0); // C25519/Ed25519 identity type
b.append(_publicKey.data, ZT_C25519_PUBLIC_KEY_LEN);
if ((_privateKey) && (includePrivate)) {
b.append((uint8_t)0); // C25519/Ed25519 identity type
b.append(_publicKey.data,ZT_C25519_PUBLIC_KEY_LEN);
if ((_privateKey)&&(includePrivate)) {
b.append((unsigned char)ZT_C25519_PRIVATE_KEY_LEN);
b.append(_privateKey->data, ZT_C25519_PRIVATE_KEY_LEN);
}
else {
b.append(_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
} else {
b.append((unsigned char)0);
}
}
@ -237,21 +238,22 @@ class Identity {
* @throws std::out_of_range Serialized data invalid
* @throws std::invalid_argument Serialized data invalid
*/
template <unsigned int C> inline unsigned int deserialize(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
{
delete _privateKey;
_privateKey = (C25519::Private*)0;
_privateKey = (C25519::Private *)0;
unsigned int p = startAt;
_address.setTo(b.field(p, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
_address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
p += ZT_ADDRESS_LENGTH;
if (b[p++] != 0) {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
}
memcpy(_publicKey.data, b.field(p, ZT_C25519_PUBLIC_KEY_LEN), ZT_C25519_PUBLIC_KEY_LEN);
memcpy(_publicKey.data,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
p += ZT_C25519_PUBLIC_KEY_LEN;
unsigned int privateKeyLength = (unsigned int)b[p++];
@ -260,7 +262,7 @@ class Identity {
throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
}
_privateKey = new C25519::Private();
memcpy(_privateKey->data, b.field(p, ZT_C25519_PRIVATE_KEY_LEN), ZT_C25519_PRIVATE_KEY_LEN);
memcpy(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
p += ZT_C25519_PRIVATE_KEY_LEN;
}
@ -274,7 +276,7 @@ class Identity {
* @param buf Buffer to store string
* @return ASCII string representation of identity
*/
char* toString(bool includePrivate, char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
/**
* Deserialize a human-friendly string
@ -285,15 +287,12 @@ class Identity {
* @param str String to deserialize
* @return True if deserialization appears successful
*/
bool fromString(const char* str);
bool fromString(const char *str);
/**
* @return C25519 public key
*/
inline const C25519::Public& publicKey() const
{
return _publicKey;
}
inline const C25519::Public &publicKey() const { return _publicKey; }
/**
* @return C25519 key pair (only returns valid pair if private key is present in this Identity object)
@ -304,9 +303,8 @@ class Identity {
pair.pub = _publicKey;
if (_privateKey) {
pair.priv = *_privateKey;
}
else {
memset(pair.priv.data, 0, ZT_C25519_PRIVATE_KEY_LEN);
} else {
memset(pair.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
}
return pair;
}
@ -314,42 +312,21 @@ class Identity {
/**
* @return True if this identity contains something
*/
inline operator bool() const
{
return (_address);
}
inline operator bool() const { return (_address); }
inline bool operator==(const Identity& id) const
{
return ((_address == id._address) && (memcmp(_publicKey.data, id._publicKey.data, ZT_C25519_PUBLIC_KEY_LEN) == 0));
}
inline bool operator<(const Identity& id) const
{
return ((_address < id._address) || ((_address == id._address) && (memcmp(_publicKey.data, id._publicKey.data, ZT_C25519_PUBLIC_KEY_LEN) < 0)));
}
inline bool operator!=(const Identity& id) const
{
return ! (*this == id);
}
inline bool operator>(const Identity& id) const
{
return (id < *this);
}
inline bool operator<=(const Identity& id) const
{
return ! (id < *this);
}
inline bool operator>=(const Identity& id) const
{
return ! (*this < id);
}
inline bool operator==(const Identity &id) const { return ((_address == id._address)&&(memcmp(_publicKey.data,id._publicKey.data,ZT_C25519_PUBLIC_KEY_LEN) == 0)); }
inline bool operator<(const Identity &id) const { return ((_address < id._address)||((_address == id._address)&&(memcmp(_publicKey.data,id._publicKey.data,ZT_C25519_PUBLIC_KEY_LEN) < 0))); }
inline bool operator!=(const Identity &id) const { return !(*this == id); }
inline bool operator>(const Identity &id) const { return (id < *this); }
inline bool operator<=(const Identity &id) const { return !(id < *this); }
inline bool operator>=(const Identity &id) const { return !(*this < id); }
private:
private:
Address _address;
C25519::Public _publicKey;
C25519::Private* _privateKey;
C25519::Private *_privateKey;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,13 +14,13 @@
#ifndef ZT_INCOMINGPACKET_HPP
#define ZT_INCOMINGPACKET_HPP
#include "MulticastGroup.hpp"
#include <stdexcept>
#include "Packet.hpp"
#include "Path.hpp"
#include "Peer.hpp"
#include "Utils.hpp"
#include <stdexcept>
#include "MulticastGroup.hpp"
#include "Peer.hpp"
/*
* The big picture:
@ -46,9 +46,14 @@ class Network;
/**
* Subclass of packet that handles the decoding of it
*/
class IncomingPacket : public Packet {
public:
IncomingPacket() : Packet(), _receiveTime(0), _path(), _authenticated(false)
class IncomingPacket : public Packet
{
public:
IncomingPacket() :
Packet(),
_receiveTime(0),
_path(),
_authenticated(false)
{
}
@ -61,7 +66,11 @@ class IncomingPacket : public Packet {
* @param now Current time
* @throws std::out_of_range Range error processing packet
*/
IncomingPacket(const void* data, unsigned int len, const SharedPtr<Path>& path, int64_t now) : Packet(data, len), _receiveTime(now), _path(path), _authenticated(false)
IncomingPacket(const void *data,unsigned int len,const SharedPtr<Path> &path,int64_t now) :
Packet(data,len),
_receiveTime(now),
_path(path),
_authenticated(false)
{
}
@ -74,9 +83,9 @@ class IncomingPacket : public Packet {
* @param now Current time
* @throws std::out_of_range Range error processing packet
*/
inline void init(const void* data, unsigned int len, const SharedPtr<Path>& path, int64_t now)
inline void init(const void *data,unsigned int len,const SharedPtr<Path> &path,int64_t now)
{
copyFrom(data, len);
copyFrom(data,len);
_receiveTime = now;
_path = path;
_authenticated = false;
@ -95,47 +104,44 @@ class IncomingPacket : public Packet {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @return True if decoding and processing is complete, false if caller should try again
*/
bool tryDecode(const RuntimeEnvironment* RR, void* tPtr, int32_t flowId);
bool tryDecode(const RuntimeEnvironment *RR,void *tPtr,int32_t flowId);
/**
* @return Time of packet receipt / start of decode
*/
inline uint64_t receiveTime() const
{
return _receiveTime;
}
inline uint64_t receiveTime() const { return _receiveTime; }
private:
private:
// These are called internally to handle packet contents once it has
// been authenticated, decrypted, decompressed, and classified.
bool _doERROR(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doHELLO(const RuntimeEnvironment* RR, void* tPtr, const bool alreadyAuthenticated);
bool _doACK(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doQOS_MEASUREMENT(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doOK(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doWHOIS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doRENDEZVOUS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doFRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, int32_t flowId);
bool _doEXT_FRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, int32_t flowId);
bool _doECHO(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doMULTICAST_LIKE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doNETWORK_CREDENTIALS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doNETWORK_CONFIG(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doMULTICAST_GATHER(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doMULTICAST_FRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doPUSH_DIRECT_PATHS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doUSER_MESSAGE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doREMOTE_TRACE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer);
bool _doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated);
bool _doACK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId);
bool _doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,int32_t flowId);
bool _doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
bool _doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
void _sendErrorNeedCredentials(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, const uint64_t nwid);
void _sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid);
uint64_t _receiveTime;
SharedPtr<Path> _path;
bool _authenticated;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,234 +4,221 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "InetAddress.hpp"
#include "Constants.hpp"
#include "Utils.hpp"
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <string>
#include "Constants.hpp"
#include "InetAddress.hpp"
#include "Utils.hpp"
namespace ZeroTier {
const InetAddress InetAddress::LO4((const void*)("\x7f\x00\x00\x01"), 4, 0);
const InetAddress InetAddress::LO6((const void*)("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), 16, 0);
const InetAddress InetAddress::LO4((const void *)("\x7f\x00\x00\x01"),4,0);
const InetAddress InetAddress::LO6((const void *)("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"),16,0);
InetAddress::IpScope InetAddress::ipScope() const
{
switch (ss_family) {
switch(ss_family) {
case AF_INET: {
const uint32_t ip = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr);
switch (ip >> 24) {
const uint32_t ip = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
switch(ip >> 24) {
case 0x00:
return IP_SCOPE_NONE; // 0.0.0.0/8 (reserved, never used)
return IP_SCOPE_NONE; // 0.0.0.0/8 (reserved, never used)
case 0x06:
return IP_SCOPE_PSEUDOPRIVATE; // 6.0.0.0/8 (US Army)
return IP_SCOPE_PSEUDOPRIVATE; // 6.0.0.0/8 (US Army)
case 0x0a:
return IP_SCOPE_PRIVATE; // 10.0.0.0/8
return IP_SCOPE_PRIVATE; // 10.0.0.0/8
case 0x0b:
return IP_SCOPE_PSEUDOPRIVATE; // 11.0.0.0/8 (US DoD)
return IP_SCOPE_PSEUDOPRIVATE; // 11.0.0.0/8 (US DoD)
case 0x15:
return IP_SCOPE_PSEUDOPRIVATE; // 21.0.0.0/8 (US DDN-RVN)
return IP_SCOPE_PSEUDOPRIVATE; // 21.0.0.0/8 (US DDN-RVN)
case 0x16:
return IP_SCOPE_PSEUDOPRIVATE; // 22.0.0.0/8 (US DISA)
return IP_SCOPE_PSEUDOPRIVATE; // 22.0.0.0/8 (US DISA)
case 0x19:
return IP_SCOPE_PSEUDOPRIVATE; // 25.0.0.0/8 (UK Ministry of Defense)
return IP_SCOPE_PSEUDOPRIVATE; // 25.0.0.0/8 (UK Ministry of Defense)
case 0x1a:
return IP_SCOPE_PSEUDOPRIVATE; // 26.0.0.0/8 (US DISA)
return IP_SCOPE_PSEUDOPRIVATE; // 26.0.0.0/8 (US DISA)
case 0x1c:
return IP_SCOPE_PSEUDOPRIVATE; // 28.0.0.0/8 (US DSI-North)
return IP_SCOPE_PSEUDOPRIVATE; // 28.0.0.0/8 (US DSI-North)
case 0x1d:
return IP_SCOPE_PSEUDOPRIVATE; // 29.0.0.0/8 (US DISA)
return IP_SCOPE_PSEUDOPRIVATE; // 29.0.0.0/8 (US DISA)
case 0x1e:
return IP_SCOPE_PSEUDOPRIVATE; // 30.0.0.0/8 (US DISA)
return IP_SCOPE_PSEUDOPRIVATE; // 30.0.0.0/8 (US DISA)
case 0x33:
return IP_SCOPE_PSEUDOPRIVATE; // 51.0.0.0/8 (UK Department of Social Security)
return IP_SCOPE_PSEUDOPRIVATE; // 51.0.0.0/8 (UK Department of Social Security)
case 0x37:
return IP_SCOPE_PSEUDOPRIVATE; // 55.0.0.0/8 (US DoD)
return IP_SCOPE_PSEUDOPRIVATE; // 55.0.0.0/8 (US DoD)
case 0x38:
return IP_SCOPE_PSEUDOPRIVATE; // 56.0.0.0/8 (US Postal Service)
return IP_SCOPE_PSEUDOPRIVATE; // 56.0.0.0/8 (US Postal Service)
case 0x64:
if ((ip & 0xffc00000) == 0x64400000) {
return IP_SCOPE_PRIVATE; // 100.64.0.0/10
return IP_SCOPE_PRIVATE; // 100.64.0.0/10
}
break;
case 0x7f:
return IP_SCOPE_LOOPBACK; // 127.0.0.0/8
return IP_SCOPE_LOOPBACK; // 127.0.0.0/8
case 0xa9:
if ((ip & 0xffff0000) == 0xa9fe0000) {
return IP_SCOPE_LINK_LOCAL; // 169.254.0.0/16
return IP_SCOPE_LINK_LOCAL; // 169.254.0.0/16
}
break;
case 0xac:
if ((ip & 0xfff00000) == 0xac100000) {
return IP_SCOPE_PRIVATE; // 172.16.0.0/12
return IP_SCOPE_PRIVATE; // 172.16.0.0/12
}
break;
case 0xc0:
if ((ip & 0xffff0000) == 0xc0a80000) {
return IP_SCOPE_PRIVATE; // 192.168.0.0/16
return IP_SCOPE_PRIVATE; // 192.168.0.0/16
}
if ((ip & 0xffffff00) == 0xc0000200) {
return IP_SCOPE_PRIVATE; // 192.0.2.0/24
return IP_SCOPE_PRIVATE; // 192.0.2.0/24
}
break;
case 0xc6:
if ((ip & 0xfffe0000) == 0xc6120000) {
return IP_SCOPE_PRIVATE; // 198.18.0.0/15
return IP_SCOPE_PRIVATE; // 198.18.0.0/15
}
if ((ip & 0xffffff00) == 0xc6336400) {
return IP_SCOPE_PRIVATE; // 198.51.100.0/24
return IP_SCOPE_PRIVATE; // 198.51.100.0/24
}
break;
case 0xcb:
if ((ip & 0xffffff00) == 0xcb007100) {
return IP_SCOPE_PRIVATE; // 203.0.113.0/24
return IP_SCOPE_PRIVATE; // 203.0.113.0/24
}
break;
case 0xff:
return IP_SCOPE_NONE; // 255.0.0.0/8 (broadcast, or unused/unusable)
return IP_SCOPE_NONE; // 255.0.0.0/8 (broadcast, or unused/unusable)
}
switch (ip >> 28) {
switch(ip >> 28) {
case 0xe:
return IP_SCOPE_MULTICAST; // 224.0.0.0/4
return IP_SCOPE_MULTICAST; // 224.0.0.0/4
case 0xf:
return IP_SCOPE_PSEUDOPRIVATE; // 240.0.0.0/4 ("reserved," usually unusable)
return IP_SCOPE_PSEUDOPRIVATE; // 240.0.0.0/4 ("reserved," usually unusable)
}
return IP_SCOPE_GLOBAL;
} break;
} break;
case AF_INET6: {
const unsigned char* ip = reinterpret_cast<const unsigned char*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
const unsigned char *ip = reinterpret_cast<const unsigned char *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
if ((ip[0] & 0xf0) == 0xf0) {
if (ip[0] == 0xff) {
return IP_SCOPE_MULTICAST; // ff00::/8
return IP_SCOPE_MULTICAST; // ff00::/8
}
if ((ip[0] == 0xfe) && ((ip[1] & 0xc0) == 0x80)) {
if ((ip[0] == 0xfe)&&((ip[1] & 0xc0) == 0x80)) {
unsigned int k = 2;
while ((! ip[k]) && (k < 15)) {
while ((!ip[k])&&(k < 15)) {
++k;
}
if ((k == 15) && (ip[15] == 0x01)) {
return IP_SCOPE_LOOPBACK; // fe80::1/128
}
else {
return IP_SCOPE_LINK_LOCAL; // fe80::/10
if ((k == 15)&&(ip[15] == 0x01)) {
return IP_SCOPE_LOOPBACK; // fe80::1/128
} else {
return IP_SCOPE_LINK_LOCAL; // fe80::/10
}
}
if ((ip[0] & 0xfe) == 0xfc) {
return IP_SCOPE_PRIVATE; // fc00::/7
return IP_SCOPE_PRIVATE; // fc00::/7
}
}
// :::ffff:127.0.0.1
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1
unsigned int k = 0;
while ((! ip[k]) && (k < 9)) {
while ((!ip[k])&&(k < 15)) {
++k;
}
if (k == 9) {
if (ip[10] == 0xff && ip[11] == 0xff && ip[12] == 0x7f) {
return IP_SCOPE_LOOPBACK;
}
}
k = 0;
while ((! ip[k]) && (k < 15)) {
++k;
}
if (k == 15) { // all 0's except last byte
if (k == 15) { // all 0's except last byte
if (ip[15] == 0x01) {
return IP_SCOPE_LOOPBACK; // ::1/128
return IP_SCOPE_LOOPBACK; // ::1/128
}
if (ip[15] == 0x00) {
return IP_SCOPE_NONE; // ::/128
return IP_SCOPE_NONE; // ::/128
}
}
return IP_SCOPE_GLOBAL;
} break;
} break;
}
return IP_SCOPE_NONE;
}
void InetAddress::set(const void* ipBytes, unsigned int ipLen, unsigned int port)
void InetAddress::set(const void *ipBytes,unsigned int ipLen,unsigned int port)
{
memset(this, 0, sizeof(InetAddress));
memset(this,0,sizeof(InetAddress));
if (ipLen == 4) {
uint32_t ipb[1];
memcpy(ipb, ipBytes, 4);
memcpy(ipb,ipBytes,4);
ss_family = AF_INET;
reinterpret_cast<struct sockaddr_in*>(this)->sin_addr.s_addr = ipb[0];
reinterpret_cast<struct sockaddr_in*>(this)->sin_port = Utils::hton((uint16_t)port);
}
else if (ipLen == 16) {
reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr = ipb[0];
reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton((uint16_t)port);
} else if (ipLen == 16) {
ss_family = AF_INET6;
memcpy(reinterpret_cast<struct sockaddr_in6*>(this)->sin6_addr.s6_addr, ipBytes, 16);
reinterpret_cast<struct sockaddr_in6*>(this)->sin6_port = Utils::hton((uint16_t)port);
memcpy(reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,ipBytes,16);
reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_port = Utils::hton((uint16_t)port);
}
}
char* InetAddress::toString(char buf[64]) const
char *InetAddress::toString(char buf[64]) const
{
char* p = toIpString(buf);
char *p = toIpString(buf);
if (*p) {
while (*p) {
++p;
}
*(p++) = '/';
Utils::decimal(port(), p);
Utils::decimal(port(),p);
}
return buf;
}
char* InetAddress::toIpString(char buf[64]) const
char *InetAddress::toIpString(char buf[64]) const
{
buf[0] = (char)0;
switch (ss_family) {
switch(ss_family) {
case AF_INET: {
#ifdef _WIN32
inet_ntop(AF_INET, (void*)&reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
inet_ntop(AF_INET, (void*)&reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
#else
inet_ntop(AF_INET, &reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
inet_ntop(AF_INET, &reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
#endif
} break;
} break;
case AF_INET6: {
#ifdef _WIN32
inet_ntop(AF_INET6, (void*)reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, (void*)reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN);
#else
inet_ntop(AF_INET6, reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr, buf, INET6_ADDRSTRLEN);
#endif
} break;
} break;
}
return buf;
}
bool InetAddress::fromString(const char* ipSlashPort)
bool InetAddress::fromString(const char *ipSlashPort)
{
char buf[64];
memset(this, 0, sizeof(InetAddress));
memset(this,0,sizeof(InetAddress));
if (! *ipSlashPort) {
if (!*ipSlashPort) {
return true;
}
if (! Utils::scopy(buf, sizeof(buf), ipSlashPort)) {
if (!Utils::scopy(buf,sizeof(buf),ipSlashPort)) {
return false;
}
char* portAt = buf;
while ((*portAt) && (*portAt != '/')) {
char *portAt = buf;
while ((*portAt)&&(*portAt != '/')) {
++portAt;
}
unsigned int port = 0;
@ -240,21 +227,19 @@ bool InetAddress::fromString(const char* ipSlashPort)
port = Utils::strToUInt(portAt) & 0xffff;
}
if (strchr(buf, ':')) {
struct sockaddr_in6* const in6 = reinterpret_cast<struct sockaddr_in6*>(this);
if (strchr(buf,':')) {
struct sockaddr_in6 *const in6 = reinterpret_cast<struct sockaddr_in6 *>(this);
inet_pton(AF_INET6, buf, &in6->sin6_addr.s6_addr);
in6->sin6_family = AF_INET6;
in6->sin6_port = Utils::hton((uint16_t)port);
return true;
}
else if (strchr(buf, '.')) {
struct sockaddr_in* const in = reinterpret_cast<struct sockaddr_in*>(this);
} else if (strchr(buf,'.')) {
struct sockaddr_in *const in = reinterpret_cast<struct sockaddr_in *>(this);
inet_pton(AF_INET, buf, &in->sin_addr.s_addr);
in->sin_family = AF_INET;
in->sin_port = Utils::hton((uint16_t)port);
return true;
}
else {
} else {
return false;
}
}
@ -262,23 +247,22 @@ bool InetAddress::fromString(const char* ipSlashPort)
InetAddress InetAddress::netmask() const
{
InetAddress r(*this);
switch (r.ss_family) {
switch(r.ss_family) {
case AF_INET:
reinterpret_cast<struct sockaddr_in*>(&r)->sin_addr.s_addr = Utils::hton((uint32_t)(0xffffffff << (32 - netmaskBits())));
reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr = Utils::hton((uint32_t)(0xffffffff << (32 - netmaskBits())));
break;
case AF_INET6: {
uint64_t nm[2];
const unsigned int bits = netmaskBits();
if (bits) {
if(bits) {
nm[0] = Utils::hton((uint64_t)((bits >= 64) ? 0xffffffffffffffffULL : (0xffffffffffffffffULL << (64 - bits))));
nm[1] = Utils::hton((uint64_t)((bits <= 64) ? 0ULL : (0xffffffffffffffffULL << (128 - bits))));
}
else {
} else {
nm[0] = 0;
nm[1] = 0;
}
memcpy(reinterpret_cast<struct sockaddr_in6*>(&r)->sin6_addr.s6_addr, nm, 16);
} break;
memcpy(reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,nm,16);
} break;
}
return r;
}
@ -287,7 +271,7 @@ InetAddress InetAddress::broadcast() const
{
if (ss_family == AF_INET) {
InetAddress r(*this);
reinterpret_cast<struct sockaddr_in*>(&r)->sin_addr.s_addr |= Utils::hton((uint32_t)(0xffffffff >> netmaskBits()));
reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr |= Utils::hton((uint32_t)(0xffffffff >> netmaskBits()));
return r;
}
return InetAddress();
@ -296,34 +280,34 @@ InetAddress InetAddress::broadcast() const
InetAddress InetAddress::network() const
{
InetAddress r(*this);
switch (r.ss_family) {
switch(r.ss_family) {
case AF_INET:
reinterpret_cast<struct sockaddr_in*>(&r)->sin_addr.s_addr &= Utils::hton((uint32_t)(0xffffffff << (32 - netmaskBits())));
reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr &= Utils::hton((uint32_t)(0xffffffff << (32 - netmaskBits())));
break;
case AF_INET6: {
uint64_t nm[2];
const unsigned int bits = netmaskBits();
memcpy(nm, reinterpret_cast<struct sockaddr_in6*>(&r)->sin6_addr.s6_addr, 16);
memcpy(nm,reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,16);
nm[0] &= Utils::hton((uint64_t)((bits >= 64) ? 0xffffffffffffffffULL : (0xffffffffffffffffULL << (64 - bits))));
nm[1] &= Utils::hton((uint64_t)((bits <= 64) ? 0ULL : (0xffffffffffffffffULL << (128 - bits))));
memcpy(reinterpret_cast<struct sockaddr_in6*>(&r)->sin6_addr.s6_addr, nm, 16);
} break;
memcpy(reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,nm,16);
} break;
}
return r;
}
bool InetAddress::isEqualPrefix(const InetAddress& addr) const
bool InetAddress::isEqualPrefix(const InetAddress &addr) const
{
if (addr.ss_family == ss_family) {
switch (ss_family) {
switch(ss_family) {
case AF_INET6: {
const InetAddress mask(netmask());
InetAddress addr_mask(addr.netmask());
const uint8_t* n = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&addr_mask)->sin6_addr.s6_addr);
const uint8_t* m = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&mask)->sin6_addr.s6_addr);
const uint8_t* a = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&addr)->sin6_addr.s6_addr);
const uint8_t* b = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
for (unsigned int i = 0; i < 16; ++i) {
const uint8_t *n = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&addr_mask)->sin6_addr.s6_addr);
const uint8_t *m = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&mask)->sin6_addr.s6_addr);
const uint8_t *a = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_addr.s6_addr);
const uint8_t *b = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
for(unsigned int i=0;i<16;++i) {
if ((a[i] & m[i]) != (b[i] & n[i])) {
return false;
}
@ -335,24 +319,23 @@ bool InetAddress::isEqualPrefix(const InetAddress& addr) const
return false;
}
bool InetAddress::containsAddress(const InetAddress& addr) const
bool InetAddress::containsAddress(const InetAddress &addr) const
{
if (addr.ss_family == ss_family) {
switch (ss_family) {
switch(ss_family) {
case AF_INET: {
const unsigned int bits = netmaskBits();
if (bits == 0) {
return true;
}
return (
(Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(&addr)->sin_addr.s_addr) >> (32 - bits)) == (Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr) >> (32 - bits)));
return ( (Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_addr.s_addr) >> (32 - bits)) == (Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr) >> (32 - bits)) );
}
case AF_INET6: {
const InetAddress mask(netmask());
const uint8_t* m = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&mask)->sin6_addr.s6_addr);
const uint8_t* a = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&addr)->sin6_addr.s6_addr);
const uint8_t* b = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
for (unsigned int i = 0; i < 16; ++i) {
const uint8_t *m = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&mask)->sin6_addr.s6_addr);
const uint8_t *a = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_addr.s6_addr);
const uint8_t *b = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
for(unsigned int i=0;i<16;++i) {
if ((a[i] & m[i]) != b[i]) {
return false;
}
@ -366,7 +349,7 @@ bool InetAddress::containsAddress(const InetAddress& addr) const
bool InetAddress::isNetwork() const
{
switch (ss_family) {
switch(ss_family) {
case AF_INET: {
unsigned int bits = netmaskBits();
if (bits <= 0) {
@ -375,7 +358,7 @@ bool InetAddress::isNetwork() const
if (bits >= 32) {
return false;
}
uint32_t ip = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr);
uint32_t ip = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
return ((ip & (0xffffffff >> bits)) == 0);
}
case AF_INET6: {
@ -386,7 +369,7 @@ bool InetAddress::isNetwork() const
if (bits >= 128) {
return false;
}
const unsigned char* ip = reinterpret_cast<const unsigned char*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
const unsigned char *ip = reinterpret_cast<const unsigned char *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
unsigned int p = bits / 8;
if ((ip[p++] & (0xff >> (bits % 8))) != 0) {
return false;
@ -402,60 +385,55 @@ bool InetAddress::isNetwork() const
return false;
}
bool InetAddress::operator==(const InetAddress& a) const
bool InetAddress::operator==(const InetAddress &a) const
{
if (ss_family == a.ss_family) {
switch (ss_family) {
switch(ss_family) {
case AF_INET:
return (
(reinterpret_cast<const struct sockaddr_in*>(this)->sin_port == reinterpret_cast<const struct sockaddr_in*>(&a)->sin_port)
&& (reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in*>(&a)->sin_addr.s_addr));
(reinterpret_cast<const struct sockaddr_in *>(this)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_port)&&
(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr));
break;
case AF_INET6:
return (
(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port == reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_port)
&& (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_flowinfo == reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_flowinfo)
&& (memcmp(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_addr.s6_addr, 16) == 0)
&& (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_scope_id == reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_scope_id));
(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port == reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_port)&&
(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_flowinfo == reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_flowinfo)&&
(memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,16) == 0)&&
(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_scope_id == reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_scope_id));
break;
default:
return (memcmp(this, &a, sizeof(InetAddress)) == 0);
return (memcmp(this,&a,sizeof(InetAddress)) == 0);
}
}
return false;
}
bool InetAddress::operator<(const InetAddress& a) const
bool InetAddress::operator<(const InetAddress &a) const
{
if (ss_family < a.ss_family) {
return true;
}
else if (ss_family == a.ss_family) {
switch (ss_family) {
} else if (ss_family == a.ss_family) {
switch(ss_family) {
case AF_INET:
if (reinterpret_cast<const struct sockaddr_in*>(this)->sin_port < reinterpret_cast<const struct sockaddr_in*>(&a)->sin_port) {
if (reinterpret_cast<const struct sockaddr_in *>(this)->sin_port < reinterpret_cast<const struct sockaddr_in *>(&a)->sin_port) {
return true;
}
else if (reinterpret_cast<const struct sockaddr_in*>(this)->sin_port == reinterpret_cast<const struct sockaddr_in*>(&a)->sin_port) {
if (reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr < reinterpret_cast<const struct sockaddr_in*>(&a)->sin_addr.s_addr) {
} else if (reinterpret_cast<const struct sockaddr_in *>(this)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_port) {
if (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr < reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr) {
return true;
}
}
break;
case AF_INET6:
if (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port < reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_port) {
if (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port < reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_port) {
return true;
}
else if (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port == reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_port) {
if (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_flowinfo < reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_flowinfo) {
} else if (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port == reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_port) {
if (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_flowinfo < reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_flowinfo) {
return true;
}
else if (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_flowinfo == reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_flowinfo) {
if (memcmp(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_addr.s6_addr, 16) < 0) {
} else if (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_flowinfo == reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_flowinfo) {
if (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,16) < 0) {
return true;
}
else if (memcmp(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_addr.s6_addr, 16) == 0) {
if (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_scope_id < reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_scope_id) {
} else if (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,16) == 0) {
if (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_scope_id < reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_scope_id) {
return true;
}
}
@ -463,13 +441,13 @@ bool InetAddress::operator<(const InetAddress& a) const
}
break;
default:
return (memcmp(this, &a, sizeof(InetAddress)) < 0);
return (memcmp(this,&a,sizeof(InetAddress)) < 0);
}
}
return false;
}
InetAddress InetAddress::makeIpv6LinkLocal(const MAC& mac)
InetAddress InetAddress::makeIpv6LinkLocal(const MAC &mac)
{
struct sockaddr_in6 sin6;
sin6.sin6_family = AF_INET6;
@ -493,10 +471,10 @@ InetAddress InetAddress::makeIpv6LinkLocal(const MAC& mac)
return InetAddress(sin6);
}
InetAddress InetAddress::makeIpv6rfc4193(uint64_t nwid, uint64_t zeroTierAddress)
InetAddress InetAddress::makeIpv6rfc4193(uint64_t nwid,uint64_t zeroTierAddress)
{
InetAddress r;
struct sockaddr_in6* const sin6 = reinterpret_cast<struct sockaddr_in6*>(&r);
struct sockaddr_in6 *const sin6 = reinterpret_cast<struct sockaddr_in6 *>(&r);
sin6->sin6_family = AF_INET6;
sin6->sin6_addr.s6_addr[0] = 0xfd;
sin6->sin6_addr.s6_addr[1] = (uint8_t)(nwid >> 56);
@ -514,15 +492,15 @@ InetAddress InetAddress::makeIpv6rfc4193(uint64_t nwid, uint64_t zeroTierAddress
sin6->sin6_addr.s6_addr[13] = (uint8_t)(zeroTierAddress >> 16);
sin6->sin6_addr.s6_addr[14] = (uint8_t)(zeroTierAddress >> 8);
sin6->sin6_addr.s6_addr[15] = (uint8_t)zeroTierAddress;
sin6->sin6_port = Utils::hton((uint16_t)88); // /88 includes 0xfd + network ID, discriminating by device ID below that
sin6->sin6_port = Utils::hton((uint16_t)88); // /88 includes 0xfd + network ID, discriminating by device ID below that
return r;
}
InetAddress InetAddress::makeIpv66plane(uint64_t nwid, uint64_t zeroTierAddress)
InetAddress InetAddress::makeIpv66plane(uint64_t nwid,uint64_t zeroTierAddress)
{
nwid ^= (nwid >> 32);
InetAddress r;
struct sockaddr_in6* const sin6 = reinterpret_cast<struct sockaddr_in6*>(&r);
struct sockaddr_in6 *const sin6 = reinterpret_cast<struct sockaddr_in6 *>(&r);
sin6->sin6_family = AF_INET6;
sin6->sin6_addr.s6_addr[0] = 0xfc;
sin6->sin6_addr.s6_addr[1] = (uint8_t)(nwid >> 24);
@ -539,4 +517,4 @@ InetAddress InetAddress::makeIpv66plane(uint64_t nwid, uint64_t zeroTierAddress)
return r;
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,15 +14,15 @@
#ifndef ZT_INETADDRESS_HPP
#define ZT_INETADDRESS_HPP
#include "../include/ZeroTierOne.h"
#include "Buffer.hpp"
#include "Constants.hpp"
#include "MAC.hpp"
#include "Utils.hpp"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "Constants.hpp"
#include "../include/ZeroTierOne.h"
#include "Utils.hpp"
#include "MAC.hpp"
#include "Buffer.hpp"
namespace ZeroTier {
@ -39,7 +39,8 @@ namespace ZeroTier {
* sockaddr_storage and used interchangeably. DO NOT change this by e.g.
* adding non-static fields, since much code depends on this identity.
*/
struct InetAddress : public sockaddr_storage {
struct InetAddress : public sockaddr_storage
{
/**
* Loopback IPv4 address (no port)
*/
@ -57,177 +58,134 @@ struct InetAddress : public sockaddr_storage {
* MUST remain that way or Path must be changed to reflect. Also be sure
* to change ZT_INETADDRESS_MAX_SCOPE if the max changes.
*/
enum IpScope {
IP_SCOPE_NONE = 0, // NULL or not an IP address
IP_SCOPE_MULTICAST = 1, // 224.0.0.0 and other V4/V6 multicast IPs
IP_SCOPE_LOOPBACK = 2, // 127.0.0.1, ::1, etc.
IP_SCOPE_PSEUDOPRIVATE = 3, // 28.x.x.x, etc. -- unofficially unrouted IPv4 blocks often "bogarted"
IP_SCOPE_GLOBAL = 4, // globally routable IP address (all others)
IP_SCOPE_LINK_LOCAL = 5, // 169.254.x.x, IPv6 LL
IP_SCOPE_SHARED = 6, // currently unused, formerly used for carrier-grade NAT ranges
IP_SCOPE_PRIVATE = 7 // 10.x.x.x, 192.168.x.x, etc.
enum IpScope
{
IP_SCOPE_NONE = 0, // NULL or not an IP address
IP_SCOPE_MULTICAST = 1, // 224.0.0.0 and other V4/V6 multicast IPs
IP_SCOPE_LOOPBACK = 2, // 127.0.0.1, ::1, etc.
IP_SCOPE_PSEUDOPRIVATE = 3, // 28.x.x.x, etc. -- unofficially unrouted IPv4 blocks often "bogarted"
IP_SCOPE_GLOBAL = 4, // globally routable IP address (all others)
IP_SCOPE_LINK_LOCAL = 5, // 169.254.x.x, IPv6 LL
IP_SCOPE_SHARED = 6, // currently unused, formerly used for carrier-grade NAT ranges
IP_SCOPE_PRIVATE = 7 // 10.x.x.x, 192.168.x.x, etc.
};
// Can be used with the unordered maps and sets in c++11. We don't use C++11 in the core
// but this is safe to put here.
struct Hasher {
inline std::size_t operator()(const InetAddress& a) const
{
return (std::size_t)a.hashCode();
}
struct Hasher
{
inline std::size_t operator()(const InetAddress &a) const { return (std::size_t)a.hashCode(); }
};
InetAddress()
{
memset(this, 0, sizeof(InetAddress));
}
InetAddress(const InetAddress& a)
{
memcpy(this, &a, sizeof(InetAddress));
}
InetAddress(const InetAddress* a)
{
memcpy(this, a, sizeof(InetAddress));
}
InetAddress(const struct sockaddr_storage& ss)
{
*this = ss;
}
InetAddress(const struct sockaddr_storage* ss)
{
*this = ss;
}
InetAddress(const struct sockaddr& sa)
{
*this = sa;
}
InetAddress(const struct sockaddr* sa)
{
*this = sa;
}
InetAddress(const struct sockaddr_in& sa)
{
*this = sa;
}
InetAddress(const struct sockaddr_in* sa)
{
*this = sa;
}
InetAddress(const struct sockaddr_in6& sa)
{
*this = sa;
}
InetAddress(const struct sockaddr_in6* sa)
{
*this = sa;
}
InetAddress(const void* ipBytes, unsigned int ipLen, unsigned int port)
{
this->set(ipBytes, ipLen, port);
}
InetAddress(const uint32_t ipv4, unsigned int port)
{
this->set(&ipv4, 4, port);
}
InetAddress(const char* ipSlashPort)
{
this->fromString(ipSlashPort);
}
InetAddress() { memset(this,0,sizeof(InetAddress)); }
InetAddress(const InetAddress &a) { memcpy(this,&a,sizeof(InetAddress)); }
InetAddress(const InetAddress *a) { memcpy(this,a,sizeof(InetAddress)); }
InetAddress(const struct sockaddr_storage &ss) { *this = ss; }
InetAddress(const struct sockaddr_storage *ss) { *this = ss; }
InetAddress(const struct sockaddr &sa) { *this = sa; }
InetAddress(const struct sockaddr *sa) { *this = sa; }
InetAddress(const struct sockaddr_in &sa) { *this = sa; }
InetAddress(const struct sockaddr_in *sa) { *this = sa; }
InetAddress(const struct sockaddr_in6 &sa) { *this = sa; }
InetAddress(const struct sockaddr_in6 *sa) { *this = sa; }
InetAddress(const void *ipBytes,unsigned int ipLen,unsigned int port) { this->set(ipBytes,ipLen,port); }
InetAddress(const uint32_t ipv4,unsigned int port) { this->set(&ipv4,4,port); }
InetAddress(const char *ipSlashPort) { this->fromString(ipSlashPort); }
inline InetAddress& operator=(const InetAddress& a)
inline InetAddress &operator=(const InetAddress &a)
{
if (&a != this) {
memcpy(this, &a, sizeof(InetAddress));
memcpy(this,&a,sizeof(InetAddress));
}
return *this;
}
inline InetAddress& operator=(const InetAddress* a)
inline InetAddress &operator=(const InetAddress *a)
{
if (a != this) {
memcpy(this, a, sizeof(InetAddress));
memcpy(this,a,sizeof(InetAddress));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_storage& ss)
inline InetAddress &operator=(const struct sockaddr_storage &ss)
{
if (reinterpret_cast<const InetAddress*>(&ss) != this) {
memcpy(this, &ss, sizeof(InetAddress));
if (reinterpret_cast<const InetAddress *>(&ss) != this) {
memcpy(this,&ss,sizeof(InetAddress));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_storage* ss)
inline InetAddress &operator=(const struct sockaddr_storage *ss)
{
if (reinterpret_cast<const InetAddress*>(ss) != this) {
memcpy(this, ss, sizeof(InetAddress));
if (reinterpret_cast<const InetAddress *>(ss) != this) {
memcpy(this,ss,sizeof(InetAddress));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_in& sa)
inline InetAddress &operator=(const struct sockaddr_in &sa)
{
if (reinterpret_cast<const InetAddress*>(&sa) != this) {
memset(this, 0, sizeof(InetAddress));
memcpy(this, &sa, sizeof(struct sockaddr_in));
if (reinterpret_cast<const InetAddress *>(&sa) != this) {
memset(this,0,sizeof(InetAddress));
memcpy(this,&sa,sizeof(struct sockaddr_in));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_in* sa)
inline InetAddress &operator=(const struct sockaddr_in *sa)
{
if (reinterpret_cast<const InetAddress*>(sa) != this) {
memset(this, 0, sizeof(InetAddress));
memcpy(this, sa, sizeof(struct sockaddr_in));
if (reinterpret_cast<const InetAddress *>(sa) != this) {
memset(this,0,sizeof(InetAddress));
memcpy(this,sa,sizeof(struct sockaddr_in));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_in6& sa)
inline InetAddress &operator=(const struct sockaddr_in6 &sa)
{
if (reinterpret_cast<const InetAddress*>(&sa) != this) {
memset(this, 0, sizeof(InetAddress));
memcpy(this, &sa, sizeof(struct sockaddr_in6));
if (reinterpret_cast<const InetAddress *>(&sa) != this) {
memset(this,0,sizeof(InetAddress));
memcpy(this,&sa,sizeof(struct sockaddr_in6));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr_in6* sa)
inline InetAddress &operator=(const struct sockaddr_in6 *sa)
{
if (reinterpret_cast<const InetAddress*>(sa) != this) {
memset(this, 0, sizeof(InetAddress));
memcpy(this, sa, sizeof(struct sockaddr_in6));
if (reinterpret_cast<const InetAddress *>(sa) != this) {
memset(this,0,sizeof(InetAddress));
memcpy(this,sa,sizeof(struct sockaddr_in6));
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr& sa)
inline InetAddress &operator=(const struct sockaddr &sa)
{
if (reinterpret_cast<const InetAddress*>(&sa) != this) {
memset(this, 0, sizeof(InetAddress));
switch (sa.sa_family) {
if (reinterpret_cast<const InetAddress *>(&sa) != this) {
memset(this,0,sizeof(InetAddress));
switch(sa.sa_family) {
case AF_INET:
memcpy(this, &sa, sizeof(struct sockaddr_in));
memcpy(this,&sa,sizeof(struct sockaddr_in));
break;
case AF_INET6:
memcpy(this, &sa, sizeof(struct sockaddr_in6));
memcpy(this,&sa,sizeof(struct sockaddr_in6));
break;
}
}
return *this;
}
inline InetAddress& operator=(const struct sockaddr* sa)
inline InetAddress &operator=(const struct sockaddr *sa)
{
if (reinterpret_cast<const InetAddress*>(sa) != this) {
memset(this, 0, sizeof(InetAddress));
switch (sa->sa_family) {
if (reinterpret_cast<const InetAddress *>(sa) != this) {
memset(this,0,sizeof(InetAddress));
switch(sa->sa_family) {
case AF_INET:
memcpy(this, sa, sizeof(struct sockaddr_in));
memcpy(this,sa,sizeof(struct sockaddr_in));
break;
case AF_INET6:
memcpy(this, sa, sizeof(struct sockaddr_in6));
memcpy(this,sa,sizeof(struct sockaddr_in6));
break;
}
}
@ -246,7 +204,7 @@ struct InetAddress : public sockaddr_storage {
* @param ipLen Length of IP address: 4 or 16
* @param port Port number or 0 for none
*/
void set(const void* ipBytes, unsigned int ipLen, unsigned int port);
void set(const void *ipBytes,unsigned int ipLen,unsigned int port);
/**
* Set the port component
@ -255,12 +213,12 @@ struct InetAddress : public sockaddr_storage {
*/
inline void setPort(unsigned int port)
{
switch (ss_family) {
switch(ss_family) {
case AF_INET:
reinterpret_cast<struct sockaddr_in*>(this)->sin_port = Utils::hton((uint16_t)port);
reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton((uint16_t)port);
break;
case AF_INET6:
reinterpret_cast<struct sockaddr_in6*>(this)->sin6_port = Utils::hton((uint16_t)port);
reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_port = Utils::hton((uint16_t)port);
break;
}
}
@ -270,17 +228,17 @@ struct InetAddress : public sockaddr_storage {
*/
inline bool isDefaultRoute() const
{
switch (ss_family) {
switch(ss_family) {
case AF_INET:
return ((reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr == 0) && (reinterpret_cast<const struct sockaddr_in*>(this)->sin_port == 0));
return ( (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == 0) && (reinterpret_cast<const struct sockaddr_in *>(this)->sin_port == 0) );
case AF_INET6:
const uint8_t* ipb = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
for (int i = 0; i < 16; ++i) {
const uint8_t *ipb = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
for(int i=0;i<16;++i) {
if (ipb[i]) {
return false;
}
}
return (reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port == 0);
return (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port == 0);
}
return false;
}
@ -288,29 +246,29 @@ struct InetAddress : public sockaddr_storage {
/**
* @return ASCII IP/port format representation
*/
char* toString(char buf[64]) const;
char *toString(char buf[64]) const;
/**
* @return IP portion only, in ASCII string format
*/
char* toIpString(char buf[64]) const;
char *toIpString(char buf[64]) const;
/**
* @param ipSlashPort IP/port (port is optional, will be 0 if not included)
* @return True if address appeared to be valid
*/
bool fromString(const char* ipSlashPort);
bool fromString(const char *ipSlashPort);
/**
* @return Port or 0 if no port component defined
*/
inline unsigned int port() const
{
switch (ss_family) {
switch(ss_family) {
case AF_INET:
return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in*>(this)->sin_port));
return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(this)->sin_port));
case AF_INET6:
return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port));
return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port));
default:
return 0;
}
@ -325,10 +283,7 @@ struct InetAddress : public sockaddr_storage {
*
* @return Netmask bits
*/
inline unsigned int netmaskBits() const
{
return port();
}
inline unsigned int netmaskBits() const { return port(); }
/**
* @return True if netmask bits is valid for the address type
@ -336,7 +291,7 @@ struct InetAddress : public sockaddr_storage {
inline bool netmaskBitsValid() const
{
const unsigned int n = port();
switch (ss_family) {
switch(ss_family) {
case AF_INET:
return (n <= 32);
case AF_INET6:
@ -353,10 +308,7 @@ struct InetAddress : public sockaddr_storage {
*
* @return Gateway metric
*/
inline unsigned int metric() const
{
return port();
}
inline unsigned int metric() const { return port(); }
/**
* Construct a full netmask as an InetAddress
@ -388,7 +340,7 @@ struct InetAddress : public sockaddr_storage {
* @param addr Address to check
* @return True if this IPv6 prefix matches the prefix of a given IPv6 address
*/
bool isEqualPrefix(const InetAddress& addr) const;
bool isEqualPrefix(const InetAddress &addr) const;
/**
* Test whether this IP/netmask contains this address
@ -396,34 +348,28 @@ struct InetAddress : public sockaddr_storage {
* @param addr Address to check
* @return True if this IP/netmask (route) contains this address
*/
bool containsAddress(const InetAddress& addr) const;
bool containsAddress(const InetAddress &addr) const;
/**
* @return True if this is an IPv4 address
*/
inline bool isV4() const
{
return (ss_family == AF_INET);
}
inline bool isV4() const { return (ss_family == AF_INET); }
/**
* @return True if this is an IPv6 address
*/
inline bool isV6() const
{
return (ss_family == AF_INET6);
}
inline bool isV6() const { return (ss_family == AF_INET6); }
/**
* @return pointer to raw address bytes or NULL if not available
*/
inline const void* rawIpData() const
inline const void *rawIpData() const
{
switch (ss_family) {
switch(ss_family) {
case AF_INET:
return (const void*)&(reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr);
return (const void *)&(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
case AF_INET6:
return (const void*)(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
return (const void *)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
default:
return 0;
}
@ -435,14 +381,14 @@ struct InetAddress : public sockaddr_storage {
inline InetAddress ipOnly() const
{
InetAddress r;
switch (ss_family) {
switch(ss_family) {
case AF_INET:
r.ss_family = AF_INET;
reinterpret_cast<struct sockaddr_in*>(&r)->sin_addr.s_addr = reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr;
reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr = reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr;
break;
case AF_INET6:
r.ss_family = AF_INET6;
memcpy(reinterpret_cast<struct sockaddr_in6*>(&r)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, 16);
memcpy(reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,16);
break;
}
return r;
@ -454,16 +400,16 @@ struct InetAddress : public sockaddr_storage {
* @param a InetAddress to compare again
* @return True if only IP portions are equal (false for non-IP or null addresses)
*/
inline bool ipsEqual(const InetAddress& a) const
inline bool ipsEqual(const InetAddress &a) const
{
if (ss_family == a.ss_family) {
if (ss_family == AF_INET) {
return (reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in*>(&a)->sin_addr.s_addr);
return (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr);
}
if (ss_family == AF_INET6) {
return (memcmp(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_addr.s6_addr, 16) == 0);
return (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,16) == 0);
}
return (memcmp(this, &a, sizeof(InetAddress)) == 0);
return (memcmp(this,&a,sizeof(InetAddress)) == 0);
}
return false;
}
@ -476,16 +422,16 @@ struct InetAddress : public sockaddr_storage {
* @param a InetAddress to compare again
* @return True if only IP portions are equal (false for non-IP or null addresses)
*/
inline bool ipsEqual2(const InetAddress& a) const
inline bool ipsEqual2(const InetAddress &a) const
{
if (ss_family == a.ss_family) {
if (ss_family == AF_INET) {
return (reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in*>(&a)->sin_addr.s_addr);
return (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr);
}
if (ss_family == AF_INET6) {
return (memcmp(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6*>(&a)->sin6_addr.s6_addr, 8) == 0);
return (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr, reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr, 8) == 0);
}
return (memcmp(this, &a, sizeof(InetAddress)) == 0);
return (memcmp(this,&a,sizeof(InetAddress)) == 0);
}
return false;
}
@ -493,21 +439,19 @@ struct InetAddress : public sockaddr_storage {
inline unsigned long hashCode() const
{
if (ss_family == AF_INET) {
return ((unsigned long)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr + (unsigned long)reinterpret_cast<const struct sockaddr_in*>(this)->sin_port);
}
else if (ss_family == AF_INET6) {
unsigned long tmp = reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port;
const uint8_t* a = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
for (long i = 0; i < 16; ++i) {
reinterpret_cast<uint8_t*>(&tmp)[i % sizeof(tmp)] ^= a[i];
return ((unsigned long)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr + (unsigned long)reinterpret_cast<const struct sockaddr_in *>(this)->sin_port);
} else if (ss_family == AF_INET6) {
unsigned long tmp = reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port;
const uint8_t *a = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
for(long i=0;i<16;++i) {
reinterpret_cast<uint8_t *>(&tmp)[i % sizeof(tmp)] ^= a[i];
}
return tmp;
}
else {
unsigned long tmp = reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_port;
const uint8_t* a = reinterpret_cast<const uint8_t*>(this);
for (long i = 0; i < (long)sizeof(InetAddress); ++i) {
reinterpret_cast<uint8_t*>(&tmp)[i % sizeof(tmp)] ^= a[i];
} else {
unsigned long tmp = reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port;
const uint8_t *a = reinterpret_cast<const uint8_t *>(this);
for(long i=0;i<(long)sizeof(InetAddress);++i) {
reinterpret_cast<uint8_t *>(&tmp)[i % sizeof(tmp)] ^= a[i];
}
return tmp;
}
@ -516,10 +460,7 @@ struct InetAddress : public sockaddr_storage {
/**
* Set to null/zero
*/
inline void zero()
{
memset(this, 0, sizeof(InetAddress));
}
inline void zero() { memset(this,0,sizeof(InetAddress)); }
/**
* Check whether this is a network/route rather than an IP assignment
@ -533,18 +474,18 @@ struct InetAddress : public sockaddr_storage {
/**
* Find the total number of prefix bits that match between this IP and another
*
*
* @param b Second IP to compare with
* @return Number of matching prefix bits or 0 if none match or IPs are of different families (e.g. v4 and v6)
*/
inline unsigned int matchingPrefixBits(const InetAddress& b) const
inline unsigned int matchingPrefixBits(const InetAddress &b) const
{
unsigned int c = 0;
if (ss_family == b.ss_family) {
switch (ss_family) {
switch(ss_family) {
case AF_INET: {
uint32_t ip0 = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr);
uint32_t ip1 = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(&b)->sin_addr.s_addr);
uint32_t ip0 = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
uint32_t ip1 = Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(&b)->sin_addr.s_addr);
while ((ip0 >> 31) == (ip1 >> 31)) {
ip0 <<= 1;
ip1 <<= 1;
@ -552,15 +493,14 @@ struct InetAddress : public sockaddr_storage {
break;
}
}
} break;
} break;
case AF_INET6: {
const uint8_t* ip0 = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
const uint8_t* ip1 = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(&b)->sin6_addr.s6_addr);
for (unsigned int i = 0; i < 16; ++i) {
const uint8_t *ip0 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
const uint8_t *ip1 = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&b)->sin6_addr.s6_addr);
for(unsigned int i=0;i<16;++i) {
if (ip0[i] == ip1[i]) {
c += 8;
}
else {
} else {
uint8_t ip0b = ip0[i];
uint8_t ip1b = ip1[i];
uint8_t bit = 0x80;
@ -574,7 +514,7 @@ struct InetAddress : public sockaddr_storage {
break;
}
}
} break;
} break;
}
}
return c;
@ -586,13 +526,13 @@ struct InetAddress : public sockaddr_storage {
inline unsigned long rateGateHash() const
{
unsigned long h = 0;
switch (ss_family) {
switch(ss_family) {
case AF_INET:
h = (Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr) & 0xffffff00) >> 8;
h = (Utils::ntoh((uint32_t)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr) & 0xffffff00) >> 8;
h ^= (h >> 14);
break;
case AF_INET6: {
const uint8_t* ip = reinterpret_cast<const uint8_t*>(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr);
const uint8_t *ip = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
h = ((unsigned long)ip[0]);
h <<= 1;
h += ((unsigned long)ip[1]);
@ -604,7 +544,7 @@ struct InetAddress : public sockaddr_storage {
h += ((unsigned long)ip[4]);
h <<= 1;
h += ((unsigned long)ip[5]);
} break;
} break;
}
return (h & 0x3fff);
}
@ -612,25 +552,23 @@ struct InetAddress : public sockaddr_storage {
/**
* @return True if address family is non-zero
*/
inline operator bool() const
{
return (ss_family != 0);
}
inline operator bool() const { return (ss_family != 0); }
template <unsigned int C> inline void serialize(Buffer<C>& b) const
template<unsigned int C>
inline void serialize(Buffer<C> &b) const
{
// This is used in the protocol and must be the same as describe in places
// like VERB_HELLO in Packet.hpp.
switch (ss_family) {
switch(ss_family) {
case AF_INET:
b.append((uint8_t)0x04);
b.append(&(reinterpret_cast<const struct sockaddr_in*>(this)->sin_addr.s_addr), 4);
b.append((uint16_t)port()); // just in case sin_port != uint16_t
b.append(&(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr),4);
b.append((uint16_t)port()); // just in case sin_port != uint16_t
return;
case AF_INET6:
b.append((uint8_t)0x06);
b.append(reinterpret_cast<const struct sockaddr_in6*>(this)->sin6_addr.s6_addr, 16);
b.append((uint16_t)port()); // just in case sin_port != uint16_t
b.append(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,16);
b.append((uint16_t)port()); // just in case sin_port != uint16_t
return;
default:
b.append((uint8_t)0);
@ -638,11 +576,12 @@ struct InetAddress : public sockaddr_storage {
}
}
template <unsigned int C> inline unsigned int deserialize(const Buffer<C>& b, unsigned int startAt = 0)
template<unsigned int C>
inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
{
memset(this, 0, sizeof(InetAddress));
memset(this,0,sizeof(InetAddress));
unsigned int p = startAt;
switch (b[p++]) {
switch(b[p++]) {
case 0:
return 1;
case 0x01:
@ -654,19 +593,19 @@ struct InetAddress : public sockaddr_storage {
case 0x03:
// TODO: Other address types (but accept for forward compatibility)
// These could be extended/optional things like AF_UNIX, LTE Direct, shared memory, etc.
return (unsigned int)(b.template at<uint16_t>(p) + 3); // other addresses begin with 16-bit non-inclusive length
return (unsigned int)(b.template at<uint16_t>(p) + 3); // other addresses begin with 16-bit non-inclusive length
case 0x04:
ss_family = AF_INET;
memcpy(&(reinterpret_cast<struct sockaddr_in*>(this)->sin_addr.s_addr), b.field(p, 4), 4);
memcpy(&(reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr),b.field(p,4),4);
p += 4;
reinterpret_cast<struct sockaddr_in*>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p));
reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p));
p += 2;
break;
case 0x06:
ss_family = AF_INET6;
memcpy(reinterpret_cast<struct sockaddr_in6*>(this)->sin6_addr.s6_addr, b.field(p, 16), 16);
memcpy(reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,b.field(p,16),16);
p += 16;
reinterpret_cast<struct sockaddr_in*>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p));
reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p));
p += 2;
break;
default:
@ -675,30 +614,18 @@ struct InetAddress : public sockaddr_storage {
return (p - startAt);
}
bool operator==(const InetAddress& a) const;
bool operator<(const InetAddress& a) const;
inline bool operator!=(const InetAddress& a) const
{
return ! (*this == a);
}
inline bool operator>(const InetAddress& a) const
{
return (a < *this);
}
inline bool operator<=(const InetAddress& a) const
{
return ! (a < *this);
}
inline bool operator>=(const InetAddress& a) const
{
return ! (*this < a);
}
bool operator==(const InetAddress &a) const;
bool operator<(const InetAddress &a) const;
inline bool operator!=(const InetAddress &a) const { return !(*this == a); }
inline bool operator>(const InetAddress &a) const { return (a < *this); }
inline bool operator<=(const InetAddress &a) const { return !(a < *this); }
inline bool operator>=(const InetAddress &a) const { return !(*this < a); }
/**
* @param mac MAC address seed
* @return IPv6 link-local address
*/
static InetAddress makeIpv6LinkLocal(const MAC& mac);
static InetAddress makeIpv6LinkLocal(const MAC &mac);
/**
* Compute private IPv6 unicast address from network ID and ZeroTier address
@ -741,14 +668,14 @@ struct InetAddress : public sockaddr_storage {
* @param zeroTierAddress 40-bit device address (in least significant 40 bits, highest 24 bits ignored)
* @return IPv6 private unicast address with /88 netmask
*/
static InetAddress makeIpv6rfc4193(uint64_t nwid, uint64_t zeroTierAddress);
static InetAddress makeIpv6rfc4193(uint64_t nwid,uint64_t zeroTierAddress);
/**
* Compute a private IPv6 "6plane" unicast address from network ID and ZeroTier address
*/
static InetAddress makeIpv66plane(uint64_t nwid, uint64_t zeroTierAddress);
static InetAddress makeIpv66plane(uint64_t nwid,uint64_t zeroTierAddress);
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,81 +14,64 @@
#ifndef ZT_MAC_HPP
#define ZT_MAC_HPP
#include "Address.hpp"
#include "Buffer.hpp"
#include "Constants.hpp"
#include "Utils.hpp"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "Constants.hpp"
#include "Utils.hpp"
#include "Address.hpp"
#include "Buffer.hpp"
namespace ZeroTier {
/**
* 48-byte Ethernet MAC address
*/
class MAC {
public:
MAC() : _m(0ULL)
{
}
MAC(const MAC& m) : _m(m._m)
{
}
class MAC
{
public:
MAC() : _m(0ULL) {}
MAC(const MAC &m) : _m(m._m) {}
MAC(const unsigned char a, const unsigned char b, const unsigned char c, const unsigned char d, const unsigned char e, const unsigned char f)
: _m(((((uint64_t)a) & 0xffULL) << 40) | ((((uint64_t)b) & 0xffULL) << 32) | ((((uint64_t)c) & 0xffULL) << 24) | ((((uint64_t)d) & 0xffULL) << 16) | ((((uint64_t)e) & 0xffULL) << 8) | (((uint64_t)f) & 0xffULL))
{
}
MAC(const void* bits, unsigned int len)
{
setTo(bits, len);
}
MAC(const Address& ztaddr, uint64_t nwid)
{
fromAddress(ztaddr, nwid);
}
MAC(const uint64_t m) : _m(m & 0xffffffffffffULL)
{
}
MAC(const unsigned char a,const unsigned char b,const unsigned char c,const unsigned char d,const unsigned char e,const unsigned char f) :
_m( ((((uint64_t)a) & 0xffULL) << 40) |
((((uint64_t)b) & 0xffULL) << 32) |
((((uint64_t)c) & 0xffULL) << 24) |
((((uint64_t)d) & 0xffULL) << 16) |
((((uint64_t)e) & 0xffULL) << 8) |
(((uint64_t)f) & 0xffULL) ) {}
MAC(const void *bits,unsigned int len) { setTo(bits,len); }
MAC(const Address &ztaddr,uint64_t nwid) { fromAddress(ztaddr,nwid); }
MAC(const uint64_t m) : _m(m & 0xffffffffffffULL) {}
/**
* @return MAC in 64-bit integer
*/
inline uint64_t toInt() const
{
return _m;
}
inline uint64_t toInt() const { return _m; }
/**
* Set MAC to zero
*/
inline void zero()
{
_m = 0ULL;
}
inline void zero() { _m = 0ULL; }
/**
* @return True if MAC is non-zero
*/
inline operator bool() const
{
return (_m != 0ULL);
}
inline operator bool() const { return (_m != 0ULL); }
/**
* @param bits Raw MAC in big-endian byte order
* @param len Length, must be >= 6 or result is zero
*/
inline void setTo(const void* bits, unsigned int len)
inline void setTo(const void *bits,unsigned int len)
{
if (len < 6) {
_m = 0ULL;
return;
}
const unsigned char* b = (const unsigned char*)bits;
_m = ((((uint64_t)*b) & 0xff) << 40);
const unsigned char *b = (const unsigned char *)bits;
_m = ((((uint64_t)*b) & 0xff) << 40);
++b;
_m |= ((((uint64_t)*b) & 0xff) << 32);
++b;
@ -105,12 +88,12 @@ class MAC {
* @param buf Destination buffer for MAC in big-endian byte order
* @param len Length of buffer, must be >= 6 or nothing is copied
*/
inline void copyTo(void* buf, unsigned int len) const
inline void copyTo(void *buf,unsigned int len) const
{
if (len < 6) {
return;
}
unsigned char* b = (unsigned char*)buf;
unsigned char *b = (unsigned char *)buf;
*(b++) = (unsigned char)((_m >> 40) & 0xff);
*(b++) = (unsigned char)((_m >> 32) & 0xff);
*(b++) = (unsigned char)((_m >> 24) & 0xff);
@ -124,9 +107,10 @@ class MAC {
*
* @param b Buffer to append to
*/
template <unsigned int C> inline void appendTo(Buffer<C>& b) const
template<unsigned int C>
inline void appendTo(Buffer<C> &b) const
{
unsigned char* p = (unsigned char*)b.appendField(6);
unsigned char *p = (unsigned char *)b.appendField(6);
*(p++) = (unsigned char)((_m >> 40) & 0xff);
*(p++) = (unsigned char)((_m >> 32) & 0xff);
*(p++) = (unsigned char)((_m >> 24) & 0xff);
@ -138,26 +122,17 @@ class MAC {
/**
* @return True if this is broadcast (all 0xff)
*/
inline bool isBroadcast() const
{
return (_m == 0xffffffffffffULL);
}
inline bool isBroadcast() const { return (_m == 0xffffffffffffULL); }
/**
* @return True if this is a multicast MAC
*/
inline bool isMulticast() const
{
return ((_m & 0x010000000000ULL) != 0ULL);
}
inline bool isMulticast() const { return ((_m & 0x010000000000ULL) != 0ULL); }
/**
* @param True if this is a locally-administered MAC
*/
inline bool isLocallyAdministered() const
{
return ((_m & 0x020000000000ULL) != 0ULL);
}
inline bool isLocallyAdministered() const { return ((_m & 0x020000000000ULL) != 0ULL); }
/**
* Set this MAC to a MAC derived from an address and a network ID
@ -165,10 +140,10 @@ class MAC {
* @param ztaddr ZeroTier address
* @param nwid 64-bit network ID
*/
inline void fromAddress(const Address& ztaddr, uint64_t nwid)
inline void fromAddress(const Address &ztaddr,uint64_t nwid)
{
uint64_t m = ((uint64_t)firstOctetForNetwork(nwid)) << 40;
m |= ztaddr.toInt(); // a is 40 bits
m |= ztaddr.toInt(); // a is 40 bits
m ^= ((nwid >> 8) & 0xff) << 32;
m ^= ((nwid >> 16) & 0xff) << 24;
m ^= ((nwid >> 24) & 0xff) << 16;
@ -186,8 +161,8 @@ class MAC {
*/
inline Address toAddress(uint64_t nwid) const
{
uint64_t a = _m & 0xffffffffffULL; // least significant 40 bits of MAC are formed from address
a ^= ((nwid >> 8) & 0xff) << 32; // ... XORed with bits 8-48 of the nwid in little-endian byte order, so unmask it
uint64_t a = _m & 0xffffffffffULL; // least significant 40 bits of MAC are formed from address
a ^= ((nwid >> 8) & 0xff) << 32; // ... XORed with bits 8-48 of the nwid in little-endian byte order, so unmask it
a ^= ((nwid >> 16) & 0xff) << 24;
a ^= ((nwid >> 24) & 0xff) << 16;
a ^= ((nwid >> 32) & 0xff) << 8;
@ -201,33 +176,24 @@ class MAC {
*/
static inline unsigned char firstOctetForNetwork(uint64_t nwid)
{
unsigned char a = ((unsigned char)(nwid & 0xfe) | 0x02); // locally administered, not multicast, from LSB of network ID
return ((a == 0x52) ? 0x32 : a); // blacklist 0x52 since it's used by KVM, libvirt, and other popular virtualization engines... seems de-facto standard on Linux
unsigned char a = ((unsigned char)(nwid & 0xfe) | 0x02); // locally administered, not multicast, from LSB of network ID
return ((a == 0x52) ? 0x32 : a); // blacklist 0x52 since it's used by KVM, libvirt, and other popular virtualization engines... seems de-facto standard on Linux
}
/**
* @param i Value from 0 to 5 (inclusive)
* @return Byte at said position (address interpreted in big-endian order)
*/
inline unsigned char operator[](unsigned int i) const
{
return (unsigned char)((_m >> (40 - (i * 8))) & 0xff);
}
inline unsigned char operator[](unsigned int i) const { return (unsigned char)((_m >> (40 - (i * 8))) & 0xff); }
/**
* @return 6, which is the number of bytes in a MAC, for container compliance
*/
inline unsigned int size() const
{
return 6;
}
inline unsigned int size() const { return 6; }
inline unsigned long hashCode() const
{
return (unsigned long)_m;
}
inline unsigned long hashCode() const { return (unsigned long)_m; }
inline char* toString(char buf[18]) const
inline char *toString(char buf[18]) const
{
buf[0] = Utils::HEXCHARS[(_m >> 44) & 0xf];
buf[1] = Utils::HEXCHARS[(_m >> 40) & 0xf];
@ -250,46 +216,28 @@ class MAC {
return buf;
}
inline MAC& operator=(const MAC& m)
inline MAC &operator=(const MAC &m)
{
_m = m._m;
return *this;
}
inline MAC& operator=(const uint64_t m)
inline MAC &operator=(const uint64_t m)
{
_m = m;
return *this;
}
inline bool operator==(const MAC& m) const
{
return (_m == m._m);
}
inline bool operator!=(const MAC& m) const
{
return (_m != m._m);
}
inline bool operator<(const MAC& m) const
{
return (_m < m._m);
}
inline bool operator<=(const MAC& m) const
{
return (_m <= m._m);
}
inline bool operator>(const MAC& m) const
{
return (_m > m._m);
}
inline bool operator>=(const MAC& m) const
{
return (_m >= m._m);
}
inline bool operator==(const MAC &m) const { return (_m == m._m); }
inline bool operator!=(const MAC &m) const { return (_m != m._m); }
inline bool operator<(const MAC &m) const { return (_m < m._m); }
inline bool operator<=(const MAC &m) const { return (_m <= m._m); }
inline bool operator>(const MAC &m) const { return (_m > m._m); }
inline bool operator>=(const MAC &m) const { return (_m >= m._m); }
private:
private:
uint64_t _m;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,48 +4,54 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "Membership.hpp"
#include "Node.hpp"
#include "Packet.hpp"
#include "Peer.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
#include "Trace.hpp"
#include <algorithm>
#include "Membership.hpp"
#include "RuntimeEnvironment.hpp"
#include "Peer.hpp"
#include "Topology.hpp"
#include "Switch.hpp"
#include "Packet.hpp"
#include "Node.hpp"
#include "Trace.hpp"
namespace ZeroTier {
Membership::Membership() : _lastUpdatedMulticast(0), _comRevocationThreshold(0), _lastPushedCredentials(0), _revocations(4), _remoteTags(4), _remoteCaps(4), _remoteCoos(4)
Membership::Membership() :
_lastUpdatedMulticast(0),
_comRevocationThreshold(0),
_lastPushedCredentials(0),
_revocations(4),
_remoteTags(4),
_remoteCaps(4),
_remoteCoos(4)
{
}
void Membership::pushCredentials(const RuntimeEnvironment* RR, void* tPtr, const int64_t now, const Address& peerAddress, const NetworkConfig& nconf)
void Membership::pushCredentials(const RuntimeEnvironment *RR,void *tPtr,const int64_t now,const Address &peerAddress,const NetworkConfig &nconf)
{
const Capability* sendCaps[ZT_MAX_NETWORK_CAPABILITIES];
const Capability *sendCaps[ZT_MAX_NETWORK_CAPABILITIES];
unsigned int sendCapCount = 0;
for (unsigned int c = 0; c < nconf.capabilityCount; ++c) {
for(unsigned int c=0;c<nconf.capabilityCount;++c) {
sendCaps[sendCapCount++] = &(nconf.capabilities[c]);
}
const Tag* sendTags[ZT_MAX_NETWORK_TAGS];
const Tag *sendTags[ZT_MAX_NETWORK_TAGS];
unsigned int sendTagCount = 0;
for (unsigned int t = 0; t < nconf.tagCount; ++t) {
for(unsigned int t=0;t<nconf.tagCount;++t) {
sendTags[sendTagCount++] = &(nconf.tags[t]);
}
const CertificateOfOwnership* sendCoos[ZT_MAX_CERTIFICATES_OF_OWNERSHIP];
const CertificateOfOwnership *sendCoos[ZT_MAX_CERTIFICATES_OF_OWNERSHIP];
unsigned int sendCooCount = 0;
for (unsigned int c = 0; c < nconf.certificateOfOwnershipCount; ++c) {
for(unsigned int c=0;c<nconf.certificateOfOwnershipCount;++c) {
sendCoos[sendCooCount++] = &(nconf.certificatesOfOwnership[c]);
}
@ -53,8 +59,8 @@ void Membership::pushCredentials(const RuntimeEnvironment* RR, void* tPtr, const
unsigned int tagPtr = 0;
unsigned int cooPtr = 0;
bool sendCom = (bool)(nconf.com);
while ((capPtr < sendCapCount) || (tagPtr < sendTagCount) || (cooPtr < sendCooCount) || (sendCom)) {
Packet outp(peerAddress, RR->identity.address(), Packet::VERB_NETWORK_CREDENTIALS);
while ((capPtr < sendCapCount)||(tagPtr < sendTagCount)||(cooPtr < sendCooCount)||(sendCom)) {
Packet outp(peerAddress,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
if (sendCom) {
sendCom = false;
@ -65,20 +71,20 @@ void Membership::pushCredentials(const RuntimeEnvironment* RR, void* tPtr, const
const unsigned int capCountAt = outp.size();
outp.addSize(2);
unsigned int thisPacketCapCount = 0;
while ((capPtr < sendCapCount) && ((outp.size() + sizeof(Capability) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
while ((capPtr < sendCapCount)&&((outp.size() + sizeof(Capability) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
sendCaps[capPtr++]->serialize(outp);
++thisPacketCapCount;
}
outp.setAt(capCountAt, (uint16_t)thisPacketCapCount);
outp.setAt(capCountAt,(uint16_t)thisPacketCapCount);
const unsigned int tagCountAt = outp.size();
outp.addSize(2);
unsigned int thisPacketTagCount = 0;
while ((tagPtr < sendTagCount) && ((outp.size() + sizeof(Tag) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
while ((tagPtr < sendTagCount)&&((outp.size() + sizeof(Tag) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
sendTags[tagPtr++]->serialize(outp);
++thisPacketTagCount;
}
outp.setAt(tagCountAt, (uint16_t)thisPacketTagCount);
outp.setAt(tagCountAt,(uint16_t)thisPacketTagCount);
// No revocations, these propagate differently
outp.append((uint16_t)0);
@ -86,43 +92,43 @@ void Membership::pushCredentials(const RuntimeEnvironment* RR, void* tPtr, const
const unsigned int cooCountAt = outp.size();
outp.addSize(2);
unsigned int thisPacketCooCount = 0;
while ((cooPtr < sendCooCount) && ((outp.size() + sizeof(CertificateOfOwnership) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
while ((cooPtr < sendCooCount)&&((outp.size() + sizeof(CertificateOfOwnership) + 16) < ZT_PROTO_MAX_PACKET_LENGTH)) {
sendCoos[cooPtr++]->serialize(outp);
++thisPacketCooCount;
}
outp.setAt(cooCountAt, (uint16_t)thisPacketCooCount);
outp.setAt(cooCountAt,(uint16_t)thisPacketCooCount);
outp.compress();
RR->sw->send(tPtr, outp, true);
RR->sw->send(tPtr,outp,true);
Metrics::pkt_network_credentials_out++;
}
_lastPushedCredentials = now;
}
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const CertificateOfMembership& com)
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfMembership &com)
{
const int64_t newts = com.timestamp();
if (newts <= _comRevocationThreshold) {
RR->t->credentialRejected(tPtr, com, "revoked");
RR->t->credentialRejected(tPtr,com,"revoked");
return ADD_REJECTED;
}
const int64_t oldts = _com.timestamp();
if (newts < oldts) {
RR->t->credentialRejected(tPtr, com, "old");
RR->t->credentialRejected(tPtr,com,"old");
return ADD_REJECTED;
}
if (_com == com) {
return ADD_ACCEPTED_REDUNDANT;
}
switch (com.verify(RR, tPtr)) {
switch(com.verify(RR,tPtr)) {
default:
RR->t->credentialRejected(tPtr, com, "invalid");
RR->t->credentialRejected(tPtr,com,"invalid");
return ADD_REJECTED;
case 0:
// printf("%.16llx %.10llx replacing COM %lld with %lld\n", com.networkId(), com.issuedTo().toInt(), _com.timestamp(), com.timestamp()); fflush(stdout);
//printf("%.16llx %.10llx replacing COM %lld with %lld\n", com.networkId(), com.issuedTo().toInt(), _com.timestamp(), com.timestamp()); fflush(stdout);
_com = com;
return ADD_ACCEPTED_NEW;
case 1:
@ -131,13 +137,13 @@ Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironme
}
// Template out addCredential() for many cred types to avoid copypasta
template <typename C>
static Membership::AddCredentialResult _addCredImpl(Hashtable<uint32_t, C>& remoteCreds, const Hashtable<uint64_t, int64_t>& revocations, const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const C& cred)
template<typename C>
static Membership::AddCredentialResult _addCredImpl(Hashtable<uint32_t,C> &remoteCreds,const Hashtable<uint64_t,int64_t> &revocations,const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const C &cred)
{
C* rc = remoteCreds.get(cred.id());
C *rc = remoteCreds.get(cred.id());
if (rc) {
if (rc->timestamp() > cred.timestamp()) {
RR->t->credentialRejected(tPtr, cred, "old");
RR->t->credentialRejected(tPtr,cred,"old");
return Membership::ADD_REJECTED;
}
if (*rc == cred) {
@ -145,18 +151,18 @@ static Membership::AddCredentialResult _addCredImpl(Hashtable<uint32_t, C>& remo
}
}
const int64_t* const rt = revocations.get(Membership::credentialKey(C::credentialType(), cred.id()));
if ((rt) && (*rt >= cred.timestamp())) {
RR->t->credentialRejected(tPtr, cred, "revoked");
const int64_t *const rt = revocations.get(Membership::credentialKey(C::credentialType(),cred.id()));
if ((rt)&&(*rt >= cred.timestamp())) {
RR->t->credentialRejected(tPtr,cred,"revoked");
return Membership::ADD_REJECTED;
}
switch (cred.verify(RR, tPtr)) {
switch(cred.verify(RR,tPtr)) {
default:
RR->t->credentialRejected(tPtr, cred, "invalid");
RR->t->credentialRejected(tPtr,cred,"invalid");
return Membership::ADD_REJECTED;
case 0:
if (! rc) {
if (!rc) {
rc = &(remoteCreds[cred.id()]);
}
*rc = cred;
@ -166,29 +172,20 @@ static Membership::AddCredentialResult _addCredImpl(Hashtable<uint32_t, C>& remo
}
}
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Tag& tag)
{
return _addCredImpl<Tag>(_remoteTags, _revocations, RR, tPtr, nconf, tag);
}
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Capability& cap)
{
return _addCredImpl<Capability>(_remoteCaps, _revocations, RR, tPtr, nconf, cap);
}
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const CertificateOfOwnership& coo)
{
return _addCredImpl<CertificateOfOwnership>(_remoteCoos, _revocations, RR, tPtr, nconf, coo);
}
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Tag &tag) { return _addCredImpl<Tag>(_remoteTags,_revocations,RR,tPtr,nconf,tag); }
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Capability &cap) { return _addCredImpl<Capability>(_remoteCaps,_revocations,RR,tPtr,nconf,cap); }
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfOwnership &coo) { return _addCredImpl<CertificateOfOwnership>(_remoteCoos,_revocations,RR,tPtr,nconf,coo); }
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Revocation& rev)
Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Revocation &rev)
{
int64_t* rt;
switch (rev.verify(RR, tPtr)) {
int64_t *rt;
switch(rev.verify(RR,tPtr)) {
default:
RR->t->credentialRejected(tPtr, rev, "invalid");
RR->t->credentialRejected(tPtr,rev,"invalid");
return ADD_REJECTED;
case 0: {
const Credential::Type ct = rev.type();
switch (ct) {
switch(ct) {
case Credential::CREDENTIAL_TYPE_COM:
if (rev.threshold() > _comRevocationThreshold) {
_comRevocationThreshold = rev.threshold();
@ -198,7 +195,7 @@ Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironme
case Credential::CREDENTIAL_TYPE_CAPABILITY:
case Credential::CREDENTIAL_TYPE_TAG:
case Credential::CREDENTIAL_TYPE_COO:
rt = &(_revocations[credentialKey(ct, rev.credentialId())]);
rt = &(_revocations[credentialKey(ct,rev.credentialId())]);
if (*rt < rev.threshold()) {
*rt = rev.threshold();
_comRevocationThreshold = rev.threshold();
@ -206,7 +203,7 @@ Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironme
}
return ADD_ACCEPTED_REDUNDANT;
default:
RR->t->credentialRejected(tPtr, rev, "invalid");
RR->t->credentialRejected(tPtr,rev,"invalid");
return ADD_REJECTED;
}
}
@ -215,11 +212,11 @@ Membership::AddCredentialResult Membership::addCredential(const RuntimeEnvironme
}
}
void Membership::clean(const int64_t now, const NetworkConfig& nconf)
void Membership::clean(const int64_t now,const NetworkConfig &nconf)
{
_cleanCredImpl<Tag>(nconf, _remoteTags);
_cleanCredImpl<Capability>(nconf, _remoteCaps);
_cleanCredImpl<CertificateOfOwnership>(nconf, _remoteCoos);
_cleanCredImpl<Tag>(nconf,_remoteTags);
_cleanCredImpl<Capability>(nconf,_remoteCaps);
_cleanCredImpl<CertificateOfOwnership>(nconf,_remoteCoos);
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,17 +14,17 @@
#ifndef ZT_MEMBERSHIP_HPP
#define ZT_MEMBERSHIP_HPP
#include "../include/ZeroTierOne.h"
#include "Capability.hpp"
#include "CertificateOfMembership.hpp"
#include <stdint.h>
#include "Constants.hpp"
#include "../include/ZeroTierOne.h"
#include "Credential.hpp"
#include "Hashtable.hpp"
#include "NetworkConfig.hpp"
#include "Revocation.hpp"
#include "CertificateOfMembership.hpp"
#include "Capability.hpp"
#include "Tag.hpp"
#include <stdint.h>
#include "Revocation.hpp"
#include "NetworkConfig.hpp"
#define ZT_MEMBERSHIP_CRED_ID_UNUSED 0xffffffffffffffffULL
@ -40,9 +40,16 @@ class Network;
*
* This class is not thread safe. It must be locked externally.
*/
class Membership {
public:
enum AddCredentialResult { ADD_REJECTED, ADD_ACCEPTED_NEW, ADD_ACCEPTED_REDUNDANT, ADD_DEFERRED_FOR_WHOIS };
class Membership
{
public:
enum AddCredentialResult
{
ADD_REJECTED,
ADD_ACCEPTED_NEW,
ADD_ACCEPTED_REDUNDANT,
ADD_DEFERRED_FOR_WHOIS
};
Membership();
@ -55,20 +62,11 @@ class Membership {
* @param peerAddress Address of member peer (the one that this Membership describes)
* @param nconf My network config
*/
void pushCredentials(const RuntimeEnvironment* RR, void* tPtr, const int64_t now, const Address& peerAddress, const NetworkConfig& nconf);
void pushCredentials(const RuntimeEnvironment *RR,void *tPtr,const int64_t now,const Address &peerAddress,const NetworkConfig &nconf);
inline int64_t lastPushedCredentials()
{
return _lastPushedCredentials;
}
inline int64_t comTimestamp()
{
return _com.timestamp();
}
inline int64_t comRevocationThreshold()
{
return _comRevocationThreshold;
}
inline int64_t lastPushedCredentials() { return _lastPushedCredentials; }
inline int64_t comTimestamp() { return _com.timestamp(); }
inline int64_t comRevocationThreshold() { return _comRevocationThreshold; }
/**
* Check whether we should push MULTICAST_LIKEs to this peer, and update last sent time if true
@ -92,14 +90,14 @@ class Membership {
* @param otherNodeIdentity Identity of remote node
* @return True if this peer is allowed on this network at all
*/
inline bool isAllowedOnNetwork(const NetworkConfig& thisNodeNetworkConfig, const Identity& otherNodeIdentity) const
inline bool isAllowedOnNetwork(const NetworkConfig &thisNodeNetworkConfig, const Identity &otherNodeIdentity) const
{
return thisNodeNetworkConfig.isPublic() || (((_com.timestamp() > _comRevocationThreshold) && (thisNodeNetworkConfig.com.agreesWith(_com, otherNodeIdentity))));
}
inline bool recentlyAssociated(const int64_t now) const
{
return ((_com) && ((now - _com.timestamp()) < ZT_PEER_ACTIVITY_TIMEOUT));
return ((_com)&&((now - _com.timestamp()) < ZT_PEER_ACTIVITY_TIMEOUT));
}
/**
@ -110,17 +108,18 @@ class Membership {
* @param r Resource to check
* @return True if this peer has a certificate of ownership for the given resource
*/
template <typename T> inline bool hasCertificateOfOwnershipFor(const NetworkConfig& nconf, const T& r) const
template<typename T>
inline bool hasCertificateOfOwnershipFor(const NetworkConfig &nconf,const T &r) const
{
uint32_t* k = (uint32_t*)0;
CertificateOfOwnership* v = (CertificateOfOwnership*)0;
Hashtable<uint32_t, CertificateOfOwnership>::Iterator i(*(const_cast<Hashtable<uint32_t, CertificateOfOwnership>*>(&_remoteCoos)));
while (i.next(k, v)) {
if (_isCredentialTimestampValid(nconf, *v) && (v->owns(r))) {
uint32_t *k = (uint32_t *)0;
CertificateOfOwnership *v = (CertificateOfOwnership *)0;
Hashtable< uint32_t,CertificateOfOwnership >::Iterator i(*(const_cast< Hashtable< uint32_t,CertificateOfOwnership> *>(&_remoteCoos)));
while (i.next(k,v)) {
if (_isCredentialTimestampValid(nconf,*v)&&(v->owns(r))) {
return true;
}
}
return _isV6NDPEmulated(nconf, r);
return _isV6NDPEmulated(nconf,r);
}
/**
@ -130,36 +129,36 @@ class Membership {
* @param id Tag ID
* @return Pointer to tag or NULL if not found
*/
inline const Tag* getTag(const NetworkConfig& nconf, const uint32_t id) const
inline const Tag *getTag(const NetworkConfig &nconf,const uint32_t id) const
{
const Tag* const t = _remoteTags.get(id);
return (((t) && (_isCredentialTimestampValid(nconf, *t))) ? t : (Tag*)0);
const Tag *const t = _remoteTags.get(id);
return (((t)&&(_isCredentialTimestampValid(nconf,*t))) ? t : (Tag *)0);
}
/**
* Validate and add a credential if signature is okay and it's otherwise good
*/
AddCredentialResult addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const CertificateOfMembership& com);
AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfMembership &com);
/**
* Validate and add a credential if signature is okay and it's otherwise good
*/
AddCredentialResult addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Tag& tag);
AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Tag &tag);
/**
* Validate and add a credential if signature is okay and it's otherwise good
*/
AddCredentialResult addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Capability& cap);
AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Capability &cap);
/**
* Validate and add a credential if signature is okay and it's otherwise good
*/
AddCredentialResult addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const CertificateOfOwnership& coo);
AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfOwnership &coo);
/**
* Validate and add a credential if signature is okay and it's otherwise good
*/
AddCredentialResult addCredential(const RuntimeEnvironment* RR, void* tPtr, const NetworkConfig& nconf, const Revocation& rev);
AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Revocation &rev);
/**
* Clean internal databases of stale entries
@ -167,30 +166,24 @@ class Membership {
* @param now Current time
* @param nconf Current network configuration
*/
void clean(const int64_t now, const NetworkConfig& nconf);
void clean(const int64_t now,const NetworkConfig &nconf);
/**
* Generates a key for the internal use in indexing credentials by type and credential ID
*/
static uint64_t credentialKey(const Credential::Type& t, const uint32_t i)
{
return (((uint64_t)t << 32) | (uint64_t)i);
}
static uint64_t credentialKey(const Credential::Type &t,const uint32_t i) { return (((uint64_t)t << 32) | (uint64_t)i); }
private:
inline bool _isV6NDPEmulated(const NetworkConfig& nconf, const MAC& m) const
private:
inline bool _isV6NDPEmulated(const NetworkConfig &nconf,const MAC &m) const { return false; }
inline bool _isV6NDPEmulated(const NetworkConfig &nconf,const InetAddress &ip) const
{
return false;
}
inline bool _isV6NDPEmulated(const NetworkConfig& nconf, const InetAddress& ip) const
{
if ((ip.isV6()) && (nconf.ndpEmulation())) {
const InetAddress sixpl(InetAddress::makeIpv66plane(nconf.networkId, nconf.issuedTo.toInt()));
for (unsigned int i = 0; i < nconf.staticIpCount; ++i) {
if ((ip.isV6())&&(nconf.ndpEmulation())) {
const InetAddress sixpl(InetAddress::makeIpv66plane(nconf.networkId,nconf.issuedTo.toInt()));
for(unsigned int i=0;i<nconf.staticIpCount;++i) {
if (nconf.staticIps[i].ipsEqual(sixpl)) {
bool prefixMatches = true;
for (unsigned int j = 0; j < 5; ++j) { // check for match on /40
if ((((const struct sockaddr_in6*)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6*)&sixpl)->sin6_addr.s6_addr)[j]) {
for(unsigned int j=0;j<5;++j) { // check for match on /40
if ((((const struct sockaddr_in6 *)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6 *)&sixpl)->sin6_addr.s6_addr)[j]) {
prefixMatches = false;
break;
}
@ -202,12 +195,12 @@ class Membership {
}
}
const InetAddress rfc4193(InetAddress::makeIpv6rfc4193(nconf.networkId, nconf.issuedTo.toInt()));
for (unsigned int i = 0; i < nconf.staticIpCount; ++i) {
const InetAddress rfc4193(InetAddress::makeIpv6rfc4193(nconf.networkId,nconf.issuedTo.toInt()));
for(unsigned int i=0;i<nconf.staticIpCount;++i) {
if (nconf.staticIps[i].ipsEqual(rfc4193)) {
bool prefixMatches = true;
for (unsigned int j = 0; j < 11; ++j) { // check for match on /88
if ((((const struct sockaddr_in6*)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6*)&rfc4193)->sin6_addr.s6_addr)[j]) {
for(unsigned int j=0;j<11;++j) { // check for match on /88
if ((((const struct sockaddr_in6 *)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6 *)&rfc4193)->sin6_addr.s6_addr)[j]) {
prefixMatches = false;
break;
}
@ -222,23 +215,25 @@ class Membership {
return false;
}
template <typename C> inline bool _isCredentialTimestampValid(const NetworkConfig& nconf, const C& remoteCredential) const
template<typename C>
inline bool _isCredentialTimestampValid(const NetworkConfig &nconf,const C &remoteCredential) const
{
const int64_t ts = remoteCredential.timestamp();
if (((ts >= nconf.timestamp) ? (ts - nconf.timestamp) : (nconf.timestamp - ts)) <= nconf.credentialTimeMaxDelta) {
const int64_t* threshold = _revocations.get(credentialKey(C::credentialType(), remoteCredential.id()));
return ((! threshold) || (ts > *threshold));
const int64_t *threshold = _revocations.get(credentialKey(C::credentialType(),remoteCredential.id()));
return ((!threshold)||(ts > *threshold));
}
return false;
}
template <typename C> inline void _cleanCredImpl(const NetworkConfig& nconf, Hashtable<uint32_t, C>& remoteCreds)
template<typename C>
inline void _cleanCredImpl(const NetworkConfig &nconf,Hashtable<uint32_t,C> &remoteCreds)
{
uint32_t* k = (uint32_t*)0;
C* v = (C*)0;
typename Hashtable<uint32_t, C>::Iterator i(remoteCreds);
while (i.next(k, v)) {
if (! _isCredentialTimestampValid(nconf, *v)) {
uint32_t *k = (uint32_t *)0;
C *v = (C *)0;
typename Hashtable<uint32_t,C>::Iterator i(remoteCreds);
while (i.next(k,v)) {
if (!_isCredentialTimestampValid(nconf,*v)) {
remoteCreds.erase(*k);
}
}
@ -257,39 +252,45 @@ class Membership {
CertificateOfMembership _com;
// Revocations by credentialKey()
Hashtable<uint64_t, int64_t> _revocations;
Hashtable< uint64_t,int64_t > _revocations;
// Remote credentials that we have received from this member (and that are valid)
Hashtable<uint32_t, Tag> _remoteTags;
Hashtable<uint32_t, Capability> _remoteCaps;
Hashtable<uint32_t, CertificateOfOwnership> _remoteCoos;
Hashtable< uint32_t,Tag > _remoteTags;
Hashtable< uint32_t,Capability > _remoteCaps;
Hashtable< uint32_t,CertificateOfOwnership > _remoteCoos;
public:
class CapabilityIterator {
public:
CapabilityIterator(Membership& m, const NetworkConfig& nconf) : _hti(m._remoteCaps), _k((uint32_t*)0), _c((Capability*)0), _m(m), _nconf(nconf)
public:
class CapabilityIterator
{
public:
CapabilityIterator(Membership &m,const NetworkConfig &nconf) :
_hti(m._remoteCaps),
_k((uint32_t *)0),
_c((Capability *)0),
_m(m),
_nconf(nconf)
{
}
inline Capability* next()
inline Capability *next()
{
while (_hti.next(_k, _c)) {
if (_m._isCredentialTimestampValid(_nconf, *_c)) {
while (_hti.next(_k,_c)) {
if (_m._isCredentialTimestampValid(_nconf,*_c)) {
return _c;
}
}
return (Capability*)0;
return (Capability *)0;
}
private:
Hashtable<uint32_t, Capability>::Iterator _hti;
uint32_t* _k;
Capability* _c;
Membership& _m;
const NetworkConfig& _nconf;
private:
Hashtable< uint32_t,Capability >::Iterator _hti;
uint32_t *_k;
Capability *_c;
Membership &_m;
const NetworkConfig &_nconf;
};
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,163 +4,269 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
// clang-format off
#include <prometheus/simpleapi.h>
#include <prometheus/histogram.h>
// clang-format on
namespace prometheus {
namespace simpleapi {
std::shared_ptr<Registry> registry_ptr = std::make_shared<Registry>();
Registry& registry = *registry_ptr;
SaveToFile saver;
} // namespace simpleapi
} // namespace prometheus
namespace simpleapi {
std::shared_ptr<Registry> registry_ptr = std::make_shared<Registry>();
Registry& registry = *registry_ptr;
SaveToFile saver;
}
}
namespace ZeroTier {
namespace Metrics {
// Packet Type Counts
prometheus::simpleapi::counter_family_t packets { "zt_packet", "ZeroTier packet type counts" };
namespace Metrics {
// Packet Type Counts
prometheus::simpleapi::counter_family_t packets
{ "zt_packet", "ZeroTier packet type counts"};
// Incoming packets
prometheus::simpleapi::counter_metric_t pkt_nop_in { packets.Add({ { "packet_type", "nop" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_in { packets.Add({ { "packet_type", "error" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ack_in { packets.Add({ { "packet_type", "ack" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_qos_in { packets.Add({ { "packet_type", "qos" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_hello_in { packets.Add({ { "packet_type", "hello" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ok_in { packets.Add({ { "packet_type", "ok" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_whois_in { packets.Add({ { "packet_type", "whois" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_rendezvous_in { packets.Add({ { "packet_type", "rendezvous" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_frame_in { packets.Add({ { "packet_type", "frame" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ext_frame_in { packets.Add({ { "packet_type", "ext_frame" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_echo_in { packets.Add({ { "packet_type", "echo" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_like_in { packets.Add({ { "packet_type", "multicast_like" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_credentials_in { packets.Add({ { "packet_type", "network_credentials" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_config_request_in { packets.Add({ { "packet_type", "network_config_request" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_config_in { packets.Add({ { "packet_type", "network_config" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_gather_in { packets.Add({ { "packet_type", "multicast_gather" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_frame_in { packets.Add({ { "packet_type", "multicast_frame" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_in { packets.Add({ { "packet_type", "push_direct_paths" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_user_message_in { packets.Add({ { "packet_type", "user_message" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_remote_trace_in { packets.Add({ { "packet_type", "remote_trace" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_in { packets.Add({ { "packet_type", "path_negotiation_request" }, { "direction", "rx" } }) };
// Incoming packets
prometheus::simpleapi::counter_metric_t pkt_nop_in
{ packets.Add({{"packet_type", "nop"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_in
{ packets.Add({{"packet_type", "error"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ack_in
{ packets.Add({{"packet_type", "ack"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_qos_in
{ packets.Add({{"packet_type", "qos"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_hello_in
{ packets.Add({{"packet_type", "hello"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ok_in
{ packets.Add({{"packet_type", "ok"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_whois_in
{ packets.Add({{"packet_type", "whois"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_rendezvous_in
{ packets.Add({{"packet_type", "rendezvous"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_frame_in
{ packets.Add({{"packet_type", "frame"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ext_frame_in
{ packets.Add({{"packet_type", "ext_frame"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_echo_in
{ packets.Add({{"packet_type", "echo"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_like_in
{ packets.Add({{"packet_type", "multicast_like"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_credentials_in
{ packets.Add({{"packet_type", "network_credentials"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_config_request_in
{ packets.Add({{"packet_type", "network_config_request"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_config_in
{ packets.Add({{"packet_type", "network_config"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_gather_in
{ packets.Add({{"packet_type", "multicast_gather"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_frame_in
{ packets.Add({{"packet_type", "multicast_frame"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_in
{ packets.Add({{"packet_type", "push_direct_paths"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_user_message_in
{ packets.Add({{"packet_type", "user_message"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_remote_trace_in
{ packets.Add({{"packet_type", "remote_trace"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_in
{ packets.Add({{"packet_type", "path_negotiation_request"}, {"direction", "rx"}}) };
// Outgoing packets
prometheus::simpleapi::counter_metric_t pkt_nop_out { packets.Add({ { "packet_type", "nop" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_out { packets.Add({ { "packet_type", "error" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ack_out { packets.Add({ { "packet_type", "ack" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_qos_out { packets.Add({ { "packet_type", "qos" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_hello_out { packets.Add({ { "packet_type", "hello" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ok_out { packets.Add({ { "packet_type", "ok" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_whois_out { packets.Add({ { "packet_type", "whois" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_rendezvous_out { packets.Add({ { "packet_type", "rendezvous" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_frame_out { packets.Add({ { "packet_type", "frame" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_ext_frame_out { packets.Add({ { "packet_type", "ext_frame" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_echo_out { packets.Add({ { "packet_type", "echo" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_like_out { packets.Add({ { "packet_type", "multicast_like" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_credentials_out { packets.Add({ { "packet_type", "network_credentials" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_config_request_out { packets.Add({ { "packet_type", "network_config_request" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_network_config_out { packets.Add({ { "packet_type", "network_config" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_gather_out { packets.Add({ { "packet_type", "multicast_gather" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_multicast_frame_out { packets.Add({ { "packet_type", "multicast_frame" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_out { packets.Add({ { "packet_type", "push_direct_paths" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_user_message_out { packets.Add({ { "packet_type", "user_message" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_remote_trace_out { packets.Add({ { "packet_type", "remote_trace" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_out { packets.Add({ { "packet_type", "path_negotiation_request" }, { "direction", "tx" } }) };
// Outgoing packets
prometheus::simpleapi::counter_metric_t pkt_nop_out
{ packets.Add({{"packet_type", "nop"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_out
{ packets.Add({{"packet_type", "error"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ack_out
{ packets.Add({{"packet_type", "ack"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_qos_out
{ packets.Add({{"packet_type", "qos"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_hello_out
{ packets.Add({{"packet_type", "hello"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ok_out
{ packets.Add({{"packet_type", "ok"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_whois_out
{ packets.Add({{"packet_type", "whois"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_rendezvous_out
{ packets.Add({{"packet_type", "rendezvous"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_frame_out
{ packets.Add({{"packet_type", "frame"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_ext_frame_out
{ packets.Add({{"packet_type", "ext_frame"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_echo_out
{ packets.Add({{"packet_type", "echo"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_like_out
{ packets.Add({{"packet_type", "multicast_like"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_credentials_out
{ packets.Add({{"packet_type", "network_credentials"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_config_request_out
{ packets.Add({{"packet_type", "network_config_request"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_network_config_out
{ packets.Add({{"packet_type", "network_config"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_gather_out
{ packets.Add({{"packet_type", "multicast_gather"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_multicast_frame_out
{ packets.Add({{"packet_type", "multicast_frame"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_out
{ packets.Add({{"packet_type", "push_direct_paths"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_user_message_out
{ packets.Add({{"packet_type", "user_message"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_remote_trace_out
{ packets.Add({{"packet_type", "remote_trace"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_out
{ packets.Add({{"packet_type", "path_negotiation_request"}, {"direction", "tx"}}) };
// Packet Error Counts
prometheus::simpleapi::counter_family_t packet_errors { "zt_packet_error", "ZeroTier packet errors" };
// Incoming Error Counts
prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_in { packet_errors.Add({ { "error_type", "obj_not_found" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_in { packet_errors.Add({ { "error_type", "unsupported_operation" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_in { packet_errors.Add({ { "error_type", "identity_collision" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_in { packet_errors.Add({ { "error_type", "need_membership_certificate" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_in { packet_errors.Add({ { "error_type", "network_access_denied" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_in { packet_errors.Add({ { "error_type", "unwanted_multicast" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_in { packet_errors.Add({ { "error_type", "authentication_required" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_in { packet_errors.Add({ { "error_type", "internal_server_error" }, { "direction", "rx" } }) };
// Packet Error Counts
prometheus::simpleapi::counter_family_t packet_errors
{ "zt_packet_error", "ZeroTier packet errors"};
// Outgoing Error Counts
prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_out { packet_errors.Add({ { "error_type", "obj_not_found" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_out { packet_errors.Add({ { "error_type", "unsupported_operation" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_out { packet_errors.Add({ { "error_type", "identity_collision" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_out { packet_errors.Add({ { "error_type", "need_membership_certificate" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_out { packet_errors.Add({ { "error_type", "network_access_denied" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_out { packet_errors.Add({ { "error_type", "unwanted_multicast" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_out { packet_errors.Add({ { "error_type", "authentication_required" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_out { packet_errors.Add({ { "error_type", "internal_server_error" }, { "direction", "tx" } }) };
// Incoming Error Counts
prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_in
{ packet_errors.Add({{"error_type", "obj_not_found"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_in
{ packet_errors.Add({{"error_type", "unsupported_operation"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_in
{ packet_errors.Add({{"error_type", "identity_collision"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_in
{ packet_errors.Add({{"error_type", "need_membership_certificate"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_in
{ packet_errors.Add({{"error_type", "network_access_denied"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_in
{ packet_errors.Add({{"error_type", "unwanted_multicast"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_in
{ packet_errors.Add({{"error_type", "authentication_required"}, {"direction", "rx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_in
{ packet_errors.Add({{"error_type", "internal_server_error"}, {"direction", "rx"}}) };
// Data Sent/Received Metrics
prometheus::simpleapi::counter_family_t data { "zt_data", "number of bytes ZeroTier has transmitted or received" };
prometheus::simpleapi::counter_metric_t udp_recv { data.Add({ { "protocol", "udp" }, { "direction", "rx" } }) };
prometheus::simpleapi::counter_metric_t udp_send { data.Add({ { "protocol", "udp" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t tcp_send { data.Add({ { "protocol", "tcp" }, { "direction", "tx" } }) };
prometheus::simpleapi::counter_metric_t tcp_recv { data.Add({ { "protocol", "tcp" }, { "direction", "rx" } }) };
// Outgoing Error Counts
prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_out
{ packet_errors.Add({{"error_type", "obj_not_found"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_out
{ packet_errors.Add({{"error_type", "unsupported_operation"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_out
{ packet_errors.Add({{"error_type", "identity_collision"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_out
{ packet_errors.Add({{"error_type", "need_membership_certificate"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_out
{ packet_errors.Add({{"error_type", "network_access_denied"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_out
{ packet_errors.Add({{"error_type", "unwanted_multicast"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_out
{ packet_errors.Add({{"error_type", "authentication_required"}, {"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_out
{ packet_errors.Add({{"error_type", "internal_server_error"}, {"direction", "tx"}}) };
// Network Metrics
prometheus::simpleapi::gauge_metric_t network_num_joined { "zt_num_networks", "number of networks this instance is joined to" };
prometheus::simpleapi::gauge_family_t network_num_multicast_groups { "zt_network_multicast_groups_subscribed", "number of multicast groups networks are subscribed to" };
prometheus::simpleapi::counter_family_t network_packets { "zt_network_packets", "number of incoming/outgoing packets per network" };
// Data Sent/Received Metrics
prometheus::simpleapi::counter_family_t data
{ "zt_data", "number of bytes ZeroTier has transmitted or received" };
prometheus::simpleapi::counter_metric_t udp_recv
{ data.Add({{"protocol","udp"},{"direction","rx"}}) };
prometheus::simpleapi::counter_metric_t udp_send
{ data.Add({{"protocol","udp"},{"direction","tx"}}) };
prometheus::simpleapi::counter_metric_t tcp_send
{ data.Add({{"protocol","tcp"},{"direction", "tx"}}) };
prometheus::simpleapi::counter_metric_t tcp_recv
{ data.Add({{"protocol","tcp"},{"direction", "rx"}}) };
// Network Metrics
prometheus::simpleapi::gauge_metric_t network_num_joined
{ "zt_num_networks", "number of networks this instance is joined to" };
prometheus::simpleapi::gauge_family_t network_num_multicast_groups
{ "zt_network_multicast_groups_subscribed", "number of multicast groups networks are subscribed to" };
prometheus::simpleapi::counter_family_t network_packets
{ "zt_network_packets", "number of incoming/outgoing packets per network" };
#ifndef ZT_NO_PEER_METRICS
// PeerMetrics
prometheus::CustomFamily<prometheus::Histogram<uint64_t> >& peer_latency = prometheus::Builder<prometheus::Histogram<uint64_t> >().Name("zt_peer_latency").Help("peer latency (ms)").Register(prometheus::simpleapi::registry);
prometheus::simpleapi::gauge_family_t peer_path_count { "zt_peer_path_count", "number of paths to peer" };
prometheus::simpleapi::counter_family_t peer_packets { "zt_peer_packets", "number of packets to/from a peer" };
prometheus::simpleapi::counter_family_t peer_packet_errors { "zt_peer_packet_errors", "number of incoming packet errors from a peer" };
// PeerMetrics
prometheus::CustomFamily<prometheus::Histogram<uint64_t>> &peer_latency =
prometheus::Builder<prometheus::Histogram<uint64_t>>()
.Name("zt_peer_latency")
.Help("peer latency (ms)")
.Register(prometheus::simpleapi::registry);
prometheus::simpleapi::gauge_family_t peer_path_count
{ "zt_peer_path_count", "number of paths to peer" };
prometheus::simpleapi::counter_family_t peer_packets
{ "zt_peer_packets", "number of packets to/from a peer" };
prometheus::simpleapi::counter_family_t peer_packet_errors
{ "zt_peer_packet_errors" , "number of incoming packet errors from a peer" };
#endif
// General Controller Metrics
prometheus::simpleapi::gauge_metric_t network_count { "controller_network_count", "number of networks the controller is serving" };
prometheus::simpleapi::gauge_metric_t member_count { "controller_member_count", "number of network members the controller is serving" };
prometheus::simpleapi::counter_metric_t network_changes { "controller_network_change_count", "number of times a network configuration is changed" };
prometheus::simpleapi::counter_metric_t member_changes { "controller_member_change_count", "number of times a network member configuration is changed" };
prometheus::simpleapi::counter_metric_t member_auths { "controller_member_auth_count", "number of network member auths" };
prometheus::simpleapi::counter_metric_t member_deauths { "controller_member_deauth_count", "number of network member deauths" };
// General Controller Metrics
prometheus::simpleapi::gauge_metric_t network_count
{"controller_network_count", "number of networks the controller is serving"};
prometheus::simpleapi::gauge_metric_t member_count
{"controller_member_count", "number of network members the controller is serving"};
prometheus::simpleapi::counter_metric_t network_changes
{"controller_network_change_count", "number of times a network configuration is changed"};
prometheus::simpleapi::counter_metric_t member_changes
{"controller_member_change_count", "number of times a network member configuration is changed"};
prometheus::simpleapi::counter_metric_t member_auths
{"controller_member_auth_count", "number of network member auths"};
prometheus::simpleapi::counter_metric_t member_deauths
{"controller_member_deauth_count", "number of network member deauths"};
prometheus::simpleapi::gauge_metric_t network_config_request_queue_size { "controller_network_config_request_queue", "number of entries in the request queue for network configurations" };
prometheus::simpleapi::gauge_metric_t network_config_request_queue_size
{ "controller_network_config_request_queue", "number of entries in the request queue for network configurations" };
prometheus::simpleapi::counter_metric_t sso_expiration_checks
{ "controller_sso_expiration_checks", "number of sso expiration checks done" };
prometheus::simpleapi::counter_metric_t sso_expiration_checks { "controller_sso_expiration_checks", "number of sso expiration checks done" };
prometheus::simpleapi::counter_metric_t sso_member_deauth
{ "controller_sso_timeouts", "number of sso timeouts" };
prometheus::simpleapi::counter_metric_t sso_member_deauth { "controller_sso_timeouts", "number of sso timeouts" };
prometheus::simpleapi::counter_metric_t network_config_request { "controller_network_config_request", "count of config requests handled" };
prometheus::simpleapi::gauge_metric_t network_config_request_threads { "controller_network_config_request_threads", "number of active network config handling threads" };
prometheus::simpleapi::counter_metric_t db_get_network { "controller_db_get_network", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_and_member { "controller_db_get_network_and_member", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_and_member_and_summary { "controller_db_get_networK_and_member_summary", "counter" };
prometheus::simpleapi::counter_metric_t db_get_member_list { "controller_db_get_member_list", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_list { "controller_db_get_network_list", "counter" };
prometheus::simpleapi::counter_metric_t db_member_change { "controller_db_member_change", "counter" };
prometheus::simpleapi::counter_metric_t db_network_change { "controller_db_network_change", "counter" };
prometheus::simpleapi::counter_metric_t network_config_request
{ "controller_network_config_request", "count of config requests handled" };
prometheus::simpleapi::gauge_metric_t network_config_request_threads
{ "controller_network_config_request_threads", "number of active network config handling threads" };
prometheus::simpleapi::counter_metric_t db_get_network
{ "controller_db_get_network", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_and_member
{ "controller_db_get_network_and_member", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_and_member_and_summary
{ "controller_db_get_networK_and_member_summary", "counter" };
prometheus::simpleapi::counter_metric_t db_get_member_list
{ "controller_db_get_member_list", "counter" };
prometheus::simpleapi::counter_metric_t db_get_network_list
{ "controller_db_get_network_list", "counter" };
prometheus::simpleapi::counter_metric_t db_member_change
{ "controller_db_member_change", "counter" };
prometheus::simpleapi::counter_metric_t db_network_change
{ "controller_db_network_change", "counter" };
#ifdef ZT_CONTROLLER_USE_LIBPQ
// Central Controller Metrics
prometheus::simpleapi::counter_metric_t pgsql_mem_notification { "controller_pgsql_member_notifications_received", "number of member change notifications received via pgsql NOTIFY" };
prometheus::simpleapi::counter_metric_t pgsql_net_notification { "controller_pgsql_network_notifications_received", "number of network change notifications received via pgsql NOTIFY" };
prometheus::simpleapi::counter_metric_t pgsql_node_checkin { "controller_pgsql_node_checkin_count", "number of node check-ins (pgsql)" };
prometheus::simpleapi::counter_metric_t pgsql_commit_ticks { "controller_pgsql_commit_ticks", "number of commit ticks run (pgsql)" };
prometheus::simpleapi::counter_metric_t db_get_sso_info { "controller_db_get_sso_info", "counter" };
// Central Controller Metrics
prometheus::simpleapi::counter_metric_t pgsql_mem_notification
{ "controller_pgsql_member_notifications_received", "number of member change notifications received via pgsql NOTIFY" };
prometheus::simpleapi::counter_metric_t pgsql_net_notification
{ "controller_pgsql_network_notifications_received", "number of network change notifications received via pgsql NOTIFY" };
prometheus::simpleapi::counter_metric_t pgsql_node_checkin
{ "controller_pgsql_node_checkin_count", "number of node check-ins (pgsql)" };
prometheus::simpleapi::counter_metric_t pgsql_commit_ticks
{ "controller_pgsql_commit_ticks", "number of commit ticks run (pgsql)" };
prometheus::simpleapi::counter_metric_t db_get_sso_info
{ "controller_db_get_sso_info", "counter" };
prometheus::simpleapi::counter_metric_t redis_mem_notification { "controller_redis_member_notifications_received", "number of member change notifications received via redis" };
prometheus::simpleapi::counter_metric_t redis_net_notification { "controller_redis_network_notifications_received", "number of network change notifications received via redis" };
prometheus::simpleapi::counter_metric_t redis_node_checkin { "controller_redis_node_checkin_count", "number of node check-ins (redis)" };
prometheus::simpleapi::counter_metric_t redis_mem_notification
{ "controller_redis_member_notifications_received", "number of member change notifications received via redis" };
prometheus::simpleapi::counter_metric_t redis_net_notification
{ "controller_redis_network_notifications_received", "number of network change notifications received via redis" };
prometheus::simpleapi::counter_metric_t redis_node_checkin
{ "controller_redis_node_checkin_count", "number of node check-ins (redis)" };
// Central DB Pool Metrics
prometheus::simpleapi::counter_metric_t conn_counter { "controller_pgsql_connections_created", "number of pgsql connections created" };
prometheus::simpleapi::counter_metric_t max_pool_size { "controller_pgsql_max_conn_pool_size", "max connection pool size for postgres" };
prometheus::simpleapi::counter_metric_t min_pool_size { "controller_pgsql_min_conn_pool_size", "minimum connection pool size for postgres" };
prometheus::simpleapi::gauge_metric_t pool_avail { "controller_pgsql_available_conns", "number of available postgres connections" };
prometheus::simpleapi::gauge_metric_t pool_in_use { "controller_pgsql_in_use_conns", "number of postgres database connections in use" };
prometheus::simpleapi::counter_metric_t pool_errors { "controller_pgsql_connection_errors", "number of connection errors the connection pool has seen" };
// Central DB Pool Metrics
prometheus::simpleapi::counter_metric_t conn_counter
{ "controller_pgsql_connections_created", "number of pgsql connections created"};
prometheus::simpleapi::counter_metric_t max_pool_size
{ "controller_pgsql_max_conn_pool_size", "max connection pool size for postgres"};
prometheus::simpleapi::counter_metric_t min_pool_size
{ "controller_pgsql_min_conn_pool_size", "minimum connection pool size for postgres" };
prometheus::simpleapi::gauge_metric_t pool_avail
{ "controller_pgsql_available_conns", "number of available postgres connections" };
prometheus::simpleapi::gauge_metric_t pool_in_use
{ "controller_pgsql_in_use_conns", "number of postgres database connections in use" };
prometheus::simpleapi::counter_metric_t pool_errors
{ "controller_pgsql_connection_errors", "number of connection errors the connection pool has seen" };
#endif
} // namespace Metrics
} // namespace ZeroTier
}
}

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -12,154 +12,155 @@
#ifndef METRICS_H_
#define METRICS_H_
// clang-format off
#include <prometheus/simpleapi.h>
#include <prometheus/histogram.h>
// clang-format on
namespace prometheus {
namespace simpleapi {
extern std::shared_ptr<Registry> registry_ptr;
namespace simpleapi {
extern std::shared_ptr<Registry> registry_ptr;
}
}
} // namespace prometheus
namespace ZeroTier {
namespace Metrics {
// Packet Type Counts
extern prometheus::simpleapi::counter_family_t packets;
namespace Metrics {
// Packet Type Counts
extern prometheus::simpleapi::counter_family_t packets;
// incoming packets
extern prometheus::simpleapi::counter_metric_t pkt_nop_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_in;
extern prometheus::simpleapi::counter_metric_t pkt_ack_in;
extern prometheus::simpleapi::counter_metric_t pkt_qos_in;
extern prometheus::simpleapi::counter_metric_t pkt_hello_in;
extern prometheus::simpleapi::counter_metric_t pkt_ok_in;
extern prometheus::simpleapi::counter_metric_t pkt_whois_in;
extern prometheus::simpleapi::counter_metric_t pkt_rendezvous_in;
extern prometheus::simpleapi::counter_metric_t pkt_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_ext_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_echo_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_like_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_credentials_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_request_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_gather_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_in;
extern prometheus::simpleapi::counter_metric_t pkt_user_message_in;
extern prometheus::simpleapi::counter_metric_t pkt_remote_trace_in;
extern prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_in;
// incoming packets
extern prometheus::simpleapi::counter_metric_t pkt_nop_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_in;
extern prometheus::simpleapi::counter_metric_t pkt_ack_in;
extern prometheus::simpleapi::counter_metric_t pkt_qos_in;
extern prometheus::simpleapi::counter_metric_t pkt_hello_in;
extern prometheus::simpleapi::counter_metric_t pkt_ok_in;
extern prometheus::simpleapi::counter_metric_t pkt_whois_in;
extern prometheus::simpleapi::counter_metric_t pkt_rendezvous_in;
extern prometheus::simpleapi::counter_metric_t pkt_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_ext_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_echo_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_like_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_credentials_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_request_in;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_gather_in;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_frame_in;
extern prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_in;
extern prometheus::simpleapi::counter_metric_t pkt_user_message_in;
extern prometheus::simpleapi::counter_metric_t pkt_remote_trace_in;
extern prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_in;
// outgoing packets
extern prometheus::simpleapi::counter_metric_t pkt_nop_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_out;
extern prometheus::simpleapi::counter_metric_t pkt_ack_out;
extern prometheus::simpleapi::counter_metric_t pkt_qos_out;
extern prometheus::simpleapi::counter_metric_t pkt_hello_out;
extern prometheus::simpleapi::counter_metric_t pkt_ok_out;
extern prometheus::simpleapi::counter_metric_t pkt_whois_out;
extern prometheus::simpleapi::counter_metric_t pkt_rendezvous_out;
extern prometheus::simpleapi::counter_metric_t pkt_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_ext_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_echo_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_like_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_credentials_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_request_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_gather_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_out;
extern prometheus::simpleapi::counter_metric_t pkt_user_message_out;
extern prometheus::simpleapi::counter_metric_t pkt_remote_trace_out;
extern prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_out;
// outgoing packets
extern prometheus::simpleapi::counter_metric_t pkt_nop_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_out;
extern prometheus::simpleapi::counter_metric_t pkt_ack_out;
extern prometheus::simpleapi::counter_metric_t pkt_qos_out;
extern prometheus::simpleapi::counter_metric_t pkt_hello_out;
extern prometheus::simpleapi::counter_metric_t pkt_ok_out;
extern prometheus::simpleapi::counter_metric_t pkt_whois_out;
extern prometheus::simpleapi::counter_metric_t pkt_rendezvous_out;
extern prometheus::simpleapi::counter_metric_t pkt_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_ext_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_echo_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_like_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_credentials_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_request_out;
extern prometheus::simpleapi::counter_metric_t pkt_network_config_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_gather_out;
extern prometheus::simpleapi::counter_metric_t pkt_multicast_frame_out;
extern prometheus::simpleapi::counter_metric_t pkt_push_direct_paths_out;
extern prometheus::simpleapi::counter_metric_t pkt_user_message_out;
extern prometheus::simpleapi::counter_metric_t pkt_remote_trace_out;
extern prometheus::simpleapi::counter_metric_t pkt_path_negotiation_request_out;
// Packet Error Counts
extern prometheus::simpleapi::counter_family_t packet_errors;
// Packet Error Counts
extern prometheus::simpleapi::counter_family_t packet_errors;
// incoming errors
extern prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_in;
// incoming errors
extern prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_in;
extern prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_in;
// outgoing errors
extern prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_out;
// outgoing errors
extern prometheus::simpleapi::counter_metric_t pkt_error_obj_not_found_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_unsupported_op_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_identity_collision_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_need_membership_cert_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_network_access_denied_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_unwanted_multicast_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_authentication_required_out;
extern prometheus::simpleapi::counter_metric_t pkt_error_internal_server_error_out;
// Data Sent/Received Metrics
extern prometheus::simpleapi::counter_family_t data;
extern prometheus::simpleapi::counter_metric_t udp_send;
extern prometheus::simpleapi::counter_metric_t udp_recv;
extern prometheus::simpleapi::counter_metric_t tcp_send;
extern prometheus::simpleapi::counter_metric_t tcp_recv;
// Data Sent/Received Metrics
extern prometheus::simpleapi::counter_family_t data;
extern prometheus::simpleapi::counter_metric_t udp_send;
extern prometheus::simpleapi::counter_metric_t udp_recv;
extern prometheus::simpleapi::counter_metric_t tcp_send;
extern prometheus::simpleapi::counter_metric_t tcp_recv;
// Network Metrics
extern prometheus::simpleapi::gauge_metric_t network_num_joined;
extern prometheus::simpleapi::gauge_family_t network_num_multicast_groups;
extern prometheus::simpleapi::counter_family_t network_packets;
// Network Metrics
extern prometheus::simpleapi::gauge_metric_t network_num_joined;
extern prometheus::simpleapi::gauge_family_t network_num_multicast_groups;
extern prometheus::simpleapi::counter_family_t network_packets;
#ifndef ZT_NO_PEER_METRICS
// Peer Metrics
extern prometheus::CustomFamily<prometheus::Histogram<uint64_t> >& peer_latency;
extern prometheus::simpleapi::gauge_family_t peer_path_count;
extern prometheus::simpleapi::counter_family_t peer_packets;
extern prometheus::simpleapi::counter_family_t peer_packet_errors;
// Peer Metrics
extern prometheus::CustomFamily<prometheus::Histogram<uint64_t>> &peer_latency;
extern prometheus::simpleapi::gauge_family_t peer_path_count;
extern prometheus::simpleapi::counter_family_t peer_packets;
extern prometheus::simpleapi::counter_family_t peer_packet_errors;
#endif
// General Controller Metrics
extern prometheus::simpleapi::gauge_metric_t network_count;
extern prometheus::simpleapi::gauge_metric_t member_count;
extern prometheus::simpleapi::counter_metric_t network_changes;
extern prometheus::simpleapi::counter_metric_t member_changes;
extern prometheus::simpleapi::counter_metric_t member_auths;
extern prometheus::simpleapi::counter_metric_t member_deauths;
// General Controller Metrics
extern prometheus::simpleapi::gauge_metric_t network_count;
extern prometheus::simpleapi::gauge_metric_t member_count;
extern prometheus::simpleapi::counter_metric_t network_changes;
extern prometheus::simpleapi::counter_metric_t member_changes;
extern prometheus::simpleapi::counter_metric_t member_auths;
extern prometheus::simpleapi::counter_metric_t member_deauths;
extern prometheus::simpleapi::gauge_metric_t network_config_request_queue_size;
extern prometheus::simpleapi::counter_metric_t sso_expiration_checks;
extern prometheus::simpleapi::counter_metric_t sso_member_deauth;
extern prometheus::simpleapi::counter_metric_t network_config_request;
extern prometheus::simpleapi::gauge_metric_t network_config_request_threads;
extern prometheus::simpleapi::gauge_metric_t network_config_request_queue_size;
extern prometheus::simpleapi::counter_metric_t sso_expiration_checks;
extern prometheus::simpleapi::counter_metric_t sso_member_deauth;
extern prometheus::simpleapi::counter_metric_t network_config_request;
extern prometheus::simpleapi::gauge_metric_t network_config_request_threads;
extern prometheus::simpleapi::counter_metric_t db_get_network;
extern prometheus::simpleapi::counter_metric_t db_get_network_and_member;
extern prometheus::simpleapi::counter_metric_t db_get_network_and_member_and_summary;
extern prometheus::simpleapi::counter_metric_t db_get_member_list;
extern prometheus::simpleapi::counter_metric_t db_get_network_list;
extern prometheus::simpleapi::counter_metric_t db_member_change;
extern prometheus::simpleapi::counter_metric_t db_network_change;
extern prometheus::simpleapi::counter_metric_t db_get_network;
extern prometheus::simpleapi::counter_metric_t db_get_network_and_member;
extern prometheus::simpleapi::counter_metric_t db_get_network_and_member_and_summary;
extern prometheus::simpleapi::counter_metric_t db_get_member_list;
extern prometheus::simpleapi::counter_metric_t db_get_network_list;
extern prometheus::simpleapi::counter_metric_t db_member_change;
extern prometheus::simpleapi::counter_metric_t db_network_change;
#ifdef ZT_CONTROLLER_USE_LIBPQ
// Central Controller Metrics
extern prometheus::simpleapi::counter_metric_t pgsql_mem_notification;
extern prometheus::simpleapi::counter_metric_t pgsql_net_notification;
extern prometheus::simpleapi::counter_metric_t pgsql_node_checkin;
extern prometheus::simpleapi::counter_metric_t pgsql_commit_ticks;
extern prometheus::simpleapi::counter_metric_t db_get_sso_info;
// Central Controller Metrics
extern prometheus::simpleapi::counter_metric_t pgsql_mem_notification;
extern prometheus::simpleapi::counter_metric_t pgsql_net_notification;
extern prometheus::simpleapi::counter_metric_t pgsql_node_checkin;
extern prometheus::simpleapi::counter_metric_t pgsql_commit_ticks;
extern prometheus::simpleapi::counter_metric_t db_get_sso_info;
extern prometheus::simpleapi::counter_metric_t redis_mem_notification;
extern prometheus::simpleapi::counter_metric_t redis_net_notification;
extern prometheus::simpleapi::counter_metric_t redis_node_checkin;
extern prometheus::simpleapi::counter_metric_t redis_mem_notification;
extern prometheus::simpleapi::counter_metric_t redis_net_notification;
extern prometheus::simpleapi::counter_metric_t redis_node_checkin;
// Central DB Pool Metrics
extern prometheus::simpleapi::counter_metric_t conn_counter;
extern prometheus::simpleapi::counter_metric_t max_pool_size;
extern prometheus::simpleapi::counter_metric_t min_pool_size;
extern prometheus::simpleapi::gauge_metric_t pool_avail;
extern prometheus::simpleapi::gauge_metric_t pool_in_use;
extern prometheus::simpleapi::counter_metric_t pool_errors;
// Central DB Pool Metrics
extern prometheus::simpleapi::counter_metric_t conn_counter;
extern prometheus::simpleapi::counter_metric_t max_pool_size;
extern prometheus::simpleapi::counter_metric_t min_pool_size;
extern prometheus::simpleapi::gauge_metric_t pool_avail;
extern prometheus::simpleapi::gauge_metric_t pool_in_use;
extern prometheus::simpleapi::counter_metric_t pool_errors;
#endif
} // namespace Metrics
} // namespace ZeroTier
} // namespace Metrics
}// namespace ZeroTier
#endif // METRICS_H_
#endif // METRICS_H_

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,11 +14,11 @@
#ifndef ZT_MULTICASTGROUP_HPP
#define ZT_MULTICASTGROUP_HPP
#include "InetAddress.hpp"
#include "MAC.hpp"
#include <stdint.h>
#include "MAC.hpp"
#include "InetAddress.hpp"
namespace ZeroTier {
/**
@ -36,13 +36,18 @@ namespace ZeroTier {
*
* MulticastGroup behaves as an immutable value object.
*/
class MulticastGroup {
public:
MulticastGroup() : _mac(), _adi(0)
class MulticastGroup
{
public:
MulticastGroup() :
_mac(),
_adi(0)
{
}
MulticastGroup(const MAC& m, uint32_t a) : _mac(m), _adi(a)
MulticastGroup(const MAC &m,uint32_t a) :
_mac(m),
_adi(a)
{
}
@ -52,22 +57,21 @@ class MulticastGroup {
* @param ip IP address (port field is ignored)
* @return Multicast group for ARP/NDP
*/
static inline MulticastGroup deriveMulticastGroupForAddressResolution(const InetAddress& ip)
static inline MulticastGroup deriveMulticastGroupForAddressResolution(const InetAddress &ip)
{
if (ip.isV4()) {
// IPv4 wants broadcast MACs, so we shove the V4 address itself into
// the Multicast Group ADI field. Making V4 ARP work is basically why
// ADI was added, as well as handling other things that want mindless
// Ethernet broadcast to all.
return MulticastGroup(MAC(0xffffffffffffULL), Utils::ntoh(*((const uint32_t*)ip.rawIpData())));
}
else if (ip.isV6()) {
return MulticastGroup(MAC(0xffffffffffffULL),Utils::ntoh(*((const uint32_t *)ip.rawIpData())));
} else if (ip.isV6()) {
// IPv6 is better designed in this respect. We can compute the IPv6
// multicast address directly from the IP address, and it gives us
// 24 bits of uniqueness. Collisions aren't likely to be common enough
// to care about.
const unsigned char* a = (const unsigned char*)ip.rawIpData();
return MulticastGroup(MAC(0x33, 0x33, 0xff, a[13], a[14], a[15]), 0);
const unsigned char *a = (const unsigned char *)ip.rawIpData();
return MulticastGroup(MAC(0x33,0x33,0xff,a[13],a[14],a[15]),0);
}
return MulticastGroup();
}
@ -75,60 +79,35 @@ class MulticastGroup {
/**
* @return Multicast address
*/
inline const MAC& mac() const
{
return _mac;
}
inline const MAC &mac() const { return _mac; }
/**
* @return Additional distinguishing information
*/
inline uint32_t adi() const
{
return _adi;
}
inline uint32_t adi() const { return _adi; }
inline unsigned long hashCode() const
{
return (_mac.hashCode() ^ (unsigned long)_adi);
}
inline unsigned long hashCode() const { return (_mac.hashCode() ^ (unsigned long)_adi); }
inline bool operator==(const MulticastGroup& g) const
{
return ((_mac == g._mac) && (_adi == g._adi));
}
inline bool operator!=(const MulticastGroup& g) const
{
return ((_mac != g._mac) || (_adi != g._adi));
}
inline bool operator<(const MulticastGroup& g) const
inline bool operator==(const MulticastGroup &g) const { return ((_mac == g._mac)&&(_adi == g._adi)); }
inline bool operator!=(const MulticastGroup &g) const { return ((_mac != g._mac)||(_adi != g._adi)); }
inline bool operator<(const MulticastGroup &g) const
{
if (_mac < g._mac) {
return true;
}
else if (_mac == g._mac) {
} else if (_mac == g._mac) {
return (_adi < g._adi);
}
return false;
}
inline bool operator>(const MulticastGroup& g) const
{
return (g < *this);
}
inline bool operator<=(const MulticastGroup& g) const
{
return ! (g < *this);
}
inline bool operator>=(const MulticastGroup& g) const
{
return ! (*this < g);
}
inline bool operator>(const MulticastGroup &g) const { return (g < *this); }
inline bool operator<=(const MulticastGroup &g) const { return !(g < *this); }
inline bool operator>=(const MulticastGroup &g) const { return !(*this < g); }
private:
private:
MAC _mac;
uint32_t _adi;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,31 +4,32 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "Multicaster.hpp"
#include <algorithm>
#include "C25519.hpp"
#include "CertificateOfMembership.hpp"
#include "Constants.hpp"
#include "Network.hpp"
#include "Node.hpp"
#include "RuntimeEnvironment.hpp"
#include "Multicaster.hpp"
#include "Topology.hpp"
#include "Switch.hpp"
#include "Packet.hpp"
#include "Peer.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
#include <algorithm>
#include "C25519.hpp"
#include "CertificateOfMembership.hpp"
#include "Node.hpp"
#include "Network.hpp"
namespace ZeroTier {
Multicaster::Multicaster(const RuntimeEnvironment* renv) : RR(renv), _groups(32)
Multicaster::Multicaster(const RuntimeEnvironment *renv) :
RR(renv),
_groups(32)
{
}
@ -36,24 +37,24 @@ Multicaster::~Multicaster()
{
}
void Multicaster::addMultiple(void* tPtr, int64_t now, uint64_t nwid, const MulticastGroup& mg, const void* addresses, unsigned int count, unsigned int totalKnown)
void Multicaster::addMultiple(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown)
{
const unsigned char* p = (const unsigned char*)addresses;
const unsigned char* e = p + (5 * count);
const unsigned char *p = (const unsigned char *)addresses;
const unsigned char *e = p + (5 * count);
Mutex::Lock _l(_groups_m);
MulticastGroupStatus& gs = _groups[Multicaster::Key(nwid, mg)];
MulticastGroupStatus &gs = _groups[Multicaster::Key(nwid,mg)];
while (p != e) {
_add(tPtr, now, nwid, mg, gs, Address(p, 5));
_add(tPtr,now,nwid,mg,gs,Address(p,5));
p += 5;
}
}
void Multicaster::remove(uint64_t nwid, const MulticastGroup& mg, const Address& member)
void Multicaster::remove(uint64_t nwid,const MulticastGroup &mg,const Address &member)
{
Mutex::Lock _l(_groups_m);
MulticastGroupStatus* s = _groups.get(Multicaster::Key(nwid, mg));
MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
if (s) {
for (std::vector<MulticastGroupMember>::iterator m(s->members.begin()); m != s->members.end(); ++m) {
for(std::vector<MulticastGroupMember>::iterator m(s->members.begin());m!=s->members.end();++m) {
if (m->address == member) {
s->members.erase(m);
break;
@ -62,27 +63,26 @@ void Multicaster::remove(uint64_t nwid, const MulticastGroup& mg, const Address&
}
}
unsigned int Multicaster::gather(const Address& queryingPeer, uint64_t nwid, const MulticastGroup& mg, Buffer<ZT_PROTO_MAX_PACKET_LENGTH>& appendTo, unsigned int limit) const
unsigned int Multicaster::gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &appendTo,unsigned int limit) const
{
unsigned char* p;
unsigned int added = 0, i, k, rptr, totalKnown = 0;
uint64_t a, picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
unsigned char *p;
unsigned int added = 0,i,k,rptr,totalKnown = 0;
uint64_t a,picked[(ZT_PROTO_MAX_PACKET_LENGTH / 5) + 2];
if (! limit) {
if (!limit) {
return 0;
}
else if (limit > 0xffff) {
} else if (limit > 0xffff) {
limit = 0xffff;
}
const unsigned int totalAt = appendTo.size();
appendTo.addSize(4); // sizeof(uint32_t)
appendTo.addSize(4); // sizeof(uint32_t)
const unsigned int addedAt = appendTo.size();
appendTo.addSize(2); // sizeof(uint16_t)
appendTo.addSize(2); // sizeof(uint16_t)
{ // Return myself if I am a member of this group
{ // Return myself if I am a member of this group
SharedPtr<Network> network(RR->node->network(nwid));
if ((network) && (network->subscribedToMulticastGroup(mg, true))) {
if ((network)&&(network->subscribedToMulticastGroup(mg,true))) {
RR->identity.address().appendTo(appendTo);
++totalKnown;
++added;
@ -91,19 +91,19 @@ unsigned int Multicaster::gather(const Address& queryingPeer, uint64_t nwid, con
Mutex::Lock _l(_groups_m);
const MulticastGroupStatus* s = _groups.get(Multicaster::Key(nwid, mg));
if ((s) && (! s->members.empty())) {
const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
if ((s)&&(!s->members.empty())) {
totalKnown += (unsigned int)s->members.size();
// Members are returned in random order so that repeated gather queries
// will return different subsets of a large multicast group.
k = 0;
while ((added < limit) && (k < s->members.size()) && ((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
while ((added < limit)&&(k < s->members.size())&&((appendTo.size() + ZT_ADDRESS_LENGTH) <= ZT_PROTO_MAX_PACKET_LENGTH)) {
rptr = (unsigned int)RR->node->prng();
restart_member_scan:
restart_member_scan:
a = s->members[rptr % (unsigned int)s->members.size()].address.toInt();
for (i = 0; i < k; ++i) {
for(i=0;i<k;++i) {
if (picked[i] == a) {
++rptr;
goto restart_member_scan;
@ -111,8 +111,8 @@ unsigned int Multicaster::gather(const Address& queryingPeer, uint64_t nwid, con
}
picked[k++] = a;
if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
p = (unsigned char*)appendTo.appendField(ZT_ADDRESS_LENGTH);
if (queryingPeer.toInt() != a) { // do not return the peer that is making the request as a result
p = (unsigned char *)appendTo.appendField(ZT_ADDRESS_LENGTH);
*(p++) = (unsigned char)((a >> 32) & 0xff);
*(p++) = (unsigned char)((a >> 24) & 0xff);
*(p++) = (unsigned char)((a >> 16) & 0xff);
@ -123,21 +123,21 @@ unsigned int Multicaster::gather(const Address& queryingPeer, uint64_t nwid, con
}
}
appendTo.setAt(totalAt, (uint32_t)totalKnown);
appendTo.setAt(addedAt, (uint16_t)added);
appendTo.setAt(totalAt,(uint32_t)totalKnown);
appendTo.setAt(addedAt,(uint16_t)added);
return added;
}
std::vector<Address> Multicaster::getMembers(uint64_t nwid, const MulticastGroup& mg, unsigned int limit) const
std::vector<Address> Multicaster::getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const
{
std::vector<Address> ls;
Mutex::Lock _l(_groups_m);
const MulticastGroupStatus* s = _groups.get(Multicaster::Key(nwid, mg));
if (! s) {
const MulticastGroupStatus *s = _groups.get(Multicaster::Key(nwid,mg));
if (!s) {
return ls;
}
for (std::vector<MulticastGroupMember>::const_reverse_iterator m(s->members.rbegin()); m != s->members.rend(); ++m) {
for(std::vector<MulticastGroupMember>::const_reverse_iterator m(s->members.rbegin());m!=s->members.rend();++m) {
ls.push_back(m->address);
if (ls.size() >= limit) {
break;
@ -146,10 +146,19 @@ std::vector<Address> Multicaster::getMembers(uint64_t nwid, const MulticastGroup
return ls;
}
void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& network, const Address& origin, const MulticastGroup& mg, const MAC& src, unsigned int etherType, const void* data, unsigned int len)
void Multicaster::send(
void *tPtr,
int64_t now,
const SharedPtr<Network> &network,
const Address &origin,
const MulticastGroup &mg,
const MAC &src,
unsigned int etherType,
const void *data,
unsigned int len)
{
unsigned long idxbuf[4096];
unsigned long* indexes = idxbuf;
unsigned long *indexes = idxbuf;
// If we're in hub-and-spoke designated multicast replication mode, see if we
// have a multicast replicator active. If so, pick the best and send it
@ -159,19 +168,19 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
// the current protocol and could be fixed, but fixing it would add more
// complexity than the fix is probably worth. Bridges are generally high
// bandwidth nodes.
if (! network->config().isActiveBridge(RR->identity.address())) {
if (!network->config().isActiveBridge(RR->identity.address())) {
Address multicastReplicators[ZT_MAX_NETWORK_SPECIALISTS];
const unsigned int multicastReplicatorCount = network->config().multicastReplicators(multicastReplicators);
if (multicastReplicatorCount) {
if (std::find(multicastReplicators, multicastReplicators + multicastReplicatorCount, RR->identity.address()) == (multicastReplicators + multicastReplicatorCount)) {
if (std::find(multicastReplicators,multicastReplicators + multicastReplicatorCount,RR->identity.address()) == (multicastReplicators + multicastReplicatorCount)) {
SharedPtr<Peer> bestMulticastReplicator;
SharedPtr<Path> bestMulticastReplicatorPath;
unsigned int bestMulticastReplicatorLatency = 0xffff;
for (unsigned int i = 0; i < multicastReplicatorCount; ++i) {
for(unsigned int i=0;i<multicastReplicatorCount;++i) {
const SharedPtr<Peer> p(RR->topology->getPeerNoCache(multicastReplicators[i]));
if ((p) && (p->isAlive(now))) {
const SharedPtr<Path> pp(p->getAppropriatePath(now, false));
if ((pp) && (pp->latency() < bestMulticastReplicatorLatency)) {
if ((p)&&(p->isAlive(now))) {
const SharedPtr<Path> pp(p->getAppropriatePath(now,false));
if ((pp)&&(pp->latency() < bestMulticastReplicatorLatency)) {
bestMulticastReplicatorLatency = pp->latency();
bestMulticastReplicatorPath = pp;
bestMulticastReplicator = p;
@ -179,20 +188,20 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
}
}
if (bestMulticastReplicator) {
Packet outp(bestMulticastReplicator->address(), RR->identity.address(), Packet::VERB_MULTICAST_FRAME);
Packet outp(bestMulticastReplicator->address(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
outp.append((uint64_t)network->id());
outp.append((uint8_t)0x0c); // includes source MAC | please replicate
((src) ? src : MAC(RR->identity.address(), network->id())).appendTo(outp);
outp.append((uint8_t)0x0c); // includes source MAC | please replicate
((src) ? src : MAC(RR->identity.address(),network->id())).appendTo(outp);
mg.mac().appendTo(outp);
outp.append((uint32_t)mg.adi());
outp.append((uint16_t)etherType);
outp.append(data, len);
if (! network->config().disableCompression()) {
outp.append(data,len);
if (!network->config().disableCompression()) {
outp.compress();
}
outp.armor(bestMulticastReplicator->key(), true, bestMulticastReplicator->aesKeysIfSupported());
outp.armor(bestMulticastReplicator->key(),true,bestMulticastReplicator->aesKeysIfSupported());
Metrics::pkt_multicast_frame_out++;
bestMulticastReplicatorPath->send(RR, tPtr, outp.data(), outp.size(), now);
bestMulticastReplicatorPath->send(RR,tPtr,outp.data(),outp.size(),now);
return;
}
}
@ -201,19 +210,19 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
try {
Mutex::Lock _l(_groups_m);
MulticastGroupStatus& gs = _groups[Multicaster::Key(network->id(), mg)];
MulticastGroupStatus &gs = _groups[Multicaster::Key(network->id(),mg)];
if (! gs.members.empty()) {
if (!gs.members.empty()) {
// Allocate a memory buffer if group is monstrous
if (gs.members.size() > (sizeof(idxbuf) / sizeof(unsigned long))) {
indexes = new unsigned long[gs.members.size()];
}
// Generate a random permutation of member indexes
for (unsigned long i = 0; i < gs.members.size(); ++i) {
for(unsigned long i=0;i<gs.members.size();++i) {
indexes[i] = i;
}
for (unsigned long i = (unsigned long)gs.members.size() - 1; i > 0; --i) {
for(unsigned long i=(unsigned long)gs.members.size()-1;i>0;--i) {
unsigned long j = (unsigned long)RR->node->prng() % (i + 1);
unsigned long tmp = indexes[j];
indexes[j] = indexes[i];
@ -235,7 +244,7 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
network->id(),
network->config().disableCompression(),
limit,
1, // we'll still gather a little from peers to keep multicast list fresh
1, // we'll still gather a little from peers to keep multicast list fresh
src,
mg,
etherType,
@ -244,22 +253,24 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
unsigned int count = 0;
for (unsigned int i = 0; i < activeBridgeCount; ++i) {
if ((activeBridges[i] != RR->identity.address()) && (activeBridges[i] != origin)) {
out.sendOnly(RR, tPtr, activeBridges[i]); // optimization: don't use dedup log if it's a one-pass send
for(unsigned int i=0;i<activeBridgeCount;++i) {
if ((activeBridges[i] != RR->identity.address())&&(activeBridges[i] != origin)) {
out.sendOnly(RR,tPtr,activeBridges[i]); // optimization: don't use dedup log if it's a one-pass send
if (++count >= limit) {
break;
}
}
}
unsigned long idx = 0;
while ((count < limit) && (idx < gs.members.size())) {
while ((count < limit)&&(idx < gs.members.size())) {
const Address ma(gs.members[indexes[idx++]].address);
if ((std::find(activeBridges, activeBridges + activeBridgeCount, ma) == (activeBridges + activeBridgeCount)) && (ma != origin)) {
out.sendOnly(RR, tPtr, ma); // optimization: don't use dedup log if it's a one-pass send
if ((std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount))&&(ma != origin)) {
out.sendOnly(RR,tPtr,ma); // optimization: don't use dedup log if it's a one-pass send
++count;
}
}
}
else {
} else {
while (gs.txQueue.size() >= ZT_TX_QUEUE_SIZE) {
gs.txQueue.pop_front();
}
@ -267,7 +278,7 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
const unsigned int gatherLimit = (limit - (unsigned int)gs.members.size()) + 1;
int timerScale = RR->node->lowBandwidthModeEnabled() ? 3 : 1;
if ((gs.members.empty()) || ((now - gs.lastExplicitGather) >= (ZT_MULTICAST_EXPLICIT_GATHER_DELAY * timerScale))) {
if ((gs.members.empty())||((now - gs.lastExplicitGather) >= (ZT_MULTICAST_EXPLICIT_GATHER_DELAY * timerScale))) {
gs.lastExplicitGather = now;
Address explicitGatherPeers[16];
@ -283,10 +294,10 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
Address ac[ZT_MAX_NETWORK_SPECIALISTS];
const unsigned int accnt = network->config().alwaysContactAddresses(ac);
unsigned int shuffled[ZT_MAX_NETWORK_SPECIALISTS];
for (unsigned int i = 0; i < accnt; ++i) {
for(unsigned int i=0;i<accnt;++i) {
shuffled[i] = i;
}
for (unsigned int i = 0, k = accnt >> 1; i < k; ++i) {
for(unsigned int i=0,k=accnt>>1;i<k;++i) {
const uint64_t x = RR->node->prng();
const unsigned int x1 = shuffled[(unsigned int)x % accnt];
const unsigned int x2 = shuffled[(unsigned int)(x >> 32) % accnt];
@ -294,7 +305,7 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
shuffled[x1] = shuffled[x2];
shuffled[x2] = tmp;
}
for (unsigned int i = 0; i < accnt; ++i) {
for(unsigned int i=0;i<accnt;++i) {
explicitGatherPeers[numExplicitGatherPeers++] = ac[shuffled[i]];
if (numExplicitGatherPeers == 16) {
break;
@ -302,7 +313,7 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
}
std::vector<Address> anchors(network->config().anchors());
for (std::vector<Address>::const_iterator a(anchors.begin()); a != anchors.end(); ++a) {
for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a) {
if (*a != RR->identity.address()) {
explicitGatherPeers[numExplicitGatherPeers++] = *a;
if (numExplicitGatherPeers == 16) {
@ -311,9 +322,9 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
}
}
for (unsigned int k = 0; k < numExplicitGatherPeers; ++k) {
const CertificateOfMembership* com = (network) ? ((network->config().com) ? &(network->config().com) : (const CertificateOfMembership*)0) : (const CertificateOfMembership*)0;
Packet outp(explicitGatherPeers[k], RR->identity.address(), Packet::VERB_MULTICAST_GATHER);
for(unsigned int k=0;k<numExplicitGatherPeers;++k) {
const CertificateOfMembership *com = (network) ? ((network->config().com) ? &(network->config().com) : (const CertificateOfMembership *)0) : (const CertificateOfMembership *)0;
Packet outp(explicitGatherPeers[k],RR->identity.address(),Packet::VERB_MULTICAST_GATHER);
outp.append(network->id());
outp.append((uint8_t)((com) ? 0x01 : 0x00));
mg.mac().appendTo(outp);
@ -323,15 +334,26 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
com->serialize(outp);
}
RR->node->expectReplyTo(outp.packetId());
RR->sw->send(tPtr, outp, true);
RR->sw->send(tPtr,outp,true);
Metrics::pkt_multicast_gather_out++;
}
}
gs.txQueue.push_back(OutboundMulticast());
OutboundMulticast& out = gs.txQueue.back();
OutboundMulticast &out = gs.txQueue.back();
out.init(RR, now, network->id(), network->config().disableCompression(), limit, gatherLimit, src, mg, etherType, data, len);
out.init(
RR,
now,
network->id(),
network->config().disableCompression(),
limit,
gatherLimit,
src,
mg,
etherType,
data,
len);
if (origin) {
out.logAsSent(origin);
@ -339,9 +361,9 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
unsigned int count = 0;
for (unsigned int i = 0; i < activeBridgeCount; ++i) {
for(unsigned int i=0;i<activeBridgeCount;++i) {
if (activeBridges[i] != RR->identity.address()) {
out.sendAndLog(RR, tPtr, activeBridges[i]);
out.sendAndLog(RR,tPtr,activeBridges[i]);
if (++count >= limit) {
break;
}
@ -349,36 +371,33 @@ void Multicaster::send(void* tPtr, int64_t now, const SharedPtr<Network>& networ
}
unsigned long idx = 0;
while ((count < limit) && (idx < gs.members.size())) {
while ((count < limit)&&(idx < gs.members.size())) {
Address ma(gs.members[indexes[idx++]].address);
if (std::find(activeBridges, activeBridges + activeBridgeCount, ma) == (activeBridges + activeBridgeCount)) {
out.sendAndLog(RR, tPtr, ma);
if (std::find(activeBridges,activeBridges + activeBridgeCount,ma) == (activeBridges + activeBridgeCount)) {
out.sendAndLog(RR,tPtr,ma);
++count;
}
}
}
}
catch (...) {
} // this is a sanity check to catch any failures and make sure indexes[] still gets deleted
} catch ( ... ) {} // this is a sanity check to catch any failures and make sure indexes[] still gets deleted
// Free allocated memory buffer if any
if (indexes != idxbuf) {
delete[] indexes;
delete [] indexes;
}
}
void Multicaster::clean(int64_t now)
{
Mutex::Lock _l(_groups_m);
Multicaster::Key* k = (Multicaster::Key*)0;
MulticastGroupStatus* s = (MulticastGroupStatus*)0;
Hashtable<Multicaster::Key, MulticastGroupStatus>::Iterator mm(_groups);
while (mm.next(k, s)) {
for (std::list<OutboundMulticast>::iterator tx(s->txQueue.begin()); tx != s->txQueue.end();) {
if ((tx->expired(now)) || (tx->atLimit())) {
Multicaster::Key *k = (Multicaster::Key *)0;
MulticastGroupStatus *s = (MulticastGroupStatus *)0;
Hashtable<Multicaster::Key,MulticastGroupStatus>::Iterator mm(_groups);
while (mm.next(k,s)) {
for(std::list<OutboundMulticast>::iterator tx(s->txQueue.begin());tx!=s->txQueue.end();) {
if ((tx->expired(now))||(tx->atLimit())) {
s->txQueue.erase(tx++);
}
else {
} else {
++tx;
}
}
@ -399,17 +418,15 @@ void Multicaster::clean(int64_t now)
if (count) {
s->members.resize(count);
}
else if (s->txQueue.empty()) {
} else if (s->txQueue.empty()) {
_groups.erase(*k);
}
else {
} else {
s->members.clear();
}
}
}
void Multicaster::_add(void* tPtr, int64_t now, uint64_t nwid, const MulticastGroup& mg, MulticastGroupStatus& gs, const Address& member)
void Multicaster::_add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member)
{
// assumes _groups_m is locked
@ -418,32 +435,29 @@ void Multicaster::_add(void* tPtr, int64_t now, uint64_t nwid, const MulticastGr
return;
}
std::vector<MulticastGroupMember>::iterator m(std::lower_bound(gs.members.begin(), gs.members.end(), member));
std::vector<MulticastGroupMember>::iterator m(std::lower_bound(gs.members.begin(),gs.members.end(),member));
if (m != gs.members.end()) {
if (m->address == member) {
m->timestamp = now;
return;
}
gs.members.insert(m, MulticastGroupMember(member, now));
}
else {
gs.members.push_back(MulticastGroupMember(member, now));
gs.members.insert(m,MulticastGroupMember(member,now));
} else {
gs.members.push_back(MulticastGroupMember(member,now));
}
for (std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin()); tx != gs.txQueue.end();) {
for(std::list<OutboundMulticast>::iterator tx(gs.txQueue.begin());tx!=gs.txQueue.end();) {
if (tx->atLimit()) {
gs.txQueue.erase(tx++);
}
else {
tx->sendIfNew(RR, tPtr, member);
} else {
tx->sendIfNew(RR,tPtr,member);
if (tx->atLimit()) {
gs.txQueue.erase(tx++);
}
else {
} else {
++tx;
}
}
}
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,21 +14,22 @@
#ifndef ZT_MULTICASTER_HPP
#define ZT_MULTICASTER_HPP
#include "Address.hpp"
#include "Constants.hpp"
#include "Hashtable.hpp"
#include "MAC.hpp"
#include "MulticastGroup.hpp"
#include "Mutex.hpp"
#include "OutboundMulticast.hpp"
#include "SharedPtr.hpp"
#include "Utils.hpp"
#include <list>
#include <map>
#include <stdint.h>
#include <string.h>
#include <map>
#include <vector>
#include <list>
#include "Constants.hpp"
#include "Hashtable.hpp"
#include "Address.hpp"
#include "MAC.hpp"
#include "MulticastGroup.hpp"
#include "OutboundMulticast.hpp"
#include "Utils.hpp"
#include "Mutex.hpp"
#include "SharedPtr.hpp"
namespace ZeroTier {
@ -40,9 +41,10 @@ class Network;
/**
* Database of known multicast peers within a network
*/
class Multicaster {
public:
Multicaster(const RuntimeEnvironment* renv);
class Multicaster
{
public:
Multicaster(const RuntimeEnvironment *renv);
~Multicaster();
/**
@ -53,10 +55,10 @@ class Multicaster {
* @param mg Multicast group
* @param member New member address
*/
inline void add(void* tPtr, int64_t now, uint64_t nwid, const MulticastGroup& mg, const Address& member)
inline void add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,const Address &member)
{
Mutex::Lock _l(_groups_m);
_add(tPtr, now, nwid, mg, _groups[Multicaster::Key(nwid, mg)], member);
_add(tPtr,now,nwid,mg,_groups[Multicaster::Key(nwid,mg)],member);
}
/**
@ -72,7 +74,7 @@ class Multicaster {
* @param count Number of addresses
* @param totalKnown Total number of known addresses as reported by peer
*/
void addMultiple(void* tPtr, int64_t now, uint64_t nwid, const MulticastGroup& mg, const void* addresses, unsigned int count, unsigned int totalKnown);
void addMultiple(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,const void *addresses,unsigned int count,unsigned int totalKnown);
/**
* Remove a multicast group member (if present)
@ -81,7 +83,7 @@ class Multicaster {
* @param mg Multicast group
* @param member Member to unsubscribe
*/
void remove(uint64_t nwid, const MulticastGroup& mg, const Address& member);
void remove(uint64_t nwid,const MulticastGroup &mg,const Address &member);
/**
* Append gather results to a packet by choosing registered multicast recipients at random
@ -101,7 +103,7 @@ class Multicaster {
* @return Number of addresses appended
* @throws std::out_of_range Buffer overflow writing to packet
*/
unsigned int gather(const Address& queryingPeer, uint64_t nwid, const MulticastGroup& mg, Buffer<ZT_PROTO_MAX_PACKET_LENGTH>& appendTo, unsigned int limit) const;
unsigned int gather(const Address &queryingPeer,uint64_t nwid,const MulticastGroup &mg,Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &appendTo,unsigned int limit) const;
/**
* Get subscribers to a multicast group
@ -109,7 +111,7 @@ class Multicaster {
* @param nwid Network ID
* @param mg Multicast group
*/
std::vector<Address> getMembers(uint64_t nwid, const MulticastGroup& mg, unsigned int limit) const;
std::vector<Address> getMembers(uint64_t nwid,const MulticastGroup &mg,unsigned int limit) const;
/**
* Send a multicast
@ -124,7 +126,16 @@ class Multicaster {
* @param data Packet data
* @param len Length of packet data
*/
void send(void* tPtr, int64_t now, const SharedPtr<Network>& network, const Address& origin, const MulticastGroup& mg, const MAC& src, unsigned int etherType, const void* data, unsigned int len);
void send(
void *tPtr,
int64_t now,
const SharedPtr<Network> &network,
const Address &origin,
const MulticastGroup &mg,
const MAC &src,
unsigned int etherType,
const void *data,
unsigned int len);
/**
* Clean database
@ -134,87 +145,53 @@ class Multicaster {
*/
void clean(int64_t now);
private:
struct Key {
Key() : nwid(0), mg()
{
}
Key(uint64_t n, const MulticastGroup& g) : nwid(n), mg(g)
{
}
private:
struct Key
{
Key() : nwid(0),mg() {}
Key(uint64_t n,const MulticastGroup &g) : nwid(n),mg(g) {}
uint64_t nwid;
MulticastGroup mg;
inline bool operator==(const Key& k) const
{
return ((nwid == k.nwid) && (mg == k.mg));
}
inline bool operator!=(const Key& k) const
{
return ((nwid != k.nwid) || (mg != k.mg));
}
inline unsigned long hashCode() const
{
return (mg.hashCode() ^ (unsigned long)(nwid ^ (nwid >> 32)));
}
inline bool operator==(const Key &k) const { return ((nwid == k.nwid)&&(mg == k.mg)); }
inline bool operator!=(const Key &k) const { return ((nwid != k.nwid)||(mg != k.mg)); }
inline unsigned long hashCode() const { return (mg.hashCode() ^ (unsigned long)(nwid ^ (nwid >> 32))); }
};
struct MulticastGroupMember {
MulticastGroupMember()
{
}
MulticastGroupMember(const Address& a, uint64_t ts) : address(a), timestamp(ts)
{
}
struct MulticastGroupMember
{
MulticastGroupMember() {}
MulticastGroupMember(const Address &a,uint64_t ts) : address(a),timestamp(ts) {}
inline bool operator<(const MulticastGroupMember& a) const
{
return (address < a.address);
}
inline bool operator==(const MulticastGroupMember& a) const
{
return (address == a.address);
}
inline bool operator!=(const MulticastGroupMember& a) const
{
return (address != a.address);
}
inline bool operator<(const Address& a) const
{
return (address < a);
}
inline bool operator==(const Address& a) const
{
return (address == a);
}
inline bool operator!=(const Address& a) const
{
return (address != a);
}
inline bool operator<(const MulticastGroupMember &a) const { return (address < a.address); }
inline bool operator==(const MulticastGroupMember &a) const { return (address == a.address); }
inline bool operator!=(const MulticastGroupMember &a) const { return (address != a.address); }
inline bool operator<(const Address &a) const { return (address < a); }
inline bool operator==(const Address &a) const { return (address == a); }
inline bool operator!=(const Address &a) const { return (address != a); }
Address address;
int64_t timestamp; // time of last notification
int64_t timestamp; // time of last notification
};
struct MulticastGroupStatus {
MulticastGroupStatus() : lastExplicitGather(0)
{
}
struct MulticastGroupStatus
{
MulticastGroupStatus() : lastExplicitGather(0) {}
int64_t lastExplicitGather;
std::list<OutboundMulticast> txQueue; // pending outbound multicasts
std::vector<MulticastGroupMember> members; // members of this group
std::list<OutboundMulticast> txQueue; // pending outbound multicasts
std::vector<MulticastGroupMember> members; // members of this group
};
void _add(void* tPtr, int64_t now, uint64_t nwid, const MulticastGroup& mg, MulticastGroupStatus& gs, const Address& member);
void _add(void *tPtr,int64_t now,uint64_t nwid,const MulticastGroup &mg,MulticastGroupStatus &gs,const Address &member);
const RuntimeEnvironment* const RR;
const RuntimeEnvironment *const RR;
Hashtable<Multicaster::Key, MulticastGroupStatus> _groups;
Hashtable<Multicaster::Key,MulticastGroupStatus> _groups;
Mutex _groups_m;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -18,18 +18,19 @@
#ifdef __UNIX_LIKE__
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
namespace ZeroTier {
// libpthread based mutex lock
class Mutex {
public:
class Mutex
{
public:
Mutex()
{
pthread_mutex_init(&_mh, (const pthread_mutexattr_t*)0);
pthread_mutex_init(&_mh,(const pthread_mutexattr_t *)0);
}
~Mutex()
@ -39,22 +40,25 @@ class Mutex {
inline void lock() const
{
pthread_mutex_lock(&((const_cast<Mutex*>(this))->_mh));
pthread_mutex_lock(&((const_cast <Mutex *> (this))->_mh));
}
inline void unlock() const
{
pthread_mutex_unlock(&((const_cast<Mutex*>(this))->_mh));
pthread_mutex_unlock(&((const_cast <Mutex *> (this))->_mh));
}
class Lock {
public:
Lock(Mutex& m) : _m(&m)
class Lock
{
public:
Lock(Mutex &m) :
_m(&m)
{
m.lock();
}
Lock(const Mutex& m) : _m(const_cast<Mutex*>(&m))
Lock(const Mutex &m) :
_m(const_cast<Mutex *>(&m))
{
_m->lock();
}
@ -64,23 +68,18 @@ class Mutex {
_m->unlock();
}
private:
Mutex* const _m;
private:
Mutex *const _m;
};
private:
Mutex(const Mutex&)
{
}
const Mutex& operator=(const Mutex&)
{
return *this;
}
private:
Mutex(const Mutex &) {}
const Mutex &operator=(const Mutex &) { return *this; }
pthread_mutex_t _mh;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif
@ -92,8 +91,9 @@ class Mutex {
namespace ZeroTier {
// Windows critical section based lock
class Mutex {
public:
class Mutex
{
public:
Mutex()
{
InitializeCriticalSection(&_cs);
@ -116,22 +116,25 @@ class Mutex {
inline void lock() const
{
(const_cast<Mutex*>(this))->lock();
(const_cast <Mutex *> (this))->lock();
}
inline void unlock() const
{
(const_cast<Mutex*>(this))->unlock();
(const_cast <Mutex *> (this))->unlock();
}
class Lock {
public:
Lock(Mutex& m) : _m(&m)
class Lock
{
public:
Lock(Mutex &m) :
_m(&m)
{
m.lock();
}
Lock(const Mutex& m) : _m(const_cast<Mutex*>(&m))
Lock(const Mutex &m) :
_m(const_cast<Mutex *>(&m))
{
_m->lock();
}
@ -141,24 +144,19 @@ class Mutex {
_m->unlock();
}
private:
Mutex* const _m;
private:
Mutex *const _m;
};
private:
Mutex(const Mutex&)
{
}
const Mutex& operator=(const Mutex&)
{
return *this;
}
private:
Mutex(const Mutex &) {}
const Mutex &operator=(const Mutex &) { return *this; }
CRITICAL_SECTION _cs;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif // _WIN32
#endif // _WIN32
#endif

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,31 +14,33 @@
#ifndef ZT_NETWORK_HPP
#define ZT_NETWORK_HPP
#include "../include/ZeroTierOne.h"
#include "Address.hpp"
#include "AtomicCounter.hpp"
#include "CertificateOfMembership.hpp"
#include "Constants.hpp"
#include "Dictionary.hpp"
#include "Hashtable.hpp"
#include "MAC.hpp"
#include "Membership.hpp"
#include "Metrics.hpp"
#include "MulticastGroup.hpp"
#include "Multicaster.hpp"
#include "Mutex.hpp"
#include "NetworkConfig.hpp"
#include "SharedPtr.hpp"
#include <algorithm>
#include <map>
#include <stdexcept>
#include <stdint.h>
#include "../include/ZeroTierOne.h"
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include "Constants.hpp"
#include "Hashtable.hpp"
#include "Address.hpp"
#include "Mutex.hpp"
#include "SharedPtr.hpp"
#include "AtomicCounter.hpp"
#include "MulticastGroup.hpp"
#include "MAC.hpp"
#include "Dictionary.hpp"
#include "Multicaster.hpp"
#include "Membership.hpp"
#include "NetworkConfig.hpp"
#include "CertificateOfMembership.hpp"
#include "Metrics.hpp"
#define ZT_NETWORK_MAX_INCOMING_UPDATES 3
#define ZT_NETWORK_MAX_UPDATE_CHUNKS ((ZT_NETWORKCONFIG_DICT_CAPACITY / 1024) + 1)
#define ZT_NETWORK_MAX_UPDATE_CHUNKS ((ZT_NETWORKCONFIG_DICT_CAPACITY / 1024) + 1)
namespace ZeroTier {
@ -48,10 +50,11 @@ class Peer;
/**
* A virtual LAN
*/
class Network {
class Network
{
friend class SharedPtr<Network>;
public:
public:
/**
* Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
*/
@ -60,10 +63,7 @@ class Network {
/**
* Compute primary controller device ID from network ID
*/
static inline Address controllerFor(uint64_t nwid)
{
return Address(nwid >> 24);
}
static inline Address controllerFor(uint64_t nwid) { return Address(nwid >> 24); }
/**
* Construct a new network
@ -77,43 +77,18 @@ class Network {
* @param uptr Arbitrary pointer used by externally-facing API (for user use)
* @param nconf Network config, if known
*/
Network(const RuntimeEnvironment* renv, void* tPtr, uint64_t nwid, void* uptr, const NetworkConfig* nconf);
Network(const RuntimeEnvironment *renv,void *tPtr,uint64_t nwid,void *uptr,const NetworkConfig *nconf);
~Network();
inline uint64_t id() const
{
return _id;
}
inline Address controller() const
{
return Address(_id >> 24);
}
inline bool multicastEnabled() const
{
return (_config.multicastLimit > 0);
}
inline bool hasConfig() const
{
return (_config);
}
inline uint64_t lastConfigUpdate() const
{
return _lastConfigUpdate;
}
inline ZT_VirtualNetworkStatus status() const
{
Mutex::Lock _l(_lock);
return _status();
}
inline const NetworkConfig& config() const
{
return _config;
}
inline const MAC& mac() const
{
return _mac;
}
inline uint64_t id() const { return _id; }
inline Address controller() const { return Address(_id >> 24); }
inline bool multicastEnabled() const { return (_config.multicastLimit > 0); }
inline bool hasConfig() const { return (_config); }
inline uint64_t lastConfigUpdate() const { return _lastConfigUpdate; }
inline ZT_VirtualNetworkStatus status() const { Mutex::Lock _l(_lock); return _status(); }
inline const NetworkConfig &config() const { return _config; }
inline const MAC &mac() const { return _mac; }
/**
* Apply filters to an outgoing packet
@ -136,17 +111,17 @@ class Network {
* @return True if packet should be sent, false if dropped or redirected
*/
bool filterOutgoingPacket(
void* tPtr,
void *tPtr,
const bool noTee,
const Address& ztSource,
const Address& ztDest,
const MAC& macSource,
const MAC& macDest,
const uint8_t* frameData,
const Address &ztSource,
const Address &ztDest,
const MAC &macSource,
const MAC &macDest,
const uint8_t *frameData,
const unsigned int frameLen,
const unsigned int etherType,
const unsigned int vlanId,
uint8_t& qosBucket);
uint8_t &qosBucket);
/**
* Apply filters to an incoming packet
@ -168,12 +143,12 @@ class Network {
* @return 0 == drop, 1 == accept, 2 == accept even if bridged
*/
int filterIncomingPacket(
void* tPtr,
const SharedPtr<Peer>& sourcePeer,
const Address& ztDest,
const MAC& macSource,
const MAC& macDest,
const uint8_t* frameData,
void *tPtr,
const SharedPtr<Peer> &sourcePeer,
const Address &ztDest,
const MAC &macSource,
const MAC &macDest,
const uint8_t *frameData,
const unsigned int frameLen,
const unsigned int etherType,
const unsigned int vlanId);
@ -185,7 +160,7 @@ class Network {
* @param includeBridgedGroups If true, also check groups we've learned via bridging
* @return True if this network endpoint / peer is a member
*/
bool subscribedToMulticastGroup(const MulticastGroup& mg, bool includeBridgedGroups) const;
bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
/**
* Subscribe to a multicast group
@ -193,14 +168,14 @@ class Network {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @param mg New multicast group
*/
void multicastSubscribe(void* tPtr, const MulticastGroup& mg);
void multicastSubscribe(void *tPtr,const MulticastGroup &mg);
/**
* Unsubscribe from a multicast group
*
* @param mg Multicast group
*/
void multicastUnsubscribe(const MulticastGroup& mg);
void multicastUnsubscribe(const MulticastGroup &mg);
/**
* Handle an inbound network config chunk
@ -216,7 +191,7 @@ class Network {
* @param ptr Index of chunk and related fields in packet
* @return Update ID if update was fully assembled and accepted or 0 otherwise
*/
uint64_t handleConfigChunk(void* tPtr, const uint64_t packetId, const Address& source, const Buffer<ZT_PROTO_MAX_PACKET_LENGTH>& chunk, unsigned int ptr);
uint64_t handleConfigChunk(void *tPtr,const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr);
/**
* Set network configuration
@ -226,12 +201,12 @@ class Network {
* @param saveToDisk Save to disk? Used during loading, should usually be true otherwise.
* @return 0 == bad, 1 == accepted but duplicate/unchanged, 2 == accepted and new
*/
int setConfiguration(void* tPtr, const NetworkConfig& nconf, bool saveToDisk);
int setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk);
/**
* Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
*/
inline void setAccessDenied(void* tPtr)
inline void setAccessDenied(void *tPtr)
{
Mutex::Lock _l(_lock);
_netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
@ -242,7 +217,7 @@ class Network {
/**
* Set netconf failure to 'not found' -- called by IncomingPacket when controller reports this
*/
inline void setNotFound(void* tPtr)
inline void setNotFound(void *tPtr)
{
Mutex::Lock _l(_lock);
_netconfFailure = NETCONF_FAILURE_NOT_FOUND;
@ -253,7 +228,7 @@ class Network {
/**
* Set netconf failure to 'authentication required' possibly with an authorization URL
*/
inline void setAuthenticationRequired(void* tPtr, const char* url)
inline void setAuthenticationRequired(void *tPtr, const char *url)
{
Mutex::Lock _l(_lock);
_netconfFailure = NETCONF_FAILURE_AUTHENTICATION_REQUIRED;
@ -267,14 +242,14 @@ class Network {
* set netconf failure to 'authentication required' along with info needed
* for sso full flow authentication.
*/
void setAuthenticationRequired(void* tPtr, const char* issuerURL, const char* centralEndpoint, const char* clientID, const char* ssoProvider, const char* nonce, const char* state);
void setAuthenticationRequired(void *tPtr, const char* issuerURL, const char* centralEndpoint, const char* clientID, const char *ssoProvider, const char* nonce, const char* state);
/**
* Causes this network to request an updated configuration from its master node now
*
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
*/
void requestConfiguration(void* tPtr);
void requestConfiguration(void *tPtr);
/**
* Determine whether this peer is permitted to communicate on this network
@ -282,7 +257,7 @@ class Network {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @param peer Peer to check
*/
bool gate(void* tPtr, const SharedPtr<Peer>& peer);
bool gate(void *tPtr,const SharedPtr<Peer> &peer);
/**
* Check whether a given peer has recently had an association with this network
@ -295,7 +270,7 @@ class Network {
* @param addr Peer address
* @return True if peer has recently associated
*/
bool recentlyAssociatedWith(const Address& addr);
bool recentlyAssociatedWith(const Address &addr);
/**
* Do periodic cleanup and housekeeping tasks
@ -307,10 +282,10 @@ class Network {
*
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
*/
inline void sendUpdatesToMembers(void* tPtr)
inline void sendUpdatesToMembers(void *tPtr)
{
Mutex::Lock _l(_lock);
_sendUpdatesToMembers(tPtr, (const MulticastGroup*)0);
_sendUpdatesToMembers(tPtr,(const MulticastGroup *)0);
}
/**
@ -319,20 +294,17 @@ class Network {
* @param mac MAC address
* @return ZeroTier address of bridge to this MAC
*/
inline Address findBridgeTo(const MAC& mac) const
inline Address findBridgeTo(const MAC &mac) const
{
Mutex::Lock _l(_lock);
const Address* const br = _remoteBridgeRoutes.get(mac);
const Address *const br = _remoteBridgeRoutes.get(mac);
return ((br) ? *br : Address());
}
/**
* @return True if QoS is in effect for this network
*/
inline bool qosEnabled()
{
return false;
}
inline bool qosEnabled() { return false; }
/**
* Set a bridge route
@ -340,7 +312,7 @@ class Network {
* @param mac MAC address of destination
* @param addr Bridge this MAC is reachable behind
*/
void learnBridgeRoute(const MAC& mac, const Address& addr);
void learnBridgeRoute(const MAC &mac,const Address &addr);
/**
* Learn a multicast group that is bridged to our tap device
@ -349,52 +321,52 @@ class Network {
* @param mg Multicast group
* @param now Current time
*/
void learnBridgedMulticastGroup(void* tPtr, const MulticastGroup& mg, int64_t now);
void learnBridgedMulticastGroup(void *tPtr,const MulticastGroup &mg,int64_t now);
/**
* Validate a credential and learn it if it passes certificate and other checks
*/
Membership::AddCredentialResult addCredential(void* tPtr, const CertificateOfMembership& com);
Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfMembership &com);
/**
* Validate a credential and learn it if it passes certificate and other checks
*/
inline Membership::AddCredentialResult addCredential(void* tPtr, const Capability& cap)
inline Membership::AddCredentialResult addCredential(void *tPtr,const Capability &cap)
{
if (cap.networkId() != _id) {
return Membership::ADD_REJECTED;
}
Mutex::Lock _l(_lock);
return _membership(cap.issuedTo()).addCredential(RR, tPtr, _config, cap);
return _membership(cap.issuedTo()).addCredential(RR,tPtr,_config,cap);
}
/**
* Validate a credential and learn it if it passes certificate and other checks
*/
inline Membership::AddCredentialResult addCredential(void* tPtr, const Tag& tag)
inline Membership::AddCredentialResult addCredential(void *tPtr,const Tag &tag)
{
if (tag.networkId() != _id) {
return Membership::ADD_REJECTED;
}
Mutex::Lock _l(_lock);
return _membership(tag.issuedTo()).addCredential(RR, tPtr, _config, tag);
return _membership(tag.issuedTo()).addCredential(RR,tPtr,_config,tag);
}
/**
* Validate a credential and learn it if it passes certificate and other checks
*/
Membership::AddCredentialResult addCredential(void* tPtr, const Address& sentFrom, const Revocation& rev);
Membership::AddCredentialResult addCredential(void *tPtr,const Address &sentFrom,const Revocation &rev);
/**
* Validate a credential and learn it if it passes certificate and other checks
*/
inline Membership::AddCredentialResult addCredential(void* tPtr, const CertificateOfOwnership& coo)
inline Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfOwnership &coo)
{
if (coo.networkId() != _id) {
return Membership::ADD_REJECTED;
}
Mutex::Lock _l(_lock);
return _membership(coo.issuedTo()).addCredential(RR, tPtr, _config, coo);
return _membership(coo.issuedTo()).addCredential(RR,tPtr,_config,coo);
}
/**
@ -404,13 +376,13 @@ class Network {
* @param to Destination peer address
* @param now Current time
*/
inline void peerRequestedCredentials(void* tPtr, const Address& to, const int64_t now)
inline void peerRequestedCredentials(void *tPtr,const Address &to,const int64_t now)
{
Mutex::Lock _l(_lock);
Membership& m = _membership(to);
Membership &m = _membership(to);
const int64_t lastPushed = m.lastPushedCredentials();
if ((lastPushed < _lastConfigUpdate) || ((now - lastPushed) > ZT_PEER_CREDENTIALS_REQUEST_RATE_LIMIT)) {
m.pushCredentials(RR, tPtr, now, to, _config);
if ((lastPushed < _lastConfigUpdate)||((now - lastPushed) > ZT_PEER_CREDENTIALS_REQUEST_RATE_LIMIT)) {
m.pushCredentials(RR,tPtr,now,to,_config);
}
}
@ -421,13 +393,13 @@ class Network {
* @param to Destination peer address
* @param now Current time
*/
inline void pushCredentialsIfNeeded(void* tPtr, const Address& to, const int64_t now)
inline void pushCredentialsIfNeeded(void *tPtr,const Address &to,const int64_t now)
{
Mutex::Lock _l(_lock);
Membership& m = _membership(to);
Membership &m = _membership(to);
const int64_t lastPushed = m.lastPushedCredentials();
if ((lastPushed < _lastConfigUpdate) || ((now - lastPushed) > ZT_PEER_ACTIVITY_TIMEOUT)) {
m.pushCredentials(RR, tPtr, now, to, _config);
if ((lastPushed < _lastConfigUpdate)||((now - lastPushed) > ZT_PEER_ACTIVITY_TIMEOUT)) {
m.pushCredentials(RR,tPtr,now,to,_config);
}
}
@ -444,7 +416,7 @@ class Network {
*
* @param ec Buffer to fill with externally-visible network configuration
*/
inline void externalConfig(ZT_VirtualNetworkConfig* ec) const
inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
{
Mutex::Lock _l(_lock);
_externalConfig(ec);
@ -453,41 +425,36 @@ class Network {
/**
* @return Externally usable pointer-to-pointer exported via the core API
*/
inline void** userPtr()
{
return &_uPtr;
}
inline void **userPtr() { return &_uPtr; }
private:
private:
ZT_VirtualNetworkStatus _status() const;
void _externalConfig(ZT_VirtualNetworkConfig* ec) const; // assumes _lock is locked
bool _gate(const SharedPtr<Peer>& peer);
void _sendUpdatesToMembers(void* tPtr, const MulticastGroup* const newMulticastGroup);
void _announceMulticastGroupsTo(void* tPtr, const Address& peer, const std::vector<MulticastGroup>& allMulticastGroups);
void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
bool _gate(const SharedPtr<Peer> &peer);
void _sendUpdatesToMembers(void *tPtr,const MulticastGroup *const newMulticastGroup);
void _announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
std::vector<MulticastGroup> _allMulticastGroups() const;
Membership& _membership(const Address& a);
void _sendUpdateEvent(void* tPtr);
Membership &_membership(const Address &a);
void _sendUpdateEvent(void *tPtr);
const RuntimeEnvironment* const RR;
void* _uPtr;
const RuntimeEnvironment *const RR;
void *_uPtr;
const uint64_t _id;
std::string _nwidStr;
uint64_t _lastAnnouncedMulticastGroupsUpstream;
MAC _mac; // local MAC address
MAC _mac; // local MAC address
bool _portInitialized;
std::vector<MulticastGroup> _myMulticastGroups; // multicast groups that we belong to (according to tap)
Hashtable<MulticastGroup, uint64_t> _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
Hashtable<MAC, Address> _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
NetworkConfig _config;
int64_t _lastConfigUpdate;
struct _IncomingConfigChunk {
_IncomingConfigChunk()
{
memset(this, 0, sizeof(_IncomingConfigChunk));
}
struct _IncomingConfigChunk
{
_IncomingConfigChunk() { memset(this,0,sizeof(_IncomingConfigChunk)); }
uint64_t ts;
uint64_t updateId;
uint64_t haveChunkIds[ZT_NETWORK_MAX_UPDATE_CHUNKS];
@ -499,11 +466,17 @@ class Network {
bool _destroyed;
enum { NETCONF_FAILURE_NONE, NETCONF_FAILURE_ACCESS_DENIED, NETCONF_FAILURE_NOT_FOUND, NETCONF_FAILURE_INIT_FAILED, NETCONF_FAILURE_AUTHENTICATION_REQUIRED } _netconfFailure;
int _portError; // return value from port config callback
enum {
NETCONF_FAILURE_NONE,
NETCONF_FAILURE_ACCESS_DENIED,
NETCONF_FAILURE_NOT_FOUND,
NETCONF_FAILURE_INIT_FAILED,
NETCONF_FAILURE_AUTHENTICATION_REQUIRED
} _netconfFailure;
int _portError; // return value from port config callback
std::string _authenticationURL;
Hashtable<Address, Membership> _memberships;
Hashtable<Address,Membership> _memberships;
Mutex _lock;

View file

@ -4,94 +4,95 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "NetworkConfig.hpp"
#include <stdint.h>
#include <algorithm>
#include <stdint.h>
#include "NetworkConfig.hpp"
namespace ZeroTier {
bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d, bool includeLegacy) const
bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d,bool includeLegacy) const
{
Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>* tmp = new Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>();
char tmp2[128] = { 0 };
Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY> *tmp = new Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>();
char tmp2[128] = {0};
try {
d.clear();
// Try to put the more human-readable fields first
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_VERSION, (uint64_t)ZT_NETWORKCONFIG_VERSION)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID, this->networkId)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID,this->networkId)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP, this->timestamp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP,this->timestamp)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CREDENTIAL_TIME_MAX_DELTA, this->credentialTimeMaxDelta)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CREDENTIAL_TIME_MAX_DELTA,this->credentialTimeMaxDelta)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_REVISION, this->revision)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_REVISION,this->revision)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO, this->issuedTo.toString(tmp2))) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO,this->issuedTo.toString(tmp2))) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_TARGET, this->remoteTraceTarget.toString(tmp2))) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_TARGET,this->remoteTraceTarget.toString(tmp2))) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_LEVEL, (uint64_t)this->remoteTraceLevel)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_LEVEL,(uint64_t)this->remoteTraceLevel)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_FLAGS, this->flags)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_FLAGS,this->flags)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT, (uint64_t)this->multicastLimit)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT,(uint64_t)this->multicastLimit)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_TYPE, (uint64_t)this->type)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_TYPE,(uint64_t)this->type)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_NAME, this->name)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_NAME,this->name)) {
delete tmp;
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_MTU, (uint64_t)this->mtu)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_MTU,(uint64_t)this->mtu)) {
delete tmp;
return false;
}
#ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
if (includeLegacy) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST_OLD, this->enableBroadcast())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST_OLD,this->enableBroadcast())) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE_OLD, this->isPrivate())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE_OLD,this->isPrivate())) {
return false;
}
std::string v4s;
for (unsigned int i = 0; i < staticIpCount; ++i) {
for(unsigned int i=0;i<staticIpCount;++i) {
if (this->staticIps[i].ss_family == AF_INET) {
if (v4s.length() > 0) {
v4s.push_back(',');
@ -101,12 +102,12 @@ bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d,
}
}
if (v4s.length() > 0) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC_OLD, v4s.c_str())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC_OLD,v4s.c_str())) {
return false;
}
}
std::string v6s;
for (unsigned int i = 0; i < staticIpCount; ++i) {
for(unsigned int i=0;i<staticIpCount;++i) {
if (this->staticIps[i].ss_family == AF_INET6) {
if (v6s.length() > 0) {
v6s.push_back(',');
@ -116,7 +117,7 @@ bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d,
}
}
if (v6s.length() > 0) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC_OLD, v6s.c_str())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC_OLD,v6s.c_str())) {
return false;
}
}
@ -124,131 +125,130 @@ bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d,
std::string ets;
unsigned int et = 0;
ZT_VirtualNetworkRuleType lastrt = ZT_NETWORK_RULE_ACTION_ACCEPT;
for (unsigned int i = 0; i < ruleCount; ++i) {
for(unsigned int i=0;i<ruleCount;++i) {
ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[i].t & 0x7f);
if (rt == ZT_NETWORK_RULE_MATCH_ETHERTYPE) {
et = rules[i].v.etherType;
}
else if (rt == ZT_NETWORK_RULE_ACTION_ACCEPT) {
if (((int)lastrt < 32) || (lastrt == ZT_NETWORK_RULE_MATCH_ETHERTYPE)) {
} else if (rt == ZT_NETWORK_RULE_ACTION_ACCEPT) {
if (((int)lastrt < 32)||(lastrt == ZT_NETWORK_RULE_MATCH_ETHERTYPE)) {
if (ets.length() > 0) {
ets.push_back(',');
}
char tmp2[16] = { 0 };
ets.append(Utils::hex((uint16_t)et, tmp2));
char tmp2[16] = {0};
ets.append(Utils::hex((uint16_t)et,tmp2));
}
et = 0;
}
lastrt = rt;
}
if (ets.length() > 0) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES_OLD, ets.c_str())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES_OLD,ets.c_str())) {
return false;
}
}
if (this->com) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP_OLD, this->com.toString().c_str())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP_OLD,this->com.toString().c_str())) {
return false;
}
}
std::string ab;
for (unsigned int i = 0; i < this->specialistCount; ++i) {
for(unsigned int i=0;i<this->specialistCount;++i) {
if ((this->specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0) {
if (ab.length() > 0) {
ab.push_back(',');
}
char tmp2[16] = { 0 };
char tmp2[16] = {0};
ab.append(Address(this->specialists[i]).toString(tmp2));
}
}
if (ab.length() > 0) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES_OLD, ab.c_str())) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES_OLD,ab.c_str())) {
return false;
}
}
}
#endif // ZT_SUPPORT_OLD_STYLE_NETCONF
#endif // ZT_SUPPORT_OLD_STYLE_NETCONF
// Then add binary blobs
if (this->com) {
tmp->clear();
this->com.serialize(*tmp);
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_COM, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_COM,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->capabilityCount; ++i) {
for(unsigned int i=0;i<this->capabilityCount;++i) {
this->capabilities[i].serialize(*tmp);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CAPABILITIES, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CAPABILITIES,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->tagCount; ++i) {
for(unsigned int i=0;i<this->tagCount;++i) {
this->tags[i].serialize(*tmp);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_TAGS, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_TAGS,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->certificateOfOwnershipCount; ++i) {
for(unsigned int i=0;i<this->certificateOfOwnershipCount;++i) {
this->certificatesOfOwnership[i].serialize(*tmp);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATES_OF_OWNERSHIP, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATES_OF_OWNERSHIP,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->specialistCount; ++i) {
for(unsigned int i=0;i<this->specialistCount;++i) {
tmp->append((uint64_t)this->specialists[i]);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SPECIALISTS, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SPECIALISTS,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->routeCount; ++i) {
reinterpret_cast<const InetAddress*>(&(this->routes[i].target))->serialize(*tmp);
reinterpret_cast<const InetAddress*>(&(this->routes[i].via))->serialize(*tmp);
for(unsigned int i=0;i<this->routeCount;++i) {
reinterpret_cast<const InetAddress *>(&(this->routes[i].target))->serialize(*tmp);
reinterpret_cast<const InetAddress *>(&(this->routes[i].via))->serialize(*tmp);
tmp->append((uint16_t)this->routes[i].flags);
tmp->append((uint16_t)this->routes[i].metric);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ROUTES, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ROUTES,*tmp)) {
return false;
}
}
tmp->clear();
for (unsigned int i = 0; i < this->staticIpCount; ++i) {
for(unsigned int i=0;i<this->staticIpCount;++i) {
this->staticIps[i].serialize(*tmp);
}
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_STATIC_IPS, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_STATIC_IPS,*tmp)) {
return false;
}
}
if (this->ruleCount) {
tmp->clear();
Capability::serializeRules(*tmp, rules, ruleCount);
Capability::serializeRules(*tmp,rules,ruleCount);
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_RULES, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_RULES,*tmp)) {
return false;
}
}
@ -257,61 +257,59 @@ bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d,
tmp->clear();
DNS::serializeDNS(*tmp, &dns);
if (tmp->size()) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_DNS, *tmp)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_DNS,*tmp)) {
return false;
}
}
if (this->ssoVersion == 0) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_VERSION, this->ssoVersion)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_VERSION, this->ssoVersion)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_ENABLED, this->ssoEnabled)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_ENABLED, this->ssoEnabled)) {
return false;
}
if (this->ssoEnabled) {
if (this->authenticationURL[0]) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL)) {
return false;
}
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_EXPIRY_TIME, this->authenticationExpiryTime)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_EXPIRY_TIME, this->authenticationExpiryTime)) {
return false;
}
}
}
else if (this->ssoVersion == 1) {
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_VERSION, this->ssoVersion)) {
} else if(this->ssoVersion == 1) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_VERSION, this->ssoVersion)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_ENABLED, this->ssoEnabled)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_ENABLED, this->ssoEnabled)) {
return false;
}
// if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL)) return false;
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_ISSUER_URL, this->issuerURL)) {
//if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL)) return false;
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_ISSUER_URL, this->issuerURL)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CENTRAL_ENDPOINT_URL, this->centralAuthURL)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CENTRAL_ENDPOINT_URL, this->centralAuthURL)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_NONCE, this->ssoNonce)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_NONCE, this->ssoNonce)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_STATE, this->ssoState)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_STATE, this->ssoState)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_CLIENT_ID, this->ssoClientID)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_CLIENT_ID, this->ssoClientID)) {
return false;
}
if (! d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_PROVIDER, this->ssoProvider)) {
if (!d.add(ZT_NETWORKCONFIG_DICT_KEY_SSO_PROVIDER, this->ssoProvider)) {
return false;
}
}
delete tmp;
}
catch (...) {
} catch ( ... ) {
delete tmp;
throw;
}
@ -319,84 +317,83 @@ bool NetworkConfig::toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d,
return true;
}
bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d)
bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d)
{
static const NetworkConfig NIL_NC;
Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>* tmp = new Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>();
Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY> *tmp = new Buffer<ZT_NETWORKCONFIG_DICT_CAPACITY>();
try {
*this = NIL_NC;
// Fields that are always present, new or old
this->networkId = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID, 0);
if (! this->networkId) {
this->networkId = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID,0);
if (!this->networkId) {
delete tmp;
return false;
}
this->timestamp = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP, 0);
this->credentialTimeMaxDelta = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_CREDENTIAL_TIME_MAX_DELTA, 0);
this->revision = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_REVISION, 0);
this->issuedTo = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO, 0);
if (! this->issuedTo) {
this->timestamp = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP,0);
this->credentialTimeMaxDelta = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_CREDENTIAL_TIME_MAX_DELTA,0);
this->revision = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_REVISION,0);
this->issuedTo = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO,0);
if (!this->issuedTo) {
delete tmp;
return false;
}
this->remoteTraceTarget = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_TARGET);
this->remoteTraceLevel = (Trace::Level)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_REMOTE_TRACE_LEVEL);
this->multicastLimit = (unsigned int)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT, 0);
d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME, this->name, sizeof(this->name));
this->multicastLimit = (unsigned int)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT,0);
d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME,this->name,sizeof(this->name));
this->mtu = (unsigned int)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_MTU, ZT_DEFAULT_MTU);
this->mtu = (unsigned int)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_MTU,ZT_DEFAULT_MTU);
if (this->mtu < 1280) {
this->mtu = 1280; // minimum MTU allowed by IPv6 standard and others
}
else if (this->mtu > ZT_MAX_MTU) {
this->mtu = 1280; // minimum MTU allowed by IPv6 standard and others
} else if (this->mtu > ZT_MAX_MTU) {
this->mtu = ZT_MAX_MTU;
}
if (d.getUI(ZT_NETWORKCONFIG_DICT_KEY_VERSION, 0) < 6) {
#ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
char tmp2[1024] = { 0 };
if (d.getUI(ZT_NETWORKCONFIG_DICT_KEY_VERSION,0) < 6) {
#ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
char tmp2[1024] = {0};
// Decode legacy fields if version is old
if (d.getB(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST_OLD)) {
this->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
}
this->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION; // always enable for old-style netconf
this->type = (d.getB(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE_OLD, true)) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
this->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION; // always enable for old-style netconf
this->type = (d.getB(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE_OLD,true)) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC_OLD, tmp2, sizeof(tmp2)) > 0) {
char* saveptr = (char*)0;
for (char* f = Utils::stok(tmp2, ",", &saveptr); (f); f = Utils::stok((char*)0, ",", &saveptr)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC_OLD,tmp2,sizeof(tmp2)) > 0) {
char *saveptr = (char *)0;
for(char *f=Utils::stok(tmp2,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
if (this->staticIpCount >= ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
break;
}
InetAddress ip(f);
if (! ip.isNetwork()) {
if (!ip.isNetwork()) {
this->staticIps[this->staticIpCount++] = ip;
}
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC_OLD, tmp2, sizeof(tmp2)) > 0) {
char* saveptr = (char*)0;
for (char* f = Utils::stok(tmp2, ",", &saveptr); (f); f = Utils::stok((char*)0, ",", &saveptr)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC_OLD,tmp2,sizeof(tmp2)) > 0) {
char *saveptr = (char *)0;
for(char *f=Utils::stok(tmp2,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
if (this->staticIpCount >= ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
break;
}
InetAddress ip(f);
if (! ip.isNetwork()) {
if (!ip.isNetwork()) {
this->staticIps[this->staticIpCount++] = ip;
}
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP_OLD, tmp2, sizeof(tmp2)) > 0) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP_OLD,tmp2,sizeof(tmp2)) > 0) {
this->com.fromString(tmp2);
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES_OLD, tmp2, sizeof(tmp2)) > 0) {
char* saveptr = (char*)0;
for (char* f = Utils::stok(tmp2, ",", &saveptr); (f); f = Utils::stok((char*)0, ",", &saveptr)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES_OLD,tmp2,sizeof(tmp2)) > 0) {
char *saveptr = (char *)0;
for(char *f=Utils::stok(tmp2,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
unsigned int et = Utils::hexStrToUInt(f) & 0xffff;
if ((this->ruleCount + 2) > ZT_MAX_NETWORK_RULES) {
break;
@ -408,74 +405,67 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
}
this->rules[this->ruleCount++].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
}
}
else {
} else {
this->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
this->ruleCount = 1;
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES_OLD, tmp2, sizeof(tmp2)) > 0) {
char* saveptr = (char*)0;
for (char* f = Utils::stok(tmp2, ",", &saveptr); (f); f = Utils::stok((char*)0, ",", &saveptr)) {
this->addSpecialist(Address(Utils::hexStrToU64(f)), ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES_OLD,tmp2,sizeof(tmp2)) > 0) {
char *saveptr = (char *)0;
for(char *f=Utils::stok(tmp2,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
this->addSpecialist(Address(Utils::hexStrToU64(f)),ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
}
}
#else
#else
delete tmp;
return false;
#endif // ZT_SUPPORT_OLD_STYLE_NETCONF
}
else {
#endif // ZT_SUPPORT_OLD_STYLE_NETCONF
} else {
// Otherwise we can use the new fields
this->flags = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_FLAGS, 0);
this->type = (ZT_VirtualNetworkType)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_TYPE, (uint64_t)ZT_NETWORK_TYPE_PRIVATE);
this->flags = d.getUI(ZT_NETWORKCONFIG_DICT_KEY_FLAGS,0);
this->type = (ZT_VirtualNetworkType)d.getUI(ZT_NETWORKCONFIG_DICT_KEY_TYPE,(uint64_t)ZT_NETWORK_TYPE_PRIVATE);
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_COM, *tmp)) {
this->com.deserialize(*tmp, 0);
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_COM,*tmp)) {
this->com.deserialize(*tmp,0);
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CAPABILITIES, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CAPABILITIES,*tmp)) {
try {
unsigned int p = 0;
while (p < tmp->size()) {
Capability cap;
p += cap.deserialize(*tmp, p);
p += cap.deserialize(*tmp,p);
this->capabilities[this->capabilityCount++] = cap;
}
}
catch (...) {
}
std::sort(&(this->capabilities[0]), &(this->capabilities[this->capabilityCount]));
} catch ( ... ) {}
std::sort(&(this->capabilities[0]),&(this->capabilities[this->capabilityCount]));
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_TAGS, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_TAGS,*tmp)) {
try {
unsigned int p = 0;
while (p < tmp->size()) {
Tag tag;
p += tag.deserialize(*tmp, p);
p += tag.deserialize(*tmp,p);
this->tags[this->tagCount++] = tag;
}
}
catch (...) {
}
std::sort(&(this->tags[0]), &(this->tags[this->tagCount]));
} catch ( ... ) {}
std::sort(&(this->tags[0]),&(this->tags[this->tagCount]));
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATES_OF_OWNERSHIP, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATES_OF_OWNERSHIP,*tmp)) {
unsigned int p = 0;
while (p < tmp->size()) {
if (certificateOfOwnershipCount < ZT_MAX_CERTIFICATES_OF_OWNERSHIP) {
p += certificatesOfOwnership[certificateOfOwnershipCount++].deserialize(*tmp, p);
}
else {
p += certificatesOfOwnership[certificateOfOwnershipCount++].deserialize(*tmp,p);
} else {
CertificateOfOwnership foo;
p += foo.deserialize(*tmp, p);
p += foo.deserialize(*tmp,p);
}
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_SPECIALISTS, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_SPECIALISTS,*tmp)) {
unsigned int p = 0;
while ((p + 8) <= tmp->size()) {
if (specialistCount < ZT_MAX_NETWORK_SPECIALISTS) {
@ -485,11 +475,11 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ROUTES, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_ROUTES,*tmp)) {
unsigned int p = 0;
while ((p < tmp->size()) && (routeCount < ZT_MAX_NETWORK_ROUTES)) {
p += reinterpret_cast<InetAddress*>(&(this->routes[this->routeCount].target))->deserialize(*tmp, p);
p += reinterpret_cast<InetAddress*>(&(this->routes[this->routeCount].via))->deserialize(*tmp, p);
while ((p < tmp->size())&&(routeCount < ZT_MAX_NETWORK_ROUTES)) {
p += reinterpret_cast<InetAddress *>(&(this->routes[this->routeCount].target))->deserialize(*tmp,p);
p += reinterpret_cast<InetAddress *>(&(this->routes[this->routeCount].via))->deserialize(*tmp,p);
this->routes[this->routeCount].flags = tmp->at<uint16_t>(p);
p += 2;
this->routes[this->routeCount].metric = tmp->at<uint16_t>(p);
@ -498,17 +488,17 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_STATIC_IPS, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_STATIC_IPS,*tmp)) {
unsigned int p = 0;
while ((p < tmp->size()) && (staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
p += this->staticIps[this->staticIpCount++].deserialize(*tmp, p);
while ((p < tmp->size())&&(staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
p += this->staticIps[this->staticIpCount++].deserialize(*tmp,p);
}
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_RULES, *tmp)) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_RULES,*tmp)) {
this->ruleCount = 0;
unsigned int p = 0;
Capability::deserializeRules(*tmp, p, this->rules, this->ruleCount, ZT_MAX_NETWORK_RULES);
Capability::deserializeRules(*tmp,p,this->rules,this->ruleCount,ZT_MAX_NETWORK_RULES);
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_DNS, *tmp)) {
@ -523,19 +513,16 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
// implicit flow
if (this->ssoEnabled) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL, (unsigned int)sizeof(this->authenticationURL)) > 0) {
this->authenticationURL[sizeof(this->authenticationURL) - 1] = 0; // ensure null terminated
}
else {
this->authenticationURL[sizeof(this->authenticationURL) - 1] = 0; // ensure null terminated
} else {
this->authenticationURL[0] = 0;
}
this->authenticationExpiryTime = d.getI(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_EXPIRY_TIME, 0);
}
else {
} else {
this->authenticationURL[0] = 0;
this->authenticationExpiryTime = 0;
}
}
else if (this->ssoVersion == 1) {
} else if (this->ssoVersion == 1) {
// full flow
if (this->ssoEnabled) {
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_AUTHENTICATION_URL, this->authenticationURL, (unsigned int)sizeof(this->authenticationURL)) > 0) {
@ -558,13 +545,11 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
}
if (d.get(ZT_NETWORKCONFIG_DICT_KEY_SSO_PROVIDER, this->ssoProvider, (unsigned int)(sizeof(this->ssoProvider))) > 0) {
this->ssoProvider[sizeof(this->ssoProvider) - 1] = 0;
}
else {
} else {
strncpy(this->ssoProvider, "default", sizeof(this->ssoProvider));
this->ssoProvider[sizeof(this->ssoProvider) - 1] = 0;
}
}
else {
} else {
this->authenticationURL[0] = 0;
this->authenticationExpiryTime = 0;
this->centralAuthURL[0] = 0;
@ -577,17 +562,16 @@ bool NetworkConfig::fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACI
}
}
// printf("~~~\n%s\n~~~\n",d.data());
// dump();
// printf("~~~\n");
//printf("~~~\n%s\n~~~\n",d.data());
//dump();
//printf("~~~\n");
delete tmp;
return true;
}
catch (...) {
} catch ( ... ) {
delete tmp;
return false;
}
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,29 +14,31 @@
#ifndef ZT_NETWORKCONFIG_HPP
#define ZT_NETWORKCONFIG_HPP
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include "../include/ZeroTierOne.h"
#include "Address.hpp"
#include "Constants.hpp"
#include "Buffer.hpp"
#include "Capability.hpp"
#include "DNS.hpp"
#include "InetAddress.hpp"
#include "MulticastGroup.hpp"
#include "Address.hpp"
#include "CertificateOfMembership.hpp"
#include "CertificateOfOwnership.hpp"
#include "Constants.hpp"
#include "DNS.hpp"
#include "Capability.hpp"
#include "Tag.hpp"
#include "Dictionary.hpp"
#include "Hashtable.hpp"
#include "Identity.hpp"
#include "InetAddress.hpp"
#include "MulticastGroup.hpp"
#include "Tag.hpp"
#include "Trace.hpp"
#include "Utils.hpp"
#include <algorithm>
#include <stdexcept>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "Trace.hpp"
/**
* Default time delta for COMs, tags, and capabilities
@ -91,9 +93,7 @@
namespace ZeroTier {
// Dictionary capacity needed for max size network config
#define ZT_NETWORKCONFIG_DICT_CAPACITY \
(4096 + (sizeof(ZT_VirtualNetworkConfig)) + (sizeof(ZT_VirtualNetworkRule) * ZT_MAX_NETWORK_RULES) + (sizeof(Capability) * ZT_MAX_NETWORK_CAPABILITIES) + (sizeof(Tag) * ZT_MAX_NETWORK_TAGS) \
+ (sizeof(CertificateOfOwnership) * ZT_MAX_CERTIFICATES_OF_OWNERSHIP))
#define ZT_NETWORKCONFIG_DICT_CAPACITY (4096 + (sizeof(ZT_VirtualNetworkConfig)) + (sizeof(ZT_VirtualNetworkRule) * ZT_MAX_NETWORK_RULES) + (sizeof(Capability) * ZT_MAX_NETWORK_CAPABILITIES) + (sizeof(Tag) * ZT_MAX_NETWORK_TAGS) + (sizeof(CertificateOfOwnership) * ZT_MAX_CERTIFICATES_OF_OWNERSHIP))
// Dictionary capacity needed for max size network meta-data
#define ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY 1024
@ -105,8 +105,6 @@ namespace ZeroTier {
// Network config version
#define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION "v"
// Network config version
#define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_OS_ARCH "o"
// Protocol version (see Packet.hpp)
#define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION "pv"
// Software vendor
@ -248,45 +246,46 @@ namespace ZeroTier {
* This is a memcpy()'able structure and is safe (in a crash sense) to modify
* without locks.
*/
class NetworkConfig {
public:
NetworkConfig()
: networkId(0)
, timestamp(0)
, credentialTimeMaxDelta(0)
, revision(0)
, issuedTo()
, remoteTraceTarget()
, flags(0)
, remoteTraceLevel(Trace::LEVEL_NORMAL)
, mtu(0)
, multicastLimit(0)
, specialistCount(0)
, routeCount(0)
, staticIpCount(0)
, ruleCount(0)
, capabilityCount(0)
, tagCount(0)
, certificateOfOwnershipCount(0)
, capabilities()
, tags()
, certificatesOfOwnership()
, type(ZT_NETWORK_TYPE_PRIVATE)
, dnsCount(0)
, ssoEnabled(false)
, authenticationURL()
, authenticationExpiryTime(0)
, issuerURL()
, centralAuthURL()
, ssoNonce()
, ssoState()
, ssoClientID()
class NetworkConfig
{
public:
NetworkConfig() :
networkId(0),
timestamp(0),
credentialTimeMaxDelta(0),
revision(0),
issuedTo(),
remoteTraceTarget(),
flags(0),
remoteTraceLevel(Trace::LEVEL_NORMAL),
mtu(0),
multicastLimit(0),
specialistCount(0),
routeCount(0),
staticIpCount(0),
ruleCount(0),
capabilityCount(0),
tagCount(0),
certificateOfOwnershipCount(0),
capabilities(),
tags(),
certificatesOfOwnership(),
type(ZT_NETWORK_TYPE_PRIVATE),
dnsCount(0),
ssoEnabled(false),
authenticationURL(),
authenticationExpiryTime(0),
issuerURL(),
centralAuthURL(),
ssoNonce(),
ssoState(),
ssoClientID()
{
name[0] = 0;
memset(specialists, 0, sizeof(uint64_t) * ZT_MAX_NETWORK_SPECIALISTS);
memset(routes, 0, sizeof(ZT_VirtualNetworkRoute) * ZT_MAX_NETWORK_ROUTES);
memset(staticIps, 0, sizeof(InetAddress) * ZT_MAX_ZT_ASSIGNED_ADDRESSES);
memset(rules, 0, sizeof(ZT_VirtualNetworkRule) * ZT_MAX_NETWORK_RULES);
memset(specialists, 0, sizeof(uint64_t)*ZT_MAX_NETWORK_SPECIALISTS);
memset(routes, 0, sizeof(ZT_VirtualNetworkRoute)*ZT_MAX_NETWORK_ROUTES);
memset(staticIps, 0, sizeof(InetAddress)*ZT_MAX_ZT_ASSIGNED_ADDRESSES);
memset(rules, 0, sizeof(ZT_VirtualNetworkRule)*ZT_MAX_NETWORK_RULES);
memset(&dns, 0, sizeof(ZT_VirtualNetworkDNS));
memset(authenticationURL, 0, sizeof(authenticationURL));
memset(issuerURL, 0, sizeof(issuerURL));
@ -304,7 +303,7 @@ class NetworkConfig {
* @param includeLegacy If true, include legacy fields for old node versions
* @return True if dictionary was successfully created, false if e.g. overflow
*/
bool toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d, bool includeLegacy) const;
bool toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d,bool includeLegacy) const;
/**
* Read this network config from a dictionary
@ -312,23 +311,17 @@ class NetworkConfig {
* @param d Dictionary (non-const since it might be modified during parse, should not be used after call)
* @return True if dictionary was valid and network config successfully initialized
*/
bool fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>& d);
bool fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d);
/**
* @return True if broadcast (ff:ff:ff:ff:ff:ff) address should work on this network
*/
inline bool enableBroadcast() const
{
return ((this->flags & ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST) != 0);
}
inline bool enableBroadcast() const { return ((this->flags & ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST) != 0); }
/**
* @return True if IPv6 NDP emulation should be allowed for certain "magic" IPv6 address patterns
*/
inline bool ndpEmulation() const
{
return ((this->flags & ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION) != 0);
}
inline bool ndpEmulation() const { return ((this->flags & ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION) != 0); }
/**
* @return True if frames should not be compressed
@ -349,18 +342,12 @@ class NetworkConfig {
/**
* @return Network type is public (no access control)
*/
inline bool isPublic() const
{
return (this->type == ZT_NETWORK_TYPE_PUBLIC);
}
inline bool isPublic() const { return (this->type == ZT_NETWORK_TYPE_PUBLIC); }
/**
* @return Network type is private (certificate access control)
*/
inline bool isPrivate() const
{
return (this->type == ZT_NETWORK_TYPE_PRIVATE);
}
inline bool isPrivate() const { return (this->type == ZT_NETWORK_TYPE_PRIVATE); }
/**
* @return ZeroTier addresses of devices on this network designated as active bridges
@ -368,7 +355,7 @@ class NetworkConfig {
inline std::vector<Address> activeBridges() const
{
std::vector<Address> r;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0) {
r.push_back(Address(specialists[i]));
}
@ -379,7 +366,7 @@ class NetworkConfig {
inline unsigned int activeBridges(Address ab[ZT_MAX_NETWORK_SPECIALISTS]) const
{
unsigned int c = 0;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0) {
ab[c++] = specialists[i];
}
@ -387,10 +374,10 @@ class NetworkConfig {
return c;
}
inline bool isActiveBridge(const Address& a) const
inline bool isActiveBridge(const Address &a) const
{
for (unsigned int i = 0; i < specialistCount; ++i) {
if (((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0) && (a == specialists[i])) {
for(unsigned int i=0;i<specialistCount;++i) {
if (((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)&&(a == specialists[i])) {
return true;
}
}
@ -400,7 +387,7 @@ class NetworkConfig {
inline std::vector<Address> anchors() const
{
std::vector<Address> r;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR) != 0) {
r.push_back(Address(specialists[i]));
}
@ -411,7 +398,7 @@ class NetworkConfig {
inline std::vector<Address> multicastReplicators() const
{
std::vector<Address> r;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR) != 0) {
r.push_back(Address(specialists[i]));
}
@ -422,7 +409,7 @@ class NetworkConfig {
inline unsigned int multicastReplicators(Address mr[ZT_MAX_NETWORK_SPECIALISTS]) const
{
unsigned int c = 0;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR) != 0) {
mr[c++] = specialists[i];
}
@ -430,10 +417,10 @@ class NetworkConfig {
return c;
}
inline bool isMulticastReplicator(const Address& a) const
inline bool isMulticastReplicator(const Address &a) const
{
for (unsigned int i = 0; i < specialistCount; ++i) {
if (((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR) != 0) && (a == specialists[i])) {
for(unsigned int i=0;i<specialistCount;++i) {
if (((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR) != 0)&&(a == specialists[i])) {
return true;
}
}
@ -443,7 +430,7 @@ class NetworkConfig {
inline std::vector<Address> alwaysContactAddresses() const
{
std::vector<Address> r;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & (ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR | ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR)) != 0) {
r.push_back(Address(specialists[i]));
}
@ -454,7 +441,7 @@ class NetworkConfig {
inline unsigned int alwaysContactAddresses(Address ac[ZT_MAX_NETWORK_SPECIALISTS]) const
{
unsigned int c = 0;
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & (ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR | ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR)) != 0) {
ac[c++] = specialists[i];
}
@ -462,9 +449,9 @@ class NetworkConfig {
return c;
}
inline void alwaysContactAddresses(Hashtable<Address, std::vector<InetAddress> >& a) const
inline void alwaysContactAddresses(Hashtable< Address,std::vector<InetAddress> > &a) const
{
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & (ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR | ZT_NETWORKCONFIG_SPECIALIST_TYPE_MULTICAST_REPLICATOR)) != 0) {
a[Address(specialists[i])];
}
@ -475,28 +462,19 @@ class NetworkConfig {
* @param fromPeer Peer attempting to bridge other Ethernet peers onto network
* @return True if this network allows bridging
*/
inline bool permitsBridging(const Address& fromPeer) const
inline bool permitsBridging(const Address &fromPeer) const
{
for (unsigned int i = 0; i < specialistCount; ++i) {
if ((fromPeer == specialists[i]) && ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((fromPeer == specialists[i])&&((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)) {
return true;
}
}
return false;
}
inline operator bool() const
{
return (networkId != 0);
}
inline bool operator==(const NetworkConfig& nc) const
{
return (memcmp(this, &nc, sizeof(NetworkConfig)) == 0);
}
inline bool operator!=(const NetworkConfig& nc) const
{
return (! (*this == nc));
}
inline operator bool() const { return (networkId != 0); }
inline bool operator==(const NetworkConfig &nc) const { return (memcmp(this,&nc,sizeof(NetworkConfig)) == 0); }
inline bool operator!=(const NetworkConfig &nc) const { return (!(*this == nc)); }
/**
* Add a specialist or mask flags if already present
@ -508,10 +486,10 @@ class NetworkConfig {
* @param f Flags (OR of specialist role/type flags)
* @return True if successfully masked or added
*/
inline bool addSpecialist(const Address& a, const uint64_t f)
inline bool addSpecialist(const Address &a,const uint64_t f)
{
const uint64_t aint = a.toInt();
for (unsigned int i = 0; i < specialistCount; ++i) {
for(unsigned int i=0;i<specialistCount;++i) {
if ((specialists[i] & 0xffffffffffULL) == aint) {
specialists[i] |= f;
return true;
@ -524,24 +502,24 @@ class NetworkConfig {
return false;
}
const Capability* capability(const uint32_t id) const
const Capability *capability(const uint32_t id) const
{
for (unsigned int i = 0; i < capabilityCount; ++i) {
for(unsigned int i=0;i<capabilityCount;++i) {
if (capabilities[i].id() == id) {
return &(capabilities[i]);
}
}
return (Capability*)0;
return (Capability *)0;
}
const Tag* tag(const uint32_t id) const
const Tag *tag(const uint32_t id) const
{
for (unsigned int i = 0; i < tagCount; ++i) {
for(unsigned int i=0;i<tagCount;++i) {
if (tags[i].id() == id) {
return &(tags[i]);
}
}
return (Tag*)0;
return (Tag *)0;
}
/**
@ -709,7 +687,7 @@ class NetworkConfig {
/**
* Time current authentication expires or 0 if external authentication is disabled
*
*
* Not used if authVersion >= 1
*/
uint64_t authenticationExpiryTime;
@ -749,6 +727,6 @@ class NetworkConfig {
char ssoProvider[64];
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,13 +14,13 @@
#ifndef ZT_NETWORKCONFIGMASTER_HPP
#define ZT_NETWORKCONFIGMASTER_HPP
#include "Address.hpp"
#include <stdint.h>
#include "Constants.hpp"
#include "Dictionary.hpp"
#include "NetworkConfig.hpp"
#include "Revocation.hpp"
#include <stdint.h>
#include "Address.hpp"
namespace ZeroTier {
@ -30,15 +30,24 @@ struct InetAddress;
/**
* Interface for network controller implementations
*/
class NetworkController {
public:
enum ErrorCode { NC_ERROR_NONE = 0, NC_ERROR_OBJECT_NOT_FOUND = 1, NC_ERROR_ACCESS_DENIED = 2, NC_ERROR_INTERNAL_SERVER_ERROR = 3, NC_ERROR_AUTHENTICATION_REQUIRED = 4 };
class NetworkController
{
public:
enum ErrorCode
{
NC_ERROR_NONE = 0,
NC_ERROR_OBJECT_NOT_FOUND = 1,
NC_ERROR_ACCESS_DENIED = 2,
NC_ERROR_INTERNAL_SERVER_ERROR = 3,
NC_ERROR_AUTHENTICATION_REQUIRED = 4
};
/**
* Interface for sender used to send pushes and replies
*/
class Sender {
public:
class Sender
{
public:
/**
* Send a configuration to a remote peer
*
@ -48,7 +57,7 @@ class NetworkController {
* @param nc Network configuration to send
* @param sendLegacyFormatConfig If true, send an old-format network config
*/
virtual void ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address& destination, const NetworkConfig& nc, bool sendLegacyFormatConfig) = 0;
virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig) = 0;
/**
* Send revocation to a node
@ -56,14 +65,14 @@ class NetworkController {
* @param destination Destination node address
* @param rev Revocation to send
*/
virtual void ncSendRevocation(const Address& destination, const Revocation& rev) = 0;
virtual void ncSendRevocation(const Address &destination,const Revocation &rev) = 0;
/**
* Send a network configuration request error
*
* If errorData/errorDataSize are provided they must point to a valid serialized
* Dictionary containing error data. They can be null/zero if not specified.
*
*
* @param nwid Network ID
* @param requestPacketId Request packet ID or 0 if none
* @param destination Destination peer Address
@ -71,15 +80,11 @@ class NetworkController {
* @param errorData Data associated with error or NULL if none
* @param errorDataSize Size of errorData in bytes
*/
virtual void ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address& destination, NetworkController::ErrorCode errorCode, const void* errorData, unsigned int errorDataSize) = 0;
virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize) = 0;
};
NetworkController()
{
}
virtual ~NetworkController()
{
}
NetworkController() {}
virtual ~NetworkController() {}
/**
* Called when this is added to a Node to initialize and supply info
@ -87,7 +92,7 @@ class NetworkController {
* @param signingId Identity for signing of network configurations, certs, etc.
* @param sender Sender implementation for sending replies or config pushes
*/
virtual void init(const Identity& signingId, Sender* sender) = 0;
virtual void init(const Identity &signingId,Sender *sender) = 0;
/**
* Handle a network configuration request
@ -99,9 +104,14 @@ class NetworkController {
* @param metaData Meta-data bundled with request (if any)
* @return Returns NETCONF_QUERY_OK if result 'nc' is valid, or an error code on error
*/
virtual void request(uint64_t nwid, const InetAddress& fromAddr, uint64_t requestPacketId, const Identity& identity, const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>& metaData) = 0;
virtual void request(
uint64_t nwid,
const InetAddress &fromAddr,
uint64_t requestPacketId,
const Identity &identity,
const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData) = 0;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,26 +14,29 @@
#ifndef ZT_NODE_HPP
#define ZT_NODE_HPP
#include "../include/ZeroTierOne.h"
#include "Bond.hpp"
#include "Constants.hpp"
#include "Hashtable.hpp"
#include "InetAddress.hpp"
#include "MAC.hpp"
#include "Mutex.hpp"
#include "Network.hpp"
#include "NetworkController.hpp"
#include "Path.hpp"
#include "RuntimeEnvironment.hpp"
#include "Salsa20.hpp"
#include "SelfAwareness.hpp"
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <vector>
#include "Constants.hpp"
#include "../include/ZeroTierOne.h"
#include "RuntimeEnvironment.hpp"
#include "InetAddress.hpp"
#include "Mutex.hpp"
#include "MAC.hpp"
#include "Network.hpp"
#include "Path.hpp"
#include "Salsa20.hpp"
#include "NetworkController.hpp"
#include "Hashtable.hpp"
#include "Bond.hpp"
#include "SelfAwareness.hpp"
// Bit mask for "expecting reply" hash
#define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
#define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
@ -47,76 +50,94 @@ class World;
*
* The pointer returned by ZT_Node_new() is an instance of this class.
*/
class Node : public NetworkController::Sender {
public:
Node(void* uptr, void* tptr, const struct ZT_Node_Callbacks* callbacks, int64_t now);
class Node : public NetworkController::Sender
{
public:
Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now);
virtual ~Node();
// Get rid of alignment warnings on 32-bit Windows and possibly improve performance
#ifdef __WINDOWS__
void* operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void operator delete(void* p)
{
_mm_free(p);
}
void * operator new(size_t i) { return _mm_malloc(i,16); }
void operator delete(void* p) { _mm_free(p); }
#endif
// Public API Functions ----------------------------------------------------
ZT_ResultCode processWirePacket(void* tptr, int64_t now, int64_t localSocket, const struct sockaddr_storage* remoteAddress, const void* packetData, unsigned int packetLength, volatile int64_t* nextBackgroundTaskDeadline);
ZT_ResultCode processWirePacket(
void *tptr,
int64_t now,
int64_t localSocket,
const struct sockaddr_storage *remoteAddress,
const void *packetData,
unsigned int packetLength,
volatile int64_t *nextBackgroundTaskDeadline);
ZT_ResultCode processVirtualNetworkFrame(
void* tptr,
void *tptr,
int64_t now,
uint64_t nwid,
uint64_t sourceMac,
uint64_t destMac,
unsigned int etherType,
unsigned int vlanId,
const void* frameData,
const void *frameData,
unsigned int frameLength,
volatile int64_t* nextBackgroundTaskDeadline);
ZT_ResultCode processBackgroundTasks(void* tptr, int64_t now, volatile int64_t* nextBackgroundTaskDeadline);
ZT_ResultCode join(uint64_t nwid, void* uptr, void* tptr);
ZT_ResultCode leave(uint64_t nwid, void** uptr, void* tptr);
ZT_ResultCode multicastSubscribe(void* tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi);
ZT_ResultCode multicastUnsubscribe(uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi);
ZT_ResultCode orbit(void* tptr, uint64_t moonWorldId, uint64_t moonSeed);
ZT_ResultCode deorbit(void* tptr, uint64_t moonWorldId);
volatile int64_t *nextBackgroundTaskDeadline);
ZT_ResultCode processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline);
ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
ZT_ResultCode orbit(void *tptr,uint64_t moonWorldId,uint64_t moonSeed);
ZT_ResultCode deorbit(void *tptr,uint64_t moonWorldId);
uint64_t address() const;
void status(ZT_NodeStatus* status) const;
ZT_PeerList* peers() const;
ZT_VirtualNetworkConfig* networkConfig(uint64_t nwid) const;
ZT_VirtualNetworkList* networks() const;
void freeQueryResult(void* qr);
int addLocalInterfaceAddress(const struct sockaddr_storage* addr);
void status(ZT_NodeStatus *status) const;
ZT_PeerList *peers() const;
ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
ZT_VirtualNetworkList *networks() const;
void freeQueryResult(void *qr);
int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
void clearLocalInterfaceAddresses();
int sendUserMessage(void* tptr, uint64_t dest, uint64_t typeId, const void* data, unsigned int len);
void setNetconfMaster(void* networkControllerInstance);
int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
void setNetconfMaster(void *networkControllerInstance);
// Internal functions ------------------------------------------------------
inline int64_t now() const
inline int64_t now() const { return _now; }
inline bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
{
return _now;
return (_cb.wirePacketSendFunction(
reinterpret_cast<ZT_Node *>(this),
_uPtr,
tPtr,
localSocket,
reinterpret_cast<const struct sockaddr_storage *>(&addr),
data,
len,
ttl) == 0);
}
inline bool putPacket(void* tPtr, const int64_t localSocket, const InetAddress& addr, const void* data, unsigned int len, unsigned int ttl = 0)
inline void putFrame(void *tPtr,uint64_t nwid,void **nuptr,const MAC &source,const MAC &dest,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
{
return (_cb.wirePacketSendFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, localSocket, reinterpret_cast<const struct sockaddr_storage*>(&addr), data, len, ttl) == 0);
}
inline void putFrame(void* tPtr, uint64_t nwid, void** nuptr, const MAC& source, const MAC& dest, unsigned int etherType, unsigned int vlanId, const void* data, unsigned int len)
{
_cb.virtualNetworkFrameFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, nwid, nuptr, source.toInt(), dest.toInt(), etherType, vlanId, data, len);
_cb.virtualNetworkFrameFunction(
reinterpret_cast<ZT_Node *>(this),
_uPtr,
tPtr,
nwid,
nuptr,
source.toInt(),
dest.toInt(),
etherType,
vlanId,
data,
len);
}
inline SharedPtr<Network> network(uint64_t nwid) const
{
Mutex::Lock _l(_networks_m);
const SharedPtr<Network>* n = _networks.get(nwid);
const SharedPtr<Network> *n = _networks.get(nwid);
if (n) {
return *n;
}
@ -129,14 +150,14 @@ class Node : public NetworkController::Sender {
return _networks.contains(nwid);
}
inline std::vector<SharedPtr<Network> > allNetworks() const
inline std::vector< SharedPtr<Network> > allNetworks() const
{
std::vector<SharedPtr<Network> > nw;
std::vector< SharedPtr<Network> > nw;
Mutex::Lock _l(_networks_m);
Hashtable<uint64_t, SharedPtr<Network> >::Iterator i(*const_cast<Hashtable<uint64_t, SharedPtr<Network> >*>(&_networks));
uint64_t* k = (uint64_t*)0;
SharedPtr<Network>* v = (SharedPtr<Network>*)0;
while (i.next(k, v)) {
Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > * >(&_networks));
uint64_t *k = (uint64_t *)0;
SharedPtr<Network> *v = (SharedPtr<Network> *)0;
while (i.next(k,v)) {
nw.push_back(*v);
}
return nw;
@ -148,60 +169,30 @@ class Node : public NetworkController::Sender {
return _directPaths;
}
inline void postEvent(void* tPtr, ZT_Event ev, const void* md = (const void*)0)
{
_cb.eventCallback(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, ev, md);
}
inline void postEvent(void *tPtr,ZT_Event ev,const void *md = (const void *)0) { _cb.eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ev,md); }
inline int configureVirtualNetworkPort(void* tPtr, uint64_t nwid, void** nuptr, ZT_VirtualNetworkConfigOperation op, const ZT_VirtualNetworkConfig* nc)
{
return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, nwid, nuptr, op, nc);
}
inline int configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc); }
inline bool online() const
{
return _online;
}
inline bool online() const { return _online; }
inline int stateObjectGet(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2], void* const data, const unsigned int maxlen)
{
return _cb.stateGetFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, data, maxlen);
}
inline void stateObjectPut(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2], const void* const data, const unsigned int len)
{
_cb.statePutFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, data, (int)len);
}
inline void stateObjectDelete(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2])
{
_cb.statePutFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, (const void*)0, -1);
}
inline int stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],void *const data,const unsigned int maxlen) { return _cb.stateGetFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,maxlen); }
inline void stateObjectPut(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void *const data,const unsigned int len) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,(int)len); }
inline void stateObjectDelete(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]) { _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,(const void *)0,-1); }
bool shouldUsePathForZeroTierTraffic(void* tPtr, const Address& ztaddr, const int64_t localSocket, const InetAddress& remoteAddress);
inline bool externalPathLookup(void* tPtr, const Address& ztaddr, int family, InetAddress& addr)
{
return ((_cb.pathLookupFunction) ? (_cb.pathLookupFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, ztaddr.toInt(), family, reinterpret_cast<struct sockaddr_storage*>(&addr)) != 0) : false);
}
bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
inline bool externalPathLookup(void *tPtr,const Address &ztaddr,int family,InetAddress &addr) { return ( (_cb.pathLookupFunction) ? (_cb.pathLookupFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ztaddr.toInt(),family,reinterpret_cast<struct sockaddr_storage *>(&addr)) != 0) : false ); }
uint64_t prng();
ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage* pathNetwork, const ZT_PhysicalPathConfiguration* pathConfig);
ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
World planet() const;
std::vector<World> moons() const;
inline const Identity& identity() const
{
return _RR.identity;
}
inline const Identity &identity() const { return _RR.identity; }
inline const std::vector<InetAddress> SurfaceAddresses() const
{
return _RR.sa->whoami();
}
inline const std::vector<InetAddress> SurfaceAddresses() const { return _RR.sa->whoami(); }
inline Bond* bondController() const
{
return _RR.bc;
}
inline Bond *bondController() const { return _RR.bc; }
/**
* Register that we are expecting a reply to a packet ID
@ -233,7 +224,7 @@ class Node : public NetworkController::Sender {
{
const uint32_t pid2 = (uint32_t)(packetId >> 32);
const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
for (unsigned long i = 0; i <= ZT_EXPECTING_REPLIES_BUCKET_MASK2; ++i) {
for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
if (_expectingRepliesTo[bucket][i] == pid2) {
return true;
}
@ -248,7 +239,7 @@ class Node : public NetworkController::Sender {
* @param from Source address of packet
* @return True if within rate limits
*/
inline bool rateGateIdentityVerification(const int64_t now, const InetAddress& from)
inline bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
{
unsigned long iph = from.rateGateHash();
if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
@ -258,23 +249,17 @@ class Node : public NetworkController::Sender {
return false;
}
virtual void ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address& destination, const NetworkConfig& nc, bool sendLegacyFormatConfig);
virtual void ncSendRevocation(const Address& destination, const Revocation& rev);
virtual void ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address& destination, NetworkController::ErrorCode errorCode, const void* errorData, unsigned int errorDataSize);
virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode, const void *errorData, unsigned int errorDataSize);
inline const Address& remoteTraceTarget() const
{
return _remoteTraceTarget;
}
inline Trace::Level remoteTraceLevel() const
{
return _remoteTraceLevel;
}
inline const Address &remoteTraceTarget() const { return _remoteTraceTarget; }
inline Trace::Level remoteTraceLevel() const { return _remoteTraceLevel; }
inline bool localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address& addr) const
inline bool localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
{
_localControllerAuthorizations_m.lock();
const int64_t* const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid, addr));
const int64_t *const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid,addr));
_localControllerAuthorizations_m.unlock();
if (at) {
return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
@ -282,7 +267,7 @@ class Node : public NetworkController::Sender {
return false;
}
inline void statsLogVerb(const unsigned int v, const unsigned int bytes)
inline void statsLogVerb(const unsigned int v,const unsigned int bytes)
{
++_stats.inVerbCounts[v];
_stats.inVerbBytes[v] += (uint64_t)bytes;
@ -298,12 +283,10 @@ class Node : public NetworkController::Sender {
return _lowBandwidthMode;
}
void initMultithreading(unsigned int concurrency, bool cpuPinningEnabled);
public:
private:
RuntimeEnvironment _RR;
RuntimeEnvironment* RR;
void* _uPtr; // _uptr (lower case) is reserved in Visual Studio :P
RuntimeEnvironment *RR;
void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
ZT_Node_Callbacks _cb;
// For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
@ -318,28 +301,18 @@ class Node : public NetworkController::Sender {
// Map that remembers if we have recently sent a network config to someone
// querying us as a controller.
struct _LocalControllerAuth {
uint64_t nwid, address;
_LocalControllerAuth(const uint64_t nwid_, const Address& address_) : nwid(nwid_), address(address_.toInt())
{
}
inline unsigned long hashCode() const
{
return (unsigned long)(nwid ^ address);
}
inline bool operator==(const _LocalControllerAuth& a) const
{
return ((a.nwid == nwid) && (a.address == address));
}
inline bool operator!=(const _LocalControllerAuth& a) const
{
return ((a.nwid != nwid) || (a.address != address));
}
struct _LocalControllerAuth
{
uint64_t nwid,address;
_LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
inline unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
inline bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
inline bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
};
Hashtable<_LocalControllerAuth, int64_t> _localControllerAuthorizations;
Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
Mutex _localControllerAuthorizations_m;
Hashtable<uint64_t, SharedPtr<Network> > _networks;
Hashtable< uint64_t,SharedPtr<Network> > _networks;
Mutex _networks_m;
std::vector<InetAddress> _directPaths;
@ -360,6 +333,6 @@ class Node : public NetworkController::Sender {
bool _lowBandwidthMode;
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

View file

@ -4,36 +4,35 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "OutboundMulticast.hpp"
#include "Constants.hpp"
#include "RuntimeEnvironment.hpp"
#include "OutboundMulticast.hpp"
#include "Switch.hpp"
#include "Network.hpp"
#include "Node.hpp"
#include "Peer.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Topology.hpp"
namespace ZeroTier {
void OutboundMulticast::init(
const RuntimeEnvironment* RR,
const RuntimeEnvironment *RR,
uint64_t timestamp,
uint64_t nwid,
bool disableCompression,
unsigned int limit,
unsigned int gatherLimit,
const MAC& src,
const MulticastGroup& dest,
const MAC &src,
const MulticastGroup &dest,
unsigned int etherType,
const void* payload,
const void *payload,
unsigned int len)
{
uint8_t flags = 0;
@ -43,9 +42,8 @@ void OutboundMulticast::init(
if (src) {
_macSrc = src;
flags |= 0x04;
}
else {
_macSrc.fromAddress(RR->identity.address(), nwid);
} else {
_macSrc.fromAddress(RR->identity.address(),nwid);
}
_macDest = dest.mac();
_limit = limit;
@ -69,26 +67,26 @@ void OutboundMulticast::init(
dest.mac().appendTo(_packet);
_packet.append((uint32_t)dest.adi());
_packet.append((uint16_t)etherType);
_packet.append(payload, _frameLen);
if (! disableCompression) {
_packet.append(payload,_frameLen);
if (!disableCompression) {
_packet.compress();
}
memcpy(_frameData, payload, _frameLen);
memcpy(_frameData,payload,_frameLen);
}
void OutboundMulticast::sendOnly(const RuntimeEnvironment* RR, void* tPtr, const Address& toAddr)
void OutboundMulticast::sendOnly(const RuntimeEnvironment *RR,void *tPtr,const Address &toAddr)
{
const SharedPtr<Network> nw(RR->node->network(_nwid));
uint8_t QoSBucket = 255; // Dummy value
if ((nw) && (nw->filterOutgoingPacket(tPtr, true, RR->identity.address(), toAddr, _macSrc, _macDest, _frameData, _frameLen, _etherType, 0, QoSBucket))) {
nw->pushCredentialsIfNeeded(tPtr, toAddr, RR->node->now());
uint8_t QoSBucket = 255; // Dummy value
if ((nw)&&(nw->filterOutgoingPacket(tPtr,true,RR->identity.address(),toAddr,_macSrc,_macDest,_frameData,_frameLen,_etherType,0,QoSBucket))) {
nw->pushCredentialsIfNeeded(tPtr,toAddr,RR->node->now());
_packet.newInitializationVector();
_packet.setDestination(toAddr);
RR->node->expectReplyTo(_packet.packetId());
_tmp = _packet;
RR->sw->send(tPtr, _tmp, true);
RR->sw->send(tPtr,_tmp,true);
}
}
} // namespace ZeroTier
} // namespace ZeroTier

View file

@ -4,7 +4,7 @@
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
@ -14,16 +14,17 @@
#ifndef ZT_OUTBOUNDMULTICAST_HPP
#define ZT_OUTBOUNDMULTICAST_HPP
#include "Address.hpp"
#include <stdint.h>
#include <vector>
#include <algorithm>
#include "Constants.hpp"
#include "MAC.hpp"
#include "MulticastGroup.hpp"
#include "Address.hpp"
#include "Packet.hpp"
#include <algorithm>
#include <stdint.h>
#include <vector>
namespace ZeroTier {
class CertificateOfMembership;
@ -34,16 +35,15 @@ class RuntimeEnvironment;
*
* This object isn't guarded by a mutex; caller must synchronize access.
*/
class OutboundMulticast {
public:
class OutboundMulticast
{
public:
/**
* Create an uninitialized outbound multicast
*
* It must be initialized with init().
*/
OutboundMulticast()
{
}
OutboundMulticast() {}
/**
* Initialize outbound multicast
@ -62,42 +62,33 @@ class OutboundMulticast {
* @throws std::out_of_range Data too large to fit in a MULTICAST_FRAME
*/
void init(
const RuntimeEnvironment* RR,
const RuntimeEnvironment *RR,
uint64_t timestamp,
uint64_t nwid,
bool disableCompression,
unsigned int limit,
unsigned int gatherLimit,
const MAC& src,
const MulticastGroup& dest,
const MAC &src,
const MulticastGroup &dest,
unsigned int etherType,
const void* payload,
const void *payload,
unsigned int len);
/**
* @return Multicast creation time
*/
inline uint64_t timestamp() const
{
return _timestamp;
}
inline uint64_t timestamp() const { return _timestamp; }
/**
* @param now Current time
* @return True if this multicast is expired (has exceeded transmit timeout)
*/
inline bool expired(int64_t now) const
{
return ((now - _timestamp) >= ZT_MULTICAST_TRANSMIT_TIMEOUT);
}
inline bool expired(int64_t now) const { return ((now - _timestamp) >= ZT_MULTICAST_TRANSMIT_TIMEOUT); }
/**
* @return True if this outbound multicast has been sent to enough peers
*/
inline bool atLimit() const
{
return (_alreadySentTo.size() >= _limit);
}
inline bool atLimit() const { return (_alreadySentTo.size() >= _limit); }
/**
* Just send without checking log
@ -106,7 +97,7 @@ class OutboundMulticast {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @param toAddr Destination address
*/
void sendOnly(const RuntimeEnvironment* RR, void* tPtr, const Address& toAddr);
void sendOnly(const RuntimeEnvironment *RR,void *tPtr,const Address &toAddr);
/**
* Just send and log but do not check sent log
@ -115,10 +106,10 @@ class OutboundMulticast {
* @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
* @param toAddr Destination address
*/
inline void sendAndLog(const RuntimeEnvironment* RR, void* tPtr, const Address& toAddr)
inline void sendAndLog(const RuntimeEnvironment *RR,void *tPtr,const Address &toAddr)
{
_alreadySentTo.push_back(toAddr);
sendOnly(RR, tPtr, toAddr);
sendOnly(RR,tPtr,toAddr);
}
/**
@ -126,7 +117,7 @@ class OutboundMulticast {
*
* @param toAddr Address to log as sent
*/
inline void logAsSent(const Address& toAddr)
inline void logAsSent(const Address &toAddr)
{
_alreadySentTo.push_back(toAddr);
}
@ -139,18 +130,17 @@ class OutboundMulticast {
* @param toAddr Destination address
* @return True if address is new and packet was sent to switch, false if duplicate
*/
inline bool sendIfNew(const RuntimeEnvironment* RR, void* tPtr, const Address& toAddr)
inline bool sendIfNew(const RuntimeEnvironment *RR,void *tPtr,const Address &toAddr)
{
if (std::find(_alreadySentTo.begin(), _alreadySentTo.end(), toAddr) == _alreadySentTo.end()) {
sendAndLog(RR, tPtr, toAddr);
if (std::find(_alreadySentTo.begin(),_alreadySentTo.end(),toAddr) == _alreadySentTo.end()) {
sendAndLog(RR,tPtr,toAddr);
return true;
}
else {
} else {
return false;
}
}
private:
private:
uint64_t _timestamp;
uint64_t _nwid;
MAC _macSrc;
@ -158,11 +148,11 @@ class OutboundMulticast {
unsigned int _limit;
unsigned int _frameLen;
unsigned int _etherType;
Packet _packet, _tmp;
Packet _packet,_tmp;
std::vector<Address> _alreadySentTo;
uint8_t _frameData[ZT_MAX_MTU];
};
} // namespace ZeroTier
} // namespace ZeroTier
#endif

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more