mirror of
https://github.com/ZeroTier/ZeroTierOne
synced 2025-08-24 07:05:50 -07:00
Merge 6d1dc47368
into 9cc2733ed8
This commit is contained in:
commit
0bd287d720
63 changed files with 2130 additions and 828 deletions
|
@ -152,7 +152,7 @@ For most users, it just works.
|
|||
|
||||
If you are running a local system firewall, we recommend adding a rule permitting UDP port 9993 inbound and outbound. If you installed binaries for Windows this should be done automatically. Other platforms might require manual editing of local firewall rules depending on your configuration.
|
||||
|
||||
The Mac firewall can be founder under "Security" in System Preferences. Linux has a variety of firewall configuration systems and tools. If you're using Ubuntu's *ufw*, you can do this:
|
||||
The Mac firewall can be found under "Security" in System Preferences. Linux has a variety of firewall configuration systems and tools. If you're using Ubuntu's *ufw*, you can do this:
|
||||
|
||||
sudo ufw allow 9993/udp
|
||||
|
||||
|
|
|
@ -61,18 +61,23 @@
|
|||
// Stored in database as schemaVersion key in Config.
|
||||
// If not present, database is assumed to be empty and at the current schema version
|
||||
// and this key/value is added automatically.
|
||||
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION 1
|
||||
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "1"
|
||||
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION 2
|
||||
#define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "2"
|
||||
|
||||
// API version reported via JSON control plane
|
||||
#define ZT_NETCONF_CONTROLLER_API_VERSION 1
|
||||
|
||||
// Drop requests for a given peer and network ID that occur more frequently
|
||||
// than this (ms).
|
||||
// Min duration between requests for an address/nwid combo to prevent floods
|
||||
#define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
|
||||
|
||||
// Delay between backups in milliseconds
|
||||
#define ZT_NETCONF_BACKUP_PERIOD 120000
|
||||
#define ZT_NETCONF_BACKUP_PERIOD 300000
|
||||
|
||||
// Number of NodeHistory entries to maintain per node and network (can be changed)
|
||||
#define ZT_NETCONF_NODE_HISTORY_LENGTH 64
|
||||
|
||||
// Nodes are considered active if they've queried in less than this long
|
||||
#define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000)
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
|
@ -134,6 +139,9 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
|
|||
throw std::runtime_error("SqliteNetworkController cannot open database file");
|
||||
sqlite3_busy_timeout(_db,10000);
|
||||
|
||||
sqlite3_exec(_db,"PRAGMA synchronous = OFF",0,0,0);
|
||||
sqlite3_exec(_db,"PRAGMA journal_mode = MEMORY",0,0,0);
|
||||
|
||||
sqlite3_stmt *s = (sqlite3_stmt *)0;
|
||||
if ((sqlite3_prepare_v2(_db,"SELECT v FROM Config WHERE k = 'schemaVersion';",-1,&s,(const char **)0) == SQLITE_OK)&&(s)) {
|
||||
int schemaVersion = -1234;
|
||||
|
@ -146,8 +154,34 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
|
|||
if (schemaVersion == -1234) {
|
||||
sqlite3_close(_db);
|
||||
throw std::runtime_error("SqliteNetworkController schemaVersion not found in Config table (init failure?)");
|
||||
} else if (schemaVersion == 1) {
|
||||
// Create NodeHistory table to upgrade from version 1 to version 2
|
||||
if (sqlite3_exec(_db,
|
||||
"CREATE TABLE NodeHistory (\n"
|
||||
" nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"
|
||||
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"
|
||||
" networkVisitCounter INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" requestTime INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" clientMajorVersion INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" clientMinorVersion INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" clientRevision INTEGER NOT NULL DEFAULT(0),\n"
|
||||
" networkRequestMetaData VARCHAR(1024),\n"
|
||||
" fromAddress VARCHAR(128)\n"
|
||||
");\n"
|
||||
"\n"
|
||||
"CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);\n"
|
||||
"CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);\n"
|
||||
"CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);\n"
|
||||
"\n"
|
||||
"UPDATE \"Config\" SET \"v\" = 2 WHERE \"k\" = 'schemaVersion';\n"
|
||||
,0,0,0) != SQLITE_OK) {
|
||||
char err[1024];
|
||||
Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot upgrade the database to version 2: %s",sqlite3_errmsg(_db));
|
||||
sqlite3_close(_db);
|
||||
throw std::runtime_error(err);
|
||||
}
|
||||
} else if (schemaVersion != ZT_NETCONF_SQLITE_SCHEMA_VERSION) {
|
||||
// Note -- this will eventually run auto-upgrades so this isn't how it'll work going forward
|
||||
sqlite3_close(_db);
|
||||
throw std::runtime_error("SqliteNetworkController database schema version mismatch");
|
||||
}
|
||||
|
@ -177,6 +211,13 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
|
|||
||(sqlite3_prepare_v2(_db,"SELECT identity FROM Node WHERE id = ?",-1,&_sGetNodeIdentity,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO Node (id,identity) VALUES (?,?)",-1,&_sCreateOrReplaceNode,(const char **)0) != SQLITE_OK)
|
||||
|
||||
/* NodeHistory */
|
||||
||(sqlite3_prepare_v2(_db,"SELECT IFNULL(MAX(networkVisitCounter),0) FROM NodeHistory WHERE networkId = ? AND nodeId = ?",-1,&_sGetMaxNodeHistoryNetworkVisitCounter,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"INSERT INTO NodeHistory (nodeId,networkId,networkVisitCounter,networkRequestAuthorized,requestTime,clientMajorVersion,clientMinorVersion,clientRevision,networkRequestMetaData,fromAddress) VALUES (?,?,?,?,?,?,?,?,?,?)",-1,&_sAddNodeHistoryEntry,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"DELETE FROM NodeHistory WHERE networkId = ? AND nodeId = ? AND networkVisitCounter <= ?",-1,&_sDeleteOldNodeHistoryEntries,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"SELECT nodeId,MAX(requestTime),MAX((((clientMajorVersion & 65535) << 32) | ((clientMinorVersion & 65535) << 16) | (clientRevision & 65535))) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"SELECT networkVisitCounter,networkRequestAuthorized,requestTime,clientMajorVersion,clientMinorVersion,clientRevision,networkRequestMetaData,fromAddress FROM NodeHistory WHERE networkId = ? AND nodeId = ? ORDER BY requestTime DESC",-1,&_sGetNodeHistory,(const char **)0) != SQLITE_OK)
|
||||
|
||||
/* Rule */
|
||||
||(sqlite3_prepare_v2(_db,"SELECT etherType FROM Rule WHERE networkId = ? AND \"action\" = 'accept'",-1,&_sGetEtherTypesFromRuleTable,(const char **)0) != SQLITE_OK)
|
||||
||(sqlite3_prepare_v2(_db,"INSERT INTO Rule (networkId,ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcP,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,flags,invFlags,\"action\") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",-1,&_sCreateRule,(const char **)0) != SQLITE_OK)
|
||||
|
@ -224,9 +265,9 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
|
|||
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO \"Config\" (\"k\",\"v\") VALUES (?,?)",-1,&_sSetConfig,(const char **)0) != SQLITE_OK)
|
||||
|
||||
) {
|
||||
//printf("%s\n",sqlite3_errmsg(_db));
|
||||
std::string err(std::string("SqliteNetworkController unable to initialize one or more prepared statements: ") + sqlite3_errmsg(_db));
|
||||
sqlite3_close(_db);
|
||||
throw std::runtime_error("SqliteNetworkController unable to initialize one or more prepared statements");
|
||||
throw std::runtime_error(err);
|
||||
}
|
||||
|
||||
/* Generate a 128-bit / 32-character "instance ID" if one isn't already
|
||||
|
@ -267,6 +308,11 @@ SqliteNetworkController::~SqliteNetworkController()
|
|||
sqlite3_finalize(_sCreateMember);
|
||||
sqlite3_finalize(_sGetNodeIdentity);
|
||||
sqlite3_finalize(_sCreateOrReplaceNode);
|
||||
sqlite3_finalize(_sGetMaxNodeHistoryNetworkVisitCounter);
|
||||
sqlite3_finalize(_sAddNodeHistoryEntry);
|
||||
sqlite3_finalize(_sDeleteOldNodeHistoryEntries);
|
||||
sqlite3_finalize(_sGetActiveNodesOnNetwork);
|
||||
sqlite3_finalize(_sGetNodeHistory);
|
||||
sqlite3_finalize(_sGetEtherTypesFromRuleTable);
|
||||
sqlite3_finalize(_sGetActiveBridges);
|
||||
sqlite3_finalize(_sGetIpAssignmentsForNode);
|
||||
|
@ -555,9 +601,18 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpPOST(
|
|||
}
|
||||
|
||||
test->timestamp = OSUtils::now();
|
||||
_circuitTests[test->testId] = test;
|
||||
|
||||
_CircuitTestEntry &te = _circuitTests[test->testId];
|
||||
te.test = test;
|
||||
te.jsonResults = "";
|
||||
|
||||
_node->circuitTestBegin(test,&(SqliteNetworkController::_circuitTestCallback));
|
||||
|
||||
char json[1024];
|
||||
Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
|
||||
responseBody = json;
|
||||
responseContentType = "application/json";
|
||||
|
||||
return 200;
|
||||
} // else 404
|
||||
|
||||
|
@ -1003,8 +1058,28 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpDELETE(
|
|||
void SqliteNetworkController::threadMain()
|
||||
throw()
|
||||
{
|
||||
uint64_t lastBackupTime = 0;
|
||||
uint64_t lastBackupTime = OSUtils::now();
|
||||
uint64_t lastCleanupTime = OSUtils::now();
|
||||
|
||||
while (_backupThreadRun) {
|
||||
if ((OSUtils::now() - lastCleanupTime) >= 5000) {
|
||||
const uint64_t now = OSUtils::now();
|
||||
lastCleanupTime = now;
|
||||
|
||||
Mutex::Lock _l(_lock);
|
||||
|
||||
// Clean out really old circuit tests to prevent memory build-up
|
||||
for(std::map< uint64_t,_CircuitTestEntry >::iterator ct(_circuitTests.begin());ct!=_circuitTests.end();) {
|
||||
if (!ct->second.test) {
|
||||
_circuitTests.erase(ct++);
|
||||
} else if ((now - ct->second.test->timestamp) >= ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT) {
|
||||
_node->circuitTestEnd(ct->second.test);
|
||||
::free((void *)ct->second.test);
|
||||
_circuitTests.erase(ct++);
|
||||
} else ++ct;
|
||||
}
|
||||
}
|
||||
|
||||
if ((OSUtils::now() - lastBackupTime) >= ZT_NETCONF_BACKUP_PERIOD) {
|
||||
lastBackupTime = OSUtils::now();
|
||||
|
||||
|
@ -1049,6 +1124,7 @@ void SqliteNetworkController::threadMain()
|
|||
OSUtils::rm(backupPath2);
|
||||
::rename(backupPath,backupPath2);
|
||||
}
|
||||
|
||||
Thread::sleep(250);
|
||||
}
|
||||
}
|
||||
|
@ -1171,44 +1247,36 @@ unsigned int SqliteNetworkController::_doCPGet(
|
|||
(unsigned int)sqlite3_column_int(_sGetIpAssignmentsForNode2,1)
|
||||
);
|
||||
responseBody.append(firstIp ? "\"" : ",\"");
|
||||
firstIp = false;
|
||||
responseBody.append(_jsonEscape(ip.toString()));
|
||||
responseBody.push_back('"');
|
||||
firstIp = false;
|
||||
}
|
||||
|
||||
responseBody.append("],\n\t\"recentLog\": [");
|
||||
|
||||
{
|
||||
std::map< std::pair<Address,uint64_t>,_LLEntry >::const_iterator lli(_lastLog.find(std::pair<Address,uint64_t>(Address(address),nwid)));
|
||||
if (lli != _lastLog.end()) {
|
||||
const _LLEntry &lastLogEntry = lli->second;
|
||||
uint64_t eptr = lastLogEntry.totalRequests;
|
||||
for(int k=0;k<ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;++k) {
|
||||
if (!eptr--)
|
||||
break;
|
||||
const unsigned long ptr = (unsigned long)eptr % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
|
||||
|
||||
char tsbuf[64];
|
||||
Utils::snprintf(tsbuf,sizeof(tsbuf),"%llu",(unsigned long long)lastLogEntry.l[ptr].ts);
|
||||
|
||||
responseBody.append((k == 0) ? "{" : ",{");
|
||||
sqlite3_reset(_sGetNodeHistory);
|
||||
sqlite3_bind_text(_sGetNodeHistory,1,nwids,16,SQLITE_STATIC);
|
||||
sqlite3_bind_text(_sGetNodeHistory,2,addrs,10,SQLITE_STATIC);
|
||||
bool firstHistory = true;
|
||||
while (sqlite3_step(_sGetNodeHistory) == SQLITE_ROW) {
|
||||
responseBody.append(firstHistory ? "{" : ",{");
|
||||
responseBody.append("\"ts\":");
|
||||
responseBody.append(tsbuf);
|
||||
responseBody.append(lastLogEntry.l[ptr].authorized ? ",\"authorized\":false,\"version\":" : ",\"authorized\":true,\"version\":");
|
||||
if (lastLogEntry.l[ptr].version[0]) {
|
||||
responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,2));
|
||||
responseBody.append((sqlite3_column_int(_sGetNodeHistory,1) == 0) ? ",\"authorized\":false,\"clientMajorVersion\":" : ",\"authorized\":true,\"clientMajorVersion\":");
|
||||
responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,3));
|
||||
responseBody.append(",\"clientMinorVersion\":");
|
||||
responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,4));
|
||||
responseBody.append(",\"clientRevision\":");
|
||||
responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,5));
|
||||
responseBody.append(",\"fromAddr\":");
|
||||
const char *fa = (const char *)sqlite3_column_text(_sGetNodeHistory,7);
|
||||
if (fa) {
|
||||
responseBody.push_back('"');
|
||||
responseBody.append(_jsonEscape(lastLogEntry.l[ptr].version));
|
||||
responseBody.append("\",\"fromAddr\":");
|
||||
} else responseBody.append("null,\"fromAddr\":");
|
||||
if (lastLogEntry.l[ptr].fromAddr) {
|
||||
responseBody.push_back('"');
|
||||
responseBody.append(_jsonEscape(lastLogEntry.l[ptr].fromAddr.toString()));
|
||||
responseBody.append(_jsonEscape(fa));
|
||||
responseBody.append("\"}");
|
||||
} else responseBody.append("null}");
|
||||
firstHistory = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responseBody.append("]\n}\n");
|
||||
|
||||
responseContentType = "application/json";
|
||||
|
@ -1220,7 +1288,7 @@ unsigned int SqliteNetworkController::_doCPGet(
|
|||
|
||||
sqlite3_reset(_sListNetworkMembers);
|
||||
sqlite3_bind_text(_sListNetworkMembers,1,nwids,16,SQLITE_STATIC);
|
||||
responseBody.append("{");
|
||||
responseBody.push_back('{');
|
||||
bool firstMember = true;
|
||||
while (sqlite3_step(_sListNetworkMembers) == SQLITE_ROW) {
|
||||
responseBody.append(firstMember ? "\"" : ",\"");
|
||||
|
@ -1235,10 +1303,51 @@ unsigned int SqliteNetworkController::_doCPGet(
|
|||
|
||||
}
|
||||
|
||||
} else if ((path[2] == "active")&&(path.size() == 3)) {
|
||||
|
||||
sqlite3_reset(_sGetActiveNodesOnNetwork);
|
||||
sqlite3_bind_text(_sGetActiveNodesOnNetwork,1,nwids,16,SQLITE_STATIC);
|
||||
sqlite3_bind_int64(_sGetActiveNodesOnNetwork,2,(int64_t)(OSUtils::now() - ZT_NETCONF_NODE_ACTIVE_THRESHOLD));
|
||||
|
||||
responseBody.push_back('{');
|
||||
bool firstMember = true;
|
||||
while (sqlite3_step(_sGetActiveNodesOnNetwork) == SQLITE_ROW) {
|
||||
const char *nid = (const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,0);
|
||||
if (nid) {
|
||||
responseBody.append(firstMember ? "\"" : ",\"");
|
||||
responseBody.append(nid);
|
||||
responseBody.append("\":{\"lt\":");
|
||||
responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,1));
|
||||
if ((uint64_t)sqlite3_column_int64(_sGetActiveNodesOnNetwork,2) >= 0x0000000100010000ULL)
|
||||
responseBody.append(",\"cts\":true");
|
||||
else responseBody.append(",\"cts\":false");
|
||||
responseBody.push_back('}');
|
||||
firstMember = false;
|
||||
}
|
||||
}
|
||||
responseBody.push_back('}');
|
||||
|
||||
responseContentType = "application/json";
|
||||
return 200;
|
||||
|
||||
} else if ((path[2] == "test")&&(path.size() >= 4)) {
|
||||
|
||||
std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
|
||||
if ((cte != _circuitTests.end())&&(cte->second.test)) {
|
||||
|
||||
responseBody = "[";
|
||||
responseBody.append(cte->second.jsonResults);
|
||||
responseBody.push_back(']');
|
||||
responseContentType = "application/json";
|
||||
|
||||
return 200;
|
||||
|
||||
} // else 404
|
||||
|
||||
} // else 404
|
||||
|
||||
} else {
|
||||
// get network info
|
||||
|
||||
sqlite3_reset(_sGetNetworkById);
|
||||
sqlite3_bind_text(_sGetNetworkById,1,nwids,16,SQLITE_STATIC);
|
||||
if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
|
||||
|
@ -1541,12 +1650,15 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
|
|||
return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
|
||||
// Check rate limit circuit breaker to prevent flooding
|
||||
const uint64_t now = OSUtils::now();
|
||||
_LLEntry &lastLogEntry = _lastLog[std::pair<Address,uint64_t>(identity.address(),nwid)];
|
||||
if ((now - lastLogEntry.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
|
||||
|
||||
// Check rate limit circuit breaker to prevent flooding
|
||||
{
|
||||
uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
|
||||
if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
|
||||
return NetworkController::NETCONF_QUERY_IGNORE;
|
||||
lastLogEntry.lastRequestTime = now;
|
||||
lrt = now;
|
||||
}
|
||||
|
||||
NetworkRecord network;
|
||||
memset(&network,0,sizeof(network));
|
||||
|
@ -1632,18 +1744,47 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
|
|||
sqlite3_step(_sIncrementMemberRevisionCounter);
|
||||
}
|
||||
|
||||
// Add log entry to in-memory circular log
|
||||
// Update NodeHistory with new log entry and delete expired entries
|
||||
|
||||
{
|
||||
const unsigned long ptr = (unsigned long)lastLogEntry.totalRequests % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
|
||||
lastLogEntry.l[ptr].ts = now;
|
||||
lastLogEntry.l[ptr].fromAddr = fromAddr;
|
||||
if ((clientMajorVersion > 0)||(clientMinorVersion > 0)||(clientRevision > 0))
|
||||
Utils::snprintf(lastLogEntry.l[ptr].version,sizeof(lastLogEntry.l[ptr].version),"%u.%u.%u",clientMajorVersion,clientMinorVersion,clientRevision);
|
||||
else lastLogEntry.l[ptr].version[0] = (char)0;
|
||||
lastLogEntry.l[ptr].authorized = member.authorized;
|
||||
++lastLogEntry.totalRequests;
|
||||
// TODO: push or save these somewhere
|
||||
int64_t nextVC = 1;
|
||||
sqlite3_reset(_sGetMaxNodeHistoryNetworkVisitCounter);
|
||||
sqlite3_bind_text(_sGetMaxNodeHistoryNetworkVisitCounter,1,network.id,16,SQLITE_STATIC);
|
||||
sqlite3_bind_text(_sGetMaxNodeHistoryNetworkVisitCounter,2,member.nodeId,10,SQLITE_STATIC);
|
||||
if (sqlite3_step(_sGetMaxNodeHistoryNetworkVisitCounter) == SQLITE_ROW) {
|
||||
nextVC = (int64_t)sqlite3_column_int64(_sGetMaxNodeHistoryNetworkVisitCounter,0) + 1;
|
||||
}
|
||||
|
||||
std::string mdstr(metaData.toString());
|
||||
if (mdstr.length() > 1024)
|
||||
mdstr = mdstr.substr(0,1024);
|
||||
std::string fastr;
|
||||
if (fromAddr)
|
||||
fastr = fromAddr.toString();
|
||||
|
||||
sqlite3_reset(_sAddNodeHistoryEntry);
|
||||
sqlite3_bind_text(_sAddNodeHistoryEntry,1,member.nodeId,10,SQLITE_STATIC);
|
||||
sqlite3_bind_text(_sAddNodeHistoryEntry,2,network.id,16,SQLITE_STATIC);
|
||||
sqlite3_bind_int64(_sAddNodeHistoryEntry,3,nextVC);
|
||||
sqlite3_bind_int(_sAddNodeHistoryEntry,4,(member.authorized ? 1 : 0));
|
||||
sqlite3_bind_int64(_sAddNodeHistoryEntry,5,(long long)now);
|
||||
sqlite3_bind_int(_sAddNodeHistoryEntry,6,(int)clientMajorVersion);
|
||||
sqlite3_bind_int(_sAddNodeHistoryEntry,7,(int)clientMinorVersion);
|
||||
sqlite3_bind_int(_sAddNodeHistoryEntry,8,(int)clientRevision);
|
||||
sqlite3_bind_text(_sAddNodeHistoryEntry,9,mdstr.c_str(),-1,SQLITE_STATIC);
|
||||
if (fastr.length() > 0)
|
||||
sqlite3_bind_text(_sAddNodeHistoryEntry,10,fastr.c_str(),-1,SQLITE_STATIC);
|
||||
else sqlite3_bind_null(_sAddNodeHistoryEntry,10);
|
||||
sqlite3_step(_sAddNodeHistoryEntry);
|
||||
|
||||
nextVC -= ZT_NETCONF_NODE_HISTORY_LENGTH;
|
||||
if (nextVC >= 0) {
|
||||
sqlite3_reset(_sDeleteOldNodeHistoryEntries);
|
||||
sqlite3_bind_text(_sDeleteOldNodeHistoryEntries,1,network.id,16,SQLITE_STATIC);
|
||||
sqlite3_bind_text(_sDeleteOldNodeHistoryEntries,2,member.nodeId,10,SQLITE_STATIC);
|
||||
sqlite3_bind_int64(_sDeleteOldNodeHistoryEntries,3,nextVC);
|
||||
sqlite3_step(_sDeleteOldNodeHistoryEntries);
|
||||
}
|
||||
}
|
||||
|
||||
// Check member authorization
|
||||
|
@ -1910,7 +2051,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
|
|||
}
|
||||
|
||||
if (network.isPrivate) {
|
||||
CertificateOfMembership com(now,ZT_NETWORK_AUTOCONF_DELAY + (ZT_NETWORK_AUTOCONF_DELAY / 2),nwid,identity.address());
|
||||
CertificateOfMembership com(now,ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA,nwid,identity.address());
|
||||
if (com.sign(signingId)) // basically can't fail unless our identity is invalid
|
||||
netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
|
||||
else {
|
||||
|
@ -1930,31 +2071,25 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
|
|||
|
||||
void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
|
||||
{
|
||||
static Mutex circuitTestWriteLock;
|
||||
char tmp[65535];
|
||||
SqliteNetworkController *const self = reinterpret_cast<SqliteNetworkController *>(test->ptr);
|
||||
|
||||
const uint64_t now = OSUtils::now();
|
||||
|
||||
SqliteNetworkController *const c = reinterpret_cast<SqliteNetworkController *>(test->ptr);
|
||||
char tmp[128];
|
||||
|
||||
std::string reportSavePath(c->_circuitTestPath);
|
||||
OSUtils::mkdir(reportSavePath);
|
||||
Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx",test->credentialNetworkId);
|
||||
reportSavePath.append(tmp);
|
||||
OSUtils::mkdir(reportSavePath);
|
||||
Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.16llx",test->timestamp,test->testId);
|
||||
reportSavePath.append(tmp);
|
||||
OSUtils::mkdir(reportSavePath);
|
||||
Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.10llx_%.10llx",now,report->upstream,report->current);
|
||||
reportSavePath.append(tmp);
|
||||
|
||||
{
|
||||
Mutex::Lock _l(circuitTestWriteLock);
|
||||
FILE *f = fopen(reportSavePath.c_str(),"a");
|
||||
if (!f)
|
||||
if (!test)
|
||||
return;
|
||||
fseek(f,0,SEEK_END);
|
||||
fprintf(f,"%s{\n"
|
||||
if (!report)
|
||||
return;
|
||||
|
||||
Mutex::Lock _l(self->_lock);
|
||||
std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
|
||||
|
||||
if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
|
||||
self->_node->circuitTestEnd(test);
|
||||
::free((void *)test);
|
||||
return;
|
||||
}
|
||||
|
||||
Utils::snprintf(tmp,sizeof(tmp),
|
||||
"%s{\n"
|
||||
"\t\"timestamp\": %llu,"ZT_EOL_S
|
||||
"\t\"testId\": \"%.16llx\","ZT_EOL_S
|
||||
"\t\"upstream\": \"%.10llx\","ZT_EOL_S
|
||||
|
@ -1975,12 +2110,12 @@ void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest
|
|||
"\t\"receivedOnLocalAddress\": \"%s\","ZT_EOL_S
|
||||
"\t\"receivedFromRemoteAddress\": \"%s\""ZT_EOL_S
|
||||
"}",
|
||||
((ftell(f) > 0) ? ",\n" : ""),
|
||||
((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
|
||||
(unsigned long long)report->timestamp,
|
||||
(unsigned long long)test->testId,
|
||||
(unsigned long long)report->upstream,
|
||||
(unsigned long long)report->current,
|
||||
(unsigned long long)now,
|
||||
(unsigned long long)OSUtils::now(),
|
||||
(unsigned long long)report->remoteTimestamp,
|
||||
(unsigned long long)report->sourcePacketId,
|
||||
(unsigned long long)report->flags,
|
||||
|
@ -1995,8 +2130,8 @@ void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest
|
|||
(int)report->architecture,
|
||||
reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
|
||||
reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
cte->second.jsonResults.append(tmp);
|
||||
}
|
||||
|
||||
} // namespace ZeroTier
|
||||
|
|
|
@ -44,8 +44,8 @@
|
|||
// Number of in-memory last log entries to maintain per user
|
||||
#define ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE 32
|
||||
|
||||
// How long do circuit tests "live"? This is just to prevent buildup in memory.
|
||||
#define ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT 300000
|
||||
// How long do circuit tests last before they're forgotten?
|
||||
#define ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT 60000
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
|
@ -123,37 +123,16 @@ private:
|
|||
std::string _circuitTestPath;
|
||||
std::string _instanceId;
|
||||
|
||||
// A circular buffer last log
|
||||
struct _LLEntry
|
||||
{
|
||||
_LLEntry()
|
||||
{
|
||||
for(long i=0;i<ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;++i)
|
||||
this->l[i].ts = 0;
|
||||
this->lastRequestTime = 0;
|
||||
this->totalRequests = 0;
|
||||
}
|
||||
|
||||
// Circular buffer of last log entries
|
||||
struct {
|
||||
uint64_t ts; // timestamp or 0 if circular buffer entry unused
|
||||
char version[64];
|
||||
InetAddress fromAddr;
|
||||
bool authorized;
|
||||
} l[ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE];
|
||||
|
||||
// Time of last request whether successful or not
|
||||
uint64_t lastRequestTime;
|
||||
|
||||
// Total requests by this address / network ID pair (also serves mod IN_MEMORY_LOG_SIZE as circular buffer ptr)
|
||||
uint64_t totalRequests;
|
||||
};
|
||||
|
||||
// Last log entries by address and network ID pair
|
||||
std::map< std::pair<Address,uint64_t>,_LLEntry > _lastLog;
|
||||
|
||||
// Circuit tests outstanding
|
||||
std::map< uint64_t,ZT_CircuitTest * > _circuitTests;
|
||||
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;
|
||||
|
||||
|
@ -162,6 +141,11 @@ private:
|
|||
sqlite3_stmt *_sCreateMember;
|
||||
sqlite3_stmt *_sGetNodeIdentity;
|
||||
sqlite3_stmt *_sCreateOrReplaceNode;
|
||||
sqlite3_stmt *_sGetMaxNodeHistoryNetworkVisitCounter;
|
||||
sqlite3_stmt *_sAddNodeHistoryEntry;
|
||||
sqlite3_stmt *_sDeleteOldNodeHistoryEntries;
|
||||
sqlite3_stmt *_sGetActiveNodesOnNetwork;
|
||||
sqlite3_stmt *_sGetNodeHistory;
|
||||
sqlite3_stmt *_sGetEtherTypesFromRuleTable;
|
||||
sqlite3_stmt *_sGetActiveBridges;
|
||||
sqlite3_stmt *_sGetIpAssignmentsForNode;
|
||||
|
|
|
@ -34,6 +34,23 @@ CREATE TABLE Node (
|
|||
identity varchar(4096) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE NodeHistory (
|
||||
nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,
|
||||
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
|
||||
networkVisitCounter INTEGER NOT NULL DEFAULT(0),
|
||||
networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),
|
||||
requestTime INTEGER NOT NULL DEFAULT(0),
|
||||
clientMajorVersion INTEGER NOT NULL DEFAULT(0),
|
||||
clientMinorVersion INTEGER NOT NULL DEFAULT(0),
|
||||
clientRevision INTEGER NOT NULL DEFAULT(0),
|
||||
networkRequestMetaData VARCHAR(1024),
|
||||
fromAddress VARCHAR(128)
|
||||
);
|
||||
|
||||
CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);
|
||||
CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);
|
||||
CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);
|
||||
|
||||
CREATE TABLE Gateway (
|
||||
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
|
||||
ip blob(16) NOT NULL,
|
||||
|
|
|
@ -35,6 +35,23 @@
|
|||
" identity varchar(4096) NOT NULL\n"\
|
||||
");\n"\
|
||||
"\n"\
|
||||
"CREATE TABLE NodeHistory (\n"\
|
||||
" nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"\
|
||||
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
|
||||
" networkVisitCounter INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" requestTime INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" clientMajorVersion INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" clientMinorVersion INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" clientRevision INTEGER NOT NULL DEFAULT(0),\n"\
|
||||
" networkRequestMetaData VARCHAR(1024),\n"\
|
||||
" fromAddress VARCHAR(128)\n"\
|
||||
");\n"\
|
||||
"\n"\
|
||||
"CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);\n"\
|
||||
"CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);\n"\
|
||||
"CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);\n"\
|
||||
"\n"\
|
||||
"CREATE TABLE Gateway (\n"\
|
||||
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
|
||||
" ip blob(16) NOT NULL,\n"\
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
API Examples
|
||||
======
|
||||
|
||||
This folder contains examples that can be posted with curl or another http query utility to a local instance.
|
||||
|
||||
To test querying with curl:
|
||||
|
||||
curl -H 'X-ZT1-Auth:AUTHTOKEN' http://127.0.0.1:9993/status
|
||||
|
||||
To create a public network on a local controller (service must be built with "make ZT\_ENABLE\_NETWORK\_CONTROLLER=1"):
|
||||
|
||||
curl -H 'X-ZT1-Auth:AUTHTOKEN' -X POST -d @public.json http://127.0.0.1:9993/controller/network/################
|
||||
|
||||
Replace AUTHTOKEN with the contents of this instance's authtoken.secret file and ################ with a valid network ID. Its first 10 hex digits must be the ZeroTier address of the controller itself, while the last 6 hex digits can be anything. Also be sure to change the port if you have this instance listening somewhere other than 9993.
|
||||
|
||||
After POSTing you can double check the network config with:
|
||||
|
||||
curl -H 'X-ZT1-Auth:AUTHTOKEN' http://127.0.0.1:9993/controller/network/################
|
||||
|
||||
Once this network is created (and if your controller is online, etc.) you can then join this network from any device anywhere in the world and it will receive a valid network configuration.
|
||||
|
||||
---
|
||||
|
||||
**public.json**: A valid configuration for a public network that allows IPv4 and IPv6 traffic.
|
||||
|
||||
**circuit-test-pingpong.json**: An example circuit test that can be posted to /controller/network/################/test to order a test -- you will have to edit this to insert the hops you want since the two hard coded device IDs are from our own test instances.
|
|
@ -1,13 +0,0 @@
|
|||
{
|
||||
"hops": [
|
||||
[ "4cbc810d4c" ],
|
||||
[ "868cd1664f" ],
|
||||
[ "4cbc810d4c" ],
|
||||
[ "868cd1664f" ],
|
||||
[ "4cbc810d4c" ],
|
||||
[ "868cd1664f" ],
|
||||
[ "4cbc810d4c" ],
|
||||
[ "868cd1664f" ]
|
||||
],
|
||||
"reportAtEveryHop": true
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
{
|
||||
"name": "public_test_network",
|
||||
"private": false,
|
||||
"enableBroadcast": true,
|
||||
"allowPassiveBridging": false,
|
||||
"v4AssignMode": "zt",
|
||||
"v6AssignMode": "rfc4193",
|
||||
"multicastLimit": 32,
|
||||
"relays": [],
|
||||
"gateways": [],
|
||||
"ipLocalRoutes": ["10.66.0.0/16"],
|
||||
"ipAssignmentPools": [{"ipRangeStart":"10.66.0.1","ipRangeEnd":"10.66.255.254"}],
|
||||
"rules": [
|
||||
{
|
||||
"ruleNo": 10,
|
||||
"etherType": 2048,
|
||||
"action": "accept"
|
||||
},{
|
||||
"ruleNo": 20,
|
||||
"etherType": 2054,
|
||||
"action": "accept"
|
||||
},{
|
||||
"ruleNo": 30,
|
||||
"etherType": 34525,
|
||||
"action": "accept"
|
||||
}]
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
FROM centos:7
|
||||
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
RUN yum -y update && yum install -y sqlite net-tools && yum clean all
|
||||
|
||||
EXPOSE 9993/udp
|
||||
|
||||
RUN mkdir -p /var/lib/zerotier-one
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
RUN ln -sf /var/lib/zerotier-one/zerotier-one /usr/local/bin/zerotier-cli
|
||||
RUN ln -sf /var/lib/zerotier-one/zerotier-one /usr/local/bin/zerotier-idtool
|
||||
|
||||
ADD zerotier-one /var/lib/zerotier-one/
|
||||
|
||||
ADD main.sh /
|
||||
RUN chmod a+x /main.sh
|
||||
|
||||
CMD ["./main.sh"]
|
|
@ -1,8 +0,0 @@
|
|||
Simple Dockerfile Example
|
||||
======
|
||||
|
||||
This is a simple Docker example using ZeroTier One in normal tun/tap mode. It uses a Dockerfile to build an image containing ZeroTier One and a main.sh that launches it with an identity supplied via the Docker environment via the ZEROTIER\_IDENTITY\_SECRET and ZEROTIER\_NETWORK variables. The Dockerfile assumes that the zerotier-one binary is in the build folder.
|
||||
|
||||
This is not a very secure way to load an identity secret, but it's useful for testing since it allows you to repeatedly launch Docker containers with the same identity. For production we'd recommend using something like Hashicorp Vault, or modifying main.sh to leave identities unspecified and allow the container to generate a new identity at runtime. Then you could script approval of containers using the controller API, approving them as they launch, etc. (We are working on better ways of doing mass provisioning.)
|
||||
|
||||
To use in normal tun/tap mode with Docker, containers must be run with the options "--device=/dev/net/tun --privileged". The main.sh script supplied here will complain and exit if these options are not present (no /dev/net/tun device).
|
|
@ -1,25 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
|
||||
|
||||
if [ ! -c "/dev/net/tun" ]; then
|
||||
echo 'FATAL: must be docker run with: --device=/dev/net/tun --cap-add=NET_ADMIN'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$ZEROTIER_IDENTITY_SECRET" ]; then
|
||||
echo 'FATAL: ZEROTIER_IDENTITY_SECRET not set -- aborting!'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$ZEROTIER_NETWORK" ]; then
|
||||
echo 'Warning: ZEROTIER_NETWORK not set, you will need to docker exec zerotier-cli to join a network.'
|
||||
else
|
||||
# The existence of a .conf will cause the service to "remember" this network
|
||||
touch /var/lib/zerotier-one/networks.d/$ZEROTIER_NETWORK.conf
|
||||
fi
|
||||
|
||||
rm -f /var/lib/zerotier-one/identity.*
|
||||
echo "$ZEROTIER_IDENTITY_SECRET" >/var/lib/zerotier-one/identity.secret
|
||||
|
||||
/var/lib/zerotier-one/zerotier-one
|
|
@ -1,11 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
if [ -z "$1" -o -z "$2" ]; then
|
||||
echo 'Usage: maketestenv.sh <output file e.g. test-01.env> <network ID>'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
newid=`../../zerotier-idtool generate`
|
||||
|
||||
echo "ZEROTIER_IDENTITY_SECRET=$newid" >$1
|
||||
echo "ZEROTIER_NETWORK=$2" >>$1
|
|
@ -400,6 +400,8 @@ enum http_host_state
|
|||
, s_http_host
|
||||
, s_http_host_v6
|
||||
, s_http_host_v6_end
|
||||
, s_http_host_v6_zone_start
|
||||
, s_http_host_v6_zone
|
||||
, s_http_host_port_start
|
||||
, s_http_host_port
|
||||
};
|
||||
|
@ -433,6 +435,12 @@ enum http_host_state
|
|||
(IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Verify that a char is a valid visible (printable) US-ASCII
|
||||
* character or %x80-FF
|
||||
**/
|
||||
#define IS_HEADER_CHAR(ch) \
|
||||
(ch == CR || ch == LF || ch == 9 || (ch > 31 && ch != 127))
|
||||
|
||||
#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
|
||||
|
||||
|
@ -637,6 +645,7 @@ size_t http_parser_execute (http_parser *parser,
|
|||
const char *body_mark = 0;
|
||||
const char *status_mark = 0;
|
||||
enum state p_state = (enum state) parser->state;
|
||||
const unsigned int lenient = parser->lenient_http_headers;
|
||||
|
||||
/* We're in an error state. Don't bother doing anything. */
|
||||
if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
|
||||
|
@ -957,21 +966,23 @@ reexecute:
|
|||
parser->method = (enum http_method) 0;
|
||||
parser->index = 1;
|
||||
switch (ch) {
|
||||
case 'A': parser->method = HTTP_ACL; break;
|
||||
case 'B': parser->method = HTTP_BIND; break;
|
||||
case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
|
||||
case 'D': parser->method = HTTP_DELETE; break;
|
||||
case 'G': parser->method = HTTP_GET; break;
|
||||
case 'H': parser->method = HTTP_HEAD; break;
|
||||
case 'L': parser->method = HTTP_LOCK; break;
|
||||
case 'L': parser->method = HTTP_LOCK; /* or LINK */ break;
|
||||
case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
|
||||
case 'N': parser->method = HTTP_NOTIFY; break;
|
||||
case 'O': parser->method = HTTP_OPTIONS; break;
|
||||
case 'P': parser->method = HTTP_POST;
|
||||
/* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
|
||||
break;
|
||||
case 'R': parser->method = HTTP_REPORT; break;
|
||||
case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break;
|
||||
case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break;
|
||||
case 'T': parser->method = HTTP_TRACE; break;
|
||||
case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
|
||||
case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;
|
||||
default:
|
||||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
|
@ -1027,7 +1038,15 @@ reexecute:
|
|||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
}
|
||||
} else if (parser->index == 1 && parser->method == HTTP_POST) {
|
||||
} else if (parser->method == HTTP_REPORT) {
|
||||
if (parser->index == 2 && ch == 'B') {
|
||||
parser->method = HTTP_REBIND;
|
||||
} else {
|
||||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
}
|
||||
} else if (parser->index == 1) {
|
||||
if (parser->method == HTTP_POST) {
|
||||
if (ch == 'R') {
|
||||
parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
|
||||
} else if (ch == 'U') {
|
||||
|
@ -1038,6 +1057,14 @@ reexecute:
|
|||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
}
|
||||
} else if (parser->method == HTTP_LOCK) {
|
||||
if (ch == 'I') {
|
||||
parser->method = HTTP_LINK;
|
||||
} else {
|
||||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
}
|
||||
}
|
||||
} else if (parser->index == 2) {
|
||||
if (parser->method == HTTP_PUT) {
|
||||
if (ch == 'R') {
|
||||
|
@ -1049,6 +1076,8 @@ reexecute:
|
|||
} else if (parser->method == HTTP_UNLOCK) {
|
||||
if (ch == 'S') {
|
||||
parser->method = HTTP_UNSUBSCRIBE;
|
||||
} else if(ch == 'B') {
|
||||
parser->method = HTTP_UNBIND;
|
||||
} else {
|
||||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
|
@ -1059,6 +1088,8 @@ reexecute:
|
|||
}
|
||||
} else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') {
|
||||
parser->method = HTTP_PROPPATCH;
|
||||
} else if (parser->index == 3 && parser->method == HTTP_UNLOCK && ch == 'I') {
|
||||
parser->method = HTTP_UNLINK;
|
||||
} else {
|
||||
SET_ERRNO(HPE_INVALID_METHOD);
|
||||
goto error;
|
||||
|
@ -1384,7 +1415,12 @@ reexecute:
|
|||
|| c != CONTENT_LENGTH[parser->index]) {
|
||||
parser->header_state = h_general;
|
||||
} else if (parser->index == sizeof(CONTENT_LENGTH)-2) {
|
||||
if (parser->flags & F_CONTENTLENGTH) {
|
||||
SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
|
||||
goto error;
|
||||
}
|
||||
parser->header_state = h_content_length;
|
||||
parser->flags |= F_CONTENTLENGTH;
|
||||
}
|
||||
break;
|
||||
|
||||
|
@ -1536,6 +1572,11 @@ reexecute:
|
|||
REEXECUTE();
|
||||
}
|
||||
|
||||
if (!lenient && !IS_HEADER_CHAR(ch)) {
|
||||
SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
|
||||
goto error;
|
||||
}
|
||||
|
||||
c = LOWER(ch);
|
||||
|
||||
switch (h_state) {
|
||||
|
@ -1703,7 +1744,10 @@ reexecute:
|
|||
|
||||
case s_header_almost_done:
|
||||
{
|
||||
STRICT_CHECK(ch != LF);
|
||||
if (UNLIKELY(ch != LF)) {
|
||||
SET_ERRNO(HPE_LF_EXPECTED);
|
||||
goto error;
|
||||
}
|
||||
|
||||
UPDATE_STATE(s_header_value_lws);
|
||||
break;
|
||||
|
@ -1782,9 +1826,17 @@ reexecute:
|
|||
|
||||
if (parser->flags & F_TRAILING) {
|
||||
/* End of a chunked request */
|
||||
UPDATE_STATE(NEW_MESSAGE());
|
||||
CALLBACK_NOTIFY(message_complete);
|
||||
break;
|
||||
UPDATE_STATE(s_message_done);
|
||||
CALLBACK_NOTIFY_NOADVANCE(chunk_complete);
|
||||
REEXECUTE();
|
||||
}
|
||||
|
||||
/* Cannot use chunked encoding and a content-length header together
|
||||
per the HTTP specification. */
|
||||
if ((parser->flags & F_CHUNKED) &&
|
||||
(parser->flags & F_CONTENTLENGTH)) {
|
||||
SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
|
||||
goto error;
|
||||
}
|
||||
|
||||
UPDATE_STATE(s_headers_done);
|
||||
|
@ -1828,12 +1880,16 @@ reexecute:
|
|||
|
||||
case s_headers_done:
|
||||
{
|
||||
int hasBody;
|
||||
STRICT_CHECK(ch != LF);
|
||||
|
||||
parser->nread = 0;
|
||||
|
||||
/* Exit, the rest of the connect is in a different protocol. */
|
||||
if (parser->upgrade) {
|
||||
hasBody = parser->flags & F_CHUNKED ||
|
||||
(parser->content_length > 0 && parser->content_length != ULLONG_MAX);
|
||||
if (parser->upgrade && (parser->method == HTTP_CONNECT ||
|
||||
(parser->flags & F_SKIPBODY) || !hasBody)) {
|
||||
/* Exit, the rest of the message is in a different protocol. */
|
||||
UPDATE_STATE(NEW_MESSAGE());
|
||||
CALLBACK_NOTIFY(message_complete);
|
||||
RETURN((p - data) + 1);
|
||||
|
@ -1854,8 +1910,7 @@ reexecute:
|
|||
/* Content-Length header given and non-zero */
|
||||
UPDATE_STATE(s_body_identity);
|
||||
} else {
|
||||
if (parser->type == HTTP_REQUEST ||
|
||||
!http_message_needs_eof(parser)) {
|
||||
if (!http_message_needs_eof(parser)) {
|
||||
/* Assume content-length 0 - read the next */
|
||||
UPDATE_STATE(NEW_MESSAGE());
|
||||
CALLBACK_NOTIFY(message_complete);
|
||||
|
@ -1915,6 +1970,10 @@ reexecute:
|
|||
case s_message_done:
|
||||
UPDATE_STATE(NEW_MESSAGE());
|
||||
CALLBACK_NOTIFY(message_complete);
|
||||
if (parser->upgrade) {
|
||||
/* Exit, the rest of the message is in a different protocol. */
|
||||
RETURN((p - data) + 1);
|
||||
}
|
||||
break;
|
||||
|
||||
case s_chunk_size_start:
|
||||
|
@ -1994,6 +2053,7 @@ reexecute:
|
|||
} else {
|
||||
UPDATE_STATE(s_chunk_data);
|
||||
}
|
||||
CALLBACK_NOTIFY(chunk_header);
|
||||
break;
|
||||
}
|
||||
|
||||
|
@ -2033,6 +2093,7 @@ reexecute:
|
|||
STRICT_CHECK(ch != LF);
|
||||
parser->nread = 0;
|
||||
UPDATE_STATE(s_chunk_size_start);
|
||||
CALLBACK_NOTIFY(chunk_complete);
|
||||
break;
|
||||
|
||||
default:
|
||||
|
@ -2144,13 +2205,13 @@ http_parser_settings_init(http_parser_settings *settings)
|
|||
|
||||
const char *
|
||||
http_errno_name(enum http_errno err) {
|
||||
assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
|
||||
assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
|
||||
return http_strerror_tab[err].name;
|
||||
}
|
||||
|
||||
const char *
|
||||
http_errno_description(enum http_errno err) {
|
||||
assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
|
||||
assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
|
||||
return http_strerror_tab[err].description;
|
||||
}
|
||||
|
||||
|
@ -2203,6 +2264,23 @@ http_parse_host_char(enum http_host_state s, const char ch) {
|
|||
return s_http_host_v6;
|
||||
}
|
||||
|
||||
if (s == s_http_host_v6 && ch == '%') {
|
||||
return s_http_host_v6_zone_start;
|
||||
}
|
||||
break;
|
||||
|
||||
case s_http_host_v6_zone:
|
||||
if (ch == ']') {
|
||||
return s_http_host_v6_end;
|
||||
}
|
||||
|
||||
/* FALLTHROUGH */
|
||||
case s_http_host_v6_zone_start:
|
||||
/* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
|
||||
if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
|
||||
ch == '~') {
|
||||
return s_http_host_v6_zone;
|
||||
}
|
||||
break;
|
||||
|
||||
case s_http_host_port:
|
||||
|
@ -2221,6 +2299,7 @@ http_parse_host_char(enum http_host_state s, const char ch) {
|
|||
|
||||
static int
|
||||
http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
|
||||
assert(u->field_set & (1 << UF_HOST));
|
||||
enum http_host_state s;
|
||||
|
||||
const char *p;
|
||||
|
@ -2252,6 +2331,11 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
|
|||
u->field_data[UF_HOST].len++;
|
||||
break;
|
||||
|
||||
case s_http_host_v6_zone_start:
|
||||
case s_http_host_v6_zone:
|
||||
u->field_data[UF_HOST].len++;
|
||||
break;
|
||||
|
||||
case s_http_host_port:
|
||||
if (s != s_http_host_port) {
|
||||
u->field_data[UF_PORT].off = p - buf;
|
||||
|
@ -2281,6 +2365,8 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
|
|||
case s_http_host_start:
|
||||
case s_http_host_v6_start:
|
||||
case s_http_host_v6:
|
||||
case s_http_host_v6_zone_start:
|
||||
case s_http_host_v6_zone:
|
||||
case s_http_host_port_start:
|
||||
case s_http_userinfo:
|
||||
case s_http_userinfo_start:
|
||||
|
@ -2292,6 +2378,11 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
|
|||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
http_parser_url_init(struct http_parser_url *u) {
|
||||
memset(u, 0, sizeof(*u));
|
||||
}
|
||||
|
||||
int
|
||||
http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
|
||||
struct http_parser_url *u)
|
||||
|
@ -2365,7 +2456,12 @@ http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
|
|||
|
||||
/* host must be present if there is a schema */
|
||||
/* parsing http:///toto will fail */
|
||||
if ((u->field_set & ((1 << UF_SCHEMA) | (1 << UF_HOST))) != 0) {
|
||||
if ((u->field_set & (1 << UF_SCHEMA)) &&
|
||||
(u->field_set & (1 << UF_HOST)) == 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (u->field_set & (1 << UF_HOST)) {
|
||||
if (http_parse_host(buf, u, found_at) != 0) {
|
||||
return 1;
|
||||
}
|
||||
|
|
|
@ -26,11 +26,12 @@ extern "C" {
|
|||
|
||||
/* Also update SONAME in the Makefile whenever you change these. */
|
||||
#define HTTP_PARSER_VERSION_MAJOR 2
|
||||
#define HTTP_PARSER_VERSION_MINOR 4
|
||||
#define HTTP_PARSER_VERSION_PATCH 2
|
||||
#define HTTP_PARSER_VERSION_MINOR 6
|
||||
#define HTTP_PARSER_VERSION_PATCH 1
|
||||
|
||||
#include <sys/types.h>
|
||||
#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600)
|
||||
#if defined(_WIN32) && !defined(__MINGW32__) && \
|
||||
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
|
||||
#include <BaseTsd.h>
|
||||
#include <stddef.h>
|
||||
typedef __int8 int8_t;
|
||||
|
@ -95,7 +96,7 @@ typedef int (*http_cb) (http_parser*);
|
|||
XX(5, CONNECT, CONNECT) \
|
||||
XX(6, OPTIONS, OPTIONS) \
|
||||
XX(7, TRACE, TRACE) \
|
||||
/* webdav */ \
|
||||
/* WebDAV */ \
|
||||
XX(8, COPY, COPY) \
|
||||
XX(9, LOCK, LOCK) \
|
||||
XX(10, MKCOL, MKCOL) \
|
||||
|
@ -104,21 +105,28 @@ typedef int (*http_cb) (http_parser*);
|
|||
XX(13, PROPPATCH, PROPPATCH) \
|
||||
XX(14, SEARCH, SEARCH) \
|
||||
XX(15, UNLOCK, UNLOCK) \
|
||||
XX(16, BIND, BIND) \
|
||||
XX(17, REBIND, REBIND) \
|
||||
XX(18, UNBIND, UNBIND) \
|
||||
XX(19, ACL, ACL) \
|
||||
/* subversion */ \
|
||||
XX(16, REPORT, REPORT) \
|
||||
XX(17, MKACTIVITY, MKACTIVITY) \
|
||||
XX(18, CHECKOUT, CHECKOUT) \
|
||||
XX(19, MERGE, MERGE) \
|
||||
XX(20, REPORT, REPORT) \
|
||||
XX(21, MKACTIVITY, MKACTIVITY) \
|
||||
XX(22, CHECKOUT, CHECKOUT) \
|
||||
XX(23, MERGE, MERGE) \
|
||||
/* upnp */ \
|
||||
XX(20, MSEARCH, M-SEARCH) \
|
||||
XX(21, NOTIFY, NOTIFY) \
|
||||
XX(22, SUBSCRIBE, SUBSCRIBE) \
|
||||
XX(23, UNSUBSCRIBE, UNSUBSCRIBE) \
|
||||
XX(24, MSEARCH, M-SEARCH) \
|
||||
XX(25, NOTIFY, NOTIFY) \
|
||||
XX(26, SUBSCRIBE, SUBSCRIBE) \
|
||||
XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
|
||||
/* RFC-5789 */ \
|
||||
XX(24, PATCH, PATCH) \
|
||||
XX(25, PURGE, PURGE) \
|
||||
XX(28, PATCH, PATCH) \
|
||||
XX(29, PURGE, PURGE) \
|
||||
/* CalDAV */ \
|
||||
XX(26, MKCALENDAR, MKCALENDAR) \
|
||||
XX(30, MKCALENDAR, MKCALENDAR) \
|
||||
/* RFC-2068, section 19.6.1.2 */ \
|
||||
XX(31, LINK, LINK) \
|
||||
XX(32, UNLINK, UNLINK) \
|
||||
|
||||
enum http_method
|
||||
{
|
||||
|
@ -140,6 +148,7 @@ enum flags
|
|||
, F_TRAILING = 1 << 4
|
||||
, F_UPGRADE = 1 << 5
|
||||
, F_SKIPBODY = 1 << 6
|
||||
, F_CONTENTLENGTH = 1 << 7
|
||||
};
|
||||
|
||||
|
||||
|
@ -160,6 +169,8 @@ enum flags
|
|||
XX(CB_body, "the on_body callback failed") \
|
||||
XX(CB_message_complete, "the on_message_complete callback failed") \
|
||||
XX(CB_status, "the on_status callback failed") \
|
||||
XX(CB_chunk_header, "the on_chunk_header callback failed") \
|
||||
XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
|
||||
\
|
||||
/* Parsing-related errors */ \
|
||||
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
|
||||
|
@ -180,6 +191,8 @@ enum flags
|
|||
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
|
||||
XX(INVALID_CONTENT_LENGTH, \
|
||||
"invalid character in content-length header") \
|
||||
XX(UNEXPECTED_CONTENT_LENGTH, \
|
||||
"unexpected content-length header") \
|
||||
XX(INVALID_CHUNK_SIZE, \
|
||||
"invalid character in chunk size header") \
|
||||
XX(INVALID_CONSTANT, "invalid constant string") \
|
||||
|
@ -204,10 +217,11 @@ enum http_errno {
|
|||
struct http_parser {
|
||||
/** PRIVATE **/
|
||||
unsigned int type : 2; /* enum http_parser_type */
|
||||
unsigned int flags : 7; /* F_* values from 'flags' enum; semi-public */
|
||||
unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
|
||||
unsigned int state : 7; /* enum state from http_parser.c */
|
||||
unsigned int header_state : 8; /* enum header_state from http_parser.c */
|
||||
unsigned int index : 8; /* index into current matcher */
|
||||
unsigned int header_state : 7; /* enum header_state from http_parser.c */
|
||||
unsigned int index : 7; /* index into current matcher */
|
||||
unsigned int lenient_http_headers : 1;
|
||||
|
||||
uint32_t nread; /* # bytes read in various scenarios */
|
||||
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
|
||||
|
@ -240,6 +254,11 @@ struct http_parser_settings {
|
|||
http_cb on_headers_complete;
|
||||
http_data_cb on_body;
|
||||
http_cb on_message_complete;
|
||||
/* When on_chunk_header is called, the current chunk length is stored
|
||||
* in parser->content_length.
|
||||
*/
|
||||
http_cb on_chunk_header;
|
||||
http_cb on_chunk_complete;
|
||||
};
|
||||
|
||||
|
||||
|
@ -318,6 +337,9 @@ const char *http_errno_name(enum http_errno err);
|
|||
/* Return a string description of the given error */
|
||||
const char *http_errno_description(enum http_errno err);
|
||||
|
||||
/* Initialize all http_parser_url members to 0 */
|
||||
void http_parser_url_init(struct http_parser_url *u);
|
||||
|
||||
/* Parse a URL; return nonzero on failure */
|
||||
int http_parser_parse_url(const char *buf, size_t buflen,
|
||||
int is_connect,
|
||||
|
|
|
@ -7,5 +7,6 @@ Installed-Size: 1024
|
|||
Homepage: https://github.com/zerotier/ZeroTierOne
|
||||
Description: ZeroTier One network virtualization service
|
||||
ZeroTier One is a fast, secure, and easy to use peer to peer network
|
||||
virtualization engine. Visit https://www.zerotier.com/ for more
|
||||
information.
|
||||
virtualization engine that provides global-scale software defined
|
||||
networking to any device or application. Visit https://www.zerotier.com/
|
||||
for more information.
|
||||
|
|
24
ext/installfiles/linux/RPM/README.md
Normal file
24
ext/installfiles/linux/RPM/README.md
Normal file
|
@ -0,0 +1,24 @@
|
|||
This folder contains two spec files which enable building of various RPM packages for ZeroTier.
|
||||
|
||||
#zerotier-one.spec.in
|
||||
This file contains the information to build an RPM from the bash based binary installer of ZeroTier. The resulting RPM cannot be recompiled to different architectures.
|
||||
|
||||
#zerotier.spec
|
||||
This spec file is a “standard” RPM spec file. It fits to the common rpmbuild process, SRPM and differnt architectures are supported too. The spec file can be used to build two packages: the standard zerotier and the zerotier-controller. It supports some of the build options exposed in the original Linux makefile:
|
||||
|
||||
> `rpmbuild -ba zerotier.spec` #builds the standard zerotier package, this is what you need in most of the cases
|
||||
|
||||
> `rpmbuild -ba zerotier.spec --with controller` #builds the zerotier-controller package
|
||||
|
||||
> `rpmbuild -ba zerotier.spec --with debug` #builds the zerotier package with debug enable<>d
|
||||
|
||||
> `rpmbuild -ba zerotier.spec --with miniupnpc` #builds the zerotier package with miniupnpc enabled
|
||||
|
||||
> `rpmbuild -ba zerotier.spec --with cluster` #builds the zerotier package with cluster enabled
|
||||
|
||||
|
||||
####Build environment preparation
|
||||
As zerotier is not distributed in tar.gz format at the moment, the %prep section of the spec file takes care about the prepartion of an rpmbuild compatible tar.gz.
|
||||
|
||||
|
||||
|
|
@ -21,11 +21,11 @@ mkdir -p /var/lib/zerotier-one/updates.d
|
|||
|
||||
%post
|
||||
chmod 0755 /var/lib/zerotier-one/updates.d/__INSTALLER__
|
||||
/var/lib/zerotier-one/updates.d/__INSTALLER__
|
||||
/var/lib/zerotier-one/updates.d/__INSTALLER__ >>/dev/null 2>&1
|
||||
|
||||
%preun
|
||||
if [ "$1" -lt 1 ]; then
|
||||
/var/lib/zerotier-one/uninstall.sh
|
||||
/var/lib/zerotier-one/uninstall.sh >>/dev/null 2>&1
|
||||
fi
|
||||
|
||||
%clean
|
||||
|
|
194
ext/installfiles/linux/RPM/zerotier.spec
Executable file
194
ext/installfiles/linux/RPM/zerotier.spec
Executable file
|
@ -0,0 +1,194 @@
|
|||
# add --with controller option to build controller (builds zerotier-controller package)
|
||||
%bcond_with controller
|
||||
# add --with miniupnpc option to enable the miniupnpc option during build
|
||||
%bcond_with miniupnpc
|
||||
# add --with cluster option to enable the cluster option during build
|
||||
%bcond_with cluster
|
||||
# add --with debug option to enable the debug option during build
|
||||
%bcond_with debug
|
||||
%if %{with controller}
|
||||
Name:zerotier-controller
|
||||
Conflicts:zerotier
|
||||
%else
|
||||
Name:zerotier
|
||||
Conflicts:zerotier-controller
|
||||
%endif
|
||||
Version: 1.1.4
|
||||
Release: 1
|
||||
Summary: Network Virtualization Everywhere https://www.zerotier.com/
|
||||
Group: network
|
||||
License: GPLv3
|
||||
BuildRoot: %{_tmppath}/%{name}-root
|
||||
Provides: zerotier-one
|
||||
Source0: http:///download/%{name}-%{version}.tar.gz
|
||||
BuildRequires: gcc-c++
|
||||
BuildRequires: make
|
||||
BuildRequires: gcc
|
||||
%if %{with server}
|
||||
BuildRequires: sqlite-devel
|
||||
BuildRequires: wget
|
||||
BuildRequires: unzip
|
||||
Requires: sqlite
|
||||
%endif
|
||||
%description
|
||||
ZeroTier One creates virtual Ethernet networks that work anywhere and everywhere.
|
||||
Visit https://www.zerotier.com/ for more information.
|
||||
|
||||
%prep
|
||||
cd `mktemp -d`
|
||||
wget -O master.zip https://github.com/zerotier/ZeroTierOne/archive/master.zip
|
||||
unzip master.zip
|
||||
mv ZeroTierOne-master zerotier-1.1.4
|
||||
ln -s zerotier-1.1.4 zerotier-controller-1.1.4
|
||||
tar zcvf zerotier-1.1.4.tar.gz zerotier-1.1.4 zerotier-controller-1.1.4
|
||||
ln -s zerotier-1.1.4.tar.gz zerotier-controller-1.1.4.tar.gz
|
||||
mv zero*.tar.gz ~/rpmbuild/SOURCES
|
||||
cd -
|
||||
%setup -q
|
||||
|
||||
%build
|
||||
%if %{with miniupnpc}
|
||||
ZT_USE_MINIUPNPC=1; export ZT_USE_MINIUPNPC;
|
||||
%endif
|
||||
|
||||
%if %{with controller}
|
||||
ZT_ENABLE_NETWORK_CONTROLLER=1; export ZT_ENABLE_NETWORK_CONTROLLER;
|
||||
%endif
|
||||
|
||||
%if %{with cluster}
|
||||
export ZT_ENABLE_CLUSTER=1
|
||||
%endif
|
||||
|
||||
%if %{with debug}
|
||||
export ZT_DEBUG=1
|
||||
%endif
|
||||
|
||||
make
|
||||
|
||||
%install
|
||||
|
||||
|
||||
rm -rf $RPM_BUILD_ROOT
|
||||
rm -f $RPM_BUILD_ROOT%{_prefix}/bin/zerotier-idtool $RPM_BUILD_ROOT%{_prefix}/bin/zerotier-idtool
|
||||
echo 'Install...'
|
||||
mkdir -p $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/{init.d,systemd}
|
||||
install -m 0755 -D zerotier-one -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/
|
||||
install -m 0755 -D ext/installfiles/linux/init.d/* -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/init.d/
|
||||
install -m 0755 -D ext/installfiles/linux/systemd/* -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/systemd/
|
||||
|
||||
|
||||
|
||||
%posttrans
|
||||
echo -n 'Getting version of new install... '
|
||||
newVersion=`/var/lib/zerotier-one/zerotier-one -v`
|
||||
echo $newVersion
|
||||
|
||||
echo 'Creating symlinks...'
|
||||
|
||||
rm -f /usr/bin/zerotier-cli /usr/bin/zerotier-idtool
|
||||
ln -sf /var/lib/zerotier-one/zerotier-one /usr/bin/zerotier-cli
|
||||
ln -sf /var/lib/zerotier-one/zerotier-one /usr/bin/zerotier-idtool
|
||||
echo 'Installing zerotier-one service...'
|
||||
|
||||
SYSTEMDUNITDIR=
|
||||
if [ -e /bin/systemctl -o -e /usr/bin/systemctl -o -e /usr/local/bin/systemctl -o -e /sbin/systemctl -o -e /usr/sbin/systemctl ]; then
|
||||
# Second check: test if systemd appears to actually be running. Apparently Ubuntu
|
||||
# thought it was a good idea to ship with systemd installed but not used. Issue #133
|
||||
if [ -d /var/run/systemd/system -o -d /run/systemd/system ]; then
|
||||
if [ -e /usr/bin/pkg-config ]; then
|
||||
SYSTEMDUNITDIR=`/usr/bin/pkg-config systemd --variable=systemdsystemunitdir`
|
||||
fi
|
||||
if [ -z "$SYSTEMDUNITDIR" -o ! -d "$SYSTEMDUNITDIR" ]; then
|
||||
if [ -d /usr/lib/systemd/system ]; then
|
||||
SYSTEMDUNITDIR=/usr/lib/systemd/system
|
||||
fi
|
||||
if [ -d /etc/systemd/system ]; then
|
||||
SYSTEMDUNITDIR=/etc/systemd/system
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -n "$SYSTEMDUNITDIR" -a -d "$SYSTEMDUNITDIR" ]; then
|
||||
# SYSTEMD
|
||||
|
||||
# If this was updated or upgraded from an init.d based system, clean up the old
|
||||
# init.d stuff before installing directly via systemd.
|
||||
if [ -f /etc/init.d/zerotier-one ]; then
|
||||
if [ -e /sbin/chkconfig -o -e /usr/sbin/chkconfig -o -e /bin/chkconfig -o -e /usr/bin/chkconfig ]; then
|
||||
chkconfig zerotier-one off
|
||||
fi
|
||||
rm -f /etc/init.d/zerotier-one
|
||||
fi
|
||||
|
||||
cp -f /var/lib/zerotier-one/initfiles/systemd/zerotier-one.service "$SYSTEMDUNITDIR/zerotier-one.service"
|
||||
chown 0 "$SYSTEMDUNITDIR/zerotier-one.service"
|
||||
chgrp 0 "$SYSTEMDUNITDIR/zerotier-one.service"
|
||||
chmod 0755 "$SYSTEMDUNITDIR/zerotier-one.service"
|
||||
|
||||
systemctl enable zerotier-one.service
|
||||
|
||||
echo
|
||||
echo 'Done! Installed and service configured to start at system boot.'
|
||||
echo
|
||||
echo "To start now or restart the service if it's already running:"
|
||||
echo ' sudo systemctl restart zerotier-one.service'
|
||||
else
|
||||
# SYSV INIT -- also covers upstart which supports SysVinit backward compatibility
|
||||
|
||||
cp -f /var/lib/zerotier-one/initfiles/init.d/zerotier-one /etc/init.d/zerotier-one
|
||||
chmod 0755 /etc/init.d/zerotier-one
|
||||
|
||||
if [ -f /sbin/chkconfig -o -f /usr/sbin/chkconfig -o -f /usr/bin/chkconfig -o -f /bin/chkconfig ]; then
|
||||
chkconfig zerotier-one on
|
||||
else
|
||||
# Yes Virginia, some systems lack chkconfig.
|
||||
if [ -d /etc/rc0.d ]; then
|
||||
rm -f /etc/rc0.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc0.d/K89zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc1.d ]; then
|
||||
rm -f /etc/rc1.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc1.d/K89zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc2.d ]; then
|
||||
rm -f /etc/rc2.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc2.d/S11zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc3.d ]; then
|
||||
rm -f /etc/rc3.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc3.d/S11zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc4.d ]; then
|
||||
rm -f /etc/rc4.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc4.d/S11zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc5.d ]; then
|
||||
rm -f /etc/rc5.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc5.d/S11zerotier-one
|
||||
fi
|
||||
if [ -d /etc/rc6.d ]; then
|
||||
rm -f /etc/rc6.d/???zerotier-one
|
||||
ln -sf /etc/init.d/zerotier-one /etc/rc6.d/K89zerotier-one
|
||||
fi
|
||||
fi
|
||||
echo
|
||||
echo 'Done! Installed and service configured to start at system boot.'
|
||||
echo
|
||||
echo "To start now or restart the service if it's already running:"
|
||||
echo ' sudo service zerotier-one restart'
|
||||
fi
|
||||
%preun
|
||||
/sbin/chkconfig --del zerotier-one
|
||||
rm -f /usr/bin/zerotier-cli /usr/bin/zerotier-idtool
|
||||
|
||||
%clean
|
||||
rm -rf $RPM_BUILD_ROOT
|
||||
%files
|
||||
%{_vardir}/lib/zerotier-one/zerotier-one
|
||||
%{_vardir}/lib/zerotier-one/initfiles/systemd/zerotier-one.service
|
||||
%{_vardir}/lib/zerotier-one/initfiles/init.d/zerotier-one
|
||||
|
||||
%changelog
|
||||
* Fri Feb 26 2016 Kristof Imre Szabo <kristof.szabo@lxsystems.de> 1.1.4-1
|
||||
- initial package
|
|
@ -91,14 +91,14 @@ case "$system" in
|
|||
rm -f "${debfolder}/postinst" "${debfolder}/prerm"
|
||||
|
||||
echo '#!/bin/bash' >${debfolder}/postinst
|
||||
echo "/var/lib/zerotier-one/updates.d/${targ}" >>${debfolder}/postinst
|
||||
echo "/var/lib/zerotier-one/updates.d/${targ} >>/dev/null 2>&1" >>${debfolder}/postinst
|
||||
echo "/bin/rm -f /var/lib/zerotier-one/updates.d/*" >>${debfolder}/postinst
|
||||
chmod a+x ${debfolder}/postinst
|
||||
|
||||
echo '#!/bin/bash' >${debfolder}/prerm
|
||||
echo 'export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin' >>${debfolder}/prerm
|
||||
echo 'if [ "$1" != "upgrade" ]; then' >>${debfolder}/prerm
|
||||
echo ' /var/lib/zerotier-one/uninstall.sh' >>${debfolder}/prerm
|
||||
echo ' /var/lib/zerotier-one/uninstall.sh >>/dev/null 2>&1' >>${debfolder}/prerm
|
||||
echo 'fi' >>${debfolder}/prerm
|
||||
chmod a+x ${debfolder}/prerm
|
||||
|
||||
|
|
|
@ -59,7 +59,7 @@ fi
|
|||
echo "Erasing binary and support files..."
|
||||
if [ -d /var/lib/zerotier-one ]; then
|
||||
cd /var/lib/zerotier-one
|
||||
rm -rf zerotier-one *.persist identity.public *.log *.pid *.sh updates.d networks.d iddb.d root-topology
|
||||
rm -rf zerotier-one *.persist identity.public *.log *.pid *.sh updates.d networks.d iddb.d root-topology ui
|
||||
fi
|
||||
|
||||
echo "Erasing anything installed into system bin directories..."
|
||||
|
|
627
ext/lz4/lz4.c
627
ext/lz4/lz4.c
|
@ -34,7 +34,7 @@
|
|||
|
||||
|
||||
/**************************************
|
||||
Tuning parameters
|
||||
* Tuning parameters
|
||||
**************************************/
|
||||
/*
|
||||
* HEAPMODE :
|
||||
|
@ -44,50 +44,15 @@
|
|||
#define HEAPMODE 0
|
||||
|
||||
/*
|
||||
* CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS :
|
||||
* By default, the source code expects the compiler to correctly optimize
|
||||
* 4-bytes and 8-bytes read on architectures able to handle it efficiently.
|
||||
* This is not always the case. In some circumstances (ARM notably),
|
||||
* the compiler will issue cautious code even when target is able to correctly handle unaligned memory accesses.
|
||||
*
|
||||
* You can force the compiler to use unaligned memory access by uncommenting the line below.
|
||||
* One of the below scenarios will happen :
|
||||
* 1 - Your target CPU correctly handle unaligned access, and was not well optimized by compiler (good case).
|
||||
* You will witness large performance improvements (+50% and up).
|
||||
* Keep the line uncommented and send a word to upstream (https://groups.google.com/forum/#!forum/lz4c)
|
||||
* The goal is to automatically detect such situations by adding your target CPU within an exception list.
|
||||
* 2 - Your target CPU correctly handle unaligned access, and was already already optimized by compiler
|
||||
* No change will be experienced.
|
||||
* 3 - Your target CPU inefficiently handle unaligned access.
|
||||
* You will experience a performance loss. Comment back the line.
|
||||
* 4 - Your target CPU does not handle unaligned access.
|
||||
* Program will crash.
|
||||
* If uncommenting results in better performance (case 1)
|
||||
* please report your configuration to upstream (https://groups.google.com/forum/#!forum/lz4c)
|
||||
* This way, an automatic detection macro can be added to match your case within later versions of the library.
|
||||
* ACCELERATION_DEFAULT :
|
||||
* Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
|
||||
*/
|
||||
/* #define CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS 1 */
|
||||
#define ACCELERATION_DEFAULT 1
|
||||
|
||||
|
||||
/**************************************
|
||||
CPU Feature Detection
|
||||
* CPU Feature Detection
|
||||
**************************************/
|
||||
/*
|
||||
* Automated efficient unaligned memory access detection
|
||||
* Based on known hardware architectures
|
||||
* This list will be updated thanks to feedbacks
|
||||
*/
|
||||
#if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
|
||||
|| defined(__ARM_FEATURE_UNALIGNED) \
|
||||
|| defined(__i386__) || defined(__x86_64__) \
|
||||
|| defined(_M_IX86) || defined(_M_X64) \
|
||||
|| defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
|
||||
|| (defined(_M_ARM) && (_M_ARM >= 7))
|
||||
# define LZ4_UNALIGNED_ACCESS 1
|
||||
#else
|
||||
# define LZ4_UNALIGNED_ACCESS 0
|
||||
#endif
|
||||
|
||||
/*
|
||||
* LZ4_FORCE_SW_BITCOUNT
|
||||
* Define this parameter if your target system or compiler does not support hardware bit count
|
||||
|
@ -97,15 +62,15 @@
|
|||
#endif
|
||||
|
||||
|
||||
/**************************************
|
||||
* Includes
|
||||
**************************************/
|
||||
#include "lz4.h"
|
||||
|
||||
|
||||
/**************************************
|
||||
* Compiler Options
|
||||
**************************************/
|
||||
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
|
||||
/* "restrict" is a known keyword */
|
||||
#else
|
||||
# define restrict /* Disable restrict */
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER /* Visual Studio */
|
||||
# define FORCE_INLINE static __forceinline
|
||||
# include <intrin.h>
|
||||
|
@ -113,7 +78,7 @@
|
|||
# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
|
||||
#else
|
||||
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
|
||||
# ifdef __GNUC__
|
||||
# if defined(__GNUC__) || defined(__clang__)
|
||||
# define FORCE_INLINE static inline __attribute__((always_inline))
|
||||
# else
|
||||
# define FORCE_INLINE static inline
|
||||
|
@ -123,9 +88,8 @@
|
|||
# endif /* __STDC_VERSION__ */
|
||||
#endif /* _MSC_VER */
|
||||
|
||||
#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
|
||||
|
||||
#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
|
||||
/* LZ4_GCC_VERSION is defined into lz4.h */
|
||||
#if (LZ4_GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
|
||||
# define expect(expr,value) (__builtin_expect ((expr),(value)) )
|
||||
#else
|
||||
# define expect(expr,value) (expr)
|
||||
|
@ -136,7 +100,7 @@
|
|||
|
||||
|
||||
/**************************************
|
||||
Memory routines
|
||||
* Memory routines
|
||||
**************************************/
|
||||
#include <stdlib.h> /* malloc, calloc, free */
|
||||
#define ALLOCATOR(n,s) calloc(n,s)
|
||||
|
@ -146,13 +110,7 @@
|
|||
|
||||
|
||||
/**************************************
|
||||
Includes
|
||||
**************************************/
|
||||
#include "lz4.h"
|
||||
|
||||
|
||||
/**************************************
|
||||
Basic Types
|
||||
* Basic Types
|
||||
**************************************/
|
||||
#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
|
||||
# include <stdint.h>
|
||||
|
@ -171,7 +129,7 @@
|
|||
|
||||
|
||||
/**************************************
|
||||
Reading and writing into memory
|
||||
* Reading and writing into memory
|
||||
**************************************/
|
||||
#define STEPSIZE sizeof(size_t)
|
||||
|
||||
|
@ -184,10 +142,19 @@ static unsigned LZ4_isLittleEndian(void)
|
|||
}
|
||||
|
||||
|
||||
static U16 LZ4_read16(const void* memPtr)
|
||||
{
|
||||
U16 val16;
|
||||
memcpy(&val16, memPtr, 2);
|
||||
return val16;
|
||||
}
|
||||
|
||||
static U16 LZ4_readLE16(const void* memPtr)
|
||||
{
|
||||
if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
|
||||
return *(U16*)memPtr;
|
||||
if (LZ4_isLittleEndian())
|
||||
{
|
||||
return LZ4_read16(memPtr);
|
||||
}
|
||||
else
|
||||
{
|
||||
const BYTE* p = (const BYTE*)memPtr;
|
||||
|
@ -197,10 +164,9 @@ static U16 LZ4_readLE16(const void* memPtr)
|
|||
|
||||
static void LZ4_writeLE16(void* memPtr, U16 value)
|
||||
{
|
||||
if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
|
||||
if (LZ4_isLittleEndian())
|
||||
{
|
||||
*(U16*)memPtr = value;
|
||||
return;
|
||||
memcpy(memPtr, &value, 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
@ -210,42 +176,19 @@ static void LZ4_writeLE16(void* memPtr, U16 value)
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
static U16 LZ4_read16(const void* memPtr)
|
||||
{
|
||||
if (LZ4_UNALIGNED_ACCESS)
|
||||
return *(U16*)memPtr;
|
||||
else
|
||||
{
|
||||
U16 val16;
|
||||
memcpy(&val16, memPtr, 2);
|
||||
return val16;
|
||||
}
|
||||
}
|
||||
|
||||
static U32 LZ4_read32(const void* memPtr)
|
||||
{
|
||||
if (LZ4_UNALIGNED_ACCESS)
|
||||
return *(U32*)memPtr;
|
||||
else
|
||||
{
|
||||
U32 val32;
|
||||
memcpy(&val32, memPtr, 4);
|
||||
return val32;
|
||||
}
|
||||
}
|
||||
|
||||
static U64 LZ4_read64(const void* memPtr)
|
||||
{
|
||||
if (LZ4_UNALIGNED_ACCESS)
|
||||
return *(U64*)memPtr;
|
||||
else
|
||||
{
|
||||
U64 val64;
|
||||
memcpy(&val64, memPtr, 8);
|
||||
return val64;
|
||||
}
|
||||
}
|
||||
|
||||
static size_t LZ4_read_ARCH(const void* p)
|
||||
{
|
||||
|
@ -256,31 +199,9 @@ static size_t LZ4_read_ARCH(const void* p)
|
|||
}
|
||||
|
||||
|
||||
static void LZ4_copy4(void* dstPtr, const void* srcPtr)
|
||||
{
|
||||
if (LZ4_UNALIGNED_ACCESS)
|
||||
{
|
||||
*(U32*)dstPtr = *(U32*)srcPtr;
|
||||
return;
|
||||
}
|
||||
memcpy(dstPtr, srcPtr, 4);
|
||||
}
|
||||
static void LZ4_copy4(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 4); }
|
||||
|
||||
static void LZ4_copy8(void* dstPtr, const void* srcPtr)
|
||||
{
|
||||
#if GCC_VERSION!=409 /* disabled on GCC 4.9, as it generates invalid opcode (crash) */
|
||||
if (LZ4_UNALIGNED_ACCESS)
|
||||
{
|
||||
if (LZ4_64bits())
|
||||
*(U64*)dstPtr = *(U64*)srcPtr;
|
||||
else
|
||||
((U32*)dstPtr)[0] = ((U32*)srcPtr)[0],
|
||||
((U32*)dstPtr)[1] = ((U32*)srcPtr)[1];
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
memcpy(dstPtr, srcPtr, 8);
|
||||
}
|
||||
static void LZ4_copy8(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 8); }
|
||||
|
||||
/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
|
||||
static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
|
||||
|
@ -293,7 +214,7 @@ static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
|
|||
|
||||
|
||||
/**************************************
|
||||
Common Constants
|
||||
* Common Constants
|
||||
**************************************/
|
||||
#define MINMATCH 4
|
||||
|
||||
|
@ -334,7 +255,7 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
|
|||
unsigned long r = 0;
|
||||
_BitScanForward64( &r, (U64)val );
|
||||
return (int)(r>>3);
|
||||
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_ctzll((U64)val) >> 3);
|
||||
# else
|
||||
static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
|
||||
|
@ -347,7 +268,7 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
|
|||
unsigned long r;
|
||||
_BitScanForward( &r, (U32)val );
|
||||
return (int)(r>>3);
|
||||
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_ctz((U32)val) >> 3);
|
||||
# else
|
||||
static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
|
||||
|
@ -363,8 +284,8 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
|
|||
unsigned long r = 0;
|
||||
_BitScanReverse64( &r, val );
|
||||
return (unsigned)(r>>3);
|
||||
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_clzll(val) >> 3);
|
||||
# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_clzll((U64)val) >> 3);
|
||||
# else
|
||||
unsigned r;
|
||||
if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
|
||||
|
@ -379,8 +300,8 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
|
|||
unsigned long r = 0;
|
||||
_BitScanReverse( &r, (unsigned long)val );
|
||||
return (unsigned)(r>>3);
|
||||
# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_clz(val) >> 3);
|
||||
# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
|
||||
return (__builtin_clz((U32)val) >> 3);
|
||||
# else
|
||||
unsigned r;
|
||||
if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
|
||||
|
@ -422,13 +343,6 @@ static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
|
|||
static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */
|
||||
|
||||
|
||||
/**************************************
|
||||
* Local Utils
|
||||
**************************************/
|
||||
int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
|
||||
int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
|
||||
|
||||
|
||||
/**************************************
|
||||
* Local Structures and types
|
||||
**************************************/
|
||||
|
@ -437,7 +351,7 @@ typedef struct {
|
|||
U32 currentOffset;
|
||||
U32 initCheck;
|
||||
const BYTE* dictionary;
|
||||
const BYTE* bufferStart;
|
||||
BYTE* bufferStart; /* obsolete, used for slideInputBuffer */
|
||||
U32 dictSize;
|
||||
} LZ4_stream_t_internal;
|
||||
|
||||
|
@ -451,6 +365,14 @@ typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
|
|||
typedef enum { full = 0, partial = 1 } earlyEnd_directive;
|
||||
|
||||
|
||||
/**************************************
|
||||
* Local Utils
|
||||
**************************************/
|
||||
int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
|
||||
int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
|
||||
int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
|
||||
|
||||
|
||||
|
||||
/********************************
|
||||
* Compression functions
|
||||
|
@ -464,7 +386,22 @@ static U32 LZ4_hashSequence(U32 sequence, tableType_t const tableType)
|
|||
return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
|
||||
}
|
||||
|
||||
static U32 LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(LZ4_read32(p), tableType); }
|
||||
static const U64 prime5bytes = 889523592379ULL;
|
||||
static U32 LZ4_hashSequence64(size_t sequence, tableType_t const tableType)
|
||||
{
|
||||
const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
|
||||
const U32 hashMask = (1<<hashLog) - 1;
|
||||
return ((sequence * prime5bytes) >> (40 - hashLog)) & hashMask;
|
||||
}
|
||||
|
||||
static U32 LZ4_hashSequenceT(size_t sequence, tableType_t const tableType)
|
||||
{
|
||||
if (LZ4_64bits())
|
||||
return LZ4_hashSequence64(sequence, tableType);
|
||||
return LZ4_hashSequence((U32)sequence, tableType);
|
||||
}
|
||||
|
||||
static U32 LZ4_hashPosition(const void* p, tableType_t tableType) { return LZ4_hashSequenceT(LZ4_read_ARCH(p), tableType); }
|
||||
|
||||
static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
|
||||
{
|
||||
|
@ -495,16 +432,17 @@ static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t t
|
|||
return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
|
||||
}
|
||||
|
||||
static int LZ4_compress_generic(
|
||||
void* ctx,
|
||||
const char* source,
|
||||
char* dest,
|
||||
int inputSize,
|
||||
int maxOutputSize,
|
||||
limitedOutput_directive outputLimited,
|
||||
tableType_t const tableType,
|
||||
dict_directive dict,
|
||||
dictIssue_directive dictIssue)
|
||||
FORCE_INLINE int LZ4_compress_generic(
|
||||
void* const ctx,
|
||||
const char* const source,
|
||||
char* const dest,
|
||||
const int inputSize,
|
||||
const int maxOutputSize,
|
||||
const limitedOutput_directive outputLimited,
|
||||
const tableType_t tableType,
|
||||
const dict_directive dict,
|
||||
const dictIssue_directive dictIssue,
|
||||
const U32 acceleration)
|
||||
{
|
||||
LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;
|
||||
|
||||
|
@ -559,14 +497,14 @@ static int LZ4_compress_generic(
|
|||
{
|
||||
const BYTE* forwardIp = ip;
|
||||
unsigned step = 1;
|
||||
unsigned searchMatchNb = (1U << LZ4_skipTrigger);
|
||||
unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
|
||||
|
||||
/* Find a match */
|
||||
do {
|
||||
U32 h = forwardH;
|
||||
ip = forwardIp;
|
||||
forwardIp += step;
|
||||
step = searchMatchNb++ >> LZ4_skipTrigger;
|
||||
step = (searchMatchNb++ >> LZ4_skipTrigger);
|
||||
|
||||
if (unlikely(forwardIp > mflimit)) goto _last_literals;
|
||||
|
||||
|
@ -693,13 +631,22 @@ _next_match:
|
|||
_last_literals:
|
||||
/* Encode Last Literals */
|
||||
{
|
||||
int lastRun = (int)(iend - anchor);
|
||||
if ((outputLimited) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
|
||||
const size_t lastRun = (size_t)(iend - anchor);
|
||||
if ((outputLimited) && ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
|
||||
return 0; /* Check output limit */
|
||||
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun >= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
|
||||
else *op++ = (BYTE)(lastRun<<ML_BITS);
|
||||
memcpy(op, anchor, iend - anchor);
|
||||
op += iend-anchor;
|
||||
if (lastRun >= RUN_MASK)
|
||||
{
|
||||
size_t accumulator = lastRun - RUN_MASK;
|
||||
*op++ = RUN_MASK << ML_BITS;
|
||||
for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
|
||||
*op++ = (BYTE) accumulator;
|
||||
}
|
||||
else
|
||||
{
|
||||
*op++ = (BYTE)(lastRun<<ML_BITS);
|
||||
}
|
||||
memcpy(op, anchor, lastRun);
|
||||
op += lastRun;
|
||||
}
|
||||
|
||||
/* End */
|
||||
|
@ -707,39 +654,271 @@ _last_literals:
|
|||
}
|
||||
|
||||
|
||||
int LZ4_compress(const char* source, char* dest, int inputSize)
|
||||
int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
|
||||
{
|
||||
LZ4_resetStream((LZ4_stream_t*)state);
|
||||
if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
|
||||
|
||||
if (maxOutputSize >= LZ4_compressBound(inputSize))
|
||||
{
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
|
||||
else
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
|
||||
else
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
|
||||
{
|
||||
#if (HEAPMODE)
|
||||
void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
|
||||
void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
|
||||
#else
|
||||
U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
|
||||
LZ4_stream_t ctx;
|
||||
void* ctxPtr = &ctx;
|
||||
#endif
|
||||
int result;
|
||||
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
|
||||
else
|
||||
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
|
||||
int result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
|
||||
|
||||
#if (HEAPMODE)
|
||||
FREEMEM(ctx);
|
||||
FREEMEM(ctxPtr);
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
|
||||
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
|
||||
|
||||
int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize)
|
||||
{
|
||||
#if (HEAPMODE)
|
||||
void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
|
||||
#else
|
||||
U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
|
||||
#endif
|
||||
int result;
|
||||
return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1);
|
||||
}
|
||||
|
||||
|
||||
/* hidden debug function */
|
||||
/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
|
||||
int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
|
||||
{
|
||||
LZ4_stream_t ctx;
|
||||
|
||||
LZ4_resetStream(&ctx);
|
||||
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
|
||||
return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
|
||||
else
|
||||
result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
|
||||
return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
|
||||
}
|
||||
|
||||
|
||||
/********************************
|
||||
* destSize variant
|
||||
********************************/
|
||||
|
||||
static int LZ4_compress_destSize_generic(
|
||||
void* const ctx,
|
||||
const char* const src,
|
||||
char* const dst,
|
||||
int* const srcSizePtr,
|
||||
const int targetDstSize,
|
||||
const tableType_t tableType)
|
||||
{
|
||||
const BYTE* ip = (const BYTE*) src;
|
||||
const BYTE* base = (const BYTE*) src;
|
||||
const BYTE* lowLimit = (const BYTE*) src;
|
||||
const BYTE* anchor = ip;
|
||||
const BYTE* const iend = ip + *srcSizePtr;
|
||||
const BYTE* const mflimit = iend - MFLIMIT;
|
||||
const BYTE* const matchlimit = iend - LASTLITERALS;
|
||||
|
||||
BYTE* op = (BYTE*) dst;
|
||||
BYTE* const oend = op + targetDstSize;
|
||||
BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */;
|
||||
BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */);
|
||||
BYTE* const oMaxSeq = oMaxLit - 1 /* token */;
|
||||
|
||||
U32 forwardH;
|
||||
|
||||
|
||||
/* Init conditions */
|
||||
if (targetDstSize < 1) return 0; /* Impossible to store anything */
|
||||
if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
|
||||
if ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
|
||||
if (*srcSizePtr<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
|
||||
|
||||
/* First Byte */
|
||||
*srcSizePtr = 0;
|
||||
LZ4_putPosition(ip, ctx, tableType, base);
|
||||
ip++; forwardH = LZ4_hashPosition(ip, tableType);
|
||||
|
||||
/* Main Loop */
|
||||
for ( ; ; )
|
||||
{
|
||||
const BYTE* match;
|
||||
BYTE* token;
|
||||
{
|
||||
const BYTE* forwardIp = ip;
|
||||
unsigned step = 1;
|
||||
unsigned searchMatchNb = 1 << LZ4_skipTrigger;
|
||||
|
||||
/* Find a match */
|
||||
do {
|
||||
U32 h = forwardH;
|
||||
ip = forwardIp;
|
||||
forwardIp += step;
|
||||
step = (searchMatchNb++ >> LZ4_skipTrigger);
|
||||
|
||||
if (unlikely(forwardIp > mflimit))
|
||||
goto _last_literals;
|
||||
|
||||
match = LZ4_getPositionOnHash(h, ctx, tableType, base);
|
||||
forwardH = LZ4_hashPosition(forwardIp, tableType);
|
||||
LZ4_putPositionOnHash(ip, h, ctx, tableType, base);
|
||||
|
||||
} while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
|
||||
|| (LZ4_read32(match) != LZ4_read32(ip)) );
|
||||
}
|
||||
|
||||
/* Catch up */
|
||||
while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
|
||||
|
||||
{
|
||||
/* Encode Literal length */
|
||||
unsigned litLength = (unsigned)(ip - anchor);
|
||||
token = op++;
|
||||
if (op + ((litLength+240)/255) + litLength > oMaxLit)
|
||||
{
|
||||
/* Not enough space for a last match */
|
||||
op--;
|
||||
goto _last_literals;
|
||||
}
|
||||
if (litLength>=RUN_MASK)
|
||||
{
|
||||
unsigned len = litLength - RUN_MASK;
|
||||
*token=(RUN_MASK<<ML_BITS);
|
||||
for(; len >= 255 ; len-=255) *op++ = 255;
|
||||
*op++ = (BYTE)len;
|
||||
}
|
||||
else *token = (BYTE)(litLength<<ML_BITS);
|
||||
|
||||
/* Copy Literals */
|
||||
LZ4_wildCopy(op, anchor, op+litLength);
|
||||
op += litLength;
|
||||
}
|
||||
|
||||
_next_match:
|
||||
/* Encode Offset */
|
||||
LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
|
||||
|
||||
/* Encode MatchLength */
|
||||
{
|
||||
size_t matchLength;
|
||||
|
||||
matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
|
||||
|
||||
if (op + ((matchLength+240)/255) > oMaxMatch)
|
||||
{
|
||||
/* Match description too long : reduce it */
|
||||
matchLength = (15-1) + (oMaxMatch-op) * 255;
|
||||
}
|
||||
//printf("offset %5i, matchLength%5i \n", (int)(ip-match), matchLength + MINMATCH);
|
||||
ip += MINMATCH + matchLength;
|
||||
|
||||
if (matchLength>=ML_MASK)
|
||||
{
|
||||
*token += ML_MASK;
|
||||
matchLength -= ML_MASK;
|
||||
while (matchLength >= 255) { matchLength-=255; *op++ = 255; }
|
||||
*op++ = (BYTE)matchLength;
|
||||
}
|
||||
else *token += (BYTE)(matchLength);
|
||||
}
|
||||
|
||||
anchor = ip;
|
||||
|
||||
/* Test end of block */
|
||||
if (ip > mflimit) break;
|
||||
if (op > oMaxSeq) break;
|
||||
|
||||
/* Fill table */
|
||||
LZ4_putPosition(ip-2, ctx, tableType, base);
|
||||
|
||||
/* Test next position */
|
||||
match = LZ4_getPosition(ip, ctx, tableType, base);
|
||||
LZ4_putPosition(ip, ctx, tableType, base);
|
||||
if ( (match+MAX_DISTANCE>=ip)
|
||||
&& (LZ4_read32(match)==LZ4_read32(ip)) )
|
||||
{ token=op++; *token=0; goto _next_match; }
|
||||
|
||||
/* Prepare next loop */
|
||||
forwardH = LZ4_hashPosition(++ip, tableType);
|
||||
}
|
||||
|
||||
_last_literals:
|
||||
/* Encode Last Literals */
|
||||
{
|
||||
size_t lastRunSize = (size_t)(iend - anchor);
|
||||
if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend)
|
||||
{
|
||||
/* adapt lastRunSize to fill 'dst' */
|
||||
lastRunSize = (oend-op) - 1;
|
||||
lastRunSize -= (lastRunSize+240)/255;
|
||||
}
|
||||
ip = anchor + lastRunSize;
|
||||
|
||||
if (lastRunSize >= RUN_MASK)
|
||||
{
|
||||
size_t accumulator = lastRunSize - RUN_MASK;
|
||||
*op++ = RUN_MASK << ML_BITS;
|
||||
for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
|
||||
*op++ = (BYTE) accumulator;
|
||||
}
|
||||
else
|
||||
{
|
||||
*op++ = (BYTE)(lastRunSize<<ML_BITS);
|
||||
}
|
||||
memcpy(op, anchor, lastRunSize);
|
||||
op += lastRunSize;
|
||||
}
|
||||
|
||||
/* End */
|
||||
*srcSizePtr = (int) (((const char*)ip)-src);
|
||||
return (int) (((char*)op)-dst);
|
||||
}
|
||||
|
||||
|
||||
static int LZ4_compress_destSize_extState (void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
|
||||
{
|
||||
LZ4_resetStream((LZ4_stream_t*)state);
|
||||
|
||||
if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) /* compression success is guaranteed */
|
||||
{
|
||||
return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (*srcSizePtr < LZ4_64Klimit)
|
||||
return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, byU16);
|
||||
else
|
||||
return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, LZ4_64bits() ? byU32 : byPtr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
|
||||
{
|
||||
#if (HEAPMODE)
|
||||
void* ctx = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
|
||||
#else
|
||||
LZ4_stream_t ctxBody;
|
||||
void* ctx = &ctxBody;
|
||||
#endif
|
||||
|
||||
int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
|
||||
|
||||
#if (HEAPMODE)
|
||||
FREEMEM(ctx);
|
||||
|
@ -748,19 +927,10 @@ int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, in
|
|||
}
|
||||
|
||||
|
||||
/*****************************************
|
||||
* Experimental : Streaming functions
|
||||
*****************************************/
|
||||
|
||||
/*
|
||||
* LZ4_initStream
|
||||
* Use this function once, to init a newly allocated LZ4_stream_t structure
|
||||
* Return : 1 if OK, 0 if error
|
||||
*/
|
||||
void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
|
||||
{
|
||||
MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
|
||||
}
|
||||
/********************************
|
||||
* Streaming functions
|
||||
********************************/
|
||||
|
||||
LZ4_stream_t* LZ4_createStream(void)
|
||||
{
|
||||
|
@ -770,6 +940,11 @@ LZ4_stream_t* LZ4_createStream(void)
|
|||
return lz4s;
|
||||
}
|
||||
|
||||
void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
|
||||
{
|
||||
MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
|
||||
}
|
||||
|
||||
int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
|
||||
{
|
||||
FREEMEM(LZ4_stream);
|
||||
|
@ -777,6 +952,7 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
|
|||
}
|
||||
|
||||
|
||||
#define HASH_UNIT sizeof(size_t)
|
||||
int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
|
||||
{
|
||||
LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
|
||||
|
@ -784,24 +960,26 @@ int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
|
|||
const BYTE* const dictEnd = p + dictSize;
|
||||
const BYTE* base;
|
||||
|
||||
if (dict->initCheck) LZ4_resetStream(LZ4_dict); /* Uninitialized structure detected */
|
||||
if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */
|
||||
LZ4_resetStream(LZ4_dict);
|
||||
|
||||
if (dictSize < MINMATCH)
|
||||
if (dictSize < (int)HASH_UNIT)
|
||||
{
|
||||
dict->dictionary = NULL;
|
||||
dict->dictSize = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (p <= dictEnd - 64 KB) p = dictEnd - 64 KB;
|
||||
if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
|
||||
dict->currentOffset += 64 KB;
|
||||
base = p - dict->currentOffset;
|
||||
dict->dictionary = p;
|
||||
dict->dictSize = (U32)(dictEnd - p);
|
||||
dict->currentOffset += dict->dictSize;
|
||||
|
||||
while (p <= dictEnd-MINMATCH)
|
||||
while (p <= dictEnd-HASH_UNIT)
|
||||
{
|
||||
LZ4_putPosition(p, dict, byU32, base);
|
||||
LZ4_putPosition(p, dict->hashTable, byU32, base);
|
||||
p+=3;
|
||||
}
|
||||
|
||||
|
@ -830,8 +1008,7 @@ static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
|
|||
}
|
||||
|
||||
|
||||
FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* source, char* dest, int inputSize,
|
||||
int maxOutputSize, limitedOutput_directive limit)
|
||||
int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
|
||||
{
|
||||
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream;
|
||||
const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
|
||||
|
@ -840,6 +1017,7 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
|
|||
if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
|
||||
if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;
|
||||
LZ4_renormDictT(streamPtr, smallest);
|
||||
if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
|
||||
|
||||
/* Check overlapping input/dictionary space */
|
||||
{
|
||||
|
@ -858,9 +1036,9 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
|
|||
{
|
||||
int result;
|
||||
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, dictSmall);
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration);
|
||||
else
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, noDictIssue);
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration);
|
||||
streamPtr->dictSize += (U32)inputSize;
|
||||
streamPtr->currentOffset += (U32)inputSize;
|
||||
return result;
|
||||
|
@ -870,9 +1048,9 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
|
|||
{
|
||||
int result;
|
||||
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, dictSmall);
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration);
|
||||
else
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, noDictIssue);
|
||||
result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration);
|
||||
streamPtr->dictionary = (const BYTE*)source;
|
||||
streamPtr->dictSize = (U32)inputSize;
|
||||
streamPtr->currentOffset += (U32)inputSize;
|
||||
|
@ -880,18 +1058,8 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
|
|||
}
|
||||
}
|
||||
|
||||
int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
|
||||
{
|
||||
return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, 0, notLimited);
|
||||
}
|
||||
|
||||
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize)
|
||||
{
|
||||
return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput);
|
||||
}
|
||||
|
||||
|
||||
/* Hidden debug function, to force separate dictionary mode */
|
||||
/* Hidden debug function, to force external dictionary mode */
|
||||
int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)
|
||||
{
|
||||
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;
|
||||
|
@ -902,7 +1070,7 @@ int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char*
|
|||
if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;
|
||||
LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest);
|
||||
|
||||
result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue);
|
||||
result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
|
||||
|
||||
streamPtr->dictionary = (const BYTE*)source;
|
||||
streamPtr->dictSize = (U32)inputSize;
|
||||
|
@ -955,7 +1123,7 @@ FORCE_INLINE int LZ4_decompress_generic(
|
|||
)
|
||||
{
|
||||
/* Local Variables */
|
||||
const BYTE* restrict ip = (const BYTE*) source;
|
||||
const BYTE* ip = (const BYTE*) source;
|
||||
const BYTE* const iend = ip + inputSize;
|
||||
|
||||
BYTE* op = (BYTE*) dest;
|
||||
|
@ -1051,8 +1219,7 @@ FORCE_INLINE int LZ4_decompress_generic(
|
|||
{
|
||||
/* match can be copied as a single segment from external dictionary */
|
||||
match = dictEnd - (lowPrefix-match);
|
||||
memcpy(op, match, length);
|
||||
op += length;
|
||||
memmove(op, match, length); op += length;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
@ -1110,11 +1277,11 @@ FORCE_INLINE int LZ4_decompress_generic(
|
|||
if (endOnInput)
|
||||
return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
|
||||
else
|
||||
return (int) (((char*)ip)-source); /* Nb of input bytes read */
|
||||
return (int) (((const char*)ip)-source); /* Nb of input bytes read */
|
||||
|
||||
/* Overflow error detected */
|
||||
_output_error:
|
||||
return (int) (-(((char*)ip)-source))-1;
|
||||
return (int) (-(((const char*)ip)-source))-1;
|
||||
}
|
||||
|
||||
|
||||
|
@ -1138,9 +1305,9 @@ int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
|
|||
|
||||
typedef struct
|
||||
{
|
||||
BYTE* externalDict;
|
||||
const BYTE* externalDict;
|
||||
size_t extDictSize;
|
||||
BYTE* prefixEnd;
|
||||
const BYTE* prefixEnd;
|
||||
size_t prefixSize;
|
||||
} LZ4_streamDecode_t_internal;
|
||||
|
||||
|
@ -1172,7 +1339,7 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti
|
|||
{
|
||||
LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
|
||||
lz4sd->prefixSize = (size_t) dictSize;
|
||||
lz4sd->prefixEnd = (BYTE*) dictionary + dictSize;
|
||||
lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
|
||||
lz4sd->externalDict = NULL;
|
||||
lz4sd->extDictSize = 0;
|
||||
return 1;
|
||||
|
@ -1261,7 +1428,7 @@ FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest
|
|||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);
|
||||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);
|
||||
}
|
||||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
|
||||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
|
||||
}
|
||||
|
||||
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
|
||||
|
@ -1277,13 +1444,21 @@ int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSi
|
|||
/* debug function */
|
||||
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
|
||||
{
|
||||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
|
||||
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
|
||||
}
|
||||
|
||||
|
||||
/***************************************************
|
||||
* Obsolete Functions
|
||||
***************************************************/
|
||||
/* obsolete compression functions */
|
||||
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); }
|
||||
int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); }
|
||||
int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); }
|
||||
int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); }
|
||||
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); }
|
||||
int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); }
|
||||
|
||||
/*
|
||||
These function names are deprecated and should no longer be used.
|
||||
They are only provided here for compatibility with older user programs.
|
||||
|
@ -1298,23 +1473,23 @@ int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize,
|
|||
|
||||
int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
|
||||
|
||||
static void LZ4_init(LZ4_stream_t_internal* lz4ds, const BYTE* base)
|
||||
static void LZ4_init(LZ4_stream_t_internal* lz4ds, BYTE* base)
|
||||
{
|
||||
MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE);
|
||||
lz4ds->bufferStart = base;
|
||||
}
|
||||
|
||||
int LZ4_resetStreamState(void* state, const char* inputBuffer)
|
||||
int LZ4_resetStreamState(void* state, char* inputBuffer)
|
||||
{
|
||||
if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */
|
||||
LZ4_init((LZ4_stream_t_internal*)state, (const BYTE*)inputBuffer);
|
||||
LZ4_init((LZ4_stream_t_internal*)state, (BYTE*)inputBuffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void* LZ4_create (const char* inputBuffer)
|
||||
void* LZ4_create (char* inputBuffer)
|
||||
{
|
||||
void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64);
|
||||
LZ4_init ((LZ4_stream_t_internal*)lz4ds, (const BYTE*)inputBuffer);
|
||||
LZ4_init ((LZ4_stream_t_internal*)lz4ds, (BYTE*)inputBuffer);
|
||||
return lz4ds;
|
||||
}
|
||||
|
||||
|
@ -1325,32 +1500,6 @@ char* LZ4_slideInputBuffer (void* LZ4_Data)
|
|||
return (char*)(ctx->bufferStart + dictSize);
|
||||
}
|
||||
|
||||
/* Obsolete compresson functions using User-allocated state */
|
||||
|
||||
int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
|
||||
|
||||
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize)
|
||||
{
|
||||
if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
|
||||
MEM_INIT(state, 0, LZ4_STREAMSIZE);
|
||||
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
|
||||
else
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
|
||||
}
|
||||
|
||||
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
|
||||
{
|
||||
if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
|
||||
MEM_INIT(state, 0, LZ4_STREAMSIZE);
|
||||
|
||||
if (inputSize < LZ4_64Klimit)
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
|
||||
else
|
||||
return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
|
||||
}
|
||||
|
||||
/* Obsolete streaming decompression functions */
|
||||
|
||||
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
|
||||
|
|
200
ext/lz4/lz4.h
200
ext/lz4/lz4.h
|
@ -39,17 +39,17 @@ extern "C" {
|
|||
#endif
|
||||
|
||||
/*
|
||||
* lz4.h provides block compression functions, for optimal performance.
|
||||
* lz4.h provides block compression functions, and gives full buffer control to programmer.
|
||||
* If you need to generate inter-operable compressed data (respecting LZ4 frame specification),
|
||||
* please use lz4frame.h instead.
|
||||
* and can let the library handle its own memory, please use lz4frame.h instead.
|
||||
*/
|
||||
|
||||
/**************************************
|
||||
* Version
|
||||
**************************************/
|
||||
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
|
||||
#define LZ4_VERSION_MINOR 6 /* for new (non-breaking) interface capabilities */
|
||||
#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */
|
||||
#define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
|
||||
#define LZ4_VERSION_RELEASE 1 /* for tweaks, bug-fixes, or development */
|
||||
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
|
||||
int LZ4_versionNumber (void);
|
||||
|
||||
|
@ -70,28 +70,32 @@ int LZ4_versionNumber (void);
|
|||
* Simple Functions
|
||||
**************************************/
|
||||
|
||||
int LZ4_compress (const char* source, char* dest, int sourceSize);
|
||||
int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize);
|
||||
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
|
||||
|
||||
/*
|
||||
LZ4_compress() :
|
||||
Compresses 'sourceSize' bytes from 'source' into 'dest'.
|
||||
Destination buffer must be already allocated,
|
||||
and must be sized to handle worst cases situations (input data not compressible)
|
||||
Worst case size evaluation is provided by function LZ4_compressBound()
|
||||
inputSize : Max supported value is LZ4_MAX_INPUT_SIZE
|
||||
return : the number of bytes written in buffer dest
|
||||
or 0 if the compression fails
|
||||
LZ4_compress_default() :
|
||||
Compresses 'sourceSize' bytes from buffer 'source'
|
||||
into already allocated 'dest' buffer of size 'maxDestSize'.
|
||||
Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize).
|
||||
It also runs faster, so it's a recommended setting.
|
||||
If the function cannot compress 'source' into a more limited 'dest' budget,
|
||||
compression stops *immediately*, and the function result is zero.
|
||||
As a consequence, 'dest' content is not valid.
|
||||
This function never writes outside 'dest' buffer, nor read outside 'source' buffer.
|
||||
sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
|
||||
maxDestSize : full or partial size of buffer 'dest' (which must be already allocated)
|
||||
return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize)
|
||||
or 0 if compression fails
|
||||
|
||||
LZ4_decompress_safe() :
|
||||
compressedSize : is obviously the source size
|
||||
maxDecompressedSize : is the size of the destination buffer, which must be already allocated.
|
||||
return : the number of bytes decompressed into the destination buffer (necessarily <= maxDecompressedSize)
|
||||
If the destination buffer is not large enough, decoding will stop and output an error code (<0).
|
||||
compressedSize : is the precise full size of the compressed block.
|
||||
maxDecompressedSize : is the size of destination buffer, which must be already allocated.
|
||||
return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize)
|
||||
If destination buffer is not large enough, decoding will stop and output an error code (<0).
|
||||
If the source stream is detected malformed, the function will stop decoding and return a negative result.
|
||||
This function is protected against buffer overflow exploits,
|
||||
and never writes outside of output buffer, nor reads outside of input buffer.
|
||||
It is also protected against malicious data packets.
|
||||
This function is protected against buffer overflow exploits, including malicious data packets.
|
||||
It never writes outside output buffer, nor reads outside input buffer.
|
||||
*/
|
||||
|
||||
|
||||
|
@ -99,45 +103,54 @@ LZ4_decompress_safe() :
|
|||
* Advanced Functions
|
||||
**************************************/
|
||||
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
|
||||
#define LZ4_COMPRESSBOUND(isize) ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
|
||||
#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
|
||||
|
||||
/*
|
||||
LZ4_compressBound() :
|
||||
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
|
||||
This function is primarily useful for memory allocation purposes (output buffer size).
|
||||
This function is primarily useful for memory allocation purposes (destination buffer size).
|
||||
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
|
||||
|
||||
isize : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE
|
||||
Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize)
|
||||
inputSize : max supported value is LZ4_MAX_INPUT_SIZE
|
||||
return : maximum output size in a "worst case" scenario
|
||||
or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
|
||||
*/
|
||||
int LZ4_compressBound(int isize);
|
||||
|
||||
int LZ4_compressBound(int inputSize);
|
||||
|
||||
/*
|
||||
LZ4_compress_limitedOutput() :
|
||||
Compress 'sourceSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
|
||||
If it cannot achieve it, compression will stop, and result of the function will be zero.
|
||||
This saves time and memory on detecting non-compressible (or barely compressible) data.
|
||||
This function never writes outside of provided output buffer.
|
||||
|
||||
sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
|
||||
maxOutputSize : is the size of the destination buffer (which must be already allocated)
|
||||
return : the number of bytes written in buffer 'dest'
|
||||
or 0 if compression fails
|
||||
LZ4_compress_fast() :
|
||||
Same as LZ4_compress_default(), but allows to select an "acceleration" factor.
|
||||
The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
|
||||
It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
|
||||
An acceleration value of "1" is the same as regular LZ4_compress_default()
|
||||
Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1.
|
||||
*/
|
||||
int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
|
||||
int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration);
|
||||
|
||||
|
||||
/*
|
||||
LZ4_compress_withState() :
|
||||
Same compression functions, but using an externally allocated memory space to store compression state.
|
||||
LZ4_compress_fast_extState() :
|
||||
Same compression function, just using an externally allocated memory space to store compression state.
|
||||
Use LZ4_sizeofState() to know how much memory must be allocated,
|
||||
and then, provide it as 'void* state' to compression functions.
|
||||
and allocate it on 8-bytes boundaries (using malloc() typically).
|
||||
Then, provide it as 'void* state' to compression function.
|
||||
*/
|
||||
int LZ4_sizeofState(void);
|
||||
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
|
||||
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
|
||||
int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration);
|
||||
|
||||
|
||||
/*
|
||||
LZ4_compress_destSize() :
|
||||
Reverse the logic, by compressing as much data as possible from 'source' buffer
|
||||
into already allocated buffer 'dest' of size 'targetDestSize'.
|
||||
This function either compresses the entire 'source' content into 'dest' if it's large enough,
|
||||
or fill 'dest' buffer completely with as much data as possible from 'source'.
|
||||
*sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'.
|
||||
New value is necessarily <= old value.
|
||||
return : Nb bytes written into 'dest' (necessarily <= targetDestSize)
|
||||
or 0 if compression fails
|
||||
*/
|
||||
int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize);
|
||||
|
||||
|
||||
/*
|
||||
|
@ -153,7 +166,6 @@ LZ4_decompress_fast() :
|
|||
*/
|
||||
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
|
||||
|
||||
|
||||
/*
|
||||
LZ4_decompress_safe_partial() :
|
||||
This function decompress a compressed block of size 'compressedSize' at position 'source'
|
||||
|
@ -172,7 +184,6 @@ int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedS
|
|||
/***********************************************
|
||||
* Streaming Compression Functions
|
||||
***********************************************/
|
||||
|
||||
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
|
||||
#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(long long))
|
||||
/*
|
||||
|
@ -188,7 +199,7 @@ typedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t;
|
|||
* LZ4_resetStream
|
||||
* Use this function to init an allocated LZ4_stream_t structure
|
||||
*/
|
||||
void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
|
||||
void LZ4_resetStream (LZ4_stream_t* streamPtr);
|
||||
|
||||
/*
|
||||
* LZ4_createStream will allocate and initialize an LZ4_stream_t structure
|
||||
|
@ -197,7 +208,7 @@ void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
|
|||
* They are more future proof, in case of a change of LZ4_stream_t size.
|
||||
*/
|
||||
LZ4_stream_t* LZ4_createStream(void);
|
||||
int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
|
||||
int LZ4_freeStream (LZ4_stream_t* streamPtr);
|
||||
|
||||
/*
|
||||
* LZ4_loadDict
|
||||
|
@ -206,32 +217,27 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
|
|||
* Loading a size of 0 is allowed.
|
||||
* Return : dictionary size, in bytes (necessarily <= 64 KB)
|
||||
*/
|
||||
int LZ4_loadDict (LZ4_stream_t* LZ4_streamPtr, const char* dictionary, int dictSize);
|
||||
int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
|
||||
|
||||
/*
|
||||
* LZ4_compress_continue
|
||||
* Compress data block 'source', using blocks compressed before as dictionary to improve compression ratio
|
||||
* Previous data blocks are assumed to still be present at their previous location.
|
||||
* dest buffer must be already allocated, and sized to at least LZ4_compressBound(inputSize)
|
||||
* LZ4_compress_fast_continue
|
||||
* Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio.
|
||||
* Important : Previous data blocks are assumed to still be present and unmodified !
|
||||
* 'dst' buffer must be already allocated.
|
||||
* If maxDstSize >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
|
||||
* If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function returns a zero.
|
||||
*/
|
||||
int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
|
||||
|
||||
/*
|
||||
* LZ4_compress_limitedOutput_continue
|
||||
* Same as before, but also specify a maximum target compressed size (maxOutputSize)
|
||||
* If objective cannot be met, compression exits, and returns a zero.
|
||||
*/
|
||||
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
|
||||
int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int maxDstSize, int acceleration);
|
||||
|
||||
/*
|
||||
* LZ4_saveDict
|
||||
* If previously compressed data block is not guaranteed to remain available at its memory location
|
||||
* save it into a safer place (char* safeBuffer)
|
||||
* Note : you don't need to call LZ4_loadDict() afterwards,
|
||||
* dictionary is immediately usable, you can therefore call again LZ4_compress_continue()
|
||||
* dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue()
|
||||
* Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error
|
||||
*/
|
||||
int LZ4_saveDict (LZ4_stream_t* LZ4_streamPtr, char* safeBuffer, int dictSize);
|
||||
int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize);
|
||||
|
||||
|
||||
/************************************************
|
||||
|
@ -266,8 +272,18 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti
|
|||
*_continue() :
|
||||
These decoding functions allow decompression of multiple blocks in "streaming" mode.
|
||||
Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)
|
||||
If this condition is not possible, save the relevant part of decoded data into a safe buffer,
|
||||
and indicate where is its new address using LZ4_setStreamDecode()
|
||||
In the case of a ring buffers, decoding buffer must be either :
|
||||
- Exactly same size as encoding buffer, with same update rule (block boundaries at same positions)
|
||||
In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB).
|
||||
- Larger than encoding buffer, by a minimum of maxBlockSize more bytes.
|
||||
maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block.
|
||||
In which case, encoding and decoding buffers do not need to be synchronized,
|
||||
and encoding ring buffer can have any size, including small ones ( < 64 KB).
|
||||
- _At least_ 64 KB + 8 bytes + maxBlockSize.
|
||||
In which case, encoding and decoding buffers do not need to be synchronized,
|
||||
and encoding ring buffer can have any size, including larger than decoding buffer.
|
||||
Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer,
|
||||
and indicate where it is saved using LZ4_setStreamDecode()
|
||||
*/
|
||||
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
|
||||
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
|
||||
|
@ -277,8 +293,8 @@ int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const ch
|
|||
Advanced decoding functions :
|
||||
*_usingDict() :
|
||||
These decoding functions work the same as
|
||||
a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()
|
||||
They are stand-alone and don't use nor update an LZ4_streamDecode_t structure.
|
||||
a combination of LZ4_setStreamDecode() followed by LZ4_decompress_x_continue()
|
||||
They are stand-alone. They don't need nor update an LZ4_streamDecode_t structure.
|
||||
*/
|
||||
int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
|
||||
int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
|
||||
|
@ -288,27 +304,55 @@ int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalS
|
|||
/**************************************
|
||||
* Obsolete Functions
|
||||
**************************************/
|
||||
/*
|
||||
Obsolete decompression functions
|
||||
These function names are deprecated and should no longer be used.
|
||||
They are only provided here for compatibility with older user programs.
|
||||
/* Deprecate Warnings */
|
||||
/* Should these warnings messages be a problem,
|
||||
it is generally possible to disable them,
|
||||
with -Wno-deprecated-declarations for gcc
|
||||
or _CRT_SECURE_NO_WARNINGS in Visual for example.
|
||||
You can also define LZ4_DEPRECATE_WARNING_DEFBLOCK. */
|
||||
#ifndef LZ4_DEPRECATE_WARNING_DEFBLOCK
|
||||
# define LZ4_DEPRECATE_WARNING_DEFBLOCK
|
||||
# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
|
||||
# if (LZ4_GCC_VERSION >= 405) || defined(__clang__)
|
||||
# define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
|
||||
# elif (LZ4_GCC_VERSION >= 301)
|
||||
# define LZ4_DEPRECATED(message) __attribute__((deprecated))
|
||||
# elif defined(_MSC_VER)
|
||||
# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
|
||||
# else
|
||||
# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
|
||||
# define LZ4_DEPRECATED(message)
|
||||
# endif
|
||||
#endif /* LZ4_DEPRECATE_WARNING_DEFBLOCK */
|
||||
|
||||
/* Obsolete compression functions */
|
||||
/* These functions are planned to start generate warnings by r131 approximately */
|
||||
int LZ4_compress (const char* source, char* dest, int sourceSize);
|
||||
int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
|
||||
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
|
||||
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
|
||||
int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
|
||||
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
|
||||
|
||||
/* Obsolete decompression functions */
|
||||
/* These function names are completely deprecated and must no longer be used.
|
||||
They are only provided here for compatibility with older programs.
|
||||
- LZ4_uncompress is the same as LZ4_decompress_fast
|
||||
- LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe
|
||||
These function prototypes are now disabled; uncomment them if you really need them.
|
||||
It is highly recommended to stop using these functions and migrate to newer ones */
|
||||
These function prototypes are now disabled; uncomment them only if you really need them.
|
||||
It is highly recommended to stop using these prototypes and migrate to maintained ones */
|
||||
/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */
|
||||
/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */
|
||||
|
||||
|
||||
/* Obsolete streaming functions; use new streaming interface whenever possible */
|
||||
void* LZ4_create (const char* inputBuffer);
|
||||
int LZ4_sizeofStreamState(void);
|
||||
int LZ4_resetStreamState(void* state, const char* inputBuffer);
|
||||
char* LZ4_slideInputBuffer (void* state);
|
||||
LZ4_DEPRECATED("use LZ4_createStream() instead") void* LZ4_create (char* inputBuffer);
|
||||
LZ4_DEPRECATED("use LZ4_createStream() instead") int LZ4_sizeofStreamState(void);
|
||||
LZ4_DEPRECATED("use LZ4_resetStream() instead") int LZ4_resetStreamState(void* state, char* inputBuffer);
|
||||
LZ4_DEPRECATED("use LZ4_saveDict() instead") char* LZ4_slideInputBuffer (void* state);
|
||||
|
||||
/* Obsolete streaming decoding functions */
|
||||
int LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int compressedSize, int maxOutputSize);
|
||||
int LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int originalSize);
|
||||
LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize);
|
||||
LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);
|
||||
|
||||
|
||||
#if defined (__cplusplus)
|
||||
|
|
|
@ -112,12 +112,12 @@ extern "C" {
|
|||
* This is more or less the max that can be fit in a given packet (with
|
||||
* fragmentation) and only one address per hop.
|
||||
*/
|
||||
#define ZT_CIRCUIT_TEST_MAX_HOPS 512
|
||||
#define ZT_CIRCUIT_TEST_MAX_HOPS 256
|
||||
|
||||
/**
|
||||
* Maximum number of addresses per hop in a circuit test
|
||||
*/
|
||||
#define ZT_CIRCUIT_TEST_MAX_HOP_BREADTH 256
|
||||
#define ZT_CIRCUIT_TEST_MAX_HOP_BREADTH 8
|
||||
|
||||
/**
|
||||
* Maximum number of cluster members (and max member ID plus one)
|
||||
|
|
|
@ -90,6 +90,7 @@ namespace {
|
|||
ZT_Node *node,
|
||||
void *userData,
|
||||
uint64_t nwid,
|
||||
void **,
|
||||
enum ZT_VirtualNetworkConfigOperation operation,
|
||||
const ZT_VirtualNetworkConfig *config)
|
||||
{
|
||||
|
@ -137,6 +138,7 @@ namespace {
|
|||
void VirtualNetworkFrameFunctionCallback(ZT_Node *node,
|
||||
void *userData,
|
||||
uint64_t nwid,
|
||||
void**,
|
||||
uint64_t sourceMac,
|
||||
uint64_t destMac,
|
||||
unsigned int etherType,
|
||||
|
@ -609,6 +611,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
|
|||
&WirePacketSendFunction,
|
||||
&VirtualNetworkFrameFunctionCallback,
|
||||
&VirtualNetworkConfigFunctionCallback,
|
||||
NULL,
|
||||
&EventCallback);
|
||||
|
||||
if(rc != ZT_RESULT_OK)
|
||||
|
@ -995,7 +998,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_join(
|
|||
|
||||
uint64_t nwid = (uint64_t)in_nwid;
|
||||
|
||||
ZT_ResultCode rc = ZT_Node_join(node, nwid);
|
||||
ZT_ResultCode rc = ZT_Node_join(node, nwid, NULL);
|
||||
|
||||
return createResultObject(env, rc);
|
||||
}
|
||||
|
@ -1018,7 +1021,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_leave(
|
|||
|
||||
uint64_t nwid = (uint64_t)in_nwid;
|
||||
|
||||
ZT_ResultCode rc = ZT_Node_leave(node, nwid);
|
||||
ZT_ResultCode rc = ZT_Node_leave(node, nwid, NULL);
|
||||
|
||||
return createResultObject(env, rc);
|
||||
}
|
||||
|
|
14
make-mac.mk
14
make-mac.mk
|
@ -79,6 +79,18 @@ one: $(OBJS) service/OneService.o one.o
|
|||
$(CODESIGN) -f -s $(CODESIGN_APP_CERT) zerotier-one
|
||||
$(CODESIGN) -vvv zerotier-one
|
||||
|
||||
netcon: $(OBJS)
|
||||
rm -f *.o
|
||||
# Need to selectively rebuild one.cpp and OneService.cpp with ZT_SERVICE_NETCON and ZT_ONE_NO_ROOT_CHECK defined, and also NetconEthernetTap
|
||||
$(CXX) $(CXXFLAGS) $(LDFLAGS) -DZT_SERVICE_NETCON -DZT_ONE_NO_ROOT_CHECK -Iext/lwip/src/include -Iext/lwip/src/include/ipv4 -Iext/lwip/src/include/ipv6 -o zerotier-netcon-service $(OBJS) service/OneService.cpp netcon/NetconEthernetTap.cpp one.cpp -x c netcon/RPC.c $(LDLIBS) -ldl
|
||||
# Build netcon/liblwip.so which must be placed in ZT home for zerotier-netcon-service to work
|
||||
cd netcon ; make -f make-liblwip.mk
|
||||
# Use gcc not clang to build standalone intercept library since gcc is typically used for libc and we want to ensure maximal ABI compatibility
|
||||
cd netcon ; gcc -O2 -Wall -std=c99 -fPIC -fno-common -dynamiclib -flat_namespace -DVERBOSE -D_GNU_SOURCE -DNETCON_INTERCEPT -I. -nostdlib -shared -o libzerotierintercept.so Intercept.c RPC.c -ldl
|
||||
cp netcon/libzerotierintercept.so libzerotierintercept.so
|
||||
ln -sf zerotier-netcon-service zerotier-cli
|
||||
ln -sf zerotier-netcon-service zerotier-idtool
|
||||
|
||||
selftest: $(OBJS) selftest.o
|
||||
$(CXX) $(CXXFLAGS) -o zerotier-selftest selftest.o $(OBJS) $(LIBS)
|
||||
$(STRIP) zerotier-selftest
|
||||
|
@ -97,7 +109,7 @@ official: FORCE
|
|||
make ZT_OFFICIAL_RELEASE=1 mac-dist-pkg
|
||||
|
||||
clean:
|
||||
rm -rf *.dSYM build-* *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli ZeroTierOneInstaller-* mkworld
|
||||
rm -rf netcon/*.so *.dSYM build-* *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli ZeroTierOneInstaller-* mkworld
|
||||
|
||||
# For those building from source -- installs signed binary tap driver in system ZT home
|
||||
install-mac-tap: FORCE
|
||||
|
|
|
@ -38,20 +38,25 @@
|
|||
#include <sys/time.h>
|
||||
#include <pwd.h>
|
||||
#include <errno.h>
|
||||
#include <linux/errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <netdb.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/poll.h>
|
||||
#include <sys/un.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/resource.h>
|
||||
#include <linux/net.h> /* for NPROTO */
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <linux/errno.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <linux/net.h> /* for NPROTO */
|
||||
#endif
|
||||
|
||||
#if defined(__linux__)
|
||||
#define SOCK_MAX (SOCK_PACKET + 1)
|
||||
#endif
|
||||
#define SOCK_TYPE_MASK 0xf
|
||||
|
||||
#include "Intercept.h"
|
||||
|
@ -92,6 +97,11 @@ static int connected_to_service(int sockfd)
|
|||
static int set_up_intercept()
|
||||
{
|
||||
if (!realconnect) {
|
||||
|
||||
#if defined(__linux__)
|
||||
realaccept4 = dlsym(RTLD_NEXT, "accept4");
|
||||
realsyscall = dlsym(RTLD_NEXT, "syscall");
|
||||
#endif
|
||||
realconnect = dlsym(RTLD_NEXT, "connect");
|
||||
realbind = dlsym(RTLD_NEXT, "bind");
|
||||
realaccept = dlsym(RTLD_NEXT, "accept");
|
||||
|
@ -100,9 +110,7 @@ static int set_up_intercept()
|
|||
realbind = dlsym(RTLD_NEXT, "bind");
|
||||
realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
|
||||
realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
|
||||
realaccept4 = dlsym(RTLD_NEXT, "accept4");
|
||||
realclose = dlsym(RTLD_NEXT, "close");
|
||||
realsyscall = dlsym(RTLD_NEXT, "syscall");
|
||||
realgetsockname = dlsym(RTLD_NEXT, "getsockname");
|
||||
}
|
||||
if (!netpath) {
|
||||
|
@ -127,10 +135,12 @@ int setsockopt(SETSOCKOPT_SIG)
|
|||
return realsetsockopt(socket, level, option_name, option_value, option_len);
|
||||
|
||||
dwr(MSG_DEBUG,"setsockopt(%d)\n", socket);
|
||||
#if defined(__linux__)
|
||||
if(level == SOL_IPV6 && option_name == IPV6_V6ONLY)
|
||||
return 0;
|
||||
if(level == SOL_IP && (option_name == IP_TTL || option_name == IP_TOS))
|
||||
return 0;
|
||||
#endif
|
||||
if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE))
|
||||
return 0;
|
||||
if(realsetsockopt(socket, level, option_name, option_value, option_len) < 0)
|
||||
|
@ -169,13 +179,16 @@ int socket(SOCKET_SIG)
|
|||
|
||||
dwr(MSG_DEBUG,"socket():\n");
|
||||
/* Check that type makes sense */
|
||||
#if defined(__linux__)
|
||||
int flags = socket_type & ~SOCK_TYPE_MASK;
|
||||
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
socket_type &= SOCK_TYPE_MASK;
|
||||
/* Check protocol is in range */
|
||||
#if defined(__linux__)
|
||||
if (socket_family < 0 || socket_family >= NPROTO){
|
||||
errno = EAFNOSUPPORT;
|
||||
return -1;
|
||||
|
@ -184,9 +197,12 @@ int socket(SOCKET_SIG)
|
|||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
/* TODO: detect ENFILE condition */
|
||||
if(socket_family == AF_LOCAL
|
||||
#if defined(__linux__)
|
||||
|| socket_family == AF_NETLINK
|
||||
#endif
|
||||
|| socket_family == AF_UNIX) {
|
||||
int err = realsocket(socket_family, socket_type, protocol);
|
||||
dwr(MSG_DEBUG,"realsocket() = %d\n", err);
|
||||
|
@ -244,24 +260,30 @@ int connect(CONNECT_SIG)
|
|||
errno = ENOTSOCK;
|
||||
return -1;
|
||||
}
|
||||
#if defined(__linux__)
|
||||
/* Check family */
|
||||
if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
|
||||
errno = EAFNOSUPPORT;
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
/* make sure we don't touch any standard outputs */
|
||||
if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO)
|
||||
return(realconnect(__fd, __addr, __len));
|
||||
|
||||
if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
|
||||
#if defined(__linux__)
|
||||
|| connaddr->sin_family == PF_NETLINK
|
||||
|| connaddr->sin_family == AF_NETLINK
|
||||
#endif
|
||||
|| connaddr->sin_family == AF_UNIX)) {
|
||||
return realconnect(__fd, __addr, __len);
|
||||
}
|
||||
/* Assemble and send RPC */
|
||||
struct connect_st rpc_st;
|
||||
#if defined(__linux__)
|
||||
rpc_st.__tid = syscall(SYS_gettid);
|
||||
#endif
|
||||
rpc_st.__fd = __fd;
|
||||
memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr_storage));
|
||||
memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
|
||||
|
@ -300,7 +322,9 @@ int bind(BIND_SIG)
|
|||
connaddr = (struct sockaddr_in *)addr;
|
||||
|
||||
if(connaddr->sin_family == AF_LOCAL
|
||||
#if defined(__linux__)
|
||||
|| connaddr->sin_family == AF_NETLINK
|
||||
#endif
|
||||
|| connaddr->sin_family == AF_UNIX) {
|
||||
int err = realbind(sockfd, addr, addrlen);
|
||||
dwr(MSG_DEBUG,"realbind, err = %d\n", err);
|
||||
|
@ -317,7 +341,9 @@ int bind(BIND_SIG)
|
|||
/* Assemble and send RPC */
|
||||
struct bind_st rpc_st;
|
||||
rpc_st.sockfd = sockfd;
|
||||
#if defined(__linux__)
|
||||
rpc_st.__tid = syscall(SYS_gettid);
|
||||
#endif
|
||||
memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr_storage));
|
||||
memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
|
||||
return rpc_send_command(netpath, RPC_BIND, sockfd, &rpc_st, sizeof(struct bind_st));
|
||||
|
@ -328,6 +354,7 @@ int bind(BIND_SIG)
|
|||
------------------------------------------------------------------------------*/
|
||||
|
||||
/* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
|
||||
#if defined(__linux__)
|
||||
int accept4(ACCEPT4_SIG)
|
||||
{
|
||||
dwr(MSG_DEBUG,"accept4(%d):\n", sockfd);
|
||||
|
@ -337,6 +364,7 @@ int accept4(ACCEPT4_SIG)
|
|||
fcntl(sockfd, F_SETFL, O_NONBLOCK);
|
||||
return accept(sockfd, addr, addrlen);
|
||||
}
|
||||
#endif
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
----------------------------------- accept() -----------------------------------
|
||||
|
@ -442,7 +470,9 @@ int listen(LISTEN_SIG)
|
|||
struct listen_st rpc_st;
|
||||
rpc_st.sockfd = sockfd;
|
||||
rpc_st.backlog = backlog;
|
||||
#if defined(__linux__)
|
||||
rpc_st.__tid = syscall(SYS_gettid);
|
||||
#endif
|
||||
return rpc_send_command(netpath, RPC_LISTEN, sockfd, &rpc_st, sizeof(struct listen_st));
|
||||
}
|
||||
|
||||
|
@ -502,6 +532,7 @@ int getsockname(GETSOCKNAME_SIG)
|
|||
------------------------------------ syscall() ---------------------------------
|
||||
------------------------------------------------------------------------------*/
|
||||
|
||||
#if defined(__linux__)
|
||||
long syscall(SYSCALL_SIG)
|
||||
{
|
||||
va_list ap;
|
||||
|
@ -542,3 +573,4 @@ long syscall(SYSCALL_SIG)
|
|||
#endif
|
||||
return realsyscall(number,a,b,c,d,e,f);
|
||||
}
|
||||
#endif
|
|
@ -25,12 +25,17 @@
|
|||
* LLC. Start here: http://www.zerotier.com/
|
||||
*/
|
||||
|
||||
|
||||
#ifndef _INTERCEPT_H
|
||||
#define _INTERCEPT_H 1
|
||||
|
||||
#include <sys/socket.h>
|
||||
|
||||
|
||||
#if defined(__linux__)
|
||||
#define ACCEPT4_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags
|
||||
#define SYSCALL_SIG long number, ...
|
||||
#endif
|
||||
|
||||
#define CLOSE_SIG int fd
|
||||
#define READ_SIG int __fd, void *__buf, size_t __nbytes
|
||||
#define BIND_SIG int sockfd, const struct sockaddr *addr, socklen_t addrlen
|
||||
|
@ -38,7 +43,6 @@
|
|||
#define WRITE_SIG int __fd, const void *__buf, size_t __n
|
||||
#define LISTEN_SIG int sockfd, int backlog
|
||||
#define SOCKET_SIG int socket_family, int socket_type, int protocol
|
||||
#define ACCEPT4_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags
|
||||
#define ACCEPT_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen
|
||||
#define SHUTDOWN_SIG int socket, int how
|
||||
#define CONNECT_SOCKARG struct sockaddr *
|
||||
|
@ -47,12 +51,17 @@
|
|||
#define DAEMON_SIG int nochdir, int noclose
|
||||
#define SETSOCKOPT_SIG int socket, int level, int option_name, const void *option_value, socklen_t option_len
|
||||
#define GETSOCKOPT_SIG int sockfd, int level, int optname, void *optval, socklen_t *optlen
|
||||
#define SYSCALL_SIG long number, ...
|
||||
#define CLONE_SIG int (*fn)(void *), void *child_stack, int flags, void *arg, ...
|
||||
#define GETSOCKNAME_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen
|
||||
#define DUP2_SIG int oldfd, int newfd
|
||||
#define DUP3_SIG int oldfd, int newfd, int flags
|
||||
|
||||
|
||||
#if defined(__linux__)
|
||||
int accept4(ACCEPT4_SIG);
|
||||
long syscall(SYSCALL_SIG);
|
||||
#endif
|
||||
|
||||
void my_init(void);
|
||||
int connect(CONNECT_SIG);
|
||||
int bind(BIND_SIG);
|
||||
|
@ -61,14 +70,17 @@ int listen(LISTEN_SIG);
|
|||
int socket(SOCKET_SIG);
|
||||
int setsockopt(SETSOCKOPT_SIG);
|
||||
int getsockopt(GETSOCKOPT_SIG);
|
||||
int accept4(ACCEPT4_SIG);
|
||||
long syscall(SYSCALL_SIG);
|
||||
int close(CLOSE_SIG);
|
||||
int clone(CLONE_SIG);
|
||||
int dup2(DUP2_SIG);
|
||||
int dup3(DUP3_SIG);
|
||||
int getsockname(GETSOCKNAME_SIG);
|
||||
|
||||
#if defined(__linux__)
|
||||
static int (*realaccept4)(ACCEPT4_SIG) = 0;
|
||||
static long (*realsyscall)(SYSCALL_SIG) = 0;
|
||||
#endif
|
||||
|
||||
static int (*realconnect)(CONNECT_SIG) = 0;
|
||||
static int (*realbind)(BIND_SIG) = 0;
|
||||
static int (*realaccept)(ACCEPT_SIG) = 0;
|
||||
|
@ -76,8 +88,6 @@ static int (*reallisten)(LISTEN_SIG) = 0;
|
|||
static int (*realsocket)(SOCKET_SIG) = 0;
|
||||
static int (*realsetsockopt)(SETSOCKOPT_SIG) = 0;
|
||||
static int (*realgetsockopt)(GETSOCKOPT_SIG) = 0;
|
||||
static int (*realaccept4)(ACCEPT4_SIG) = 0;
|
||||
static long (*realsyscall)(SYSCALL_SIG) = 0;
|
||||
static int (*realclose)(CLOSE_SIG) = 0;
|
||||
static int (*realgetsockname)(GETSOCKNAME_SIG) = 0;
|
||||
|
||||
|
|
|
@ -132,7 +132,13 @@ public:
|
|||
LWIPStack(const char* path) :
|
||||
_libref(NULL)
|
||||
{
|
||||
|
||||
#if defined(__linux__)
|
||||
_libref = dlmopen(LM_ID_NEWLM, path, RTLD_NOW);
|
||||
#elif defined(__APPLE__)
|
||||
_libref = dlopen(path, RTLD_NOW);
|
||||
#endif
|
||||
|
||||
if(_libref == NULL)
|
||||
printf("dlerror(): %s\n", dlerror());
|
||||
|
||||
|
|
|
@ -70,6 +70,22 @@ The intercept library does nothing unless the *ZT\_NC\_NETWORK* environment vari
|
|||
|
||||
Unlike *zerotier-one*, *zerotier-netcon-service* does not need to be run with root privileges and will not modify the host's network configuration in any way. It can be run alongside *zerotier-one* on the same host with no ill effect, though this can be confusing since you'll have to remember the difference between "real" host interfaces (tun/tap) and network containerized endpoints. The latter are completely unknown to the kernel and will not show up in *ifconfig*.
|
||||
|
||||
# Linking into an application on Mac OSX
|
||||
|
||||
Example:
|
||||
|
||||
gcc myapp.c -o myapp libzerotierintercept.so
|
||||
export ZT_NC_NETWORK=/tmp/netcon-test-home/nc_8056c2e21c000001
|
||||
|
||||
Start service
|
||||
|
||||
./zerotier-netcon-service -d -p8000 /tmp/netcon-test-home
|
||||
|
||||
Run application
|
||||
|
||||
./myapp
|
||||
|
||||
|
||||
# Starting the Network Containers Service
|
||||
|
||||
You don't need Docker or any other container engine to try Network Containers. A simple test can be performed in user space (no root) in your own home directory.
|
||||
|
@ -154,9 +170,11 @@ Results will be written to the *netcon/docker-test/_results/* directory which is
|
|||
|
||||
To run unit tests:
|
||||
|
||||
1) Set up your own network at [https://my.zerotier.com/](https://my.zerotier.com/). For our example we'll just use the Earth network (8056c2e21c000001). Use its network id as follows:
|
||||
1) Disable SELinux. This is so the containers can use a shared volume to exchange MD5 sums and address information.
|
||||
|
||||
2) Generate two pairs of identity keys. Each public/private pair will be used by the *netcon* and *monitor* containers:
|
||||
2) Set up your own network at [https://my.zerotier.com/](https://my.zerotier.com/). For our example we'll just use the Earth network (8056c2e21c000001). Use its network id as follows:
|
||||
|
||||
3) Generate two pairs of identity keys. Each public/private pair will be used by the *netcon* and *monitor* containers:
|
||||
|
||||
mkdir -p /tmp/netcon_first
|
||||
cp -f ./netcon/liblwip.so /tmp/netcon_first
|
||||
|
@ -176,7 +194,7 @@ To run unit tests:
|
|||
./zerotier-cli -D/tmp/netcon_second join 8056c2e21c000001
|
||||
kill `cat /tmp/netcon_second/zerotier-one.pid`
|
||||
|
||||
3) Copy the identity files to your *docker-test* directory. Names will be altered during copy step so the dockerfiles know which identities to use for each image/container:
|
||||
4) Copy the identity files to your *docker-test* directory. Names will be altered during copy step so the dockerfiles know which identities to use for each image/container:
|
||||
|
||||
cp /tmp/netcon_first/identity.public ./netcon/docker-test/netcon_identity.public
|
||||
cp /tmp/netcon_first/identity.secret ./netcon/docker-test/netcon_identity.secret
|
||||
|
@ -185,7 +203,7 @@ To run unit tests:
|
|||
cp /tmp/netcon_second/identity.secret ./netcon/docker-test/monitor_identity.secret
|
||||
|
||||
|
||||
4) Place a blank network config file in the *netcon/docker-test* directory (e.g. "8056c2e21c000001.conf")
|
||||
5) Place a blank network config file in the *netcon/docker-test* directory (e.g. "8056c2e21c000001.conf")
|
||||
- This will be used to inform test-specific scripts what network to use for testing
|
||||
|
||||
After you've created your network and placed its blank config file in *netcon/docker-test* run the following to perform unit tests for httpd:
|
||||
|
|
12
netcon/RPC.c
12
netcon/RPC.c
|
@ -3,7 +3,10 @@
|
|||
#include <sys/un.h>
|
||||
#include <pthread.h>
|
||||
#include <errno.h>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <sys/syscall.h>
|
||||
#endif
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <dlfcn.h>
|
||||
|
@ -131,19 +134,22 @@ int rpc_send_command(char *path, int cmd, int forfd, void *data, int len)
|
|||
memcpy(&cmdbuf[CANARY_IDX], &canary_num, CANARY_SZ);
|
||||
memcpy(&cmdbuf[STRUCT_IDX], data, len);
|
||||
|
||||
#ifdef VERBOSE
|
||||
#if defined(VERBOSE)
|
||||
rpc_count++;
|
||||
memset(metabuf, 0, BUF_SZ);
|
||||
#if defined(__linux__)
|
||||
pid_t pid = syscall(SYS_getpid);
|
||||
pid_t tid = syscall(SYS_gettid);
|
||||
rpc_count++;
|
||||
#endif
|
||||
char timestring[20];
|
||||
time_t timestamp;
|
||||
timestamp = time(NULL);
|
||||
strftime(timestring, sizeof(timestring), "%H:%M:%S", localtime(×tamp));
|
||||
memcpy(metabuf, RPC_PHRASE, RPC_PHRASE_SZ); // Write signal phrase
|
||||
|
||||
#if defined(__linux__)
|
||||
memcpy(&metabuf[IDX_PID], &pid, sizeof(pid_t) ); /* pid */
|
||||
memcpy(&metabuf[IDX_TID], &tid, sizeof(pid_t) ); /* tid */
|
||||
#endif
|
||||
memcpy(&metabuf[IDX_COUNT], &rpc_count, sizeof(rpc_count) ); /* rpc_count */
|
||||
memcpy(&metabuf[IDX_TIME], ×tring, 20 ); /* timestamp */
|
||||
#endif
|
||||
|
|
|
@ -18,7 +18,7 @@ find . -mindepth 2 -maxdepth 2 -type d | while read testdir; do
|
|||
continue
|
||||
fi
|
||||
|
||||
echo "*** Building: '$testdir'..."
|
||||
echo "\n\n\n*** Building: '$testdir'..."
|
||||
rm _results/*.tmp
|
||||
|
||||
# Stage scripts
|
||||
|
|
|
@ -4,7 +4,7 @@ MAINTAINER https://www.zerotier.com/
|
|||
|
||||
# Install apps
|
||||
RUN yum -y update
|
||||
RUN yum -y install httpd-2.4.17-3.fc23.x86_64
|
||||
RUN yum -y install darkhttpd-1.11
|
||||
RUN yum clean all
|
||||
|
||||
EXPOSE 9993/udp 80/udp
|
|
@ -0,0 +1,46 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile
|
||||
bigfile_size=10M # size of file we want to use for the test
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test: ' "$test_name"
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
|
||||
done
|
||||
echo '--- Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Writing address to ' "$address_file"
|
||||
echo $virtip4 > "$address_file"
|
||||
|
||||
# --- Test section ---
|
||||
# Generate large random file for transfer test, share md5sum for monitor container to check
|
||||
echo '*** Generating ' "$bigfile_size" ' file'
|
||||
dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
|
||||
md5sum < "$bigfile_name" > "$tx_md5sumfile"
|
||||
echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
|
||||
|
||||
echo '*** Starting application...'
|
||||
sleep 0.5
|
||||
|
||||
export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
|
||||
export LD_PRELOAD=./libzerotierintercept.so
|
||||
darkhttpd /
|
|
@ -0,0 +1,24 @@
|
|||
# ZT Network Containers Test Monitor
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
EXPOSE 9993/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD monitor_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
ADD zerotier-one /
|
||||
ADD zerotier-cli /
|
||||
|
||||
# Start ZeroTier-One
|
||||
ADD monitor_entrypoint.sh /monitor_entrypoint.sh
|
||||
RUN chmod -v +x /monitor_entrypoint.sh
|
||||
CMD ["./monitor_entrypoint.sh"]
|
|
@ -0,0 +1,80 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
netcon_wait_time=35 # wait for test container to come online
|
||||
app_timeout_time=25 # app-specific timeout
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
fail=FAIL. # appended to result file in event of failure
|
||||
ok=OK. # appended to result file in event of success
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile # large, random test transfer file
|
||||
rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test Monitor'
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-one -d -U -p9993 >>/tmp/zerotier-one.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
done
|
||||
echo '*** Starting Test...'
|
||||
echo '*** Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
|
||||
sleep "$netcon_wait_time"s
|
||||
ncvirtip=$(<$address_file)
|
||||
|
||||
|
||||
# --- Test section ---
|
||||
echo '*** Curling from intercepted server at' $ncvirtip
|
||||
rm -rf "$file_path"*."$file_base"
|
||||
touch "$bigfile_name"
|
||||
|
||||
# Perform test
|
||||
# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
|
||||
# Large transfer test
|
||||
curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
|
||||
|
||||
# Check md5
|
||||
md5sum < "$bigfile_name" > "$rx_md5sumfile"
|
||||
rx_md5sum=$(<$rx_md5sumfile)
|
||||
tx_md5sum=$(<$tx_md5sumfile)
|
||||
|
||||
echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
|
||||
|
||||
if [ "$rx_md5sum" != "$tx_md5sum" ];
|
||||
then
|
||||
echo 'MD5 FAIL'
|
||||
touch "$file_path$fail$test_name.txt"
|
||||
printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
|
||||
else
|
||||
echo 'MD5 OK'
|
||||
touch "$file_path$ok$test_name.txt"
|
||||
printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
|
||||
cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
# ZT Network Containers Test
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
# Install apps
|
||||
RUN yum -y update
|
||||
RUN yum -y install httpd-2.4.18-1.fc23.x86_64
|
||||
RUN yum clean all
|
||||
|
||||
EXPOSE 9993/udp 80/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD netcon_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
# Install syscall intercept library
|
||||
ADD zerotier-intercept /
|
||||
ADD libzerotierintercept.so /
|
||||
RUN cp libzerotierintercept.so lib/libzerotierintercept.so
|
||||
RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
|
||||
RUN /usr/bin/install -c zerotier-intercept /usr/bin
|
||||
|
||||
ADD zerotier-cli /
|
||||
ADD zerotier-netcon-service /
|
||||
|
||||
# Install test scripts
|
||||
ADD netcon_entrypoint.sh /netcon_entrypoint.sh
|
||||
RUN chmod -v +x /netcon_entrypoint.sh
|
||||
|
||||
# Start ZeroTier-One
|
||||
CMD ["./netcon_entrypoint.sh"]
|
24
netcon/docker-test/python/python/monitor_dockerfile
Normal file
24
netcon/docker-test/python/python/monitor_dockerfile
Normal file
|
@ -0,0 +1,24 @@
|
|||
# ZT Network Containers Test Monitor
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
EXPOSE 9993/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD monitor_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
ADD zerotier-one /
|
||||
ADD zerotier-cli /
|
||||
|
||||
# Start ZeroTier-One
|
||||
ADD monitor_entrypoint.sh /monitor_entrypoint.sh
|
||||
RUN chmod -v +x /monitor_entrypoint.sh
|
||||
CMD ["./monitor_entrypoint.sh"]
|
80
netcon/docker-test/python/python/monitor_entrypoint.sh
Normal file
80
netcon/docker-test/python/python/monitor_entrypoint.sh
Normal file
|
@ -0,0 +1,80 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
netcon_wait_time=35 # wait for test container to come online
|
||||
app_timeout_time=25 # app-specific timeout
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
fail=FAIL. # appended to result file in event of failure
|
||||
ok=OK. # appended to result file in event of success
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile # large, random test transfer file
|
||||
rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test Monitor'
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-one -d -U -p9993 >>/tmp/zerotier-one.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
done
|
||||
echo '*** Starting Test...'
|
||||
echo '*** Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
|
||||
sleep "$netcon_wait_time"s
|
||||
ncvirtip=$(<$address_file)
|
||||
|
||||
|
||||
# --- Test section ---
|
||||
echo '*** Curling from intercepted server at' $ncvirtip
|
||||
rm -rf "$file_path"*."$file_base"
|
||||
touch "$bigfile_name"
|
||||
|
||||
# Perform test
|
||||
# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
|
||||
# Large transfer test
|
||||
curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
|
||||
|
||||
# Check md5
|
||||
md5sum < "$bigfile_name" > "$rx_md5sumfile"
|
||||
rx_md5sum=$(<$rx_md5sumfile)
|
||||
tx_md5sum=$(<$tx_md5sumfile)
|
||||
|
||||
echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
|
||||
|
||||
if [ "$rx_md5sum" != "$tx_md5sum" ];
|
||||
then
|
||||
echo 'MD5 FAIL'
|
||||
touch "$file_path$fail$test_name.txt"
|
||||
printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
|
||||
else
|
||||
echo 'MD5 OK'
|
||||
touch "$file_path$ok$test_name.txt"
|
||||
printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
|
||||
cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
38
netcon/docker-test/python/python/netcon_dockerfile
Normal file
38
netcon/docker-test/python/python/netcon_dockerfile
Normal file
|
@ -0,0 +1,38 @@
|
|||
# ZT Network Containers Test
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
# Install apps
|
||||
RUN yum -y update
|
||||
RUN yum -y install python
|
||||
RUN yum clean all
|
||||
|
||||
EXPOSE 9993/udp 80/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD netcon_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
# Install syscall intercept library
|
||||
ADD zerotier-intercept /
|
||||
ADD libzerotierintercept.so /
|
||||
RUN cp libzerotierintercept.so lib/libzerotierintercept.so
|
||||
RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
|
||||
RUN /usr/bin/install -c zerotier-intercept /usr/bin
|
||||
|
||||
ADD zerotier-cli /
|
||||
ADD zerotier-netcon-service /
|
||||
|
||||
# Install test scripts
|
||||
ADD netcon_entrypoint.sh /netcon_entrypoint.sh
|
||||
RUN chmod -v +x /netcon_entrypoint.sh
|
||||
|
||||
# Start ZeroTier-One
|
||||
CMD ["./netcon_entrypoint.sh"]
|
46
netcon/docker-test/python/python/netcon_entrypoint.sh
Normal file
46
netcon/docker-test/python/python/netcon_entrypoint.sh
Normal file
|
@ -0,0 +1,46 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile
|
||||
bigfile_size=10M # size of file we want to use for the test
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test: ' "$test_name"
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
|
||||
done
|
||||
echo '--- Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Writing address to ' "$address_file"
|
||||
echo $virtip4 > "$address_file"
|
||||
|
||||
# --- Test section ---
|
||||
# Generate large random file for transfer test, share md5sum for monitor container to check
|
||||
echo '*** Generating ' "$bigfile_size" ' file'
|
||||
dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
|
||||
md5sum < "$bigfile_name" > "$tx_md5sumfile"
|
||||
echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
|
||||
|
||||
echo '*** Starting application...'
|
||||
sleep 0.5
|
||||
|
||||
export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
|
||||
export LD_PRELOAD=./libzerotierintercept.so
|
||||
python -m SimpleHTTPServer 80
|
24
netcon/docker-test/python/python3/monitor_dockerfile
Normal file
24
netcon/docker-test/python/python3/monitor_dockerfile
Normal file
|
@ -0,0 +1,24 @@
|
|||
# ZT Network Containers Test Monitor
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
EXPOSE 9993/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD monitor_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
ADD zerotier-one /
|
||||
ADD zerotier-cli /
|
||||
|
||||
# Start ZeroTier-One
|
||||
ADD monitor_entrypoint.sh /monitor_entrypoint.sh
|
||||
RUN chmod -v +x /monitor_entrypoint.sh
|
||||
CMD ["./monitor_entrypoint.sh"]
|
80
netcon/docker-test/python/python3/monitor_entrypoint.sh
Normal file
80
netcon/docker-test/python/python3/monitor_entrypoint.sh
Normal file
|
@ -0,0 +1,80 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
netcon_wait_time=35 # wait for test container to come online
|
||||
app_timeout_time=25 # app-specific timeout
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
fail=FAIL. # appended to result file in event of failure
|
||||
ok=OK. # appended to result file in event of success
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile # large, random test transfer file
|
||||
rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test Monitor'
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-one -d -U -p9993 >>/tmp/zerotier-one.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
done
|
||||
echo '*** Starting Test...'
|
||||
echo '*** Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
|
||||
sleep "$netcon_wait_time"s
|
||||
ncvirtip=$(<$address_file)
|
||||
|
||||
|
||||
# --- Test section ---
|
||||
echo '*** Curling from intercepted server at' $ncvirtip
|
||||
rm -rf "$file_path"*."$file_base"
|
||||
touch "$bigfile_name"
|
||||
|
||||
# Perform test
|
||||
# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
|
||||
# Large transfer test
|
||||
curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
|
||||
|
||||
# Check md5
|
||||
md5sum < "$bigfile_name" > "$rx_md5sumfile"
|
||||
rx_md5sum=$(<$rx_md5sumfile)
|
||||
tx_md5sum=$(<$tx_md5sumfile)
|
||||
|
||||
echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
|
||||
|
||||
if [ "$rx_md5sum" != "$tx_md5sum" ];
|
||||
then
|
||||
echo 'MD5 FAIL'
|
||||
touch "$file_path$fail$test_name.txt"
|
||||
printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
|
||||
else
|
||||
echo 'MD5 OK'
|
||||
touch "$file_path$ok$test_name.txt"
|
||||
printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
|
||||
cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
37
netcon/docker-test/python/python3/netcon_dockerfile
Normal file
37
netcon/docker-test/python/python3/netcon_dockerfile
Normal file
|
@ -0,0 +1,37 @@
|
|||
# ZT Network Containers Test
|
||||
FROM fedora:23
|
||||
MAINTAINER https://www.zerotier.com/
|
||||
|
||||
# Install apps
|
||||
RUN yum -y update
|
||||
RUN yum clean all
|
||||
|
||||
EXPOSE 9993/udp 80/udp
|
||||
|
||||
# Add ZT files
|
||||
RUN mkdir -p /var/lib/zerotier-one/networks.d
|
||||
ADD netcon_identity.public /var/lib/zerotier-one/identity.public
|
||||
ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
|
||||
ADD *.conf /var/lib/zerotier-one/networks.d/
|
||||
ADD *.conf /
|
||||
ADD *.name /
|
||||
|
||||
# Install LWIP library used by service
|
||||
ADD liblwip.so /var/lib/zerotier-one/liblwip.so
|
||||
|
||||
# Install syscall intercept library
|
||||
ADD zerotier-intercept /
|
||||
ADD libzerotierintercept.so /
|
||||
RUN cp libzerotierintercept.so lib/libzerotierintercept.so
|
||||
RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
|
||||
RUN /usr/bin/install -c zerotier-intercept /usr/bin
|
||||
|
||||
ADD zerotier-cli /
|
||||
ADD zerotier-netcon-service /
|
||||
|
||||
# Install test scripts
|
||||
ADD netcon_entrypoint.sh /netcon_entrypoint.sh
|
||||
RUN chmod -v +x /netcon_entrypoint.sh
|
||||
|
||||
# Start ZeroTier-One
|
||||
CMD ["./netcon_entrypoint.sh"]
|
46
netcon/docker-test/python/python3/netcon_entrypoint.sh
Normal file
46
netcon/docker-test/python/python3/netcon_entrypoint.sh
Normal file
|
@ -0,0 +1,46 @@
|
|||
#!/bin/bash
|
||||
|
||||
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
|
||||
|
||||
|
||||
# --- Test Parameters ---
|
||||
test_namefile=$(ls *.name)
|
||||
test_name="${test_namefile%.*}" # test network id
|
||||
nwconf=$(ls *.conf) # blank test network config file
|
||||
nwid="${nwconf%.*}" # test network id
|
||||
file_path=/opt/results/ # test result output file path (fs shared between host and containers)
|
||||
file_base="$test_name".txt # test result output file
|
||||
tmp_ext=.tmp # temporary filetype used for sharing test data between containers
|
||||
address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
|
||||
bigfile_name=bigfile
|
||||
bigfile_size=10M # size of file we want to use for the test
|
||||
tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
|
||||
|
||||
# --- Network Config ---
|
||||
echo '*** ZeroTier Network Containers Test: ' "$test_name"
|
||||
chown -R daemon /var/lib/zerotier-one
|
||||
chgrp -R daemon /var/lib/zerotier-one
|
||||
su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
|
||||
virtip4=""
|
||||
while [ -z "$virtip4" ]; do
|
||||
sleep 0.2
|
||||
virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
|
||||
dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
|
||||
done
|
||||
echo '--- Up and running at' $virtip4 ' on network: ' $nwid
|
||||
echo '*** Writing address to ' "$address_file"
|
||||
echo $virtip4 > "$address_file"
|
||||
|
||||
# --- Test section ---
|
||||
# Generate large random file for transfer test, share md5sum for monitor container to check
|
||||
echo '*** Generating ' "$bigfile_size" ' file'
|
||||
dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
|
||||
md5sum < "$bigfile_name" > "$tx_md5sumfile"
|
||||
echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
|
||||
|
||||
echo '*** Starting application...'
|
||||
sleep 0.5
|
||||
|
||||
export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
|
||||
export LD_PRELOAD=./libzerotierintercept.so
|
||||
python3 -m http.server 80
|
|
@ -33,6 +33,16 @@
|
|||
#include "Identity.hpp"
|
||||
#include "Utils.hpp"
|
||||
|
||||
/**
|
||||
* Default window of time for certificate agreement
|
||||
*
|
||||
* Right now we use time for 'revision' so this is the maximum time divergence
|
||||
* between two certs for them to agree. It comes out to five minutes, which
|
||||
* gives a lot of margin for error if the controller hiccups or its clock
|
||||
* drifts but causes de-authorized peers to fall off fast enough.
|
||||
*/
|
||||
#define ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA (ZT_NETWORK_AUTOCONF_DELAY * 5)
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
/**
|
||||
|
|
|
@ -47,22 +47,22 @@
|
|||
/**
|
||||
* Desired period between doPeriodicTasks() in milliseconds
|
||||
*/
|
||||
#define ZT_CLUSTER_PERIODIC_TASK_PERIOD 50
|
||||
#define ZT_CLUSTER_PERIODIC_TASK_PERIOD 20
|
||||
|
||||
/**
|
||||
* How often to flush outgoing message queues (maximum interval)
|
||||
*/
|
||||
#define ZT_CLUSTER_FLUSH_PERIOD 100
|
||||
#define ZT_CLUSTER_FLUSH_PERIOD ZT_CLUSTER_PERIODIC_TASK_PERIOD
|
||||
|
||||
/**
|
||||
* Maximum number of queued outgoing packets per sender address
|
||||
*/
|
||||
#define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 8
|
||||
#define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 16
|
||||
|
||||
/**
|
||||
* Expiration time for send queue entries
|
||||
*/
|
||||
#define ZT_CLUSTER_QUEUE_EXPIRATION 5000
|
||||
#define ZT_CLUSTER_QUEUE_EXPIRATION 3000
|
||||
|
||||
/**
|
||||
* Chunk size for allocating queue entries
|
||||
|
@ -85,11 +85,8 @@
|
|||
|
||||
/**
|
||||
* Max data per queue entry
|
||||
*
|
||||
* If we ever support larger transport MTUs this must be increased. The plus
|
||||
* 16 is just a small margin and has no special meaning.
|
||||
*/
|
||||
#define ZT_CLUSTER_SEND_QUEUE_DATA_MAX (ZT_UDP_DEFAULT_PAYLOAD_MTU + 16)
|
||||
#define ZT_CLUSTER_SEND_QUEUE_DATA_MAX 1500
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
|
|
|
@ -255,12 +255,17 @@
|
|||
/**
|
||||
* Delay between ordinary case pings of direct links
|
||||
*/
|
||||
#define ZT_PEER_DIRECT_PING_DELAY 90000
|
||||
#define ZT_PEER_DIRECT_PING_DELAY 60000
|
||||
|
||||
/**
|
||||
* Timeout for overall peer activity (measured from last receive)
|
||||
*/
|
||||
#define ZT_PEER_ACTIVITY_TIMEOUT ((ZT_PEER_DIRECT_PING_DELAY * 4) + ZT_PING_CHECK_INVERVAL)
|
||||
#define ZT_PEER_ACTIVITY_TIMEOUT 500000
|
||||
|
||||
/**
|
||||
* Timeout for path activity
|
||||
*/
|
||||
#define ZT_PATH_ACTIVITY_TIMEOUT ZT_PEER_ACTIVITY_TIMEOUT
|
||||
|
||||
/**
|
||||
* No answer timeout to trigger dead path detection
|
||||
|
|
|
@ -282,7 +282,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,SharedPtr<Peer> &peer
|
|||
}
|
||||
|
||||
if (externalSurfaceAddress)
|
||||
RR->sa->iam(id.address(),_remoteAddress,externalSurfaceAddress,RR->topology->isRoot(id),RR->node->now());
|
||||
RR->sa->iam(id.address(),_localAddress,_remoteAddress,externalSurfaceAddress,RR->topology->isRoot(id),RR->node->now());
|
||||
|
||||
Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
|
||||
outp.append((unsigned char)Packet::VERB_HELLO);
|
||||
|
@ -388,7 +388,7 @@ bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &p
|
|||
peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
|
||||
|
||||
if (externalSurfaceAddress)
|
||||
RR->sa->iam(peer->address(),_remoteAddress,externalSurfaceAddress,trusted,RR->node->now());
|
||||
RR->sa->iam(peer->address(),_localAddress,_remoteAddress,externalSurfaceAddress,trusted,RR->node->now());
|
||||
} break;
|
||||
|
||||
case Packet::VERB_WHOIS: {
|
||||
|
@ -934,7 +934,7 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha
|
|||
switch(addrType) {
|
||||
case 4: {
|
||||
InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
|
||||
if ( ((flags & 0x01) == 0) && (Path::isAddressValidForPath(a)) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
|
||||
if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
|
||||
if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
|
||||
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
|
||||
peer->sendHELLO(_localAddress,a,now);
|
||||
|
@ -945,7 +945,7 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha
|
|||
} break;
|
||||
case 6: {
|
||||
InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
|
||||
if ( ((flags & 0x01) == 0) && (Path::isAddressValidForPath(a)) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
|
||||
if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
|
||||
if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
|
||||
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
|
||||
peer->sendHELLO(_localAddress,a,now);
|
||||
|
@ -1016,8 +1016,9 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
|
|||
if (previousHopCredentialLength >= 1) {
|
||||
switch((*this)[ZT_PACKET_IDX_PAYLOAD + 31 + vlf]) {
|
||||
case 0x01: { // network certificate of membership for previous hop
|
||||
if (previousHopCom.deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 32 + vlf) != (previousHopCredentialLength - 1)) {
|
||||
TRACE("dropped CIRCUIT_TEST from %s(%s): previous hop COM invalid",source().toString().c_str(),_remoteAddress.toString().c_str());
|
||||
const unsigned int phcl = previousHopCom.deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 32 + vlf);
|
||||
if (phcl != (previousHopCredentialLength - 1)) {
|
||||
TRACE("dropped CIRCUIT_TEST from %s(%s): previous hop COM invalid (%u != %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),phcl,(previousHopCredentialLength - 1));
|
||||
return true;
|
||||
}
|
||||
} break;
|
||||
|
@ -1078,7 +1079,7 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
|
|||
Packet outp(originatorAddress,RR->identity.address(),Packet::VERB_CIRCUIT_TEST_REPORT);
|
||||
outp.append((uint64_t)timestamp);
|
||||
outp.append((uint64_t)testId);
|
||||
outp.append((uint64_t)now);
|
||||
outp.append((uint64_t)0); // field reserved for future use
|
||||
outp.append((uint8_t)ZT_VENDOR_ZEROTIER);
|
||||
outp.append((uint8_t)ZT_PROTO_VERSION);
|
||||
outp.append((uint8_t)ZEROTIER_ONE_VERSION_MAJOR);
|
||||
|
@ -1111,7 +1112,7 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
|
|||
if ((originatorCredentialNetworkConfig)&&(!originatorCredentialNetworkConfig->isPublic())&&(originatorCredentialNetworkConfig->com())) {
|
||||
outp.append((uint8_t)0x01); // COM
|
||||
originatorCredentialNetworkConfig->com().serialize(outp);
|
||||
outp.setAt<uint16_t>(previousHopCredentialPos,(uint16_t)(size() - previousHopCredentialPos));
|
||||
outp.setAt<uint16_t>(previousHopCredentialPos,(uint16_t)(outp.size() - (previousHopCredentialPos + 2)));
|
||||
}
|
||||
if (remainingHopsPtr < size())
|
||||
outp.append(field(remainingHopsPtr,size() - remainingHopsPtr),size() - remainingHopsPtr);
|
||||
|
|
|
@ -127,8 +127,10 @@ void InetAddress::set(const void *ipBytes,unsigned int ipLen,unsigned int port)
|
|||
{
|
||||
memset(this,0,sizeof(InetAddress));
|
||||
if (ipLen == 4) {
|
||||
uint32_t ipb[1];
|
||||
memcpy(ipb,ipBytes,4);
|
||||
ss_family = AF_INET;
|
||||
reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr = *(reinterpret_cast<const uint32_t *>(ipBytes));
|
||||
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;
|
||||
|
|
|
@ -670,6 +670,9 @@ std::string Node::dataStoreGet(const char *name)
|
|||
|
||||
bool Node::shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress)
|
||||
{
|
||||
if (!Path::isAddressValidForPath(remoteAddress))
|
||||
return false;
|
||||
|
||||
{
|
||||
Mutex::Lock _l(_networks_m);
|
||||
for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
|
||||
|
|
|
@ -934,7 +934,7 @@ public:
|
|||
* Circuit test hop report:
|
||||
* <[8] 64-bit timestamp (from original test)>
|
||||
* <[8] 64-bit test ID (from original test)>
|
||||
* <[8] 64-bit reporter timestamp (reporter's clock, 0 if unspec)>
|
||||
* <[8] 64-bit reserved field (set to 0, currently unused)>
|
||||
* <[1] 8-bit vendor ID (set to 0, currently unused)>
|
||||
* <[1] 8-bit reporter protocol version>
|
||||
* <[1] 8-bit reporter major version>
|
||||
|
|
|
@ -127,7 +127,7 @@ public:
|
|||
inline bool active(uint64_t now) const
|
||||
throw()
|
||||
{
|
||||
return (((now - _lastReceived) < ZT_PEER_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
|
||||
return (((now - _lastReceived) < ZT_PATH_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -243,6 +243,14 @@ public:
|
|||
case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
|
||||
case InetAddress::IP_SCOPE_SHARED:
|
||||
case InetAddress::IP_SCOPE_GLOBAL:
|
||||
if (a.ss_family == AF_INET6) {
|
||||
// TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
|
||||
// tunnels due to very spotty performance and low MTU issues over
|
||||
// these IPv6 tunnel links.
|
||||
const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
|
||||
if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
|
|
|
@ -240,20 +240,32 @@ bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
|
|||
return false;
|
||||
}
|
||||
|
||||
void Peer::pushDirectPaths(Path *path,uint64_t now,bool force)
|
||||
bool Peer::pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force)
|
||||
{
|
||||
#ifdef ZT_ENABLE_CLUSTER
|
||||
// Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
|
||||
if (RR->cluster)
|
||||
return;
|
||||
return false;
|
||||
#endif
|
||||
|
||||
if (((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force)) {
|
||||
_lastDirectPathPushSent = now;
|
||||
if (!force) {
|
||||
if ((now - _lastDirectPathPushSent) < ZT_DIRECT_PATH_PUSH_INTERVAL)
|
||||
return false;
|
||||
else _lastDirectPathPushSent = now;
|
||||
}
|
||||
|
||||
std::vector<InetAddress> dps(RR->node->directPaths());
|
||||
std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
|
||||
for(unsigned long i=0,added=0;i<sym.size();++i) {
|
||||
InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
|
||||
if (std::find(dps.begin(),dps.end(),tmp) == dps.end()) {
|
||||
dps.push_back(tmp);
|
||||
if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dps.empty())
|
||||
return;
|
||||
return false;
|
||||
|
||||
#ifdef ZT_TRACE
|
||||
{
|
||||
|
@ -273,7 +285,7 @@ void Peer::pushDirectPaths(Path *path,uint64_t now,bool force)
|
|||
outp.addSize(2); // leave room for count
|
||||
|
||||
unsigned int count = 0;
|
||||
while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
|
||||
while ((p != dps.end())&&((outp.size() + 24) < 1200)) {
|
||||
uint8_t addressType = 4;
|
||||
switch(p->ss_family) {
|
||||
case AF_INET:
|
||||
|
@ -300,10 +312,11 @@ void Peer::pushDirectPaths(Path *path,uint64_t now,bool force)
|
|||
if (count) {
|
||||
outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
|
||||
outp.armor(_key,true);
|
||||
path->send(RR,outp.data(),outp.size(),now);
|
||||
}
|
||||
RR->node->putPacket(localAddr,toAddress,outp.data(),outp.size(),0);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Peer::resetWithinScope(InetAddress::IpScope scope,uint64_t now)
|
||||
|
@ -419,7 +432,7 @@ bool Peer::needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool
|
|||
const uint64_t tmp = lastPushed;
|
||||
if (updateLastPushedTime)
|
||||
lastPushed = now;
|
||||
return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 2));
|
||||
return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 3));
|
||||
}
|
||||
|
||||
void Peer::clean(uint64_t now)
|
||||
|
|
|
@ -170,11 +170,13 @@ public:
|
|||
/**
|
||||
* Push direct paths back to self if we haven't done so in the configured timeout
|
||||
*
|
||||
* @param path Remote path to use to send the push
|
||||
* @param localAddr Local address
|
||||
* @param toAddress Remote address to send push to (usually from path)
|
||||
* @param now Current time
|
||||
* @param force If true, push regardless of rate limit
|
||||
* @return True if something was actually sent
|
||||
*/
|
||||
void pushDirectPaths(Path *path,uint64_t now,bool force);
|
||||
bool pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force);
|
||||
|
||||
/**
|
||||
* @return All known direct paths to this peer (active or inactive)
|
||||
|
|
|
@ -20,6 +20,9 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
#include "Constants.hpp"
|
||||
#include "SelfAwareness.hpp"
|
||||
#include "RuntimeEnvironment.hpp"
|
||||
|
@ -64,34 +67,18 @@ SelfAwareness::~SelfAwareness()
|
|||
{
|
||||
}
|
||||
|
||||
void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
|
||||
void SelfAwareness::iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
|
||||
{
|
||||
const InetAddress::IpScope scope = myPhysicalAddress.ipScope();
|
||||
|
||||
// This would be weird, e.g. a public IP talking to 10.0.0.1, so just ignore it.
|
||||
// If your network is this weird it's probably not reliable information.
|
||||
if (scope != reporterPhysicalAddress.ipScope())
|
||||
if ((scope != reporterPhysicalAddress.ipScope())||(scope == InetAddress::IP_SCOPE_NONE)||(scope == InetAddress::IP_SCOPE_LOOPBACK)||(scope == InetAddress::IP_SCOPE_MULTICAST))
|
||||
return;
|
||||
|
||||
// Some scopes we ignore, and global scope IPs are only used for this
|
||||
// mechanism if they come from someone we trust (e.g. a root).
|
||||
switch(scope) {
|
||||
case InetAddress::IP_SCOPE_NONE:
|
||||
case InetAddress::IP_SCOPE_LOOPBACK:
|
||||
case InetAddress::IP_SCOPE_MULTICAST:
|
||||
return;
|
||||
case InetAddress::IP_SCOPE_GLOBAL:
|
||||
if (!trusted)
|
||||
return;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
Mutex::Lock _l(_phy_m);
|
||||
PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,reporterPhysicalAddress,scope)];
|
||||
PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,receivedOnLocalAddress,reporterPhysicalAddress,scope)];
|
||||
|
||||
if ( ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
|
||||
if ( (trusted) && ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
|
||||
// Changes to external surface reported by trusted peers causes path reset in this scope
|
||||
entry.mySurface = myPhysicalAddress;
|
||||
entry.ts = now;
|
||||
TRACE("physical address %s for scope %u as seen from %s(%s) differs from %s, resetting paths in scope",myPhysicalAddress.toString().c_str(),(unsigned int)scope,reporter.toString().c_str(),reporterPhysicalAddress.toString().c_str(),entry.mySurface.toString().c_str());
|
||||
|
@ -123,6 +110,7 @@ void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysi
|
|||
}
|
||||
}
|
||||
} else {
|
||||
// Otherwise just update DB to use to determine external surface info
|
||||
entry.mySurface = myPhysicalAddress;
|
||||
entry.ts = now;
|
||||
}
|
||||
|
@ -140,4 +128,60 @@ void SelfAwareness::clean(uint64_t now)
|
|||
}
|
||||
}
|
||||
|
||||
std::vector<InetAddress> SelfAwareness::getSymmetricNatPredictions()
|
||||
{
|
||||
/* This is based on ideas and strategies found here:
|
||||
* https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00
|
||||
*
|
||||
* In short: a great many symmetric NATs allocate ports sequentially.
|
||||
* This is common on enterprise and carrier grade NATs as well as consumer
|
||||
* devices. This code generates a list of "you might try this" addresses by
|
||||
* extrapolating likely port assignments from currently known external
|
||||
* global IPv4 surfaces. These can then be included in a PUSH_DIRECT_PATHS
|
||||
* message to another peer, causing it to possibly try these addresses and
|
||||
* bust our local symmetric NAT. It works often enough to be worth the
|
||||
* extra bit of code and does no harm in cases where it fails. */
|
||||
|
||||
// Gather unique surfaces indexed by local received-on address and flag
|
||||
// us as behind a symmetric NAT if there is more than one.
|
||||
std::map< InetAddress,std::set<InetAddress> > surfaces;
|
||||
bool symmetric = false;
|
||||
{
|
||||
Mutex::Lock _l(_phy_m);
|
||||
Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
|
||||
PhySurfaceKey *k = (PhySurfaceKey *)0;
|
||||
PhySurfaceEntry *e = (PhySurfaceEntry *)0;
|
||||
while (i.next(k,e)) {
|
||||
if ((e->mySurface.ss_family == AF_INET)&&(e->mySurface.ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
|
||||
std::set<InetAddress> &s = surfaces[k->receivedOnLocalAddress];
|
||||
s.insert(e->mySurface);
|
||||
symmetric = symmetric||(s.size() > 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we appear to be symmetrically NATed, generate and return extrapolations
|
||||
// of those surfaces. Since PUSH_DIRECT_PATHS is sent multiple times, we
|
||||
// probabilistically generate extrapolations of anywhere from +1 to +5 to
|
||||
// increase the odds that it will work "eventually".
|
||||
if (symmetric) {
|
||||
std::vector<InetAddress> r;
|
||||
for(std::map< InetAddress,std::set<InetAddress> >::iterator si(surfaces.begin());si!=surfaces.end();++si) {
|
||||
for(std::set<InetAddress>::iterator i(si->second.begin());i!=si->second.end();++i) {
|
||||
InetAddress ipp(*i);
|
||||
unsigned int p = ipp.port() + 1 + ((unsigned int)RR->node->prng() % 5);
|
||||
if (p >= 65535)
|
||||
p -= 64510; // NATs seldom use ports <=1024 so wrap to 1025
|
||||
ipp.setPort(p);
|
||||
if ((si->second.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) {
|
||||
r.push_back(ipp);
|
||||
}
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
return std::vector<InetAddress>();
|
||||
}
|
||||
|
||||
} // namespace ZeroTier
|
||||
|
|
|
@ -42,12 +42,13 @@ public:
|
|||
* Called when a trusted remote peer informs us of our external network address
|
||||
*
|
||||
* @param reporter ZeroTier address of reporting peer
|
||||
* @param receivedOnLocalAddress Local address on which report was received
|
||||
* @param reporterPhysicalAddress Physical address that reporting peer seems to have
|
||||
* @param myPhysicalAddress Physical address that peer says we have
|
||||
* @param trusted True if this peer is trusted as an authority to inform us of external address changes
|
||||
* @param now Current time
|
||||
*/
|
||||
void iam(const Address &reporter,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now);
|
||||
void iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now);
|
||||
|
||||
/**
|
||||
* Clean up database periodically
|
||||
|
@ -56,18 +57,26 @@ public:
|
|||
*/
|
||||
void clean(uint64_t now);
|
||||
|
||||
/**
|
||||
* If we appear to be behind a symmetric NAT, get predictions for possible external endpoints
|
||||
*
|
||||
* @return Symmetric NAT predictions or empty vector if none
|
||||
*/
|
||||
std::vector<InetAddress> getSymmetricNatPredictions();
|
||||
|
||||
private:
|
||||
struct PhySurfaceKey
|
||||
{
|
||||
Address reporter;
|
||||
InetAddress receivedOnLocalAddress;
|
||||
InetAddress reporterPhysicalAddress;
|
||||
InetAddress::IpScope scope;
|
||||
|
||||
PhySurfaceKey() : reporter(),scope(InetAddress::IP_SCOPE_NONE) {}
|
||||
PhySurfaceKey(const Address &r,const InetAddress &ra,InetAddress::IpScope s) : reporter(r),reporterPhysicalAddress(ra),scope(s) {}
|
||||
PhySurfaceKey(const Address &r,const InetAddress &rol,const InetAddress &ra,InetAddress::IpScope s) : reporter(r),receivedOnLocalAddress(rol),reporterPhysicalAddress(ra),scope(s) {}
|
||||
|
||||
inline unsigned long hashCode() const throw() { return ((unsigned long)reporter.toInt() + (unsigned long)scope); }
|
||||
inline bool operator==(const PhySurfaceKey &k) const throw() { return ((reporter == k.reporter)&&(reporterPhysicalAddress == k.reporterPhysicalAddress)&&(scope == k.scope)); }
|
||||
inline bool operator==(const PhySurfaceKey &k) const throw() { return ((reporter == k.reporter)&&(receivedOnLocalAddress == k.receivedOnLocalAddress)&&(reporterPhysicalAddress == k.reporterPhysicalAddress)&&(scope == k.scope)); }
|
||||
};
|
||||
struct PhySurfaceEntry
|
||||
{
|
||||
|
|
|
@ -478,11 +478,11 @@ unsigned long Switch::doTimerTasks(uint64_t now)
|
|||
Mutex::Lock _l(_contactQueue_m);
|
||||
for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
|
||||
if (now >= qi->fireAtTime) {
|
||||
if (qi->peer->hasActiveDirectPath(now)) {
|
||||
// Cancel if connection has succeeded
|
||||
if (!qi->peer->pushDirectPaths(qi->localAddr,qi->inaddr,now,true))
|
||||
qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
|
||||
_contactQueue.erase(qi++);
|
||||
continue;
|
||||
} else {
|
||||
/* Old symmetric NAT buster code, obsoleted by port prediction alg in SelfAwareness but left around for now in case we revert
|
||||
if (qi->strategyIteration == 0) {
|
||||
// First strategy: send packet directly to destination
|
||||
qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
|
||||
|
@ -490,10 +490,10 @@ unsigned long Switch::doTimerTasks(uint64_t now)
|
|||
// Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
|
||||
InetAddress tmpaddr(qi->inaddr);
|
||||
int p = (int)qi->inaddr.port() + qi->strategyIteration;
|
||||
if (p < 0xffff) {
|
||||
if (p > 65535)
|
||||
p -= 64511;
|
||||
tmpaddr.setPort((unsigned int)p);
|
||||
qi->peer->sendHELLO(qi->localAddr,tmpaddr,now);
|
||||
} else qi->strategyIteration = 5;
|
||||
} else {
|
||||
// All strategies tried, expire entry
|
||||
_contactQueue.erase(qi++);
|
||||
|
@ -502,7 +502,7 @@ unsigned long Switch::doTimerTasks(uint64_t now)
|
|||
++qi->strategyIteration;
|
||||
qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
|
||||
nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
|
||||
}
|
||||
*/
|
||||
} else {
|
||||
nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
|
||||
}
|
||||
|
@ -813,12 +813,13 @@ bool Switch::_trySend(const Packet &packet,bool encrypt,uint64_t nwid)
|
|||
relay = RR->topology->getBestRoot();
|
||||
|
||||
if (!(relay)||(!(viaPath = relay->getBestPath(now))))
|
||||
return false; // no paths, no root servers?
|
||||
return false; // no paths, no root servers?, no relays? :P~~~
|
||||
}
|
||||
|
||||
if ((network)&&(relay)&&(network->isAllowed(peer))) {
|
||||
// Push hints for direct connectivity to this peer if we are relaying
|
||||
peer->pushDirectPaths(viaPath,now,false);
|
||||
peer->pushDirectPaths(viaPath->localAddress(),viaPath->address(),now,false);
|
||||
viaPath->sent(now);
|
||||
}
|
||||
|
||||
Packet tmp(packet);
|
||||
|
|
|
@ -83,8 +83,11 @@ LinuxEthernetTap::LinuxEthernetTap(
|
|||
throw std::runtime_error("max tap MTU is 2800");
|
||||
|
||||
_fd = ::open("/dev/net/tun",O_RDWR);
|
||||
if (_fd <= 0) {
|
||||
_fd = ::open("/dev/tun",O_RDWR);
|
||||
if (_fd <= 0)
|
||||
throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
|
||||
}
|
||||
|
||||
struct ifreq ifr;
|
||||
memset(&ifr,0,sizeof(ifr));
|
||||
|
|
|
@ -852,7 +852,7 @@ struct TestPhyHandlers
|
|||
inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
|
||||
inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
|
||||
inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
|
||||
inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
|
||||
inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool b) {}
|
||||
#endif // __UNIX_LIKE__
|
||||
|
||||
inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
|
||||
|
|
|
@ -32,6 +32,6 @@
|
|||
/**
|
||||
* Revision
|
||||
*/
|
||||
#define ZEROTIER_ONE_VERSION_REVISION 4
|
||||
#define ZEROTIER_ONE_VERSION_REVISION 5
|
||||
|
||||
#endif
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue