Browse Source

[log] update log messages (closes #1693)

Signed-off-by: R4SAS <r4sas@i2pmail.org>
pull/1717/head
R4SAS 3 years ago
parent
commit
94661f697b
Signed by: r4sas
GPG Key ID: 66F6C87B98EBCFE2
  1. 4
      Win32/Win32NetState.cpp
  2. 72
      daemon/Daemon.cpp
  3. 12
      daemon/HTTPServer.cpp
  4. 34
      daemon/I2PControl.cpp
  5. 24
      daemon/UPnP.cpp
  6. 22
      daemon/UnixDaemon.cpp
  7. 14
      libi2pd/Blinding.cpp
  8. 26
      libi2pd/Destination.cpp
  9. 30
      libi2pd/ECIESX25519AEADRatchetSession.cpp
  10. 60
      libi2pd/Garlic.cpp
  11. 20
      libi2pd/I2NPProtocol.cpp
  12. 4
      libi2pd/Identity.cpp
  13. 30
      libi2pd/LeaseSet.cpp
  14. 6
      libi2pd/Log.cpp
  15. 62
      libi2pd/NTCP2.cpp
  16. 62
      libi2pd/NetDb.cpp
  17. 6
      libi2pd/Profiling.cpp
  18. 40
      libi2pd/Reseed.cpp
  19. 12
      libi2pd/RouterInfo.cpp
  20. 26
      libi2pd/SSU.cpp
  21. 74
      libi2pd/SSUSession.cpp
  22. 26
      libi2pd/Transports.cpp
  23. 36
      libi2pd/Tunnel.cpp
  24. 12
      libi2pd/TunnelEndpoint.cpp
  25. 6
      libi2pd/TunnelPool.cpp
  26. 14
      libi2pd/api.cpp
  27. 28
      libi2pd/util.cpp
  28. 62
      libi2pd_client/AddressBook.cpp
  29. 16
      libi2pd_client/BOB.cpp
  30. 42
      libi2pd_client/ClientContext.cpp
  31. 40
      libi2pd_client/HTTPProxy.cpp
  32. 62
      libi2pd_client/I2CP.cpp
  33. 24
      libi2pd_client/I2PService.cpp
  34. 46
      libi2pd_client/I2PTunnel.cpp
  35. 8
      libi2pd_client/MatchedDestination.cpp
  36. 82
      libi2pd_client/SAM.cpp
  37. 62
      libi2pd_client/SOCKS.cpp

4
Win32/Win32NetState.cpp

@ -32,7 +32,7 @@ void SubscribeToEvents()
Result = pNetworkListManager->IsConnectedToInternet(&IsConnect); Result = pNetworkListManager->IsConnectedToInternet(&IsConnect);
if (SUCCEEDED(Result)) { if (SUCCEEDED(Result)) {
i2p::transport::transports.SetOnline (true); i2p::transport::transports.SetOnline (true);
LogPrint(eLogInfo, "NetState: current state: ", IsConnect == VARIANT_TRUE ? "connected" : "disconnected"); LogPrint(eLogInfo, "NetState: Current state: ", IsConnect == VARIANT_TRUE ? "connected" : "disconnected");
} }
Result = pNetworkListManager->QueryInterface(IID_IConnectionPointContainer, (void **)&pCPContainer); Result = pNetworkListManager->QueryInterface(IID_IConnectionPointContainer, (void **)&pCPContainer);
@ -79,7 +79,7 @@ void UnSubscribeFromEvents()
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "NetState: received exception: ", ex.what ()); LogPrint (eLogError, "NetState: Received exception: ", ex.what ());
} }
} }

72
daemon/Daemon.cpp

@ -118,26 +118,26 @@ namespace util
i2p::log::Logger().SetLogLevel(loglevel); i2p::log::Logger().SetLogLevel(loglevel);
if (logstream) { if (logstream) {
LogPrint(eLogInfo, "Log: will send messages to std::ostream"); LogPrint(eLogInfo, "Log: Sending messages to std::ostream");
i2p::log::Logger().SendTo (logstream); i2p::log::Logger().SendTo (logstream);
} else if (logs == "file") { } else if (logs == "file") {
if (logfile == "") if (logfile == "")
logfile = i2p::fs::DataDirPath("i2pd.log"); logfile = i2p::fs::DataDirPath("i2pd.log");
LogPrint(eLogInfo, "Log: will send messages to ", logfile); LogPrint(eLogInfo, "Log: Sending messages to ", logfile);
i2p::log::Logger().SendTo (logfile); i2p::log::Logger().SendTo (logfile);
#ifndef _WIN32 #ifndef _WIN32
} else if (logs == "syslog") { } else if (logs == "syslog") {
LogPrint(eLogInfo, "Log: will send messages to syslog"); LogPrint(eLogInfo, "Log: Sending messages to syslog");
i2p::log::Logger().SendTo("i2pd", LOG_DAEMON); i2p::log::Logger().SendTo("i2pd", LOG_DAEMON);
#endif #endif
} else { } else {
// use stdout -- default // use stdout -- default
} }
LogPrint(eLogNone, "i2pd v", VERSION, " (", I2P_VERSION, ") starting"); LogPrint(eLogNone, "i2pd v", VERSION, " (", I2P_VERSION, ") starting...");
LogPrint(eLogDebug, "FS: main config file: ", config); LogPrint(eLogDebug, "FS: Main config file: ", config);
LogPrint(eLogDebug, "FS: data directory: ", datadir); LogPrint(eLogDebug, "FS: Data directory: ", datadir);
LogPrint(eLogDebug, "FS: certificates directory: ", certsdir); LogPrint(eLogDebug, "FS: Certificates directory: ", certsdir);
bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation); bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation);
bool aesni; i2p::config::GetOption("cpuext.aesni", aesni); bool aesni; i2p::config::GetOption("cpuext.aesni", aesni);
@ -204,7 +204,7 @@ namespace util
uint16_t port; i2p::config::GetOption("port", port); uint16_t port; i2p::config::GetOption("port", port);
if (!i2p::config::IsDefault("port")) if (!i2p::config::IsDefault("port"))
{ {
LogPrint(eLogInfo, "Daemon: accepting incoming connections at port ", port); LogPrint(eLogInfo, "Daemon: Accepting incoming connections at port ", port);
i2p::context.UpdatePort (port); i2p::context.UpdatePort (port);
} }
i2p::context.SetSupportsV6 (ipv6); i2p::context.SetSupportsV6 (ipv6);
@ -252,7 +252,7 @@ namespace util
bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill); bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill);
if (isFloodfill) { if (isFloodfill) {
LogPrint(eLogInfo, "Daemon: router will be floodfill"); LogPrint(eLogInfo, "Daemon: Router configured as floodfill");
i2p::context.SetFloodfill (true); i2p::context.SetFloodfill (true);
} }
else else
@ -267,7 +267,7 @@ namespace util
if (bandwidth[0] >= 'K' && bandwidth[0] <= 'X') if (bandwidth[0] >= 'K' && bandwidth[0] <= 'X')
{ {
i2p::context.SetBandwidth (bandwidth[0]); i2p::context.SetBandwidth (bandwidth[0]);
LogPrint(eLogInfo, "Daemon: bandwidth set to ", i2p::context.GetBandwidthLimit (), "KBps"); LogPrint(eLogInfo, "Daemon: Bandwidth set to ", i2p::context.GetBandwidthLimit (), "KBps");
} }
else else
{ {
@ -275,18 +275,18 @@ namespace util
if (value > 0) if (value > 0)
{ {
i2p::context.SetBandwidth (value); i2p::context.SetBandwidth (value);
LogPrint(eLogInfo, "Daemon: bandwidth set to ", i2p::context.GetBandwidthLimit (), " KBps"); LogPrint(eLogInfo, "Daemon: Bandwidth set to ", i2p::context.GetBandwidthLimit (), " KBps");
} }
else else
{ {
LogPrint(eLogInfo, "Daemon: unexpected bandwidth ", bandwidth, ". Set to 'low'"); LogPrint(eLogInfo, "Daemon: Unexpected bandwidth ", bandwidth, ". Set to 'low'");
i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2); i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2);
} }
} }
} }
else if (isFloodfill) else if (isFloodfill)
{ {
LogPrint(eLogInfo, "Daemon: floodfill bandwidth set to 'extra'"); LogPrint(eLogInfo, "Daemon: Floodfill bandwidth set to 'extra'");
i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH2); i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH2);
} }
else else
@ -301,12 +301,12 @@ namespace util
std::string family; i2p::config::GetOption("family", family); std::string family; i2p::config::GetOption("family", family);
i2p::context.SetFamily (family); i2p::context.SetFamily (family);
if (family.length () > 0) if (family.length () > 0)
LogPrint(eLogInfo, "Daemon: family set to ", family); LogPrint(eLogInfo, "Daemon: Router family set to ", family);
bool trust; i2p::config::GetOption("trust.enabled", trust); bool trust; i2p::config::GetOption("trust.enabled", trust);
if (trust) if (trust)
{ {
LogPrint(eLogInfo, "Daemon: explicit trust enabled"); LogPrint(eLogInfo, "Daemon: Explicit trust enabled");
std::string fam; i2p::config::GetOption("trust.family", fam); std::string fam; i2p::config::GetOption("trust.family", fam);
std::string routers; i2p::config::GetOption("trust.routers", routers); std::string routers; i2p::config::GetOption("trust.routers", routers);
bool restricted = false; bool restricted = false;
@ -336,18 +336,18 @@ namespace util
pos = comma + 1; pos = comma + 1;
} }
while (comma != std::string::npos); while (comma != std::string::npos);
LogPrint(eLogInfo, "Daemon: setting restricted routes to use ", idents.size(), " trusted routers"); LogPrint(eLogInfo, "Daemon: Setting restricted routes to use ", idents.size(), " trusted routers");
i2p::transport::transports.RestrictRoutesToRouters(idents); i2p::transport::transports.RestrictRoutesToRouters(idents);
restricted = idents.size() > 0; restricted = idents.size() > 0;
} }
if(!restricted) if(!restricted)
LogPrint(eLogError, "Daemon: no trusted routers of families specified"); LogPrint(eLogError, "Daemon: No trusted routers of families specified");
} }
bool hidden; i2p::config::GetOption("trust.hidden", hidden); bool hidden; i2p::config::GetOption("trust.hidden", hidden);
if (hidden) if (hidden)
{ {
LogPrint(eLogInfo, "Daemon: using hidden mode"); LogPrint(eLogInfo, "Daemon: Hidden mode enabled");
i2p::data::netdb.SetHidden(true); i2p::data::netdb.SetHidden(true);
} }
@ -360,7 +360,7 @@ namespace util
bool Daemon_Singleton::start() bool Daemon_Singleton::start()
{ {
i2p::log::Logger().Start(); i2p::log::Logger().Start();
LogPrint(eLogInfo, "Daemon: starting NetDB"); LogPrint(eLogInfo, "Daemon: Starting NetDB");
i2p::data::netdb.Start(); i2p::data::netdb.Start();
bool upnp; i2p::config::GetOption("upnp.enabled", upnp); bool upnp; i2p::config::GetOption("upnp.enabled", upnp);
@ -379,9 +379,9 @@ namespace util
bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2); bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2);
bool ssu; i2p::config::GetOption("ssu", ssu); bool ssu; i2p::config::GetOption("ssu", ssu);
bool checkInReserved; i2p::config::GetOption("reservedrange", checkInReserved); bool checkInReserved; i2p::config::GetOption("reservedrange", checkInReserved);
LogPrint(eLogInfo, "Daemon: starting Transports"); LogPrint(eLogInfo, "Daemon: Starting Transports");
if(!ssu) LogPrint(eLogInfo, "Daemon: ssu disabled"); if(!ssu) LogPrint(eLogInfo, "Daemon: SSU disabled");
if(!ntcp2) LogPrint(eLogInfo, "Daemon: ntcp2 disabled"); if(!ntcp2) LogPrint(eLogInfo, "Daemon: NTCP2 disabled");
i2p::transport::transports.SetCheckReserved(checkInReserved); i2p::transport::transports.SetCheckReserved(checkInReserved);
i2p::transport::transports.Start(ntcp2, ssu); i2p::transport::transports.Start(ntcp2, ssu);
@ -389,7 +389,7 @@ namespace util
LogPrint(eLogInfo, "Daemon: Transports started"); LogPrint(eLogInfo, "Daemon: Transports started");
else else
{ {
LogPrint(eLogError, "Daemon: failed to start Transports"); LogPrint(eLogError, "Daemon: Failed to start Transports");
/** shut down netdb right away */ /** shut down netdb right away */
i2p::transport::transports.Stop(); i2p::transport::transports.Stop();
i2p::data::netdb.Stop(); i2p::data::netdb.Stop();
@ -400,7 +400,7 @@ namespace util
if (http) { if (http) {
std::string httpAddr; i2p::config::GetOption("http.address", httpAddr); std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
uint16_t httpPort; i2p::config::GetOption("http.port", httpPort); uint16_t httpPort; i2p::config::GetOption("http.port", httpPort);
LogPrint(eLogInfo, "Daemon: starting webconsole at ", httpAddr, ":", httpPort); LogPrint(eLogInfo, "Daemon: Starting Webconsole at ", httpAddr, ":", httpPort);
try try
{ {
d.httpServer = std::unique_ptr<i2p::http::HTTPServer>(new i2p::http::HTTPServer(httpAddr, httpPort)); d.httpServer = std::unique_ptr<i2p::http::HTTPServer>(new i2p::http::HTTPServer(httpAddr, httpPort));
@ -408,16 +408,16 @@ namespace util
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "Daemon: failed to start webconsole: ", ex.what ()); LogPrint (eLogError, "Daemon: Failed to start Webconsole: ", ex.what ());
ThrowFatal ("Unable to start webconsole at ", httpAddr, ":", httpPort, ": ", ex.what ()); ThrowFatal ("Unable to start webconsole at ", httpAddr, ":", httpPort, ": ", ex.what ());
} }
} }
LogPrint(eLogInfo, "Daemon: starting Tunnels"); LogPrint(eLogInfo, "Daemon: Starting Tunnels");
i2p::tunnel::tunnels.Start(); i2p::tunnel::tunnels.Start();
LogPrint(eLogInfo, "Daemon: starting Client"); LogPrint(eLogInfo, "Daemon: Starting Client");
i2p::client::context.Start (); i2p::client::context.Start ();
// I2P Control Protocol // I2P Control Protocol
@ -425,7 +425,7 @@ namespace util
if (i2pcontrol) { if (i2pcontrol) {
std::string i2pcpAddr; i2p::config::GetOption("i2pcontrol.address", i2pcpAddr); std::string i2pcpAddr; i2p::config::GetOption("i2pcontrol.address", i2pcpAddr);
uint16_t i2pcpPort; i2p::config::GetOption("i2pcontrol.port", i2pcpPort); uint16_t i2pcpPort; i2p::config::GetOption("i2pcontrol.port", i2pcpPort);
LogPrint(eLogInfo, "Daemon: starting I2PControl at ", i2pcpAddr, ":", i2pcpPort); LogPrint(eLogInfo, "Daemon: Starting I2PControl at ", i2pcpAddr, ":", i2pcpPort);
try try
{ {
d.m_I2PControlService = std::unique_ptr<i2p::client::I2PControlService>(new i2p::client::I2PControlService (i2pcpAddr, i2pcpPort)); d.m_I2PControlService = std::unique_ptr<i2p::client::I2PControlService>(new i2p::client::I2PControlService (i2pcpAddr, i2pcpPort));
@ -433,7 +433,7 @@ namespace util
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "Daemon: failed to start I2PControl: ", ex.what ()); LogPrint (eLogError, "Daemon: Failed to start I2PControl: ", ex.what ());
ThrowFatal ("Unable to start I2PControl service at ", i2pcpAddr, ":", i2pcpPort, ": ", ex.what ()); ThrowFatal ("Unable to start I2PControl service at ", i2pcpAddr, ":", i2pcpPort, ": ", ex.what ());
} }
} }
@ -442,10 +442,10 @@ namespace util
bool Daemon_Singleton::stop() bool Daemon_Singleton::stop()
{ {
LogPrint(eLogInfo, "Daemon: shutting down"); LogPrint(eLogInfo, "Daemon: Shutting down");
LogPrint(eLogInfo, "Daemon: stopping Client"); LogPrint(eLogInfo, "Daemon: Stopping Client");
i2p::client::context.Stop(); i2p::client::context.Stop();
LogPrint(eLogInfo, "Daemon: stopping Tunnels"); LogPrint(eLogInfo, "Daemon: Stopping Tunnels");
i2p::tunnel::tunnels.Stop(); i2p::tunnel::tunnels.Stop();
if (d.UPnP) if (d.UPnP)
@ -460,18 +460,18 @@ namespace util
d.m_NTPSync = nullptr; d.m_NTPSync = nullptr;
} }
LogPrint(eLogInfo, "Daemon: stopping Transports"); LogPrint(eLogInfo, "Daemon: Stopping Transports");
i2p::transport::transports.Stop(); i2p::transport::transports.Stop();
LogPrint(eLogInfo, "Daemon: stopping NetDB"); LogPrint(eLogInfo, "Daemon: Stopping NetDB");
i2p::data::netdb.Stop(); i2p::data::netdb.Stop();
if (d.httpServer) { if (d.httpServer) {
LogPrint(eLogInfo, "Daemon: stopping HTTP Server"); LogPrint(eLogInfo, "Daemon: Stopping HTTP Server");
d.httpServer->Stop(); d.httpServer->Stop();
d.httpServer = nullptr; d.httpServer = nullptr;
} }
if (d.m_I2PControlService) if (d.m_I2PControlService)
{ {
LogPrint(eLogInfo, "Daemon: stopping I2PControl"); LogPrint(eLogInfo, "Daemon: Stopping I2PControl");
d.m_I2PControlService->Stop (); d.m_I2PControlService->Stop ();
d.m_I2PControlService = nullptr; d.m_I2PControlService = nullptr;
} }

12
daemon/HTTPServer.cpp

@ -160,7 +160,7 @@ namespace http {
if (level == "none" || level == "error" || level == "warn" || level == "info" || level == "debug") if (level == "none" || level == "error" || level == "warn" || level == "info" || level == "debug")
i2p::log::Logger().SetLogLevel(level); i2p::log::Logger().SetLogLevel(level);
else { else {
LogPrint(eLogError, "HTTPServer: unknown loglevel set attempted"); LogPrint(eLogError, "HTTPServer: Unknown loglevel set attempted");
return; return;
} }
i2p::log::Logger().Reopen (); i2p::log::Logger().Reopen ();
@ -1039,7 +1039,7 @@ namespace http {
if (expected == provided) return true; if (expected == provided) return true;
} }
LogPrint(eLogWarning, "HTTPServer: auth failure from ", m_Socket->remote_endpoint().address ()); LogPrint(eLogWarning, "HTTPServer: Auth failure from ", m_Socket->remote_endpoint().address ());
return false; return false;
} }
@ -1049,7 +1049,7 @@ namespace http {
std::string content; std::string content;
HTTPRes res; HTTPRes res;
LogPrint(eLogDebug, "HTTPServer: request: ", req.uri); LogPrint(eLogDebug, "HTTPServer: Request: ", req.uri);
if (needAuth && !CheckAuth(req)) { if (needAuth && !CheckAuth(req)) {
res.code = 401; res.code = 401;
@ -1377,7 +1377,7 @@ namespace http {
pass[i] = alnum[random[i] % (sizeof(alnum) - 1)]; pass[i] = alnum[random[i] % (sizeof(alnum) - 1)];
} }
i2p::config::SetOption("http.pass", pass); i2p::config::SetOption("http.pass", pass);
LogPrint(eLogInfo, "HTTPServer: password set to ", pass); LogPrint(eLogInfo, "HTTPServer: Password set to ", pass);
} }
m_IsRunning = true; m_IsRunning = true;
@ -1412,7 +1412,7 @@ namespace http {
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "HTTPServer: runtime exception: ", ex.what ()); LogPrint (eLogError, "HTTPServer: Runtime exception: ", ex.what ());
} }
} }
} }
@ -1430,7 +1430,7 @@ namespace http {
if (ecode) if (ecode)
{ {
if(newSocket) newSocket->close(); if(newSocket) newSocket->close();
LogPrint(eLogError, "HTTP Server: error handling accept ", ecode.message()); LogPrint(eLogError, "HTTP Server: Error handling accept ", ecode.message());
if(ecode != boost::asio::error::operation_aborted) if(ecode != boost::asio::error::operation_aborted)
Accept(); Accept();
return; return;

34
daemon/I2PControl.cpp

@ -48,10 +48,10 @@ namespace client
if (i2pcp_key.at(0) != '/') if (i2pcp_key.at(0) != '/')
i2pcp_key = i2p::fs::DataDirPath(i2pcp_key); i2pcp_key = i2p::fs::DataDirPath(i2pcp_key);
if (!i2p::fs::Exists (i2pcp_crt) || !i2p::fs::Exists (i2pcp_key)) { if (!i2p::fs::Exists (i2pcp_crt) || !i2p::fs::Exists (i2pcp_key)) {
LogPrint (eLogInfo, "I2PControl: creating new certificate for control connection"); LogPrint (eLogInfo, "I2PControl: Creating new certificate for control connection");
CreateCertificate (i2pcp_crt.c_str(), i2pcp_key.c_str()); CreateCertificate (i2pcp_crt.c_str(), i2pcp_key.c_str());
} else { } else {
LogPrint(eLogDebug, "I2PControl: using cert from ", i2pcp_crt); LogPrint(eLogDebug, "I2PControl: Using cert from ", i2pcp_crt);
} }
m_SSLContext.set_options (boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); m_SSLContext.set_options (boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use);
m_SSLContext.use_certificate_file (i2pcp_crt, boost::asio::ssl::context::pem); m_SSLContext.use_certificate_file (i2pcp_crt, boost::asio::ssl::context::pem);
@ -142,7 +142,7 @@ namespace client
try { try {
m_Service.run (); m_Service.run ();
} catch (std::exception& ex) { } catch (std::exception& ex) {
LogPrint (eLogError, "I2PControl: runtime exception: ", ex.what ()); LogPrint (eLogError, "I2PControl: Runtime exception: ", ex.what ());
} }
} }
} }
@ -160,10 +160,10 @@ namespace client
Accept (); Accept ();
if (ecode) { if (ecode) {
LogPrint (eLogError, "I2PControl: accept error: ", ecode.message ()); LogPrint (eLogError, "I2PControl: Accept error: ", ecode.message ());
return; return;
} }
LogPrint (eLogDebug, "I2PControl: new request from ", socket->lowest_layer ().remote_endpoint ()); LogPrint (eLogDebug, "I2PControl: New request from ", socket->lowest_layer ().remote_endpoint ());
Handshake (socket); Handshake (socket);
} }
@ -176,7 +176,7 @@ namespace client
void I2PControlService::HandleHandshake (const boost::system::error_code& ecode, std::shared_ptr<ssl_socket> socket) void I2PControlService::HandleHandshake (const boost::system::error_code& ecode, std::shared_ptr<ssl_socket> socket)
{ {
if (ecode) { if (ecode) {
LogPrint (eLogError, "I2PControl: handshake error: ", ecode.message ()); LogPrint (eLogError, "I2PControl: Handshake error: ", ecode.message ());
return; return;
} }
//std::this_thread::sleep_for (std::chrono::milliseconds(5)); //std::this_thread::sleep_for (std::chrono::milliseconds(5));
@ -202,7 +202,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "I2PControl: read error: ", ecode.message ()); LogPrint (eLogError, "I2PControl: Read error: ", ecode.message ());
return; return;
} }
else else
@ -225,7 +225,7 @@ namespace client
} }
if (ss.eof ()) if (ss.eof ())
{ {
LogPrint (eLogError, "I2PControl: malformed request, HTTP header expected"); LogPrint (eLogError, "I2PControl: Malformed request, HTTP header expected");
return; // TODO: return; // TODO:
} }
std::streamoff rem = contentLength + ss.tellg () - bytes_transferred; // more bytes to read std::streamoff rem = contentLength + ss.tellg () - bytes_transferred; // more bytes to read
@ -250,7 +250,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogWarning, "I2PControl: unknown method ", method); LogPrint (eLogWarning, "I2PControl: Unknown method ", method);
response << "{\"id\":null,\"error\":"; response << "{\"id\":null,\"error\":";
response << "{\"code\":-32601,\"message\":\"Method not found\"},"; response << "{\"code\":-32601,\"message\":\"Method not found\"},";
response << "\"jsonrpc\":\"2.0\"}"; response << "\"jsonrpc\":\"2.0\"}";
@ -259,7 +259,7 @@ namespace client
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "I2PControl: exception when handle request: ", ex.what ()); LogPrint (eLogError, "I2PControl: Exception when handle request: ", ex.what ());
std::ostringstream response; std::ostringstream response;
response << "{\"id\":null,\"error\":"; response << "{\"id\":null,\"error\":";
response << "{\"code\":-32700,\"message\":\"" << ex.what () << "\"},"; response << "{\"code\":-32700,\"message\":\"" << ex.what () << "\"},";
@ -268,7 +268,7 @@ namespace client
} }
catch (...) catch (...)
{ {
LogPrint (eLogError, "I2PControl: handle request unknown exception"); LogPrint (eLogError, "I2PControl: Handle request unknown exception");
} }
} }
} }
@ -329,7 +329,7 @@ namespace client
std::shared_ptr<ssl_socket> socket, std::shared_ptr<I2PControlBuffer> buf) std::shared_ptr<ssl_socket> socket, std::shared_ptr<I2PControlBuffer> buf)
{ {
if (ecode) { if (ecode) {
LogPrint (eLogError, "I2PControl: write error: ", ecode.message ()); LogPrint (eLogError, "I2PControl: Write error: ", ecode.message ());
} }
} }
@ -379,7 +379,7 @@ namespace client
void I2PControlService::PasswordHandler (const std::string& value) void I2PControlService::PasswordHandler (const std::string& value)
{ {
LogPrint (eLogWarning, "I2PControl: new password=", value, ", to make it persistent you should update your config!"); LogPrint (eLogWarning, "I2PControl: New password=", value, ", to make it persistent you should update your config!");
m_Password = value; m_Password = value;
m_Tokens.clear (); m_Tokens.clear ();
} }
@ -577,11 +577,11 @@ namespace client
// save cert // save cert
if ((f = fopen (crt_path, "wb")) != NULL) { if ((f = fopen (crt_path, "wb")) != NULL) {
LogPrint (eLogInfo, "I2PControl: saving new cert to ", crt_path); LogPrint (eLogInfo, "I2PControl: Saving new cert to ", crt_path);
PEM_write_X509 (f, x509); PEM_write_X509 (f, x509);
fclose (f); fclose (f);
} else { } else {
LogPrint (eLogError, "I2PControl: can't write cert: ", strerror(errno)); LogPrint (eLogError, "I2PControl: Can't write cert: ", strerror(errno));
} }
// save key // save key
@ -590,12 +590,12 @@ namespace client
PEM_write_PrivateKey (f, pkey, NULL, NULL, 0, NULL, NULL); PEM_write_PrivateKey (f, pkey, NULL, NULL, 0, NULL, NULL);
fclose (f); fclose (f);
} else { } else {
LogPrint (eLogError, "I2PControl: can't write key: ", strerror(errno)); LogPrint (eLogError, "I2PControl: Can't write key: ", strerror(errno));
} }
X509_free (x509); X509_free (x509);
} else { } else {
LogPrint (eLogError, "I2PControl: can't create RSA key for certificate"); LogPrint (eLogError, "I2PControl: Can't create RSA key for certificate");
} }
EVP_PKEY_free (pkey); EVP_PKEY_free (pkey);
} }

24
daemon/UPnP.cpp

@ -29,7 +29,7 @@ namespace transport
{ {
if (m_IsRunning) if (m_IsRunning)
{ {
LogPrint(eLogInfo, "UPnP: stopping"); LogPrint(eLogInfo, "UPnP: Stopping");
m_IsRunning = false; m_IsRunning = false;
m_Timer.cancel (); m_Timer.cancel ();
m_Service.stop (); m_Service.stop ();
@ -46,7 +46,7 @@ namespace transport
void UPnP::Start() void UPnP::Start()
{ {
m_IsRunning = true; m_IsRunning = true;
LogPrint(eLogInfo, "UPnP: starting"); LogPrint(eLogInfo, "UPnP: Starting");
m_Service.post (std::bind (&UPnP::Discover, this)); m_Service.post (std::bind (&UPnP::Discover, this));
std::unique_lock<std::mutex> l(m_StartedMutex); std::unique_lock<std::mutex> l(m_StartedMutex);
m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this))); m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));
@ -72,7 +72,7 @@ namespace transport
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "UPnP: runtime exception: ", ex.what ()); LogPrint (eLogError, "UPnP: Runtime exception: ", ex.what ());
PortMapping (); PortMapping ();
} }
} }
@ -106,7 +106,7 @@ namespace transport
if (isError) if (isError)
{ {
LogPrint (eLogError, "UPnP: unable to discover Internet Gateway Devices: error ", err); LogPrint (eLogError, "UPnP: Unable to discover Internet Gateway Devices: error ", err);
return; return;
} }
@ -117,22 +117,22 @@ namespace transport
err = UPNP_GetExternalIPAddress (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress); err = UPNP_GetExternalIPAddress (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);
if(err != UPNPCOMMAND_SUCCESS) if(err != UPNPCOMMAND_SUCCESS)
{ {
LogPrint (eLogError, "UPnP: unable to get external address: error ", err); LogPrint (eLogError, "UPnP: Unable to get external address: error ", err);
return; return;
} }
else else
{ {
LogPrint (eLogError, "UPnP: found Internet Gateway Device ", m_upnpUrls.controlURL); LogPrint (eLogError, "UPnP: Found Internet Gateway Device ", m_upnpUrls.controlURL);
if (!m_externalIPAddress[0]) if (!m_externalIPAddress[0])
{ {
LogPrint (eLogError, "UPnP: found Internet Gateway Device doesn't know our external address"); LogPrint (eLogError, "UPnP: Found Internet Gateway Device doesn't know our external address");
return; return;
} }
} }
} }
else else
{ {
LogPrint (eLogError, "UPnP: unable to find valid Internet Gateway Device: error ", err); LogPrint (eLogError, "UPnP: Unable to find valid Internet Gateway Device: error ", err);
return; return;
} }
@ -183,7 +183,7 @@ namespace transport
err = CheckMapping (strPort.c_str (), strType.c_str ()); err = CheckMapping (strPort.c_str (), strType.c_str ());
if (err != UPNPCOMMAND_SUCCESS) // if mapping not found if (err != UPNPCOMMAND_SUCCESS) // if mapping not found
{ {
LogPrint (eLogDebug, "UPnP: possibly port ", strPort, " is not forwarded: return code ", err); LogPrint (eLogDebug, "UPnP: Port ", strPort, " is possibly not forwarded: return code ", err);
#if ((MINIUPNPC_API_VERSION >= 8) || defined (UPNPDISCOVER_SUCCESS)) #if ((MINIUPNPC_API_VERSION >= 8) || defined (UPNPDISCOVER_SUCCESS))
err = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), NULL, NULL); err = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), NULL, NULL);
@ -192,18 +192,18 @@ namespace transport
#endif #endif
if (err != UPNPCOMMAND_SUCCESS) if (err != UPNPCOMMAND_SUCCESS)
{ {
LogPrint (eLogError, "UPnP: port forwarding to ", m_NetworkAddr, ":", strPort, " failed: return code ", err); LogPrint (eLogError, "UPnP: Port forwarding to ", m_NetworkAddr, ":", strPort, " failed: return code ", err);
return; return;
} }
else else
{ {
LogPrint (eLogInfo, "UPnP: port successfully forwarded (", m_externalIPAddress ,":", strPort, " type ", strType, " -> ", m_NetworkAddr ,":", strPort ,")"); LogPrint (eLogInfo, "UPnP: Port successfully forwarded (", m_externalIPAddress ,":", strPort, " type ", strType, " -> ", m_NetworkAddr ,":", strPort ,")");
return; return;
} }
} }
else else
{ {
LogPrint (eLogDebug, "UPnP: external forward from ", m_NetworkAddr, ":", strPort, " exists on current Internet Gateway Device"); LogPrint (eLogDebug, "UPnP: External forward from ", m_NetworkAddr, ":", strPort, " exists on current Internet Gateway Device");
return; return;
} }
} }

22
daemon/UnixDaemon.cpp

@ -72,7 +72,7 @@ namespace i2p
if (pid < 0) // error if (pid < 0) // error
{ {
LogPrint(eLogError, "Daemon: could not fork: ", strerror(errno)); LogPrint(eLogError, "Daemon: Could not fork: ", strerror(errno));
return false; return false;
} }
@ -81,13 +81,13 @@ namespace i2p
int sid = setsid(); int sid = setsid();
if (sid < 0) if (sid < 0)
{ {
LogPrint(eLogError, "Daemon: could not create process group."); LogPrint(eLogError, "Daemon: Could not create process group.");
return false; return false;
} }
std::string d = i2p::fs::GetDataDir(); std::string d = i2p::fs::GetDataDir();
if (chdir(d.c_str()) != 0) if (chdir(d.c_str()) != 0)
{ {
LogPrint(eLogError, "Daemon: could not chdir: ", strerror(errno)); LogPrint(eLogError, "Daemon: Could not chdir: ", strerror(errno));
return false; return false;
} }
@ -102,14 +102,14 @@ namespace i2p
uint16_t nfiles; i2p::config::GetOption("limits.openfiles", nfiles); uint16_t nfiles; i2p::config::GetOption("limits.openfiles", nfiles);
getrlimit(RLIMIT_NOFILE, &limit); getrlimit(RLIMIT_NOFILE, &limit);
if (nfiles == 0) { if (nfiles == 0) {
LogPrint(eLogInfo, "Daemon: using system limit in ", limit.rlim_cur, " max open files"); LogPrint(eLogInfo, "Daemon: Using system limit in ", limit.rlim_cur, " max open files");
} else if (nfiles <= limit.rlim_max) { } else if (nfiles <= limit.rlim_max) {
limit.rlim_cur = nfiles; limit.rlim_cur = nfiles;
if (setrlimit(RLIMIT_NOFILE, &limit) == 0) { if (setrlimit(RLIMIT_NOFILE, &limit) == 0) {
LogPrint(eLogInfo, "Daemon: set max number of open files to ", LogPrint(eLogInfo, "Daemon: Set max number of open files to ",
nfiles, " (system limit is ", limit.rlim_max, ")"); nfiles, " (system limit is ", limit.rlim_max, ")");
} else { } else {
LogPrint(eLogError, "Daemon: can't set max number of open files: ", strerror(errno)); LogPrint(eLogError, "Daemon: Can't set max number of open files: ", strerror(errno));
} }
} else { } else {
LogPrint(eLogError, "Daemon: limits.openfiles exceeds system limit: ", limit.rlim_max); LogPrint(eLogError, "Daemon: limits.openfiles exceeds system limit: ", limit.rlim_max);
@ -122,11 +122,11 @@ namespace i2p
if (cfsize <= limit.rlim_max) { if (cfsize <= limit.rlim_max) {
limit.rlim_cur = cfsize; limit.rlim_cur = cfsize;
if (setrlimit(RLIMIT_CORE, &limit) != 0) { if (setrlimit(RLIMIT_CORE, &limit) != 0) {
LogPrint(eLogError, "Daemon: can't set max size of coredump: ", strerror(errno)); LogPrint(eLogError, "Daemon: Can't set max size of coredump: ", strerror(errno));
} else if (cfsize == 0) { } else if (cfsize == 0) {
LogPrint(eLogInfo, "Daemon: coredumps disabled"); LogPrint(eLogInfo, "Daemon: coredumps disabled");
} else { } else {
LogPrint(eLogInfo, "Daemon: set max size of core files to ", cfsize / 1024, "Kb"); LogPrint(eLogInfo, "Daemon: Set max size of core files to ", cfsize / 1024, "Kb");
} }
} else { } else {
LogPrint(eLogError, "Daemon: limits.coresize exceeds system limit: ", limit.rlim_max); LogPrint(eLogError, "Daemon: limits.coresize exceeds system limit: ", limit.rlim_max);
@ -143,14 +143,14 @@ namespace i2p
pidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600); pidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600);
if (pidFH < 0) if (pidFH < 0)
{ {
LogPrint(eLogError, "Daemon: could not create pid file ", pidfile, ": ", strerror(errno)); LogPrint(eLogError, "Daemon: Could not create pid file ", pidfile, ": ", strerror(errno));
return false; return false;
} }
#ifndef ANDROID #ifndef ANDROID
if (lockf(pidFH, F_TLOCK, 0) != 0) if (lockf(pidFH, F_TLOCK, 0) != 0)
{ {
LogPrint(eLogError, "Daemon: could not lock pid file ", pidfile, ": ", strerror(errno)); LogPrint(eLogError, "Daemon: Could not lock pid file ", pidfile, ": ", strerror(errno));
return false; return false;
} }
#endif #endif
@ -159,7 +159,7 @@ namespace i2p
ftruncate(pidFH, 0); ftruncate(pidFH, 0);
if (write(pidFH, pid, strlen(pid)) < 0) if (write(pidFH, pid, strlen(pid)) < 0)
{ {
LogPrint(eLogError, "Daemon: could not write pidfile: ", strerror(errno)); LogPrint(eLogError, "Daemon: Could not write pidfile: ", strerror(errno));
return false; return false;
} }
} }

14
libi2pd/Blinding.cpp

@ -122,7 +122,7 @@ namespace data
break; break;
} }
default: default:
LogPrint (eLogError, "Blinding: signature type ", (int)sigType, " is not ECDSA"); LogPrint (eLogError, "Blinding: Signature type ", (int)sigType, " is not ECDSA");
} }
if (group) if (group)
{ {
@ -156,7 +156,7 @@ namespace data
size_t l = i2p::data::Base32ToByteStream (b33.c_str (), b33.length (), addr, 40); size_t l = i2p::data::Base32ToByteStream (b33.c_str (), b33.length (), addr, 40);
if (l < 32) if (l < 32)
{ {
LogPrint (eLogError, "Blinding: malformed b33 ", b33); LogPrint (eLogError, "Blinding: Malformed b33 ", b33);
return; return;
} }
uint32_t checksum = crc32 (0, addr + 3, l - 3); uint32_t checksum = crc32 (0, addr + 3, l - 3);
@ -186,10 +186,10 @@ namespace data
memcpy (m_PublicKey.data (), addr + offset, len); memcpy (m_PublicKey.data (), addr + offset, len);
} }
else else
LogPrint (eLogError, "Blinding: public key in b33 address is too short for signature type ", (int)m_SigType); LogPrint (eLogError, "Blinding: Public key in b33 address is too short for signature type ", (int)m_SigType);
} }
else else
LogPrint (eLogError, "Blinding: unknown signature type ", (int)m_SigType, " in b33"); LogPrint (eLogError, "Blinding: Unknown signature type ", (int)m_SigType, " in b33");
} }
std::string BlindedPublicKey::ToB33 () const std::string BlindedPublicKey::ToB33 () const
@ -256,7 +256,7 @@ namespace data
publicKeyLength = i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH; publicKeyLength = i2p::crypto::EDDSA25519_PUBLIC_KEY_LENGTH;
break; break;
default: default:
LogPrint (eLogError, "Blinding: can't blind signature type ", (int)m_SigType); LogPrint (eLogError, "Blinding: Can't blind signature type ", (int)m_SigType);
} }
return publicKeyLength; return publicKeyLength;
} }
@ -286,7 +286,7 @@ namespace data
break; break;
} }
default: default:
LogPrint (eLogError, "Blinding: can't blind signature type ", (int)m_SigType); LogPrint (eLogError, "Blinding: Can't blind signature type ", (int)m_SigType);
} }
return publicKeyLength; return publicKeyLength;
} }
@ -324,7 +324,7 @@ namespace data
SHA256_Final ((uint8_t *)hash, &ctx); SHA256_Final ((uint8_t *)hash, &ctx);
} }
else else
LogPrint (eLogError, "Blinding: blinded key type ", (int)m_BlindedSigType, " is not supported"); LogPrint (eLogError, "Blinding: Blinded key type ", (int)m_BlindedSigType, " is not supported");
return hash; return hash;
} }

26
libi2pd/Destination.cpp

@ -56,7 +56,7 @@ namespace client
it = params->find (I2CP_PARAM_TAGS_TO_SEND); it = params->find (I2CP_PARAM_TAGS_TO_SEND);
if (it != params->end ()) if (it != params->end ())
numTags = std::stoi(it->second); numTags = std::stoi(it->second);
LogPrint (eLogInfo, "Destination: parameters for tunnel set to: ", inQty, " inbound (", inLen, " hops), ", outQty, " outbound (", outLen, " hops), ", numTags, " tags"); LogPrint (eLogInfo, "Destination: Parameters for tunnel set to: ", inQty, " inbound (", inLen, " hops), ", outQty, " outbound (", outLen, " hops), ", numTags, " tags");
it = params->find (I2CP_PARAM_RATCHET_INBOUND_TAGS); it = params->find (I2CP_PARAM_RATCHET_INBOUND_TAGS);
if (it != params->end ()) if (it != params->end ())
SetNumRatchetInboundTags (std::stoi(it->second)); SetNumRatchetInboundTags (std::stoi(it->second));
@ -112,7 +112,7 @@ namespace client
m_LeaseSetPrivKey.reset (new i2p::data::Tag<32>()); m_LeaseSetPrivKey.reset (new i2p::data::Tag<32>());
if (m_LeaseSetPrivKey->FromBase64 (it->second) != 32) if (m_LeaseSetPrivKey->FromBase64 (it->second) != 32)
{ {
LogPrint(eLogError, "Destination: invalid value i2cp.leaseSetPrivKey ", it->second); LogPrint(eLogError, "Destination: Invalid value i2cp.leaseSetPrivKey ", it->second);
m_LeaseSetPrivKey.reset (nullptr); m_LeaseSetPrivKey.reset (nullptr);
} }
} }
@ -120,7 +120,7 @@ namespace client
} }
catch (std::exception & ex) catch (std::exception & ex)
{ {
LogPrint(eLogError, "Destination: unable to parse parameters for destination: ", ex.what()); LogPrint(eLogError, "Destination: Unable to parse parameters for destination: ", ex.what());
} }
SetNumTags (numTags); SetNumTags (numTags);
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (inLen, outLen, inQty, outQty); m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (inLen, outLen, inQty, outQty);
@ -136,7 +136,7 @@ namespace client
auto minlatency = std::stoi(itr->second); auto minlatency = std::stoi(itr->second);
if ( minlatency > 0 && maxlatency > 0 ) { if ( minlatency > 0 && maxlatency > 0 ) {
// set tunnel pool latency // set tunnel pool latency
LogPrint(eLogInfo, "Destination: requiring tunnel latency [", minlatency, "ms, ", maxlatency, "ms]"); LogPrint(eLogInfo, "Destination: Requiring tunnel latency [", minlatency, "ms, ", maxlatency, "ms]");
m_Pool->RequireLatency(minlatency, maxlatency); m_Pool->RequireLatency(minlatency, maxlatency);
} }
} }
@ -251,7 +251,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogWarning, "Destination: remote LeaseSet expired"); LogPrint (eLogWarning, "Destination: Remote LeaseSet expired");
std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex); std::lock_guard<std::mutex> lock(m_RemoteLeaseSetsMutex);
m_RemoteLeaseSets.erase (ident); m_RemoteLeaseSets.erase (ident);
return nullptr; return nullptr;
@ -618,7 +618,7 @@ namespace client
auto ls = GetLeaseSetMt (); auto ls = GetLeaseSetMt ();
if (!ls) if (!ls)
{ {
LogPrint (eLogWarning, "Destination: couldn't verify LeaseSet for ", GetIdentHash().ToBase32()); LogPrint (eLogWarning, "Destination: Couldn't verify LeaseSet for ", GetIdentHash().ToBase32());
return; return;
} }
auto s = shared_from_this (); auto s = shared_from_this ();
@ -630,7 +630,7 @@ namespace client
if (*ls == *leaseSet) if (*ls == *leaseSet)
{ {
// we got latest LeasetSet // we got latest LeasetSet
LogPrint (eLogDebug, "Destination: published LeaseSet verified for ", s->GetIdentHash().ToBase32()); LogPrint (eLogDebug, "Destination: Published LeaseSet verified for ", s->GetIdentHash().ToBase32());
s->m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_REGULAR_VERIFICATION_INTERNAL)); s->m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_REGULAR_VERIFICATION_INTERNAL));
s->m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer, s, std::placeholders::_1)); s->m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer, s, std::placeholders::_1));
return; return;
@ -639,7 +639,7 @@ namespace client
LogPrint (eLogDebug, "Destination: LeaseSet is different than just published for ", s->GetIdentHash().ToBase32()); LogPrint (eLogDebug, "Destination: LeaseSet is different than just published for ", s->GetIdentHash().ToBase32());
} }
else else
LogPrint (eLogWarning, "Destination: couldn't find published LeaseSet for ", s->GetIdentHash().ToBase32()); LogPrint (eLogWarning, "Destination: Couldn't find published LeaseSet for ", s->GetIdentHash().ToBase32());
// we have to publish again // we have to publish again
s->Publish (); s->Publish ();
}); });
@ -966,7 +966,7 @@ namespace client
} }
catch (std::exception & ex) catch (std::exception & ex)
{ {
LogPrint(eLogError, "Destination: unable to parse parameters for destination: ", ex.what()); LogPrint(eLogError, "Destination: Unable to parse parameters for destination: ", ex.what());
} }
} }
@ -1042,7 +1042,7 @@ namespace client
LogPrint (eLogError, "Destination: Missing raw datagram destination"); LogPrint (eLogError, "Destination: Missing raw datagram destination");
break; break;
default: default:
LogPrint (eLogError, "Destination: Data: unexpected protocol ", buf[9]); LogPrint (eLogError, "Destination: Data: Unexpected protocol ", buf[9]);
} }
} }
@ -1050,7 +1050,7 @@ namespace client
{ {
if (!streamRequestComplete) if (!streamRequestComplete)
{ {
LogPrint (eLogError, "Destination: request callback is not specified in CreateStream"); LogPrint (eLogError, "Destination: Request callback is not specified in CreateStream");
return; return;
} }
auto leaseSet = FindLeaseSet (dest); auto leaseSet = FindLeaseSet (dest);
@ -1074,7 +1074,7 @@ namespace client
{ {
if (!streamRequestComplete) if (!streamRequestComplete)
{ {
LogPrint (eLogError, "Destination: request callback is not specified in CreateStream"); LogPrint (eLogError, "Destination: Request callback is not specified in CreateStream");
return; return;
} }
auto s = GetSharedFromThis (); auto s = GetSharedFromThis ();
@ -1282,7 +1282,7 @@ namespace client
if (m_StandardEncryptionKey && m_StandardEncryptionKey->decryptor) if (m_StandardEncryptionKey && m_StandardEncryptionKey->decryptor)
return m_StandardEncryptionKey->decryptor->Decrypt (encrypted, data); return m_StandardEncryptionKey->decryptor->Decrypt (encrypted, data);
else else
LogPrint (eLogError, "Destinations: decryptor is not set"); LogPrint (eLogError, "Destinations: Decryptor is not set");
return false; return false;
} }

30
libi2pd/ECIESX25519AEADRatchetSession.cpp

@ -314,7 +314,7 @@ namespace garlic
GetOwner ()->HandleECIESx25519GarlicClove (buf + offset, size); GetOwner ()->HandleECIESx25519GarlicClove (buf + offset, size);
break; break;
case eECIESx25519BlkNextKey: case eECIESx25519BlkNextKey:
LogPrint (eLogDebug, "Garlic: next key"); LogPrint (eLogDebug, "Garlic: Next key");
if (receiveTagset) if (receiveTagset)
HandleNextKey (buf + offset, size, receiveTagset); HandleNextKey (buf + offset, size, receiveTagset);
else else
@ -322,7 +322,7 @@ namespace garlic
break; break;
case eECIESx25519BlkAck: case eECIESx25519BlkAck:
{ {
LogPrint (eLogDebug, "Garlic: ack"); LogPrint (eLogDebug, "Garlic: Ack");
int numAcks = size >> 2; // /4 int numAcks = size >> 2; // /4
auto offset1 = offset; auto offset1 = offset;
for (auto i = 0; i < numAcks; i++) for (auto i = 0; i < numAcks; i++)
@ -334,24 +334,24 @@ namespace garlic
} }
case eECIESx25519BlkAckRequest: case eECIESx25519BlkAckRequest:
{ {
LogPrint (eLogDebug, "Garlic: ack request"); LogPrint (eLogDebug, "Garlic: Ack request");
m_AckRequests.push_back ({receiveTagset->GetTagSetID (), index}); m_AckRequests.push_back ({receiveTagset->GetTagSetID (), index});
break; break;
} }
case eECIESx25519BlkTermination: case eECIESx25519BlkTermination:
LogPrint (eLogDebug, "Garlic: termination"); LogPrint (eLogDebug, "Garlic: Termination");
if (GetOwner ()) if (GetOwner ())
GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey); GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey);
if (receiveTagset) receiveTagset->Expire (); if (receiveTagset) receiveTagset->Expire ();
break; break;
case eECIESx25519BlkDateTime: case eECIESx25519BlkDateTime:
LogPrint (eLogDebug, "Garlic: datetime"); LogPrint (eLogDebug, "Garlic: Datetime");
break; break;
case eECIESx25519BlkOptions: case eECIESx25519BlkOptions:
LogPrint (eLogDebug, "Garlic: options"); LogPrint (eLogDebug, "Garlic: Options");
break; break;
case eECIESx25519BlkPadding: case eECIESx25519BlkPadding:
LogPrint (eLogDebug, "Garlic: padding"); LogPrint (eLogDebug, "Garlic: Padding");
break; break;
default: default:
LogPrint (eLogWarning, "Garlic: Unknown block type ", (int)blk); LogPrint (eLogWarning, "Garlic: Unknown block type ", (int)blk);
@ -381,7 +381,7 @@ namespace garlic
newTagset->NextSessionTagRatchet (); newTagset->NextSessionTagRatchet ();
m_SendTagset = newTagset; m_SendTagset = newTagset;
m_SendForwardKey = false; m_SendForwardKey = false;
LogPrint (eLogDebug, "Garlic: next send tagset ", newTagset->GetTagSetID (), " created"); LogPrint (eLogDebug, "Garlic: Next send tagset ", newTagset->GetTagSetID (), " created");
} }
else else
LogPrint (eLogDebug, "Garlic: Unexpected next key ", keyID); LogPrint (eLogDebug, "Garlic: Unexpected next key ", keyID);
@ -424,7 +424,7 @@ namespace garlic
GenerateMoreReceiveTags (newTagset, (GetOwner () && GetOwner ()->GetNumRatchetInboundTags () > 0) ? GenerateMoreReceiveTags (newTagset, (GetOwner () && GetOwner ()->GetNumRatchetInboundTags () > 0) ?
GetOwner ()->GetNumRatchetInboundTags () : ECIESX25519_MAX_NUM_GENERATED_TAGS); GetOwner ()->GetNumRatchetInboundTags () : ECIESX25519_MAX_NUM_GENERATED_TAGS);
receiveTagset->Expire (); receiveTagset->Expire ();
LogPrint (eLogDebug, "Garlic: next receive tagset ", tagsetID, " created"); LogPrint (eLogDebug, "Garlic: Next receive tagset ", tagsetID, " created");
} }
} }
@ -446,7 +446,7 @@ namespace garlic
m_NextSendRatchet->key = i2p::transport::transports.GetNextX25519KeysPair (); m_NextSendRatchet->key = i2p::transport::transports.GetNextX25519KeysPair ();
m_SendForwardKey = true; m_SendForwardKey = true;
LogPrint (eLogDebug, "Garlic: new send ratchet ", m_NextSendRatchet->newKey ? "new" : "old", " key ", m_NextSendRatchet->keyID, " created"); LogPrint (eLogDebug, "Garlic: New send ratchet ", m_NextSendRatchet->newKey ? "new" : "old", " key ", m_NextSendRatchet->keyID, " created");
} }
bool ECIESX25519AEADRatchetSession::NewOutgoingSessionMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen, bool isStatic) bool ECIESX25519AEADRatchetSession::NewOutgoingSessionMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen, bool isStatic)
@ -618,7 +618,7 @@ namespace garlic
bool ECIESX25519AEADRatchetSession::HandleNewOutgoingSessionReply (uint8_t * buf, size_t len) bool ECIESX25519AEADRatchetSession::HandleNewOutgoingSessionReply (uint8_t * buf, size_t len)
{ {
// we are Alice // we are Alice
LogPrint (eLogDebug, "Garlic: reply received"); LogPrint (eLogDebug, "Garlic: Reply received");
const uint8_t * tag = buf; const uint8_t * tag = buf;
buf += 8; len -= 8; // tag buf += 8; len -= 8; // tag
uint8_t bepk[32]; // Bob's ephemeral key uint8_t bepk[32]; // Bob's ephemeral key
@ -700,7 +700,7 @@ namespace garlic
uint64_t tag = m_SendTagset->GetNextSessionTag (); uint64_t tag = m_SendTagset->GetNextSessionTag ();
if (!tag) if (!tag)
{ {
LogPrint (eLogError, "Garlic: can't create new ECIES-X25519-AEAD-Ratchet tag for send tagset"); LogPrint (eLogError, "Garlic: Can't create new ECIES-X25519-AEAD-Ratchet tag for send tagset");
if (GetOwner ()) if (GetOwner ())
GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey); GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey);
return false; return false;
@ -776,7 +776,7 @@ namespace garlic
if (receiveTagset->IsNS ()) if (receiveTagset->IsNS ())
{ {
// our of sequence NSR // our of sequence NSR
LogPrint (eLogDebug, "Garlic: check for out of order NSR with index ", index); LogPrint (eLogDebug, "Garlic: Check for out of order NSR with index ", index);
if (receiveTagset->GetNextIndex () - index < ECIESX25519_NSR_NUM_GENERATED_TAGS/2) if (receiveTagset->GetNextIndex () - index < ECIESX25519_NSR_NUM_GENERATED_TAGS/2)
GenerateMoreReceiveTags (receiveTagset, ECIESX25519_NSR_NUM_GENERATED_TAGS); GenerateMoreReceiveTags (receiveTagset, ECIESX25519_NSR_NUM_GENERATED_TAGS);
return HandleNewOutgoingSessionReply (buf, len); return HandleNewOutgoingSessionReply (buf, len);
@ -912,7 +912,7 @@ namespace garlic
{ {
if (payloadLen > I2NP_MAX_MESSAGE_SIZE) if (payloadLen > I2NP_MAX_MESSAGE_SIZE)
{ {
LogPrint (eLogError, "Garlic: payload length ", payloadLen, " is too long"); LogPrint (eLogError, "Garlic: Payload length ", payloadLen, " is too long");
return 0; return 0;
} }
m_LastSentTimestamp = ts; m_LastSentTimestamp = ts;
@ -1056,7 +1056,7 @@ namespace garlic
auto tag = GetOwner ()->AddECIESx25519SessionNextTag (receiveTagset); auto tag = GetOwner ()->AddECIESx25519SessionNextTag (receiveTagset);
if (!tag) if (!tag)
{ {
LogPrint (eLogError, "Garlic: can't create new ECIES-X25519-AEAD-Ratchet tag for receive tagset"); LogPrint (eLogError, "Garlic: Can't create new ECIES-X25519-AEAD-Ratchet tag for receive tagset");
break; break;
} }
} }

60
libi2pd/Garlic.cpp

@ -490,7 +490,7 @@ namespace garlic
uint32_t length = bufbe32toh (buf); uint32_t length = bufbe32toh (buf);
if (length > msg->GetLength ()) if (length > msg->GetLength ())
{ {
LogPrint (eLogWarning, "Garlic: message length ", length, " exceeds I2NP message length ", msg->GetLength ()); LogPrint (eLogWarning, "Garlic: Message length ", length, " exceeds I2NP message length ", msg->GetLength ());
return; return;
} }
auto mod = length & 0x0f; // %16 auto mod = length & 0x0f; // %16
@ -519,7 +519,7 @@ namespace garlic
found = true; found = true;
} }
else else
LogPrint (eLogWarning, "Garlic: message length ", length, " is less than 32 bytes"); LogPrint (eLogWarning, "Garlic: Message length ", length, " is less than 32 bytes");
} }
if (!found) // assume new session if (!found) // assume new session
{ {
@ -547,13 +547,13 @@ namespace garlic
{ {
uint64_t missingTag; memcpy (&missingTag, buf, 8); uint64_t missingTag; memcpy (&missingTag, buf, 8);
auto maxTags = std::max (m_NumRatchetInboundTags, ECIESX25519_MAX_NUM_GENERATED_TAGS); auto maxTags = std::max (m_NumRatchetInboundTags, ECIESX25519_MAX_NUM_GENERATED_TAGS);
LogPrint (eLogWarning, "Garlic: trying to generate more ECIES-X25519-AEAD-Ratchet tags"); LogPrint (eLogWarning, "Garlic: Trying to generate more ECIES-X25519-AEAD-Ratchet tags");
for (int i = 0; i < maxTags; i++) for (int i = 0; i < maxTags; i++)
{ {
auto nextTag = AddECIESx25519SessionNextTag (m_LastTagset); auto nextTag = AddECIESx25519SessionNextTag (m_LastTagset);
if (!nextTag) if (!nextTag)
{ {
LogPrint (eLogError, "Garlic: can't create new ECIES-X25519-AEAD-Ratchet tag for last tagset"); LogPrint (eLogError, "Garlic: Can't create new ECIES-X25519-AEAD-Ratchet tag for last tagset");
break; break;
} }
if (nextTag == missingTag) if (nextTag == missingTag)
@ -567,7 +567,7 @@ namespace garlic
if (!found) m_LastTagset = nullptr; if (!found) m_LastTagset = nullptr;
} }
if (!found) if (!found)
LogPrint (eLogError, "Garlic: can't handle ECIES-X25519-AEAD-Ratchet message"); LogPrint (eLogError, "Garlic: Can't handle ECIES-X25519-AEAD-Ratchet message");
} }
} }
else else
@ -586,7 +586,7 @@ namespace garlic
if (it->second.tagset->HandleNextMessage (buf, len, it->second.index)) if (it->second.tagset->HandleNextMessage (buf, len, it->second.index))
m_LastTagset = it->second.tagset; m_LastTagset = it->second.tagset;
else else
LogPrint (eLogError, "Garlic: can't handle ECIES-X25519-AEAD-Ratchet message"); LogPrint (eLogError, "Garlic: Can't handle ECIES-X25519-AEAD-Ratchet message");
m_ECIESx25519Tags.erase (it); m_ECIESx25519Tags.erase (it);
return true; return true;
} }
@ -629,7 +629,7 @@ namespace garlic
SHA256 (buf, payloadSize, digest); SHA256 (buf, payloadSize, digest);
if (memcmp (payloadHash, digest, 32)) // payload hash doesn't match if (memcmp (payloadHash, digest, 32)) // payload hash doesn't match
{ {
LogPrint (eLogError, "Garlic: wrong payload hash"); LogPrint (eLogError, "Garlic: Wrong payload hash");
return; return;
} }
HandleGarlicPayload (buf, payloadSize, from); HandleGarlicPayload (buf, payloadSize, from);
@ -639,7 +639,7 @@ namespace garlic
{ {
if (len < 1) if (len < 1)
{ {
LogPrint (eLogError, "Garlic: payload is too short"); LogPrint (eLogError, "Garlic: Payload is too short");
return; return;
} }
int numCloves = buf[0]; int numCloves = buf[0];
@ -654,7 +654,7 @@ namespace garlic
if (flag & 0x80) // encrypted? if (flag & 0x80) // encrypted?
{ {
// TODO: implement // TODO: implement
LogPrint (eLogWarning, "Garlic: clove encrypted"); LogPrint (eLogWarning, "Garlic: Clove encrypted");
buf += 32; buf += 32;
} }
ptrdiff_t offset = buf - buf1; ptrdiff_t offset = buf - buf1;
@ -662,35 +662,35 @@ namespace garlic
switch (deliveryType) switch (deliveryType)
{ {
case eGarlicDeliveryTypeLocal: case eGarlicDeliveryTypeLocal:
LogPrint (eLogDebug, "Garlic: type local"); LogPrint (eLogDebug, "Garlic: Type local");
if (offset > (int)len) if (offset > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
HandleI2NPMessage (buf, len - offset); HandleI2NPMessage (buf, len - offset);
break; break;
case eGarlicDeliveryTypeDestination: case eGarlicDeliveryTypeDestination:
LogPrint (eLogDebug, "Garlic: type destination"); LogPrint (eLogDebug, "Garlic: Type destination");
buf += 32; // destination. check it later or for multiple destinations buf += 32; // destination. check it later or for multiple destinations
offset = buf - buf1; offset = buf - buf1;
if (offset > (int)len) if (offset > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
HandleI2NPMessage (buf, len - offset); HandleI2NPMessage (buf, len - offset);
break; break;
case eGarlicDeliveryTypeTunnel: case eGarlicDeliveryTypeTunnel:
{ {
LogPrint (eLogDebug, "Garlic: type tunnel"); LogPrint (eLogDebug, "Garlic: Type tunnel");
// gwHash and gwTunnel sequence is reverted // gwHash and gwTunnel sequence is reverted
uint8_t * gwHash = buf; uint8_t * gwHash = buf;
buf += 32; buf += 32;
offset = buf - buf1; offset = buf - buf1;
if (offset + 4 > (int)len) if (offset + 4 > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
uint32_t gwTunnel = bufbe32toh (buf); uint32_t gwTunnel = bufbe32toh (buf);
@ -721,22 +721,22 @@ namespace garlic
{ {
if (offset > (int)len) if (offset > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
i2p::transport::transports.SendMessage (ident, i2p::transport::transports.SendMessage (ident,
CreateI2NPMessage (buf, GetI2NPMessageLength (buf, len - offset))); CreateI2NPMessage (buf, GetI2NPMessageLength (buf, len - offset)));
} }
else else
LogPrint (eLogWarning, "Garlic: type router for inbound tunnels not supported"); LogPrint (eLogWarning, "Garlic: Type router for inbound tunnels not supported");
break; break;
} }
default: default:
LogPrint (eLogWarning, "Garlic: unknown delivery type ", (int)deliveryType); LogPrint (eLogWarning, "Garlic: Unknown delivery type ", (int)deliveryType);
} }
if (offset > (int)len) if (offset > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
buf += GetI2NPMessageLength (buf, len - offset); // I2NP buf += GetI2NPMessageLength (buf, len - offset); // I2NP
@ -746,7 +746,7 @@ namespace garlic
offset = buf - buf1; offset = buf - buf1;
if (offset > (int)len) if (offset > (int)len)
{ {
LogPrint (eLogError, "Garlic: clove is too long"); LogPrint (eLogError, "Garlic: Clove is too long");
break; break;
} }
len -= offset; len -= offset;
@ -780,7 +780,7 @@ namespace garlic
session = it->second; session = it->second;
if (session->IsInactive (i2p::util::GetSecondsSinceEpoch ())) if (session->IsInactive (i2p::util::GetSecondsSinceEpoch ()))
{ {
LogPrint (eLogDebug, "Garlic: session restarted"); LogPrint (eLogDebug, "Garlic: Session restarted");
session = nullptr; session = nullptr;
} }
} }
@ -840,7 +840,7 @@ namespace garlic
it->second->GetSharedRoutingPath (); // delete shared path if necessary it->second->GetSharedRoutingPath (); // delete shared path if necessary
if (!it->second->CleanupExpiredTags ()) if (!it->second->CleanupExpiredTags ())
{ {
LogPrint (eLogInfo, "Routing session to ", it->first.ToBase32 (), " deleted"); LogPrint (eLogInfo, "Garlic: Routing session to ", it->first.ToBase32 (), " deleted");
it->second->SetOwner (nullptr); it->second->SetOwner (nullptr);
it = m_Sessions.erase (it); it = m_Sessions.erase (it);
} }
@ -925,7 +925,7 @@ namespace garlic
if (session) if (session)
{ {
session->MessageConfirmed (msgID); session->MessageConfirmed (msgID);
LogPrint (eLogDebug, "Garlic: message ", msgID, " acknowledged"); LogPrint (eLogDebug, "Garlic: Message ", msgID, " acknowledged");
} }
} }
@ -1030,7 +1030,7 @@ namespace garlic
switch (deliveryType) switch (deliveryType)
{ {
case eGarlicDeliveryTypeDestination: case eGarlicDeliveryTypeDestination:
LogPrint (eLogDebug, "Garlic: type destination"); LogPrint (eLogDebug, "Garlic: Type destination");
buf += 32; // TODO: check destination buf += 32; // TODO: check destination
#if (__cplusplus >= 201703L) // C++ 17 or higher #if (__cplusplus >= 201703L) // C++ 17 or higher
[[fallthrough]]; [[fallthrough]];
@ -1038,7 +1038,7 @@ namespace garlic
// no break here // no break here
case eGarlicDeliveryTypeLocal: case eGarlicDeliveryTypeLocal:
{ {
LogPrint (eLogDebug, "Garlic: type local"); LogPrint (eLogDebug, "Garlic: Type local");
I2NPMessageType typeID = (I2NPMessageType)(buf[0]); buf++; // typeid I2NPMessageType typeID = (I2NPMessageType)(buf[0]); buf++; // typeid
int32_t msgID = bufbe32toh (buf); buf += 4; // msgID int32_t msgID = bufbe32toh (buf); buf += 4; // msgID
buf += 4; // expiration buf += 4; // expiration
@ -1046,19 +1046,19 @@ namespace garlic
if (offset <= (int)len) if (offset <= (int)len)
HandleCloveI2NPMessage (typeID, buf, len - offset, msgID); HandleCloveI2NPMessage (typeID, buf, len - offset, msgID);
else else
LogPrint (eLogError, "Garlic: clove is too long"); LogPrint (eLogError, "Garlic: Clove is too long");
break; break;
} }
case eGarlicDeliveryTypeTunnel: case eGarlicDeliveryTypeTunnel:
{ {
LogPrint (eLogDebug, "Garlic: type tunnel"); LogPrint (eLogDebug, "Garlic: Type tunnel");
// gwHash and gwTunnel sequence is reverted // gwHash and gwTunnel sequence is reverted
const uint8_t * gwHash = buf; const uint8_t * gwHash = buf;
buf += 32; buf += 32;
ptrdiff_t offset = buf - buf1; ptrdiff_t offset = buf - buf1;
if (offset + 13 > (int)len) if (offset + 13 > (int)len)
{ {
LogPrint (eLogError, "Garlic: message is too short"); LogPrint (eLogError, "Garlic: Message is too short");
break; break;
} }
uint32_t gwTunnel = bufbe32toh (buf); buf += 4; uint32_t gwTunnel = bufbe32toh (buf); buf += 4;
@ -1079,7 +1079,7 @@ namespace garlic
break; break;
} }
default: default:
LogPrint (eLogWarning, "Garlic: unexpected delivery type ", (int)deliveryType); LogPrint (eLogWarning, "Garlic: Unexpected delivery type ", (int)deliveryType);
} }
} }
@ -1105,7 +1105,7 @@ namespace garlic
} }
else else
{ {
LogPrint (eLogInfo, "Garlic: ECIESx25519 session with static key ", staticKeyTag.ToBase64 (), " already exists"); LogPrint (eLogInfo, "Garlic: ECIESx25519 session with static key ", staticKeyTag.ToBase64 (), " already exists");
return; return;
} }
} }

20
libi2pd/I2NPProtocol.cpp

@ -75,7 +75,7 @@ namespace i2p
{ {
auto msg = NewI2NPMessage (len); auto msg = NewI2NPMessage (len);
if (msg->Concat (buf, len) < len) if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length ", msg->maxLen); LogPrint (eLogError, "I2NP: Message length ", len, " exceeds max length ", msg->maxLen);
msg->FillI2NPMessageHeader (msgType, replyMsgID); msg->FillI2NPMessageHeader (msgType, replyMsgID);
return msg; return msg;
} }
@ -90,7 +90,7 @@ namespace i2p
msg->from = from; msg->from = from;
} }
else else
LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length"); LogPrint (eLogError, "I2NP: Message length ", len, " exceeds max length");
return msg; return msg;
} }
@ -171,7 +171,7 @@ namespace i2p
std::shared_ptr<I2NPMessage> CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest, std::shared_ptr<I2NPMessage> CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest,
const std::set<i2p::data::IdentHash>& excludedFloodfills, const std::set<i2p::data::IdentHash>& excludedFloodfills,
std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel, const uint8_t * replyKey, std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel, const uint8_t * replyKey,
const uint8_t * replyTag, bool replyECIES) const uint8_t * replyTag, bool replyECIES)
{ {
int cnt = excludedFloodfills.size (); int cnt = excludedFloodfills.size ();
auto m = cnt > 7 ? NewI2NPMessage () : NewI2NPShortMessage (); auto m = cnt > 7 ? NewI2NPMessage () : NewI2NPShortMessage ();
@ -685,7 +685,7 @@ namespace i2p
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len); htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
msg->len += TUNNEL_GATEWAY_HEADER_SIZE; msg->len += TUNNEL_GATEWAY_HEADER_SIZE;
if (msg->Concat (buf, len) < len) if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen); LogPrint (eLogError, "I2NP: Tunnel gateway buffer overflow ", msg->maxLen);
msg->FillI2NPMessageHeader (eI2NPTunnelGateway); msg->FillI2NPMessageHeader (eI2NPTunnelGateway);
return msg; return msg;
} }
@ -716,7 +716,7 @@ namespace i2p
msg->offset += gatewayMsgOffset; msg->offset += gatewayMsgOffset;
msg->len += gatewayMsgOffset; msg->len += gatewayMsgOffset;
if (msg->Concat (buf, len) < len) if (msg->Concat (buf, len) < len)
LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen); LogPrint (eLogError, "I2NP: Tunnel gateway buffer overflow ", msg->maxLen);
msg->FillI2NPMessageHeader (msgType, replyMsgID); // create content message msg->FillI2NPMessageHeader (msgType, replyMsgID); // create content message
len = msg->GetLength (); len = msg->GetLength ();
msg->offset -= gatewayMsgOffset; msg->offset -= gatewayMsgOffset;
@ -731,13 +731,13 @@ namespace i2p
{ {
if (len < I2NP_HEADER_SIZE_OFFSET + 2) if (len < I2NP_HEADER_SIZE_OFFSET + 2)
{ {
LogPrint (eLogError, "I2NP: message length ", len, " is smaller than header"); LogPrint (eLogError, "I2NP: Message length ", len, " is smaller than header");
return len; return len;
} }
auto l = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET) + I2NP_HEADER_SIZE; auto l = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET) + I2NP_HEADER_SIZE;
if (l > len) if (l > len)
{ {
LogPrint (eLogError, "I2NP: message length ", l, " exceeds buffer length ", len); LogPrint (eLogError, "I2NP: Message length ", l, " exceeds buffer length ", len);
l = len; l = len;
} }
return l; return l;
@ -747,18 +747,18 @@ namespace i2p
{ {
if (len < I2NP_HEADER_SIZE) if (len < I2NP_HEADER_SIZE)
{ {
LogPrint (eLogError, "I2NP: message length ", len, " is smaller than header"); LogPrint (eLogError, "I2NP: Message length ", len, " is smaller than header");
return; return;
} }
uint8_t typeID = msg[I2NP_HEADER_TYPEID_OFFSET]; uint8_t typeID = msg[I2NP_HEADER_TYPEID_OFFSET];
uint32_t msgID = bufbe32toh (msg + I2NP_HEADER_MSGID_OFFSET); uint32_t msgID = bufbe32toh (msg + I2NP_HEADER_MSGID_OFFSET);
LogPrint (eLogDebug, "I2NP: msg received len=", len,", type=", (int)typeID, ", msgID=", (unsigned int)msgID); LogPrint (eLogDebug, "I2NP: Msg received len=", len,", type=", (int)typeID, ", msgID=", (unsigned int)msgID);
uint8_t * buf = msg + I2NP_HEADER_SIZE; uint8_t * buf = msg + I2NP_HEADER_SIZE;
auto size = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET); auto size = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET);
len -= I2NP_HEADER_SIZE; len -= I2NP_HEADER_SIZE;
if (size > len) if (size > len)
{ {
LogPrint (eLogError, "I2NP: payload size ", size, " exceeds buffer length ", len); LogPrint (eLogError, "I2NP: Payload size ", size, " exceeds buffer length ", len);
size = len; size = len;
} }
switch (typeID) switch (typeID)

4
libi2pd/Identity.cpp

@ -215,7 +215,7 @@ namespace data
{ {
if (len < DEFAULT_IDENTITY_SIZE) if (len < DEFAULT_IDENTITY_SIZE)
{ {
LogPrint (eLogError, "Identity: buffer length ", len, " is too small"); LogPrint (eLogError, "Identity: Buffer length ", len, " is too small");
return 0; return 0;
} }
memcpy (&m_StandardIdentity, buf, DEFAULT_IDENTITY_SIZE); memcpy (&m_StandardIdentity, buf, DEFAULT_IDENTITY_SIZE);
@ -509,7 +509,7 @@ namespace data
if (m_Public->GetSignatureLen () + ret > len) return 0; if (m_Public->GetSignatureLen () + ret > len) return 0;
if (!m_Public->Verify (offlineInfo, keyLen + 6, buf + ret)) if (!m_Public->Verify (offlineInfo, keyLen + 6, buf + ret))
{ {
LogPrint (eLogError, "Identity: offline signature verification failed"); LogPrint (eLogError, "Identity: Offline signature verification failed");
return 0; return 0;
} }
ret += m_Public->GetSignatureLen (); ret += m_Public->GetSignatureLen ();

30
libi2pd/LeaseSet.cpp

@ -61,7 +61,7 @@ namespace data
size_t size = m_Identity->GetFullLen (); size_t size = m_Identity->GetFullLen ();
if (size > m_BufferLen) if (size > m_BufferLen)
{ {
LogPrint (eLogError, "LeaseSet: identity length ", size, " exceeds buffer size ", m_BufferLen); LogPrint (eLogError, "LeaseSet: Identity length ", size, " exceeds buffer size ", m_BufferLen);
m_IsValid = false; m_IsValid = false;
return; return;
} }
@ -80,10 +80,10 @@ namespace data
} }
uint8_t num = m_Buffer[size]; uint8_t num = m_Buffer[size];
size++; // num size++; // num
LogPrint (eLogDebug, "LeaseSet: read num=", (int)num); LogPrint (eLogDebug, "LeaseSet: Read num=", (int)num);
if (!num || num > MAX_NUM_LEASES) if (!num || num > MAX_NUM_LEASES)
{ {
LogPrint (eLogError, "LeaseSet: incorrect number of leases", (int)num); LogPrint (eLogError, "LeaseSet: Rncorrect number of leases", (int)num);
m_IsValid = false; m_IsValid = false;
return; return;
} }
@ -112,7 +112,7 @@ namespace data
} }
if (!m_ExpirationTime) if (!m_ExpirationTime)
{ {
LogPrint (eLogWarning, "LeaseSet: all leases are expired. Dropped"); LogPrint (eLogWarning, "LeaseSet: All leases are expired. Dropped");
m_IsValid = false; m_IsValid = false;
return; return;
} }
@ -130,7 +130,7 @@ namespace data
} }
else if (!m_Identity->Verify (m_Buffer, signedSize, leases)) else if (!m_Identity->Verify (m_Buffer, signedSize, leases))
{ {
LogPrint (eLogWarning, "LeaseSet: verification failed"); LogPrint (eLogWarning, "LeaseSet: Verification failed");
m_IsValid = false; m_IsValid = false;
} }
} }
@ -274,7 +274,7 @@ namespace data
{ {
if (len <= m_BufferLen) m_BufferLen = len; if (len <= m_BufferLen) m_BufferLen = len;
else else
LogPrint (eLogError, "LeaseSet2: actual buffer size ", len , " exceeds full buffer size ", m_BufferLen); LogPrint (eLogError, "LeaseSet2: Actual buffer size ", len , " exceeds full buffer size ", m_BufferLen);
} }
LeaseSet2::LeaseSet2 (uint8_t storeType, const uint8_t * buf, size_t len, bool storeLeases, CryptoKeyType preferredCrypto): LeaseSet2::LeaseSet2 (uint8_t storeType, const uint8_t * buf, size_t len, bool storeLeases, CryptoKeyType preferredCrypto):
@ -331,7 +331,7 @@ namespace data
m_TransientVerifier = ProcessOfflineSignature (identity, buf, len, offset); m_TransientVerifier = ProcessOfflineSignature (identity, buf, len, offset);
if (!m_TransientVerifier) if (!m_TransientVerifier)
{ {
LogPrint (eLogError, "LeaseSet2: offline signature failed"); LogPrint (eLogError, "LeaseSet2: Offline signature failed");
return; return;
} }
} }
@ -378,7 +378,7 @@ namespace data
bool verified = verifier->Verify (buf - 1, signatureOffset + 1, buf + signatureOffset); bool verified = verifier->Verify (buf - 1, signatureOffset + 1, buf + signatureOffset);
const_cast<uint8_t *>(buf)[-1] = c; const_cast<uint8_t *>(buf)[-1] = c;
if (!verified) if (!verified)
LogPrint (eLogWarning, "LeaseSet2: verification failed"); LogPrint (eLogWarning, "LeaseSet2: Verification failed");
return verified; return verified;
} }
@ -489,7 +489,7 @@ namespace data
m_TransientVerifier = ProcessOfflineSignature (blindedVerifier, buf, len, offset); m_TransientVerifier = ProcessOfflineSignature (blindedVerifier, buf, len, offset);
if (!m_TransientVerifier) if (!m_TransientVerifier)
{ {
LogPrint (eLogError, "LeaseSet2: offline signature failed"); LogPrint (eLogError, "LeaseSet2: Offline signature failed");
return; return;
} }
} }
@ -515,7 +515,7 @@ namespace data
key->GetBlindedKey (date, blinded.data ()); key->GetBlindedKey (date, blinded.data ());
if (memcmp (blindedPublicKey, blinded.data (), blindedKeyLen)) if (memcmp (blindedPublicKey, blinded.data (), blindedKeyLen))
{ {
LogPrint (eLogError, "LeaseSet2: blinded public key doesn't match"); LogPrint (eLogError, "LeaseSet2: Blinded public key doesn't match");
return; return;
} }
} }
@ -569,7 +569,7 @@ namespace data
ReadFromBuffer (innerPlainText.data () + 1, lenInnerPlaintext - 1); ReadFromBuffer (innerPlainText.data () + 1, lenInnerPlaintext - 1);
} }
else else
LogPrint (eLogError, "LeaseSet2: unexpected LeaseSet type ", (int)innerPlainText[0], " inside encrypted LeaseSet"); LogPrint (eLogError, "LeaseSet2: Unexpected LeaseSet type ", (int)innerPlainText[0], " inside encrypted LeaseSet");
} }
else else
{ {
@ -653,7 +653,7 @@ namespace data
LogPrint (eLogError, "LeaseSet2: Can't calculate authCookie: psk_i is not provided"); LogPrint (eLogError, "LeaseSet2: Can't calculate authCookie: psk_i is not provided");
} }
else else
LogPrint (eLogError, "LeaseSet2: unknown client auth type ", (int)flag); LogPrint (eLogError, "LeaseSet2: Unknown client auth type ", (int)flag);
} }
return offset - 1; return offset - 1;
} }
@ -768,7 +768,7 @@ namespace data
size_t size = ident.GetFullLen (); size_t size = ident.GetFullLen ();
if (size > sz) if (size > sz)
{ {
LogPrint (eLogError, "LeaseSet: identity length ", size, " exceeds buffer size ", sz); LogPrint (eLogError, "LeaseSet: Identity length ", size, " exceeds buffer size ", sz);
return false; return false;
} }
// encryption key // encryption key
@ -779,7 +779,7 @@ namespace data
++size; ++size;
if (!numLeases || numLeases > MAX_NUM_LEASES) if (!numLeases || numLeases > MAX_NUM_LEASES)
{ {
LogPrint (eLogError, "LeaseSet: incorrect number of leases", (int)numLeases); LogPrint (eLogError, "LeaseSet: Incorrect number of leases", (int)numLeases);
return false; return false;
} }
const uint8_t * leases = ptr + size; const uint8_t * leases = ptr + size;
@ -984,7 +984,7 @@ namespace data
m_StoreHash = blindedKey->GetStoreHash (); m_StoreHash = blindedKey->GetStoreHash ();
} }
else else
LogPrint (eLogError, "LeaseSet2: couldn't extract inner layer"); LogPrint (eLogError, "LeaseSet2: Couldn't extract inner layer");
} }
void LocalEncryptedLeaseSet2::CreateClientAuthData (const uint8_t * subcredential, int authType, std::shared_ptr<std::vector<AuthPublicKey> > authKeys, const uint8_t * authCookie, uint8_t * authData) const void LocalEncryptedLeaseSet2::CreateClientAuthData (const uint8_t * subcredential, int authType, std::shared_ptr<std::vector<AuthPublicKey> > authKeys, const uint8_t * authCookie, uint8_t * authData) const

6
libi2pd/Log.cpp

@ -129,10 +129,10 @@ namespace log {
else if (level == "info") { m_MinLevel = eLogInfo; } else if (level == "info") { m_MinLevel = eLogInfo; }
else if (level == "debug") { m_MinLevel = eLogDebug; } else if (level == "debug") { m_MinLevel = eLogDebug; }
else { else {
LogPrint(eLogError, "Log: unknown loglevel: ", level); LogPrint(eLogError, "Log: Unknown loglevel: ", level);
return; return;
} }
LogPrint(eLogInfo, "Log: min messages level set to ", level); LogPrint(eLogInfo, "Log: Logging level set to ", level);
} }
const char * Log::TimeAsString(std::time_t t) { const char * Log::TimeAsString(std::time_t t) {
@ -212,7 +212,7 @@ namespace log {
m_LogStream = os; m_LogStream = os;
return; return;
} }
LogPrint(eLogError, "Log: can't open file ", path); LogPrint(eLogError, "Log: Can't open file ", path);
} }
void Log::SendTo (std::shared_ptr<std::ostream> os) { void Log::SendTo (std::shared_ptr<std::ostream> os) {

62
libi2pd/NTCP2.cpp

@ -372,7 +372,7 @@ namespace transport
transports.PeerDisconnected (shared_from_this ()); transports.PeerDisconnected (shared_from_this ());
m_Server.RemoveNTCP2Session (shared_from_this ()); m_Server.RemoveNTCP2Session (shared_from_this ());
m_SendQueue.clear (); m_SendQueue.clear ();
LogPrint (eLogDebug, "NTCP2: session terminated"); LogPrint (eLogDebug, "NTCP2: Session terminated");
} }
} }
@ -453,7 +453,7 @@ namespace transport
(void) bytes_transferred; (void) bytes_transferred;
if (ecode) if (ecode)
{ {
LogPrint (eLogWarning, "NTCP2: couldn't send SessionRequest message: ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Couldn't send SessionRequest message: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
@ -583,7 +583,7 @@ namespace transport
(void) bytes_transferred; (void) bytes_transferred;
if (ecode) if (ecode)
{ {
LogPrint (eLogWarning, "NTCP2: couldn't send SessionConfirmed message: ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Couldn't send SessionConfirmed message: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
@ -610,7 +610,7 @@ namespace transport
(void) bytes_transferred; (void) bytes_transferred;
if (ecode) if (ecode)
{ {
LogPrint (eLogWarning, "NTCP2: couldn't send SessionCreated message: ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Couldn't send SessionCreated message: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
@ -653,7 +653,7 @@ namespace transport
// process RI // process RI
if (buf[0] != eNTCP2BlkRouterInfo) if (buf[0] != eNTCP2BlkRouterInfo)
{ {
LogPrint (eLogWarning, "NTCP2: unexpected block ", (int)buf[0], " in SessionConfirmed"); LogPrint (eLogWarning, "NTCP2: Unexpected block ", (int)buf[0], " in SessionConfirmed");
Terminate (); Terminate ();
return; return;
} }
@ -759,7 +759,7 @@ namespace transport
if (ecode) if (ecode)
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
LogPrint (eLogWarning, "NTCP2: receive length read error: ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Receive length read error: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
@ -774,7 +774,7 @@ namespace transport
#endif #endif
// m_NextReceivedLen comes from the network in BigEndian // m_NextReceivedLen comes from the network in BigEndian
m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key); m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key);
LogPrint (eLogDebug, "NTCP2: received length ", m_NextReceivedLen); LogPrint (eLogDebug, "NTCP2: Received length ", m_NextReceivedLen);
if (m_NextReceivedLen >= 16) if (m_NextReceivedLen >= 16)
{ {
CreateNextReceivedBuffer (m_NextReceivedLen); CreateNextReceivedBuffer (m_NextReceivedLen);
@ -791,7 +791,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogError, "NTCP2: received length ", m_NextReceivedLen, " is too short"); LogPrint (eLogError, "NTCP2: Received length ", m_NextReceivedLen, " is too short");
Terminate (); Terminate ();
} }
} }
@ -814,7 +814,7 @@ namespace transport
if (ecode) if (ecode)
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
LogPrint (eLogWarning, "NTCP2: receive read error: ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Receive read error: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
@ -826,7 +826,7 @@ namespace transport
CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++; CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++;
if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false)) if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false))
{ {
LogPrint (eLogDebug, "NTCP2: received message decrypted"); LogPrint (eLogDebug, "NTCP2: Received message decrypted");
ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16); ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16);
m_IsReceiving = false; m_IsReceiving = false;
ReceiveLength (); ReceiveLength ();
@ -857,10 +857,10 @@ namespace transport
switch (blk) switch (blk)
{ {
case eNTCP2BlkDateTime: case eNTCP2BlkDateTime:
LogPrint (eLogDebug, "NTCP2: datetime"); LogPrint (eLogDebug, "NTCP2: Datetime");
break; break;
case eNTCP2BlkOptions: case eNTCP2BlkOptions:
LogPrint (eLogDebug, "NTCP2: options"); LogPrint (eLogDebug, "NTCP2: Options");
break; break;
case eNTCP2BlkRouterInfo: case eNTCP2BlkRouterInfo:
{ {
@ -891,14 +891,14 @@ namespace transport
case eNTCP2BlkTermination: case eNTCP2BlkTermination:
if (size >= 9) if (size >= 9)
{ {
LogPrint (eLogDebug, "NTCP2: termination. reason=", (int)(frame[offset + 8])); LogPrint (eLogDebug, "NTCP2: Rermination. reason=", (int)(frame[offset + 8]));
Terminate (); Terminate ();
} }
else else
LogPrint (eLogWarning, "NTCP2: Unexpected termination block size ", size); LogPrint (eLogWarning, "NTCP2: Unexpected termination block size ", size);
break; break;
case eNTCP2BlkPadding: case eNTCP2BlkPadding:
LogPrint (eLogDebug, "NTCP2: padding"); LogPrint (eLogDebug, "NTCP2: Padding");
break; break;
default: default:
LogPrint (eLogWarning, "NTCP2: Unknown block type ", (int)blk); LogPrint (eLogWarning, "NTCP2: Unknown block type ", (int)blk);
@ -920,7 +920,7 @@ namespace transport
#endif #endif
// length must be in BigEndian // length must be in BigEndian
htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key)); htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key));
LogPrint (eLogDebug, "NTCP2: sent length ", frameLen); LogPrint (eLogDebug, "NTCP2: Sent length ", frameLen);
} }
void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs) void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs)
@ -1154,7 +1154,7 @@ namespace transport
SendQueue (); SendQueue ();
else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE) else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE)
{ {
LogPrint (eLogWarning, "NTCP2: outgoing messages queue size to ", LogPrint (eLogWarning, "NTCP2: Outgoing messages queue size to ",
GetIdentHashBase64(), " exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE); GetIdentHashBase64(), " exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE);
Terminate (); Terminate ();
} }
@ -1260,7 +1260,7 @@ namespace transport
} }
catch ( std::exception & ex ) catch ( std::exception & ex )
{ {
LogPrint(eLogError, "NTCP2: failed to bind to v6 port ", address->port, ": ", ex.what()); LogPrint(eLogError, "NTCP2: Failed to bind to v6 port ", address->port, ": ", ex.what());
ThrowFatal ("Unable to start IPv6 NTCP2 transport at port ", address->port, ": ", ex.what ()); ThrowFatal ("Unable to start IPv6 NTCP2 transport at port ", address->port, ": ", ex.what ());
continue; continue;
} }
@ -1301,7 +1301,7 @@ namespace transport
auto it = m_NTCP2Sessions.find (ident); auto it = m_NTCP2Sessions.find (ident);
if (it != m_NTCP2Sessions.end ()) if (it != m_NTCP2Sessions.end ())
{ {
LogPrint (eLogWarning, "NTCP2: session to ", ident.ToBase64 (), " already exists"); LogPrint (eLogWarning, "NTCP2: Session to ", ident.ToBase64 (), " already exists");
if (incoming) if (incoming)
// replace by new session // replace by new session
it->second->Terminate (); it->second->Terminate ();
@ -1370,7 +1370,7 @@ namespace transport
boost::system::error_code ec; boost::system::error_code ec;
conn->GetSocket ().bind (*localAddress, ec); conn->GetSocket ().bind (*localAddress, ec);
if (ec) if (ec)
LogPrint (eLogError, "NTCP2: can't bind to ", localAddress->address ().to_string (), ": ", ec.message ()); LogPrint (eLogError, "NTCP2: Can't bind to ", localAddress->address ().to_string (), ": ", ec.message ());
} }
conn->GetSocket ().async_connect (conn->GetRemoteEndpoint (), std::bind (&NTCP2Server::HandleConnect, this, std::placeholders::_1, conn, timer)); conn->GetSocket ().async_connect (conn->GetRemoteEndpoint (), std::bind (&NTCP2Server::HandleConnect, this, std::placeholders::_1, conn, timer));
} }
@ -1539,7 +1539,7 @@ namespace transport
{ {
if (ecode) if (ecode)
{ {
LogPrint(eLogWarning, "NTCP2: failed to connect to proxy ", ecode.message()); LogPrint(eLogWarning, "NTCP2: Failed to connect to proxy ", ecode.message());
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
return; return;
@ -1556,7 +1556,7 @@ namespace transport
(void) transferred; (void) transferred;
if(ec) if(ec)
{ {
LogPrint(eLogWarning, "NTCP2: socks5 write error ", ec.message()); LogPrint(eLogWarning, "NTCP2: SOCKS5 write error ", ec.message());
} }
}); });
auto readbuff = std::make_shared<std::vector<uint8_t> >(2); auto readbuff = std::make_shared<std::vector<uint8_t> >(2);
@ -1565,7 +1565,7 @@ namespace transport
{ {
if(ec) if(ec)
{ {
LogPrint(eLogError, "NTCP2: socks5 read error ", ec.message()); LogPrint(eLogError, "NTCP2: SOCKS5 read error ", ec.message());
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
return; return;
@ -1579,14 +1579,14 @@ namespace transport
} }
else if ((*readbuff)[1] == 0xff) else if ((*readbuff)[1] == 0xff)
{ {
LogPrint(eLogError, "NTCP2: socks5 proxy rejected authentication"); LogPrint(eLogError, "NTCP2: SOCKS5 proxy rejected authentication");
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
return; return;
} }
LogPrint(eLogError, "NTCP2:", (int)(*readbuff)[1]); LogPrint(eLogError, "NTCP2:", (int)(*readbuff)[1]);
} }
LogPrint(eLogError, "NTCP2: socks5 server gave invalid response"); LogPrint(eLogError, "NTCP2: SOCKS5 server gave invalid response");
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
}); });
@ -1614,7 +1614,7 @@ namespace transport
{ {
(void) transferred; (void) transferred;
if(ec) if(ec)
LogPrint(eLogError, "NTCP2: http proxy write error ", ec.message()); LogPrint(eLogError, "NTCP2: HTTP proxy write error ", ec.message());
}); });
boost::asio::streambuf * readbuff = new boost::asio::streambuf; boost::asio::streambuf * readbuff = new boost::asio::streambuf;
@ -1623,7 +1623,7 @@ namespace transport
{ {
if(ec) if(ec)
{ {
LogPrint(eLogError, "NTCP2: http proxy read error ", ec.message()); LogPrint(eLogError, "NTCP2: HTTP proxy read error ", ec.message());
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
} }
@ -1641,10 +1641,10 @@ namespace transport
return; return;
} }
else else
LogPrint(eLogError, "NTCP2: http proxy rejected request ", res.code); LogPrint(eLogError, "NTCP2: HTTP proxy rejected request ", res.code);
} }
else else
LogPrint(eLogError, "NTCP2: http proxy gave malformed response"); LogPrint(eLogError, "NTCP2: HTTP proxy gave malformed response");
timer->cancel(); timer->cancel();
conn->Terminate(); conn->Terminate();
delete readbuff; delete readbuff;
@ -1653,7 +1653,7 @@ namespace transport
break; break;
} }
default: default:
LogPrint(eLogError, "NTCP2: unknown proxy type, invalid state"); LogPrint(eLogError, "NTCP2: Unknown proxy type, invalid state");
} }
} }
@ -1694,7 +1694,7 @@ namespace transport
{ {
if(ec) if(ec)
{ {
LogPrint(eLogError, "NTCP2: failed to write handshake to socks proxy ", ec.message()); LogPrint(eLogError, "NTCP2: Failed to write handshake to socks proxy ", ec.message());
return; return;
} }
}); });
@ -1704,7 +1704,7 @@ namespace transport
{ {
if(e) if(e)
{ {
LogPrint(eLogError, "NTCP2: socks proxy read error ", e.message()); LogPrint(eLogError, "NTCP2: SOCKS proxy read error ", e.message());
} }
else if(transferred == sz) else if(transferred == sz)
{ {

62
libi2pd/NetDb.cpp

@ -118,7 +118,7 @@ namespace data
int numMsgs = 0; int numMsgs = 0;
while (msg) while (msg)
{ {
LogPrint(eLogDebug, "NetDb: got request with type ", (int) msg->GetTypeID ()); LogPrint(eLogDebug, "NetDb: Got request with type ", (int) msg->GetTypeID ());
switch (msg->GetTypeID ()) switch (msg->GetTypeID ())
{ {
case eI2NPDatabaseStore: case eI2NPDatabaseStore:
@ -138,7 +138,7 @@ namespace data
HandleNTCP2RouterInfoMsg (msg); HandleNTCP2RouterInfoMsg (msg);
break; break;
default: // WTF? default: // WTF?
LogPrint (eLogError, "NetDb: unexpected message type ", (int) msg->GetTypeID ()); LogPrint (eLogError, "NetDb: Unexpected message type ", (int) msg->GetTypeID ());
//i2p::HandleI2NPMessage (msg); //i2p::HandleI2NPMessage (msg);
} }
if (numMsgs > 100) break; if (numMsgs > 100) break;
@ -216,7 +216,7 @@ namespace data
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "NetDb: runtime exception: ", ex.what ()); LogPrint (eLogError, "NetDb: Runtime exception: ", ex.what ());
} }
} }
} }
@ -343,7 +343,7 @@ namespace data
updated = true; updated = true;
} }
else else
LogPrint (eLogError, "NetDb: new LeaseSet validation failed: ", ident.ToBase32()); LogPrint (eLogError, "NetDb: New LeaseSet validation failed: ", ident.ToBase32());
} }
return updated; return updated;
} }
@ -373,7 +373,7 @@ namespace data
} }
} }
else else
LogPrint (eLogError, "NetDb: new LeaseSet2 validation failed: ", ident.ToBase32()); LogPrint (eLogError, "NetDb: New LeaseSet2 validation failed: ", ident.ToBase32());
return false; return false;
} }
@ -430,7 +430,7 @@ namespace data
int riLen = ri->GetBufferLen(); int riLen = ri->GetBufferLen();
if(!i2p::data::netdb.AddRouterInfo(riData, riLen)) { if(!i2p::data::netdb.AddRouterInfo(riData, riLen)) {
// bad router info // bad router info
LogPrint(eLogError, "NetDb: bad router info"); LogPrint(eLogError, "NetDb: Bad router info");
return; return;
} }
m_FloodfillBootstrap = ri; m_FloodfillBootstrap = ri;
@ -445,7 +445,7 @@ namespace data
void NetDb::ReseedFromFloodfill(const RouterInfo & ri, int numRouters, int numFloodfills) void NetDb::ReseedFromFloodfill(const RouterInfo & ri, int numRouters, int numFloodfills)
{ {
LogPrint(eLogInfo, "NetDB: reseeding from floodfill ", ri.GetIdentHashBase64()); LogPrint(eLogInfo, "NetDB: Reseeding from floodfill ", ri.GetIdentHashBase64());
std::vector<std::shared_ptr<i2p::I2NPMessage> > requests; std::vector<std::shared_ptr<i2p::I2NPMessage> > requests;
i2p::data::IdentHash ourIdent = i2p::context.GetIdentHash(); i2p::data::IdentHash ourIdent = i2p::context.GetIdentHash();
@ -631,10 +631,10 @@ namespace data
} // m_RouterInfos iteration } // m_RouterInfos iteration
if (updatedCount > 0) if (updatedCount > 0)
LogPrint (eLogInfo, "NetDb: saved ", updatedCount, " new/updated routers"); LogPrint (eLogInfo, "NetDb: Saved ", updatedCount, " new/updated routers");
if (deletedCount > 0) if (deletedCount > 0)
{ {
LogPrint (eLogInfo, "NetDb: deleting ", deletedCount, " unreachable routers"); LogPrint (eLogInfo, "NetDb: Deleting ", deletedCount, " unreachable routers");
// clean up RouterInfos table // clean up RouterInfos table
{ {
std::unique_lock<std::mutex> l(m_RouterInfosMutex); std::unique_lock<std::mutex> l(m_RouterInfosMutex);
@ -666,7 +666,7 @@ namespace data
auto dest = m_Requests.CreateRequest (destination, false, requestComplete); // non-exploratory auto dest = m_Requests.CreateRequest (destination, false, requestComplete); // non-exploratory
if (!dest) if (!dest)
{ {
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already"); LogPrint (eLogWarning, "NetDb: Destination ", destination.ToBase64(), " is requested already");
return; return;
} }
@ -705,10 +705,10 @@ namespace data
auto dest = m_Requests.CreateRequest (destination, exploritory, requestComplete); // non-exploratory auto dest = m_Requests.CreateRequest (destination, exploritory, requestComplete); // non-exploratory
if (!dest) if (!dest)
{ {
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already"); LogPrint (eLogWarning, "NetDb: Destination ", destination.ToBase64(), " is requested already");
return; return;
} }
LogPrint(eLogInfo, "NetDb: destination ", destination.ToBase64(), " being requested directly from ", from.ToBase64()); LogPrint(eLogInfo, "NetDb: Destination ", destination.ToBase64(), " being requested directly from ", from.ToBase64());
// direct // direct
transports.SendMessage (from, dest->CreateRequestMessage (nullptr, nullptr)); transports.SendMessage (from, dest->CreateRequestMessage (nullptr, nullptr));
} }
@ -732,7 +732,7 @@ namespace data
IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET); IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET);
if (ident.IsZero ()) if (ident.IsZero ())
{ {
LogPrint (eLogDebug, "NetDb: database store with zero ident, dropped"); LogPrint (eLogDebug, "NetDb: Database store with zero ident, dropped");
return; return;
} }
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET); uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
@ -751,14 +751,14 @@ namespace data
if (outbound) if (outbound)
outbound->SendTunnelDataMsg (buf + offset, tunnelID, deliveryStatus); outbound->SendTunnelDataMsg (buf + offset, tunnelID, deliveryStatus);
else else
LogPrint (eLogWarning, "NetDb: no outbound tunnels for DatabaseStore reply found"); LogPrint (eLogWarning, "NetDb: No outbound tunnels for DatabaseStore reply found");
} }
offset += 32; offset += 32;
} }
// we must send reply back before this check // we must send reply back before this check
if (ident == i2p::context.GetIdentHash ()) if (ident == i2p::context.GetIdentHash ())
{ {
LogPrint (eLogDebug, "NetDb: database store with own RouterInfo received, dropped"); LogPrint (eLogDebug, "NetDb: Database store with own RouterInfo received, dropped");
return; return;
} }
size_t payloadOffset = offset; size_t payloadOffset = offset;
@ -771,24 +771,24 @@ namespace data
{ {
if (storeType == NETDB_STORE_TYPE_LEASESET) // 1 if (storeType == NETDB_STORE_TYPE_LEASESET) // 1
{ {
LogPrint (eLogDebug, "NetDb: store request: LeaseSet for ", ident.ToBase32()); LogPrint (eLogDebug, "NetDb: Store request: LeaseSet for ", ident.ToBase32());
updated = AddLeaseSet (ident, buf + offset, len - offset); updated = AddLeaseSet (ident, buf + offset, len - offset);
} }
else // all others are considered as LeaseSet2 else // all others are considered as LeaseSet2
{ {
LogPrint (eLogDebug, "NetDb: store request: LeaseSet2 of type ", storeType, " for ", ident.ToBase32()); LogPrint (eLogDebug, "NetDb: Store request: LeaseSet2 of type ", storeType, " for ", ident.ToBase32());
updated = AddLeaseSet2 (ident, buf + offset, len - offset, storeType); updated = AddLeaseSet2 (ident, buf + offset, len - offset, storeType);
} }
} }
} }
else // RouterInfo else // RouterInfo
{ {
LogPrint (eLogDebug, "NetDb: store request: RouterInfo"); LogPrint (eLogDebug, "NetDb: Store request: RouterInfo");
size_t size = bufbe16toh (buf + offset); size_t size = bufbe16toh (buf + offset);
offset += 2; offset += 2;
if (size > MAX_RI_BUFFER_SIZE || size > len - offset) if (size > MAX_RI_BUFFER_SIZE || size > len - offset)
{ {
LogPrint (eLogError, "NetDb: invalid RouterInfo length ", (int)size); LogPrint (eLogError, "NetDb: Invalid RouterInfo length ", (int)size);
return; return;
} }
uint8_t uncompressed[MAX_RI_BUFFER_SIZE]; uint8_t uncompressed[MAX_RI_BUFFER_SIZE];
@ -797,7 +797,7 @@ namespace data
updated = AddRouterInfo (ident, uncompressed, uncompressedSize); updated = AddRouterInfo (ident, uncompressed, uncompressedSize);
else else
{ {
LogPrint (eLogInfo, "NetDb: decompression failed ", uncompressedSize); LogPrint (eLogInfo, "NetDb: Decompression failed ", uncompressedSize);
return; return;
} }
} }
@ -872,7 +872,7 @@ namespace data
m_Requests.RequestComplete (ident, nullptr); m_Requests.RequestComplete (ident, nullptr);
} }
else if(!m_FloodfillBootstrap) else if(!m_FloodfillBootstrap)
LogPrint (eLogWarning, "NetDb: requested destination for ", key, " not found"); LogPrint (eLogWarning, "NetDb: Requested destination for ", key, " not found");
// try responses // try responses
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++)
@ -887,7 +887,7 @@ namespace data
if (!r || i2p::util::GetMillisecondsSinceEpoch () > r->GetTimestamp () + 3600*1000LL) if (!r || i2p::util::GetMillisecondsSinceEpoch () > r->GetTimestamp () + 3600*1000LL)
{ {
// router with ident not found or too old (1 hour) // router with ident not found or too old (1 hour)
LogPrint (eLogDebug, "NetDb: found new/outdated router. Requesting RouterInfo ..."); LogPrint (eLogDebug, "NetDb: Found new/outdated router. Requesting RouterInfo...");
if(m_FloodfillBootstrap) if(m_FloodfillBootstrap)
RequestDestinationFrom(router, m_FloodfillBootstrap->GetIdentHash(), true); RequestDestinationFrom(router, m_FloodfillBootstrap->GetIdentHash(), true);
else else
@ -928,14 +928,14 @@ namespace data
excluded += 2; excluded += 2;
if (numExcluded > 512) if (numExcluded > 512)
{ {
LogPrint (eLogWarning, "NetDb: number of excluded peers", numExcluded, " exceeds 512"); LogPrint (eLogWarning, "NetDb: Number of excluded peers", numExcluded, " exceeds 512");
return; return;
} }
std::shared_ptr<I2NPMessage> replyMsg; std::shared_ptr<I2NPMessage> replyMsg;
if (lookupType == DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP) if (lookupType == DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP)
{ {
LogPrint (eLogInfo, "NetDb: exploratory close to ", key, " ", numExcluded, " excluded"); LogPrint (eLogInfo, "NetDb: Exploratory close to ", key, " ", numExcluded, " excluded");
std::set<IdentHash> excludedRouters; std::set<IdentHash> excludedRouters;
for (int i = 0; i < numExcluded; i++) for (int i = 0; i < numExcluded; i++)
{ {
@ -962,7 +962,7 @@ namespace data
auto router = FindRouter (ident); auto router = FindRouter (ident);
if (router) if (router)
{ {
LogPrint (eLogDebug, "NetDb: requested RouterInfo ", key, " found"); LogPrint (eLogDebug, "NetDb: Requested RouterInfo ", key, " found");
if (!router->GetBuffer ()) if (!router->GetBuffer ())
router->LoadBuffer (m_Storage.Path (router->GetIdentHashBase64 ())); router->LoadBuffer (m_Storage.Path (router->GetIdentHashBase64 ()));
if (router->GetBuffer ()) if (router->GetBuffer ())
@ -977,11 +977,11 @@ namespace data
if (!leaseSet) if (!leaseSet)
{ {
// no lease set found // no lease set found
LogPrint(eLogDebug, "NetDb: requested LeaseSet not found for ", ident.ToBase32()); LogPrint(eLogDebug, "NetDb: Requested LeaseSet not found for ", ident.ToBase32());
} }
else if (!leaseSet->IsExpired ()) // we don't send back our LeaseSets else if (!leaseSet->IsExpired ()) // we don't send back our LeaseSets
{ {
LogPrint (eLogDebug, "NetDb: requested LeaseSet ", key, " found"); LogPrint (eLogDebug, "NetDb: Requested LeaseSet ", key, " found");
replyMsg = CreateDatabaseStoreMsg (ident, leaseSet); replyMsg = CreateDatabaseStoreMsg (ident, leaseSet);
} }
} }
@ -1026,10 +1026,10 @@ namespace data
replyMsg = garlic.WrapSingleMessage (replyMsg); replyMsg = garlic.WrapSingleMessage (replyMsg);
} }
if (!replyMsg) if (!replyMsg)
LogPrint (eLogError, "NetDb: failed to wrap message"); LogPrint (eLogError, "NetDb: Failed to wrap message");
} }
else else
LogPrint(eLogWarning, "NetDb: encrypted reply requested but no tags provided"); LogPrint(eLogWarning, "NetDb: Encrypted reply requested but no tags provided");
} }
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool (); auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr; auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr;
@ -1063,14 +1063,14 @@ namespace data
uint8_t randomHash[32]; uint8_t randomHash[32];
std::vector<i2p::tunnel::TunnelMessageBlock> msgs; std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
LogPrint (eLogInfo, "NetDb: exploring new ", numDestinations, " routers ..."); LogPrint (eLogInfo, "NetDb: Exploring new ", numDestinations, " routers ...");
for (int i = 0; i < numDestinations; i++) for (int i = 0; i < numDestinations; i++)
{ {
RAND_bytes (randomHash, 32); RAND_bytes (randomHash, 32);
auto dest = m_Requests.CreateRequest (randomHash, true); // exploratory auto dest = m_Requests.CreateRequest (randomHash, true); // exploratory
if (!dest) if (!dest)
{ {
LogPrint (eLogWarning, "NetDb: exploratory destination is requested already"); LogPrint (eLogWarning, "NetDb: Exploratory destination is requested already");
return; return;
} }
auto floodfill = GetClosestFloodfill (randomHash, dest->GetExcludedPeers ()); auto floodfill = GetClosestFloodfill (randomHash, dest->GetExcludedPeers ());

6
libi2pd/Profiling.cpp

@ -73,7 +73,7 @@ namespace data
if (!i2p::fs::Exists(path)) if (!i2p::fs::Exists(path))
{ {
LogPrint(eLogWarning, "Profiling: no profile yet for ", ident); LogPrint(eLogWarning, "Profiling: No profile yet for ", ident);
return; return;
} }
@ -115,7 +115,7 @@ namespace data
} }
catch (boost::property_tree::ptree_bad_path& ex) catch (boost::property_tree::ptree_bad_path& ex)
{ {
LogPrint (eLogWarning, "Missing section ", PEER_PROFILE_SECTION_USAGE, " in profile for ", ident); LogPrint (eLogWarning, "Profiling: Missing section ", PEER_PROFILE_SECTION_USAGE, " in profile for ", ident);
} }
} }
else else
@ -194,7 +194,7 @@ namespace data
continue; continue;
} }
if (((now - st.st_mtime) / 3600) >= PEER_PROFILE_EXPIRATION_TIMEOUT) { if (((now - st.st_mtime) / 3600) >= PEER_PROFILE_EXPIRATION_TIMEOUT) {
LogPrint(eLogDebug, "Profiling: removing expired peer profile: ", path); LogPrint(eLogDebug, "Profiling: Removing expired peer profile: ", path);
i2p::fs::Remove(path); i2p::fs::Remove(path);
} }
} }

40
libi2pd/Reseed.cpp

@ -60,19 +60,19 @@ namespace data
num = ProcessSU3File (su3FileName.c_str ()); num = ProcessSU3File (su3FileName.c_str ());
} }
if (num == 0) if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from ", su3FileName); LogPrint (eLogWarning, "Reseed: Failed to reseed from ", su3FileName);
} }
else if (zipFileName.length() > 0) // bootstrap from ZIP file else if (zipFileName.length() > 0) // bootstrap from ZIP file
{ {
int num = ProcessZIPFile (zipFileName.c_str ()); int num = ProcessZIPFile (zipFileName.c_str ());
if (num == 0) if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from ", zipFileName); LogPrint (eLogWarning, "Reseed: Failed to reseed from ", zipFileName);
} }
else // bootstrap from reseed servers else // bootstrap from reseed servers
{ {
int num = ReseedFromServers (); int num = ReseedFromServers ();
if (num == 0) if (num == 0)
LogPrint (eLogWarning, "Reseed: failed to reseed from servers"); LogPrint (eLogWarning, "Reseed: Failed to reseed from servers");
} }
} }
@ -96,7 +96,7 @@ namespace data
std::vector<std::string> yggReseedHostList; std::vector<std::string> yggReseedHostList;
if (!i2p::util::net::GetYggdrasilAddress ().is_unspecified ()) if (!i2p::util::net::GetYggdrasilAddress ().is_unspecified ())
{ {
LogPrint (eLogInfo, "Reseed: yggdrasil is supported"); LogPrint (eLogInfo, "Reseed: Yggdrasil is supported");
std::string yggReseedURLs; i2p::config::GetOption("reseed.yggurls", yggReseedURLs); std::string yggReseedURLs; i2p::config::GetOption("reseed.yggurls", yggReseedURLs);
if (!yggReseedURLs.empty ()) if (!yggReseedURLs.empty ())
boost::split(yggReseedHostList, yggReseedURLs, boost::is_any_of(","), boost::token_compress_on); boost::split(yggReseedHostList, yggReseedURLs, boost::is_any_of(","), boost::token_compress_on);
@ -120,7 +120,7 @@ namespace data
if (num > 0) return num; // success if (num > 0) return num; // success
reseedRetries++; reseedRetries++;
} }
LogPrint (eLogWarning, "Reseed: failed to reseed from servers after 10 attempts"); LogPrint (eLogWarning, "Reseed: Failed to reseed from servers after 10 attempts");
return 0; return 0;
} }
@ -414,13 +414,13 @@ namespace data
{ {
if (r && ts > r->GetTimestamp () + 10*i2p::data::NETDB_MAX_EXPIRATION_TIMEOUT*1000LL) // 270 hours if (r && ts > r->GetTimestamp () + 10*i2p::data::NETDB_MAX_EXPIRATION_TIMEOUT*1000LL) // 270 hours
{ {
LogPrint (eLogError, "Reseed: router ", r->GetIdentHash().ToBase64 (), " is outdated by ", (ts - r->GetTimestamp ())/1000LL/3600LL, " hours"); LogPrint (eLogError, "Reseed: Router ", r->GetIdentHash().ToBase64 (), " is outdated by ", (ts - r->GetTimestamp ())/1000LL/3600LL, " hours");
numOutdated++; numOutdated++;
} }
}); });
if (numOutdated > numFiles/2) // more than half if (numOutdated > numFiles/2) // more than half
{ {
LogPrint (eLogError, "Reseed: mammoth's shit\n" LogPrint (eLogError, "Reseed: Mammoth's shit\n"
" *_____*\n" " *_____*\n"
" *_*****_*\n" " *_*****_*\n"
" *_(O)_(O)_*\n" " *_(O)_(O)_*\n"
@ -509,7 +509,7 @@ namespace data
for (const std::string & file : files) { for (const std::string & file : files) {
if (file.compare(file.size() - 4, 4, ".crt") != 0) { if (file.compare(file.size() - 4, 4, ".crt") != 0) {
LogPrint(eLogWarning, "Reseed: ignoring file ", file); LogPrint(eLogWarning, "Reseed: Ignoring file ", file);
continue; continue;
} }
LoadCertificate (file); LoadCertificate (file);
@ -533,17 +533,17 @@ namespace data
} }
// check for valid proxy url schema // check for valid proxy url schema
if (proxyUrl.schema != "http" && proxyUrl.schema != "socks") { if (proxyUrl.schema != "http" && proxyUrl.schema != "socks") {
LogPrint(eLogError, "Reseed: bad proxy url: ", proxy); LogPrint(eLogError, "Reseed: Bad proxy url: ", proxy);
return ""; return "";
} }
} else { } else {
LogPrint(eLogError, "Reseed: bad proxy url: ", proxy); LogPrint(eLogError, "Reseed: Bad proxy url: ", proxy);
return ""; return "";
} }
} }
i2p::http::URL url; i2p::http::URL url;
if (!url.parse(address)) { if (!url.parse(address)) {
LogPrint(eLogError, "Reseed: failed to parse url: ", address); LogPrint(eLogError, "Reseed: Failed to parse url: ", address);
return ""; return "";
} }
url.schema = "https"; url.schema = "https";
@ -743,22 +743,22 @@ namespace data
i2p::http::HTTPRes res; i2p::http::HTTPRes res;
int len = res.parse(data); int len = res.parse(data);
if (len <= 0) { if (len <= 0) {
LogPrint(eLogWarning, "Reseed: incomplete/broken response from ", uri); LogPrint(eLogWarning, "Reseed: Incomplete/broken response from ", uri);
return ""; return "";
} }
if (res.code != 200) { if (res.code != 200) {
LogPrint(eLogError, "Reseed: failed to reseed from ", uri, ", http code ", res.code); LogPrint(eLogError, "Reseed: Failed to reseed from ", uri, ", http code ", res.code);
return ""; return "";
} }
data.erase(0, len); /* drop http headers from response */ data.erase(0, len); /* drop http headers from response */
LogPrint(eLogDebug, "Reseed: got ", data.length(), " bytes of data from ", uri); LogPrint(eLogDebug, "Reseed: Got ", data.length(), " bytes of data from ", uri);
if (res.is_chunked()) { if (res.is_chunked()) {
std::stringstream in(data), out; std::stringstream in(data), out;
if (!i2p::http::MergeChunkedResponse(in, out)) { if (!i2p::http::MergeChunkedResponse(in, out)) {
LogPrint(eLogWarning, "Reseed: failed to merge chunked response from ", uri); LogPrint(eLogWarning, "Reseed: Failed to merge chunked response from ", uri);
return ""; return "";
} }
LogPrint(eLogDebug, "Reseed: got ", data.length(), "(", out.tellg(), ") bytes of data from ", uri); LogPrint(eLogDebug, "Reseed: Got ", data.length(), "(", out.tellg(), ") bytes of data from ", uri);
data = out.str(); data = out.str();
} }
return data; return data;
@ -769,7 +769,7 @@ namespace data
i2p::http::URL url; i2p::http::URL url;
if (!url.parse(address)) if (!url.parse(address))
{ {
LogPrint(eLogError, "Reseed: failed to parse url: ", address); LogPrint(eLogError, "Reseed: Failed to parse url: ", address);
return ""; return "";
} }
url.schema = "http"; url.schema = "http";
@ -781,15 +781,15 @@ namespace data
if (url.host.length () < 2) return ""; // assume [] if (url.host.length () < 2) return ""; // assume []
auto host = url.host.substr (1, url.host.length () - 2); auto host = url.host.substr (1, url.host.length () - 2);
LogPrint (eLogDebug, "Reseed: Connecting to yggdrasil ", url.host, ":", url.port); LogPrint (eLogDebug, "Reseed: Connecting to Yggdrasil ", url.host, ":", url.port);
s.connect (boost::asio::ip::tcp::endpoint (boost::asio::ip::address_v6::from_string (host), url.port), ecode); s.connect (boost::asio::ip::tcp::endpoint (boost::asio::ip::address_v6::from_string (host), url.port), ecode);
if (!ecode) if (!ecode)
{ {
LogPrint (eLogDebug, "Reseed: Connected to yggdrasil ", url.host, ":", url.port); LogPrint (eLogDebug, "Reseed: Connected to Yggdrasil ", url.host, ":", url.port);
return ReseedRequest (s, url.to_string()); return ReseedRequest (s, url.to_string());
} }
else else
LogPrint (eLogError, "Reseed: Couldn't connect to yggdrasil ", url.host, ": ", ecode.message ()); LogPrint (eLogError, "Reseed: Couldn't connect to Yggdrasil ", url.host, ": ", ecode.message ());
return ""; return "";
} }

12
libi2pd/RouterInfo.cpp

@ -102,7 +102,7 @@ namespace data
} }
else else
{ {
LogPrint (eLogError, "RouterInfo: signature verification failed"); LogPrint (eLogError, "RouterInfo: Signature verification failed");
m_IsUnreachable = true; m_IsUnreachable = true;
} }
} }
@ -151,7 +151,7 @@ namespace data
size_t identityLen = m_RouterIdentity->GetFullLen (); size_t identityLen = m_RouterIdentity->GetFullLen ();
if (identityLen >= m_BufferLen) if (identityLen >= m_BufferLen)
{ {
LogPrint (eLogError, "RouterInfo: identity length ", identityLen, " exceeds buffer size ", m_BufferLen); LogPrint (eLogError, "RouterInfo: Identity length ", identityLen, " exceeds buffer size ", m_BufferLen);
m_IsUnreachable = true; m_IsUnreachable = true;
return; return;
} }
@ -168,7 +168,7 @@ namespace data
int l = m_BufferLen - m_RouterIdentity->GetSignatureLen (); int l = m_BufferLen - m_RouterIdentity->GetSignatureLen ();
if (l < 0 || !m_RouterIdentity->Verify ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l)) if (l < 0 || !m_RouterIdentity->Verify ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l))
{ {
LogPrint (eLogError, "RouterInfo: signature verification failed"); LogPrint (eLogError, "RouterInfo: Signature verification failed");
m_IsUnreachable = true; m_IsUnreachable = true;
return; return;
} }
@ -180,7 +180,7 @@ namespace data
ReadFromStream (str); ReadFromStream (str);
if (!str) if (!str)
{ {
LogPrint (eLogError, "RouterInfo: malformed message"); LogPrint (eLogError, "RouterInfo: Malformed message");
m_IsUnreachable = true; m_IsUnreachable = true;
} }
} }
@ -431,7 +431,7 @@ namespace data
{ {
if (!netdb.GetFamilies ().VerifyFamily (m_Family, GetIdentHash (), value)) if (!netdb.GetFamilies ().VerifyFamily (m_Family, GetIdentHash (), value))
{ {
LogPrint (eLogWarning, "RouterInfo: family signature verification failed"); LogPrint (eLogWarning, "RouterInfo: Family signature verification failed");
m_Family.clear (); m_Family.clear ();
} }
} }
@ -815,7 +815,7 @@ namespace data
} }
else else
{ {
LogPrint (eLogWarning, "RouterInfo: string length ", (int)l, " exceeds buffer size ", len); LogPrint (eLogWarning, "RouterInfo: String length ", (int)l, " exceeds buffer size ", len);
s.seekg (l, std::ios::cur); // skip s.seekg (l, std::ios::cur); // skip
str[0] = 0; str[0] = 0;
} }

26
libi2pd/SSU.cpp

@ -53,7 +53,7 @@ namespace transport
} }
catch ( std::exception & ex ) catch ( std::exception & ex )
{ {
LogPrint (eLogError, "SSU: failed to bind to v4 port ", m_Endpoint.port(), ": ", ex.what()); LogPrint (eLogError, "SSU: Failed to bind to v4 port ", m_Endpoint.port(), ": ", ex.what());
ThrowFatal ("Unable to start IPv4 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ()); ThrowFatal ("Unable to start IPv4 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ());
} }
} }
@ -83,7 +83,7 @@ namespace transport
} }
catch ( std::exception & ex ) catch ( std::exception & ex )
{ {
LogPrint (eLogError, "SSU: failed to bind to v6 port ", m_EndpointV6.port(), ": ", ex.what()); LogPrint (eLogError, "SSU: Failed to bind to v6 port ", m_EndpointV6.port(), ": ", ex.what());
ThrowFatal ("Unable to start IPv6 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ()); ThrowFatal ("Unable to start IPv6 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ());
} }
} }
@ -156,7 +156,7 @@ namespace transport
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "SSU: server runtime exception: ", ex.what ()); LogPrint (eLogError, "SSU: Server runtime exception: ", ex.what ());
} }
} }
} }
@ -173,7 +173,7 @@ namespace transport
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "SSU: receivers runtime exception: ", ex.what ()); LogPrint (eLogError, "SSU: Receivers runtime exception: ", ex.what ());
if (m_IsRunning) if (m_IsRunning)
{ {
// restart socket // restart socket
@ -249,7 +249,7 @@ namespace transport
if (ec) if (ec)
{ {
LogPrint (eLogError, "SSU: send exception: ", ec.message (), " while trying to send data to ", to.address (), ":", to.port (), " (length: ", len, ")"); LogPrint (eLogError, "SSU: Send exception: ", ec.message (), " while trying to send data to ", to.address (), ":", to.port (), " (length: ", len, ")");
} }
} }
@ -318,7 +318,7 @@ namespace transport
m_PacketsPool.ReleaseMt (packet); m_PacketsPool.ReleaseMt (packet);
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
{ {
LogPrint (eLogError, "SSU: receive error: code ", ecode.value(), ": ", ecode.message ()); LogPrint (eLogError, "SSU: Receive error: code ", ecode.value(), ": ", ecode.message ());
m_Socket.close (); m_Socket.close ();
OpenSocket (); OpenSocket ();
Receive (); Receive ();
@ -409,7 +409,7 @@ namespace transport
session = std::make_shared<SSUSession> (*this, packet->from); session = std::make_shared<SSUSession> (*this, packet->from);
session->WaitForConnect (); session->WaitForConnect ();
(*sessions)[packet->from] = session; (*sessions)[packet->from] = session;
LogPrint (eLogDebug, "SSU: new session from ", packet->from.address ().to_string (), ":", packet->from.port (), " created"); LogPrint (eLogDebug, "SSU: New session from ", packet->from.address ().to_string (), ":", packet->from.port (), " created");
} }
} }
if (session) if (session)
@ -797,7 +797,7 @@ namespace transport
if (sessions.empty () && !introducers.empty ()) if (sessions.empty () && !introducers.empty ())
{ {
// bump creation time for previous introducers if no new sessions found // bump creation time for previous introducers if no new sessions found
LogPrint (eLogDebug, "SSU: no new introducers found. Trying to reuse existing"); LogPrint (eLogDebug, "SSU: No new introducers found. Trying to reuse existing");
for (const auto& it : introducers) for (const auto& it : introducers)
{ {
auto session = FindSession (it); auto session = FindSession (it);
@ -847,7 +847,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogDebug, "SSU: can't find more introducers"); LogPrint (eLogDebug, "SSU: Can't find more introducers");
break; break;
} }
} }
@ -946,10 +946,10 @@ namespace transport
{ {
auto session = it.second; auto session = it.second;
if (it.first != session->GetRemoteEndpoint ()) if (it.first != session->GetRemoteEndpoint ())
LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first, " adjusted"); LogPrint (eLogWarning, "SSU: Remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first, " adjusted");
m_Service.post ([session] m_Service.post ([session]
{ {
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds"); LogPrint (eLogWarning, "SSU: No activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed (); session->Failed ();
}); });
} }
@ -977,10 +977,10 @@ namespace transport
{ {
auto session = it.second; auto session = it.second;
if (it.first != session->GetRemoteEndpoint ()) if (it.first != session->GetRemoteEndpoint ())
LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first); LogPrint (eLogWarning, "SSU: Remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first);
m_Service.post ([session] m_Service.post ([session]
{ {
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds"); LogPrint (eLogWarning, "SSU: No activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed (); session->Failed ();
}); });
} }

74
libi2pd/SSUSession.cpp

@ -79,7 +79,7 @@ namespace transport
nonZero++; nonZero++;
if (nonZero - sharedKey > 32) if (nonZero - sharedKey > 32)
{ {
LogPrint (eLogWarning, "SSU: first 32 bytes of shared key is all zeros. Ignored"); LogPrint (eLogWarning, "SSU: First 32 bytes of shared key is all zeros. Ignored");
return; return;
} }
} }
@ -124,7 +124,7 @@ namespace transport
i2p::context.GetRouterInfo ().GetSSUAddress (true); i2p::context.GetRouterInfo ().GetSSUAddress (true);
if (!address) if (!address)
{ {
LogPrint (eLogInfo, "SSU is not supported"); LogPrint (eLogInfo, "SSU: SSU is not supported");
return; return;
} }
if (Validate (buf, len, address->ssu->key)) if (Validate (buf, len, address->ssu->key))
@ -158,7 +158,7 @@ namespace transport
auto headerSize = GetSSUHeaderSize (buf); auto headerSize = GetSSUHeaderSize (buf);
if (headerSize >= len) if (headerSize >= len)
{ {
LogPrint (eLogError, "SSU header size ", headerSize, " exceeds packet length ", len); LogPrint (eLogError, "SSU: SSU header size ", headerSize, " exceeds packet length ", len);
return; return;
} }
SSUHeader * header = (SSUHeader *)buf; SSUHeader * header = (SSUHeader *)buf;
@ -177,12 +177,12 @@ namespace transport
ProcessSessionConfirmed (buf, len); // buf with header ProcessSessionConfirmed (buf, len); // buf with header
break; break;
case PAYLOAD_TYPE_PEER_TEST: case PAYLOAD_TYPE_PEER_TEST:
LogPrint (eLogDebug, "SSU: peer test received"); LogPrint (eLogDebug, "SSU: Peer test received");
ProcessPeerTest (buf + headerSize, len - headerSize, senderEndpoint); ProcessPeerTest (buf + headerSize, len - headerSize, senderEndpoint);
break; break;
case PAYLOAD_TYPE_SESSION_DESTROYED: case PAYLOAD_TYPE_SESSION_DESTROYED:
{ {
LogPrint (eLogDebug, "SSU: session destroy received"); LogPrint (eLogDebug, "SSU: Session destroy received");
m_Server.DeleteSession (shared_from_this ()); m_Server.DeleteSession (shared_from_this ());
break; break;
} }
@ -192,11 +192,11 @@ namespace transport
m_Server.DeleteSession (shared_from_this ()); m_Server.DeleteSession (shared_from_this ());
break; break;
case PAYLOAD_TYPE_RELAY_REQUEST: case PAYLOAD_TYPE_RELAY_REQUEST:
LogPrint (eLogDebug, "SSU: relay request received"); LogPrint (eLogDebug, "SSU: Relay request received");
ProcessRelayRequest (buf + headerSize, len - headerSize, senderEndpoint); ProcessRelayRequest (buf + headerSize, len - headerSize, senderEndpoint);
break; break;
case PAYLOAD_TYPE_RELAY_INTRO: case PAYLOAD_TYPE_RELAY_INTRO:
LogPrint (eLogDebug, "SSU: relay intro received"); LogPrint (eLogDebug, "SSU: Relay intro received");
ProcessRelayIntro (buf + headerSize, len - headerSize); ProcessRelayIntro (buf + headerSize, len - headerSize);
break; break;
default: default:
@ -206,7 +206,7 @@ namespace transport
void SSUSession::ProcessSessionRequest (const uint8_t * buf, size_t len) void SSUSession::ProcessSessionRequest (const uint8_t * buf, size_t len)
{ {
LogPrint (eLogDebug, "SSU message: session request"); LogPrint (eLogDebug, "SSU message: Session request");
bool sendRelayTag = true; bool sendRelayTag = true;
auto headerSize = sizeof (SSUHeader); auto headerSize = sizeof (SSUHeader);
if (((SSUHeader *)buf)->IsExtendedOptions ()) if (((SSUHeader *)buf)->IsExtendedOptions ())
@ -222,7 +222,7 @@ namespace transport
} }
if (headerSize >= len) if (headerSize >= len)
{ {
LogPrint (eLogError, "Session request header size ", headerSize, " exceeds packet length ", len); LogPrint (eLogError, "SSU message: Session request header size ", headerSize, " exceeds packet length ", len);
return; return;
} }
if (!m_DHKeysPair) if (!m_DHKeysPair)
@ -249,7 +249,7 @@ namespace transport
auto headerSize = GetSSUHeaderSize (buf); auto headerSize = GetSSUHeaderSize (buf);
if (headerSize >= len) if (headerSize >= len)
{ {
LogPrint (eLogError, "Session created header size ", headerSize, " exceeds packet length ", len); LogPrint (eLogError, "SSU message: Session created header size ", headerSize, " exceeds packet length ", len);
return; return;
} }
uint8_t * payload = buf + headerSize; uint8_t * payload = buf + headerSize;
@ -280,7 +280,7 @@ namespace transport
uint32_t signedOnTime = bufbe32toh(payload); uint32_t signedOnTime = bufbe32toh(payload);
if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW) if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW)
{ {
LogPrint (eLogError, "SSU: clock skew detected ", (int)ts - signedOnTime, ". Check your clock"); LogPrint (eLogError, "SSU: Clock skew detected ", (int)ts - signedOnTime, ". Check your clock");
i2p::context.SetError (eRouterErrorClockSkew); i2p::context.SetError (eRouterErrorClockSkew);
} }
} }
@ -309,7 +309,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogError, "SSU: message 'created' signature verification failed"); LogPrint (eLogError, "SSU: Message 'created' signature verification failed");
Failed (); Failed ();
} }
} }
@ -342,7 +342,7 @@ namespace transport
uint32_t signedOnTime = bufbe32toh(payload); uint32_t signedOnTime = bufbe32toh(payload);
if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW) if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW)
{ {
LogPrint (eLogError, "SSU message 'confirmed' time difference ", (int)ts - signedOnTime, " exceeds clock skew"); LogPrint (eLogError, "SSU: Message 'confirmed' time difference ", (int)ts - signedOnTime, " exceeds clock skew");
Failed (); Failed ();
return; return;
} }
@ -366,7 +366,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogError, "SSU message 'confirmed' signature verification failed"); LogPrint (eLogError, "SSU: Message 'confirmed' signature verification failed");
Failed (); Failed ();
} }
} }
@ -413,7 +413,7 @@ namespace transport
i2p::context.GetRouterInfo ().GetSSUAddress (true); i2p::context.GetRouterInfo ().GetSSUAddress (true);
if (!address) if (!address)
{ {
LogPrint (eLogInfo, "SSU is not supported"); LogPrint (eLogInfo, "SSU: SSU is not supported");
return; return;
} }
@ -438,7 +438,7 @@ namespace transport
else else
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, introducer.iKey, iv, introducer.iKey); FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, introducer.iKey, iv, introducer.iKey);
m_Server.Send (buf, 96, m_RemoteEndpoint); m_Server.Send (buf, 96, m_RemoteEndpoint);
LogPrint (eLogDebug, "SSU: relay request sent"); LogPrint (eLogDebug, "SSU: Relay request sent");
} }
void SSUSession::SendSessionCreated (const uint8_t * x, bool sendRelayTag) void SSUSession::SendSessionCreated (const uint8_t * x, bool sendRelayTag)
@ -447,7 +447,7 @@ namespace transport
i2p::context.GetRouterInfo ().GetSSUAddress (true); //v4 only i2p::context.GetRouterInfo ().GetSSUAddress (true); //v4 only
if (!address) if (!address)
{ {
LogPrint (eLogInfo, "SSU is not supported"); LogPrint (eLogInfo, "SSU: SSU is not supported");
return; return;
} }
SignedData s; // x,y, remote IP, remote port, our IP, our port, relayTag, signed on time SignedData s; // x,y, remote IP, remote port, our IP, our port, relayTag, signed on time
@ -647,7 +647,7 @@ namespace transport
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, isV4 ? 64 : 80, introKey, iv, introKey); FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, isV4 ? 64 : 80, introKey, iv, introKey);
m_Server.Send (buf, isV4 ? 64 : 80, from); m_Server.Send (buf, isV4 ? 64 : 80, from);
} }
LogPrint (eLogDebug, "SSU: relay response sent"); LogPrint (eLogDebug, "SSU: Relay response sent");
} }
void SSUSession::SendRelayIntro (std::shared_ptr<SSUSession> session, const boost::asio::ip::udp::endpoint& from) void SSUSession::SendRelayIntro (std::shared_ptr<SSUSession> session, const boost::asio::ip::udp::endpoint& from)
@ -683,7 +683,7 @@ namespace transport
RAND_bytes (iv, 16); // random iv RAND_bytes (iv, 16); // random iv
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_INTRO, buf, isV4 ? 48 : 64, session->m_SessionKey, iv, session->m_MacKey); FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_INTRO, buf, isV4 ? 48 : 64, session->m_SessionKey, iv, session->m_MacKey);
m_Server.Send (buf, isV4 ? 48 : 64, session->m_RemoteEndpoint); m_Server.Send (buf, isV4 ? 48 : 64, session->m_RemoteEndpoint);
LogPrint (eLogDebug, "SSU: relay intro sent"); LogPrint (eLogDebug, "SSU: Relay intro sent");
} }
void SSUSession::ProcessRelayResponse (const uint8_t * buf, size_t len) void SSUSession::ProcessRelayResponse (const uint8_t * buf, size_t len)
@ -872,7 +872,7 @@ namespace transport
if (!IsOutgoing ()) // incoming session if (!IsOutgoing ()) // incoming session
ScheduleConnectTimer (); ScheduleConnectTimer ();
else else
LogPrint (eLogError, "SSU: wait for connect for outgoing session"); LogPrint (eLogError, "SSU: Wait for connect for outgoing session");
} }
void SSUSession::ScheduleConnectTimer () void SSUSession::ScheduleConnectTimer ()
@ -888,7 +888,7 @@ namespace transport
if (!ecode) if (!ecode)
{ {
// timeout expired // timeout expired
LogPrint (eLogWarning, "SSU: session with ", m_RemoteEndpoint, " was not established after ", SSU_CONNECT_TIMEOUT, " seconds"); LogPrint (eLogWarning, "SSU: Session with ", m_RemoteEndpoint, " was not established after ", SSU_CONNECT_TIMEOUT, " seconds");
Failed (); Failed ();
} }
} }
@ -1036,7 +1036,7 @@ namespace transport
{ {
if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob
{ {
LogPrint (eLogDebug, "SSU: peer test from Bob. We are Alice"); LogPrint (eLogDebug, "SSU: Peer test from Bob. We are Alice");
if (IsV6 ()) if (IsV6 ())
{ {
if (i2p::context.GetStatusV6 () == eRouterStatusTesting) if (i2p::context.GetStatusV6 () == eRouterStatusTesting)
@ -1053,9 +1053,9 @@ namespace transport
} }
else else
{ {
LogPrint (eLogDebug, "SSU: first peer test from Charlie. We are Alice"); LogPrint (eLogDebug, "SSU: First peer test from Charlie. We are Alice");
if (m_State == eSessionStateEstablished) if (m_State == eSessionStateEstablished)
LogPrint (eLogWarning, "SSU: first peer test from Charlie through established session. We are Alice"); LogPrint (eLogWarning, "SSU: First peer test from Charlie through established session. We are Alice");
if (IsV6 ()) if (IsV6 ())
i2p::context.SetStatusV6 (eRouterStatusOK); i2p::context.SetStatusV6 (eRouterStatusOK);
else else
@ -1068,11 +1068,11 @@ namespace transport
case ePeerTestParticipantAlice2: case ePeerTestParticipantAlice2:
{ {
if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob
LogPrint (eLogDebug, "SSU: peer test from Bob. We are Alice"); LogPrint (eLogDebug, "SSU: Peer test from Bob. We are Alice");
else else
{ {
// peer test successive // peer test successive
LogPrint (eLogDebug, "SSU: second peer test from Charlie. We are Alice"); LogPrint (eLogDebug, "SSU: Second peer test from Charlie. We are Alice");
if (IsV6 ()) if (IsV6 ())
i2p::context.SetStatusV6 (eRouterStatusOK); i2p::context.SetStatusV6 (eRouterStatusOK);
else else
@ -1083,7 +1083,7 @@ namespace transport
} }
case ePeerTestParticipantBob: case ePeerTestParticipantBob:
{ {
LogPrint (eLogDebug, "SSU: peer test from Charlie. We are Bob"); LogPrint (eLogDebug, "SSU: Peer test from Charlie. We are Bob");
auto session = m_Server.GetPeerTestSession (nonce); // session with Alice from PeerTest auto session = m_Server.GetPeerTestSession (nonce); // session with Alice from PeerTest
if (session && session->m_State == eSessionStateEstablished) if (session && session->m_State == eSessionStateEstablished)
{ {
@ -1095,7 +1095,7 @@ namespace transport
} }
case ePeerTestParticipantCharlie: case ePeerTestParticipantCharlie:
{ {
LogPrint (eLogDebug, "SSU: peer test from Alice. We are Charlie"); LogPrint (eLogDebug, "SSU: Peer test from Alice. We are Charlie");
SendPeerTest (nonce, senderEndpoint.address (), senderEndpoint.port (), introKey); // to Alice with her actual address SendPeerTest (nonce, senderEndpoint.address (), senderEndpoint.port (), introKey); // to Alice with her actual address
m_Server.RemovePeerTest (nonce); // nonce has been used m_Server.RemovePeerTest (nonce); // nonce has been used
break; break;
@ -1108,7 +1108,7 @@ namespace transport
// new test // new test
if (port) if (port)
{ {
LogPrint (eLogDebug, "SSU: peer test from Bob. We are Charlie"); LogPrint (eLogDebug, "SSU: Peer test from Bob. We are Charlie");
Send (PAYLOAD_TYPE_PEER_TEST, buf, len); // back to Bob Send (PAYLOAD_TYPE_PEER_TEST, buf, len); // back to Bob
if (!addr.is_unspecified () && !i2p::util::net::IsInReservedRange(addr)) if (!addr.is_unspecified () && !i2p::util::net::IsInReservedRange(addr))
{ {
@ -1118,7 +1118,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogDebug, "SSU: peer test from Alice. We are Bob"); LogPrint (eLogDebug, "SSU: Peer test from Alice. We are Bob");
auto session = senderEndpoint.address ().is_v4 () ? m_Server.GetRandomEstablishedV4Session (shared_from_this ()) : m_Server.GetRandomEstablishedV6Session (shared_from_this ()); // Charlie auto session = senderEndpoint.address ().is_v4 () ? m_Server.GetRandomEstablishedV4Session (shared_from_this ()) : m_Server.GetRandomEstablishedV6Session (shared_from_this ()); // Charlie
if (session) if (session)
{ {
@ -1128,7 +1128,7 @@ namespace transport
} }
} }
else else
LogPrint (eLogError, "SSU: unexpected peer test"); LogPrint (eLogError, "SSU: Unexpected peer test");
} }
} }
} }
@ -1176,7 +1176,7 @@ namespace transport
if (addr) if (addr)
memcpy (payload, addr->ssu->key, 32); // intro key memcpy (payload, addr->ssu->key, 32); // intro key
else else
LogPrint (eLogInfo, "SSU is not supported. Can't send peer test"); LogPrint (eLogInfo, "SSU: SSU is not supported. Can't send peer test");
} }
else else
memcpy (payload, introKey, 32); // intro key memcpy (payload, introKey, 32); // intro key
@ -1201,11 +1201,11 @@ namespace transport
void SSUSession::SendPeerTest () void SSUSession::SendPeerTest ()
{ {
// we are Alice // we are Alice
LogPrint (eLogDebug, "SSU: sending peer test"); LogPrint (eLogDebug, "SSU: Sending peer test");
auto address = IsV6 () ? i2p::context.GetRouterInfo ().GetSSUV6Address () : i2p::context.GetRouterInfo ().GetSSUAddress (true); auto address = IsV6 () ? i2p::context.GetRouterInfo ().GetSSUV6Address () : i2p::context.GetRouterInfo ().GetSSUAddress (true);
if (!address) if (!address)
{ {
LogPrint (eLogInfo, "SSU is not supported. Can't send peer test"); LogPrint (eLogInfo, "SSU: SSU is not supported. Can't send peer test");
return; return;
} }
uint32_t nonce; uint32_t nonce;
@ -1246,9 +1246,9 @@ namespace transport
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogWarning, "SSU: exception while sending session destoroyed: ", ex.what ()); LogPrint (eLogWarning, "SSU: Exception while sending session destoroyed: ", ex.what ());
} }
LogPrint (eLogDebug, "SSU: session destroyed sent"); LogPrint (eLogDebug, "SSU: Session destroyed sent");
} }
} }
@ -1260,7 +1260,7 @@ namespace transport
if (paddingSize > 0) msgSize += (16 - paddingSize); if (paddingSize > 0) msgSize += (16 - paddingSize);
if (msgSize > SSU_MTU_V4) if (msgSize > SSU_MTU_V4)
{ {
LogPrint (eLogWarning, "SSU: payload size ", msgSize, " exceeds MTU"); LogPrint (eLogWarning, "SSU: Payload size ", msgSize, " exceeds MTU");
return; return;
} }
memcpy (buf + sizeof (SSUHeader), payload, len); memcpy (buf + sizeof (SSUHeader), payload, len);

26
libi2pd/Transports.cpp

@ -128,7 +128,7 @@ namespace transport
m_Queue.push (pair); m_Queue.push (pair);
} }
else else
LogPrint(eLogError, "Transports: return null DHKeys"); LogPrint(eLogError, "Transports: Return null DHKeys");
} }
Transports transports; Transports transports;
@ -192,10 +192,10 @@ namespace transport
i2p::context.SetStatus (eRouterStatusProxy); i2p::context.SetStatus (eRouterStatusProxy);
} }
else else
LogPrint(eLogError, "Transports: unsupported NTCP2 proxy URL ", ntcp2proxy); LogPrint(eLogError, "Transports: Unsupported NTCP2 proxy URL ", ntcp2proxy);
} }
else else
LogPrint(eLogError, "Transports: invalid NTCP2 proxy url ", ntcp2proxy); LogPrint(eLogError, "Transports: Invalid NTCP2 proxy URL ", ntcp2proxy);
} }
else else
m_NTCP2Server = new NTCP2Server (); m_NTCP2Server = new NTCP2Server ();
@ -335,7 +335,7 @@ namespace transport
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "Transports: runtime exception: ", ex.what ()); LogPrint (eLogError, "Transports: Runtime exception: ", ex.what ());
} }
} }
} }
@ -426,7 +426,7 @@ namespace transport
} }
else else
{ {
LogPrint (eLogWarning, "Transports: delayed messages queue size to ", LogPrint (eLogWarning, "Transports: Delayed messages queue size to ",
ident.ToBase64 (), " exceeds ", MAX_NUM_DELAYED_MESSAGES); ident.ToBase64 (), " exceeds ", MAX_NUM_DELAYED_MESSAGES);
std::unique_lock<std::mutex> l(m_PeersMutex); std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it); m_Peers.erase (it);
@ -554,13 +554,13 @@ namespace transport
{ {
if (r) if (r)
{ {
LogPrint (eLogDebug, "Transports: RouterInfo for ", ident.ToBase64 (), " found, Trying to connect"); LogPrint (eLogDebug, "Transports: RouterInfo for ", ident.ToBase64 (), " found, trying to connect");
it->second.router = r; it->second.router = r;
ConnectToPeer (ident, it->second); ConnectToPeer (ident, it->second);
} }
else else
{ {
LogPrint (eLogWarning, "Transports: RouterInfo not found, Failed to send messages"); LogPrint (eLogWarning, "Transports: RouterInfo not found, failed to send messages");
std::unique_lock<std::mutex> l(m_PeersMutex); std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it); m_Peers.erase (it);
} }
@ -571,7 +571,7 @@ namespace transport
{ {
if (RoutesRestricted()) if (RoutesRestricted())
{ {
LogPrint(eLogInfo, "Transports: restricted routes enabled, not detecting ip"); LogPrint(eLogInfo, "Transports: Restricted routes enabled, not detecting IP");
i2p::context.SetStatus (eRouterStatusOK); i2p::context.SetStatus (eRouterStatusOK);
return; return;
} }
@ -586,7 +586,7 @@ namespace transport
if (RoutesRestricted() || !m_SSUServer) return; if (RoutesRestricted() || !m_SSUServer) return;
if (ipv4 && i2p::context.SupportsV4 ()) if (ipv4 && i2p::context.SupportsV4 ())
{ {
LogPrint (eLogInfo, "Transports: Started peer test ipv4"); LogPrint (eLogInfo, "Transports: Started peer test IPv4");
std::set<i2p::data::IdentHash> excluded; std::set<i2p::data::IdentHash> excluded;
bool statusChanged = false; bool statusChanged = false;
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
@ -608,11 +608,11 @@ namespace transport
} }
} }
if (!statusChanged) if (!statusChanged)
LogPrint (eLogWarning, "Transports: Can't find routers for peer test ipv4"); LogPrint (eLogWarning, "Transports: Can't find routers for peer test IPv4");
} }
if (ipv6 && i2p::context.SupportsV6 ()) if (ipv6 && i2p::context.SupportsV6 ())
{ {
LogPrint (eLogInfo, "Transports: Started peer test ipv6"); LogPrint (eLogInfo, "Transports: Started peer test IPv6");
std::set<i2p::data::IdentHash> excluded; std::set<i2p::data::IdentHash> excluded;
bool statusChanged = false; bool statusChanged = false;
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
@ -634,7 +634,7 @@ namespace transport
} }
} }
if (!statusChanged) if (!statusChanged)
LogPrint (eLogWarning, "Transports: Can't find routers for peer test ipv6"); LogPrint (eLogWarning, "Transports: Can't find routers for peer test IPv6");
} }
} }
@ -680,7 +680,7 @@ namespace transport
{ {
if(RoutesRestricted() && ! IsRestrictedPeer(ident)) { if(RoutesRestricted() && ! IsRestrictedPeer(ident)) {
// not trusted // not trusted
LogPrint(eLogWarning, "Transports: closing untrusted inbound connection from ", ident.ToBase64()); LogPrint(eLogWarning, "Transports: Closing untrusted inbound connection from ", ident.ToBase64());
session->Done(); session->Done();
return; return;
} }

36
libi2pd/Tunnel.cpp

@ -137,7 +137,7 @@ namespace tunnel
} }
else else
{ {
LogPrint (eLogWarning, "Tunnel: hop index ", hop->recordIndex, " is out of range"); LogPrint (eLogWarning, "Tunnel: Hop index ", hop->recordIndex, " is out of range");
return false; return false;
} }
@ -149,7 +149,7 @@ namespace tunnel
if (idx >= 0 && idx < msg[0]) if (idx >= 0 && idx < msg[0])
hop->DecryptRecord (msg + 1, idx); hop->DecryptRecord (msg + 1, idx);
else else
LogPrint (eLogWarning, "Tunnel: hop index ", idx, " is out of range"); LogPrint (eLogWarning, "Tunnel: Hop index ", idx, " is out of range");
hop1 = hop1->prev; hop1 = hop1->prev;
} }
hop = hop->prev; hop = hop->prev;
@ -312,7 +312,7 @@ namespace tunnel
void OutboundTunnel::HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg) void OutboundTunnel::HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg)
{ {
LogPrint (eLogError, "Tunnel: incoming message for outbound tunnel ", GetTunnelID ()); LogPrint (eLogError, "Tunnel: Incoming message for outbound tunnel ", GetTunnelID ());
} }
void OutboundTunnel::Print (std::stringstream& s) const void OutboundTunnel::Print (std::stringstream& s) const
@ -465,7 +465,7 @@ namespace tunnel
if (m_Tunnels.emplace (tunnel->GetTunnelID (), tunnel).second) if (m_Tunnels.emplace (tunnel->GetTunnelID (), tunnel).second)
m_TransitTunnels.push_back (tunnel); m_TransitTunnels.push_back (tunnel);
else else
LogPrint (eLogError, "Tunnel: tunnel with id ", tunnel->GetTunnelID (), " already exists"); LogPrint (eLogError, "Tunnel: Tunnel with id ", tunnel->GetTunnelID (), " already exists");
} }
void Tunnels::Start () void Tunnels::Start ()
@ -526,7 +526,7 @@ namespace tunnel
HandleTunnelGatewayMsg (tunnel, msg); HandleTunnelGatewayMsg (tunnel, msg);
} }
else else
LogPrint (eLogWarning, "Tunnel: tunnel not found, tunnelID=", tunnelID, " previousTunnelID=", prevTunnelID, " type=", (int)typeID); LogPrint (eLogWarning, "Tunnel: Tunnel not found, tunnelID=", tunnelID, " previousTunnelID=", prevTunnelID, " type=", (int)typeID);
break; break;
} }
@ -539,7 +539,7 @@ namespace tunnel
HandleI2NPMessage (msg->GetBuffer (), msg->GetLength ()); HandleI2NPMessage (msg->GetBuffer (), msg->GetLength ());
break; break;
default: default:
LogPrint (eLogWarning, "Tunnel: unexpected message type ", (int) typeID); LogPrint (eLogWarning, "Tunnel: Unexpected message type ", (int) typeID);
} }
msg = m_Queue.Get (); msg = m_Queue.Get ();
@ -577,7 +577,7 @@ namespace tunnel
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, "Tunnel: runtime exception: ", ex.what ()); LogPrint (eLogError, "Tunnel: Runtime exception: ", ex.what ());
} }
} }
} }
@ -586,7 +586,7 @@ namespace tunnel
{ {
if (!tunnel) if (!tunnel)
{ {
LogPrint (eLogError, "Tunnel: missing tunnel for gateway"); LogPrint (eLogError, "Tunnel: Missing tunnel for gateway");
return; return;
} }
const uint8_t * payload = msg->GetPayload (); const uint8_t * payload = msg->GetPayload ();
@ -595,12 +595,12 @@ namespace tunnel
msg->offset += I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE; msg->offset += I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE;
if (msg->offset + len > msg->len) if (msg->offset + len > msg->len)
{ {
LogPrint (eLogError, "Tunnel: gateway payload ", (int)len, " exceeds message length ", (int)msg->len); LogPrint (eLogError, "Tunnel: Gateway payload ", (int)len, " exceeds message length ", (int)msg->len);
return; return;
} }
msg->len = msg->offset + len; msg->len = msg->offset + len;
auto typeID = msg->GetTypeID (); auto typeID = msg->GetTypeID ();
LogPrint (eLogDebug, "Tunnel: gateway of ", (int) len, " bytes for tunnel ", tunnel->GetTunnelID (), ", msg type ", (int)typeID); LogPrint (eLogDebug, "Tunnel: Gateway of ", (int) len, " bytes for tunnel ", tunnel->GetTunnelID (), ", msg type ", (int)typeID);
if (IsRouterInfoMsg (msg) || typeID == eI2NPDatabaseSearchReply) if (IsRouterInfoMsg (msg) || typeID == eI2NPDatabaseSearchReply)
// transit DatabaseStore my contain new/updated RI // transit DatabaseStore my contain new/updated RI
@ -636,7 +636,7 @@ namespace tunnel
case eTunnelStatePending: case eTunnelStatePending:
if (ts > tunnel->GetCreationTime () + TUNNEL_CREATION_TIMEOUT) if (ts > tunnel->GetCreationTime () + TUNNEL_CREATION_TIMEOUT)
{ {
LogPrint (eLogDebug, "Tunnel: pending build request ", it->first, " timeout, deleted"); LogPrint (eLogDebug, "Tunnel: Pending build request ", it->first, " timeout, deleted");
// update stats // update stats
auto config = tunnel->GetTunnelConfig (); auto config = tunnel->GetTunnelConfig ();
if (config) if (config)
@ -661,7 +661,7 @@ namespace tunnel
++it; ++it;
break; break;
case eTunnelStateBuildFailed: case eTunnelStateBuildFailed:
LogPrint (eLogDebug, "Tunnel: pending build request ", it->first, " failed, deleted"); LogPrint (eLogDebug, "Tunnel: Pending build request ", it->first, " failed, deleted");
it = pendingTunnels.erase (it); it = pendingTunnels.erase (it);
m_NumFailedTunnelCreations++; m_NumFailedTunnelCreations++;
break; break;
@ -686,7 +686,7 @@ namespace tunnel
auto tunnel = *it; auto tunnel = *it;
if (ts > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT) if (ts > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT)
{ {
LogPrint (eLogDebug, "Tunnel: tunnel with id ", tunnel->GetTunnelID (), " expired"); LogPrint (eLogDebug, "Tunnel: Tunnel with id ", tunnel->GetTunnelID (), " expired");
auto pool = tunnel->GetTunnelPool (); auto pool = tunnel->GetTunnelPool ();
if (pool) if (pool)
pool->TunnelExpired (tunnel); pool->TunnelExpired (tunnel);
@ -723,7 +723,7 @@ namespace tunnel
i2p::transport::transports.GetRestrictedPeer() : i2p::transport::transports.GetRestrictedPeer() :
i2p::data::netdb.GetRandomRouter (i2p::context.GetSharedRouterInfo (), false); // reachable by us i2p::data::netdb.GetRandomRouter (i2p::context.GetSharedRouterInfo (), false); // reachable by us
if (!inboundTunnel || !router) return; if (!inboundTunnel || !router) return;
LogPrint (eLogDebug, "Tunnel: creating one hop outbound tunnel"); LogPrint (eLogDebug, "Tunnel: Creating one hop outbound tunnel");
CreateTunnel<OutboundTunnel> ( CreateTunnel<OutboundTunnel> (
std::make_shared<TunnelConfig> (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > { router->GetRouterIdentity () }, std::make_shared<TunnelConfig> (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > { router->GetRouterIdentity () },
inboundTunnel->GetNextTunnelID (), inboundTunnel->GetNextIdentHash (), false), nullptr inboundTunnel->GetNextTunnelID (), inboundTunnel->GetNextIdentHash (), false), nullptr
@ -740,7 +740,7 @@ namespace tunnel
auto tunnel = *it; auto tunnel = *it;
if (ts > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT) if (ts > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT)
{ {
LogPrint (eLogDebug, "Tunnel: tunnel with id ", tunnel->GetTunnelID (), " expired"); LogPrint (eLogDebug, "Tunnel: Tunnel with id ", tunnel->GetTunnelID (), " expired");
auto pool = tunnel->GetTunnelPool (); auto pool = tunnel->GetTunnelPool ();
if (pool) if (pool)
pool->TunnelExpired (tunnel); pool->TunnelExpired (tunnel);
@ -797,10 +797,10 @@ namespace tunnel
// should be reachable by us because we send build request directly // should be reachable by us because we send build request directly
i2p::data::netdb.GetRandomRouter (i2p::context.GetSharedRouterInfo (), false); i2p::data::netdb.GetRandomRouter (i2p::context.GetSharedRouterInfo (), false);
if (!router) { if (!router) {
LogPrint (eLogWarning, "Tunnel: can't find any router, skip creating tunnel"); LogPrint (eLogWarning, "Tunnel: Can't find any router, skip creating tunnel");
return; return;
} }
LogPrint (eLogDebug, "Tunnel: creating one hop inbound tunnel"); LogPrint (eLogDebug, "Tunnel: Creating one hop inbound tunnel");
CreateTunnel<InboundTunnel> ( CreateTunnel<InboundTunnel> (
std::make_shared<TunnelConfig> (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > { router->GetRouterIdentity () }, false), nullptr std::make_shared<TunnelConfig> (std::vector<std::shared_ptr<const i2p::data::IdentityEx> > { router->GetRouterIdentity () }, false), nullptr
); );
@ -920,7 +920,7 @@ namespace tunnel
} }
} }
else else
LogPrint (eLogError, "Tunnel: tunnel with id ", newTunnel->GetTunnelID (), " already exists"); LogPrint (eLogError, "Tunnel: Tunnel with id ", newTunnel->GetTunnelID (), " already exists");
} }

12
libi2pd/TunnelEndpoint.cpp

@ -40,7 +40,7 @@ namespace tunnel
SHA256(fragment, TUNNEL_DATA_MSG_SIZE -(fragment - msg->GetPayload ()) + 16, hash); // payload + iv SHA256(fragment, TUNNEL_DATA_MSG_SIZE -(fragment - msg->GetPayload ()) + 16, hash); // payload + iv
if (memcmp (hash, decrypted, 4)) if (memcmp (hash, decrypted, 4))
{ {
LogPrint (eLogError, "TunnelMessage: checksum verification failed"); LogPrint (eLogError, "TunnelMessage: Checksum verification failed");
return; return;
} }
// process fragments // process fragments
@ -118,7 +118,7 @@ namespace tunnel
// check message size // check message size
if (msg->len > msg->maxLen) if (msg->len > msg->maxLen)
{ {
LogPrint (eLogError, "TunnelMessage: fragment is too long ", (int)size); LogPrint (eLogError, "TunnelMessage: Fragment is too long ", (int)size);
m_CurrentMsgID = 0; m_CurrentMessage.data = nullptr; m_CurrentMsgID = 0; m_CurrentMessage.data = nullptr;
return; return;
} }
@ -156,7 +156,7 @@ namespace tunnel
} }
} }
else else
LogPrint (eLogError, "TunnelMessage: zero not found"); LogPrint (eLogError, "TunnelMessage: Zero not found");
} }
void TunnelEndpoint::HandleFollowOnFragment (uint32_t msgID, bool isLastFragment, void TunnelEndpoint::HandleFollowOnFragment (uint32_t msgID, bool isLastFragment,
@ -264,7 +264,7 @@ namespace tunnel
std::unique_ptr<Fragment> f(new Fragment (isLastFragment, i2p::util::GetMillisecondsSinceEpoch (), size)); std::unique_ptr<Fragment> f(new Fragment (isLastFragment, i2p::util::GetMillisecondsSinceEpoch (), size));
memcpy (f->data.data (), fragment, size); memcpy (f->data.data (), fragment, size);
if (!m_OutOfSequenceFragments.emplace ((uint64_t)msgID << 32 | fragmentNum, std::move (f)).second) if (!m_OutOfSequenceFragments.emplace ((uint64_t)msgID << 32 | fragmentNum, std::move (f)).second)
LogPrint (eLogInfo, "TunnelMessage: duplicate out-of-sequence fragment ", fragmentNum, " of message ", msgID); LogPrint (eLogInfo, "TunnelMessage: Duplicate out-of-sequence fragment ", fragmentNum, " of message ", msgID);
} }
void TunnelEndpoint::HandleOutOfSequenceFragments (uint32_t msgID, TunnelMessageBlockEx& msg) void TunnelEndpoint::HandleOutOfSequenceFragments (uint32_t msgID, TunnelMessageBlockEx& msg)
@ -318,11 +318,11 @@ namespace tunnel
{ {
if (!m_IsInbound && msg.data->IsExpired ()) if (!m_IsInbound && msg.data->IsExpired ())
{ {
LogPrint (eLogInfo, "TunnelMessage: message expired"); LogPrint (eLogInfo, "TunnelMessage: Message expired");
return; return;
} }
uint8_t typeID = msg.data->GetTypeID (); uint8_t typeID = msg.data->GetTypeID ();
LogPrint (eLogDebug, "TunnelMessage: handle fragment of ", msg.data->GetLength (), " bytes, msg type ", (int)typeID); LogPrint (eLogDebug, "TunnelMessage: Handle fragment of ", msg.data->GetLength (), " bytes, msg type ", (int)typeID);
// catch RI or reply with new list of routers // catch RI or reply with new list of routers
if ((IsRouterInfoMsg (msg.data) || typeID == eI2NPDatabaseSearchReply) && if ((IsRouterInfoMsg (msg.data) || typeID == eI2NPDatabaseSearchReply) &&
!m_IsInbound && msg.deliveryType != eDeliveryTypeLocal) !m_IsInbound && msg.deliveryType != eDeliveryTypeLocal)

6
libi2pd/TunnelPool.cpp

@ -307,7 +307,7 @@ namespace tunnel
for (auto& it: tests) for (auto& it: tests)
{ {
LogPrint (eLogWarning, "Tunnels: test of tunnel ", it.first, " failed"); LogPrint (eLogWarning, "Tunnels: Test of tunnel ", it.first, " failed");
// if test failed again with another tunnel we consider it failed // if test failed again with another tunnel we consider it failed
if (it.second.first) if (it.second.first)
{ {
@ -383,7 +383,7 @@ namespace tunnel
if (m_LocalDestination) if (m_LocalDestination)
m_LocalDestination->ProcessGarlicMessage (msg); m_LocalDestination->ProcessGarlicMessage (msg);
else else
LogPrint (eLogWarning, "Tunnels: local destination doesn't exist, dropped"); LogPrint (eLogWarning, "Tunnels: Local destination doesn't exist, dropped");
} }
void TunnelPool::ProcessDeliveryStatus (std::shared_ptr<I2NPMessage> msg) void TunnelPool::ProcessDeliveryStatus (std::shared_ptr<I2NPMessage> msg)
@ -408,7 +408,7 @@ namespace tunnel
if (found) if (found)
{ {
uint64_t dlt = i2p::util::GetMillisecondsSinceEpoch () - timestamp; uint64_t dlt = i2p::util::GetMillisecondsSinceEpoch () - timestamp;
LogPrint (eLogDebug, "Tunnels: test of ", msgID, " successful. ", dlt, " milliseconds"); LogPrint (eLogDebug, "Tunnels: Test of ", msgID, " successful. ", dlt, " milliseconds");
uint64_t latency = dlt / 2; uint64_t latency = dlt / 2;
// restore from test failed state if any // restore from test failed state if any
if (test.first) if (test.first)

14
libi2pd/api.cpp

@ -60,22 +60,22 @@ namespace api
else else
i2p::log::Logger().SendTo (i2p::fs::DataDirPath (i2p::fs::GetAppName () + ".log")); i2p::log::Logger().SendTo (i2p::fs::DataDirPath (i2p::fs::GetAppName () + ".log"));
i2p::log::Logger().Start (); i2p::log::Logger().Start ();
LogPrint(eLogInfo, "API: starting NetDB"); LogPrint(eLogInfo, "API: Starting NetDB");
i2p::data::netdb.Start(); i2p::data::netdb.Start();
LogPrint(eLogInfo, "API: starting Transports"); LogPrint(eLogInfo, "API: Starting Transports");
i2p::transport::transports.Start(); i2p::transport::transports.Start();
LogPrint(eLogInfo, "API: starting Tunnels"); LogPrint(eLogInfo, "API: Starting Tunnels");
i2p::tunnel::tunnels.Start(); i2p::tunnel::tunnels.Start();
} }
void StopI2P () void StopI2P ()
{ {
LogPrint(eLogInfo, "API: shutting down"); LogPrint(eLogInfo, "API: Shutting down");
LogPrint(eLogInfo, "API: stopping Tunnels"); LogPrint(eLogInfo, "API: Stopping Tunnels");
i2p::tunnel::tunnels.Stop(); i2p::tunnel::tunnels.Stop();
LogPrint(eLogInfo, "API: stopping Transports"); LogPrint(eLogInfo, "API: Stopping Transports");
i2p::transport::transports.Stop(); i2p::transport::transports.Stop();
LogPrint(eLogInfo, "API: stopping NetDB"); LogPrint(eLogInfo, "API: Stopping NetDB");
i2p::data::netdb.Stop(); i2p::data::netdb.Stop();
i2p::log::Logger().Stop (); i2p::log::Logger().Stop ();
} }

28
libi2pd/util.cpp

@ -117,7 +117,7 @@ namespace util
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
LogPrint (eLogError, m_Name, ": runtime exception: ", ex.what ()); LogPrint (eLogError, m_Name, ": Runtime exception: ", ex.what ());
} }
} }
} }
@ -176,7 +176,7 @@ namespace net
if(dwRetVal != NO_ERROR) if(dwRetVal != NO_ERROR)
{ {
LogPrint(eLogError, "NetIface: GetMTU(): enclosed GetAdaptersAddresses() call has failed"); LogPrint(eLogError, "NetIface: GetMTU(): Enclosed GetAdaptersAddresses() call has failed");
FREE(pAddresses); FREE(pAddresses);
return fallback; return fallback;
} }
@ -188,7 +188,7 @@ namespace net
pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast = pCurrAddresses->FirstUnicastAddress;
if(pUnicast == nullptr) if(pUnicast == nullptr)
LogPrint(eLogError, "NetIface: GetMTU(): not a unicast ipv4 address, this is not supported"); LogPrint(eLogError, "NetIface: GetMTU(): Not a unicast IPv4 address, this is not supported");
for(int i = 0; pUnicast != nullptr; ++i) for(int i = 0; pUnicast != nullptr; ++i)
{ {
@ -205,7 +205,7 @@ namespace net
pCurrAddresses = pCurrAddresses->Next; pCurrAddresses = pCurrAddresses->Next;
} }
LogPrint(eLogError, "NetIface: GetMTU(): no usable unicast ipv4 addresses found"); LogPrint(eLogError, "NetIface: GetMTU(): No usable unicast IPv4 addresses found");
FREE(pAddresses); FREE(pAddresses);
return fallback; return fallback;
} }
@ -230,7 +230,7 @@ namespace net
if(dwRetVal != NO_ERROR) if(dwRetVal != NO_ERROR)
{ {
LogPrint(eLogError, "NetIface: GetMTU(): enclosed GetAdaptersAddresses() call has failed"); LogPrint(eLogError, "NetIface: GetMTU(): Enclosed GetAdaptersAddresses() call has failed");
FREE(pAddresses); FREE(pAddresses);
return fallback; return fallback;
} }
@ -242,7 +242,7 @@ namespace net
PIP_ADAPTER_UNICAST_ADDRESS firstUnicastAddress = pCurrAddresses->FirstUnicastAddress; PIP_ADAPTER_UNICAST_ADDRESS firstUnicastAddress = pCurrAddresses->FirstUnicastAddress;
pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast = pCurrAddresses->FirstUnicastAddress;
if(pUnicast == nullptr) if(pUnicast == nullptr)
LogPrint(eLogError, "NetIface: GetMTU(): not a unicast ipv6 address, this is not supported"); LogPrint(eLogError, "NetIface: GetMTU(): Not a unicast IPv6 address, this is not supported");
for(int i = 0; pUnicast != nullptr; ++i) for(int i = 0; pUnicast != nullptr; ++i)
{ {
@ -270,7 +270,7 @@ namespace net
pCurrAddresses = pCurrAddresses->Next; pCurrAddresses = pCurrAddresses->Next;
} }
LogPrint(eLogError, "NetIface: GetMTU(): no usable unicast ipv6 addresses found"); LogPrint(eLogError, "NetIface: GetMTU(): No usable unicast IPv6 addresses found");
FREE(pAddresses); FREE(pAddresses);
return fallback; return fallback;
} }
@ -302,7 +302,7 @@ namespace net
} }
else else
{ {
LogPrint(eLogError, "NetIface: GetMTU(): address family is not supported"); LogPrint(eLogError, "NetIface: GetMTU(): Address family is not supported");
return fallback; return fallback;
} }
} }
@ -355,7 +355,7 @@ namespace net
LogPrint(eLogError, "NetIface: Failed to create datagram socket"); LogPrint(eLogError, "NetIface: Failed to create datagram socket");
} }
else else
LogPrint(eLogWarning, "NetIface: interface for local address", localAddress.to_string(), " not found"); LogPrint(eLogWarning, "NetIface: Interface for local address", localAddress.to_string(), " not found");
freeifaddrs(ifaddr); freeifaddrs(ifaddr);
return mtu; return mtu;
@ -377,7 +377,7 @@ namespace net
const boost::asio::ip::address GetInterfaceAddress (const std::string & ifname, bool ipv6) const boost::asio::ip::address GetInterfaceAddress (const std::string & ifname, bool ipv6)
{ {
#ifdef _WIN32 #ifdef _WIN32
LogPrint(eLogError, "NetIface: cannot get address by interface name, not implemented on WIN32"); LogPrint(eLogError, "NetIface: Cannot get address by interface name, not implemented on WIN32");
if(ipv6) if(ipv6)
return boost::asio::ip::address::from_string("::1"); return boost::asio::ip::address::from_string("::1");
else else
@ -413,10 +413,10 @@ namespace net
if(ipv6) if(ipv6)
{ {
fallback = "::1"; fallback = "::1";
LogPrint(eLogWarning, "NetIface: cannot find ipv6 address for interface ", ifname); LogPrint(eLogWarning, "NetIface: Cannot find IPv6 address for interface ", ifname);
} else { } else {
fallback = "127.0.0.1"; fallback = "127.0.0.1";
LogPrint(eLogWarning, "NetIface: cannot find ipv4 address for interface ", ifname); LogPrint(eLogWarning, "NetIface: Cannot find IPv4 address for interface ", ifname);
} }
return boost::asio::ip::address::from_string(fallback); return boost::asio::ip::address::from_string(fallback);
#endif #endif
@ -479,7 +479,7 @@ namespace net
} }
pCurrAddresses = pCurrAddresses->Next; pCurrAddresses = pCurrAddresses->Next;
} }
LogPrint(eLogWarning, "NetIface: interface with yggdrasil network address not found"); LogPrint(eLogWarning, "NetIface: Interface with Yggdrasil network address not found");
FREE(pAddresses); FREE(pAddresses);
return boost::asio::ip::address_v6 (); return boost::asio::ip::address_v6 ();
#else #else
@ -504,7 +504,7 @@ namespace net
cur = cur->ifa_next; cur = cur->ifa_next;
} }
} }
LogPrint(eLogWarning, "NetIface: interface with yggdrasil network address not found"); LogPrint(eLogWarning, "NetIface: Interface with Yggdrasil network address not found");
if(addrs) freeifaddrs(addrs); if(addrs) freeifaddrs(addrs);
return boost::asio::ip::address_v6 (); return boost::asio::ip::address_v6 ();
#endif #endif

62
libi2pd_client/AddressBook.cpp

@ -119,7 +119,7 @@ namespace client
std::string path = storage.Path( address->GetIdentHash().ToBase32() ); std::string path = storage.Path( address->GetIdentHash().ToBase32() );
std::ofstream f (path, std::ofstream::binary | std::ofstream::out); std::ofstream f (path, std::ofstream::binary | std::ofstream::out);
if (!f.is_open ()) { if (!f.is_open ()) {
LogPrint (eLogError, "Addressbook: can't open file ", path); LogPrint (eLogError, "Addressbook: Can't open file ", path);
return; return;
} }
size_t len = address->GetFullLen (); size_t len = address->GetFullLen ();
@ -169,7 +169,7 @@ namespace client
LogPrint(eLogWarning, "Addressbook: Can't open ", indexPath); LogPrint(eLogWarning, "Addressbook: Can't open ", indexPath);
return 0; return 0;
} }
LogPrint(eLogInfo, "Addressbook: using index file ", indexPath); LogPrint(eLogInfo, "Addressbook: Using index file ", indexPath);
LogPrint (eLogInfo, "Addressbook: ", num, " addresses loaded from storage"); LogPrint (eLogInfo, "Addressbook: ", num, " addresses loaded from storage");
return num; return num;
@ -187,7 +187,7 @@ namespace client
{ {
if (addresses.empty()) if (addresses.empty())
{ {
LogPrint(eLogWarning, "Addressbook: not saving empty addressbook"); LogPrint(eLogWarning, "Addressbook: Not saving empty addressbook");
return 0; return 0;
} }
@ -210,7 +210,7 @@ namespace client
num++; num++;
} }
else else
LogPrint (eLogWarning, "Addressbook: invalid address ", it.first); LogPrint (eLogWarning, "Addressbook: Invalid address ", it.first);
} }
LogPrint (eLogInfo, "Addressbook: ", num, " addresses saved"); LogPrint (eLogInfo, "Addressbook: ", num, " addresses saved");
} }
@ -265,7 +265,7 @@ namespace client
void AddressBookFilesystemStorage::ResetEtags () void AddressBookFilesystemStorage::ResetEtags ()
{ {
LogPrint (eLogError, "Addressbook: resetting eTags"); LogPrint (eLogError, "Addressbook: Resetting eTags");
for (boost::filesystem::directory_iterator it (etagsPath); it != boost::filesystem::directory_iterator (); ++it) for (boost::filesystem::directory_iterator it (etagsPath); it != boost::filesystem::directory_iterator (); ++it)
{ {
if (!boost::filesystem::is_regular_file (it->status ())) if (!boost::filesystem::is_regular_file (it->status ()))
@ -334,17 +334,17 @@ namespace client
} }
if (m_IsDownloading) if (m_IsDownloading)
{ {
LogPrint (eLogInfo, "Addressbook: subscriptions are downloading, abort"); LogPrint (eLogInfo, "Addressbook: Subscriptions are downloading, abort");
for (int i = 0; i < 30; i++) for (int i = 0; i < 30; i++)
{ {
if (!m_IsDownloading) if (!m_IsDownloading)
{ {
LogPrint (eLogInfo, "Addressbook: subscriptions download complete"); LogPrint (eLogInfo, "Addressbook: Subscriptions download complete");
break; break;
} }
std::this_thread::sleep_for (std::chrono::seconds (1)); // wait for 1 seconds std::this_thread::sleep_for (std::chrono::seconds (1)); // wait for 1 seconds
} }
LogPrint (eLogError, "Addressbook: subscription download timeout"); LogPrint (eLogError, "Addressbook: Subscription download timeout");
m_IsDownloading = false; m_IsDownloading = false;
} }
if (m_Storage) if (m_Storage)
@ -397,7 +397,7 @@ namespace client
if (pos != std::string::npos) if (pos != std::string::npos)
{ {
m_Addresses[address] = std::make_shared<Address>(jump.substr (0, pos)); m_Addresses[address] = std::make_shared<Address>(jump.substr (0, pos));
LogPrint (eLogInfo, "Addressbook: added ", address," -> ", jump); LogPrint (eLogInfo, "Addressbook: Added ", address," -> ", jump);
} }
else else
{ {
@ -407,10 +407,10 @@ namespace client
{ {
m_Storage->AddAddress (ident); m_Storage->AddAddress (ident);
m_Addresses[address] = std::make_shared<Address>(ident->GetIdentHash ()); m_Addresses[address] = std::make_shared<Address>(ident->GetIdentHash ());
LogPrint (eLogInfo, "Addressbook: added ", address," -> ", ToAddress(ident->GetIdentHash ())); LogPrint (eLogInfo, "Addressbook: Added ", address," -> ", ToAddress(ident->GetIdentHash ()));
} }
else else
LogPrint (eLogError, "Addressbook: malformed address ", jump); LogPrint (eLogError, "Addressbook: Malformed address ", jump);
} }
} }
@ -473,20 +473,20 @@ namespace client
pos = name.find(".b32.i2p"); pos = name.find(".b32.i2p");
if (pos != std::string::npos) if (pos != std::string::npos)
{ {
LogPrint (eLogError, "Addressbook: skipped adding of b32 address: ", name); LogPrint (eLogError, "Addressbook: Skipped adding of b32 address: ", name);
continue; continue;
} }
pos = name.find(".i2p"); pos = name.find(".i2p");
if (pos == std::string::npos) if (pos == std::string::npos)
{ {
LogPrint (eLogError, "Addressbook: malformed domain: ", name); LogPrint (eLogError, "Addressbook: Malformed domain: ", name);
continue; continue;
} }
auto ident = std::make_shared<i2p::data::IdentityEx> (); auto ident = std::make_shared<i2p::data::IdentityEx> ();
if (!ident->FromBase64(addr)) { if (!ident->FromBase64(addr)) {
LogPrint (eLogError, "Addressbook: malformed address ", addr, " for ", name); LogPrint (eLogError, "Addressbook: Malformed address ", addr, " for ", name);
incomplete = f.eof (); incomplete = f.eof ();
continue; continue;
} }
@ -500,7 +500,7 @@ namespace client
it->second->identHash = ident->GetIdentHash (); it->second->identHash = ident->GetIdentHash ();
m_Storage->AddAddress (ident); m_Storage->AddAddress (ident);
m_Storage->RemoveAddress (it->second->identHash); m_Storage->RemoveAddress (it->second->identHash);
LogPrint (eLogInfo, "Addressbook: updated host: ", name); LogPrint (eLogInfo, "Addressbook: Updated host: ", name);
} }
} }
else else
@ -508,7 +508,7 @@ namespace client
m_Addresses.emplace (name, std::make_shared<Address>(ident->GetIdentHash ())); m_Addresses.emplace (name, std::make_shared<Address>(ident->GetIdentHash ()));
m_Storage->AddAddress (ident); m_Storage->AddAddress (ident);
if (is_update) if (is_update)
LogPrint (eLogInfo, "Addressbook: added new host: ", name); LogPrint (eLogInfo, "Addressbook: Added new host: ", name);
} }
} }
else else
@ -556,7 +556,7 @@ namespace client
} }
} }
else else
LogPrint (eLogError, "Addressbook: subscriptions already loaded"); LogPrint (eLogError, "Addressbook: Subscriptions already loaded");
} }
void AddressBook::LoadLocal () void AddressBook::LoadLocal ()
@ -641,7 +641,7 @@ namespace client
this, std::placeholders::_1)); this, std::placeholders::_1));
} }
else else
LogPrint (eLogError, "Addressbook: can't start subscriptions: missing shared local destination"); LogPrint (eLogError, "Addressbook: Can't start subscriptions: missing shared local destination");
} }
void AddressBook::StopSubscriptions () void AddressBook::StopSubscriptions ()
@ -656,7 +656,7 @@ namespace client
{ {
auto dest = i2p::client::context.GetSharedLocalDestination (); auto dest = i2p::client::context.GetSharedLocalDestination ();
if (!dest) { if (!dest) {
LogPrint(eLogWarning, "Addressbook: missing local destination, skip subscription update"); LogPrint(eLogWarning, "Addressbook: Missing local destination, skip subscription update");
return; return;
} }
if (!m_IsDownloading && dest->IsReady ()) if (!m_IsDownloading && dest->IsReady ())
@ -664,7 +664,7 @@ namespace client
if (!m_IsLoaded) if (!m_IsLoaded)
{ {
// download it from default subscription // download it from default subscription
LogPrint (eLogInfo, "Addressbook: trying to download it from default subscription."); LogPrint (eLogInfo, "Addressbook: Trying to download it from default subscription.");
std::string defaultSubURL; i2p::config::GetOption("addressbook.defaulturl", defaultSubURL); std::string defaultSubURL; i2p::config::GetOption("addressbook.defaulturl", defaultSubURL);
if (!m_DefaultSubscription) if (!m_DefaultSubscription)
m_DefaultSubscription = std::make_shared<AddressBookSubscription>(*this, defaultSubURL); m_DefaultSubscription = std::make_shared<AddressBookSubscription>(*this, defaultSubURL);
@ -802,7 +802,7 @@ namespace client
LogPrint (eLogInfo, "Addressbook: Downloading hosts database from ", m_Link); LogPrint (eLogInfo, "Addressbook: Downloading hosts database from ", m_Link);
if (!url.parse(m_Link)) if (!url.parse(m_Link))
{ {
LogPrint(eLogError, "Addressbook: failed to parse url: ", m_Link); LogPrint(eLogError, "Addressbook: Failed to parse url: ", m_Link);
return false; return false;
} }
auto addr = m_Book.GetAddress (url.host); auto addr = m_Book.GetAddress (url.host);
@ -841,7 +841,7 @@ namespace client
} }
if (m_Etag.empty() && m_LastModified.empty()) { if (m_Etag.empty() && m_LastModified.empty()) {
m_Book.GetEtag (m_Ident, m_Etag, m_LastModified); m_Book.GetEtag (m_Ident, m_Etag, m_LastModified);
LogPrint (eLogDebug, "Addressbook: loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified); LogPrint (eLogDebug, "Addressbook: Loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified);
} }
/* save url parts for later use */ /* save url parts for later use */
std::string dest_host = url.host; std::string dest_host = url.host;
@ -886,7 +886,7 @@ namespace client
// wait 1 more second // wait 1 more second
if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT + 1)) == std::cv_status::timeout) if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT + 1)) == std::cv_status::timeout)
{ {
LogPrint (eLogError, "Addressbook: subscriptions request timeout expired"); LogPrint (eLogError, "Addressbook: Subscriptions request timeout expired");
numAttempts++; numAttempts++;
if (numAttempts > 5) end = true; if (numAttempts > 5) end = true;
} }
@ -899,35 +899,35 @@ namespace client
int res_head_len = res.parse(response); int res_head_len = res.parse(response);
if (res_head_len < 0) if (res_head_len < 0)
{ {
LogPrint(eLogError, "Addressbook: can't parse http response from ", dest_host); LogPrint(eLogError, "Addressbook: Can't parse http response from ", dest_host);
return false; return false;
} }
if (res_head_len == 0) if (res_head_len == 0)
{ {
LogPrint(eLogError, "Addressbook: incomplete http response from ", dest_host, ", interrupted by timeout"); LogPrint(eLogError, "Addressbook: Incomplete http response from ", dest_host, ", interrupted by timeout");
return false; return false;
} }
/* assert: res_head_len > 0 */ /* assert: res_head_len > 0 */
response.erase(0, res_head_len); response.erase(0, res_head_len);
if (res.code == 304) if (res.code == 304)
{ {
LogPrint (eLogInfo, "Addressbook: no updates from ", dest_host, ", code 304"); LogPrint (eLogInfo, "Addressbook: No updates from ", dest_host, ", code 304");
return false; return false;
} }
if (res.code != 200) if (res.code != 200)
{ {
LogPrint (eLogWarning, "Adressbook: can't get updates from ", dest_host, ", response code ", res.code); LogPrint (eLogWarning, "Adressbook: Can't get updates from ", dest_host, ", response code ", res.code);
return false; return false;
} }
int len = res.content_length(); int len = res.content_length();
if (response.empty()) if (response.empty())
{ {
LogPrint(eLogError, "Addressbook: empty response from ", dest_host, ", expected ", len, " bytes"); LogPrint(eLogError, "Addressbook: Empty response from ", dest_host, ", expected ", len, " bytes");
return false; return false;
} }
if (!res.is_gzipped () && len > 0 && len != (int) response.length()) if (!res.is_gzipped () && len > 0 && len != (int) response.length())
{ {
LogPrint(eLogError, "Addressbook: response size mismatch, expected: ", len, ", got: ", response.length(), "bytes"); LogPrint(eLogError, "Addressbook: Response size mismatch, expected: ", len, ", got: ", response.length(), "bytes");
return false; return false;
} }
/* assert: res.code == 200 */ /* assert: res.code == 200 */
@ -948,13 +948,13 @@ namespace client
inflator.Inflate ((const uint8_t *) response.data(), response.length(), out); inflator.Inflate ((const uint8_t *) response.data(), response.length(), out);
if (out.fail()) if (out.fail())
{ {
LogPrint(eLogError, "Addressbook: can't gunzip http response"); LogPrint(eLogError, "Addressbook: Can't gunzip http response");
return false; return false;
} }
response = out.str(); response = out.str();
} }
std::stringstream ss(response); std::stringstream ss(response);
LogPrint (eLogInfo, "Addressbook: got update from ", dest_host); LogPrint (eLogInfo, "Addressbook: Got update from ", dest_host);
m_Book.LoadHostsFromStream (ss, true); m_Book.LoadHostsFromStream (ss, true);
return true; return true;
} }

16
libi2pd_client/BOB.cpp

@ -68,7 +68,7 @@ namespace client
std::shared_ptr<AddressReceiver> receiver) std::shared_ptr<AddressReceiver> receiver)
{ {
if (ecode) if (ecode)
LogPrint (eLogError, "BOB: inbound tunnel read error: ", ecode.message ()); LogPrint (eLogError, "BOB: Inbound tunnel read error: ", ecode.message ());
else else
{ {
receiver->bufferOffset += bytes_transferred; receiver->bufferOffset += bytes_transferred;
@ -83,7 +83,7 @@ namespace client
auto addr = context.GetAddressBook ().GetAddress (receiver->buffer); auto addr = context.GetAddressBook ().GetAddress (receiver->buffer);
if (!addr) if (!addr)
{ {
LogPrint (eLogError, "BOB: address ", receiver->buffer, " not found"); LogPrint (eLogError, "BOB: Address ", receiver->buffer, " not found");
return; return;
} }
if (addr->IsIdentHash ()) if (addr->IsIdentHash ())
@ -106,7 +106,7 @@ namespace client
if (receiver->bufferOffset < BOB_COMMAND_BUFFER_SIZE) if (receiver->bufferOffset < BOB_COMMAND_BUFFER_SIZE)
ReceiveAddress (receiver); ReceiveAddress (receiver);
else else
LogPrint (eLogError, "BOB: missing inbound address"); LogPrint (eLogError, "BOB: Missing inbound address");
} }
} }
} }
@ -268,7 +268,7 @@ namespace client
{ {
if(ecode) if(ecode)
{ {
LogPrint (eLogError, "BOB: command channel read error: ", ecode.message()); LogPrint (eLogError, "BOB: Command channel read error: ", ecode.message());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate (); Terminate ();
} }
@ -292,7 +292,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "BOB: unknown command ", command.c_str()); LogPrint (eLogError, "BOB: Unknown command ", command.c_str());
SendReplyError ("unknown command"); SendReplyError ("unknown command");
} }
} }
@ -310,7 +310,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "BOB: command channel send error: ", ecode.message ()); LogPrint (eLogError, "BOB: Command channel send error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate (); Terminate ();
} }
@ -523,7 +523,7 @@ namespace client
} }
catch (std::invalid_argument& ex) catch (std::invalid_argument& ex)
{ {
LogPrint (eLogWarning, "BOB: newkeys ", ex.what ()); LogPrint (eLogWarning, "BOB: Error on newkeys: ", ex.what ());
} }
} }
@ -880,7 +880,7 @@ namespace client
session->SendVersion (); session->SendVersion ();
} }
else else
LogPrint (eLogError, "BOB: accept error: ", ecode.message ()); LogPrint (eLogError, "BOB: Accept error: ", ecode.message ());
} }
} }
} }

42
libi2pd_client/ClientContext.cpp

@ -65,7 +65,7 @@ namespace client
std::string samAddr; i2p::config::GetOption("sam.address", samAddr); std::string samAddr; i2p::config::GetOption("sam.address", samAddr);
uint16_t samPort; i2p::config::GetOption("sam.port", samPort); uint16_t samPort; i2p::config::GetOption("sam.port", samPort);
bool singleThread; i2p::config::GetOption("sam.singlethread", singleThread); bool singleThread; i2p::config::GetOption("sam.singlethread", singleThread);
LogPrint(eLogInfo, "Clients: starting SAM bridge at ", samAddr, ":", samPort); LogPrint(eLogInfo, "Clients: Starting SAM bridge at ", samAddr, ":", samPort);
try try
{ {
m_SamBridge = new SAMBridge (samAddr, samPort, singleThread); m_SamBridge = new SAMBridge (samAddr, samPort, singleThread);
@ -83,7 +83,7 @@ namespace client
if (bob) { if (bob) {
std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr); std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr);
uint16_t bobPort; i2p::config::GetOption("bob.port", bobPort); uint16_t bobPort; i2p::config::GetOption("bob.port", bobPort);
LogPrint(eLogInfo, "Clients: starting BOB command channel at ", bobAddr, ":", bobPort); LogPrint(eLogInfo, "Clients: Starting BOB command channel at ", bobAddr, ":", bobPort);
try try
{ {
m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort); m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort);
@ -103,7 +103,7 @@ namespace client
std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr); std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr);
uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort); uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort);
bool singleThread; i2p::config::GetOption("i2cp.singlethread", singleThread); bool singleThread; i2p::config::GetOption("i2cp.singlethread", singleThread);
LogPrint(eLogInfo, "Clients: starting I2CP at ", i2cpAddr, ":", i2cpPort); LogPrint(eLogInfo, "Clients: Starting I2CP at ", i2cpAddr, ":", i2cpPort);
try try
{ {
m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort, singleThread); m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort, singleThread);
@ -130,7 +130,7 @@ namespace client
{ {
if (m_HttpProxy) if (m_HttpProxy)
{ {
LogPrint(eLogInfo, "Clients: stopping HTTP Proxy"); LogPrint(eLogInfo, "Clients: Stopping HTTP Proxy");
m_HttpProxy->Stop(); m_HttpProxy->Stop();
delete m_HttpProxy; delete m_HttpProxy;
m_HttpProxy = nullptr; m_HttpProxy = nullptr;
@ -138,7 +138,7 @@ namespace client
if (m_SocksProxy) if (m_SocksProxy)
{ {
LogPrint(eLogInfo, "Clients: stopping SOCKS Proxy"); LogPrint(eLogInfo, "Clients: Stopping SOCKS Proxy");
m_SocksProxy->Stop(); m_SocksProxy->Stop();
delete m_SocksProxy; delete m_SocksProxy;
m_SocksProxy = nullptr; m_SocksProxy = nullptr;
@ -146,21 +146,21 @@ namespace client
for (auto& it: m_ClientTunnels) for (auto& it: m_ClientTunnels)
{ {
LogPrint(eLogInfo, "Clients: stopping I2P client tunnel on port ", it.first); LogPrint(eLogInfo, "Clients: Stopping I2P client tunnel on port ", it.first);
it.second->Stop (); it.second->Stop ();
} }
m_ClientTunnels.clear (); m_ClientTunnels.clear ();
for (auto& it: m_ServerTunnels) for (auto& it: m_ServerTunnels)
{ {
LogPrint(eLogInfo, "Clients: stopping I2P server tunnel"); LogPrint(eLogInfo, "Clients: Stopping I2P server tunnel");
it.second->Stop (); it.second->Stop ();
} }
m_ServerTunnels.clear (); m_ServerTunnels.clear ();
if (m_SamBridge) if (m_SamBridge)
{ {
LogPrint(eLogInfo, "Clients: stopping SAM bridge"); LogPrint(eLogInfo, "Clients: Stopping SAM bridge");
m_SamBridge->Stop (); m_SamBridge->Stop ();
delete m_SamBridge; delete m_SamBridge;
m_SamBridge = nullptr; m_SamBridge = nullptr;
@ -168,7 +168,7 @@ namespace client
if (m_BOBCommandChannel) if (m_BOBCommandChannel)
{ {
LogPrint(eLogInfo, "Clients: stopping BOB command channel"); LogPrint(eLogInfo, "Clients: Stopping BOB command channel");
m_BOBCommandChannel->Stop (); m_BOBCommandChannel->Stop ();
delete m_BOBCommandChannel; delete m_BOBCommandChannel;
m_BOBCommandChannel = nullptr; m_BOBCommandChannel = nullptr;
@ -176,13 +176,13 @@ namespace client
if (m_I2CPServer) if (m_I2CPServer)
{ {
LogPrint(eLogInfo, "Clients: stopping I2CP"); LogPrint(eLogInfo, "Clients: Stopping I2CP");
m_I2CPServer->Stop (); m_I2CPServer->Stop ();
delete m_I2CPServer; delete m_I2CPServer;
m_I2CPServer = nullptr; m_I2CPServer = nullptr;
} }
LogPrint(eLogInfo, "Clients: stopping AddressBook"); LogPrint(eLogInfo, "Clients: Stopping AddressBook");
m_AddressBook.Stop (); m_AddressBook.Stop ();
{ {
@ -278,7 +278,7 @@ namespace client
s.read ((char *)buf, len); s.read ((char *)buf, len);
if(!keys.FromBuffer (buf, len)) if(!keys.FromBuffer (buf, len))
{ {
LogPrint (eLogError, "Clients: failed to load keyfile ", filename); LogPrint (eLogError, "Clients: Failed to load keyfile ", filename);
success = false; success = false;
} }
else else
@ -287,7 +287,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "Clients: can't open file ", fullPath, " Creating new one with signature type ", sigType, " crypto type ", cryptoType); LogPrint (eLogError, "Clients: Can't open file ", fullPath, " Creating new one with signature type ", sigType, " crypto type ", cryptoType);
keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType); keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType);
std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out); std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
size_t len = keys.GetFullLen (); size_t len = keys.GetFullLen ();
@ -510,7 +510,7 @@ namespace client
if (tunConf.empty ()) if (tunConf.empty ())
tunConf = i2p::fs::DataDirPath ("tunnels.conf"); tunConf = i2p::fs::DataDirPath ("tunnels.conf");
LogPrint(eLogDebug, "Clients: tunnels config file: ", tunConf); LogPrint(eLogDebug, "Clients: Tunnels config file: ", tunConf);
ReadTunnels (tunConf, numClientTunnels, numServerTunnels); ReadTunnels (tunConf, numClientTunnels, numServerTunnels);
std::string tunDir; i2p::config::GetOption("tunnelsdir", tunDir); std::string tunDir; i2p::config::GetOption("tunnelsdir", tunDir);
@ -525,7 +525,7 @@ namespace client
for (auto& it: files) for (auto& it: files)
{ {
if (it.substr(it.size() - 5) != ".conf") continue; // skip files which not ends with ".conf" if (it.substr(it.size() - 5) != ".conf") continue; // skip files which not ends with ".conf"
LogPrint(eLogDebug, "Clients: tunnels extra config file: ", it); LogPrint(eLogDebug, "Clients: Tunnels extra config file: ", it);
ReadTunnels (it, numClientTunnels, numServerTunnels); ReadTunnels (it, numClientTunnels, numServerTunnels);
} }
} }
@ -754,7 +754,7 @@ namespace client
auto serverTunnel = std::make_shared<I2PUDPServerTunnel>(name, localDestination, localAddress, endpoint, port, gzip); auto serverTunnel = std::make_shared<I2PUDPServerTunnel>(name, localDestination, localAddress, endpoint, port, gzip);
if(!isUniqueLocal) if(!isUniqueLocal)
{ {
LogPrint(eLogInfo, "Clients: disabling loopback address mapping"); LogPrint(eLogInfo, "Clients: Disabling loopback address mapping");
serverTunnel->SetUniqueLocal(isUniqueLocal); serverTunnel->SetUniqueLocal(isUniqueLocal);
} }
std::lock_guard<std::mutex> lock(m_ForwardsMutex); std::lock_guard<std::mutex> lock(m_ForwardsMutex);
@ -787,7 +787,7 @@ namespace client
serverTunnel->SetLocalAddress (address); serverTunnel->SetLocalAddress (address);
if(!isUniqueLocal) if(!isUniqueLocal)
{ {
LogPrint(eLogInfo, "Clients: disabling loopback address mapping"); LogPrint(eLogInfo, "Clients: Disabling loopback address mapping");
serverTunnel->SetUniqueLocal(isUniqueLocal); serverTunnel->SetUniqueLocal(isUniqueLocal);
} }
if (accessList.length () > 0) if (accessList.length () > 0)
@ -851,7 +851,7 @@ namespace client
std::string httpOutProxyURL; i2p::config::GetOption("httpproxy.outproxy", httpOutProxyURL); std::string httpOutProxyURL; i2p::config::GetOption("httpproxy.outproxy", httpOutProxyURL);
bool httpAddresshelper; i2p::config::GetOption("httpproxy.addresshelper", httpAddresshelper); bool httpAddresshelper; i2p::config::GetOption("httpproxy.addresshelper", httpAddresshelper);
i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType); i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType);
LogPrint(eLogInfo, "Clients: starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort); LogPrint(eLogInfo, "Clients: Starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort);
if (httpProxyKeys.length () > 0) if (httpProxyKeys.length () > 0)
{ {
i2p::data::PrivateKeys keys; i2p::data::PrivateKeys keys;
@ -863,7 +863,7 @@ namespace client
if (localDestination) localDestination->Acquire (); if (localDestination) localDestination->Acquire ();
} }
else else
LogPrint(eLogError, "Clients: failed to load HTTP Proxy key"); LogPrint(eLogError, "Clients: Failed to load HTTP Proxy key");
} }
try try
{ {
@ -893,7 +893,7 @@ namespace client
std::string socksOutProxyAddr; i2p::config::GetOption("socksproxy.outproxy", socksOutProxyAddr); std::string socksOutProxyAddr; i2p::config::GetOption("socksproxy.outproxy", socksOutProxyAddr);
uint16_t socksOutProxyPort; i2p::config::GetOption("socksproxy.outproxyport", socksOutProxyPort); uint16_t socksOutProxyPort; i2p::config::GetOption("socksproxy.outproxyport", socksOutProxyPort);
i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype", sigType); i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype", sigType);
LogPrint(eLogInfo, "Clients: starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort); LogPrint(eLogInfo, "Clients: Starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort);
if (httpProxyKeys == socksProxyKeys && m_HttpProxy) if (httpProxyKeys == socksProxyKeys && m_HttpProxy)
{ {
localDestination = m_HttpProxy->GetLocalDestination (); localDestination = m_HttpProxy->GetLocalDestination ();
@ -910,7 +910,7 @@ namespace client
if (localDestination) localDestination->Acquire (); if (localDestination) localDestination->Acquire ();
} }
else else
LogPrint(eLogError, "Clients: failed to load SOCKS Proxy key"); LogPrint(eLogError, "Clients: Failed to load SOCKS Proxy key");
} }
try try
{ {

40
libi2pd_client/HTTPProxy.cpp

@ -124,9 +124,9 @@ namespace proxy {
void HTTPReqHandler::AsyncSockRead() void HTTPReqHandler::AsyncSockRead()
{ {
LogPrint(eLogDebug, "HTTPProxy: async sock read"); LogPrint(eLogDebug, "HTTPProxy: Async sock read");
if (!m_sock) { if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read"); LogPrint(eLogError, "HTTPProxy: No socket for read");
return; return;
} }
m_sock->async_read_some(boost::asio::buffer(m_recv_chunk, sizeof(m_recv_chunk)), m_sock->async_read_some(boost::asio::buffer(m_recv_chunk, sizeof(m_recv_chunk)),
@ -138,13 +138,13 @@ namespace proxy {
if (Kill()) return; if (Kill()) return;
if (m_sock) if (m_sock)
{ {
LogPrint(eLogDebug, "HTTPProxy: close sock"); LogPrint(eLogDebug, "HTTPProxy: Close sock");
m_sock->close(); m_sock->close();
m_sock = nullptr; m_sock = nullptr;
} }
if(m_proxysock) if(m_proxysock)
{ {
LogPrint(eLogDebug, "HTTPProxy: close proxysock"); LogPrint(eLogDebug, "HTTPProxy: Close proxysock");
if(m_proxysock->is_open()) if(m_proxysock->is_open())
m_proxysock->close(); m_proxysock->close();
m_proxysock = nullptr; m_proxysock = nullptr;
@ -269,13 +269,13 @@ namespace proxy {
return false; /* need more data */ return false; /* need more data */
if (m_req_len < 0) { if (m_req_len < 0) {
LogPrint(eLogError, "HTTPProxy: unable to parse request"); LogPrint(eLogError, "HTTPProxy: Unable to parse request");
GenericProxyError(tr("Invalid request"), tr("Proxy unable to parse your request")); GenericProxyError(tr("Invalid request"), tr("Proxy unable to parse your request"));
return true; /* parse error */ return true; /* parse error */
} }
/* parsing success, now let's look inside request */ /* parsing success, now let's look inside request */
LogPrint(eLogDebug, "HTTPProxy: requested: ", m_ClientRequest.uri); LogPrint(eLogDebug, "HTTPProxy: Requested: ", m_ClientRequest.uri);
m_RequestURL.parse(m_ClientRequest.uri); m_RequestURL.parse(m_ClientRequest.uri);
bool m_Confirm; bool m_Confirm;
@ -284,14 +284,14 @@ namespace proxy {
{ {
if (!m_Addresshelper) if (!m_Addresshelper)
{ {
LogPrint(eLogWarning, "HTTPProxy: addresshelper request rejected"); LogPrint(eLogWarning, "HTTPProxy: Addresshelper request rejected");
GenericProxyError(tr("Invalid request"), tr("addresshelper is not supported")); GenericProxyError(tr("Invalid request"), tr("addresshelper is not supported"));
return true; return true;
} }
if (!i2p::client::context.GetAddressBook ().FindAddress (m_RequestURL.host) || m_Confirm) if (!i2p::client::context.GetAddressBook ().FindAddress (m_RequestURL.host) || m_Confirm)
{ {
i2p::client::context.GetAddressBook ().InsertAddress (m_RequestURL.host, jump); i2p::client::context.GetAddressBook ().InsertAddress (m_RequestURL.host, jump);
LogPrint (eLogInfo, "HTTPProxy: added address from addresshelper for ", m_RequestURL.host); LogPrint (eLogInfo, "HTTPProxy: Added address from addresshelper for ", m_RequestURL.host);
std::string full_url = m_RequestURL.to_string(); std::string full_url = m_RequestURL.to_string();
std::stringstream ss; std::stringstream ss;
ss << tr("Host") <<" " << m_RequestURL.host << " " << tr("added to router's addressbook from helper") << ". "; ss << tr("Host") <<" " << m_RequestURL.host << " " << tr("added to router's addressbook from helper") << ". ";
@ -375,13 +375,13 @@ namespace proxy {
} }
} else { } else {
if(m_OutproxyUrl.size()) { if(m_OutproxyUrl.size()) {
LogPrint (eLogDebug, "HTTPProxy: use outproxy ", m_OutproxyUrl); LogPrint (eLogDebug, "HTTPProxy: Using outproxy ", m_OutproxyUrl);
if(m_ProxyURL.parse(m_OutproxyUrl)) if(m_ProxyURL.parse(m_OutproxyUrl))
ForwardToUpstreamProxy(); ForwardToUpstreamProxy();
else else
GenericProxyError(tr("Outproxy failure"), tr("bad outproxy settings")); GenericProxyError(tr("Outproxy failure"), tr("bad outproxy settings"));
} else { } else {
LogPrint (eLogWarning, "HTTPProxy: outproxy failure for ", dest_host, ": no outproxy enabled"); LogPrint (eLogWarning, "HTTPProxy: Outproxy failure for ", dest_host, ": no outproxy enabled");
std::stringstream ss; ss << tr("Host") << " " << dest_host << " " << tr("not inside I2P network, but outproxy is not enabled"); std::stringstream ss; ss << tr("Host") << " " << dest_host << " " << tr("not inside I2P network, but outproxy is not enabled");
GenericProxyError(tr("Outproxy failure"), ss.str()); GenericProxyError(tr("Outproxy failure"), ss.str());
} }
@ -404,7 +404,7 @@ namespace proxy {
m_send_buf = m_ClientRequest.to_string(); m_send_buf = m_ClientRequest.to_string();
m_send_buf.append(m_recv_buf); m_send_buf.append(m_recv_buf);
/* connect to destination */ /* connect to destination */
LogPrint(eLogDebug, "HTTPProxy: connecting to host ", dest_host, ":", dest_port); LogPrint(eLogDebug, "HTTPProxy: Connecting to host ", dest_host, ":", dest_port);
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete, GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), dest_host, dest_port); shared_from_this(), std::placeholders::_1), dest_host, dest_port);
return true; return true;
@ -412,7 +412,7 @@ namespace proxy {
void HTTPReqHandler::ForwardToUpstreamProxy() void HTTPReqHandler::ForwardToUpstreamProxy()
{ {
LogPrint(eLogDebug, "HTTPProxy: forward to upstream"); LogPrint(eLogDebug, "HTTPProxy: Forwarded to upstream");
// build http request // build http request
m_ClientRequestURL = m_RequestURL; m_ClientRequestURL = m_RequestURL;
@ -490,7 +490,7 @@ namespace proxy {
} }
uint16_t port = m_RequestURL.port; uint16_t port = m_RequestURL.port;
if(!port) port = 80; if(!port) port = 80;
LogPrint(eLogDebug, "HTTPProxy: connected to socks upstream"); LogPrint(eLogDebug, "HTTPProxy: Connected to SOCKS upstream");
std::string host = m_RequestURL.host; std::string host = m_RequestURL.host;
std::size_t reqsize = 0; std::size_t reqsize = 0;
@ -517,14 +517,14 @@ namespace proxy {
void HTTPReqHandler::HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transferred) void HTTPReqHandler::HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transferred)
{ {
LogPrint(eLogDebug, "HTTPProxy: upstream socks handshake sent"); LogPrint(eLogDebug, "HTTPProxy: Upstream SOCKS handshake sent");
if(ec) GenericProxyError(tr("Cannot negotiate with socks proxy"), ec.message()); if(ec) GenericProxyError(tr("Cannot negotiate with socks proxy"), ec.message());
else m_proxysock->async_read_some(boost::asio::buffer(m_socks_buf, 8), std::bind(&HTTPReqHandler::HandleSocksProxyReply, this, std::placeholders::_1, std::placeholders::_2)); else m_proxysock->async_read_some(boost::asio::buffer(m_socks_buf, 8), std::bind(&HTTPReqHandler::HandleSocksProxyReply, this, std::placeholders::_1, std::placeholders::_2));
} }
void HTTPReqHandler::HandoverToUpstreamProxy() void HTTPReqHandler::HandoverToUpstreamProxy()
{ {
LogPrint(eLogDebug, "HTTPProxy: handover to socks proxy"); LogPrint(eLogDebug, "HTTPProxy: Handover to SOCKS proxy");
auto connection = std::make_shared<i2p::client::TCPIPPipe>(GetOwner(), m_proxysock, m_sock); auto connection = std::make_shared<i2p::client::TCPIPPipe>(GetOwner(), m_proxysock, m_sock);
m_sock = nullptr; m_sock = nullptr;
m_proxysock = nullptr; m_proxysock = nullptr;
@ -576,7 +576,7 @@ namespace proxy {
}); });
} else { } else {
m_send_buf = m_ClientRequestBuffer.str(); m_send_buf = m_ClientRequestBuffer.str();
LogPrint(eLogDebug, "HTTPProxy: send ", m_send_buf.size(), " bytes"); LogPrint(eLogDebug, "HTTPProxy: Send ", m_send_buf.size(), " bytes");
boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&](const boost::system::error_code & ec, std::size_t transferred) boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&](const boost::system::error_code & ec, std::size_t transferred)
{ {
if(ec) GenericProxyError(tr("failed to send request to upstream"), ec.message()); if(ec) GenericProxyError(tr("failed to send request to upstream"), ec.message());
@ -606,7 +606,7 @@ namespace proxy {
void HTTPReqHandler::HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec) void HTTPReqHandler::HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec)
{ {
if(!ec) { if(!ec) {
LogPrint(eLogDebug, "HTTPProxy: connected to http upstream"); LogPrint(eLogDebug, "HTTPProxy: Connected to http upstream");
GenericProxyError(tr("cannot connect"), tr("http out proxy not implemented")); GenericProxyError(tr("cannot connect"), tr("http out proxy not implemented"));
} else GenericProxyError(tr("cannot connect to upstream http proxy"), ec.message()); } else GenericProxyError(tr("cannot connect to upstream http proxy"), ec.message());
} }
@ -614,10 +614,10 @@ namespace proxy {
/* will be called after some data received from client */ /* will be called after some data received from client */
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len) void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{ {
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes, recv buf: ", m_recv_buf.length(), ", send buf: ", m_send_buf.length()); LogPrint(eLogDebug, "HTTPProxy: Sock recv: ", len, " bytes, recv buf: ", m_recv_buf.length(), ", send buf: ", m_send_buf.length());
if(ecode) if(ecode)
{ {
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode); LogPrint(eLogWarning, "HTTPProxy: Sock recv got error: ", ecode);
Terminate(); Terminate();
return; return;
} }
@ -640,7 +640,7 @@ namespace proxy {
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream) void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{ {
if (!stream) { if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info"); LogPrint (eLogError, "HTTPProxy: Error when creating the stream, check the previous warnings for more info");
GenericProxyError(tr("Host is down"), tr("Can't create connection to requested host, it may be down. Please try again later.")); GenericProxyError(tr("Host is down"), tr("Can't create connection to requested host, it may be down. Please try again later."));
return; return;
} }

62
libi2pd_client/I2CP.cpp

@ -59,7 +59,7 @@ namespace client
if (m_Decryptor) if (m_Decryptor)
return m_Decryptor->Decrypt (encrypted, data); return m_Decryptor->Decrypt (encrypted, data);
else else
LogPrint (eLogError, "I2CP: decryptor is not set"); LogPrint (eLogError, "I2CP: Decryptor is not set");
return false; return false;
} }
@ -392,7 +392,7 @@ namespace client
if (m_SessionID != 0xFFFF) if (m_SessionID != 0xFFFF)
{ {
m_Owner.RemoveSession (GetSessionID ()); m_Owner.RemoveSession (GetSessionID ());
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " terminated"); LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " terminated");
m_SessionID = 0xFFFF; m_SessionID = 0xFFFF;
} }
} }
@ -416,7 +416,7 @@ namespace client
m_SendQueue.Add (sendBuf); m_SendQueue.Add (sendBuf);
else else
{ {
LogPrint (eLogWarning, "I2CP: send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE); LogPrint (eLogWarning, "I2CP: Send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE);
return; return;
} }
} }
@ -524,7 +524,7 @@ namespace client
size_t offset = identity->FromBuffer (buf, len); size_t offset = identity->FromBuffer (buf, len);
if (!offset) if (!offset)
{ {
LogPrint (eLogError, "I2CP: create session malformed identity"); LogPrint (eLogError, "I2CP: Create session malformed identity");
SendSessionStatusMessage (3); // invalid SendSessionStatusMessage (3); // invalid
return; return;
} }
@ -532,7 +532,7 @@ namespace client
offset += 2; offset += 2;
if (optionsSize > len - offset) if (optionsSize > len - offset)
{ {
LogPrint (eLogError, "I2CP: options size ", optionsSize, "exceeds message size"); LogPrint (eLogError, "I2CP: Options size ", optionsSize, "exceeds message size");
SendSessionStatusMessage (3); // invalid SendSessionStatusMessage (3); // invalid
return; return;
} }
@ -550,18 +550,18 @@ namespace client
std::make_shared<I2CPDestination>(m_Owner.GetService (), shared_from_this (), identity, true, params): std::make_shared<I2CPDestination>(m_Owner.GetService (), shared_from_this (), identity, true, params):
std::make_shared<RunnableI2CPDestination>(shared_from_this (), identity, true, params); std::make_shared<RunnableI2CPDestination>(shared_from_this (), identity, true, params);
SendSessionStatusMessage (1); // created SendSessionStatusMessage (1); // created
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " created"); LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " created");
m_Destination->Start (); m_Destination->Start ();
} }
else else
{ {
LogPrint (eLogError, "I2CP: session already exists"); LogPrint (eLogError, "I2CP: Session already exists");
SendSessionStatusMessage (4); // refused SendSessionStatusMessage (4); // refused
} }
} }
else else
{ {
LogPrint (eLogError, "I2CP: create session signature verification failed"); LogPrint (eLogError, "I2CP: Create session signature verification failed");
SendSessionStatusMessage (3); // invalid SendSessionStatusMessage (3); // invalid
} }
} }
@ -569,7 +569,7 @@ namespace client
void I2CPSession::DestroySessionMessageHandler (const uint8_t * buf, size_t len) void I2CPSession::DestroySessionMessageHandler (const uint8_t * buf, size_t len)
{ {
SendSessionStatusMessage (0); // destroy SendSessionStatusMessage (0); // destroy
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " destroyed"); LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " destroyed");
Terminate (); Terminate ();
} }
@ -604,29 +604,29 @@ namespace client
{ {
if(m_Destination->Reconfigure(opts)) if(m_Destination->Reconfigure(opts))
{ {
LogPrint(eLogInfo, "I2CP: reconfigured destination"); LogPrint(eLogInfo, "I2CP: Reconfigured destination");
status = 2; // updated status = 2; // updated
} }
else else
LogPrint(eLogWarning, "I2CP: failed to reconfigure destination"); LogPrint(eLogWarning, "I2CP: Failed to reconfigure destination");
} }
else else
LogPrint(eLogError, "I2CP: invalid reconfigure message signature"); LogPrint(eLogError, "I2CP: Invalid reconfigure message signature");
} }
else else
LogPrint(eLogError, "I2CP: mapping size mismatch"); LogPrint(eLogError, "I2CP: Mapping size mismatch");
} }
else else
LogPrint(eLogError, "I2CP: destination mismatch"); LogPrint(eLogError, "I2CP: Destination mismatch");
} }
else else
LogPrint(eLogError, "I2CP: malfromed destination"); LogPrint(eLogError, "I2CP: Malfromed destination");
} }
else else
LogPrint(eLogError, "I2CP: session mismatch"); LogPrint(eLogError, "I2CP: Session mismatch");
} }
else else
LogPrint(eLogError, "I2CP: short message"); LogPrint(eLogError, "I2CP: Short message");
SendSessionStatusMessage (status); SendSessionStatusMessage (status);
} }
@ -668,7 +668,7 @@ namespace client
} }
} }
else else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID); LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
} }
void I2CPSession::CreateLeaseSet2MessageHandler (const uint8_t * buf, size_t len) void I2CPSession::CreateLeaseSet2MessageHandler (const uint8_t * buf, size_t len)
@ -683,7 +683,7 @@ namespace client
i2p::data::LeaseSet2 ls (storeType, buf + offset, len - offset); // outer layer only for encrypted i2p::data::LeaseSet2 ls (storeType, buf + offset, len - offset); // outer layer only for encrypted
if (!ls.IsValid ()) if (!ls.IsValid ())
{ {
LogPrint (eLogError, "I2CP: invalid LeaseSet2 of type ", storeType); LogPrint (eLogError, "I2CP: Invalid LeaseSet2 of type ", storeType);
return; return;
} }
offset += ls.GetBufferLen (); offset += ls.GetBufferLen ();
@ -709,7 +709,7 @@ namespace client
} }
} }
else else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID); LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
} }
void I2CPSession::SendMessageMessageHandler (const uint8_t * buf, size_t len) void I2CPSession::SendMessageMessageHandler (const uint8_t * buf, size_t len)
@ -735,14 +735,14 @@ namespace client
m_Destination->SendMsgTo (buf + offset, payloadLen, identity.GetIdentHash (), nonce); m_Destination->SendMsgTo (buf + offset, payloadLen, identity.GetIdentHash (), nonce);
} }
else else
LogPrint(eLogError, "I2CP: cannot send message, too big"); LogPrint(eLogError, "I2CP: Cannot send message, too big");
} }
else else
LogPrint(eLogError, "I2CP: invalid identity"); LogPrint(eLogError, "I2CP: Invalid identity");
} }
} }
else else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID); LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
} }
void I2CPSession::SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len) void I2CPSession::SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len)
@ -770,7 +770,7 @@ namespace client
if (!addr || !addr->IsIdentHash ()) if (!addr || !addr->IsIdentHash ())
{ {
// TODO: handle blinded addresses // TODO: handle blinded addresses
LogPrint (eLogError, "I2CP: address ", name, " not found"); LogPrint (eLogError, "I2CP: Address ", name, " not found");
SendHostReplyMessage (requestID, nullptr); SendHostReplyMessage (requestID, nullptr);
return; return;
} }
@ -779,7 +779,7 @@ namespace client
break; break;
} }
default: default:
LogPrint (eLogError, "I2CP: request type ", (int)buf[10], " is not supported"); LogPrint (eLogError, "I2CP: Request type ", (int)buf[10], " is not supported");
SendHostReplyMessage (requestID, nullptr); SendHostReplyMessage (requestID, nullptr);
return; return;
} }
@ -805,7 +805,7 @@ namespace client
SendHostReplyMessage (requestID, nullptr); SendHostReplyMessage (requestID, nullptr);
} }
else else
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID); LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
} }
void I2CPSession::SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity) void I2CPSession::SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity)
@ -900,7 +900,7 @@ namespace client
m_SendQueue.Add (sendBuf); m_SendQueue.Add (sendBuf);
else else
{ {
LogPrint (eLogWarning, "I2CP: send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE); LogPrint (eLogWarning, "I2CP: Send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE);
return; return;
} }
} }
@ -980,15 +980,15 @@ namespace client
auto ep = socket->remote_endpoint (ec); auto ep = socket->remote_endpoint (ec);
if (!ec) if (!ec)
{ {
LogPrint (eLogDebug, "I2CP: new connection from ", ep); LogPrint (eLogDebug, "I2CP: New connection from ", ep);
auto session = std::make_shared<I2CPSession>(*this, socket); auto session = std::make_shared<I2CPSession>(*this, socket);
session->Start (); session->Start ();
} }
else else
LogPrint (eLogError, "I2CP: incoming connection error ", ec.message ()); LogPrint (eLogError, "I2CP: Incoming connection error ", ec.message ());
} }
else else
LogPrint (eLogError, "I2CP: accept error: ", ecode.message ()); LogPrint (eLogError, "I2CP: Accept error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Accept (); Accept ();
@ -999,7 +999,7 @@ namespace client
if (!session) return false; if (!session) return false;
if (!m_Sessions.insert({session->GetSessionID (), session}).second) if (!m_Sessions.insert({session->GetSessionID (), session}).second)
{ {
LogPrint (eLogError, "I2CP: duplicate session id ", session->GetSessionID ()); LogPrint (eLogError, "I2CP: Duplicate session id ", session->GetSessionID ());
return false; return false;
} }
return true; return true;

24
libi2pd_client/I2PService.cpp

@ -193,7 +193,7 @@ namespace client
std::placeholders::_1, std::placeholders::_2)); std::placeholders::_1, std::placeholders::_2));
} }
else else
LogPrint(eLogError, "TCPIPPipe: upstream receive: no socket"); LogPrint(eLogError, "TCPIPPipe: Upstream receive: No socket");
} }
void TCPIPPipe::AsyncReceiveDownstream() void TCPIPPipe::AsyncReceiveDownstream()
@ -204,14 +204,14 @@ namespace client
std::placeholders::_1, std::placeholders::_2)); std::placeholders::_1, std::placeholders::_2));
} }
else else
LogPrint(eLogError, "TCPIPPipe: downstream receive: no socket"); LogPrint(eLogError, "TCPIPPipe: Downstream receive: No socket");
} }
void TCPIPPipe::UpstreamWrite(size_t len) void TCPIPPipe::UpstreamWrite(size_t len)
{ {
if (m_up) if (m_up)
{ {
LogPrint(eLogDebug, "TCPIPPipe: upstream: ", (int) len, " bytes written"); LogPrint(eLogDebug, "TCPIPPipe: Upstream: ", (int) len, " bytes written");
boost::asio::async_write(*m_up, boost::asio::buffer(m_upstream_buf, len), boost::asio::async_write(*m_up, boost::asio::buffer(m_upstream_buf, len),
boost::asio::transfer_all(), boost::asio::transfer_all(),
std::bind(&TCPIPPipe::HandleUpstreamWrite, std::bind(&TCPIPPipe::HandleUpstreamWrite,
@ -219,14 +219,14 @@ namespace client
std::placeholders::_1)); std::placeholders::_1));
} }
else else
LogPrint(eLogError, "TCPIPPipe: upstream write: no socket"); LogPrint(eLogError, "TCPIPPipe: Upstream write: no socket");
} }
void TCPIPPipe::DownstreamWrite(size_t len) void TCPIPPipe::DownstreamWrite(size_t len)
{ {
if (m_down) if (m_down)
{ {
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) len, " bytes written"); LogPrint(eLogDebug, "TCPIPPipe: Downstream: ", (int) len, " bytes written");
boost::asio::async_write(*m_down, boost::asio::buffer(m_downstream_buf, len), boost::asio::async_write(*m_down, boost::asio::buffer(m_downstream_buf, len),
boost::asio::transfer_all(), boost::asio::transfer_all(),
std::bind(&TCPIPPipe::HandleDownstreamWrite, std::bind(&TCPIPPipe::HandleDownstreamWrite,
@ -234,16 +234,16 @@ namespace client
std::placeholders::_1)); std::placeholders::_1));
} }
else else
LogPrint(eLogError, "TCPIPPipe: downstream write: no socket"); LogPrint(eLogError, "TCPIPPipe: Downstream write: No socket");
} }
void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
{ {
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) bytes_transfered, " bytes received"); LogPrint(eLogDebug, "TCPIPPipe: Downstream: ", (int) bytes_transfered, " bytes received");
if (ecode) if (ecode)
{ {
LogPrint(eLogError, "TCPIPPipe: downstream read error:" , ecode.message()); LogPrint(eLogError, "TCPIPPipe: Downstream read error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate(); Terminate();
} else { } else {
@ -256,7 +256,7 @@ namespace client
void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) { void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) {
if (ecode) if (ecode)
{ {
LogPrint(eLogError, "TCPIPPipe: downstream write error:" , ecode.message()); LogPrint(eLogError, "TCPIPPipe: Downstream write error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate(); Terminate();
} }
@ -267,7 +267,7 @@ namespace client
void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) { void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) {
if (ecode) if (ecode)
{ {
LogPrint(eLogError, "TCPIPPipe: upstream write error:" , ecode.message()); LogPrint(eLogError, "TCPIPPipe: Upstream write error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate(); Terminate();
} }
@ -277,10 +277,10 @@ namespace client
void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
{ {
LogPrint(eLogDebug, "TCPIPPipe: upstream ", (int)bytes_transfered, " bytes received"); LogPrint(eLogDebug, "TCPIPPipe: Upstream ", (int)bytes_transfered, " bytes received");
if (ecode) if (ecode)
{ {
LogPrint(eLogError, "TCPIPPipe: upstream read error:" , ecode.message()); LogPrint(eLogError, "TCPIPPipe: Upstream read error:" , ecode.message());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate(); Terminate();
} else { } else {

46
libi2pd_client/I2PTunnel.cpp

@ -87,7 +87,7 @@ namespace client
boost::system::error_code ec; boost::system::error_code ec;
sock->bind (boost::asio::ip::tcp::endpoint (ourIP, 0), ec); sock->bind (boost::asio::ip::tcp::endpoint (ourIP, 0), ec);
if (ec) if (ec)
LogPrint (eLogError, "I2PTunnel: can't bind ourIP to ", ourIP.to_string (), ": ", ec.message ()); LogPrint (eLogError, "I2PTunnel: Can't bind ourIP to ", ourIP.to_string (), ": ", ec.message ());
} }
#endif #endif
@ -122,7 +122,7 @@ namespace client
boost::system::error_code ec; boost::system::error_code ec;
m_Socket->bind (boost::asio::ip::tcp::endpoint (localAddress, 0), ec); m_Socket->bind (boost::asio::ip::tcp::endpoint (localAddress, 0), ec);
if (ec) if (ec)
LogPrint (eLogError, "I2PTunnel: can't bind to ", localAddress.to_string (), ": ", ec.message ()); LogPrint (eLogError, "I2PTunnel: Can't bind to ", localAddress.to_string (), ": ", ec.message ());
} }
Connect (false); Connect (false);
} }
@ -155,7 +155,7 @@ namespace client
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
{ {
LogPrint (eLogError, "I2PTunnel: read error: ", ecode.message ()); LogPrint (eLogError, "I2PTunnel: Read error: ", ecode.message ());
Terminate (); Terminate ();
} }
} }
@ -183,7 +183,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "I2PTunnel: write error: ", ecode.message ()); LogPrint (eLogError, "I2PTunnel: Write error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate (); Terminate ();
} }
@ -221,7 +221,7 @@ namespace client
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
{ {
LogPrint (eLogError, "I2PTunnel: stream read error: ", ecode.message ()); LogPrint (eLogError, "I2PTunnel: Stream read error: ", ecode.message ());
if (bytes_transferred > 0) if (bytes_transferred > 0)
Write (m_StreamBuffer, bytes_transferred); // postpone termination Write (m_StreamBuffer, bytes_transferred); // postpone termination
else if (ecode == boost::asio::error::timed_out && m_Stream && m_Stream->IsOpen ()) else if (ecode == boost::asio::error::timed_out && m_Stream && m_Stream->IsOpen ())
@ -246,12 +246,12 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "I2PTunnel: connect error: ", ecode.message ()); LogPrint (eLogError, "I2PTunnel: Connect error: ", ecode.message ());
Terminate (); Terminate ();
} }
else else
{ {
LogPrint (eLogDebug, "I2PTunnel: connected"); LogPrint (eLogDebug, "I2PTunnel: Connected");
if (m_IsQuiet) if (m_IsQuiet)
StreamReceive (); StreamReceive ();
else else
@ -505,7 +505,7 @@ namespace client
if (stream) if (stream)
{ {
if (Kill()) return; if (Kill()) return;
LogPrint (eLogDebug, "I2PTunnel: new connection"); LogPrint (eLogDebug, "I2PTunnel: New connection");
auto connection = std::make_shared<I2PTunnelConnection>(GetOwner(), m_Socket, stream); auto connection = std::make_shared<I2PTunnelConnection>(GetOwner(), m_Socket, stream);
GetOwner()->AddHandler (connection); GetOwner()->AddHandler (connection);
connection->I2PConnect (); connection->I2PConnect ();
@ -681,7 +681,7 @@ namespace client
} }
auto addr = ep.address (); auto addr = ep.address ();
LogPrint (eLogInfo, "I2PTunnel: server tunnel ", (*it).host_name (), " has been resolved to ", addr); LogPrint (eLogInfo, "I2PTunnel: Server tunnel ", (*it).host_name (), " has been resolved to ", addr);
m_Endpoint.address (addr); m_Endpoint.address (addr);
Accept (); Accept ();
} }
@ -702,7 +702,7 @@ namespace client
if (!ec) if (!ec)
m_LocalAddress.reset (new boost::asio::ip::address (addr)); m_LocalAddress.reset (new boost::asio::ip::address (addr));
else else
LogPrint (eLogError, "I2PTunnel: can't set local address ", localAddress); LogPrint (eLogError, "I2PTunnel: Can't set local address ", localAddress);
} }
void I2PServerTunnel::Accept () void I2PServerTunnel::Accept ()
@ -829,7 +829,7 @@ namespace client
if (s->Identity.GetLL()[0] == ih.GetLL()[0] && remotePort == s->RemotePort) if (s->Identity.GetLL()[0] == ih.GetLL()[0] && remotePort == s->RemotePort)
{ {
/** found existing session */ /** found existing session */
LogPrint(eLogDebug, "UDPServer: found session ", s->IPSocket.local_endpoint(), " ", ih.ToBase32()); LogPrint(eLogDebug, "UDPServer: Found session ", s->IPSocket.local_endpoint(), " ", ih.ToBase32());
return s; return s;
} }
} }
@ -874,7 +874,7 @@ namespace client
{ {
if(!ecode) if(!ecode)
{ {
LogPrint(eLogDebug, "UDPSession: forward ", len, "B from ", FromEndpoint); LogPrint(eLogDebug, "UDPSession: Forward ", len, "B from ", FromEndpoint);
auto ts = i2p::util::GetMillisecondsSinceEpoch(); auto ts = i2p::util::GetMillisecondsSinceEpoch();
auto session = m_Destination->GetSession (Identity); auto session = m_Destination->GetSession (Identity);
if (ts > LastActivity + I2P_UDP_REPLIABLE_DATAGRAM_INTERVAL) if (ts > LastActivity + I2P_UDP_REPLIABLE_DATAGRAM_INTERVAL)
@ -892,7 +892,7 @@ namespace client
numPackets++; numPackets++;
} }
if (numPackets > 0) if (numPackets > 0)
LogPrint(eLogDebug, "UDPSession: forward more ", numPackets, "packets B from ", FromEndpoint); LogPrint(eLogDebug, "UDPSession: Forward more ", numPackets, "packets B from ", FromEndpoint);
m_Destination->FlushSendQueue (session); m_Destination->FlushSendQueue (session);
LastActivity = ts; LastActivity = ts;
Receive(); Receive();
@ -920,7 +920,7 @@ namespace client
auto dgram = m_LocalDest->GetDatagramDestination(); auto dgram = m_LocalDest->GetDatagramDestination();
if (dgram) dgram->ResetReceiver(); if (dgram) dgram->ResetReceiver();
LogPrint(eLogInfo, "UDPServer: done"); LogPrint(eLogInfo, "UDPServer: Done");
} }
void I2PUDPServerTunnel::Start() void I2PUDPServerTunnel::Start()
@ -997,7 +997,7 @@ namespace client
return; return;
} }
if(!m_RemoteIdent) { if(!m_RemoteIdent) {
LogPrint(eLogWarning, "UDP Client: remote endpoint not resolved yet"); LogPrint(eLogWarning, "UDP Client: Remote endpoint not resolved yet");
RecvFromLocal(); RecvFromLocal();
return; // drop, remote not resolved return; // drop, remote not resolved
} }
@ -1016,7 +1016,7 @@ namespace client
} }
// send off to remote i2p destination // send off to remote i2p destination
auto ts = i2p::util::GetMillisecondsSinceEpoch(); auto ts = i2p::util::GetMillisecondsSinceEpoch();
LogPrint(eLogDebug, "UDP Client: send ", transferred, " to ", m_RemoteIdent->ToBase32(), ":", RemotePort); LogPrint(eLogDebug, "UDP Client: Send ", transferred, " to ", m_RemoteIdent->ToBase32(), ":", RemotePort);
auto session = m_LocalDest->GetDatagramDestination()->GetSession (*m_RemoteIdent); auto session = m_LocalDest->GetDatagramDestination()->GetSession (*m_RemoteIdent);
if (ts > m_LastSession->second + I2P_UDP_REPLIABLE_DATAGRAM_INTERVAL) if (ts > m_LastSession->second + I2P_UDP_REPLIABLE_DATAGRAM_INTERVAL)
m_LocalDest->GetDatagramDestination()->SendDatagram (session, m_RecvBuff, transferred, remotePort, RemotePort); m_LocalDest->GetDatagramDestination()->SendDatagram (session, m_RecvBuff, transferred, remotePort, RemotePort);
@ -1035,7 +1035,7 @@ namespace client
numPackets++; numPackets++;
} }
if (numPackets) if (numPackets)
LogPrint(eLogDebug, "UDP Client: sent ", numPackets, " more packets to ", m_RemoteIdent->ToBase32()); LogPrint(eLogDebug, "UDP Client: Sent ", numPackets, " more packets to ", m_RemoteIdent->ToBase32());
m_LocalDest->GetDatagramDestination()->FlushSendQueue (session); m_LocalDest->GetDatagramDestination()->FlushSendQueue (session);
// mark convo as active // mark convo as active
@ -1058,12 +1058,12 @@ namespace client
std::shared_ptr<const Address> addr; std::shared_ptr<const Address> addr;
while(!(addr = context.GetAddressBook().GetAddress(m_RemoteDest)) && !m_cancel_resolve) while(!(addr = context.GetAddressBook().GetAddress(m_RemoteDest)) && !m_cancel_resolve)
{ {
LogPrint(eLogWarning, "UDP Tunnel: failed to lookup ", m_RemoteDest); LogPrint(eLogWarning, "UDP Tunnel: Failed to lookup ", m_RemoteDest);
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if(m_cancel_resolve) if(m_cancel_resolve)
{ {
LogPrint(eLogError, "UDP Tunnel: lookup of ", m_RemoteDest, " was cancelled"); LogPrint(eLogError, "UDP Tunnel: Lookup of ", m_RemoteDest, " was cancelled");
return; return;
} }
if (!addr || !addr->IsIdentHash ()) if (!addr || !addr->IsIdentHash ())
@ -1073,7 +1073,7 @@ namespace client
} }
m_RemoteIdent = new i2p::data::IdentHash; m_RemoteIdent = new i2p::data::IdentHash;
*m_RemoteIdent = addr->identHash; *m_RemoteIdent = addr->identHash;
LogPrint(eLogInfo, "UDP Tunnel: resolved ", m_RemoteDest, " to ", m_RemoteIdent->ToBase32()); LogPrint(eLogInfo, "UDP Tunnel: Resolved ", m_RemoteDest, " to ", m_RemoteIdent->ToBase32());
} }
void I2PUDPClientTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len) void I2PUDPClientTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
@ -1081,7 +1081,7 @@ namespace client
if(m_RemoteIdent && from.GetIdentHash() == *m_RemoteIdent) if(m_RemoteIdent && from.GetIdentHash() == *m_RemoteIdent)
HandleRecvFromI2PRaw (fromPort, toPort, buf, len); HandleRecvFromI2PRaw (fromPort, toPort, buf, len);
else else
LogPrint(eLogWarning, "UDP Client: unwarranted traffic from ", from.GetIdentHash().ToBase32()); LogPrint(eLogWarning, "UDP Client: Unwarranted traffic from ", from.GetIdentHash().ToBase32());
} }
void I2PUDPClientTunnel::HandleRecvFromI2PRaw(uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len) void I2PUDPClientTunnel::HandleRecvFromI2PRaw(uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
@ -1093,14 +1093,14 @@ namespace client
// found convo // found convo
if (len > 0) if (len > 0)
{ {
LogPrint(eLogDebug, "UDP Client: got ", len, "B from ", m_RemoteIdent ? m_RemoteIdent->ToBase32() : ""); LogPrint(eLogDebug, "UDP Client: Got ", len, "B from ", m_RemoteIdent ? m_RemoteIdent->ToBase32() : "");
m_LocalSocket.send_to(boost::asio::buffer(buf, len), itr->second->first); m_LocalSocket.send_to(boost::asio::buffer(buf, len), itr->second->first);
// mark convo as active // mark convo as active
itr->second->second = i2p::util::GetMillisecondsSinceEpoch(); itr->second->second = i2p::util::GetMillisecondsSinceEpoch();
} }
} }
else else
LogPrint(eLogWarning, "UDP Client: not tracking udp session using port ", (int) toPort); LogPrint(eLogWarning, "UDP Client: Not tracking udp session using port ", (int) toPort);
} }
I2PUDPClientTunnel::~I2PUDPClientTunnel() I2PUDPClientTunnel::~I2PUDPClientTunnel()

