Merge branch 'hidden-service-dht' of https://github.com/majestrate/llarp

This commit is contained in:
Ryan Tharp 2018-07-08 11:41:44 +00:00
commit 00e56ecfd2
44 changed files with 1162 additions and 461 deletions

View File

@ -58,6 +58,9 @@
"strstream": "cpp",
"numeric": "cpp",
"valarray": "cpp",
"*.ipp": "cpp"
"*.ipp": "cpp",
"csignal": "cpp",
"future": "cpp",
"map": "cpp"
}
}

View File

@ -164,6 +164,7 @@ set(LIB_SRC
llarp/relay_up_down.cpp
llarp/router_contact.cpp
llarp/router.cpp
llarp/service.cpp
llarp/threadpool.cpp
llarp/transit_hop.cpp
llarp/testnet.c
@ -200,8 +201,10 @@ set(LIB_SRC
set(TEST_SRC
test/main.cpp
test/api_unittest.cpp
test/base32_unittest.cpp
test/dht_unittest.cpp
test/encrypted_frame_unittest.cpp
test/hiddenservice_unittest.cpp
)
set(TEST_EXE testAll)
set(GTEST_DIR test/gtest)

View File

@ -70,7 +70,7 @@ testnet-build: testnet-configure
testnet: testnet-build
mkdir -p $(TESTNET_ROOT)
python3 contrib/testnet/genconf.py --bin=$(REPO)/llarpd --svc=30 --clients=100 --dir=$(TESTNET_ROOT) --out $(TESTNET_CONF)
python3 contrib/testnet/genconf.py --bin=$(REPO)/llarpd --svc=30 --clients=1 --dir=$(TESTNET_ROOT) --out $(TESTNET_CONF)
supervisord -n -d $(TESTNET_ROOT) -l $(TESTNET_LOG) -c $(TESTNET_CONF)
test: debug-configure

View File

@ -9,7 +9,6 @@ llarp_main *sllarp = nullptr;
void
handle_signal(int sig)
{
printf("rcutil::handle_signal [%x] got [%d]\n", ctx, sig);
if(ctx)
llarp_main_signal(ctx, sig);
}
@ -45,13 +44,13 @@ struct check_online_request;
void
HandleDHTLocate(llarp_router_lookup_job *job)
{
llarp::Info("DHT result: ", job->found ? "found" : "not found");
llarp::LogInfo("DHT result: ", job->found ? "found" : "not found");
if (job->found)
{
// save to nodedb?
}
// shutdown router
// well because we're in the gotroutermessage, we can't sigint because we'll deadlock because we're session locked
//llarp_main_signal(ctx, SIGINT);
@ -181,21 +180,22 @@ main(int argc, char *argv[])
}
if(!haveRequiredOptions)
{
llarp::Error("Parameters dont all have their required parameters.\n");
llarp::LogError("Parameters dont all have their required parameters.\n");
return 0;
}
printf("parsed options\n");
if(!genMode && !updMode && !listMode && !importMode && !exportMode
&& !locateMode && !localMode)
{
llarp::Error("I don't know what to do, no generate or update parameter\n");
llarp::LogError(
"I don't know what to do, no generate or update parameter\n");
return 0;
}
ctx = llarp_main_init(conffname, !TESTNET);
if(!ctx)
{
llarp::Error("Cant set up context");
llarp::LogError("Cant set up context");
return 0;
}
signal(SIGINT, handle_signal);
@ -273,11 +273,11 @@ main(int argc, char *argv[])
if(importMode)
{
llarp_main_loadDatabase(ctx);
llarp::Info("Loading ", rcfname);
llarp::LogInfo("Loading ", rcfname);
llarp_rc *rc = llarp_rc_read(rcfname);
if(!rc)
{
llarp::Error("Can't load RC");
llarp::LogError("Can't load RC");
return 0;
}
llarp_main_putDatabase(ctx, rc);
@ -285,25 +285,25 @@ main(int argc, char *argv[])
if(exportMode)
{
llarp_main_loadDatabase(ctx);
// llarp::Info("Looking for string: ", rcfname);
// llarp::LogInfo("Looking for string: ", rcfname);
llarp::PubKey binaryPK;
llarp::HexDecode(rcfname, binaryPK.data());
llarp::Info("Looking for binary: ", binaryPK);
llarp::LogInfo("Looking for binary: ", binaryPK);
struct llarp_rc *rc = llarp_main_getDatabase(ctx, binaryPK.data());
if(!rc)
{
llarp::Error("Can't load RC from database");
llarp::LogError("Can't load RC from database");
}
std::string filename(rcfname);
filename.append(".signed");
llarp::Info("Writing out: ", filename);
llarp::LogInfo("Writing out: ", filename);
llarp_rc_write(rc, filename.c_str());
}
if(locateMode)
{
llarp::Info("Going online");
llarp::LogInfo("Going online");
llarp_main_setup(ctx);
llarp::PubKey binaryPK;
@ -311,12 +311,12 @@ main(int argc, char *argv[])
//llarp::SetLogLevel(llarp::eLogDebug);
llarp::Info("Queueing job");
llarp::LogInfo("Queueing job");
llarp_router_lookup_job *job = new llarp_router_lookup_job;
job->found = false;
job->hook = &HandleDHTLocate;
memcpy(job->target, binaryPK, PUBKEYSIZE); // set job's target
// create query DHT request
check_online_request *request = new check_online_request;
request->ptr = ctx;
@ -326,13 +326,13 @@ main(int argc, char *argv[])
request->first = false;
llarp_main_queryDHT(request);
llarp::Info("Processing");
llarp::LogInfo("Processing");
// run system and wait
llarp_main_run(ctx);
}
if(localMode)
{
// llarp::Info("find our local rc file");
// llarp::LogInfo("find our local rc file");
// llarp_rc *rc = llarp_rc_read("router.signed");
llarp_rc *rc = llarp_main_getLocalRC(ctx);

View File

@ -108,6 +108,7 @@ R is currently set to 0 by the sender.
if R is greater than 0, do a random walk, otherwise if we are
closer to the SA of the IS than anyone else we know in the DHT
store the IS for later lookup.
As of protocol version 0, R is always 0.
If S is provided store the IS for later lookup unconditionally,
decrement S by 1 and forward to dht peer who is next closest to

View File

@ -153,6 +153,8 @@ the "network address" of a hidden service, which is computed as the blake2b
HS(BE(SI))
when in string form it's encoded with z-base32 and uses the .loki tld
introduction (I)
a descriptor annoucing a path to a hidden service

View File

@ -47,7 +47,7 @@ namespace llarp
{
if(!item.BDecode(buf))
{
llarp::Warn("failed to decode key ", k);
llarp::LogWarn("failed to decode key ", k);
return false;
}
read = true;
@ -64,7 +64,7 @@ namespace llarp
{
if(!bencode_read_integer(buf, &i))
{
llarp::Warn("failed to decode key ", k);
llarp::LogWarn("failed to decode key ", k);
return false;
}
read = true;

View File

@ -123,6 +123,7 @@ namespace llarp
{
virtual ~IMessage(){};
/// construct
IMessage(const Key_t& from) : From(from)
{
}
@ -134,18 +135,19 @@ namespace llarp
DecodeKey(llarp_buffer_t key, llarp_buffer_t* val) = 0;
virtual bool
HandleMessage(llarp_router* router,
HandleMessage(llarp_dht_context* dht,
std::vector< IMessage* >& replies) const = 0;
Key_t From;
PathID_t pathID;
};
IMessage*
DecodeMessage(const Key_t& from, llarp_buffer_t* buf);
DecodeMessage(const Key_t& from, llarp_buffer_t* buf, bool relayed = false);
bool
DecodeMesssageList(const Key_t& from, llarp_buffer_t* buf,
std::vector< IMessage* >& dst);
std::vector< IMessage* >& dst, bool relayed = false);
template < typename Val_t >
struct Bucket
@ -308,6 +310,30 @@ namespace llarp
Key_t ourKey;
};
struct PublishIntroMessage : public IMessage
{
llarp::service::IntroSet I;
uint64_t R;
uint64_t S;
bool hasS = false;
uint64_t V;
PublishIntroMessage() : IMessage({})
{
}
~PublishIntroMessage();
bool
BEncode(llarp_buffer_t* buf) const;
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* val);
virtual bool
HandleMessage(llarp_dht_context* ctx,
std::vector< IMessage* >& replies) const;
};
struct GotRouterMessage : public IMessage
{
GotRouterMessage(const Key_t& from) : IMessage(from)
@ -332,8 +358,8 @@ namespace llarp
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* val);
bool
HandleMessage(llarp_router* router,
virtual bool
HandleMessage(llarp_dht_context* ctx,
std::vector< IMessage* >& replies) const;
std::vector< llarp_rc > R;
@ -360,8 +386,8 @@ namespace llarp
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* val);
bool
HandleMessage(llarp_router* router,
virtual bool
HandleMessage(llarp_dht_context* ctx,
std::vector< IMessage* >& replies) const;
Key_t K;

View File

@ -1,10 +1,112 @@
#ifndef LLARP_ENCODE_HPP
#define LLARP_ENCODE_HPP
#include <stdint.h>
#include <cmath>
#include <cstdlib>
#include <unordered_map>
namespace llarp
{
// from https://en.wikipedia.org/wiki/Base32#z-base-32
static const char zbase32_alpha[] = {'y', 'b', 'n', 'd', 'r', 'f', 'g', '8',
'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x',
'o', 't', '1', 'u', 'w', 'i', 's', 'z',
'a', '3', '4', '5', 'h', '7', '6', '9'};
static const std::unordered_map< char, uint8_t > zbase32_reverse_alpha = {
{'y', 0}, {'b', 1}, {'n', 2}, {'d', 3}, {'r', 4}, {'f', 5},
{'g', 6}, {'8', 7}, {'e', 8}, {'j', 9}, {'k', 10}, {'m', 11},
{'c', 12}, {'p', 13}, {'q', 14}, {'x', 15}, {'o', 16}, {'t', 17},
{'1', 18}, {'u', 19}, {'w', 20}, {'i', 21}, {'s', 22}, {'z', 23},
{'a', 24}, {'3', 25}, {'4', 26}, {'5', 27}, {'h', 28}, {'7', 29},
{'6', 30}, {'9', 31}};
template < int a, int b >
static size_t
DecodeSize(size_t sz)
{
auto d = div(sz, a);
if(d.rem)
d.quot++;
return b * d.quot;
}
template < typename Stack, typename V >
bool
Base32Decode(const Stack& stack, V& value)
{
int tmp = 0, bits = 0;
size_t ret = 0;
size_t len = DecodeSize< 5, 8 >(value.size());
size_t outLen = value.size();
for(size_t i = 0; i < len; i++)
{
char ch = stack[i];
if(ch)
{
auto itr = zbase32_reverse_alpha.find(ch);
if(itr == zbase32_reverse_alpha.end())
return false;
ch = itr->second;
}
else
{
return ret == outLen;
}
tmp |= ch;
bits += 5;
if(bits >= 8)
{
if(ret >= outLen)
return false;
value[ret] = tmp >> (bits - 8);
bits -= 8;
ret++;
}
tmp <<= 5;
}
return true;
}
/// adapted from i2pd
template < typename V, typename Stack >
const char*
Base32Encode(const V& value, Stack& stack)
{
size_t ret = 0, pos = 1;
int bits = 8, tmp = value[0];
size_t len = value.size();
while(ret < sizeof(stack) && (bits > 0 || pos < len))
{
if(bits < 5)
{
if(pos < len)
{
tmp <<= 8;
tmp |= value[pos] & 0xFF;
pos++;
bits += 8;
}
else // last byte
{
tmp <<= (5 - bits);
bits = 5;
}
}
bits -= 5;
int ind = (tmp >> bits) & 0x1F;
if(ret < sizeof(stack))
{
stack[ret] = zbase32_alpha[ind];
ret++;
}
else
return nullptr;
}
return &stack[0];
}
/// encode V as hex to stack
/// null terminate
/// return pointer to base of stack buffer on success otherwise returns
@ -30,8 +132,9 @@ namespace llarp
int
char2int(char input);
void
HexDecode(const char* src, uint8_t* target);
}
} // namespace llarp
#endif

View File

@ -93,9 +93,9 @@ namespace llarp
}
} // namespace llarp
#define Debug(x, ...) _Log(llarp::eLogDebug, __FILE__, x, ##__VA_ARGS__)
#define Info(x, ...) _Log(llarp::eLogInfo, __FILE__, x, ##__VA_ARGS__)
#define Warn(x, ...) _Log(llarp::eLogWarn, __FILE__, x, ##__VA_ARGS__)
#define Error(x, ...) _Log(llarp::eLogError, __FILE__, x, ##__VA_ARGS__)
#define LogDebug(x, ...) _Log(llarp::eLogDebug, __FILE__, x, ##__VA_ARGS__)
#define LogInfo(x, ...) _Log(llarp::eLogInfo, __FILE__, x, ##__VA_ARGS__)
#define LogWarn(x, ...) _Log(llarp::eLogWarn, __FILE__, x, ##__VA_ARGS__)
#define LogError(x, ...) _Log(llarp::eLogError, __FILE__, x, ##__VA_ARGS__)
#endif

View File

@ -71,10 +71,10 @@ namespace llarp
HandleMessage(llarp_router* router) const
{
(void)router;
llarp::Info("got discard message of size ", sz, " bytes");
llarp::LogInfo("got discard message of size ", sz, " bytes");
return true;
}
};
}
} // namespace llarp
#endif

View File

@ -4,27 +4,59 @@
#include <llarp/bencode.hpp>
#include <llarp/crypto.hpp>
#include <llarp/path_types.hpp>
#include <llarp/pow.hpp>
#include <iostream>
#include <set>
#include <string>
namespace llarp
{
namespace service
{
constexpr std::size_t MAX_INTROSET_SIZE = 1024;
// forward declare
struct IntroSet;
/// hidden service address
typedef llarp::AlignedBuffer< 32 > Address;
std::string
AddressToString(const Address& addr);
typedef llarp::AlignedBuffer< 16 > VanityNonce;
struct Info : public llarp::IBEncodeMessage
struct ServiceInfo : public llarp::IBEncodeMessage
{
llarp::PubKey enckey;
llarp::PubKey signkey;
uint64_t version = 0;
VanityNonce vanity;
ServiceInfo();
~ServiceInfo();
ServiceInfo&
operator=(const ServiceInfo& other)
{
enckey = other.enckey;
signkey = other.signkey;
version = other.version;
vanity = other.vanity;
return *this;
};
friend std::ostream&
operator<<(std::ostream& out, const ServiceInfo& i)
{
return out << "[e=" << i.enckey << " s=" << i.signkey
<< " v=" << i.version << " x=" << i.vanity << "]";
}
/// calculate our address
void
bool
CalculateAddress(Address& addr) const;
bool
@ -43,7 +75,9 @@ namespace llarp
VanityNonce vanity;
// public service info
Info pub;
ServiceInfo pub;
~Identity();
// regenerate secret keys
void
@ -58,6 +92,9 @@ namespace llarp
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf);
bool
SignIntroSet(IntroSet& i, llarp_crypto* c) const;
};
struct Introduction : public llarp::IBEncodeMessage
@ -67,18 +104,73 @@ namespace llarp
uint64_t version = 0;
uint64_t expiresAt;
~Introduction();
friend std::ostream&
operator<<(std::ostream& out, const Introduction& i)
{
return out << "k=" << i.router << " p=" << i.pathID
<< " v=" << i.version << " x=" << i.expiresAt;
}
bool
BEncode(llarp_buffer_t* buf) const;
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf);
bool
operator<(const Introduction& other) const
{
return expiresAt < other.expiresAt || pathID < other.pathID;
}
};
struct IntroSet : public llarp::IBEncodeMessage
{
Info A;
ServiceInfo A;
std::set< Introduction > I;
uint64_t V = 0;
llarp::PoW* W = nullptr;
llarp::Signature Z;
~IntroSet();
IntroSet&
operator=(const IntroSet& other)
{
A = other.A;
I = other.I;
V = other.V;
if(W)
delete W;
W = other.W;
Z = other.Z;
return *this;
}
friend std::ostream&
operator<<(std::ostream& out, const IntroSet& i)
{
out << "A=[" << i.A << "] I=[";
for(const auto& intro : i.I)
{
out << intro << ",";
}
return out << "] V=" << i.V << " Z=" << i.Z;
}
bool
BDecode(llarp_buffer_t* buf);
bool
BEncode(llarp_buffer_t* buf) const;
bool
DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf);
bool
VerifySignature(llarp_crypto* crypto) const;
};
}; // namespace service

View File

@ -43,7 +43,7 @@ namespace llarp
|| ((sockaddr_in*)from)->sin_port != apiAddr.sin_port)
{
// address missmatch
llarp::Warn("got packet from bad address");
llarp::LogWarn("got packet from bad address");
return;
}
llarp_buffer_t buf;
@ -56,7 +56,7 @@ namespace llarp
delete msg;
}
else
llarp::Warn("Got Invalid Message");
llarp::LogWarn("Got Invalid Message");
}
bool

View File

