Imported Upstream version 1.1.14

This commit is contained in:
NAStools 2016-11-01 16:45:16 -07:00
commit bb232b9d52
557 changed files with 115164 additions and 0 deletions

261
controller/README.md Normal file
View file

@ -0,0 +1,261 @@
Network Controller Microservice
======
ZeroTier's 16-digit network IDs are really just a concatenation of the 10-digit ZeroTier address of a network controller followed by a 6-digit (24-bit) network number on that controller. Fans of software defined networking will recognize this as a variation of the familiar [separation of data plane and control plane](http://sdntutorials.com/difference-between-control-plane-and-data-plane/) SDN design pattern.
This code implements the *node/NetworkController.hpp* interface and provides a SQLite3-backed network controller microservice. Including it in the build allows ZeroTier One to act as a controller and create/manage networks.
This is the same code we use to run [my.zerotier.com](https://my.zerotier.com/), which is a web UI and API that runs in front of a pool of controllers.
### Building
On Linux, Mac, or BSD you can create a controller-enabled build with:
make ZT_ENABLE_NETWORK_CONTROLLER=1
You will need the development headers and libraries for SQLite3 installed.
### Running
After building and installing (`make install`) a controller-enabled build of ZeroTier One, start it and try:
sudo zerotier-cli /controller
You should see something like:
{
"controller": true,
"apiVersion": 2,
"clock": 1468002975497,
"instanceId": "8ab354604debe1da27ee627c9ef94a48"
}
When started, a controller-enabled build of ZeroTier One will automatically create and initialize a `controller.db` file in its home folder. This is where all the controller's data and persistent state lives. If you're upgrading an old controller it will upgrade its database schema automatically on first launch. Make a backup of the old controller's database first since you can't go backward.
Controllers periodically make backups of their database as `controller.db.backup`. This is done so that this file can be more easily copied/rsync'ed to other systems without worrying about corruption. SQLite3 supports multiple processes accessing the same database file, so `sqlite3 /path/to/controller.db .dump` also works but can be slow on a busy controller.
Controllers can in theory host up to 2^24 networks and serve many millions of devices (or more), but we recommend running multiple controllers for a lot of networks to spread load and be more fault tolerant.
### Dockerizing Controllers
ZeroTier network controllers can easily be run in Docker or other container systems. Since containers do not need to actually join networks, extra privilege options like "--device=/dev/net/tun --privileged" are not needed. You'll just need to map the local JSON API port of the running controller and allow it to access the Internet (over UDP/9993 at a minimum) so things can reach and query it.
### Implementing High Availability Fail-Over
ZeroTier network controllers are not single points of failure for networks-- in the sense that if a controller goes down *existing* members of a network can continue to communicate. But new members (or those that have been offline for a while) can't join, existing members can't be de-authorized, and other changes to the network's configuration can't be made. This means that short "glitches" in controller availability are not a major problem but long periods of unavailability can be.
Because controllers are just regular ZeroTier nodes and controller queries are in-band, controllers can trivially be moved without worrying about changes to underlying physical IPs. This makes high-availability fail-over very easy to implement.
Just set up two cloud hosts, preferably in different data centers (e.g. two different AWS regions or Digital Ocean SF and NYC). Now set up the hot spare controller to constantly mirror `controller.db.backup` from its active sibling.
If the active controller goes down, rename `controller.db.backup` to `controller.db` on the hot spare and start the ZeroTier One service there. The spare will take over and has now become the active controller. If the original active node comes back, it should take on the role of spare and should not start its service. Instead it should start mirroring the active controller's backup and wait until it is needed.
The details of actually implementing this kind of HA fail-over on Linux or other OSes are beyond the scope of these docs and there are many ways to do it. Docker orchestration tools like Kubernetes can also be used to accomplish this if you've dockerized your controller.
### Network Controller API
The controller API is hosted via the same JSON API endpoint that ZeroTier One uses for local control (usually at 127.0.0.1 port 9993). All controller options are routed under the `/controller` base path.
The controller microservice does not implement any fine-grained access control (authentication is via authtoken.secret just like the regular JSON API) or other complex mangement features. It just takes network and network member configurations and reponds to controller queries. We have an enterprise product called [ZeroTier Central](https://my.zerotier.com/) that we host as a service (and that companies can license to self-host) that does this.
All working network IDs on a controller must begin with the controller's ZeroTier address. The API will *allow* "foreign" networks to be added but the controller will have no way of doing anything with them.
Also note that the API is *very* sensitive about types. Integers must be integers and strings strings, etc. Incorrectly typed and unrecognized fields are just ignored.
#### `/controller`
* Purpose: Check for controller function and return controller status
* Methods: GET
* Returns: { object }
| Field | Type | Description | Writable |
| ------------------ | ----------- | ------------------------------------------------- | -------- |
| controller | boolean | Always 'true' | no |
| apiVersion | integer | Controller API version, currently 2 | no |
| clock | integer | Current clock on controller, ms since epoch | no |
| instanceId | string | A random ID generated on first controller DB init | no |
The instance ID can be used to check whether a controller's database has been reset or otherwise switched.
#### `/controller/network`
* Purpose: List all networks hosted by this controller
* Methods: GET
* Returns: [ string, ... ]
This returns an array of 16-digit hexadecimal network IDs.
#### `/controller/network/<network ID>`
* Purpose: Create, configure, and delete hosted networks
* Methods: GET, POST, DELETE
* Returns: { object }
By making queries to this path you can create, configure, and delete networks. DELETE is final, so don't do it unless you really mean it.
When POSTing new networks take care that their IDs are not in use, otherwise you may overwrite an existing one. To create a new network with a random unused ID, POST to `/controller/network/##########______`. The #'s are the controller's 10-digit ZeroTier address and they're followed by six underscores. Check the `nwid` field of the returned JSON object for your network's newly allocated ID. Subsequent POSTs to this network must refer to its actual path.
| Field | Type | Description | Writable |
| --------------------- | ------------- | ------------------------------------------------- | -------- |
| nwid | string | 16-digit network ID | no |
| controllerInstanceId | string | Controller database instance ID | no |
| clock | integer | Current clock, ms since epoch | no |
| name | string | A short name for this network | YES |
| private | boolean | Is access control enabled? | YES |
| enableBroadcast | boolean | Ethernet ff:ff:ff:ff:ff:ff allowed? | YES |
| allowPassiveBridging | boolean | Allow any member to bridge (very experimental) | YES |
| v4AssignMode | string | If 'zt', auto-assign IPv4 from pool(s) | YES |
| v6AssignMode | string | IPv6 address auto-assign modes; see below | YES |
| multicastLimit | integer | Maximum recipients for a multicast packet | YES |
| creationTime | integer | Time network was first created | no |
| revision | integer | Network config revision counter | no |
| memberRevisionCounter | integer | Network member revision counter | no |
| authorizedMemberCount | integer | Number of authorized members (for private nets) | no |
| relays | array[object] | Alternative relays; see below | YES |
| routes | array[object] | Managed IPv4 and IPv6 routes; see below | YES |
| ipAssignmentPools | array[object] | IP auto-assign ranges; see below | YES |
| rules | array[object] | Traffic rules; see below | YES |
(The `ipLocalRoutes` field appeared in older versions but is no longer present. Routes will now show up in `routes`.)
Two important things to know about networks:
- Networks without rules won't carry any traffic. See below for an example with rules to permit IPv4 and IPv6.
- Managed IP address assignments and IP assignment pools that do not fall within a route configured in `routes` are ignored and won't be used or sent to members.
- The default for `private` is `true` and this is probably what you want. Turning `private` off means *anyone* can join your network with only its 16-digit network ID. It's also impossible to de-authorize a member as these networks don't issue or enforce certificates. Such "party line" networks are used for decentralized app backplanes, gaming, and testing but are not common in ordinary use.
**IPv6 Auto-Assign Modes:**
This field is (for legacy reasons) a comma-delimited list of strings. These can be `rfc4193`, `6plane`, and `zt`. RFC4193 and 6PLANE are special addressing modes that deterministically assign IPv6 addresses based on the network ID and the ZeroTier address of each member. The `zt` mode enables IPv6 auto-assignment from arbitrary IPv6 IP ranges configured in `ipAssignmentPools`.
**Relay object format:**
Relay objects define network-specific preferred relay nodes. Traffic to peers on this network will preferentially use these relays if they are available, and otherwise will fall back to the global rootserver infrastructure.
| Field | Type | Description | Writable |
| --------------------- | ------------- | ------------------------------------------------- | -------- |
| address | string | 10-digit ZeroTier address of relay | YES |
| phyAddress | string | Optional IP/port suggestion for finding relay | YES |
**IP assignment pool object format:**
| Field | Type | Description | Writable |
| --------------------- | ------------- | ------------------------------------------------- | -------- |
| ipRangeStart | string | Starting IP address in range | YES |
| ipRangeEnd | string | Ending IP address in range (inclusive) | YES |
Pools are only used if auto-assignment is on for the given address type (IPv4 or IPv6) and if the entire range falls within a managed route.
IPv6 ranges work just like IPv4 ranges and look like this:
{
"ipRangeStart": "fd00:feed:feed:beef:0000:0000:0000:0000",
"ipRangeEnd": "fd00:feed:feed:beef:ffff:ffff:ffff:ffff"
}
(You can POST a shortened-form IPv6 address but the API will always report back un-shortened canonical form addresses.)
That defines a range within network `fd00:feed:feed:beef::/64` that contains up to 2^64 addresses. If an IPv6 range is large enough, the controller will assign addresses by placing each member's device ID into the address in a manner similar to the RFC4193 and 6PLANE modes. Otherwise it will assign addresses at random.
**Rule object format:**
Rules are matched in order of ruleNo. If no rules match, the default action is `drop`. To allow all traffic, create a single rule with all *null* fields and an action of `accept`.
In the future there will be many, many more types of rules. As of today only filtering by Ethernet packet type is supported.
| Field | Type | Description | Writable |
| --------------------- | ------------- | ------------------------------------------------- | -------- |
| ruleNo | integer | Rule sorting key | YES |
| etherType | integer | Ethernet frame type (e.g. 34525 for IPv6) | YES |
| action | string | Currently either `allow` or `drop` | YES |
**An Example: The Configuration for Earth**
Here is an example of a correctly configured ZeroTier network with IPv4 auto-assigned addresses from 28.0.0.0/7 (a "de-facto private" space) and RFC4193 IPv6 addressing. Users might recognize this as *Earth*, our public "global LAN party" that's used for demos and testing and occasionally gaming.
For your own networks you'll probably want to change `private` to `true` unless you like company. These rules on the other hand probably are what you want. These allow IPv4, IPv4 ARP, and IPv6 Ethernet frames. To allow only IPv4 omit the one for Ethernet type 34525 (IPv6).
{
"nwid": "8056c2e21c000001",
"controllerInstanceId": "8ab354604debe1da27ee627c9ef94a48",
"clock": 1468004857100,
"name": "earth.zerotier.net",
"private": false,
"enableBroadcast": false,
"allowPassiveBridging": false,
"v4AssignMode": "zt",
"v6AssignMode": "rfc4193",
"multicastLimit": 64,
"creationTime": 1442292573165,
"revision": 234,
"memberRevisionCounter": 3326,
"authorizedMemberCount": 2873,
"relays": [],
"routes": [
{"target":"28.0.0.0/7","via":null,"flags":0,"metric":0}],
"ipAssignmentPools": [
{"ipRangeStart":"28.0.0.1","ipRangeEnd":"29.255.255.254"}],
"rules": [
{
"ruleNo": 20,
"etherType": 2048,
"action": "accept"
},{
"ruleNo": 21,
"etherType": 2054,
"action": "accept"
},{
"ruleNo": 30,
"etherType": 34525,
"action": "accept"
}]
}
#### `/controller/network/<network ID>/member`
* Purpose: Get a set of all members on this network
* Methods: GET
* Returns: { object }
This returns a JSON object containing all member IDs as keys and their `memberRevisionCounter` values as values.
#### `/controller/network/<network ID>/active`
* Purpose: Get a set of all active members on this network
* Methods: GET
* Returns: { object }
This returns an object containing all currently online members and the most recent `recentLog` entries for their last request.
#### `/controller/network/<network ID>/member/<address>`
* Purpose: Create, authorize, or remove a network member
* Methods: GET, POST, DELETE
* Returns: { object }
| Field | Type | Description | Writable |
| --------------------- | ------------- | ------------------------------------------------- | -------- |
| nwid | string | 16-digit network ID | no |
| clock | integer | Current clock, ms since epoch | no |
| address | string | Member's 10-digit ZeroTier address | no |
| authorized | boolean | Is member authorized? (for private networks) | YES |
| activeBridge | boolean | Member is able to bridge to other Ethernet nets | YES |
| identity | string | Member's public ZeroTier identity (if known) | no |
| ipAssignments | array[string] | Managed IP address assignments | YES |
| memberRevision | integer | Member revision counter | no |
| recentLog | array[object] | Recent member activity log; see below | no |
Note that managed IP assignments are only used if they fall within a managed route. Otherwise they are ignored.
**Recent log object format:**
| Field | Type | Description |
| --------------------- | ------------- | ------------------------------------------------- |
| ts | integer | Time of request, ms since epoch |
| authorized | boolean | Was member authorized? |
| clientMajorVersion | integer | Client major version or -1 if unknown |
| clientMinorVersion | integer | Client minor version or -1 if unknown |
| clientRevision | integer | Client revision or -1 if unknown |
| fromAddr | string | Physical address if known |
The controller can only know a member's `fromAddr` if it's able to establish a direct path to it. Members behind very restrictive firewalls may not have this information since the controller will be receiving the member's requests by way of a relay. ZeroTier does not back-trace IP paths as packets are relayed since this would add a lot of protocol overhead.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,181 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_SQLITENETWORKCONTROLLER_HPP
#define ZT_SQLITENETWORKCONTROLLER_HPP
#include <stdint.h>
#include <sqlite3.h>
#include <string>
#include <map>
#include <vector>
#include "../node/Constants.hpp"
#include "../node/NetworkController.hpp"
#include "../node/Mutex.hpp"
#include "../osdep/Thread.hpp"
// Number of in-memory last log entries to maintain per user
#define ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE 32
// How long do circuit tests last before they're forgotten?
#define ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT 60000
namespace ZeroTier {
class Node;
class SqliteNetworkController : public NetworkController
{
public:
SqliteNetworkController(Node *node,const char *dbPath,const char *circuitTestPath);
virtual ~SqliteNetworkController();
virtual NetworkController::ResultCode doNetworkConfigRequest(
const InetAddress &fromAddr,
const Identity &signingId,
const Identity &identity,
uint64_t nwid,
const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &metaData,
NetworkConfig &nc);
unsigned int handleControlPlaneHttpGET(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType);
unsigned int handleControlPlaneHttpPOST(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType);
unsigned int handleControlPlaneHttpDELETE(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType);
// threadMain() for backup thread -- do not call directly
void threadMain()
throw();
private:
/* deprecated
enum IpAssignmentType {
// IP assignment is a static IP address
ZT_IP_ASSIGNMENT_TYPE_ADDRESS = 0,
// IP assignment is a network -- a route via this interface, not an address
ZT_IP_ASSIGNMENT_TYPE_NETWORK = 1
};
*/
unsigned int _doCPGet(
const std::vector<std::string> &path,
const std::map<std::string,std::string> &urlArgs,
const std::map<std::string,std::string> &headers,
const std::string &body,
std::string &responseBody,
std::string &responseContentType);
static void _circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report);
Node *_node;
Thread _backupThread;
volatile bool _backupThreadRun;
volatile bool _backupNeeded;
std::string _dbPath;
std::string _circuitTestPath;
std::string _instanceId;
// Circuit tests outstanding
struct _CircuitTestEntry
{
ZT_CircuitTest *test;
std::string jsonResults;
};
std::map< uint64_t,_CircuitTestEntry > _circuitTests;
// Last request time by address, for rate limitation
std::map< std::pair<uint64_t,uint64_t>,uint64_t > _lastRequestTime;
sqlite3 *_db;
sqlite3_stmt *_sGetNetworkById;
sqlite3_stmt *_sGetMember;
sqlite3_stmt *_sCreateMember;
sqlite3_stmt *_sGetNodeIdentity;
sqlite3_stmt *_sCreateOrReplaceNode;
sqlite3_stmt *_sGetEtherTypesFromRuleTable;
sqlite3_stmt *_sGetActiveBridges;
sqlite3_stmt *_sGetIpAssignmentsForNode;
sqlite3_stmt *_sGetIpAssignmentPools;
sqlite3_stmt *_sCheckIfIpIsAllocated;
sqlite3_stmt *_sAllocateIp;
sqlite3_stmt *_sDeleteIpAllocations;
sqlite3_stmt *_sGetRelays;
sqlite3_stmt *_sListNetworks;
sqlite3_stmt *_sListNetworkMembers;
sqlite3_stmt *_sGetMember2;
sqlite3_stmt *_sGetIpAssignmentPools2;
sqlite3_stmt *_sListRules;
sqlite3_stmt *_sCreateRule;
sqlite3_stmt *_sCreateNetwork;
sqlite3_stmt *_sGetNetworkRevision;
sqlite3_stmt *_sSetNetworkRevision;
sqlite3_stmt *_sDeleteRelaysForNetwork;
sqlite3_stmt *_sCreateRelay;
sqlite3_stmt *_sDeleteIpAssignmentPoolsForNetwork;
sqlite3_stmt *_sDeleteRulesForNetwork;
sqlite3_stmt *_sCreateIpAssignmentPool;
sqlite3_stmt *_sUpdateMemberAuthorized;
sqlite3_stmt *_sUpdateMemberActiveBridge;
sqlite3_stmt *_sUpdateMemberHistory;
sqlite3_stmt *_sDeleteMember;
sqlite3_stmt *_sDeleteAllNetworkMembers;
sqlite3_stmt *_sGetActiveNodesOnNetwork;
sqlite3_stmt *_sDeleteNetwork;
sqlite3_stmt *_sCreateRoute;
sqlite3_stmt *_sGetRoutes;
sqlite3_stmt *_sDeleteRoutes;
sqlite3_stmt *_sIncrementMemberRevisionCounter;
sqlite3_stmt *_sGetConfig;
sqlite3_stmt *_sSetConfig;
Mutex _lock;
};
} // namespace ZeroTier
#endif

119
controller/schema.sql Normal file
View file

@ -0,0 +1,119 @@
CREATE TABLE Config (
k varchar(16) PRIMARY KEY NOT NULL,
v varchar(1024) NOT NULL
);
CREATE TABLE Network (
id char(16) PRIMARY KEY NOT NULL,
name varchar(128) NOT NULL,
private integer NOT NULL DEFAULT(1),
enableBroadcast integer NOT NULL DEFAULT(1),
allowPassiveBridging integer NOT NULL DEFAULT(0),
multicastLimit integer NOT NULL DEFAULT(32),
creationTime integer NOT NULL DEFAULT(0),
revision integer NOT NULL DEFAULT(1),
memberRevisionCounter integer NOT NULL DEFAULT(1),
flags integer NOT NULL DEFAULT(0)
);
CREATE TABLE AuthToken (
id integer PRIMARY KEY NOT NULL,
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
authMode integer NOT NULL DEFAULT(1),
useCount integer NOT NULL DEFAULT(0),
maxUses integer NOT NULL DEFAULT(0),
expiresAt integer NOT NULL DEFAULT(0),
token varchar(256) NOT NULL
);
CREATE INDEX AuthToken_networkId_token ON AuthToken(networkId,token);
CREATE TABLE Node (
id char(10) PRIMARY KEY NOT NULL,
identity varchar(4096) NOT NULL
);
CREATE TABLE IpAssignment (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
nodeId char(10) REFERENCES Node(id) ON DELETE CASCADE,
type integer NOT NULL DEFAULT(0),
ip blob(16) NOT NULL,
ipNetmaskBits integer NOT NULL DEFAULT(0),
ipVersion integer NOT NULL DEFAULT(4)
);
CREATE UNIQUE INDEX IpAssignment_networkId_ip ON IpAssignment (networkId, ip);
CREATE INDEX IpAssignment_networkId_nodeId ON IpAssignment (networkId, nodeId);
CREATE TABLE IpAssignmentPool (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
ipRangeStart blob(16) NOT NULL,
ipRangeEnd blob(16) NOT NULL,
ipVersion integer NOT NULL DEFAULT(4)
);
CREATE UNIQUE INDEX IpAssignmentPool_networkId_ipRangeStart ON IpAssignmentPool (networkId,ipRangeStart);
CREATE TABLE Member (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,
authorized integer NOT NULL DEFAULT(0),
activeBridge integer NOT NULL DEFAULT(0),
memberRevision integer NOT NULL DEFAULT(0),
flags integer NOT NULL DEFAULT(0),
lastRequestTime integer NOT NULL DEFAULT(0),
lastPowDifficulty integer NOT NULL DEFAULT(0),
lastPowTime integer NOT NULL DEFAULT(0),
recentHistory blob,
PRIMARY KEY (networkId, nodeId)
);
CREATE INDEX Member_networkId_nodeId ON Member(networkId,nodeId);
CREATE INDEX Member_networkId_activeBridge ON Member(networkId, activeBridge);
CREATE INDEX Member_networkId_memberRevision ON Member(networkId, memberRevision);
CREATE INDEX Member_networkId_lastRequestTime ON Member(networkId, lastRequestTime);
CREATE TABLE Route (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
target blob(16) NOT NULL,
via blob(16),
targetNetmaskBits integer NOT NULL,
ipVersion integer NOT NULL,
flags integer NOT NULL,
metric integer NOT NULL
);
CREATE INDEX Route_networkId ON Route (networkId);
CREATE TABLE Relay (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
address char(10) NOT NULL,
phyAddress varchar(64) NOT NULL
);
CREATE UNIQUE INDEX Relay_networkId_address ON Relay (networkId,address);
CREATE TABLE Rule (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
ruleNo integer NOT NULL,
nodeId char(10) REFERENCES Node(id),
sourcePort char(10),
destPort char(10),
vlanId integer,
vlanPcp integer,
etherType integer,
macSource char(12),
macDest char(12),
ipSource varchar(64),
ipDest varchar(64),
ipTos integer,
ipProtocol integer,
ipSourcePort integer,
ipDestPort integer,
flags integer,
invFlags integer,
"action" varchar(4096) NOT NULL DEFAULT('accept')
);
CREATE UNIQUE INDEX Rule_networkId_ruleNo ON Rule (networkId, ruleNo);

121
controller/schema.sql.c Normal file
View file

@ -0,0 +1,121 @@
#define ZT_NETCONF_SCHEMA_SQL \
"CREATE TABLE Config (\n"\
" k varchar(16) PRIMARY KEY NOT NULL,\n"\
" v varchar(1024) NOT NULL\n"\
");\n"\
"\n"\
"CREATE TABLE Network (\n"\
" id char(16) PRIMARY KEY NOT NULL,\n"\
" name varchar(128) NOT NULL,\n"\
" private integer NOT NULL DEFAULT(1),\n"\
" enableBroadcast integer NOT NULL DEFAULT(1),\n"\
" allowPassiveBridging integer NOT NULL DEFAULT(0),\n"\
" multicastLimit integer NOT NULL DEFAULT(32),\n"\
" creationTime integer NOT NULL DEFAULT(0),\n"\
" revision integer NOT NULL DEFAULT(1),\n"\
" memberRevisionCounter integer NOT NULL DEFAULT(1),\n"\
" flags integer NOT NULL DEFAULT(0)\n"\
");\n"\
"\n"\
"CREATE TABLE AuthToken (\n"\
" id integer PRIMARY KEY NOT NULL,\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" authMode integer NOT NULL DEFAULT(1),\n"\
" useCount integer NOT NULL DEFAULT(0),\n"\
" maxUses integer NOT NULL DEFAULT(0),\n"\
" expiresAt integer NOT NULL DEFAULT(0),\n"\
" token varchar(256) NOT NULL\n"\
");\n"\
"\n"\
"CREATE INDEX AuthToken_networkId_token ON AuthToken(networkId,token);\n"\
"\n"\
"CREATE TABLE Node (\n"\
" id char(10) PRIMARY KEY NOT NULL,\n"\
" identity varchar(4096) NOT NULL\n"\
");\n"\
"\n"\
"CREATE TABLE IpAssignment (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" nodeId char(10) REFERENCES Node(id) ON DELETE CASCADE,\n"\
" type integer NOT NULL DEFAULT(0),\n"\
" ip blob(16) NOT NULL,\n"\
" ipNetmaskBits integer NOT NULL DEFAULT(0),\n"\
" ipVersion integer NOT NULL DEFAULT(4)\n"\
");\n"\
"\n"\
"CREATE UNIQUE INDEX IpAssignment_networkId_ip ON IpAssignment (networkId, ip);\n"\
"\n"\
"CREATE INDEX IpAssignment_networkId_nodeId ON IpAssignment (networkId, nodeId);\n"\
"\n"\
"CREATE TABLE IpAssignmentPool (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" ipRangeStart blob(16) NOT NULL,\n"\
" ipRangeEnd blob(16) NOT NULL,\n"\
" ipVersion integer NOT NULL DEFAULT(4)\n"\
");\n"\
"\n"\
"CREATE UNIQUE INDEX IpAssignmentPool_networkId_ipRangeStart ON IpAssignmentPool (networkId,ipRangeStart);\n"\
"\n"\
"CREATE TABLE Member (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"\
" authorized integer NOT NULL DEFAULT(0),\n"\
" activeBridge integer NOT NULL DEFAULT(0),\n"\
" memberRevision integer NOT NULL DEFAULT(0),\n"\
" flags integer NOT NULL DEFAULT(0),\n"\
" lastRequestTime integer NOT NULL DEFAULT(0),\n"\
" lastPowDifficulty integer NOT NULL DEFAULT(0),\n"\
" lastPowTime integer NOT NULL DEFAULT(0),\n"\
" recentHistory blob,\n"\
" PRIMARY KEY (networkId, nodeId)\n"\
");\n"\
"\n"\
"CREATE INDEX Member_networkId_nodeId ON Member(networkId,nodeId);\n"\
"CREATE INDEX Member_networkId_activeBridge ON Member(networkId, activeBridge);\n"\
"CREATE INDEX Member_networkId_memberRevision ON Member(networkId, memberRevision);\n"\
"CREATE INDEX Member_networkId_lastRequestTime ON Member(networkId, lastRequestTime);\n"\
"\n"\
"CREATE TABLE Route (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" target blob(16) NOT NULL,\n"\
" via blob(16),\n"\
" targetNetmaskBits integer NOT NULL,\n"\
" ipVersion integer NOT NULL,\n"\
" flags integer NOT NULL,\n"\
" metric integer NOT NULL\n"\
");\n"\
"\n"\
"CREATE INDEX Route_networkId ON Route (networkId);\n"\
"\n"\
"CREATE TABLE Relay (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" address char(10) NOT NULL,\n"\
" phyAddress varchar(64) NOT NULL\n"\
");\n"\
"\n"\
"CREATE UNIQUE INDEX Relay_networkId_address ON Relay (networkId,address);\n"\
"\n"\
"CREATE TABLE Rule (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" ruleNo integer NOT NULL,\n"\
" nodeId char(10) REFERENCES Node(id),\n"\
" sourcePort char(10),\n"\
" destPort char(10),\n"\
" vlanId integer,\n"\
" vlanPcp integer,\n"\
" etherType integer,\n"\
" macSource char(12),\n"\
" macDest char(12),\n"\
" ipSource varchar(64),\n"\
" ipDest varchar(64),\n"\
" ipTos integer,\n"\
" ipProtocol integer,\n"\
" ipSourcePort integer,\n"\
" ipDestPort integer,\n"\
" flags integer,\n"\
" invFlags integer,\n"\
" \"action\" varchar(4096) NOT NULL DEFAULT('accept')\n"\
");\n"\
"\n"\
"CREATE UNIQUE INDEX Rule_networkId_ruleNo ON Rule (networkId, ruleNo);\n"\
""

8
controller/schema2c.sh Executable file
View file

@ -0,0 +1,8 @@
#!/bin/bash
# Run this file to package the .sql file into a .c file whenever the SQL changes.
rm -f schema.sql.c
echo '#define ZT_NETCONF_SCHEMA_SQL \' >schema.sql.c
cat schema.sql | sed 's/"/\\"/g' | sed 's/^/"/' | sed 's/$/\\n"\\/' >>schema.sql.c
echo '""' >>schema.sql.c