8
libi2pd_client/MatchedDestination.cpp

@ -33,14 +33,14 @@ namespace client
RequestDestination(m_RemoteIdent, std::bind(&MatchedTunnelDestination::HandleFoundCurrentLeaseSet, this, std::placeholders::_1)); RequestDestination(m_RemoteIdent, std::bind(&MatchedTunnelDestination::HandleFoundCurrentLeaseSet, this, std::placeholders::_1));
} }
else else
LogPrint(eLogWarning, "Destination: failed to resolve ", m_RemoteName); LogPrint(eLogWarning, "Destination: Failed to resolve ", m_RemoteName);
} }
void MatchedTunnelDestination::HandleFoundCurrentLeaseSet(std::shared_ptr<const i2p::data::LeaseSet> ls) void MatchedTunnelDestination::HandleFoundCurrentLeaseSet(std::shared_ptr<const i2p::data::LeaseSet> ls)
{ {
if(ls) if(ls)
{ {
LogPrint(eLogDebug, "Destination: resolved remote lease set for ", m_RemoteName); LogPrint(eLogDebug, "Destination: Resolved remote lease set for ", m_RemoteName);
m_RemoteLeaseSet = ls; m_RemoteLeaseSet = ls;
} }
else else
@ -96,9 +96,9 @@ namespace client
if(obep) if(obep)
{ {
path.Add (obep); path.Add (obep);
LogPrint(eLogDebug, "Destination: found OBEP matching IBGW"); LogPrint(eLogDebug, "Destination: Found OBEP matching IBGW");
} else } else
LogPrint(eLogWarning, "Destination: could not find proper IBGW for matched outbound tunnel"); LogPrint(eLogWarning, "Destination: Could not find proper IBGW for matched outbound tunnel");
} }
} }
return true; return true;

82
libi2pd_client/SAM.cpp

@ -101,7 +101,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: handshake read error: ", ecode.message ()); LogPrint (eLogError, "SAM: Handshake read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("SAM: handshake read error"); Terminate ("SAM: handshake read error");
} }
@ -111,7 +111,7 @@ namespace client
char * eol = (char *)memchr (m_Buffer, '\n', bytes_transferred); char * eol = (char *)memchr (m_Buffer, '\n', bytes_transferred);
if (eol) if (eol)
*eol = 0; *eol = 0;
LogPrint (eLogDebug, "SAM: handshake ", m_Buffer); LogPrint (eLogDebug, "SAM: Handshake ", m_Buffer);
char * separator = strchr (m_Buffer, ' '); char * separator = strchr (m_Buffer, ' ');
if (separator) if (separator)
{ {
@ -168,7 +168,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "SAM: handshake mismatch"); LogPrint (eLogError, "SAM: Handshake mismatch");
Terminate ("SAM: handshake mismatch"); Terminate ("SAM: handshake mismatch");
} }
} }
@ -183,7 +183,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: handshake reply send error: ", ecode.message ()); LogPrint (eLogError, "SAM: Handshake reply send error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("SAM: handshake reply send error"); Terminate ("SAM: handshake reply send error");
} }
@ -216,7 +216,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: reply send error: ", ecode.message ()); LogPrint (eLogError, "SAM: Reply send error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("SAM: reply send error"); Terminate ("SAM: reply send error");
} }
@ -233,7 +233,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: read error: ", ecode.message ()); LogPrint (eLogError, "SAM: Read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("SAM: read error"); Terminate ("SAM: read error");
} }
@ -295,20 +295,20 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "SAM: unexpected message ", m_Buffer); LogPrint (eLogError, "SAM: Unexpected message ", m_Buffer);
Terminate ("SAM: unexpected message"); Terminate ("SAM: unexpected message");
} }
} }
else else
{ {
LogPrint (eLogError, "SAM: malformed message ", m_Buffer); LogPrint (eLogError, "SAM: Malformed message ", m_Buffer);
Terminate ("malformed message"); Terminate ("malformed message");
} }
} }
else else
{ {
LogPrint (eLogWarning, "SAM: incomplete message ", bytes_transferred); LogPrint (eLogWarning, "SAM: Incomplete message ", bytes_transferred);
m_BufferOffset = bytes_transferred; m_BufferOffset = bytes_transferred;
// try to receive remaining message // try to receive remaining message
Receive (); Receive ();
@ -331,7 +331,7 @@ namespace client
void SAMSocket::ProcessSessionCreate (char * buf, size_t len) void SAMSocket::ProcessSessionCreate (char * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: session create: ", buf); LogPrint (eLogDebug, "SAM: Session create: ", buf);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
std::string& style = params[SAM_PARAM_STYLE]; std::string& style = params[SAM_PARAM_STYLE];
@ -476,7 +476,7 @@ namespace client
void SAMSocket::ProcessStreamConnect (char * buf, size_t len, size_t rem) void SAMSocket::ProcessStreamConnect (char * buf, size_t len, size_t rem)
{ {
LogPrint (eLogDebug, "SAM: stream connect: ", buf); LogPrint (eLogDebug, "SAM: Stream connect: ", buf);
if ( m_SocketType != eSAMSocketTypeUnknown) if ( m_SocketType != eSAMSocketTypeUnknown)
{ {
SendI2PError ("Socket already in use"); SendI2PError ("Socket already in use");
@ -567,14 +567,14 @@ namespace client
Connect (leaseSet); Connect (leaseSet);
else else
{ {
LogPrint (eLogError, "SAM: destination to connect not found"); LogPrint (eLogError, "SAM: Destination to connect not found");
SendMessageReply (SAM_STREAM_STATUS_CANT_REACH_PEER, strlen(SAM_STREAM_STATUS_CANT_REACH_PEER), true); SendMessageReply (SAM_STREAM_STATUS_CANT_REACH_PEER, strlen(SAM_STREAM_STATUS_CANT_REACH_PEER), true);
} }
} }
void SAMSocket::ProcessStreamAccept (char * buf, size_t len) void SAMSocket::ProcessStreamAccept (char * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: stream accept: ", buf); LogPrint (eLogDebug, "SAM: Stream accept: ", buf);
if ( m_SocketType != eSAMSocketTypeUnknown) if ( m_SocketType != eSAMSocketTypeUnknown)
{ {
SendI2PError ("Socket already in use"); SendI2PError ("Socket already in use");
@ -603,7 +603,7 @@ namespace client
void SAMSocket::ProcessStreamForward (char * buf, size_t len) void SAMSocket::ProcessStreamForward (char * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: stream forward: ", buf); LogPrint (eLogDebug, "SAM: Stream forward: ", buf);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
std::string& id = params[SAM_PARAM_ID]; std::string& id = params[SAM_PARAM_ID];
@ -650,7 +650,7 @@ namespace client
size_t SAMSocket::ProcessDatagramSend (char * buf, size_t len, const char * data) size_t SAMSocket::ProcessDatagramSend (char * buf, size_t len, const char * data)
{ {
LogPrint (eLogDebug, "SAM: datagram send: ", buf, " ", len); LogPrint (eLogDebug, "SAM: Datagram send: ", buf, " ", len);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
size_t size = std::stoi(params[SAM_PARAM_SIZE]), offset = data - buf; size_t size = std::stoi(params[SAM_PARAM_SIZE]), offset = data - buf;
@ -670,14 +670,14 @@ namespace client
d->SendRawDatagramTo ((const uint8_t *)data, size, dest.GetIdentHash ()); d->SendRawDatagramTo ((const uint8_t *)data, size, dest.GetIdentHash ());
} }
else else
LogPrint (eLogError, "SAM: missing datagram destination"); LogPrint (eLogError, "SAM: Missing datagram destination");
} }
else else
LogPrint (eLogError, "SAM: session is not created from DATAGRAM SEND"); LogPrint (eLogError, "SAM: Session is not created from DATAGRAM SEND");
} }
else else
{ {
LogPrint (eLogWarning, "SAM: sent datagram size ", size, " exceeds buffer ", len - offset); LogPrint (eLogWarning, "SAM: Sent datagram size ", size, " exceeds buffer ", len - offset);
return 0; // try to receive more return 0; // try to receive more
} }
return offset + size; return offset + size;
@ -685,7 +685,7 @@ namespace client
void SAMSocket::ProcessDestGenerate (char * buf, size_t len) void SAMSocket::ProcessDestGenerate (char * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: dest generate"); LogPrint (eLogDebug, "SAM: Dest generate");
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
// extract signature type // extract signature type
@ -722,7 +722,7 @@ namespace client
void SAMSocket::ProcessNamingLookup (char * buf, size_t len) void SAMSocket::ProcessNamingLookup (char * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: naming lookup: ", buf); LogPrint (eLogDebug, "SAM: Naming lookup: ", buf);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
std::string& name = params[SAM_PARAM_NAME]; std::string& name = params[SAM_PARAM_NAME];
@ -753,7 +753,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "SAM: naming failed, unknown address ", name); LogPrint (eLogError, "SAM: Naming failed, unknown address ", name);
#ifdef _MSC_VER #ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str()); size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#else #else
@ -768,7 +768,7 @@ namespace client
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if (session && session->Type == eSAMSessionTypeMaster) if (session && session->Type == eSAMSessionTypeMaster)
{ {
LogPrint (eLogDebug, "SAM: subsession add: ", buf); LogPrint (eLogDebug, "SAM: Subsession add: ", buf);
auto masterSession = std::static_pointer_cast<SAMMasterSession>(session); auto masterSession = std::static_pointer_cast<SAMMasterSession>(session);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
@ -813,7 +813,7 @@ namespace client
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if (session && session->Type == eSAMSessionTypeMaster) if (session && session->Type == eSAMSessionTypeMaster)
{ {
LogPrint (eLogDebug, "SAM: subsession remove: ", buf); LogPrint (eLogDebug, "SAM: Subsession remove: ", buf);
auto masterSession = std::static_pointer_cast<SAMMasterSession>(session); auto masterSession = std::static_pointer_cast<SAMMasterSession>(session);
std::map<std::string, std::string> params; std::map<std::string, std::string> params;
ExtractParams (buf, params); ExtractParams (buf, params);
@ -832,7 +832,7 @@ namespace client
void SAMSocket::SendI2PError(const std::string & msg) void SAMSocket::SendI2PError(const std::string & msg)
{ {
LogPrint (eLogError, "SAM: i2p error ", msg); LogPrint (eLogError, "SAM: I2P error: ", msg);
#ifdef _MSC_VER #ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_STATUS_I2P_ERROR, msg.c_str()); size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_STATUS_I2P_ERROR, msg.c_str());
#else #else
@ -850,7 +850,7 @@ namespace client
} }
else else
{ {
LogPrint (eLogError, "SAM: naming lookup failed. LeaseSet for ", name, " not found"); LogPrint (eLogError, "SAM: Naming lookup failed. LeaseSet for ", name, " not found");
#ifdef _MSC_VER #ifdef _MSC_VER
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str()); size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#else #else
@ -901,7 +901,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: read error: ", ecode.message ()); LogPrint (eLogError, "SAM: Read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("read error"); Terminate ("read error");
} }
@ -978,7 +978,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: stream read error: ", ecode.message ()); LogPrint (eLogError, "SAM: Stream read error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
{ {
if (bytes_transferred > 0) if (bytes_transferred > 0)
@ -1015,7 +1015,7 @@ namespace client
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SAM: socket write error: ", ecode.message ()); LogPrint (eLogError, "SAM: Socket write error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Terminate ("socket write error at HandleWriteI2PData"); Terminate ("socket write error at HandleWriteI2PData");
} }
@ -1029,7 +1029,7 @@ namespace client
{ {
if (stream) if (stream)
{ {
LogPrint (eLogDebug, "SAM: incoming I2P connection for session ", m_ID); LogPrint (eLogDebug, "SAM: Incoming I2P connection for session ", m_ID);
m_SocketType = eSAMSocketTypeStream; m_SocketType = eSAMSocketTypeStream;
m_IsAccepting = false; m_IsAccepting = false;
m_Stream = stream; m_Stream = stream;
@ -1072,7 +1072,7 @@ namespace client
{ {
if (stream) if (stream)
{ {
LogPrint (eLogDebug, "SAM: incoming forward I2P connection for session ", m_ID); LogPrint (eLogDebug, "SAM: Incoming forward I2P connection for session ", m_ID);
auto newSocket = std::make_shared<SAMSocket>(m_Owner); auto newSocket = std::make_shared<SAMSocket>(m_Owner);
newSocket->SetSocketType (eSAMSocketTypeStream); newSocket->SetSocketType (eSAMSocketTypeStream);
auto s = shared_from_this (); auto s = shared_from_this ();
@ -1106,7 +1106,7 @@ namespace client
void SAMSocket::HandleI2PDatagramReceive (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len) void SAMSocket::HandleI2PDatagramReceive (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: datagram received ", len); LogPrint (eLogDebug, "SAM: Datagram received ", len);
auto base64 = from.ToBase64 (); auto base64 = from.ToBase64 ();
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if(session) if(session)
@ -1142,14 +1142,14 @@ namespace client
WriteI2PData(len + l); WriteI2PData(len + l);
} }
else else
LogPrint (eLogWarning, "SAM: received datagram size ", len," exceeds buffer"); LogPrint (eLogWarning, "SAM: Received datagram size ", len," exceeds buffer");
} }
} }
} }
void SAMSocket::HandleI2PRawDatagramReceive (uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len) void SAMSocket::HandleI2PRawDatagramReceive (uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{ {
LogPrint (eLogDebug, "SAM: raw datagram received ", len); LogPrint (eLogDebug, "SAM: Raw datagram received ", len);
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if(session) if(session)
{ {
@ -1170,7 +1170,7 @@ namespace client
WriteI2PData(len + l); WriteI2PData(len + l);
} }
else else
LogPrint (eLogWarning, "SAM: received raw datagram size ", len," exceeds buffer"); LogPrint (eLogWarning, "SAM: Received raw datagram size ", len," exceeds buffer");
} }
} }
} }
@ -1288,7 +1288,7 @@ namespace client
} }
catch (const std::exception& ex) catch (const std::exception& ex)
{ {
LogPrint (eLogError, "SAM: runtime exception: ", ex.what ()); LogPrint (eLogError, "SAM: Runtime exception: ", ex.what ());
} }
{ {
@ -1327,15 +1327,15 @@ namespace client
auto ep = socket->GetSocket ().remote_endpoint (ec); auto ep = socket->GetSocket ().remote_endpoint (ec);
if (!ec) if (!ec)
{ {
LogPrint (eLogDebug, "SAM: new connection from ", ep); LogPrint (eLogDebug, "SAM: New connection from ", ep);
AddSocket (socket); AddSocket (socket);
socket->ReceiveHandshake (); socket->ReceiveHandshake ();
} }
else else
LogPrint (eLogError, "SAM: incoming connection error ", ec.message ()); LogPrint (eLogError, "SAM: Incoming connection error: ", ec.message ());
} }
else else
LogPrint (eLogError, "SAM: accept error: ", ecode.message ()); LogPrint (eLogError, "SAM: Accept error: ", ecode.message ());
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
Accept (); Accept ();
@ -1479,7 +1479,7 @@ namespace client
{ {
*eol = 0; eol++; *eol = 0; eol++;
size_t payloadLen = bytes_transferred - ((uint8_t *)eol - m_DatagramReceiveBuffer); size_t payloadLen = bytes_transferred - ((uint8_t *)eol - m_DatagramReceiveBuffer);
LogPrint (eLogDebug, "SAM: datagram received ", m_DatagramReceiveBuffer," size=", payloadLen); LogPrint (eLogDebug, "SAM: Datagram received ", m_DatagramReceiveBuffer," size=", payloadLen);
char * sessionID = strchr ((char *)m_DatagramReceiveBuffer, ' '); char * sessionID = strchr ((char *)m_DatagramReceiveBuffer, ' ');
if (sessionID) if (sessionID)
{ {
@ -1510,11 +1510,11 @@ namespace client
LogPrint (eLogError, "SAM: Missing sessionID"); LogPrint (eLogError, "SAM: Missing sessionID");
} }
else else
LogPrint(eLogError, "SAM: invalid datagram"); LogPrint(eLogError, "SAM: Invalid datagram");
ReceiveDatagram (); ReceiveDatagram ();
} }
else else
LogPrint (eLogError, "SAM: datagram receive error: ", ecode.message ()); LogPrint (eLogError, "SAM: Datagram receive error: ", ecode.message ());
} }
bool SAMBridge::ResolveSignatureType (const std::string& name, i2p::data::SigningKeyType& type) const bool SAMBridge::ResolveSignatureType (const std::string& name, i2p::data::SigningKeyType& type) const

62
libi2pd_client/SOCKS.cpp

@ -191,13 +191,13 @@ namespace proxy
void SOCKSHandler::AsyncSockRead() void SOCKSHandler::AsyncSockRead()
{ {
LogPrint(eLogDebug, "SOCKS: async sock read"); LogPrint(eLogDebug, "SOCKS: Async sock read");
if (m_sock) { if (m_sock) {
m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size), m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size),
std::bind(&SOCKSHandler::HandleSockRecv, shared_from_this(), std::bind(&SOCKSHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)); std::placeholders::_1, std::placeholders::_2));
} else { } else {
LogPrint(eLogError,"SOCKS: no socket for read"); LogPrint(eLogError,"SOCKS: No socket for read");
} }
} }
@ -206,19 +206,19 @@ namespace proxy
if (Kill()) return; if (Kill()) return;
if (m_sock) if (m_sock)
{ {
LogPrint(eLogDebug, "SOCKS: closing socket"); LogPrint(eLogDebug, "SOCKS: Closing socket");
m_sock->close(); m_sock->close();
m_sock = nullptr; m_sock = nullptr;
} }
if (m_upstreamSock) if (m_upstreamSock)
{ {
LogPrint(eLogDebug, "SOCKS: closing upstream socket"); LogPrint(eLogDebug, "SOCKS: Closing upstream socket");
m_upstreamSock->close(); m_upstreamSock->close();
m_upstreamSock = nullptr; m_upstreamSock = nullptr;
} }
if (m_stream) if (m_stream)
{ {
LogPrint(eLogDebug, "SOCKS: closing stream"); LogPrint(eLogDebug, "SOCKS: Closing stream");
m_stream.reset (); m_stream.reset ();
} }
Done(shared_from_this()); Done(shared_from_this());
@ -386,7 +386,7 @@ namespace proxy
if ( m_cmd != CMD_CONNECT ) if ( m_cmd != CMD_CONNECT )
{ {
// TODO: we need to support binds and other shit! // TODO: we need to support binds and other shit!
LogPrint(eLogError, "SOCKS: unsupported command: ", m_cmd); LogPrint(eLogError, "SOCKS: Unsupported command: ", m_cmd);
SocksRequestFailed(SOCKS5_CMD_UNSUP); SocksRequestFailed(SOCKS5_CMD_UNSUP);
return false; return false;
} }
@ -399,7 +399,7 @@ namespace proxy
LogPrint(eLogError, "SOCKS: v5 unsupported address type: ", m_addrtype); LogPrint(eLogError, "SOCKS: v5 unsupported address type: ", m_addrtype);
break; break;
case SOCKS4: case SOCKS4:
LogPrint(eLogError, "SOCKS: request with v4a rejected because it's actually SOCKS4"); LogPrint(eLogError, "SOCKS: Request with v4a rejected because it's actually SOCKS4");
break; break;
} }
SocksRequestFailed(SOCKS5_ADDR_UNSUP); SocksRequestFailed(SOCKS5_ADDR_UNSUP);
@ -426,7 +426,7 @@ namespace proxy
EnterState(GET5_AUTHNUM); //Initialize the parser at the right position EnterState(GET5_AUTHNUM); //Initialize the parser at the right position
break; break;
default: default:
LogPrint(eLogError, "SOCKS: rejected invalid version: ", ((int)*sock_buff)); LogPrint(eLogError, "SOCKS: Rejected invalid version: ", ((int)*sock_buff));
Terminate(); Terminate();
return false; return false;
} }
@ -456,7 +456,7 @@ namespace proxy
[[fallthrough]]; [[fallthrough]];
#endif #endif
default: default:
LogPrint(eLogError, "SOCKS: invalid command: ", ((int)*sock_buff)); LogPrint(eLogError, "SOCKS: Invalid command: ", ((int)*sock_buff));
SocksRequestFailed(SOCKS5_GEN_FAIL); SocksRequestFailed(SOCKS5_GEN_FAIL);
return false; return false;
} }
@ -558,7 +558,7 @@ namespace proxy
if (m_parseleft == 0) EnterState(GET_PORT); if (m_parseleft == 0) EnterState(GET_PORT);
break; break;
default: default:
LogPrint(eLogError, "SOCKS: parse state?? ", m_state); LogPrint(eLogError, "SOCKS: Parse state?? ", m_state);
Terminate(); Terminate();
return false; return false;
} }
@ -576,10 +576,10 @@ namespace proxy
void SOCKSHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len) void SOCKSHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{ {
LogPrint(eLogDebug, "SOCKS: received ", len, " bytes"); LogPrint(eLogDebug, "SOCKS: Received ", len, " bytes");
if(ecode) if(ecode)
{ {
LogPrint(eLogWarning, "SOCKS: recv got error: ", ecode); LogPrint(eLogWarning, "SOCKS: Recv got error: ", ecode);
Terminate(); Terminate();
return; return;
} }
@ -589,7 +589,7 @@ namespace proxy
if (m_state == READY) if (m_state == READY)
{ {
const std::string addr = m_address.dns.ToString(); const std::string addr = m_address.dns.ToString();
LogPrint(eLogInfo, "SOCKS: requested ", addr, ":" , m_port); LogPrint(eLogInfo, "SOCKS: Requested ", addr, ":" , m_port);
const size_t addrlen = addr.size(); const size_t addrlen = addr.size();
// does it end with .i2p? // does it end with .i2p?
if ( addr.rfind(".i2p") == addrlen - 4) { if ( addr.rfind(".i2p") == addrlen - 4) {
@ -612,7 +612,7 @@ namespace proxy
void SOCKSHandler::SentSocksFailed(const boost::system::error_code & ecode) void SOCKSHandler::SentSocksFailed(const boost::system::error_code & ecode)
{ {
if (ecode) if (ecode)
LogPrint (eLogError, "SOCKS: closing socket after sending failure because: ", ecode.message ()); LogPrint (eLogError, "SOCKS: Closing socket after sending failure because: ", ecode.message ());
Terminate(); Terminate();
} }
@ -621,7 +621,7 @@ namespace proxy
if (!ecode) if (!ecode)
{ {
if (Kill()) return; if (Kill()) return;
LogPrint (eLogInfo, "SOCKS: new I2PTunnel connection"); LogPrint (eLogInfo, "SOCKS: New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, m_stream); auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, m_stream);
GetOwner()->AddHandler (connection); GetOwner()->AddHandler (connection);
connection->I2PConnect (m_remaining_data,m_remaining_data_len); connection->I2PConnect (m_remaining_data,m_remaining_data_len);
@ -629,7 +629,7 @@ namespace proxy
} }
else else
{ {
LogPrint (eLogError, "SOCKS: closing socket after completion reply because: ", ecode.message ()); LogPrint (eLogError, "SOCKS: Closing socket after completion reply because: ", ecode.message ());
Terminate(); Terminate();
} }
} }
@ -638,7 +638,7 @@ namespace proxy
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SOCKS: closing socket after sending reply because: ", ecode.message ()); LogPrint (eLogError, "SOCKS: Closing socket after sending reply because: ", ecode.message ());
Terminate(); Terminate();
} }
} }
@ -652,14 +652,14 @@ namespace proxy
} }
else else
{ {
LogPrint (eLogError, "SOCKS: error when creating the stream, check the previous warnings for more info"); LogPrint (eLogError, "SOCKS: Error when creating the stream, check the previous warnings for more info");
SocksRequestFailed(SOCKS5_HOST_UNREACH); SocksRequestFailed(SOCKS5_HOST_UNREACH);
} }
} }
void SOCKSHandler::ForwardSOCKS() void SOCKSHandler::ForwardSOCKS()
{ {
LogPrint(eLogInfo, "SOCKS: forwarding to upstream"); LogPrint(eLogInfo, "SOCKS: Forwarding to upstream");
EnterState(UPSTREAM_RESOLVE); EnterState(UPSTREAM_RESOLVE);
boost::asio::ip::tcp::resolver::query q(m_UpstreamProxyAddress, std::to_string(m_UpstreamProxyPort)); boost::asio::ip::tcp::resolver::query q(m_UpstreamProxyAddress, std::to_string(m_UpstreamProxyPort));
m_proxy_resolver.async_resolve(q, std::bind(&SOCKSHandler::HandleUpstreamResolved, shared_from_this(), m_proxy_resolver.async_resolve(q, std::bind(&SOCKSHandler::HandleUpstreamResolved, shared_from_this(),
@ -668,12 +668,12 @@ namespace proxy
void SOCKSHandler::AsyncUpstreamSockRead() void SOCKSHandler::AsyncUpstreamSockRead()
{ {
LogPrint(eLogDebug, "SOCKS: async upstream sock read"); LogPrint(eLogDebug, "SOCKS: Async upstream sock read");
if (m_upstreamSock) { if (m_upstreamSock) {
m_upstreamSock->async_read_some(boost::asio::buffer(m_upstream_response, SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE), m_upstreamSock->async_read_some(boost::asio::buffer(m_upstream_response, SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE),
std::bind(&SOCKSHandler::HandleUpstreamSockRecv, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); std::bind(&SOCKSHandler::HandleUpstreamSockRecv, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
} else { } else {
LogPrint(eLogError, "SOCKS: no upstream socket for read"); LogPrint(eLogError, "SOCKS: No upstream socket for read");
SocksRequestFailed(SOCKS5_GEN_FAIL); SocksRequestFailed(SOCKS5_GEN_FAIL);
} }
} }
@ -685,7 +685,7 @@ namespace proxy
// we are trying to handshake but it failed // we are trying to handshake but it failed
SocksRequestFailed(SOCKS5_NET_UNREACH); SocksRequestFailed(SOCKS5_NET_UNREACH);
} else { } else {
LogPrint(eLogError, "SOCKS: bad state when reading from upstream: ", (int) m_state); LogPrint(eLogError, "SOCKS: Bad state when reading from upstream: ", (int) m_state);
} }
return; return;
} }
@ -694,7 +694,7 @@ namespace proxy
void SOCKSHandler::SocksUpstreamSuccess() void SOCKSHandler::SocksUpstreamSuccess()
{ {
LogPrint(eLogInfo, "SOCKS: upstream success"); LogPrint(eLogInfo, "SOCKS: Upstream success");
boost::asio::const_buffers_1 response(nullptr, 0); boost::asio::const_buffers_1 response(nullptr, 0);
switch (m_socksv) switch (m_socksv)
{ {
@ -734,7 +734,7 @@ namespace proxy
SocksUpstreamSuccess(); SocksUpstreamSuccess();
} else { } else {
// upstream failure // upstream failure
LogPrint(eLogError, "SOCKS: upstream proxy failure: ", (int) resp); LogPrint(eLogError, "SOCKS: Upstream proxy failure: ", (int) resp);
// TODO: runtime error? // TODO: runtime error?
SocksRequestFailed(SOCKS5_GEN_FAIL); SocksRequestFailed(SOCKS5_GEN_FAIL);
} }
@ -744,30 +744,30 @@ namespace proxy
} }
} else { } else {
// invalid state // invalid state
LogPrint(eLogError, "SOCKS: invalid state reading from upstream: ", (int) m_state); LogPrint(eLogError, "SOCKS: Invalid state reading from upstream: ", (int) m_state);
} }
} }
void SOCKSHandler::SendUpstreamRequest() void SOCKSHandler::SendUpstreamRequest()
{ {
LogPrint(eLogInfo, "SOCKS: negotiating with upstream proxy"); LogPrint(eLogInfo, "SOCKS: Negotiating with upstream proxy");
EnterState(UPSTREAM_HANDSHAKE); EnterState(UPSTREAM_HANDSHAKE);
if (m_upstreamSock) { if (m_upstreamSock) {
boost::asio::write(*m_upstreamSock, GenerateUpstreamRequest()); boost::asio::write(*m_upstreamSock, GenerateUpstreamRequest());
AsyncUpstreamSockRead(); AsyncUpstreamSockRead();
} else { } else {
LogPrint(eLogError, "SOCKS: no upstream socket to send handshake to"); LogPrint(eLogError, "SOCKS: No upstream socket to send handshake to");
} }
} }
void SOCKSHandler::HandleUpstreamConnected(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr) void SOCKSHandler::HandleUpstreamConnected(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr)
{ {
if (ecode) { if (ecode) {
LogPrint(eLogWarning, "SOCKS: could not connect to upstream proxy: ", ecode.message()); LogPrint(eLogWarning, "SOCKS: Could not connect to upstream proxy: ", ecode.message());
SocksRequestFailed(SOCKS5_NET_UNREACH); SocksRequestFailed(SOCKS5_NET_UNREACH);
return; return;
} }
LogPrint(eLogInfo, "SOCKS: connected to upstream proxy"); LogPrint(eLogInfo, "SOCKS: Connected to upstream proxy");
SendUpstreamRequest(); SendUpstreamRequest();
} }
@ -775,11 +775,11 @@ namespace proxy
{ {
if (ecode) { if (ecode) {
// error resolving // error resolving
LogPrint(eLogWarning, "SOCKS: upstream proxy", m_UpstreamProxyAddress, " not resolved: ", ecode.message()); LogPrint(eLogWarning, "SOCKS: Upstream proxy", m_UpstreamProxyAddress, " not resolved: ", ecode.message());
SocksRequestFailed(SOCKS5_NET_UNREACH); SocksRequestFailed(SOCKS5_NET_UNREACH);
return; return;
} }
LogPrint(eLogInfo, "SOCKS: upstream proxy resolved"); LogPrint(eLogInfo, "SOCKS: Upstream proxy resolved");
EnterState(UPSTREAM_CONNECT); EnterState(UPSTREAM_CONNECT);
auto & service = GetOwner()->GetService(); auto & service = GetOwner()->GetService();
m_upstreamSock = std::make_shared<boost::asio::ip::tcp::socket>(service); m_upstreamSock = std::make_shared<boost::asio::ip::tcp::socket>(service);

Loading…
Cancel
Save