@ -54,7 +54,7 @@ namespace llarp
Put(const T& i)
{
Lock_t lock(m_QueueMutex);
// llarp::Info("CoDelQueue::Put - adding item, queue now has ",
// llarp::LogInfo("CoDelQueue::Put - adding item, queue now has ",
// m_Queue.size(), " items at ", getTime(*item));
PutTime()(i);
m_Queue.push(i);
@ -68,26 +68,26 @@ namespace llarp
{
llarp_time_t lowest = 0xFFFFFFFFFFFFFFFFUL;
// auto start = llarp_time_now_ms();
// llarp::Info("CoDelQueue::Process - start at ", start);
// llarp::LogInfo("CoDelQueue::Process - start at ", start);
Lock_t lock(m_QueueMutex);
auto start = firstPut;
while(m_Queue.size())
{
// llarp::Info("CoDelQueue::Process - queue has ", m_Queue.size());
// llarp::LogInfo("CoDelQueue::Process - queue has ", m_Queue.size());
const auto& item = m_Queue.top();
auto dlt = start - GetTime()(item);
// llarp::Info("CoDelQueue::Process - dlt ", dlt);
// llarp::LogInfo("CoDelQueue::Process - dlt ", dlt);
lowest = std::min(dlt, lowest);
if(m_Queue.size() == 1)
{
// llarp::Info("CoDelQueue::Process - single item: lowest ", lowest,
// " dropMs: ", dropMs);
// llarp::LogInfo("CoDelQueue::Process - single item: lowest ",
// lowest, " dropMs: ", dropMs);
if(lowest > dropMs)
{
// drop
nextTickInterval += initialIntervalMs / std::sqrt(++dropNum);
llarp::Warn("CoDel queue ", m_name, " drop ", nextTickInterval,
" ms next interval lowest=", lowest);
llarp::LogWarn("CoDel queue ", m_name, " drop ", nextTickInterval,
" ms next interval lowest=", lowest);
delete item;
m_Queue.pop();
break;
@ -98,7 +98,7 @@ namespace llarp
dropNum = 0;
}
}
// llarp::Info("CoDelQueue::Process - passing");
// llarp::LogInfo("CoDelQueue::Process - passing");
result.push(item);
m_Queue.pop();
}

View File

@ -14,7 +14,7 @@ namespace llarp
Context::Context(std::ostream &stdout, bool singleThread)
: singleThreaded(singleThread), out(stdout)
{
llarp::Info(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO);
llarp::LogInfo(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO);
}
Context::~Context()
@ -30,18 +30,18 @@ namespace llarp
bool
Context::ReloadConfig()
{
// llarp::Info("loading config at ", configfile);
// llarp::LogInfo("loading config at ", configfile);
if(llarp_load_config(config, configfile.c_str()))
{
llarp_free_config(&config);
llarp::Error("failed to load config file ", configfile);
llarp::LogError("failed to load config file ", configfile);
return false;
}
llarp_config_iterator iter;
iter.user = this;
iter.visit = &iter_config;
llarp_config_iter(config, &iter);
llarp::Info("config [", configfile, "] loaded");
llarp::LogInfo("config [", configfile, "] loaded");
return true;
}
@ -89,23 +89,24 @@ namespace llarp
nodedb = llarp_nodedb_new(&crypto);
if(!nodedb_dir[0])
{
llarp::Error("no nodedb_dir configured");
llarp::LogError("no nodedb_dir configured");
return 0;
}
nodedb_dir[sizeof(nodedb_dir) - 1] = 0;
if(!llarp_nodedb_ensure_dir(nodedb_dir))
{
llarp::Error("nodedb_dir is incorrect");
llarp::LogError("nodedb_dir is incorrect");
return 0;
}
// llarp::Info("nodedb_dir [", nodedb_dir, "] configured!");
// llarp::LogInfo("nodedb_dir [", nodedb_dir, "] configured!");
ssize_t loaded = llarp_nodedb_load_dir(nodedb, nodedb_dir);
llarp::Info("nodedb_dir loaded ", loaded, " RCs from [", nodedb_dir, "]");
llarp::LogInfo("nodedb_dir loaded ", loaded, " RCs from [", nodedb_dir,
"]");
if(loaded < 0)
{
// shouldn't be possible
llarp::Error("nodedb_dir directory doesn't exist");
llarp::LogError("nodedb_dir directory doesn't exist");
return 0;
}
return 1;
@ -132,7 +133,7 @@ namespace llarp
int
Context::Setup()
{
llarp::Info("starting up");
llarp::LogInfo("starting up");
this->LoadDatabase();
llarp_ev_loop_alloc(&mainloop);
@ -141,7 +142,7 @@ namespace llarp
worker = llarp_init_threadpool(2, "llarp-worker");
else if(singleThreaded)
{
llarp::Info("running in single threaded mode");
llarp::LogInfo("running in single threaded mode");
worker = llarp_init_same_process_threadpool();
}
// ensure netio thread
@ -156,12 +157,12 @@ namespace llarp
if(!llarp_configure_router(router, config))
{
llarp::Error("Failed to configure router");
llarp::LogError("Failed to configure router");
return 1;
}
if(custom_dht_func)
{
llarp::Info("using custom dht function");
llarp::LogInfo("using custom dht function");
llarp_dht_set_msg_handler(router->dht, custom_dht_func);
}
// set nodedb, load our RC, establish DHT
@ -180,7 +181,7 @@ namespace llarp
// set up all requirements
if(this->Setup())
{
llarp::Error("Failed to setup router");
llarp::LogError("Failed to setup router");
return 1;
}
}
@ -188,7 +189,7 @@ namespace llarp
// run net io thread
if(singleThreaded)
{
llarp::Info("running mainloop");
llarp::LogInfo("running mainloop");
llarp_ev_loop_run_single_process(mainloop, worker, logic);
}
else
@ -206,7 +207,7 @@ namespace llarp
pthread_setname_np(netio_threads.back().native_handle(), "llarp-netio");
#endif
}
llarp::Info("running mainloop");
llarp::LogInfo("running mainloop");
llarp_logic_mainloop(logic);
}
return 0;
@ -217,12 +218,12 @@ namespace llarp
{
if(sig == SIGINT)
{
llarp::Info("SIGINT");
llarp::LogInfo("SIGINT");
SigINT();
}
if(sig == SIGHUP)
{
llarp::Info("SIGHUP");
llarp::LogInfo("SIGHUP");
ReloadConfig();
}
}
@ -236,55 +237,55 @@ namespace llarp
void
Context::Close()
{
llarp::Debug("stop router");
llarp::LogDebug("stop router");
if(router)
llarp_stop_router(router);
llarp::Debug("stop workers");
llarp::LogDebug("stop workers");
if(worker)
llarp_threadpool_stop(worker);
llarp::Debug("join workers");
llarp::LogDebug("join workers");
if(worker)
llarp_threadpool_join(worker);
llarp::Debug("stop logic");
llarp::LogDebug("stop logic");
if(logic)
llarp_logic_stop(logic);
llarp::Debug("free config");
llarp::LogDebug("free config");
llarp_free_config(&config);
llarp::Debug("free workers");
llarp::LogDebug("free workers");
llarp_free_threadpool(&worker);
llarp::Debug("free nodedb");
llarp::LogDebug("free nodedb");
llarp_nodedb_free(&nodedb);
for(size_t i = 0; i < netio_threads.size(); ++i)
{
if(mainloop)
{
llarp::Debug("stopping event loop thread ", i);
llarp::LogDebug("stopping event loop thread ", i);
llarp_ev_loop_stop(mainloop);
}
}
llarp::Debug("free router");
llarp::LogDebug("free router");
llarp_free_router(&router);
llarp::Debug("free logic");
llarp::LogDebug("free logic");
llarp_free_logic(&logic);
for(auto &t : netio_threads)
{
llarp::Debug("join netio thread");
llarp::LogDebug("join netio thread");
t.join();
}
netio_threads.clear();
llarp::Debug("free mainloop");
llarp::LogDebug("free mainloop");
llarp_ev_loop_free(&mainloop);
}
@ -295,7 +296,7 @@ namespace llarp
configfile = fname;
return ReloadConfig();
}
}
} // namespace llarp
extern "C" {
struct llarp_main
@ -384,7 +385,7 @@ llarp_main_getLocalRC(struct llarp_main *ptr)
iter.visit = &iter_config;
llarp_config_iter(ctx->config, &iter);
*/
llarp::Info("Loading ", ptr->ctx->conatctFile);
llarp::LogInfo("Loading ", ptr->ctx->conatctFile);
llarp_rc *rc = llarp_rc_read(ptr->ctx->conatctFile);
return rc;
}
@ -392,19 +393,19 @@ llarp_main_getLocalRC(struct llarp_main *ptr)
void
llarp_main_checkOnline(void *u, uint64_t orig, uint64_t left)
{
// llarp::Info("checkOnline - check ", left);
// llarp::LogInfo("checkOnline - check ", left);
if(left)
return;
struct check_online_request *request =
static_cast< struct check_online_request * >(u);
// llarp::Debug("checkOnline - running");
// llarp::Info("checkOnline - DHT nodes ",
// llarp::LogDebug("checkOnline - running");
// llarp::LogInfo("checkOnline - DHT nodes ",
// request->ptr->ctx->router->dht->impl.nodes->nodes.size());
request->online = false;
request->nodes = request->ptr->ctx->router->dht->impl.nodes->nodes.size();
if(request->ptr->ctx->router->dht->impl.nodes->nodes.size())
{
// llarp::Info("checkOnline - Going to say we're online");
// llarp::LogInfo("checkOnline - Going to say we're online");
request->online = true;
}
request->hook(request);
@ -420,8 +421,8 @@ llarp_main_queryDHT_online(struct check_online_request *request)
if(request->online && !request->first)
{
request->first = true;
llarp::Info("llarp_main_queryDHT_online - We're online");
llarp::Info("llarp_main_queryDHT_online - Querying DHT");
llarp::LogInfo("llarp_main_queryDHT_online - We're online");
llarp::LogInfo("llarp_main_queryDHT_online - Querying DHT");
llarp_dht_lookup_router(request->ptr->ctx->router->dht, request->job);
}
}
@ -429,7 +430,7 @@ llarp_main_queryDHT_online(struct check_online_request *request)
void
llarp_main_queryDHT(struct check_online_request *request)
{
// llarp::Info("llarp_main_queryDHT - setting up timer");
// llarp::LogInfo("llarp_main_queryDHT - setting up timer");
request->hook = &llarp_main_queryDHT_online;
llarp_logic_call_later(request->ptr->ctx->router->logic,
{1000, request, &llarp_main_checkOnline});

View File

@ -93,7 +93,7 @@ namespace iwp
buf.sz = 32;
memcpy(intro->remote_pubkey, intro->buf + 64, 32);
crypto->xchacha20(buf, e_K, intro->nonce);
llarp::Info("handshake from ", llarp::RouterID(intro->remote_pubkey));
llarp::LogInfo("handshake from ", llarp::RouterID(intro->remote_pubkey));
// S = TKE(a.k, b.k, n)
crypto->transport_dh_server(sharedkey, intro->remote_pubkey,
intro->secretkey, intro->nonce);

View File

@ -1,5 +1,6 @@
#include <llarp/bencode.hpp>
#include <llarp/dht.hpp>
#include <llarp/messages/dht.hpp>
#include <llarp/messages/dht_immediate.hpp>
#include "router.hpp"
#include "router_contact.hpp"
@ -74,13 +75,166 @@ namespace llarp
bool result = true;
for(auto &msg : msgs)
{
result &= msg->HandleMessage(router, reply->msgs);
result &= msg->HandleMessage(router->dht, reply->msgs);
}
return result && router->SendToOrQueue(remote.data(), reply);
}
namespace dht
{
struct PathLookupInformer
{
llarp_router *router;
PathID_t pathID;
uint64_t txid;
PathLookupInformer(llarp_router *r, const PathID_t &id, uint64_t tx)
: router(r), pathID(id), txid(tx)
{
}
void
SendReply(const llarp::routing::IMessage *msg)
{
auto path = router->paths.GetByUpstream(router->pubkey(), pathID);
if(path == nullptr)
{
llarp::LogWarn("Path not found for relayed DHT message txid=", txid,
" pathid=", pathID);
return;
}
if(!path->SendRoutingMessage(msg, router))
llarp::LogWarn("Failed to send reply for relayed DHT message txid=",
txid, "pathid=", pathID);
}
static void
InformReply(llarp_router_lookup_job *job)
{
PathLookupInformer *self =
static_cast< PathLookupInformer * >(job->user);
llarp::routing::DHTMessage reply;
if(job->found)
{
if(llarp_rc_verify_sig(&self->router->crypto, &job->result))
{
reply.M.push_back(
new GotRouterMessage(job->target, self->txid, &job->result));
}
llarp_rc_free(&job->result);
llarp_rc_clear(&job->result);
}
else
{
reply.M.push_back(
new GotRouterMessage(job->target, self->txid, nullptr));
}
self->SendReply(&reply);
// TODO: is this okay?
delete self;
delete job;
}
};
/// variant of FindRouterMessage relayed via path
struct RelayedFindRouterMessage : public FindRouterMessage
{
RelayedFindRouterMessage(const Key_t &from) : FindRouterMessage(from)
{
}
/// handle a relayed FindRouterMessage, do a lookup on the dht and inform
/// the path of the result
/// TODO: smart path expiration logic needs to be implemented
virtual bool
HandleMessage(llarp_dht_context *ctx, std::vector< IMessage * > &replies)
{
auto &dht = ctx->impl;
/// lookup for us, send an immeidate reply
if(K == dht.OurKey())
{
auto path = dht.router->paths.GetByUpstream(K, pathID);
if(path)
{
llarp::routing::DHTMessage reply;
reply.M.push_back(new GotRouterMessage(K, txid, &dht.router->rc));
return path->SendRoutingMessage(&reply, dht.router);
}
return false;
}
llarp_router_lookup_job *job = new llarp_router_lookup_job;
PathLookupInformer *informer =
new PathLookupInformer(dht.router, pathID, txid);
job->user = informer;
job->hook = &PathLookupInformer::InformReply;
job->found = false;
job->dht = ctx;
memcpy(job->target, K, sizeof(job->target));
Key_t peer;
if(dht.nodes->FindClosest(K, peer))
dht.LookupRouter(K, dht.OurKey(), txid, peer, job);
return false;
}
};
PublishIntroMessage::~PublishIntroMessage()
{
}
bool
PublishIntroMessage::DecodeKey(llarp_buffer_t key, llarp_buffer_t *val)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("I", I, read, key, val))
return false;
if(!BEncodeMaybeReadDictInt("R", R, read, key, val))
return false;
if(llarp_buffer_eq(key, "S"))
{
read = true;
hasS = true;
if(!bencode_read_integer(val, &S))
return false;
}
if(!BEncodeMaybeReadDictInt("V", V, read, key, val))
return false;
return read;
}
bool
PublishIntroMessage::HandleMessage(llarp_dht_context *ctx,
std::vector< IMessage * > &replies) const
{
auto &dht = ctx->impl;
if(!I.VerifySignature(&dht.router->crypto))
{
llarp::LogWarn("invalid introset signature");
return false;
}
return false;
}
bool
PublishIntroMessage::BEncode(llarp_buffer_t *buf) const
{
if(!bencode_start_dict(buf))
return false;
if(!BEncodeWriteDictMsgType(buf, "A", "I"))
return false;
if(!BEncodeWriteDictEntry("I", I, buf))
return false;
if(!BEncodeWriteDictInt(buf, "R", R))
return false;
if(hasS)
{
if(!BEncodeWriteDictInt(buf, "S", S))
return false;
}
if(!BEncodeWriteDictInt(buf, "V", LLARP_PROTO_VERSION))
return false;
return bencode_end(buf);
}
GotRouterMessage::~GotRouterMessage()
{
for(auto &rc : R)
@ -132,10 +286,10 @@ namespace llarp
}
bool
GotRouterMessage::HandleMessage(llarp_router *router,
GotRouterMessage::HandleMessage(llarp_dht_context *ctx,
std::vector< IMessage * > &replies) const
{
auto &dht = router->dht->impl;
auto &dht = ctx->impl;
auto pending = dht.FindPendingTX(From, txid);
if(pending)
{
@ -157,17 +311,18 @@ namespace llarp
&& dht.nodes->FindCloseExcluding(pending->target, nextPeer,
pending->exclude))
{
llarp::Info(pending->target, " was not found via ", From,
" iterating to next peer ", nextPeer, " already asked ",
pending->exclude.size(), " other peers");
llarp::LogInfo(pending->target, " was not found via ", From,
" iterating to next peer ", nextPeer,
" already asked ", pending->exclude.size(),
" other peers");
dht.LookupRouter(pending->target, pending->requester,
pending->requesterTX, nextPeer, nullptr, true,
pending->exclude);
}
else
{
llarp::Info(pending->target, " was not found via ", From,
" and we won't look it up");
llarp::LogInfo(pending->target, " was not found via ", From,
" and we won't look it up");
pending->Completed(nullptr);
if(pending->requester != dht.OurKey())
{
@ -179,8 +334,8 @@ namespace llarp
dht.RemovePendingLookup(From, txid);
return true;
}
llarp::Warn("Got response for DHT transaction we are not tracking, txid=",
txid);
llarp::LogWarn(
"Got response for DHT transaction we are not tracking, txid=", txid);
return false;
}
@ -263,20 +418,20 @@ namespace llarp
}
bool
FindRouterMessage::HandleMessage(llarp_router *router,
FindRouterMessage::HandleMessage(llarp_dht_context *ctx,
std::vector< IMessage * > &replies) const
{
auto &dht = router->dht->impl;
auto &dht = ctx->impl;
if(!dht.allowTransit)
{
llarp::Warn("Got DHT lookup from ", From,
" when we are not allowing dht transit");
llarp::LogWarn("Got DHT lookup from ", From,
" when we are not allowing dht transit");
return false;
}
auto pending = dht.FindPendingTX(From, txid);
if(pending)
{
llarp::Warn("Got duplicate DHT lookup from ", From, " txid=", txid);
llarp::LogWarn("Got duplicate DHT lookup from ", From, " txid=", txid);
return false;
}
dht.LookupRouterRelayed(From, txid, K, !iterative, replies);
@ -288,6 +443,7 @@ namespace llarp
const Key_t &From;
bool firstKey = true;
IMessage *msg = nullptr;
bool relayed = false;
MessageDecoder(const Key_t &from) : From(from)
{
@ -315,18 +471,32 @@ namespace llarp
switch(*strbuf.base)
{
case 'R':
dec->msg = new FindRouterMessage(dec->From);
if(dec->relayed)
dec->msg = new RelayedFindRouterMessage(dec->From);
else
dec->msg = new FindRouterMessage(dec->From);
break;
case 'S':
dec->msg = new GotRouterMessage(dec->From);
if(dec->relayed)
{
llarp::LogWarn(
"GotRouterMessage found when parsing relayed DHT "
"message");
return false;
}
else
dec->msg = new GotRouterMessage(dec->From);
break;
case 'I':
dec->msg = new PublishIntroMessage();
break;
default:
llarp::Warn("unknown dht message type: ", (char)*strbuf.base);
llarp::LogWarn("unknown dht message type: ", (char)*strbuf.base);
// bad msg type
return false;
}
dec->firstKey = false;
return true;
return dec->msg != nullptr;
}
else
return dec->msg->DecodeKey(*key, r->buffer);
@ -334,9 +504,10 @@ namespace llarp
};
IMessage *
DecodeMesssage(const Key_t &from, llarp_buffer_t *buf)
DecodeMesssage(const Key_t &from, llarp_buffer_t *buf, bool relayed)
{
MessageDecoder dec(from);
dec.relayed = relayed;
dict_reader r;
r.user = &dec;
r.on_key = &MessageDecoder::on_key;
@ -355,6 +526,7 @@ namespace llarp
ListDecoder(const Key_t &from, std::vector< IMessage * > &list)
: From(from), l(list){};
bool relayed = false;
const Key_t &From;
std::vector< IMessage * > &l;
@ -364,7 +536,7 @@ namespace llarp
ListDecoder *dec = static_cast< ListDecoder * >(r->user);
if(!has)
return true;
auto msg = DecodeMesssage(dec->From, r->buffer);
auto msg = DecodeMesssage(dec->From, r->buffer, dec->relayed);
if(msg)
{
dec->l.push_back(msg);
@ -377,10 +549,10 @@ namespace llarp
bool
DecodeMesssageList(const Key_t &from, llarp_buffer_t *buf,
std::vector< IMessage * > &list)
std::vector< IMessage * > &list, bool relayed)
{
ListDecoder dec(from, list);
dec.relayed = relayed;
list_reader r;
r.user = &dec;
r.on_item = &ListDecoder::on_item;
@ -477,8 +649,8 @@ namespace llarp
{
// we aren't closer to the target than next hop
// so we won't ask neighboor recursively, tell them we don't have it
llarp::Info("we aren't closer to ", target, " than ", next,
" so we end it here");
llarp::LogInfo("we aren't closer to ", target, " than ", next,
" so we end it here");
replies.push_back(new GotRouterMessage(requester, txid, nullptr));
}
else
@ -489,18 +661,18 @@ namespace llarp
}
else // otherwise tell them we don't have it
{
llarp::Info("we don't have ", target,
" and this was an iterative request so telling ",
requester, " that we don't have it");
llarp::LogInfo("we don't have ", target,
" and this was an iterative request so telling ",
requester, " that we don't have it");
replies.push_back(new GotRouterMessage(requester, txid, nullptr));
}
}
else
{
// we don't know it and have no closer peers
llarp::Info("we don't have ", target,
" and have no closer peers so telling ", requester,
" that we don't have it");
llarp::LogInfo("we don't have ", target,
" and have no closer peers so telling ", requester,
" that we don't have it");
replies.push_back(new GotRouterMessage(requester, txid, nullptr));
}
}
@ -534,7 +706,7 @@ namespace llarp
Context::CleanupTX()
{
auto now = llarp_time_now_ms();
llarp::Debug("DHT tick");
llarp::LogDebug("DHT tick");
auto itr = pendingTX.begin();
while(itr != pendingTX.end())
@ -556,7 +728,7 @@ namespace llarp
ourKey = us;
nodes = new Bucket< RCNode >(ourKey);
services = new Bucket< ISNode >(ourKey);
llarp::Debug("intialize dht with key ", ourKey);
llarp::LogDebug("intialize dht with key ", ourKey);
}
void
@ -569,8 +741,11 @@ namespace llarp
bool
Context::RelayRequestForPath(const llarp::PathID_t &id, const IMessage *msg)
{
// TODO: implement me
return false;
llarp::routing::DHTMessage reply;
if(!msg->HandleMessage(router->dht, reply.M))
return false;
auto path = router->paths.GetByUpstream(router->pubkey(), id);
return path && path->SendRoutingMessage(&reply, router);
}
void
@ -592,8 +767,8 @@ namespace llarp
pendingTX[ownerKey] = SearchJob(whoasked, txid, target, job, excludes);
llarp::Info("Asking ", askpeer, " for router ", target, " for ",
whoasked);
llarp::LogInfo("Asking ", askpeer, " for router ", target, " for ",
whoasked);
auto msg = new llarp::DHTImmeidateMessage(askpeer);
auto dhtmsg = new FindRouterMessage(askpeer, target, id);
dhtmsg->iterative = iterative;
@ -630,60 +805,61 @@ llarp_dht_context::llarp_dht_context(llarp_router *router)
parent = router;
}
extern "C" {
struct llarp_dht_context *
llarp_dht_context_new(struct llarp_router *router)
extern "C"
{
return new llarp_dht_context(router);
}
struct llarp_dht_context *
llarp_dht_context_new(struct llarp_router *router)
{
return new llarp_dht_context(router);
}
void
llarp_dht_context_free(struct llarp_dht_context *ctx)
{
delete ctx;
}
void
llarp_dht_context_free(struct llarp_dht_context *ctx)
{
delete ctx;
}
void
llarp_dht_put_peer(struct llarp_dht_context *ctx, struct llarp_rc *rc)
void
llarp_dht_put_peer(struct llarp_dht_context *ctx, struct llarp_rc *rc)
{
llarp::dht::RCNode n(rc);
ctx->impl.nodes->PutNode(n);
}
{
llarp::dht::RCNode n(rc);
ctx->impl.nodes->PutNode(n);
}
void
llarp_dht_remove_peer(struct llarp_dht_context *ctx, const byte_t *id)
{
llarp::dht::Key_t k = id;
ctx->impl.nodes->DelNode(k);
}
void
llarp_dht_remove_peer(struct llarp_dht_context *ctx, const byte_t *id)
{
llarp::dht::Key_t k = id;
ctx->impl.nodes->DelNode(k);
}
void
llarp_dht_set_msg_handler(struct llarp_dht_context *ctx,
llarp_dht_msg_handler handler)
{
ctx->impl.custom_handler = handler;
}
void
llarp_dht_set_msg_handler(struct llarp_dht_context *ctx,
llarp_dht_msg_handler handler)
{
ctx->impl.custom_handler = handler;
}
void
llarp_dht_allow_transit(llarp_dht_context *ctx)
{
ctx->impl.allowTransit = true;
}
void
llarp_dht_allow_transit(llarp_dht_context *ctx)
{
ctx->impl.allowTransit = true;
}
void
llarp_dht_context_start(struct llarp_dht_context *ctx, const byte_t *key)
{
ctx->impl.Init(key, ctx->parent);
}
void
llarp_dht_context_start(struct llarp_dht_context *ctx, const byte_t *key)
{
ctx->impl.Init(key, ctx->parent);
}
void
llarp_dht_lookup_router(struct llarp_dht_context *ctx,
struct llarp_router_lookup_job *job)
{
job->dht = ctx;
job->found = false;
llarp_logic_queue_job(ctx->parent->logic,
{job, &llarp::dht::Context::queue_router_lookup});
}
void
llarp_dht_lookup_router(struct llarp_dht_context *ctx,
struct llarp_router_lookup_job *job)
{
job->dht = ctx;
job->found = false;
llarp_logic_queue_job(ctx->parent->logic,
{job, &llarp::dht::Context::queue_router_lookup});
}
}

View File

@ -4,6 +4,6 @@ namespace llarp
{
DiscardMessage::~DiscardMessage()
{
llarp::Debug("~DiscardMessage");
llarp::LogDebug("~DiscardMessage");
}
}
} // namespace llarp

View File

@ -63,14 +63,14 @@ namespace llarp
// derive shared key
if(!DH(shared, otherPubkey, ourSecretKey, nonce))
{
llarp::Error("DH failed");
llarp::LogError("DH failed");
return false;
}
// encrypt body
if(!Encrypt(buf, shared, nonce))
{
llarp::Error("encrypt failed");
llarp::LogError("encrypt failed");
return false;
}
@ -81,7 +81,7 @@ namespace llarp
if(!MDS(hash, buf, shared))
{
llarp::Error("Failed to generate messgae auth");
llarp::LogError("Failed to generate messgae auth");
return false;
}
return true;
@ -92,8 +92,8 @@ namespace llarp
{
if(size() <= size_t(EncryptedFrame::OverheadSize))
{
llarp::Warn("encrypted frame too small, ", size(),
" <= ", size_t(EncryptedFrame::OverheadSize));
llarp::LogWarn("encrypted frame too small, ", size(),
" <= ", size_t(EncryptedFrame::OverheadSize));
return false;
}
// format of frame is
@ -122,19 +122,19 @@ namespace llarp
if(!DH(shared, otherPubkey, ourSecretKey, nonce))
{
llarp::Error("DH failed");
llarp::LogError("DH failed");
return false;
}
if(!MDS(digest, buf, shared))
{
llarp::Error("Digest failed");
llarp::LogError("Digest failed");
return false;
}
if(memcmp(digest, hash, digest.size()))
{
llarp::Error("message authentication failed");
llarp::LogError("message authentication failed");
return false;
}
@ -144,7 +144,7 @@ namespace llarp
if(!Decrypt(buf, shared, nonce))
{
llarp::Error("decrypt failed");
llarp::LogError("decrypt failed");
return false;
}
return true;

View File

@ -53,7 +53,7 @@ namespace llarp
ssize_t sent = ::sendto(fd, data, sz, SOCK_NONBLOCK, to, slen);
if(sent == -1)
{
llarp::Warn(strerror(errno));
llarp::LogWarn(strerror(errno));
}
return sent;
}
@ -116,7 +116,7 @@ struct llarp_epoll_loop : public llarp_ev_loop
// handle signalfd
if(events[idx].data.fd == pipefds[0])
{
llarp::Debug("exiting epoll loop");
llarp::LogDebug("exiting epoll loop");
return 0;
}
llarp::ev_io* ev = static_cast< llarp::ev_io* >(events[idx].data.ptr);
@ -124,7 +124,7 @@ struct llarp_epoll_loop : public llarp_ev_loop
{
if(ev->read(readbuf, sizeof(readbuf)) == -1)
{
llarp::Debug("close ev");
llarp::LogDebug("close ev");
close_ev(ev);
}
}
@ -154,7 +154,7 @@ struct llarp_epoll_loop : public llarp_ev_loop
// handle signalfd
if(events[idx].data.fd == pipefds[0])
{
llarp::Debug("exiting epoll loop");
llarp::LogDebug("exiting epoll loop");
return 0;
}
llarp::ev_io* ev = static_cast< llarp::ev_io* >(events[idx].data.ptr);
@ -162,7 +162,7 @@ struct llarp_epoll_loop : public llarp_ev_loop
{
if(ev->read(readbuf, sizeof(readbuf)) == -1)
{
llarp::Debug("close ev");
llarp::LogDebug("close ev");
close_ev(ev);
}
}
@ -211,7 +211,7 @@ struct llarp_epoll_loop : public llarp_ev_loop
}
}
llarp::Addr a(*addr);
llarp::Debug("bind to ", a);
llarp::LogDebug("bind to ", a);
if(bind(fd, addr, slen) == -1)
{
perror("bind()");

View File

@ -116,7 +116,7 @@ struct llarp_kqueue_loop : public llarp_ev_loop
llarp::ev_io* ev = static_cast< llarp::ev_io* >(events[idx].udata);
if(ev->read(readbuf, sizeof(readbuf)) == -1)
{
llarp::Info("close ev");
llarp::LogInfo("close ev");
close_ev(ev);
delete ev;
}
@ -147,7 +147,7 @@ struct llarp_kqueue_loop : public llarp_ev_loop
llarp::ev_io* ev = static_cast< llarp::ev_io* >(events[idx].udata);
if(ev->read(readbuf, sizeof(readbuf)) == -1)
{
llarp::Info("close ev");
llarp::LogInfo("close ev");
close_ev(ev);
delete ev;
}
@ -165,7 +165,7 @@ struct llarp_kqueue_loop : public llarp_ev_loop
udp_bind(const sockaddr* addr)
{
socklen_t slen;
llarp::Debug("kqueue bind affam", addr->sa_family);
llarp::LogDebug("kqueue bind affam", addr->sa_family);
switch(addr->sa_family)
{
case AF_INET:
@ -182,7 +182,7 @@ struct llarp_kqueue_loop : public llarp_ev_loop
break;
#endif
default:
llarp::Error("unsupported address family");
llarp::LogError("unsupported address family");
return -1;
}
int fd = socket(addr->sa_family, SOCK_DGRAM, 0);
@ -205,7 +205,7 @@ struct llarp_kqueue_loop : public llarp_ev_loop
}
}
llarp::Addr a(*addr);
llarp::Info("bind to ", a);
llarp::LogInfo("bind to ", a);
// FreeBSD handbook said to do this
if(addr->sa_family == AF_INET && INADDR_ANY)
a._addr4.sin_addr.s_addr = htonl(INADDR_ANY);

View File

@ -533,7 +533,7 @@ namespace iwp
nextMsgID = std::max(nextMsgID, front->msgid);
if(!router->HandleRecvLinkMessage(parent, front->Buffer()))
{
llarp::Warn("failed to process inbound message ", front->msgid);
llarp::LogWarn("failed to process inbound message ", front->msgid);
}
delete front;
q.pop();
@ -564,7 +564,7 @@ namespace iwp
void
push_ackfor(uint64_t id, uint32_t bitmask)
{
llarp::Debug("ACK for msgid=", id, " mask=", bitmask);
llarp::LogDebug("ACK for msgid=", id, " mask=", bitmask);
sendqueue.push(new sendbuf_t(12 + 6));
auto body_ptr = init_sendbuf(sendqueue.back(), eACKS, 12, txflags);
// TODO: this assumes big endian
@ -578,7 +578,7 @@ namespace iwp
if(hdr.size() > sz)
{
// overflow
llarp::Warn("invalid XMIT frame size ", hdr.size(), " > ", sz);
llarp::LogWarn("invalid XMIT frame size ", hdr.size(), " > ", sz);
return false;
}
sz = hdr.size();
@ -591,8 +591,8 @@ namespace iwp
if(sz - bufsz < x.lastfrag())
{
// bad size of last fragment
llarp::Warn("XMIT frag size missmatch ", sz - bufsz, " < ",
x.lastfrag());
llarp::LogWarn("XMIT frag size missmatch ", sz - bufsz, " < ",
x.lastfrag());
return false;
}
@ -605,8 +605,8 @@ namespace iwp
{
auto msg = new transit_message(x);
rx[id] = msg;
llarp::Debug("got message XMIT with ", (int)x.numfrags(),
" fragments");
llarp::LogDebug("got message XMIT with ", (int)x.numfrags(),
" fragments");
// inserted, put last fragment
msg->put_lastfrag(hdr.data() + sizeof(x.buffer), x.lastfrag());
push_ackfor(id, 0);
@ -617,10 +617,10 @@ namespace iwp
return true;
}
else
llarp::Warn("duplicate XMIT msgid=", x.msgid());
llarp::LogWarn("duplicate XMIT msgid=", x.msgid());
}
else
llarp::Warn("LSB not set on flags");
llarp::LogWarn("LSB not set on flags");
return false;
}
@ -636,7 +636,7 @@ namespace iwp
if(hdr.size() > sz)
{
// overflow
llarp::Warn("invalid FRAG frame size ", hdr.size(), " > ", sz);
llarp::LogWarn("invalid FRAG frame size ", hdr.size(), " > ", sz);
return false;
}
sz = hdr.size();
@ -644,7 +644,7 @@ namespace iwp
if(sz <= 9)
{
// underflow
llarp::Warn("invalid FRAG frame size ", sz, " <= 9");
llarp::LogWarn("invalid FRAG frame size ", sz, " <= 9");
return false;
}
@ -658,20 +658,20 @@ namespace iwp
auto itr = rx.find(msgid);
if(itr == rx.end())
{
llarp::Warn("no such RX fragment, msgid=", msgid);
llarp::LogWarn("no such RX fragment, msgid=", msgid);
return true;
}
auto fragsize = itr->second->msginfo.fragsize();
if(fragsize != sz - 9)
{
llarp::Warn("RX fragment size missmatch ", fragsize, " != ", sz - 9);
llarp::LogWarn("RX fragment size missmatch ", fragsize, " != ", sz - 9);
return false;
}
llarp::Debug("RX got fragment ", (int)fragno, " msgid=", msgid);
llarp::LogDebug("RX got fragment ", (int)fragno, " msgid=", msgid);
if(!itr->second->put_frag(fragno, hdr.data() + 9))
{
llarp::Warn("inbound message does not have fragment msgid=", msgid,
" fragno=", (int)fragno);
llarp::LogWarn("inbound message does not have fragment msgid=", msgid,
" fragno=", (int)fragno);
return false;
}
auto mask = itr->second->get_bitmask();
@ -716,7 +716,7 @@ namespace iwp
next_frame(llarp_buffer_t *buf)
{
auto left = sendqueue.size();
llarp::Debug("next frame, ", left, " frames left in send queue");
llarp::LogDebug("next frame, ", left, " frames left in send queue");
if(left)
{
sendbuf_t *send = sendqueue.front();
@ -747,23 +747,23 @@ namespace iwp
switch(hdr.msgtype())
{
case eALIV:
llarp::Debug("iwp_link::frame_state::process Got alive");
llarp::LogDebug("iwp_link::frame_state::process Got alive");
if(rxflags & eSessionInvalidated)
{
txflags |= eSessionInvalidated;
}
return true;
case eXMIT:
llarp::Debug("iwp_link::frame_state::process Got xmit");
llarp::LogDebug("iwp_link::frame_state::process Got xmit");
return got_xmit(hdr, sz - 6);
case eACKS:
llarp::Debug("iwp_link::frame_state::process Got ack");
llarp::LogDebug("iwp_link::frame_state::process Got ack");
return got_acks(hdr, sz - 6);
case eFRAG:
llarp::Debug("iwp_link::frame_state::process Got frag");
llarp::LogDebug("iwp_link::frame_state::process Got frag");
return got_frag(hdr, sz - 6);
default:
llarp::Warn(
llarp::LogWarn(
"iwp_link::frame_state::process - unknown header message type: ",
(int)hdr.msgtype());
return false;
@ -870,14 +870,14 @@ namespace iwp
crypto->encryption_keygen(eph_seckey);
llarp_rc_clear(&remote_router);
crypto->randbytes(token, 32);
llarp::Info("session created");
llarp::LogInfo("session created");
}
~session()
{
llarp_rc_free(&remote_router);
frame.clear();
llarp::Info("session destroyed");
llarp::LogInfo("session destroyed");
}
static llarp_rc *
@ -892,7 +892,7 @@ namespace iwp
{
session *self = static_cast< session * >(s->impl);
auto id = self->frame.txids++;
// llarp::Debug("session sending to, number", id);
// llarp::LogDebug("session sending to, number", id);
llarp::ShortHash digest;
self->crypto->shorthash(digest, msg);
transit_message *m = new transit_message(msg, digest, id);
@ -903,10 +903,10 @@ namespace iwp
void
add_outbound_message(uint64_t id, transit_message *msg)
{
llarp::Debug("add outbound message ", id, " of size ",
msg->msginfo.totalsize(),
" numfrags=", (int)msg->msginfo.numfrags(),
" lastfrag=", (int)msg->msginfo.lastfrag());
llarp::LogDebug("add outbound message ", id, " of size ",
msg->msginfo.totalsize(),
" numfrags=", (int)msg->msginfo.numfrags(),
" lastfrag=", (int)msg->msginfo.lastfrag());
frame.queue_tx(id, msg);
pump();
@ -1006,7 +1006,7 @@ namespace iwp
void
pump()
{
// llarp::Info("session pump");
// llarp::LogInfo("session pump");
// TODO: in codel the timestamp may cause excssive drop when all the
// packets have a similar timestamp
now = llarp_time_now_ms();
@ -1022,10 +1022,10 @@ namespace iwp
void
recv(const void *buf, size_t sz)
{
// llarp::Debug("session recv", state);
// llarp::LogDebug("session recv", state);
// frame_header hdr((byte_t *)buf);
// llarp::Debug("recv - message header type ", (int)hdr.msgtype());
// llarp::LogDebug("recv - message header type ", (int)hdr.msgtype());
now = llarp_time_now_ms();
switch(state)
@ -1033,17 +1033,17 @@ namespace iwp
case eInitial:
case eIntroRecv:
// got intro
llarp::Debug("session recv - intro");
llarp::LogDebug("session recv - intro");
on_intro(buf, sz);
break;
case eIntroSent:
// got intro ack
llarp::Debug("session recv - introack");
llarp::LogDebug("session recv - introack");
on_intro_ack(buf, sz);
break;
case eIntroAckSent:
// probably a session start
llarp::Debug("session recv - sessionstart");
llarp::LogDebug("session recv - sessionstart");
on_session_start(buf, sz);
break;
@ -1051,15 +1051,15 @@ namespace iwp
case eLIMSent:
case eEstablished:
// session is started
llarp::Debug("session recv - ",
state == eSessionStartSent ? "startsent" : "",
state == eLIMSent ? "limset" : "",
state == eEstablished ? "established" : "");
llarp::LogDebug("session recv - ",
state == eSessionStartSent ? "startsent" : "",
state == eLIMSent ? "limset" : "",
state == eEstablished ? "established" : "");
decrypt_frame(buf, sz);
break;
default:
llarp::Error("session recv - invalid state");
llarp::LogError("session recv - invalid state");
// invalid state?
break;
}
@ -1071,7 +1071,7 @@ namespace iwp
void
send_LIM()
{
llarp::Debug("send LIM");
llarp::LogDebug("send LIM");
llarp::ShortHash digest;
// 64 bytes overhead for link message
byte_t tmp[MAX_RC_SIZE + 64];
@ -1092,7 +1092,7 @@ namespace iwp
EnterState(eLIMSent);
}
else
llarp::Error("LIM Encode failed");
llarp::LogError("LIM Encode failed");
}
static void
@ -1117,10 +1117,10 @@ namespace iwp
void
on_session_start(const void *buf, size_t sz)
{
llarp::Info("session start");
llarp::LogInfo("session start");
if(sz > sizeof(workbuf))
{
llarp::Debug("session start too big");
llarp::LogDebug("session start too big");
return;
}
// own the buffer
@ -1193,7 +1193,7 @@ namespace iwp
void
session_start()
{
llarp::Info("session gen start");
llarp::LogInfo("session gen start");
size_t w2sz = rand() % MAX_PAD;
start.buf = workbuf;
start.sz = w2sz + (32 * 3);
@ -1216,7 +1216,7 @@ namespace iwp
handle_frame_decrypt(iwp_async_frame *frame)
{
session *self = static_cast< session * >(frame->user);
llarp::Debug("rx ", frame->sz);
llarp::LogDebug("rx ", frame->sz);
if(frame->success)
{
if(self->frame.process(frame->buf + 64, frame->sz - 64))
@ -1225,10 +1225,10 @@ namespace iwp
self->pump();
}
else
llarp::Error("invalid frame from ", self->addr);
llarp::LogError("invalid frame from ", self->addr);
}
else
llarp::Error("decrypt frame fail from ", self->addr);
llarp::LogError("decrypt frame fail from ", self->addr);
}
void
@ -1252,13 +1252,13 @@ namespace iwp
ManualPumpInboundCodel();
}
else
llarp::Warn("decrypt frame fail");
llarp::LogWarn("decrypt frame fail");
*/
f->hook = &handle_frame_decrypt;
iwp_call_async_frame_decrypt(iwp, f);
}
else
llarp::Warn("short packet of ", sz, " bytes");
llarp::LogWarn("short packet of ", sz, " bytes");
}
// static void
@ -1283,7 +1283,7 @@ namespace iwp
}
else
{
llarp::Warn("DecryptInboundFrames - cant decrypt frame");
llarp::LogWarn("DecryptInboundFrames - cant decrypt frame");
}
inq.pop();
}
@ -1302,10 +1302,10 @@ namespace iwp
handle_frame_encrypt(iwp_async_frame *frame)
{
session *self = static_cast< session * >(frame->user);
llarp::Debug("tx ", frame->sz);
llarp::LogDebug("tx ", frame->sz);
if(llarp_ev_udp_sendto(self->udp, self->addr, frame->buf, frame->sz)
== -1)
llarp::Warn("sendto failed");
llarp::LogWarn("sendto failed");
}
iwp_async_frame *
@ -1314,7 +1314,7 @@ namespace iwp
// TODO don't hard code 1500
if(sz > 1500)
{
llarp::Warn("alloc frame - frame too big, >1500");
llarp::LogWarn("alloc frame - frame too big, >1500");
return nullptr;
}
@ -1327,7 +1327,7 @@ namespace iwp
frame->sessionkey = sessionkey;
/// TODO: this could be rather slow
// frame->created = now;
// llarp::Info("alloc_frame putting into q");
// llarp::LogInfo("alloc_frame putting into q");
// q.Put(frame);
return frame;
}
@ -1389,17 +1389,17 @@ namespace iwp
link->working = false;
if(i->buf)
{
llarp::Info("send intro to ", link->addr);
llarp::LogInfo("send intro to ", link->addr);
if(llarp_ev_udp_sendto(link->udp, link->addr, i->buf, i->sz) == -1)
{
llarp::Warn("send intro failed");
llarp::LogWarn("send intro failed");
return;
}
link->EnterState(eIntroSent);
}
else
{
llarp::Warn("failed to generate intro");
llarp::LogWarn("failed to generate intro");
}
}
@ -1409,7 +1409,7 @@ namespace iwp
void
introduce(uint8_t *pub)
{
llarp::Debug("session introduce");
llarp::LogDebug("session introduce");
memcpy(remote, pub, 32);
intro.buf = workbuf;
size_t w0sz = (rand() % MAX_PAD);
@ -1430,8 +1430,8 @@ namespace iwp
intro.user = this;
intro.hook = &handle_generated_intro;
working = true;
llarp::Info("try introduce to transport adddress ",
llarp::RouterID(remote));
llarp::LogInfo("try introduce to transport adddress ",
llarp::RouterID(remote));
iwp_call_async_gen_intro(iwp, &intro);
// start introduce timer
establish_job_id = llarp_logic_call_later(
@ -1446,14 +1446,14 @@ namespace iwp
void
EnterState(State st)
{
llarp::Debug("EnterState - entering state: ", st,
state == eLIMSent ? "eLIMSent" : "",
state == eSessionStartSent ? "eSessionStartSent" : "");
llarp::LogDebug("EnterState - entering state: ", st,
state == eLIMSent ? "eLIMSent" : "",
state == eSessionStartSent ? "eSessionStartSent" : "");
frame.alive();
state = st;
if(state == eSessionStartSent || state == eIntroAckSent)
{
// llarp::Info("EnterState - ", state==eLIMSent?"eLIMSent":"",
// llarp::LogInfo("EnterState - ", state==eLIMSent?"eLIMSent":"",
// state==eSessionStartSent?"eSessionStartSent":""); PumpCodelInbound();
// PumpCodelOutbound();
PumpCryptoOutbound();
@ -1678,7 +1678,7 @@ namespace iwp
auto itr = m_sessions.find(addr);
if(itr != m_sessions.end())
{
llarp::Debug("removing session ", addr);
llarp::LogDebug("removing session ", addr);
UnmapAddr(addr);
session *s = static_cast< session * >(itr->second->impl);
s->done();
@ -1697,7 +1697,7 @@ namespace iwp
bool
ensure_privkey()
{
llarp::Debug("ensure transport private key at ", keyfile);
llarp::LogDebug("ensure transport private key at ", keyfile);
std::error_code ec;
if(!fs::exists(keyfile, ec))
{
@ -1717,7 +1717,7 @@ namespace iwp
keygen(const char *fname)
{
crypto->encryption_keygen(seckey);
llarp::Info("new transport key generated");
llarp::LogInfo("new transport key generated");
std::ofstream f(fname);
if(f.is_open())
{
@ -1785,9 +1785,9 @@ namespace iwp
router->crypto.shorthash(digest, buf);
if(memcmp(digest, rxmsg->msginfo.hash(), 32))
{
llarp::Warn("message hash missmatch ",
llarp::AlignedBuffer< 32 >(digest),
" != ", llarp::AlignedBuffer< 32 >(rxmsg->msginfo.hash()));
llarp::LogWarn(
"message hash missmatch ", llarp::AlignedBuffer< 32 >(digest),
" != ", llarp::AlignedBuffer< 32 >(rxmsg->msginfo.hash()));
return false;
}
if(id == nextMsgID)
@ -1809,7 +1809,7 @@ namespace iwp
else
{
llarp::PubKey k = impl->remote_router.pubkey;
llarp::Warn("spoofed LIM from ", k);
llarp::LogWarn("spoofed LIM from ", k);
impl->parent->close(impl->parent);
success = false;
}
@ -1822,8 +1822,8 @@ namespace iwp
}
else
{
llarp::Warn("out of order message expected ", nextMsgID, " but got ",
id);
llarp::LogWarn("out of order message expected ", nextMsgID, " but got ",
id);
recvqueue.Put(new InboundMessage(id, msg));
success = true;
}
@ -1832,7 +1832,7 @@ namespace iwp
rx.erase(id);
if(!success)
llarp::Warn("Failed to process inbound message ", id);
llarp::LogWarn("Failed to process inbound message ", id);
return success;
}
@ -1844,8 +1844,8 @@ namespace iwp
if(!intro->buf)
{
self->serv->remove_intro_from(self->addr);
llarp::Error("intro verify failed from ", self->addr, " via ",
self->serv->addr);
llarp::LogError("intro verify failed from ", self->addr, " via ",
self->serv->addr);
delete self;
return;
}
@ -1858,7 +1858,7 @@ namespace iwp
session *link = static_cast< session * >(start->user);
link->working = false;
if(llarp_ev_udp_sendto(link->udp, link->addr, start->buf, start->sz) == -1)
llarp::Error("sendto failed");
llarp::LogError("sendto failed");
link->EnterState(eSessionStartSent);
link->serv->remove_intro_from(link->addr);
}
@ -1866,17 +1866,17 @@ namespace iwp
void
session::on_intro(const void *buf, size_t sz)
{
llarp::Debug("session onintro");
llarp::LogDebug("session onintro");
if(sz >= sizeof(workbuf))
{
// too big?
llarp::Error("intro too big");
llarp::LogError("intro too big");
delete this;
return;
}
if(serv->has_intro_from(addr))
{
llarp::Error("duplicate intro from ", addr);
llarp::LogError("duplicate intro from ", addr);
delete this;
return;
}
@ -1906,10 +1906,10 @@ namespace iwp
{
if(serv->has_session_to(addr))
{
llarp::Warn("won't ack intro for duplicate session from ", addr);
llarp::LogWarn("won't ack intro for duplicate session from ", addr);
return;
}
llarp::Debug("session introack");
llarp::LogDebug("session introack");
uint16_t w1sz = rand() % MAX_PAD;
introack.buf = workbuf;
introack.sz = (32 * 3) + w1sz;
@ -1938,7 +1938,7 @@ namespace iwp
session::session_established()
{
llarp::RouterID remote = remote_router.pubkey;
llarp::Info("session to ", remote, " established");
llarp::LogInfo("session to ", remote, " established");
EnterState(eEstablished);
serv->MapAddr(addr, remote_router.pubkey);
llarp_logic_cancel_call(logic, establish_job_id);
@ -1970,7 +1970,7 @@ namespace iwp
if(sz >= sizeof(workbuf))
{
// too big?
llarp::Error("introack too big");
llarp::LogError("introack too big");
serv->RemoveSessionByAddr(addr);
return;
}
@ -1999,7 +1999,7 @@ namespace iwp
if(self->is_invalidated())
{
// don't send keepalive
llarp::Info("session cant send keepalive because were invalid");
llarp::LogInfo("session cant send keepalive because were invalid");
return;
}
// all zeros means keepalive
@ -2022,13 +2022,13 @@ namespace iwp
{
if(hdr.size() > sz)
{
llarp::Error("invalid ACKS frame size ", hdr.size(), " > ", sz);
llarp::LogError("invalid ACKS frame size ", hdr.size(), " > ", sz);
return false;
}
sz = hdr.size();
if(sz < 12)
{
llarp::Error("invalid ACKS frame size ", sz, " < 12");
llarp::LogError("invalid ACKS frame size ", sz, " < 12");
return false;
}
@ -2041,7 +2041,7 @@ namespace iwp
auto itr = tx.find(msgid);
if(itr == tx.end())
{
llarp::Debug("ACK for missing TX frame msgid=", msgid);
llarp::LogDebug("ACK for missing TX frame msgid=", msgid);
return true;
}
@ -2051,13 +2051,13 @@ namespace iwp
if(msg->completed())
{
llarp::Debug("message transmitted msgid=", msgid);
llarp::LogDebug("message transmitted msgid=", msgid);
tx.erase(msgid);
delete msg;
}
else
{
llarp::Debug("message ", msgid, " retransmit fragments");
llarp::LogDebug("message ", msgid, " retransmit fragments");
msg->retransmit_frags(sendqueue, txflags);
}
@ -2080,7 +2080,7 @@ namespace iwp
if(introack->buf == nullptr)
{
// invalid signature
llarp::Error("introack verify failed from ", link->addr);
llarp::LogError("introack verify failed from ", link->addr);
link->serv->remove_intro_from(link->addr);
link->serv->RemoveSessionByAddr(link->addr);
return;
@ -2097,7 +2097,8 @@ namespace iwp
// we are timed out
// when we are done doing stuff with all of our frames from the crypto
// workers we are done
llarp::Warn("Tick - ", addr, " timed out with ", frames, " frames left");
llarp::LogWarn("Tick - ", addr, " timed out with ", frames,
" frames left");
return !working;
}
if(is_invalidated())
@ -2105,8 +2106,8 @@ namespace iwp
// both sides agreeed to session invalidation
// terminate our session when all of our frames from the crypto workers
// are done
llarp::Warn("Tick - ", addr, " invaldiated session with ", frames,
" frames left");
llarp::LogWarn("Tick - ", addr, " invaldiated session with ", frames,
" frames left");
return !working;
}
if(state == eLIMSent || state == eEstablished)
@ -2118,7 +2119,7 @@ namespace iwp
// pump frame state
if(state == eEstablished)
{
// llarp::Debug("Tick - pumping and retransmitting because we're
// llarp::LogDebug("Tick - pumping and retransmitting because we're
// eEstablished");
frame.retransmit(now);
@ -2153,7 +2154,7 @@ namespace iwp
{
// verify fail
// TODO: remove session?
llarp::Warn("session start verify failed from ", self->addr);
llarp::LogWarn("session start verify failed from ", self->addr);
self->serv->RemoveSessionByAddr(self->addr);
return;
}
@ -2201,11 +2202,12 @@ namespace iwp
server *link = static_cast< server * >(l->impl);
if(!link->ensure_privkey())
{
llarp::Error("failed to ensure private key");
llarp::LogError("failed to ensure private key");
return false;
}
llarp::Debug("configure link ifname=", ifname, " af=", af, " port=", port);
llarp::LogDebug("configure link ifname=", ifname, " af=", af,
" port=", port);
// bind
sockaddr_in ip4addr;
sockaddr_in6 ip6addr;
@ -2222,7 +2224,7 @@ namespace iwp
break;
// TODO: AF_PACKET
default:
llarp::Error(__FILE__, "unsupported address family", af);
llarp::LogError(__FILE__, "unsupported address family", af);
return false;
}
@ -2232,7 +2234,7 @@ namespace iwp
{
if(!llarp_getifaddr(ifname, af, addr))
{
llarp::Error("failed to get address of network interface ", ifname);
llarp::LogError("failed to get address of network interface ", ifname);
return false;
}
}
@ -2257,10 +2259,10 @@ namespace iwp
link->udp.recvfrom = &server::handle_recvfrom;
link->udp.user = link;
link->udp.tick = nullptr;
llarp::Debug("bind IWP link to ", link->addr);
llarp::LogDebug("bind IWP link to ", link->addr);
if(llarp_ev_add_udp(link->netloop, &link->udp, link->addr) == -1)
{
llarp::Error("failed to bind to ", link->addr);
llarp::LogError("failed to bind to ", link->addr);
return false;
}
return true;
@ -2296,7 +2298,7 @@ namespace iwp
auto sz = link->m_sessions.size();
if(sz)
{
llarp::Debug("we have ", sz, "sessions");
llarp::LogDebug("we have ", sz, "sessions");
iter.link = l;
// TODO: race condition with cleanup timer
for(auto &item : link->m_sessions)
@ -2312,7 +2314,7 @@ namespace iwp
server *link = static_cast< server * >(l->impl);
{
llarp::Addr dst(job->ai);
llarp::Debug("establish session to ", dst);
llarp::LogDebug("establish session to ", dst);
session *s = link->find_session(dst);
if(s == nullptr)
{
@ -2377,19 +2379,20 @@ namespace iwp
if(link->serv->has_session_to(link->addr))
{
// duplicate session
llarp::Warn("duplicate session to ", link->addr);
llarp::LogWarn("duplicate session to ", link->addr);
return;
}
link->frame.alive();
link->EnterState(eIntroAckSent);
link->serv->put_session(link->addr, link);
llarp::Debug("send introack to ", link->addr, " via ", link->serv->addr);
llarp::LogDebug("send introack to ", link->addr, " via ",
link->serv->addr);
llarp_ev_udp_sendto(link->udp, link->addr, i->buf, i->sz);
}
else
{
// failed to generate?
llarp::Warn("failed to generate introack");
llarp::LogWarn("failed to generate introack");
}
}
} // namespace iwp

View File

@ -17,11 +17,11 @@ namespace llarp
{
if(!llarp_rc_bdecode(RC, buf))
{
llarp::Warn("failed to decode RC");
llarp::LogWarn("failed to decode RC");
return false;
}
remote = (byte_t*)RC->pubkey;
llarp::Debug("decoded RC from ", remote);
llarp::LogDebug("decoded RC from ", remote);
return true;
}
else if(llarp_buffer_eq(key, "v"))
@ -30,16 +30,16 @@ namespace llarp
return false;
if(version != LLARP_PROTO_VERSION)
{
llarp::Warn("llarp protocol version missmatch ", version,
" != ", LLARP_PROTO_VERSION);
llarp::LogWarn("llarp protocol version missmatch ", version,
" != ", LLARP_PROTO_VERSION);
return false;
}
llarp::Debug("LIM version ", version);
llarp::LogDebug("LIM version ", version);
return true;
}
else
{
llarp::Warn("invalid LIM key: ", *key.cur);
llarp::LogWarn("invalid LIM key: ", *key.cur);
return false;
}
}

View File

@ -33,23 +33,23 @@ namespace llarp
// we are expecting the first key to be 'a'
if(!llarp_buffer_eq(*key, "a"))
{
llarp::Warn("message has no message type");
llarp::LogWarn("message has no message type");
return false;
}
if(!bencode_read_string(r->buffer, &strbuf))
{
llarp::Warn("could not read value of message type");
llarp::LogWarn("could not read value of message type");
return false;
}
// bad key size
if(strbuf.sz != 1)
{
llarp::Warn("bad mesage type size: ", strbuf.sz);
llarp::LogWarn("bad mesage type size: ", strbuf.sz);
return false;
}
// create the message to parse based off message type
llarp::Debug("inbound message ", *strbuf.cur);
llarp::LogDebug("inbound message ", *strbuf.cur);
switch(*strbuf.cur)
{
case 'i':

View File

@ -61,7 +61,7 @@ llarp_logic_stop_timer(struct llarp_logic* logic)
void
llarp_logic_stop(struct llarp_logic* logic)
{
llarp::Debug("logic thread stop");
llarp::LogDebug("logic thread stop");
if(logic->thread)
{
llarp_threadpool_stop(logic->thread);
@ -69,7 +69,7 @@ llarp_logic_stop(struct llarp_logic* logic)
}
llarp_free_threadpool(&logic->thread);
llarp::Debug("logic timer stop");
llarp::LogDebug("logic timer stop");
if(logic->timer)
llarp_timer_stop(logic->timer);
}

View File

@ -38,7 +38,6 @@ operator<(const in6_addr& a, const in6_addr& b)
}
extern "C" {
bool
llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr)
{
@ -55,11 +54,11 @@ llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr)
{
if(i->ifa_addr)
{
// llarp::Info(__FILE__, "scanning ", i->ifa_name, " af: ",
// llarp::LogInfo(__FILE__, "scanning ", i->ifa_name, " af: ",
// std::to_string(i->ifa_addr->sa_family));
if(llarp::StrEq(i->ifa_name, ifname) && i->ifa_addr->sa_family == af)
{
// llarp::Info(__FILE__, "found ", ifname, " af: ", af);
// llarp::LogInfo(__FILE__, "found ", ifname, " af: ", af);
memcpy(addr, i->ifa_addr, sl);
if(af == AF_INET6)
{

View File

@ -55,9 +55,9 @@ struct llarp_nodedb
auto itr = this->entries.begin();
while(itr != this->entries.end())
{
llarp::Info("Has byte_t [", test.size(), "] vs [", itr->first.size(),
llarp::LogInfo("Has byte_t [", test.size(), "] vs [", itr->first.size(),
"]"); if (memcmp(test.data(), itr->first.data(), 32) == 0) {
llarp::Info("Match");
llarp::LogInfo("Match");
}
itr++;
}
@ -137,7 +137,7 @@ struct llarp_nodedb
{
buf.sz = buf.cur - buf.base;
auto filepath = getRCFilePath(pk);
llarp::Debug("saving RC.pubkey ", filepath);
llarp::LogDebug("saving RC.pubkey ", filepath);
std::ofstream ofs(
filepath,
std::ofstream::out & std::ofstream::binary & std::ofstream::trunc);
@ -145,10 +145,10 @@ struct llarp_nodedb
ofs.close();
if(!ofs)
{
llarp::Error("Failed to write: ", filepath);
llarp::LogError("Failed to write: ", filepath);
return false;
}
llarp::Debug("saved RC.pubkey: ", filepath);
llarp::LogDebug("saved RC.pubkey: ", filepath);
return true;
}
return false;
@ -206,12 +206,12 @@ struct llarp_nodedb
llarp_rc *rc = llarp_rc_read(fpath.c_str());
if(!rc)
{
llarp::Error("Signature read failed", fpath);
llarp::LogError("Signature read failed", fpath);
return false;
}
if(!llarp_rc_verify_sig(crypto, rc))
{
llarp::Error("Signature verify failed", fpath);
llarp::LogError("Signature verify failed", fpath);
return false;
}
llarp::PubKey pk(rc->pubkey);
@ -283,14 +283,14 @@ crypto_threadworker_verifyrc(void *user)
// if it's valid we need to set it
if(verify_request->valid)
{
llarp::Debug("RC is valid, saving to disk");
llarp::LogDebug("RC is valid, saving to disk");
llarp_threadpool_queue_job(verify_request->diskworker,
{verify_request, &disk_threadworker_setRC});
}
else
{
// callback to logic thread
llarp::Warn("RC is not valid, can't save to disk");
llarp::LogWarn("RC is not valid, can't save to disk");
llarp_logic_queue_job(verify_request->logic,
{verify_request, &logic_threadworker_callback});
}
@ -413,7 +413,7 @@ llarp_nodedb_async_load_rc(struct llarp_async_load_rc *job)
struct llarp_rc *
llarp_nodedb_get_rc(struct llarp_nodedb *n, const byte_t *pk)
{
// llarp::Info("llarp_nodedb_get_rc [", pk, "]");
// llarp::LogInfo("llarp_nodedb_get_rc [", pk, "]");
if(n->Has(pk))
return n->getRC(pk);
else

View File

@ -64,7 +64,7 @@ namespace llarp
PathContext::ForwardLRCM(const RouterID& nextHop,
std::deque< EncryptedFrame >& frames)
{
llarp::Info("fowarding LRCM to ", nextHop);
llarp::LogInfo("fowarding LRCM to ", nextHop);
LR_CommitMessage* msg = new LR_CommitMessage;
while(frames.size())
{
@ -213,7 +213,7 @@ namespace llarp
if(itr->second->Expired(now))
{
TransitHop* path = itr->second;
llarp::Info("transit path expired ", path->info);
llarp::LogInfo("transit path expired ", path->info);
removePaths.insert(path);
}
++itr;
@ -368,7 +368,7 @@ namespace llarp
{
if(!m_InboundMessageParser.ParseMessageBuffer(buf, this, r))
{
llarp::Warn("Failed to parse inbound routing message");
llarp::LogWarn("Failed to parse inbound routing message");
return false;
}
return true;
@ -395,8 +395,8 @@ namespace llarp
Path::HandlePathTransferMessage(
const llarp::routing::PathTransferMessage* msg, llarp_router* r)
{
llarp::Warn("unwarrented path transfer message on tx=", TXID(),
" rx=", RXID());
llarp::LogWarn("unwarrented path transfer message on tx=", TXID(),
" rx=", RXID());
return false;
}
@ -408,7 +408,7 @@ namespace llarp
{
// confirm that we build the path
status = ePathEstablished;
llarp::Info("path is confirmed tx=", TXID(), " rx=", RXID());
llarp::LogInfo("path is confirmed tx=", TXID(), " rx=", RXID());
if(m_BuiltHook)
m_BuiltHook(this);
m_BuiltHook = nullptr;
@ -418,8 +418,8 @@ namespace llarp
m_LastLatencyTestTime = llarp_time_now_ms();
return SendRoutingMessage(&latency, r);
}
llarp::Warn("got unwarrented path confirm message on tx=", RXID(),
" rx=", RXID());
llarp::LogWarn("got unwarrented path confirm message on tx=", RXID(),
" rx=", RXID());
return false;
}
@ -430,8 +430,8 @@ namespace llarp
if(msg->L == m_LastLatencyTestID)
{
Latency = llarp_time_now_ms() - m_LastLatencyTestTime;
llarp::Info("path latency is ", Latency, " ms for tx=", TXID(),
" rx=", RXID());
llarp::LogInfo("path latency is ", Latency, " ms for tx=", TXID(),
" rx=", RXID());
m_LastLatencyTestID = 0;
return true;
}
@ -441,8 +441,11 @@ namespace llarp
bool
Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp_router* r)
{
// TODO: implement me
return false;
std::vector< llarp::dht::IMessage* > discard;
auto result = msg->HandleMessage(r->dht, discard);
for(auto& msg : discard)
delete msg;
return result;
}
} // namespace path
} // namespace llarp

View File

@ -46,7 +46,7 @@ namespace llarp
if(!ctx->crypto->dh_client(hop.shared, hop.router.enckey, hop.commkey,
hop.nonce))
{
llarp::Error("Failed to generate shared key for path build");
llarp::LogError("Failed to generate shared key for path build");
abort();
return;
}
@ -78,7 +78,7 @@ namespace llarp
if(!record.BEncode(buf))
{
// failed to encode?
llarp::Error("Failed to generate Commit Record");
llarp::LogError("Failed to generate Commit Record");
return;
}
// use ephameral keypair for frame
@ -86,7 +86,7 @@ namespace llarp
ctx->crypto->encryption_keygen(framekey);
if(!frame.EncryptInPlace(framekey, hop.router.enckey, ctx->crypto))
{
llarp::Error("Failed to encrypt LRCR");
llarp::LogError("Failed to encrypt LRCR");
return;
}
@ -132,11 +132,11 @@ namespace llarp
AsyncPathKeyExchangeContext< llarp_pathbuild_job >* ctx)
{
auto remote = ctx->path->Upstream();
llarp::Info("Generated LRCM to ", remote);
llarp::LogInfo("Generated LRCM to ", remote);
auto router = ctx->user->router;
if(!router->SendToOrQueue(remote, ctx->LRCM))
{
llarp::Error("failed to send LRCM");
llarp::LogError("failed to send LRCM");
return;
}
ctx->path->status = llarp::path::ePathBuilding;
@ -213,7 +213,7 @@ llarp_pathbuilder_build_path(struct llarp_pathbuild_job* job)
{
if(!job->context)
{
llarp::Error("failed to build path because no context is set in job");
llarp::LogError("failed to build path because no context is set in job");
return;
}
job->router = job->context->router;

View File

@ -82,8 +82,8 @@ namespace llarp
PathSet::HandlePathBuilt(Path* path)
{
auto dlt = llarp_time_now_ms() - path->buildStarted;
llarp::Info("Path build took ", dlt, "ms for tx=", path->TXID(),
" rx=", path->RXID());
llarp::LogInfo("Path build took ", dlt, "ms for tx=", path->TXID(),
" rx=", path->RXID());
}
} // namespace path

View File

@ -61,13 +61,13 @@ namespace llarp
{
if(!buf)
{
llarp::Error("Failed to decrypt LRAM frame");
llarp::LogError("Failed to decrypt LRAM frame");
delete self;
return;
}
if(!self->record.BDecode(buf))
{
llarp::Error("LRAR invalid format");
llarp::LogError("LRAR invalid format");
delete self;
return;
}

View File

@ -49,14 +49,14 @@ namespace llarp
{
if(frames.size() != MAXHOPS)
{
llarp::Error("LRCM invalid number of records, ", frames.size(),
"!=", MAXHOPS);
llarp::LogError("LRCM invalid number of records, ", frames.size(),
"!=", MAXHOPS);
return false;
}
if(!router->paths.AllowingTransit())
{
llarp::Error("got an LRCM from ", remote,
" when we are not allowing transit");
llarp::LogError("got an LRCM from ", remote,
" when we are not allowing transit");
return false;
}
return AsyncDecrypt(&router->paths);
@ -128,7 +128,7 @@ namespace llarp
// check for duplicate
if(self->work)
{
llarp::Warn("duplicate POW in LRCR");
llarp::LogWarn("duplicate POW in LRCR");
return false;
}
@ -202,7 +202,8 @@ namespace llarp
llarp::routing::PathConfirmMessage confirm(self->hop->lifetime);
if(!self->hop->SendRoutingMessage(&confirm, self->context->Router()))
{
llarp::Error("failed to send path confirmation for ", self->hop->info);
llarp::LogError("failed to send path confirmation for ",
self->hop->info);
}
delete self;
}
@ -213,16 +214,16 @@ namespace llarp
auto& info = self->hop->info;
if(!buf)
{
llarp::Error("LRCM decrypt failed from ", info.downstream);
llarp::LogError("LRCM decrypt failed from ", info.downstream);
delete self;
return;
}
buf->cur = buf->base + EncryptedFrame::OverheadSize;
llarp::Debug("decrypted LRCM from ", info.downstream);
llarp::LogDebug("decrypted LRCM from ", info.downstream);
// successful decrypt
if(!self->record.BDecode(buf))
{
llarp::Error("malformed frame inside LRCM from ", info.downstream);
llarp::LogError("malformed frame inside LRCM from ", info.downstream);
delete self;
return;
}
@ -232,7 +233,7 @@ namespace llarp
info.upstream = self->record.nextHop;
if(self->context->HasTransitHop(info))
{
llarp::Error("duplicate transit hop ", info);
llarp::LogError("duplicate transit hop ", info);
delete self;
return;
}
@ -241,7 +242,7 @@ namespace llarp
if(!DH(self->hop->pathKey, self->record.commkey,
self->context->EncryptionSecretKey(), self->record.tunnelNonce))
{
llarp::Error("LRCM DH Failed ", info);
llarp::LogError("LRCM DH Failed ", info);
delete self;
return;
}
@ -249,20 +250,21 @@ namespace llarp
&& self->record.work->IsValid(self->context->Crypto()->shorthash,
self->context->OurRouterID()))
{
llarp::Info("LRCM extended lifetime by ",
self->record.work->extendedLifetime, " seconds for ", info);
llarp::LogInfo("LRCM extended lifetime by ",
self->record.work->extendedLifetime, " seconds for ",
info);
self->hop->lifetime += 1000 * self->record.work->extendedLifetime;
}
else if(self->record.lifetime < 600 && self->record.lifetime > 10)
{
self->hop->lifetime = self->record.lifetime;
llarp::Info("LRCM short lifespan set to ", self->hop->lifetime,
" seconds for ", info);
llarp::LogInfo("LRCM short lifespan set to ", self->hop->lifetime,
" seconds for ", info);
}
// TODO: check if we really want to accept it
self->hop->started = llarp_time_now_ms();
llarp::Info("Accepted ", self->hop->info);
llarp::LogInfo("Accepted ", self->hop->info);
self->context->PutTransitHop(self->hop);
size_t sz = self->frames.front().size();
@ -276,7 +278,7 @@ namespace llarp
if(self->context->HopIsUs(info.upstream))
{
// we are the farthest hop
llarp::Info("We are the farthest hop for ", info);
llarp::LogInfo("We are the farthest hop for ", info);
// send a LRAM down the path
llarp_logic_queue_job(self->context->Logic(), {self, &SendPathConfirm});
}

View File

@ -63,7 +63,7 @@ namespace llarp
}
else
{
llarp::Warn("No such path downstream=", remote, " pathid=", pathid);
llarp::LogWarn("No such path downstream=", remote, " pathid=", pathid);
return false;
}
}
@ -125,7 +125,7 @@ namespace llarp
}
else
{
llarp::Warn("No such path upstream=", remote, " pathid=", pathid);
llarp::LogWarn("No such path upstream=", remote, " pathid=", pathid);
}
return false;
}

View File

@ -181,11 +181,11 @@ llarp_router::try_connect(fs::path rcfile)
f.read((char *)buf.base, sz);
}
else
llarp::Error(rcfile, " too large");
llarp::LogError(rcfile, " too large");
}
else
{
llarp::Error("failed to open ", rcfile);
llarp::LogError("failed to open ", rcfile);
return;
}
}
@ -193,17 +193,17 @@ llarp_router::try_connect(fs::path rcfile)
{
if(llarp_rc_verify_sig(&crypto, &remote))
{
llarp::Debug("verified signature");
llarp::LogDebug("verified signature");
if(!llarp_router_try_connect(this, &remote, 10))
{
llarp::Warn("session already made");
llarp::LogWarn("session already made");
}
}
else
llarp::Error("failed to verify signature of RC", rcfile);
llarp::LogError("failed to verify signature of RC", rcfile);
}
else
llarp::Error("failed to decode RC");
llarp::LogError("failed to decode RC");
llarp_rc_free(&remote);
}
@ -238,10 +238,10 @@ llarp_router::Ready()
bool
llarp_router::SaveRC()
{
llarp::Debug("verify RC signature");
llarp::LogDebug("verify RC signature");
if(!llarp_rc_verify_sig(&crypto, &rc))
{
llarp::Error("RC has bad signature not saving");
llarp::LogError("RC has bad signature not saving");
return false;
}
@ -254,11 +254,11 @@ llarp_router::SaveRC()
if(f.is_open())
{
f.write((char *)buf.base, buf.cur - buf.base);
llarp::Info("our RC saved to ", our_rc_file.c_str());
llarp::LogInfo("our RC saved to ", our_rc_file.c_str());
return true;
}
}
llarp::Error("did not save RC to ", our_rc_file.c_str());
llarp::LogError("did not save RC to ", our_rc_file.c_str());
return false;
}
@ -289,12 +289,12 @@ llarp_router::connect_job_retry(void *user, uint64_t orig, uint64_t left)
llarp::Addr remote = job->ai;
if(job->link)
{
llarp::Info("trying to establish session again with ", remote);
llarp::LogInfo("trying to establish session again with ", remote);
job->link->try_establish(job->link, job);
}
else
{
llarp::Error("establish session retry failed, no link for ", remote);
llarp::LogError("establish session retry failed, no link for ", remote);
}
}
@ -318,7 +318,7 @@ llarp_router::on_verify_server_rc(llarp_async_verify_rc *job)
llarp::PubKey pk(job->rc.pubkey);
if(!job->valid)
{
llarp::Warn("invalid server RC");
llarp::LogWarn("invalid server RC");
if(ctx->establish_job)
{
// was an outbound attempt
@ -333,7 +333,7 @@ llarp_router::on_verify_server_rc(llarp_async_verify_rc *job)
}
// we're valid, which means it's already been committed to the nodedb
llarp::Debug("rc verified and saved to nodedb");
llarp::LogDebug("rc verified and saved to nodedb");
// refresh valid routers RC value if it's there
auto v = router->validRouters.find(pk);
@ -379,7 +379,7 @@ llarp_router::HandleExploritoryPathBuildStarted(llarp_pathbuild_job *job)
void
llarp_router::Tick()
{
llarp::Debug("tick router");
llarp::LogDebug("tick router");
paths.ExpirePaths();
// TODO: don't do this if we have enough paths already
if(inboundLinks.size() == 0)
@ -391,8 +391,8 @@ llarp_router::Tick()
}
else
{
llarp::Warn("not enough nodes known to build exploritory paths, have ", N,
" nodes, need 3 now (will be 5 later)");
llarp::LogWarn("not enough nodes known to build exploritory paths, have ",
N, " nodes, need 3 now (will be 5 later)");
}
}
paths.TickPaths();
@ -439,8 +439,8 @@ llarp_router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg,
if(!msg->BEncode(&buf))
{
llarp::Warn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
llarp::LogWarn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
return;
}
// set size of message
@ -501,7 +501,7 @@ void
llarp_router::FlushOutboundFor(const llarp::RouterID &remote,
llarp_link *chosen)
{
llarp::Debug("Flush outbound for ", remote);
llarp::LogDebug("Flush outbound for ", remote);
auto itr = outboundMesssageQueue.find(remote);
if(itr == outboundMesssageQueue.end())
{
@ -520,8 +520,8 @@ llarp_router::FlushOutboundFor(const llarp::RouterID &remote,
if(!msg->BEncode(&buf))
{
llarp::Warn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
llarp::LogWarn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
delete msg;
itr->second.pop();
continue;
@ -530,8 +530,8 @@ llarp_router::FlushOutboundFor(const llarp::RouterID &remote,
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
if(!chosen->sendto(chosen, remote, buf))
llarp::Warn("failed to send outboud message to ", remote, " via ",
chosen->name());
llarp::LogWarn("failed to send outboud message to ", remote, " via ",
chosen->name());
delete msg;
itr->second.pop();
@ -544,27 +544,28 @@ llarp_router::on_try_connect_result(llarp_link_establish_job *job)
llarp_router *router = static_cast< llarp_router * >(job->user);
if(job->session)
{
// llarp::Debug("try_connect got session");
// llarp::LogDebug("try_connect got session");
auto session = job->session;
router->async_verify_RC(session->get_remote_router(session), false, job);
return;
}
// llarp::Debug("try_connect no session");
// llarp::LogDebug("try_connect no session");
llarp::PubKey pk = job->pubkey;
if(job->retries > 0)
{
job->retries--;
job->timeout *= 3;
job->timeout /= 2;
llarp::Info("session not established with ", pk, " relaxing timeout to ",
job->timeout);
llarp::LogInfo("session not established with ", pk, " relaxing timeout to ",
job->timeout);
// exponential backoff
llarp_logic_call_later(
router->logic, {job->timeout, job, &llarp_router::connect_job_retry});
}
else
{
llarp::Warn("failed to connect to ", pk, " dropping all pending messages");
llarp::LogWarn("failed to connect to ", pk,
" dropping all pending messages");
router->DiscardOutboundFor(pk);
router->pendingEstablishJobs.erase(pk);
}
@ -624,12 +625,12 @@ llarp_router::Run()
{
if(publicAddr)
{
llarp::Info("public address:port ", publicAddr);
llarp::LogInfo("public address:port ", publicAddr);
;
}
}
llarp::Info("You have ", inboundLinks.size(), " inbound links");
llarp::LogInfo("You have ", inboundLinks.size(), " inbound links");
for(auto link : inboundLinks)
{
llarp_ai addr;
@ -637,21 +638,21 @@ llarp_router::Run()
llarp::Addr a(addr);
if(this->publicOverride && a.sameAddr(publicAddr))
{
llarp::Info("Found adapter for public address");
llarp::LogInfo("Found adapter for public address");
publicFound = true;
}
if(a.isPrivate())
{
llarp::Warn("Skipping private network link: ", a);
llarp::LogWarn("Skipping private network link: ", a);
continue;
}
llarp::Info("Loading Addr: ", a, " into our RC");
llarp::LogInfo("Loading Addr: ", a, " into our RC");
llarp_ai_list_pushback(rc.addrs, &addr);
};
if(this->publicOverride && !publicFound)
{
// llarp::Warn("Need to load our public IP into RC!");
// llarp::LogWarn("Need to load our public IP into RC!");
llarp_link *link = nullptr;
if(inboundLinks.size() == 1)
@ -662,7 +663,7 @@ llarp_router::Run()
{
if(!inboundLinks.size())
{
llarp::Error("No inbound links found, aborting");
llarp::LogError("No inbound links found, aborting");
return;
}
link = inboundLinks.front();
@ -689,7 +690,7 @@ llarp_router::Run()
// override ip and port
this->addrInfo.ip = *publicAddr.addr6();
this->addrInfo.port = publicAddr.port();
llarp::Info("Loaded our public ", publicAddr, " override into RC!");
llarp::LogInfo("Loaded our public ", publicAddr, " override into RC!");
// we need the link to set the pubkey
llarp_ai_list_pushback(rc.addrs, &this->addrInfo);
}
@ -699,12 +700,12 @@ llarp_router::Run()
char ftmp[68] = {0};
const char *hexKey = llarp::HexEncode< llarp::PubKey, decltype(ftmp) >(
llarp::seckey_topublic(encryption), ftmp);
llarp::Info("Your Encryption pubkey ", hexKey);
llarp::LogInfo("Your Encryption pubkey ", hexKey);
// set public signing key
llarp_rc_set_pubsigkey(&rc, llarp::seckey_topublic(identity));
hexKey = llarp::HexEncode< llarp::PubKey, decltype(ftmp) >(
llarp::seckey_topublic(identity), ftmp);
llarp::Info("Your Identity pubkey ", hexKey);
llarp::LogInfo("Your Identity pubkey ", hexKey);
llarp_rc_sign(&crypto, identity, &rc);
@ -713,10 +714,10 @@ llarp_router::Run()
return;
}
llarp::Debug("starting outbound link");
llarp::LogDebug("starting outbound link");
if(!outboundLink->start_link(outboundLink, logic))
{
llarp::Warn("outbound link failed to start");
llarp::LogWarn("outbound link failed to start");
}
int IBLinksStarted = 0;
@ -726,11 +727,11 @@ llarp_router::Run()
{
if(link->start_link(link, logic))
{
llarp::Debug("Link ", link->name(), " started");
llarp::LogDebug("Link ", link->name(), " started");
IBLinksStarted++;
}
else
llarp::Warn("Link ", link->name(), " failed to start");
llarp::LogWarn("Link ", link->name(), " failed to start");
}
if(IBLinksStarted > 0)
@ -749,7 +750,7 @@ llarp_router::Run()
}
llarp::PubKey ourPubkey = pubkey();
llarp::Info("starting dht context as ", ourPubkey);
llarp::LogInfo("starting dht context as ", ourPubkey);
llarp_dht_context_start(dht, ourPubkey);
ScheduleTicker(1000);
@ -758,7 +759,7 @@ llarp_router::Run()
void
llarp_router::InitServiceNode()
{
llarp::Info("accepting transit traffic");
llarp::LogInfo("accepting transit traffic");
paths.AllowTransit();
llarp_dht_allow_transit(dht);
}
@ -771,7 +772,7 @@ llarp_router::ConnectAll(void *user, uint64_t orig, uint64_t left)
llarp_router *self = static_cast< llarp_router * >(user);
for(const auto &itr : self->connect)
{
llarp::Info("connecting to node ", itr.first);
llarp::LogInfo("connecting to node ", itr.first);
self->try_connect(itr.second);
}
}
@ -794,19 +795,19 @@ llarp_router::InitOutboundLink()
iwp_link_init(link, args);
if(llarp_link_initialized(link))
{
llarp::Info("outbound link initialized");
llarp::LogInfo("outbound link initialized");
for(auto af : afs)
{
if(link->configure(link, netloop, "*", af, 0))
{
outboundLink = link;
llarp::Info("outbound link ready");
llarp::LogInfo("outbound link ready");
return true;
}
}
}
delete link;
llarp::Error("failed to initialize outbound link");
llarp::LogError("failed to initialize outbound link");
return false;
}
@ -872,7 +873,7 @@ llarp_router_try_connect(struct llarp_router *router, struct llarp_rc *remote,
// do we already have a pending job for this remote?
if(router->HasPendingConnectJob(remote->pubkey))
{
llarp::Debug("We have pending connect jobs to ", hexname);
llarp::LogDebug("We have pending connect jobs to ", hexname);
return false;
}
// try first address only
@ -894,7 +895,7 @@ llarp_router_try_connect(struct llarp_router *router, struct llarp_rc *remote,
link->try_establish(link, job);
return true;
}
llarp::Warn("couldn't get first address for ", hexname);
llarp::LogWarn("couldn't get first address for ", hexname);
return false;
}
@ -1059,12 +1060,12 @@ bool
llarp_findOrCreateIdentity(llarp_crypto *crypto, const char *fpath,
byte_t *secretkey)
{
llarp::Debug("find or create ", fpath);
llarp::LogDebug("find or create ", fpath);
fs::path path(fpath);
std::error_code ec;
if(!fs::exists(path, ec))
{
llarp::Info("generating new identity key");
llarp::LogInfo("generating new identity key");
crypto->identity_keygen(secretkey);
std::ofstream f(path, std::ios::binary);
if(f.is_open())
@ -1078,7 +1079,7 @@ llarp_findOrCreateIdentity(llarp_crypto *crypto, const char *fpath,
f.read((char *)secretkey, SECKEYSIZE);
return true;
}
llarp::Info("failed to get identity key");
llarp::LogInfo("failed to get identity key");
return false;
}
@ -1089,12 +1090,12 @@ bool
llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath,
llarp::SecretKey *encryption)
{
llarp::Debug("find or create ", fpath);
llarp::LogDebug("find or create ", fpath);
fs::path path(fpath);
std::error_code ec;
if(!fs::exists(path, ec))
{
llarp::Info("generating new encryption key");
llarp::LogInfo("generating new encryption key");
crypto->encryption_keygen(*encryption);
std::ofstream f(path, std::ios::binary);
if(f.is_open())
@ -1108,7 +1109,7 @@ llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath,
f.read((char *)encryption, SECKEYSIZE);
return true;
}
llarp::Info("failed to get encryption key");
llarp::LogInfo("failed to get encryption key");
return false;
}
@ -1143,7 +1144,7 @@ namespace llarp
{
if(!StrEq(key, "*"))
{
llarp::Info("interface specific binding activated");
llarp::LogInfo("interface specific binding activated");
link = new llarp_link;
llarp::Zero(link, sizeof(llarp_link));
@ -1157,7 +1158,7 @@ namespace llarp
iwp_link_init(link, args);
if(llarp_link_initialized(link))
{
llarp::Info("link ", key, " initialized");
llarp::LogInfo("link ", key, " initialized");
if(link->configure(link, self->netloop, key, af, proto))
{
self->AddInboundLink(link);
@ -1167,7 +1168,8 @@ namespace llarp
{
// we failed to configure IPv6
// try IPv4
llarp::Info("link ", key, " failed to configure IPv6, trying IPv4");
llarp::LogInfo("link ", key,
" failed to configure IPv6, trying IPv4");
af = AF_INET;
if(link->configure(link, self->netloop, key, af, proto))
{
@ -1178,11 +1180,12 @@ namespace llarp
}
else
{
llarp::Error("link ", key, " failed to initialize. Link state", link);
llarp::LogError("link ", key, " failed to initialize. Link state",
link);
}
}
llarp::Error("link ", key,
" failed to configure. (Note: We don't support * yet)");
llarp::LogError("link ", key,
" failed to configure. (Note: We don't support * yet)");
}
else if(StrEq(section, "connect"))
{
@ -1208,7 +1211,7 @@ namespace llarp
}
if(StrEq(key, "public-address"))
{
llarp::Info("public ip ", val, " size ", strlen(val));
llarp::LogInfo("public ip ", val, " size ", strlen(val));
if(strlen(val) < 17)
{
// assume IPv4
@ -1216,7 +1219,7 @@ namespace llarp
// struct sockaddr dest;
sockaddr *dest = (sockaddr *)&self->ip4addr;
llarp::Addr a(*dest);
llarp::Info("setting public ipv4 ", a);
llarp::LogInfo("setting public ipv4 ", a);
self->addrInfo.ip = *a.addr6();
self->publicOverride = true;
}
@ -1224,7 +1227,7 @@ namespace llarp
}
if(StrEq(key, "public-port"))
{
llarp::Info("Setting public port ", val);
llarp::LogInfo("Setting public port ", val);
self->ip4addr.sin_port = htons(atoi(val));
self->addrInfo.port = htons(atoi(val));
self->publicOverride = true;

View File

@ -162,7 +162,7 @@ llarp_rc_verify_sig(struct llarp_crypto *crypto, struct llarp_rc *rc)
result = crypto->verify(rc->pubkey, buf, sig);
}
else
llarp::Warn("RC encode failed");
llarp::LogWarn("RC encode failed");
// restore sig
memcpy(rc->signature, sig, SIGSIZE);
return result;

View File

@ -18,7 +18,7 @@ namespace llarp
from.Zero();
if(llarp_buffer_eq(key, "M"))
{
return llarp::dht::DecodeMesssageList(from, val, M);
return llarp::dht::DecodeMesssageList(from, val, M, true);
}
else if(llarp_buffer_eq(key, "V"))
{
@ -50,8 +50,9 @@ namespace llarp
llarp::dht::Key_t us = r->pubkey();
for(auto& msg : M)
{
msg->From = us;
if(!r->dht->impl.RelayRequestForPath(from, msg))
msg->From = us;
msg->pathID = from;
if(!h->HandleDHTMessage(msg, r))
return false;
}
return true;

View File

@ -52,7 +52,7 @@ namespace llarp
self->msg = new PathTransferMessage;
break;
default:
llarp::Error("invalid routing message id: ", *strbuf.cur);
llarp::LogError("invalid routing message id: ", *strbuf.cur);
}
self->firstKey = false;
return self->msg != nullptr;
@ -77,7 +77,7 @@ namespace llarp
delete msg;
}
else
llarp::Error("read dict failed");
llarp::LogError("read dict failed");
return result;
}
} // namespace routing

View File

@ -56,8 +56,8 @@ namespace llarp
{
return path->HandleDownstream(T.Buffer(), Y, r);
}
llarp::Warn("No such local path for path transfer src=", from,
" dst=", P);
llarp::LogWarn("No such local path for path transfer src=", from,
" dst=", P);
return false;
}
} // namespace routing

View File

@ -1 +1,220 @@
#include <llarp/service.hpp>
#include <llarp/service.hpp>
#include "buffer.hpp"
namespace llarp
{
namespace service
{
std::string
AddressToString(const Address& addr)
{
char tmp[(1 + 32) * 2] = {0};
std::string str = Base32Encode(addr, tmp);
return str + ".loki";
}
ServiceInfo::ServiceInfo()
{
vanity.Zero();
}
ServiceInfo::~ServiceInfo()
{
}
bool
ServiceInfo::DecodeKey(llarp_buffer_t key, llarp_buffer_t* val)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("e", enckey, read, key, val))
return false;
if(!BEncodeMaybeReadDictEntry("s", signkey, read, key, val))
return false;
if(!BEncodeMaybeReadDictInt("v", version, read, key, val))
return false;
if(!BEncodeMaybeReadDictEntry("x", vanity, read, key, val))
return false;
return read;
}
bool
ServiceInfo::BEncode(llarp_buffer_t* buf) const
{
if(!bencode_start_dict(buf))
return false;
if(!BEncodeWriteDictEntry("e", enckey, buf))
return false;
if(!BEncodeWriteDictEntry("s", signkey, buf))
return false;
if(!BEncodeWriteDictInt(buf, "v", LLARP_PROTO_VERSION))
return false;
if(!vanity.IsZero())
{
if(!BEncodeWriteDictEntry("x", vanity, buf))
return false;
}
return bencode_end(buf);
}
bool
ServiceInfo::CalculateAddress(Address& addr) const
{
byte_t tmp[128];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
if(!BEncode(&buf))
return false;
return crypto_generichash(addr, addr.size(), buf.base, buf.cur - buf.base,
nullptr, 0)
!= -1;
}
IntroSet::~IntroSet()
{
if(W)
delete W;
}
bool
IntroSet::DecodeKey(llarp_buffer_t key, llarp_buffer_t* val)
{
// TODO: implement me
return false;
}
bool
IntroSetDecodeKey(dict_reader* r, llarp_buffer_t* key)
{
IntroSet* self = static_cast< IntroSet* >(r->user);
if(!key)
// TODO: determine if we read anything
return true;
return self->DecodeKey(*key, r->buffer);
}
bool
IntroSet::BDecode(llarp_buffer_t* buf)
{
dict_reader r;
r.user = this;
r.on_key = &IntroSetDecodeKey;
return bencode_read_dict(buf, &r);
}
bool
IntroSet::BEncode(llarp_buffer_t* buf) const
{
if(!bencode_start_dict(buf))
return false;
if(!BEncodeWriteDictEntry("a", A, buf))
return false;
// start introduction list
if(!bencode_write_bytestring(buf, "i", 1))
return false;
if(!BEncodeWriteList(I.begin(), I.end(), buf))
return false;
// end introduction list
// write version
if(!BEncodeWriteDictInt(buf, "v", V))
return false;
if(W)
{
if(!BEncodeWriteDictEntry("w", *W, buf))
return false;
}
if(!BEncodeWriteDictEntry("z", Z, buf))
return false;
return bencode_end(buf);
}
Introduction::~Introduction()
{
}
bool
Introduction::DecodeKey(llarp_buffer_t key, llarp_buffer_t* val)
{
// TODO: implement me
return false;
}
bool
Introduction::BEncode(llarp_buffer_t* buf) const
{
if(!bencode_start_dict(buf))
return false;
if(!BEncodeWriteDictEntry("k", router, buf))
return false;
if(!BEncodeWriteDictEntry("p", pathID, buf))
return false;
if(!BEncodeWriteDictInt(buf, "v", version))
return false;
if(!BEncodeWriteDictInt(buf, "x", expiresAt))
return false;
return bencode_end(buf);
}
Identity::~Identity()
{
}
bool
Identity::BEncode(llarp_buffer_t* buf) const
{
/// TODO: implement me
return false;
}
bool
Identity::DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf)
{
/// TODO: implement me
return false;
}
void
Identity::RegenerateKeys(llarp_crypto* crypto)
{
crypto->encryption_keygen(enckey);
crypto->identity_keygen(signkey);
pub.enckey = llarp::seckey_topublic(enckey);
pub.signkey = llarp::seckey_topublic(signkey);
}
bool
Identity::SignIntroSet(IntroSet& i, llarp_crypto* crypto) const
{
if(i.I.size() == 0)
return false;
i.A = pub;
// zero out signature for signing process
i.Z.Zero();
byte_t tmp[MAX_INTROSET_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
if(!i.BEncode(&buf))
return false;
// rewind and resize buffer
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
return crypto->sign(i.Z, signkey, buf);
}
bool
IntroSet::VerifySignature(llarp_crypto* crypto) const
{
byte_t tmp[MAX_INTROSET_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
IntroSet copy;
copy = *this;
copy.Z.Zero();
if(!copy.BEncode(&buf))
return false;
// rewind and resize buffer
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
return crypto->verify(A.signkey, buf, Z);
}
} // namespace service
} // namespace llarp

View File

@ -49,7 +49,7 @@ namespace llarp
auto after = llarp_time_now_ms();
auto dlt = after - now;
if(dlt > 10)
llarp::Warn("work took ", dlt, " ms");
llarp::LogWarn("work took ", dlt, " ms");
delete job;
}
});
@ -110,7 +110,6 @@ struct llarp_threadpool
};
extern "C" {
struct llarp_threadpool *
llarp_init_threadpool(int workers, const char *name)
{
@ -129,7 +128,7 @@ llarp_init_same_process_threadpool()
void
llarp_threadpool_join(struct llarp_threadpool *pool)
{
llarp::Debug("threadpool join");
llarp::LogDebug("threadpool join");
if(pool->impl)
pool->impl->Join();
}
@ -142,7 +141,7 @@ llarp_threadpool_start(struct llarp_threadpool *pool)
void
llarp_threadpool_stop(struct llarp_threadpool *pool)
{
llarp::Debug("threadpool stop");
llarp::LogDebug("threadpool stop");
if(pool->impl)
pool->impl->Stop();
}
@ -151,7 +150,7 @@ void
llarp_threadpool_wait(struct llarp_threadpool *pool)
{
std::mutex mtx;
llarp::Debug("threadpool wait");
llarp::LogDebug("threadpool wait");
if(pool->impl)
{
std::unique_lock< std::mutex > lock(mtx);

View File

@ -51,7 +51,7 @@ namespace llarp
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
if(!msg->BEncode(&buf))
{
llarp::Error("failed to encode routing message");
llarp::LogError("failed to encode routing message");
return false;
}
TunnelNonce N;
@ -72,8 +72,8 @@ namespace llarp
r->crypto.xchacha20(buf, pathKey, Y);
msg->X = buf;
llarp::Debug("relay ", msg->X.size(), " bytes downstream from ",
info.upstream, " to ", info.downstream);
llarp::LogDebug("relay ", msg->X.size(), " bytes downstream from ",
info.upstream, " to ", info.downstream);
return r->SendToOrQueue(info.downstream, msg);
}
@ -93,8 +93,8 @@ namespace llarp
msg->Y = Y;
msg->X = buf;
llarp::Debug("relay ", msg->X.size(), " bytes upstream from ",
info.downstream, " to ", info.upstream);
llarp::LogDebug("relay ", msg->X.size(), " bytes upstream from ",
info.downstream, " to ", info.upstream);
return r->SendToOrQueue(info.upstream, msg);
}
}
@ -103,8 +103,7 @@ namespace llarp
TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp_router* r)
{
// TODO: implement me
return false;
return r->dht->impl.RelayRequestForPath(info.rxID, msg);
}
bool
@ -120,7 +119,7 @@ namespace llarp
TransitHop::HandlePathConfirmMessage(
const llarp::routing::PathConfirmMessage* msg, llarp_router* r)
{
llarp::Warn("unwarrented path confirm message on ", info);
llarp::LogWarn("unwarrented path confirm message on ", info);
return false;
}
@ -133,14 +132,14 @@ namespace llarp
{
return path->HandleDownstream(msg->T.Buffer(), msg->Y, r);
}
llarp::Warn("No such path for path transfer pathid=", msg->P);
llarp::LogWarn("No such path for path transfer pathid=", msg->P);
return false;
}
bool
TransitHop::HandleHiddenServiceData(llarp_buffer_t buf, llarp_router* r)
{
llarp::Warn("unwarrented hidden service data on ", info);
llarp::LogWarn("unwarrented hidden service data on ", info);
return false;
}

View File

@ -22,6 +22,5 @@ TEST_F(APITest, TestMessageWellFormed)
msg.msgID = 0;
msg.sessionID = 12345;
msg.CalculateHash(&crypto, apiPassword);
llarp::Info("msghash=", msg.hash);
ASSERT_TRUE(msg.IsWellFormed(&crypto, apiPassword));
};

24
test/base32_unittest.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <gtest/gtest.h>
#include <llarp/aligned.hpp>
#include <llarp/encode.hpp>
#include <llarp/logger.hpp>
struct Base32Test : public ::testing::Test
{
Base32Test()
{
llarp_crypto_libsodium_init(&crypto);
}
llarp_crypto crypto;
};
TEST_F(Base32Test, Serialize)
{
llarp::AlignedBuffer< 32 > addr, otherAddr;
addr.Randomize();
char tmp[64] = {0};
std::string encoded = llarp::Base32Encode(addr, tmp);
ASSERT_TRUE(llarp::Base32Decode(tmp, otherAddr));
ASSERT_TRUE(otherAddr == addr);
};

View File

@ -0,0 +1,43 @@
#include <gtest/gtest.h>
#include <llarp/service.hpp>
struct HiddenServiceTest : public ::testing::Test
{
llarp_crypto crypto;
llarp::service::Identity ident;
HiddenServiceTest()
{
llarp_crypto_libsodium_init(&crypto);
}
llarp_crypto*
Crypto()
{
return &crypto;
}
void
SetUp()
{
ident.RegenerateKeys(Crypto());
ident.pub.vanity.Randomize();
}
};
TEST_F(HiddenServiceTest, TestGenerateIntroSet)
{
llarp::service::Address addr;
ASSERT_TRUE(ident.pub.CalculateAddress(addr));
llarp::service::IntroSet I;
while(I.I.size() < 10)
{
llarp::service::Introduction intro;
intro.expiresAt = 1000;
intro.router.Randomize();
intro.pathID.Randomize();
I.I.insert(intro);
}
ASSERT_TRUE(ident.SignIntroSet(I, Crypto()));
ASSERT_TRUE(I.VerifySignature(Crypto()));
};