From 182ffe44954e76fe443e30b5d45509d9864a1192 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 9 Mar 2018 14:56:06 -0500 Subject: [PATCH 01/26] use croorect encryption type for tunnel build --- libi2pd/CryptoKey.cpp | 24 ++++++++++++------------ libi2pd/CryptoKey.h | 16 ++++++++-------- libi2pd/Destination.cpp | 2 +- libi2pd/I2NPProtocol.cpp | 2 +- libi2pd/LeaseSet.cpp | 2 +- libi2pd/RouterContext.cpp | 7 ++++++- libi2pd/RouterContext.h | 1 + libi2pd/RouterInfo.cpp | 2 +- libi2pd/TunnelConfig.h | 5 +++-- libi2pd_client/I2CP.cpp | 2 +- 10 files changed, 35 insertions(+), 28 deletions(-) diff --git a/libi2pd/CryptoKey.cpp b/libi2pd/CryptoKey.cpp index cd6952a0..711d4ce6 100644 --- a/libi2pd/CryptoKey.cpp +++ b/libi2pd/CryptoKey.cpp @@ -12,9 +12,9 @@ namespace crypto memcpy (m_PublicKey, pub, 256); } - void ElGamalEncryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx) + void ElGamalEncryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding) { - ElGamalEncrypt (m_PublicKey, data, encrypted, ctx, true); + ElGamalEncrypt (m_PublicKey, data, encrypted, ctx, zeroPadding); } ElGamalDecryptor::ElGamalDecryptor (const uint8_t * priv) @@ -22,9 +22,9 @@ namespace crypto memcpy (m_PrivateKey, priv, 256); } - bool ElGamalDecryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) + bool ElGamalDecryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding) { - return ElGamalDecrypt (m_PrivateKey, encrypted, data, ctx, true); + return ElGamalDecrypt (m_PrivateKey, encrypted, data, ctx, zeroPadding); } ECIESP256Encryptor::ECIESP256Encryptor (const uint8_t * pub) @@ -44,10 +44,10 @@ namespace crypto if (m_PublicKey) EC_POINT_free (m_PublicKey); } - void ECIESP256Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx) + void ECIESP256Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding) { if (m_Curve && m_PublicKey) - ECIESEncrypt (m_Curve, m_PublicKey, data, encrypted, ctx, true); + ECIESEncrypt (m_Curve, m_PublicKey, data, encrypted, ctx, zeroPadding); } ECIESP256Decryptor::ECIESP256Decryptor (const uint8_t * priv) @@ -62,10 +62,10 @@ namespace crypto if (m_PrivateKey) BN_free (m_PrivateKey); } - bool ECIESP256Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) + bool ECIESP256Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding) { if (m_Curve && m_PrivateKey) - return ECIESDecrypt (m_Curve, m_PrivateKey, encrypted, data, ctx, true); + return ECIESDecrypt (m_Curve, m_PrivateKey, encrypted, data, ctx, zeroPadding); return false; } @@ -104,10 +104,10 @@ namespace crypto if (m_PublicKey) EC_POINT_free (m_PublicKey); } - void ECIESGOSTR3410Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx) + void ECIESGOSTR3410Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding) { if (m_PublicKey) - ECIESEncrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PublicKey, data, encrypted, ctx, true); + ECIESEncrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PublicKey, data, encrypted, ctx, zeroPadding); } ECIESGOSTR3410Decryptor::ECIESGOSTR3410Decryptor (const uint8_t * priv) @@ -120,10 +120,10 @@ namespace crypto if (m_PrivateKey) BN_free (m_PrivateKey); } - bool ECIESGOSTR3410Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) + bool ECIESGOSTR3410Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding) { if (m_PrivateKey) - return ECIESDecrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PrivateKey, encrypted, data, ctx, true); + return ECIESDecrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PrivateKey, encrypted, data, ctx, zeroPadding); return false; } diff --git a/libi2pd/CryptoKey.h b/libi2pd/CryptoKey.h index ece86eb0..0dff7584 100644 --- a/libi2pd/CryptoKey.h +++ b/libi2pd/CryptoKey.h @@ -13,7 +13,7 @@ namespace crypto public: virtual ~CryptoKeyEncryptor () {}; - virtual void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx) = 0; // 222 bytes data, 512 bytes encrypted + virtual void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding) = 0; // 222 bytes data, 512/514 bytes encrypted }; class CryptoKeyDecryptor @@ -21,7 +21,7 @@ namespace crypto public: virtual ~CryptoKeyDecryptor () {}; - virtual bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) = 0; // 512 bytes encrypted, 222 bytes data + virtual bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding) = 0; // 512/514 bytes encrypted, 222 bytes data }; // ElGamal @@ -30,7 +30,7 @@ namespace crypto public: ElGamalEncryptor (const uint8_t * pub); - void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx); + void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding); private: @@ -42,7 +42,7 @@ namespace crypto public: ElGamalDecryptor (const uint8_t * priv); - bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx); + bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding); private: @@ -57,7 +57,7 @@ namespace crypto ECIESP256Encryptor (const uint8_t * pub); ~ECIESP256Encryptor (); - void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx); + void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding); private: @@ -72,7 +72,7 @@ namespace crypto ECIESP256Decryptor (const uint8_t * priv); ~ECIESP256Decryptor (); - bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx); + bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding); private: @@ -90,7 +90,7 @@ namespace crypto ECIESGOSTR3410Encryptor (const uint8_t * pub); ~ECIESGOSTR3410Encryptor (); - void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx); + void Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding); private: @@ -104,7 +104,7 @@ namespace crypto ECIESGOSTR3410Decryptor (const uint8_t * priv); ~ECIESGOSTR3410Decryptor (); - bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx); + bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx, bool zeroPadding); private: diff --git a/libi2pd/Destination.cpp b/libi2pd/Destination.cpp index b191cbf1..bafd49da 100644 --- a/libi2pd/Destination.cpp +++ b/libi2pd/Destination.cpp @@ -1024,7 +1024,7 @@ namespace client bool ClientDestination::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const { if (m_Decryptor) - return m_Decryptor->Decrypt (encrypted, data, ctx); + return m_Decryptor->Decrypt (encrypted, data, ctx, true); else LogPrint (eLogError, "Destinations: decryptor is not set"); return false; diff --git a/libi2pd/I2NPProtocol.cpp b/libi2pd/I2NPProtocol.cpp index 9bb7dfd1..c91bfdb3 100644 --- a/libi2pd/I2NPProtocol.cpp +++ b/libi2pd/I2NPProtocol.cpp @@ -327,7 +327,7 @@ namespace i2p { LogPrint (eLogDebug, "I2NP: Build request record ", i, " is ours"); BN_CTX * ctx = BN_CTX_new (); - i2p::crypto::ElGamalDecrypt (i2p::context.GetPrivateKeys ().GetPrivateKey () , record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, clearText, ctx); + i2p::context.DecryptTunnelBuildRecord (record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, clearText, ctx); BN_CTX_free (ctx); // replace record to reply if (i2p::context.AcceptsTunnels () && diff --git a/libi2pd/LeaseSet.cpp b/libi2pd/LeaseSet.cpp index f2355930..8b6063fc 100644 --- a/libi2pd/LeaseSet.cpp +++ b/libi2pd/LeaseSet.cpp @@ -212,7 +212,7 @@ namespace data { auto encryptor = m_Identity->CreateEncryptor (m_EncryptionKey); if (encryptor) - encryptor->Encrypt (data, encrypted, ctx); + encryptor->Encrypt (data, encrypted, ctx, true); } LocalLeaseSet::LocalLeaseSet (std::shared_ptr identity, const uint8_t * encryptionPublicKey, std::vector > tunnels): diff --git a/libi2pd/RouterContext.cpp b/libi2pd/RouterContext.cpp index 38fe3224..99f79df6 100644 --- a/libi2pd/RouterContext.cpp +++ b/libi2pd/RouterContext.cpp @@ -482,6 +482,11 @@ namespace i2p bool RouterContext::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const { - return m_Decryptor ? m_Decryptor->Decrypt (encrypted, data, ctx) : false; + return m_Decryptor ? m_Decryptor->Decrypt (encrypted, data, ctx, true) : false; + } + + bool RouterContext::DecryptTunnelBuildRecord (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const + { + return m_Decryptor ? m_Decryptor->Decrypt (encrypted, data, ctx, false) : false; } } diff --git a/libi2pd/RouterContext.h b/libi2pd/RouterContext.h index ef23af25..4bd324f5 100644 --- a/libi2pd/RouterContext.h +++ b/libi2pd/RouterContext.h @@ -61,6 +61,7 @@ namespace i2p void SetError (RouterError error) { m_Status = eRouterStatusError; m_Error = error; }; int GetNetID () const { return m_NetID; }; void SetNetID (int netID) { m_NetID = netID; }; + bool DecryptTunnelBuildRecord (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const; void UpdatePort (int port); // called from Daemon void UpdateAddress (const boost::asio::ip::address& host); // called from SSU or Daemon diff --git a/libi2pd/RouterInfo.cpp b/libi2pd/RouterInfo.cpp index e9c2a384..e3f4d2d4 100644 --- a/libi2pd/RouterInfo.cpp +++ b/libi2pd/RouterInfo.cpp @@ -840,7 +840,7 @@ namespace data { auto encryptor = m_RouterIdentity->CreateEncryptor (nullptr); if (encryptor) - encryptor->Encrypt (data, encrypted, ctx); + encryptor->Encrypt (data, encrypted, ctx, true); } } } diff --git a/libi2pd/TunnelConfig.h b/libi2pd/TunnelConfig.h index 9707fa17..48e66f2e 100644 --- a/libi2pd/TunnelConfig.h +++ b/libi2pd/TunnelConfig.h @@ -5,7 +5,6 @@ #include #include #include -#include "Crypto.h" #include "Identity.h" #include "RouterContext.h" #include "Timestamp.h" @@ -103,7 +102,9 @@ namespace tunnel htobe32buf (clearText + BUILD_REQUEST_RECORD_REQUEST_TIME_OFFSET, i2p::util::GetHoursSinceEpoch ()); htobe32buf (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET, replyMsgID); RAND_bytes (clearText + BUILD_REQUEST_RECORD_PADDING_OFFSET, BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE - BUILD_REQUEST_RECORD_PADDING_OFFSET); - i2p::crypto::ElGamalEncrypt (ident->GetEncryptionPublicKey (), clearText, record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, ctx); + auto encryptor = ident->CreateEncryptor (nullptr); + if (encryptor) + encryptor->Encrypt (clearText, record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, ctx, false); memcpy (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)ident->GetIdentHash (), 16); } }; diff --git a/libi2pd_client/I2CP.cpp b/libi2pd_client/I2CP.cpp index 361d9f94..b08fded1 100644 --- a/libi2pd_client/I2CP.cpp +++ b/libi2pd_client/I2CP.cpp @@ -37,7 +37,7 @@ namespace client bool I2CPDestination::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const { if (m_Decryptor) - return m_Decryptor->Decrypt (encrypted, data, ctx); + return m_Decryptor->Decrypt (encrypted, data, ctx, true); else LogPrint (eLogError, "I2CP: decryptor is not set"); return false; From ce8d701ecb92be1563681ec9ce98a9e4d02041fd Mon Sep 17 00:00:00 2001 From: R4SAS Date: Sun, 11 Mar 2018 19:20:47 +0300 Subject: [PATCH 02/26] WITH_LIBRARY usage closes #1146. Need to be checked before. --- build/CMakeLists.txt | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/build/CMakeLists.txt b/build/CMakeLists.txt index 364c3304..fc9ca417 100644 --- a/build/CMakeLists.txt +++ b/build/CMakeLists.txt @@ -94,14 +94,17 @@ endif() add_library(libi2pd ${LIBI2PD_SRC}) set_target_properties(libi2pd PROPERTIES PREFIX "") -install(TARGETS libi2pd - EXPORT libi2pd - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - COMPONENT Libraries) + +if (WITH_LIBRARY) + install(TARGETS libi2pd + EXPORT libi2pd + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + COMPONENT Libraries) # TODO Make libi2pd available to 3rd party projects via CMake as imported target # FIXME This pulls stdafx # install(EXPORT libi2pd DESTINATION ${CMAKE_INSTALL_LIBDIR}) +endif() set (CLIENT_SRC "${LIBI2PD_CLIENT_SRC_DIR}/AddressBook.cpp" @@ -120,13 +123,17 @@ set (CLIENT_SRC if(WITH_WEBSOCKETS) list (APPEND CLIENT_SRC "${LIBI2PD_CLIENT_SRC_DIR}/Websocket.cpp") endif () + add_library(libi2pdclient ${CLIENT_SRC}) set_target_properties(libi2pdclient PROPERTIES PREFIX "") -install(TARGETS libi2pdclient - EXPORT libi2pdclient - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - COMPONENT Libraries) + +if (WITH_LIBRARY) + install(TARGETS libi2pdclient + EXPORT libi2pdclient + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + COMPONENT Libraries) +endif() set(DAEMON_SRC_DIR ../daemon) From b1a6c5ddf7787b4275ec77730f59fa1324159d6c Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 16 Mar 2018 11:12:18 -0400 Subject: [PATCH 03/26] fixed build for gcc 4.7 --- libi2pd/NTCPSession.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libi2pd/NTCPSession.cpp b/libi2pd/NTCPSession.cpp index e3d6c004..e0bd1135 100644 --- a/libi2pd/NTCPSession.cpp +++ b/libi2pd/NTCPSession.cpp @@ -178,7 +178,8 @@ namespace transport } // TODO: check for number of pending keys auto s = shared_from_this (); - m_Server.Work(s, [s]() -> std::function { + // TODO: we need to pass this for gcc 4.7, should be removed later on + m_Server.Work(s, [s, this]() -> std::function { if (!s->m_DHKeysPair) s->m_DHKeysPair = transports.GetNextDHKeysPair (); s->CreateAESKey (s->m_Establisher->phase1.pubKey); @@ -242,7 +243,8 @@ namespace transport else { auto s = shared_from_this (); - m_Server.Work(s, [s]() -> std::function { + // TODO: we need to pass this for gcc 4.7, should be removed later on + m_Server.Work(s, [s, this]() -> std::function { s->CreateAESKey (s->m_Establisher->phase2.pubKey); return std::bind(&NTCPSession::HandlePhase2, s); }); From b7c350202d63e7413bc4b21d61426fe6d5229340 Mon Sep 17 00:00:00 2001 From: orignal Date: Tue, 20 Mar 2018 20:43:47 -0400 Subject: [PATCH 04/26] always create EdDSA RouterInfo --- libi2pd/RouterContext.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/libi2pd/RouterContext.cpp b/libi2pd/RouterContext.cpp index 99f79df6..a82ace85 100644 --- a/libi2pd/RouterContext.cpp +++ b/libi2pd/RouterContext.cpp @@ -34,11 +34,7 @@ namespace i2p void RouterContext::CreateNewRouter () { -#if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER) m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519); -#else - m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); -#endif SaveKeys (); NewRouterInfo (); } From b041bcdc655c45fa106392cd272f8eddcb867326 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 23 Mar 2018 11:41:36 -0400 Subject: [PATCH 05/26] publish updated LeaseSet in destination's thread --- libi2pd/Destination.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libi2pd/Destination.cpp b/libi2pd/Destination.cpp index bafd49da..b7c2ee32 100644 --- a/libi2pd/Destination.cpp +++ b/libi2pd/Destination.cpp @@ -281,8 +281,12 @@ namespace client i2p::garlic::GarlicDestination::SetLeaseSetUpdated (); if (m_IsPublic) { - m_PublishVerificationTimer.cancel (); - Publish (); + auto s = shared_from_this (); + m_Service.post ([s](void) + { + s->m_PublishVerificationTimer.cancel (); + s->Publish (); + }); } } From 5361e11395114c4d6ccdb4489866364d906cc74a Mon Sep 17 00:00:00 2001 From: Jeff Becker Date: Tue, 20 Mar 2018 15:14:31 -0400 Subject: [PATCH 06/26] fix race --- libi2pd/NTCPSession.cpp | 33 +++++++++++++++++++++------------ libi2pd/NTCPSession.h | 6 ++++-- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/libi2pd/NTCPSession.cpp b/libi2pd/NTCPSession.cpp index e3d6c004..de4306e6 100644 --- a/libi2pd/NTCPSession.cpp +++ b/libi2pd/NTCPSession.cpp @@ -24,6 +24,12 @@ namespace i2p { namespace transport { + + struct NTCPWork + { + std::shared_ptr session; + }; + NTCPSession::NTCPSession (NTCPServer& server, std::shared_ptr in_RemoteRouter): TransportSession (in_RemoteRouter, NTCP_ESTABLISH_TIMEOUT), m_Server (server), m_Socket (m_Server.GetService ()), @@ -177,18 +183,20 @@ namespace transport } } // TODO: check for number of pending keys - auto s = shared_from_this (); - m_Server.Work(s, [s]() -> std::function { - if (!s->m_DHKeysPair) - s->m_DHKeysPair = transports.GetNextDHKeysPair (); - s->CreateAESKey (s->m_Establisher->phase1.pubKey); - return std::bind(&NTCPSession::SendPhase2, s); + auto work = new NTCPWork{shared_from_this()}; + m_Server.Work(work->session, [work]() -> std::function { + if (!work->session->m_DHKeysPair) + work->session->m_DHKeysPair = transports.GetNextDHKeysPair (); + work->session->CreateAESKey (work->session->m_Establisher->phase1.pubKey); + return std::bind(&NTCPSession::SendPhase2, work->session, work); }); } } - void NTCPSession::SendPhase2 () + void NTCPSession::SendPhase2 (NTCPWork * work) { + if(work) + delete work; const uint8_t * y = m_DHKeysPair->GetPublicKey (); memcpy (m_Establisher->phase2.pubKey, y, 256); uint8_t xy[512]; @@ -241,16 +249,17 @@ namespace transport } else { - auto s = shared_from_this (); - m_Server.Work(s, [s]() -> std::function { - s->CreateAESKey (s->m_Establisher->phase2.pubKey); - return std::bind(&NTCPSession::HandlePhase2, s); + auto work = new NTCPWork{shared_from_this()}; + m_Server.Work(work->session, [work]() -> std::function { + work->session->CreateAESKey (work->session->m_Establisher->phase2.pubKey); + return std::bind(&NTCPSession::HandlePhase2, work->session, work); }); } } - void NTCPSession::HandlePhase2 () + void NTCPSession::HandlePhase2 (NTCPWork * work) { + if(work) delete work; m_Decryption.SetIV (m_Establisher->phase2.pubKey + 240); m_Encryption.SetIV (m_Establisher->phase1.HXxorHI + 16); diff --git a/libi2pd/NTCPSession.h b/libi2pd/NTCPSession.h index 5335fbdd..e2207eb7 100644 --- a/libi2pd/NTCPSession.h +++ b/libi2pd/NTCPSession.h @@ -35,6 +35,8 @@ namespace transport } encrypted; }; + struct NTCPWork; + const size_t NTCP_MAX_MESSAGE_SIZE = 16384; const size_t NTCP_BUFFER_SIZE = 1028; // fits 1 tunnel data message const int NTCP_CONNECT_TIMEOUT = 5; // 5 seconds @@ -77,12 +79,12 @@ namespace transport void SendPhase3 (); void HandlePhase1Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandlePhase2Received (const boost::system::error_code& ecode, std::size_t bytes_transferred); - void HandlePhase2 (); + void HandlePhase2 (NTCPWork * work=nullptr); void HandlePhase3Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA); void HandlePhase4Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA); //server - void SendPhase2 (); + void SendPhase2 (NTCPWork * work=nullptr); void SendPhase4 (uint32_t tsA, uint32_t tsB); void HandlePhase1Received (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandlePhase2Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB); From f11266972e81a6db65aeecc3f77fe2b47418385c Mon Sep 17 00:00:00 2001 From: unlnown542a Date: Fri, 30 Mar 2018 15:50:30 +0300 Subject: [PATCH 07/26] Change jni to build executable. Clone with minimal changes DaemonUnix into DaemonAndroid --- android/jni/Android.mk | 8 +- android/jni/Application.mk | 8 +- android/jni/DaemonAndroid.cpp | 334 +++++++++++----------- android/jni/DaemonAndroid.h | 129 ++++----- android/jni/i2pd_android.cpp | 66 ----- android/jni/org_purplei2p_i2pd_I2PD_JNI.h | 33 --- 6 files changed, 227 insertions(+), 351 deletions(-) delete mode 100755 android/jni/i2pd_android.cpp delete mode 100644 android/jni/org_purplei2p_i2pd_I2PD_JNI.h diff --git a/android/jni/Android.mk b/android/jni/Android.mk index d5a8f05f..90284995 100755 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -12,15 +12,15 @@ LOCAL_STATIC_LIBRARIES := \ miniupnpc LOCAL_LDLIBS := -lz -LOCAL_SRC_FILES := DaemonAndroid.cpp i2pd_android.cpp $(IFADDRS_PATH)/ifaddrs.c \ +LOCAL_SRC_FILES := DaemonAndroid.cpp $(IFADDRS_PATH)/ifaddrs.c \ $(wildcard $(LIB_SRC_PATH)/*.cpp)\ $(wildcard $(LIB_CLIENT_SRC_PATH)/*.cpp)\ $(DAEMON_SRC_PATH)/Daemon.cpp \ $(DAEMON_SRC_PATH)/UPnP.cpp \ $(DAEMON_SRC_PATH)/HTTPServer.cpp \ - $(DAEMON_SRC_PATH)/I2PControl.cpp - -include $(BUILD_SHARED_LIBRARY) + $(DAEMON_SRC_PATH)/I2PControl.cpp \ + $(DAEMON_SRC_PATH)/i2pd.cpp +include $(BUILD_EXECUTABLE) LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) diff --git a/android/jni/Application.mk b/android/jni/Application.mk index 0fa116c2..acc6f895 100755 --- a/android/jni/Application.mk +++ b/android/jni/Application.mk @@ -9,12 +9,14 @@ APP_PLATFORM := android-14 # http://stackoverflow.com/a/21386866/529442 http://stackoverflow.com/a/15616255/529442 to enable c++11 support in Eclipse NDK_TOOLCHAIN_VERSION := 4.9 # APP_STL := stlport_shared --> does not seem to contain C++11 features -APP_STL := gnustl_shared +#APP_STL := gnustl_shared +APP_STL := gnustl_static # Enable c++11 extensions in source code -APP_CPPFLAGS += -std=c++11 +APP_CPPFLAGS += -std=c++11 -fvisibility=default -fPIE APP_CPPFLAGS += -DANDROID -D__ANDROID__ -DUSE_UPNP +APP_LDFLAGS += -rdynamic -fPIE -pie ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) APP_CPPFLAGS += -DANDROID_ARM7A endif @@ -26,7 +28,7 @@ APP_OPTIM := debug # git clone https://github.com/PurpleI2P/MiniUPnP-for-Android-Prebuilt.git # git clone https://github.com/PurpleI2P/android-ifaddrs.git # change to your own -I2PD_LIBS_PATH = /path/to/libraries +I2PD_LIBS_PATH = /home/u/build/i2p/daemon/static.libs BOOST_PATH = $(I2PD_LIBS_PATH)/Boost-for-Android-Prebuilt OPENSSL_PATH = $(I2PD_LIBS_PATH)/OpenSSL-for-Android-Prebuilt MINIUPNP_PATH = $(I2PD_LIBS_PATH)/MiniUPnP-for-Android-Prebuilt diff --git a/android/jni/DaemonAndroid.cpp b/android/jni/DaemonAndroid.cpp index 75584740..94c679be 100644 --- a/android/jni/DaemonAndroid.cpp +++ b/android/jni/DaemonAndroid.cpp @@ -1,193 +1,193 @@ #include "DaemonAndroid.h" -#include "Daemon.h" -#include -#include -#include -#include -//#include "mainwindow.h" -namespace i2p -{ -namespace android -{ -/* Worker::Worker (DaemonAndroidImpl& daemon): - m_Daemon (daemon) - { - } +#ifndef _WIN32 - void Worker::startDaemon() - { - Log.d(TAG"Performing daemon start..."); - m_Daemon.start(); - Log.d(TAG"Daemon started."); - emit resultReady(); - } - void Worker::restartDaemon() - { - Log.d(TAG"Performing daemon restart..."); - m_Daemon.restart(); - Log.d(TAG"Daemon restarted."); - emit resultReady(); - } - void Worker::stopDaemon() { - Log.d(TAG"Performing daemon stop..."); - m_Daemon.stop(); - Log.d(TAG"Daemon stopped."); - emit resultReady(); - } +#include +#include +#include +#include +#include +#include +#include - Controller::Controller(DaemonAndroidImpl& daemon): - m_Daemon (daemon) - { - Worker *worker = new Worker (m_Daemon); - worker->moveToThread(&workerThread); - connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater); - connect(this, &Controller::startDaemon, worker, &Worker::startDaemon); - connect(this, &Controller::stopDaemon, worker, &Worker::stopDaemon); - connect(this, &Controller::restartDaemon, worker, &Worker::restartDaemon); - connect(worker, &Worker::resultReady, this, &Controller::handleResults); - workerThread.start(); - } - Controller::~Controller() - { - Log.d(TAG"Closing and waiting for daemon worker thread..."); - workerThread.quit(); - workerThread.wait(); - Log.d(TAG"Waiting for daemon worker thread finished."); - if(m_Daemon.isRunning()) - { - Log.d(TAG"Stopping the daemon..."); - m_Daemon.stop(); - Log.d(TAG"Stopped the daemon."); - } - } -*/ - DaemonAndroidImpl::DaemonAndroidImpl () - //: - /*mutex(nullptr), */ - //m_IsRunning(false), - //m_RunningChangedCallback(nullptr) - { - } +#include "Config.h" +#include "FS.h" +#include "Log.h" +#include "Tunnel.h" +#include "RouterContext.h" +#include "ClientContext.h" - DaemonAndroidImpl::~DaemonAndroidImpl () - { - //delete mutex; - } - - bool DaemonAndroidImpl::init(int argc, char* argv[]) - { - //mutex=new QMutex(QMutex::Recursive); - //setRunningCallback(0); - //m_IsRunning=false; - return Daemon.init(argc,argv); - } - - void DaemonAndroidImpl::start() - { - //QMutexLocker locker(mutex); - //setRunning(true); - Daemon.start(); +void handle_signal(int sig) +{ + switch (sig) + { + case SIGHUP: + LogPrint(eLogInfo, "Daemon: Got SIGHUP, reopening tunnel configuration..."); + i2p::client::context.ReloadConfig(); + break; + case SIGUSR1: + LogPrint(eLogInfo, "Daemon: Got SIGUSR1, reopening logs..."); + i2p::log::Logger().Reopen (); + break; + case SIGINT: + if (i2p::context.AcceptsTunnels () && !Daemon.gracefulShutdownInterval) + { + i2p::context.SetAcceptsTunnels (false); + Daemon.gracefulShutdownInterval = 10*60; // 10 minutes + LogPrint(eLogInfo, "Graceful shutdown after ", Daemon.gracefulShutdownInterval, " seconds"); + } + else + Daemon.running = 0; + break; + case SIGABRT: + case SIGTERM: + Daemon.running = 0; // Exit loop + break; + case SIGPIPE: + LogPrint(eLogInfo, "SIGPIPE received"); + break; } +} - void DaemonAndroidImpl::stop() +namespace i2p +{ + namespace util { - //QMutexLocker locker(mutex); - Daemon.stop(); - //setRunning(false); - } + bool DaemonAndroid::start() + { + if (isDaemon) + { + pid_t pid; + pid = fork(); + if (pid > 0) // parent + ::exit (EXIT_SUCCESS); - void DaemonAndroidImpl::restart() - { - //QMutexLocker locker(mutex); - stop(); - start(); - } - /* - void DaemonAndroidImpl::setRunningCallback(runningChangedCallback cb) - { - m_RunningChangedCallback = cb; - } + if (pid < 0) // error + { + LogPrint(eLogError, "Daemon: could not fork: ", strerror(errno)); + return false; + } - bool DaemonAndroidImpl::isRunning() - { - return m_IsRunning; - } + // child + umask(S_IWGRP | S_IRWXO); // 0027 + int sid = setsid(); + if (sid < 0) + { + LogPrint(eLogError, "Daemon: could not create process group."); + return false; + } + std::string d = i2p::fs::GetDataDir(); + if (chdir(d.c_str()) != 0) + { + LogPrint(eLogError, "Daemon: could not chdir: ", strerror(errno)); + return false; + } - void DaemonAndroidImpl::setRunning(bool newValue) - { - bool oldValue = m_IsRunning; - if(oldValue!=newValue) - { - m_IsRunning = newValue; - if(m_RunningChangedCallback) - m_RunningChangedCallback(); - } - } -*/ - static DaemonAndroidImpl daemon; - static char* argv[1]={strdup("tmp")}; - /** - * returns error details if failed - * returns "ok" if daemon initialized and started okay - */ - std::string start(/*int argc, char* argv[]*/) - { - try - { - //int result; + // point std{in,out,err} descriptors to /dev/null + freopen("/dev/null", "r", stdin); + freopen("/dev/null", "w", stdout); + freopen("/dev/null", "w", stderr); + } + // set proc limits + struct rlimit limit; + uint16_t nfiles; i2p::config::GetOption("limits.openfiles", nfiles); + getrlimit(RLIMIT_NOFILE, &limit); + if (nfiles == 0) { + LogPrint(eLogInfo, "Daemon: using system limit in ", limit.rlim_cur, " max open files"); + } else if (nfiles <= limit.rlim_max) { + limit.rlim_cur = nfiles; + if (setrlimit(RLIMIT_NOFILE, &limit) == 0) { + LogPrint(eLogInfo, "Daemon: set max number of open files to ", + nfiles, " (system limit is ", limit.rlim_max, ")"); + } else { + LogPrint(eLogError, "Daemon: can't set max number of open files: ", strerror(errno)); + } + } else { + LogPrint(eLogError, "Daemon: limits.openfiles exceeds system limit: ", limit.rlim_max); + } + uint32_t cfsize; i2p::config::GetOption("limits.coresize", cfsize); + if (cfsize) // core file size set { - //Log.d(TAG"Initialising the daemon..."); - bool daemonInitSuccess = daemon.init(1,argv); - if(!daemonInitSuccess) - { - //QMessageBox::critical(0, "Error", "Daemon init failed"); - return "Daemon init failed"; + cfsize *= 1024; + getrlimit(RLIMIT_CORE, &limit); + if (cfsize <= limit.rlim_max) { + limit.rlim_cur = cfsize; + if (setrlimit(RLIMIT_CORE, &limit) != 0) { + LogPrint(eLogError, "Daemon: can't set max size of coredump: ", strerror(errno)); + } else if (cfsize == 0) { + LogPrint(eLogInfo, "Daemon: coredumps disabled"); + } else { + LogPrint(eLogInfo, "Daemon: set max size of core files to ", cfsize / 1024, "Kb"); + } + } else { + LogPrint(eLogError, "Daemon: limits.coresize exceeds system limit: ", limit.rlim_max); } - //Log.d(TAG"Initialised, creating the main window..."); - //MainWindow w; - //Log.d(TAG"Before main window.show()..."); - //w.show (); + } + // Pidfile + // this code is c-styled and a bit ugly + std::string pidfile; i2p::config::GetOption("pidfile", pidfile); + if (pidfile == "") { + pidfile = i2p::fs::DataDirPath("i2pd.pid"); + } + if (pidfile != "") { + pidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600); + if (pidFH < 0) + { + LogPrint(eLogError, "Daemon: could not create pid file ", pidfile, ": ", strerror(errno)); + return false; + } + char pid[10]; + sprintf(pid, "%d\n", getpid()); + ftruncate(pidFH, 0); + if (write(pidFH, pid, strlen(pid)) < 0) { - //i2p::qt::Controller daemonQtController(daemon); - //Log.d(TAG"Starting the daemon..."); - //emit daemonQtController.startDaemon(); - //daemon.start (); - //Log.d(TAG"Starting GUI event loop..."); - //result = app.exec(); - //daemon.stop (); - daemon.start(); + LogPrint(eLogError, "Daemon: could not write pidfile: ", strerror(errno)); + return false; } } + gracefulShutdownInterval = 0; // not specified - //QMessageBox::information(&w, "Debug", "demon stopped"); - //Log.d(TAG"Exiting the application"); - //return result; - } - catch (boost::exception& ex) - { - std::stringstream ss; - ss << boost::diagnostic_information(ex); - return ss.str(); + // Signal handler + struct sigaction sa; + sa.sa_handler = handle_signal; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + sigaction(SIGHUP, &sa, 0); + sigaction(SIGUSR1, &sa, 0); + sigaction(SIGABRT, &sa, 0); + sigaction(SIGTERM, &sa, 0); + sigaction(SIGINT, &sa, 0); + sigaction(SIGPIPE, &sa, 0); + + return Daemon_Singleton::start(); } - catch (std::exception& ex) + + bool DaemonAndroid::stop() { - std::stringstream ss; - ss << ex.what(); - return ss.str(); + i2p::fs::Remove(pidfile); + + return Daemon_Singleton::stop(); } - catch(...) + + void DaemonAndroid::run () { - return "unknown exception"; + while (running) + { + std::this_thread::sleep_for (std::chrono::seconds(1)); + if (gracefulShutdownInterval) + { + gracefulShutdownInterval--; // - 1 second + if (gracefulShutdownInterval <= 0 || i2p::tunnel::tunnels.CountTransitTunnels() <= 0) + { + LogPrint(eLogInfo, "Graceful shutdown"); + return; + } + } + } } - return "ok"; - } - - void stop() - { - daemon.stop(); } } -} + +#endif diff --git a/android/jni/DaemonAndroid.h b/android/jni/DaemonAndroid.h index 9cc8219b..c62d7c76 100644 --- a/android/jni/DaemonAndroid.h +++ b/android/jni/DaemonAndroid.h @@ -1,87 +1,60 @@ -#ifndef DAEMON_ANDROID_H -#define DAEMON_ANDROID_H +#ifndef DAEMON_H__ +#define DAEMON_H__ +#include #include namespace i2p { -namespace android +namespace util { - class DaemonAndroidImpl - { - public: - - DaemonAndroidImpl (); - ~DaemonAndroidImpl (); - - //typedef void (*runningChangedCallback)(); - - /** - * @return success - */ - bool init(int argc, char* argv[]); - void start(); - void stop(); - void restart(); - //void setRunningCallback(runningChangedCallback cb); - //bool isRunning(); - private: - //void setRunning(bool running); - private: - //QMutex* mutex; - //bool m_IsRunning; - //runningChangedCallback m_RunningChangedCallback; - }; - - /** - * returns "ok" if daemon init failed - * returns errinfo if daemon initialized and started okay - */ - std::string start(); - - // stops the daemon - void stop(); - - /* - class Worker : public QObject - { - Q_OBJECT - public: - - Worker (DaemonAndroidImpl& daemon); - - private: - - DaemonAndroidImpl& m_Daemon; - - public slots: - void startDaemon(); - void restartDaemon(); - void stopDaemon(); - - signals: - void resultReady(); - }; - - class Controller : public QObject - { - Q_OBJECT - QThread workerThread; - public: - Controller(DaemonAndroidImpl& daemon); - ~Controller(); - private: - DaemonAndroidImpl& m_Daemon; - - public slots: - void handleResults(){} - signals: - void startDaemon(); - void stopDaemon(); - void restartDaemon(); - }; - */ + class Daemon_Singleton_Private; + class Daemon_Singleton + { + public: + virtual bool init(int argc, char* argv[]); + virtual bool start(); + virtual bool stop(); + virtual void run () {}; + + bool isDaemon; + bool running; + + protected: + Daemon_Singleton(); + virtual ~Daemon_Singleton(); + + bool IsService () const; + + // d-pointer for httpServer, httpProxy, etc. + class Daemon_Singleton_Private; + Daemon_Singleton_Private &d; + }; + +#if defined(ANDROID) +#define Daemon i2p::util::DaemonAndroid::Instance() + class DaemonAndroid : public Daemon_Singleton + { + public: + static DaemonAndroid& Instance() + { + static DaemonAndroid instance; + return instance; + } + + bool start(); + bool stop(); + void run (); + + private: + std::string pidfile; + int pidFH; + + public: + int gracefulShutdownInterval; // in seconds + }; +#endif } } -#endif // DAEMON_ANDROID_H +#endif // DAEMON_H__ diff --git a/android/jni/i2pd_android.cpp b/android/jni/i2pd_android.cpp deleted file mode 100755 index 8791c90b..00000000 --- a/android/jni/i2pd_android.cpp +++ /dev/null @@ -1,66 +0,0 @@ - -//#include -#include -#include "org_purplei2p_i2pd_I2PD_JNI.h" -#include "DaemonAndroid.h" -#include "RouterContext.h" -#include "Transports.h" - -JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_getABICompiledWith - (JNIEnv * env, jclass clazz) { -#if defined(__arm__) - #if defined(__ARM_ARCH_7A__) - #if defined(__ARM_NEON__) - #if defined(__ARM_PCS_VFP) - #define ABI "armeabi-v7a/NEON (hard-float)" - #else - #define ABI "armeabi-v7a/NEON" - #endif - #else - #if defined(__ARM_PCS_VFP) - #define ABI "armeabi-v7a (hard-float)" - #else - #define ABI "armeabi-v7a" - #endif - #endif - #else - #define ABI "armeabi" - #endif -#elif defined(__i386__) - #define ABI "x86" -#elif defined(__x86_64__) - #define ABI "x86_64" -#elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */ - #define ABI "mips64" -#elif defined(__mips__) - #define ABI "mips" -#elif defined(__aarch64__) - #define ABI "arm64-v8a" -#else - #define ABI "unknown" -#endif - - return env->NewStringUTF(ABI); -} - -JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_startDaemon - (JNIEnv * env, jclass clazz) { - return env->NewStringUTF(i2p::android::start().c_str()); -} - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopDaemon - (JNIEnv * env, jclass clazz) { - i2p::android::stop(); -} - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopAcceptingTunnels - (JNIEnv * env, jclass clazz) { - i2p::context.SetAcceptsTunnels (false); -} - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_onNetworkStateChanged - (JNIEnv * env, jclass clazz, jboolean isConnected) -{ - bool isConnectedBool = (bool) isConnected; - i2p::transport::transports.SetOnline (isConnectedBool); -} diff --git a/android/jni/org_purplei2p_i2pd_I2PD_JNI.h b/android/jni/org_purplei2p_i2pd_I2PD_JNI.h deleted file mode 100644 index 04923d22..00000000 --- a/android/jni/org_purplei2p_i2pd_I2PD_JNI.h +++ /dev/null @@ -1,33 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class org_purplei2p_i2pd_I2PD_JNI */ - -#ifndef _Included_org_purplei2p_i2pd_I2PD_JNI -#define _Included_org_purplei2p_i2pd_I2PD_JNI -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: org_purplei2p_i2pd_I2PD_JNI - * Method: stringFromJNI - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_getABICompiledWith - (JNIEnv *, jclass); - -JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_startDaemon - (JNIEnv *, jclass); - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopDaemon - (JNIEnv *, jclass); - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopAcceptingTunnels - (JNIEnv *, jclass); - -JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_onNetworkStateChanged - (JNIEnv * env, jclass clazz, jboolean isConnected); - -#ifdef __cplusplus -} -#endif -#endif From f06c8710be43440526c487400aa5c681d30172ad Mon Sep 17 00:00:00 2001 From: yangfl Date: Sat, 31 Mar 2018 14:56:45 +0800 Subject: [PATCH 08/26] fix systemd service type --- contrib/i2pd.service | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/i2pd.service b/contrib/i2pd.service index 9af96c37..ecfb4e20 100644 --- a/contrib/i2pd.service +++ b/contrib/i2pd.service @@ -10,7 +10,7 @@ RuntimeDirectory=i2pd RuntimeDirectoryMode=0700 LogsDirectory=i2pd LogsDirectoryMode=0700 -Type=simple +Type=fork ExecStart=/usr/sbin/i2pd --conf=/etc/i2pd/i2pd.conf --tunconf=/etc/i2pd/tunnels.conf --pidfile=/var/run/i2pd/i2pd.pid --logfile=/var/log/i2pd/i2pd.log --daemon --service ExecReload=/bin/kill -HUP $MAINPID PIDFile=/var/run/i2pd/i2pd.pid From c0436297c2e8f4d3fad2b7658b99b81c150a74df Mon Sep 17 00:00:00 2001 From: yangfl Date: Sun, 1 Apr 2018 22:57:51 +0800 Subject: [PATCH 09/26] fix typo in systemd service type --- contrib/i2pd.service | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/i2pd.service b/contrib/i2pd.service index ecfb4e20..3f53bfb8 100644 --- a/contrib/i2pd.service +++ b/contrib/i2pd.service @@ -10,7 +10,7 @@ RuntimeDirectory=i2pd RuntimeDirectoryMode=0700 LogsDirectory=i2pd LogsDirectoryMode=0700 -Type=fork +Type=forking ExecStart=/usr/sbin/i2pd --conf=/etc/i2pd/i2pd.conf --tunconf=/etc/i2pd/tunnels.conf --pidfile=/var/run/i2pd/i2pd.pid --logfile=/var/log/i2pd/i2pd.log --daemon --service ExecReload=/bin/kill -HUP $MAINPID PIDFile=/var/run/i2pd/i2pd.pid From e80da3cbeba3fd37c25637409b93e9c00dc3fcbf Mon Sep 17 00:00:00 2001 From: Hypnosis-mewmew Date: Thu, 5 Apr 2018 15:40:44 +0800 Subject: [PATCH 10/26] fixes for i2pd_qt MSYS2 mingw32 --- libi2pd/RouterContext.h | 5 +++++ libi2pd/RouterInfo.h | 5 +++++ qt/i2pd_qt/i2pd_qt.pro | 10 ++++++++-- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/libi2pd/RouterContext.h b/libi2pd/RouterContext.h index 4bd324f5..9f42b1e0 100644 --- a/libi2pd/RouterContext.h +++ b/libi2pd/RouterContext.h @@ -1,6 +1,11 @@ #ifndef ROUTER_CONTEXT_H__ #define ROUTER_CONTEXT_H__ +// i2pd_qt.pro defines this on Windows +#ifdef WINDOWS +#include +#endif + #include #include #include diff --git a/libi2pd/RouterInfo.h b/libi2pd/RouterInfo.h index 09e2c015..09db6ee8 100644 --- a/libi2pd/RouterInfo.h +++ b/libi2pd/RouterInfo.h @@ -1,6 +1,11 @@ #ifndef ROUTER_INFO_H__ #define ROUTER_INFO_H__ +// i2pd_qt.pro defines this on Windows +#ifdef WINDOWS +#include +#endif + #include #include #include diff --git a/qt/i2pd_qt/i2pd_qt.pro b/qt/i2pd_qt/i2pd_qt.pro index a2ba4261..941dfff3 100644 --- a/qt/i2pd_qt/i2pd_qt.pro +++ b/qt/i2pd_qt/i2pd_qt.pro @@ -268,8 +268,14 @@ android { } linux:!android { - message("Using Linux settings") - LIBS += -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread -lminiupnpc + message("Using Linux settings") + LIBS += -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread -lminiupnpc +} + +windows:!android { + message("Using Windows settings") + DEFINES += BOOST_USE_WINDOWS_H WINDOWS + LIBS += -lcrypto -lssl -lboost_system -lboost_date_time -lboost_filesystem -lboost_program_options -lpthread -lminiupnpc } !android:!symbian:!maemo5:!simulator { From f4056e57bb37aee6609aafafd5d33b752e19afb2 Mon Sep 17 00:00:00 2001 From: orignal Date: Thu, 5 Apr 2018 07:16:41 -0400 Subject: [PATCH 11/26] rollback --- libi2pd/RouterContext.h | 5 ----- libi2pd/RouterInfo.h | 5 ----- 2 files changed, 10 deletions(-) diff --git a/libi2pd/RouterContext.h b/libi2pd/RouterContext.h index 9f42b1e0..4bd324f5 100644 --- a/libi2pd/RouterContext.h +++ b/libi2pd/RouterContext.h @@ -1,11 +1,6 @@ #ifndef ROUTER_CONTEXT_H__ #define ROUTER_CONTEXT_H__ -// i2pd_qt.pro defines this on Windows -#ifdef WINDOWS -#include -#endif - #include #include #include diff --git a/libi2pd/RouterInfo.h b/libi2pd/RouterInfo.h index 09db6ee8..09e2c015 100644 --- a/libi2pd/RouterInfo.h +++ b/libi2pd/RouterInfo.h @@ -1,11 +1,6 @@ #ifndef ROUTER_INFO_H__ #define ROUTER_INFO_H__ -// i2pd_qt.pro defines this on Windows -#ifdef WINDOWS -#include -#endif - #include #include #include From 2cb6283d004b37c145cfd08e8a1a1521651e7868 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 6 Apr 2018 15:23:56 -0400 Subject: [PATCH 12/26] outproxy authorization --- libi2pd/Base.cpp | 15 +++++++++++++++ libi2pd/Base.h | 9 ++++++--- libi2pd_client/HTTPProxy.cpp | 18 +++++++++++++++--- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/libi2pd/Base.cpp b/libi2pd/Base.cpp index 09f04c05..f80f2751 100644 --- a/libi2pd/Base.cpp +++ b/libi2pd/Base.cpp @@ -210,6 +210,21 @@ namespace data return 4*d.quot; } + std::string ToBase64Standard (const std::string& in) + { + auto len = Base64EncodingBufferSize (in.length ()); + char * str = new char[len+1]; + auto l = ByteStreamToBase64 ((const uint8_t *)in.c_str (), in.length (), str, len); + str[l] = 0; + // replace '-' by '+' and '~' by '/' + for (size_t i = 0; i < l; i++) + if (str[i] == '-') str[i] = '+'; + else if (str[i] == '~') str[i] = '/'; + std::string s(str); + delete[] str; + return s; + } + /* * * iT64 diff --git a/libi2pd/Base.h b/libi2pd/Base.h index bc92376f..a273f468 100644 --- a/libi2pd/Base.h +++ b/libi2pd/Base.h @@ -15,10 +15,13 @@ namespace data { size_t Base32ToByteStream (const char * inBuf, size_t len, uint8_t * outBuf, size_t outLen); size_t ByteStreamToBase32 (const uint8_t * InBuf, size_t len, char * outBuf, size_t outLen); - /** + /** Compute the size for a buffer to contain encoded base64 given that the size of the input is input_size bytes - */ - size_t Base64EncodingBufferSize(const size_t input_size); + */ + size_t Base64EncodingBufferSize(const size_t input_size); + + std::string ToBase64Standard (const std::string& in); // using standard table, for Proxy-Authorization + } // data } // i2p diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index ac5d907d..47f756d3 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -389,11 +389,19 @@ namespace proxy { m_ClientRequestURL.host = ""; m_ClientRequest.uri = m_ClientRequestURL.to_string(); + if (m_ProxyURL.schema == "http" && (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ())) + { + // http proxy authorization + std::string s = "basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); + m_ClientRequest.AddHeader("Proxy-Authorization", s); + } + m_ClientRequest.write(m_ClientRequestBuffer); m_ClientRequestBuffer << m_recv_buf.substr(m_req_len); // assume http if empty schema - if (m_ProxyURL.schema == "" || m_ProxyURL.schema == "http") { + if (m_ProxyURL.schema == "" || m_ProxyURL.schema == "http") + { // handle upstream http proxy if (!m_ProxyURL.port) m_ProxyURL.port = 80; if (m_ProxyURL.is_i2p()) @@ -409,14 +417,18 @@ namespace proxy { m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamHTTPProxyConnect, this, std::placeholders::_1)); })); } - } else if (m_ProxyURL.schema == "socks") { + } + else if (m_ProxyURL.schema == "socks") + { // handle upstream socks proxy if (!m_ProxyURL.port) m_ProxyURL.port = 9050; // default to tor default if not specified boost::asio::ip::tcp::resolver::query q(m_ProxyURL.host, std::to_string(m_ProxyURL.port)); m_proxy_resolver.async_resolve(q, std::bind(&HTTPReqHandler::HandleUpstreamProxyResolved, this, std::placeholders::_1, std::placeholders::_2, [&](boost::asio::ip::tcp::endpoint ep) { m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamSocksProxyConnect, this, std::placeholders::_1)); })); - } else { + } + else + { // unknown type, complain GenericProxyError("unknown outproxy url", m_ProxyURL.to_string().c_str()); } From ff4e254618a2724a23f316c1ad8c5257640cadc5 Mon Sep 17 00:00:00 2001 From: orignal Date: Wed, 11 Apr 2018 10:30:13 -0400 Subject: [PATCH 13/26] 0.9.34 --- libi2pd/version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libi2pd/version.h b/libi2pd/version.h index 36e7eb6e..e0443415 100644 --- a/libi2pd/version.h +++ b/libi2pd/version.h @@ -21,7 +21,7 @@ #define I2P_VERSION_MAJOR 0 #define I2P_VERSION_MINOR 9 -#define I2P_VERSION_MICRO 33 +#define I2P_VERSION_MICRO 34 #define I2P_VERSION_PATCH 0 #define I2P_VERSION MAKE_VERSION(I2P_VERSION_MAJOR, I2P_VERSION_MINOR, I2P_VERSION_MICRO) From 82534eef1216510eea7e4e5ede9c27d2099953f0 Mon Sep 17 00:00:00 2001 From: R4SAS Date: Wed, 11 Apr 2018 20:58:21 +0300 Subject: [PATCH 14/26] try fix appveyor build --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index f663c86a..68b74529 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -17,7 +17,7 @@ environment: - MSYSTEM: MINGW32 install: -- c:\msys64\usr\bin\bash -lc "pacman --noconfirm -Rns gcc-fortran gcc catgets" +- c:\msys64\usr\bin\bash -lc "pacman --noconfirm -Rns gcc-fortran gcc" - c:\msys64\usr\bin\bash -lc "pacman --noconfirm -Syuu " - c:\msys64\usr\bin\bash -lc "pacman --noconfirm -Syuu" From 855cc9ed83b0cfb8a6efb844dc872d9a876cbbac Mon Sep 17 00:00:00 2001 From: orignal Date: Thu, 12 Apr 2018 19:10:21 -0400 Subject: [PATCH 15/26] correct Proxy-Authroization --- libi2pd_client/HTTPProxy.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index 47f756d3..ffabb61d 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -282,6 +282,7 @@ namespace proxy { bool useConnect = false; if(m_ClientRequest.method == "CONNECT") { + m_ClientRequest.RemoveHeader("Proxy-"); std::string uri(m_ClientRequest.uri); auto pos = uri.find(":"); if(pos == std::string::npos || pos == uri.size() - 1) @@ -392,7 +393,7 @@ namespace proxy { if (m_ProxyURL.schema == "http" && (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ())) { // http proxy authorization - std::string s = "basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); + std::string s = "Basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); m_ClientRequest.AddHeader("Proxy-Authorization", s); } From 387e030d83cabee89913386271534d1d1259a881 Mon Sep 17 00:00:00 2001 From: orignal Date: Thu, 12 Apr 2018 21:25:20 -0400 Subject: [PATCH 16/26] correct cleanup for CONNECT --- libi2pd_client/HTTPProxy.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index ffabb61d..2778f24a 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -219,7 +219,7 @@ namespace proxy { /* replace headers */ req.UpdateHeader("User-Agent", "MYOB/6.66 (AN/ON)"); /* add headers */ - req.AddHeader("Connection", "close"); /* keep-alive conns not supported yet */ + req.UpdateHeader("Connection", "close"); /* keep-alive conns not supported yet */ } /** @@ -282,7 +282,7 @@ namespace proxy { bool useConnect = false; if(m_ClientRequest.method == "CONNECT") { - m_ClientRequest.RemoveHeader("Proxy-"); + SanitizeHTTPRequest (m_ClientRequest); std::string uri(m_ClientRequest.uri); auto pos = uri.find(":"); if(pos == std::string::npos || pos == uri.size() - 1) @@ -399,7 +399,7 @@ namespace proxy { m_ClientRequest.write(m_ClientRequestBuffer); m_ClientRequestBuffer << m_recv_buf.substr(m_req_len); - + // assume http if empty schema if (m_ProxyURL.schema == "" || m_ProxyURL.schema == "http") { From a9b64893d83bffbe8e908e0932b6eab560b40811 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 13 Apr 2018 12:47:53 -0400 Subject: [PATCH 17/26] replace Proxy-Authorization --- libi2pd_client/HTTPProxy.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index 2778f24a..5f00ffdb 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -282,7 +282,6 @@ namespace proxy { bool useConnect = false; if(m_ClientRequest.method == "CONNECT") { - SanitizeHTTPRequest (m_ClientRequest); std::string uri(m_ClientRequest.uri); auto pos = uri.find(":"); if(pos == std::string::npos || pos == uri.size() - 1) @@ -392,7 +391,9 @@ namespace proxy { if (m_ProxyURL.schema == "http" && (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ())) { - // http proxy authorization + // remove existing authorization if any + m_ClientRequest.RemoveHeader("Proxy-"); + // add own http proxy authorization std::string s = "Basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); m_ClientRequest.AddHeader("Proxy-Authorization", s); } From 48099a367e3fd967623f042d8f33d791e046cb09 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 13 Apr 2018 15:13:50 -0400 Subject: [PATCH 18/26] send correct buffer to outproxy --- libi2pd_client/HTTPProxy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index 5f00ffdb..805b3247 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -408,7 +408,7 @@ namespace proxy { if (!m_ProxyURL.port) m_ProxyURL.port = 80; if (m_ProxyURL.is_i2p()) { - m_send_buf = m_recv_buf; + m_send_buf = m_ClientRequestBuffer.str (); GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1), m_ProxyURL.host, m_ProxyURL.port); } From 17aa91803a0019dd2a557956ff044bcf729434f5 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 13 Apr 2018 15:40:25 -0400 Subject: [PATCH 19/26] update outproxy header in right place --- libi2pd_client/HTTPProxy.cpp | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index 805b3247..69cda97f 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -389,15 +389,6 @@ namespace proxy { m_ClientRequestURL.host = ""; m_ClientRequest.uri = m_ClientRequestURL.to_string(); - if (m_ProxyURL.schema == "http" && (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ())) - { - // remove existing authorization if any - m_ClientRequest.RemoveHeader("Proxy-"); - // add own http proxy authorization - std::string s = "Basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); - m_ClientRequest.AddHeader("Proxy-Authorization", s); - } - m_ClientRequest.write(m_ClientRequestBuffer); m_ClientRequestBuffer << m_recv_buf.substr(m_req_len); @@ -408,7 +399,17 @@ namespace proxy { if (!m_ProxyURL.port) m_ProxyURL.port = 80; if (m_ProxyURL.is_i2p()) { - m_send_buf = m_ClientRequestBuffer.str (); + if (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ()) + { + // remove existing authorization if any + m_ClientRequest.RemoveHeader("Proxy-"); + // add own http proxy authorization + std::string s = "Basic " + i2p::data::ToBase64Standard (m_ProxyURL.user + ":" + m_ProxyURL.pass); + m_ClientRequest.AddHeader("Proxy-Authorization", s); + } + m_send_buf = m_ClientRequest.to_string(); + m_recv_buf.erase(0, m_req_len); + m_send_buf.append(m_recv_buf); GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1), m_ProxyURL.host, m_ProxyURL.port); } From c175dc30f8b0fd4365f77e310eedbc44e2abcca9 Mon Sep 17 00:00:00 2001 From: orignal Date: Fri, 13 Apr 2018 16:29:49 -0400 Subject: [PATCH 20/26] correct uri for outproxy --- libi2pd_client/HTTPProxy.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libi2pd_client/HTTPProxy.cpp b/libi2pd_client/HTTPProxy.cpp index 69cda97f..ea95a6bd 100644 --- a/libi2pd_client/HTTPProxy.cpp +++ b/libi2pd_client/HTTPProxy.cpp @@ -387,6 +387,7 @@ namespace proxy { LogPrint(eLogDebug, "HTTPProxy: ", m_ClientRequestURL.host); m_ClientRequestURL.schema = ""; m_ClientRequestURL.host = ""; + std::string origURI = m_ClientRequest.uri; // TODO: what do we need to chage uri for? m_ClientRequest.uri = m_ClientRequestURL.to_string(); m_ClientRequest.write(m_ClientRequestBuffer); @@ -399,6 +400,7 @@ namespace proxy { if (!m_ProxyURL.port) m_ProxyURL.port = 80; if (m_ProxyURL.is_i2p()) { + m_ClientRequest.uri = origURI; if (!m_ProxyURL.user.empty () || !m_ProxyURL.pass.empty ()) { // remove existing authorization if any From 83932a6f0272a29e0128a77562f0543492221e75 Mon Sep 17 00:00:00 2001 From: Jeff Becker Date: Mon, 16 Apr 2018 09:38:32 -0400 Subject: [PATCH 21/26] remove streaming bans --- libi2pd/Streaming.cpp | 76 +------------------------------- libi2pd/Streaming.h | 31 ------------- libi2pd_client/ClientContext.cpp | 4 +- libi2pd_client/I2PTunnel.h | 2 - 4 files changed, 3 insertions(+), 110 deletions(-) diff --git a/libi2pd/Streaming.cpp b/libi2pd/Streaming.cpp index 91acc9d0..afcda9ec 100644 --- a/libi2pd/Streaming.cpp +++ b/libi2pd/Streaming.cpp @@ -904,10 +904,7 @@ namespace stream m_Owner (owner), m_LocalPort (localPort), m_Gzip (gzip), m_LastIncomingReceiveStreamID (0), m_PendingIncomingTimer (m_Owner->GetService ()), - m_ConnTrackTimer(m_Owner->GetService()), - m_ConnsPerMinute(DEFAULT_MAX_CONNS_PER_MIN), - m_LastBanClear(i2p::util::GetMillisecondsSinceEpoch()), - m_EnableDrop(false) + m_ConnTrackTimer(m_Owner->GetService()) { } @@ -923,7 +920,6 @@ namespace stream void StreamingDestination::Start () { - ScheduleConnTrack(); } void StreamingDestination::Stop () @@ -971,17 +967,7 @@ namespace stream auto incomingStream = CreateNewIncomingStream (); incomingStream->HandleNextPacket (packet); // SYN auto ident = incomingStream->GetRemoteIdentity(); - if(ident && m_EnableDrop) - { - auto ih = ident->GetIdentHash(); - if(DropNewStream(ih)) - { - // drop - LogPrint(eLogWarning, "Streaming: Dropping connection, too many inbound streams from ", ih.ToBase32()); - incomingStream->Terminate(); - return; - } - } + m_LastIncomingReceiveStreamID = receiveStreamID; // handle saved packets if any @@ -1176,63 +1162,5 @@ namespace stream return msg; } - void StreamingDestination::SetMaxConnsPerMinute(const uint32_t conns) - { - m_EnableDrop = conns > 0; - m_ConnsPerMinute = conns; - LogPrint(eLogDebug, "Streaming: Set max conns per minute per destination to ", conns); - } - - bool StreamingDestination::DropNewStream(const i2p::data::IdentHash & ih) - { - std::lock_guard lock(m_ConnsMutex); - if (m_Banned.size() > MAX_BANNED_CONNS) return true; // overload - auto end = std::end(m_Banned); - if ( std::find(std::begin(m_Banned), end, ih) != end) return true; // already banned - auto itr = m_Conns.find(ih); - if (itr == m_Conns.end()) - m_Conns[ih] = 0; - - m_Conns[ih] += 1; - - bool ban = m_Conns[ih] >= m_ConnsPerMinute; - if (ban) - { - m_Banned.push_back(ih); - m_Conns.erase(ih); - LogPrint(eLogWarning, "Streaming: ban ", ih.ToBase32()); - } - return ban; - } - - void StreamingDestination::HandleConnTrack(const boost::system::error_code& ecode) - { - if (ecode != boost::asio::error::operation_aborted) - { - { // acquire lock - std::lock_guard lock(m_ConnsMutex); - // clear conn tracking - m_Conns.clear(); - // check for ban clear - auto ts = i2p::util::GetMillisecondsSinceEpoch(); - if (ts - m_LastBanClear >= DEFAULT_BAN_INTERVAL) - { - // clear bans - m_Banned.clear(); - m_LastBanClear = ts; - } - } - // reschedule timer - ScheduleConnTrack(); - } - } - - void StreamingDestination::ScheduleConnTrack() - { - m_ConnTrackTimer.expires_from_now (boost::posix_time::seconds(60)); - m_ConnTrackTimer.async_wait ( - std::bind (&StreamingDestination::HandleConnTrack, - shared_from_this (), std::placeholders::_1)); - } } } diff --git a/libi2pd/Streaming.h b/libi2pd/Streaming.h index a114844d..9ce7e210 100644 --- a/libi2pd/Streaming.h +++ b/libi2pd/Streaming.h @@ -53,22 +53,6 @@ namespace stream const int PENDING_INCOMING_TIMEOUT = 10; // in seconds const int MAX_RECEIVE_TIMEOUT = 30; // in seconds - /** i2cp option for limiting inbound stremaing connections */ - const char I2CP_PARAM_STREAMING_MAX_CONNS_PER_MIN[] = "maxconns"; - /** default maximum connections attempts per minute per destination */ - const uint32_t DEFAULT_MAX_CONNS_PER_MIN = 600; - - /** - * max banned destinations per local destination - * TODO: make configurable - */ - const uint16_t MAX_BANNED_CONNS = 9999; - /** - * length of a ban in ms - * TODO: make configurable - */ - const uint64_t DEFAULT_BAN_INTERVAL = 60 * 60 * 1000; - struct Packet { size_t len, offset; @@ -273,9 +257,6 @@ namespace stream void HandleDataMessagePayload (const uint8_t * buf, size_t len); std::shared_ptr CreateDataMessage (const uint8_t * payload, size_t len, uint16_t toPort); - /** set max connections per minute per destination */ - void SetMaxConnsPerMinute(const uint32_t conns); - Packet * NewPacket () { return m_PacketsPool.Acquire(); } void DeletePacket (Packet * p) { return m_PacketsPool.Release(p); } @@ -286,13 +267,6 @@ namespace stream std::shared_ptr CreateNewIncomingStream (); void HandlePendingIncomingTimer (const boost::system::error_code& ecode); - /** handle cleaning up connection tracking for ratelimits */ - void HandleConnTrack(const boost::system::error_code& ecode); - - bool DropNewStream(const i2p::data::IdentHash & ident); - - void ScheduleConnTrack(); - private: std::shared_ptr m_Owner; @@ -310,13 +284,8 @@ namespace stream /** how many connections per minute did each identity have */ std::map m_Conns; boost::asio::deadline_timer m_ConnTrackTimer; - uint32_t m_ConnsPerMinute; - /** banned identities */ - std::vector m_Banned; - uint64_t m_LastBanClear; i2p::util::MemoryPool m_PacketsPool; - bool m_EnableDrop; public: diff --git a/libi2pd_client/ClientContext.cpp b/libi2pd_client/ClientContext.cpp index fb8fff97..b04ab885 100644 --- a/libi2pd_client/ClientContext.cpp +++ b/libi2pd_client/ClientContext.cpp @@ -567,7 +567,7 @@ namespace client bool gzip = section.second.get (I2P_SERVER_TUNNEL_GZIP, true); i2p::data::SigningKeyType sigType = section.second.get (I2P_SERVER_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256); i2p::data::CryptoKeyType cryptoType = section.second.get (I2P_CLIENT_TUNNEL_CRYPTO_TYPE, i2p::data::CRYPTO_KEY_TYPE_ELGAMAL); - uint32_t maxConns = section.second.get(i2p::stream::I2CP_PARAM_STREAMING_MAX_CONNS_PER_MIN, i2p::stream::DEFAULT_MAX_CONNS_PER_MIN); + std::string address = section.second.get (I2P_SERVER_TUNNEL_ADDRESS, "127.0.0.1"); bool isUniqueLocal = section.second.get(I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL, true); @@ -618,8 +618,6 @@ namespace client else // regular server tunnel by default serverTunnel = new I2PServerTunnel (name, host, port, localDestination, inPort, gzip); - LogPrint(eLogInfo, "Clients: Set Max Conns To ", maxConns); - serverTunnel->SetMaxConnsPerMinute(maxConns); if(!isUniqueLocal) { LogPrint(eLogInfo, "Clients: disabling loopback address mapping"); diff --git a/libi2pd_client/I2PTunnel.h b/libi2pd_client/I2PTunnel.h index 1bdf8bb5..0cff9ad5 100644 --- a/libi2pd_client/I2PTunnel.h +++ b/libi2pd_client/I2PTunnel.h @@ -280,8 +280,6 @@ namespace client const char* GetName() { return m_Name.c_str (); } - void SetMaxConnsPerMinute(const uint32_t conns) { m_PortDestination->SetMaxConnsPerMinute(conns); } - private: void HandleResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it, std::shared_ptr resolver); From eefbbd4efed3db5300a7593eb12d3d7b32dafd66 Mon Sep 17 00:00:00 2001 From: Jeff Becker Date: Mon, 16 Apr 2018 09:47:35 -0400 Subject: [PATCH 22/26] remove all related streaming limit members --- libi2pd/Streaming.cpp | 8 +------- libi2pd/Streaming.h | 5 ----- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/libi2pd/Streaming.cpp b/libi2pd/Streaming.cpp index afcda9ec..dd8e3634 100644 --- a/libi2pd/Streaming.cpp +++ b/libi2pd/Streaming.cpp @@ -903,8 +903,7 @@ namespace stream StreamingDestination::StreamingDestination (std::shared_ptr owner, uint16_t localPort, bool gzip): m_Owner (owner), m_LocalPort (localPort), m_Gzip (gzip), m_LastIncomingReceiveStreamID (0), - m_PendingIncomingTimer (m_Owner->GetService ()), - m_ConnTrackTimer(m_Owner->GetService()) + m_PendingIncomingTimer (m_Owner->GetService ()) { } @@ -927,15 +926,10 @@ namespace stream ResetAcceptor (); m_PendingIncomingTimer.cancel (); m_PendingIncomingStreams.clear (); - m_ConnTrackTimer.cancel(); { std::unique_lock l(m_StreamsMutex); m_Streams.clear (); } - { - std::unique_lock l(m_ConnsMutex); - m_Conns.clear (); - } } void StreamingDestination::HandleNextPacket (Packet * packet) diff --git a/libi2pd/Streaming.h b/libi2pd/Streaming.h index 9ce7e210..47f99833 100644 --- a/libi2pd/Streaming.h +++ b/libi2pd/Streaming.h @@ -280,11 +280,6 @@ namespace stream boost::asio::deadline_timer m_PendingIncomingTimer; std::map > m_SavedPackets; // receiveStreamID->packets, arrived before SYN - std::mutex m_ConnsMutex; - /** how many connections per minute did each identity have */ - std::map m_Conns; - boost::asio::deadline_timer m_ConnTrackTimer; - i2p::util::MemoryPool m_PacketsPool; public: From 0c661e7373c4463cfce31f70fd9c574f7d9f12fb Mon Sep 17 00:00:00 2001 From: orignal Date: Wed, 18 Apr 2018 15:08:06 -0400 Subject: [PATCH 23/26] save new local destination for failed insert --- libi2pd_client/ClientContext.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/libi2pd_client/ClientContext.cpp b/libi2pd_client/ClientContext.cpp index b04ab885..6c3a9410 100644 --- a/libi2pd_client/ClientContext.cpp +++ b/libi2pd_client/ClientContext.cpp @@ -531,6 +531,7 @@ namespace client LogPrint(eLogInfo, "Clients: I2P Client tunnel connect timeout set to ", timeout); } + auto clientTunnelDest = clientTunnel->GetLocalDestination (); // make copy of destination for possible update auto ins = m_ClientTunnels.insert (std::make_pair (clientEndpoint, std::unique_ptr(clientTunnel))); if (ins.second) { @@ -540,10 +541,10 @@ namespace client else { // TODO: update - if (ins.first->second->GetLocalDestination () != clientTunnel->GetLocalDestination ()) + if (ins.first->second->GetLocalDestination () != clientTunnelDest) { LogPrint (eLogInfo, "Clients: I2P client tunnel destination updated"); - ins.first->second->SetLocalDestination (clientTunnel->GetLocalDestination ()); + ins.first->second->SetLocalDestination (clientTunnelDest); } ins.first->second->isUpdated = true; LogPrint (eLogInfo, "Clients: I2P client tunnel for endpoint ", clientEndpoint, " already exists"); @@ -639,6 +640,7 @@ namespace client while (comma != std::string::npos); serverTunnel->SetAccessList (idents); } + auto serverTunnelDest = serverTunnel->GetLocalDestination (); auto ins = m_ServerTunnels.insert (std::make_pair ( std::make_pair (localDestination->GetIdentHash (), inPort), std::unique_ptr(serverTunnel))); @@ -650,10 +652,10 @@ namespace client else { // TODO: update - if (ins.first->second->GetLocalDestination () != serverTunnel->GetLocalDestination ()) + if (ins.first->second->GetLocalDestination () != serverTunnelDest) { LogPrint (eLogInfo, "Clients: I2P server tunnel destination updated"); - ins.first->second->SetLocalDestination (serverTunnel->GetLocalDestination ()); + ins.first->second->SetLocalDestination (serverTunnelDest); } ins.first->second->isUpdated = true; LogPrint (eLogInfo, "Clients: I2P server tunnel for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash ()), "/", inPort, " already exists"); From e2da16e9c32d2d7be8a1ec24fb03938653abbc61 Mon Sep 17 00:00:00 2001 From: R4SAS Date: Thu, 19 Apr 2018 19:46:00 +0300 Subject: [PATCH 24/26] moved reseed out --- libi2pd/Config.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libi2pd/Config.cpp b/libi2pd/Config.cpp index d9cc6dec..126de7fc 100644 --- a/libi2pd/Config.cpp +++ b/libi2pd/Config.cpp @@ -191,7 +191,7 @@ namespace config { // "https://uk.reseed.i2p2.no:444/," // mamoth's shit "https://i2p-0.manas.ca:8443/," "https://download.xxlspeed.com/," - "https://reseed-ru.lngserv.ru/," + "https://reseed-fr.i2pd.xyz/," "https://reseed.atomike.ninja/," "https://reseed.memcpy.io/," "https://reseed.onion.im/," From 6916147dda4a4b46a1049d38bf81b5c6c9abb264 Mon Sep 17 00:00:00 2001 From: unlnown542a Date: Sat, 21 Apr 2018 21:48:42 +0300 Subject: [PATCH 25/26] Few cents to get fullly console i2pd under Android --- android/i2pd/Android.mk | 74 +++++++++++++++++++++++++++++++++++++ android/i2pd/Application.mk | 42 +++++++++++++++++++++ daemon/Daemon.h | 13 ------- daemon/UnixDaemon.cpp | 3 ++ 4 files changed, 119 insertions(+), 13 deletions(-) create mode 100755 android/i2pd/Android.mk create mode 100755 android/i2pd/Application.mk diff --git a/android/i2pd/Android.mk b/android/i2pd/Android.mk new file mode 100755 index 00000000..ae56110c --- /dev/null +++ b/android/i2pd/Android.mk @@ -0,0 +1,74 @@ +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := i2pd +LOCAL_CPP_FEATURES := rtti exceptions +LOCAL_C_INCLUDES += $(IFADDRS_PATH) $(LIB_SRC_PATH) $(LIB_CLIENT_SRC_PATH) $(DAEMON_SRC_PATH) +LOCAL_STATIC_LIBRARIES := \ + boost_system \ + boost_date_time \ + boost_filesystem \ + boost_program_options \ + crypto ssl \ + miniupnpc +LOCAL_LDLIBS := -lz + +LOCAL_SRC_FILES := $(IFADDRS_PATH)/ifaddrs.c \ + $(wildcard $(LIB_SRC_PATH)/*.cpp)\ + $(wildcard $(LIB_CLIENT_SRC_PATH)/*.cpp)\ + $(DAEMON_SRC_PATH)/UnixDaemon.cpp \ + $(DAEMON_SRC_PATH)/Daemon.cpp \ + $(DAEMON_SRC_PATH)/UPnP.cpp \ + $(DAEMON_SRC_PATH)/HTTPServer.cpp \ + $(DAEMON_SRC_PATH)/I2PControl.cpp \ + $(DAEMON_SRC_PATH)/i2pd.cpp +include $(BUILD_EXECUTABLE) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := boost_system +LOCAL_SRC_FILES := $(BOOST_PATH)/boost_1_62_0/$(TARGET_ARCH_ABI)/lib/libboost_system.a +LOCAL_EXPORT_C_INCLUDES := $(BOOST_PATH)/boost_1_62_0/include +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := boost_date_time +LOCAL_SRC_FILES := $(BOOST_PATH)/boost_1_62_0/$(TARGET_ARCH_ABI)/lib/libboost_date_time.a +LOCAL_EXPORT_C_INCLUDES := $(BOOST_PATH)/boost_1_62_0/include +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := boost_filesystem +LOCAL_SRC_FILES := $(BOOST_PATH)/boost_1_62_0/$(TARGET_ARCH_ABI)/lib/libboost_filesystem.a +LOCAL_EXPORT_C_INCLUDES := $(BOOST_PATH)/boost_1_62_0/include +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := boost_program_options +LOCAL_SRC_FILES := $(BOOST_PATH)/boost_1_62_0/$(TARGET_ARCH_ABI)/lib/libboost_program_options.a +LOCAL_EXPORT_C_INCLUDES := $(BOOST_PATH)/boost_1_62_0/include +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := crypto +LOCAL_SRC_FILES := $(OPENSSL_PATH)/openssl-1.1.0e/$(TARGET_ARCH_ABI)/lib/libcrypto.a +LOCAL_EXPORT_C_INCLUDES := $(OPENSSL_PATH)/openssl-1.1.0e/include +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := ssl +LOCAL_SRC_FILES := $(OPENSSL_PATH)/openssl-1.1.0e/$(TARGET_ARCH_ABI)/lib/libssl.a +LOCAL_EXPORT_C_INCLUDES := $(OPENSSL_PATH)/openssl-1.1.0e/include +LOCAL_STATIC_LIBRARIES := crypto +include $(PREBUILT_STATIC_LIBRARY) + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) +LOCAL_MODULE := miniupnpc +LOCAL_SRC_FILES := $(MINIUPNP_PATH)/miniupnp-2.0/$(TARGET_ARCH_ABI)/lib/libminiupnpc.a +LOCAL_EXPORT_C_INCLUDES := $(MINIUPNP_PATH)/miniupnp-2.0/include +include $(PREBUILT_STATIC_LIBRARY) diff --git a/android/i2pd/Application.mk b/android/i2pd/Application.mk new file mode 100755 index 00000000..acc6f895 --- /dev/null +++ b/android/i2pd/Application.mk @@ -0,0 +1,42 @@ +#APP_ABI := all +#APP_ABI := armeabi-v7a x86 +#APP_ABI := x86 +#APP_ABI := x86_64 +APP_ABI := armeabi-v7a +#can be android-3 but will fail for x86 since arch-x86 is not present at ndkroot/platforms/android-3/ . libz is taken from there. +APP_PLATFORM := android-14 + +# http://stackoverflow.com/a/21386866/529442 http://stackoverflow.com/a/15616255/529442 to enable c++11 support in Eclipse +NDK_TOOLCHAIN_VERSION := 4.9 +# APP_STL := stlport_shared --> does not seem to contain C++11 features +#APP_STL := gnustl_shared +APP_STL := gnustl_static + +# Enable c++11 extensions in source code +APP_CPPFLAGS += -std=c++11 -fvisibility=default -fPIE + +APP_CPPFLAGS += -DANDROID -D__ANDROID__ -DUSE_UPNP +APP_LDFLAGS += -rdynamic -fPIE -pie +ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) +APP_CPPFLAGS += -DANDROID_ARM7A +endif + +APP_OPTIM := debug + +# git clone https://github.com/PurpleI2P/Boost-for-Android-Prebuilt.git +# git clone https://github.com/PurpleI2P/OpenSSL-for-Android-Prebuilt.git +# git clone https://github.com/PurpleI2P/MiniUPnP-for-Android-Prebuilt.git +# git clone https://github.com/PurpleI2P/android-ifaddrs.git +# change to your own +I2PD_LIBS_PATH = /home/u/build/i2p/daemon/static.libs +BOOST_PATH = $(I2PD_LIBS_PATH)/Boost-for-Android-Prebuilt +OPENSSL_PATH = $(I2PD_LIBS_PATH)/OpenSSL-for-Android-Prebuilt +MINIUPNP_PATH = $(I2PD_LIBS_PATH)/MiniUPnP-for-Android-Prebuilt +IFADDRS_PATH = $(I2PD_LIBS_PATH)/android-ifaddrs + +# don't change me +I2PD_SRC_PATH = $(PWD)/.. + +LIB_SRC_PATH = $(I2PD_SRC_PATH)/libi2pd +LIB_CLIENT_SRC_PATH = $(I2PD_SRC_PATH)/libi2pd_client +DAEMON_SRC_PATH = $(I2PD_SRC_PATH)/daemon diff --git a/daemon/Daemon.h b/daemon/Daemon.h index 48301e73..f3e72904 100644 --- a/daemon/Daemon.h +++ b/daemon/Daemon.h @@ -44,19 +44,6 @@ namespace util } }; -#elif defined(ANDROID) -#define Daemon i2p::util::DaemonAndroid::Instance() - // dummy, invoked from android/jni/DaemonAndroid.* - class DaemonAndroid: public i2p::util::Daemon_Singleton - { - public: - static DaemonAndroid& Instance() - { - static DaemonAndroid instance; - return instance; - } - }; - #elif defined(_WIN32) #define Daemon i2p::util::DaemonWin32::Instance() class DaemonWin32 : public Daemon_Singleton diff --git a/daemon/UnixDaemon.cpp b/daemon/UnixDaemon.cpp index a9c48fee..3dd38fba 100644 --- a/daemon/UnixDaemon.cpp +++ b/daemon/UnixDaemon.cpp @@ -138,11 +138,14 @@ namespace i2p LogPrint(eLogError, "Daemon: could not create pid file ", pidfile, ": ", strerror(errno)); return false; } + +#ifndef ANDROID if (lockf(pidFH, F_TLOCK, 0) != 0) { LogPrint(eLogError, "Daemon: could not lock pid file ", pidfile, ": ", strerror(errno)); return false; } +#endif char pid[10]; sprintf(pid, "%d\n", getpid()); ftruncate(pidFH, 0); From faac35cd1e868d888bba722164b7b3037af0ce46 Mon Sep 17 00:00:00 2001 From: unlnown542a Date: Sat, 21 Apr 2018 21:55:45 +0300 Subject: [PATCH 26/26] Revert "Change jni to build executable. Clone with minimal changes DaemonUnix into DaemonAndroid" This reverts commit f11266972e81a6db65aeecc3f77fe2b47418385c. --- android/jni/Android.mk | 8 +- android/jni/Application.mk | 8 +- android/jni/DaemonAndroid.cpp | 334 +++++++++++----------- android/jni/DaemonAndroid.h | 129 +++++---- android/jni/i2pd_android.cpp | 66 +++++ android/jni/org_purplei2p_i2pd_I2PD_JNI.h | 33 +++ 6 files changed, 351 insertions(+), 227 deletions(-) create mode 100755 android/jni/i2pd_android.cpp create mode 100644 android/jni/org_purplei2p_i2pd_I2PD_JNI.h diff --git a/android/jni/Android.mk b/android/jni/Android.mk index 90284995..d5a8f05f 100755 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -12,15 +12,15 @@ LOCAL_STATIC_LIBRARIES := \ miniupnpc LOCAL_LDLIBS := -lz -LOCAL_SRC_FILES := DaemonAndroid.cpp $(IFADDRS_PATH)/ifaddrs.c \ +LOCAL_SRC_FILES := DaemonAndroid.cpp i2pd_android.cpp $(IFADDRS_PATH)/ifaddrs.c \ $(wildcard $(LIB_SRC_PATH)/*.cpp)\ $(wildcard $(LIB_CLIENT_SRC_PATH)/*.cpp)\ $(DAEMON_SRC_PATH)/Daemon.cpp \ $(DAEMON_SRC_PATH)/UPnP.cpp \ $(DAEMON_SRC_PATH)/HTTPServer.cpp \ - $(DAEMON_SRC_PATH)/I2PControl.cpp \ - $(DAEMON_SRC_PATH)/i2pd.cpp -include $(BUILD_EXECUTABLE) + $(DAEMON_SRC_PATH)/I2PControl.cpp + +include $(BUILD_SHARED_LIBRARY) LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) diff --git a/android/jni/Application.mk b/android/jni/Application.mk index acc6f895..0fa116c2 100755 --- a/android/jni/Application.mk +++ b/android/jni/Application.mk @@ -9,14 +9,12 @@ APP_PLATFORM := android-14 # http://stackoverflow.com/a/21386866/529442 http://stackoverflow.com/a/15616255/529442 to enable c++11 support in Eclipse NDK_TOOLCHAIN_VERSION := 4.9 # APP_STL := stlport_shared --> does not seem to contain C++11 features -#APP_STL := gnustl_shared -APP_STL := gnustl_static +APP_STL := gnustl_shared # Enable c++11 extensions in source code -APP_CPPFLAGS += -std=c++11 -fvisibility=default -fPIE +APP_CPPFLAGS += -std=c++11 APP_CPPFLAGS += -DANDROID -D__ANDROID__ -DUSE_UPNP -APP_LDFLAGS += -rdynamic -fPIE -pie ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) APP_CPPFLAGS += -DANDROID_ARM7A endif @@ -28,7 +26,7 @@ APP_OPTIM := debug # git clone https://github.com/PurpleI2P/MiniUPnP-for-Android-Prebuilt.git # git clone https://github.com/PurpleI2P/android-ifaddrs.git # change to your own -I2PD_LIBS_PATH = /home/u/build/i2p/daemon/static.libs +I2PD_LIBS_PATH = /path/to/libraries BOOST_PATH = $(I2PD_LIBS_PATH)/Boost-for-Android-Prebuilt OPENSSL_PATH = $(I2PD_LIBS_PATH)/OpenSSL-for-Android-Prebuilt MINIUPNP_PATH = $(I2PD_LIBS_PATH)/MiniUPnP-for-Android-Prebuilt diff --git a/android/jni/DaemonAndroid.cpp b/android/jni/DaemonAndroid.cpp index 94c679be..75584740 100644 --- a/android/jni/DaemonAndroid.cpp +++ b/android/jni/DaemonAndroid.cpp @@ -1,193 +1,193 @@ #include "DaemonAndroid.h" +#include "Daemon.h" +#include +#include +#include +#include +//#include "mainwindow.h" -#ifndef _WIN32 +namespace i2p +{ +namespace android +{ +/* Worker::Worker (DaemonAndroidImpl& daemon): + m_Daemon (daemon) + { + } -#include -#include -#include -#include -#include -#include -#include + void Worker::startDaemon() + { + Log.d(TAG"Performing daemon start..."); + m_Daemon.start(); + Log.d(TAG"Daemon started."); + emit resultReady(); + } + void Worker::restartDaemon() + { + Log.d(TAG"Performing daemon restart..."); + m_Daemon.restart(); + Log.d(TAG"Daemon restarted."); + emit resultReady(); + } + void Worker::stopDaemon() { + Log.d(TAG"Performing daemon stop..."); + m_Daemon.stop(); + Log.d(TAG"Daemon stopped."); + emit resultReady(); + } -#include "Config.h" -#include "FS.h" -#include "Log.h" -#include "Tunnel.h" -#include "RouterContext.h" -#include "ClientContext.h" + Controller::Controller(DaemonAndroidImpl& daemon): + m_Daemon (daemon) + { + Worker *worker = new Worker (m_Daemon); + worker->moveToThread(&workerThread); + connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater); + connect(this, &Controller::startDaemon, worker, &Worker::startDaemon); + connect(this, &Controller::stopDaemon, worker, &Worker::stopDaemon); + connect(this, &Controller::restartDaemon, worker, &Worker::restartDaemon); + connect(worker, &Worker::resultReady, this, &Controller::handleResults); + workerThread.start(); + } + Controller::~Controller() + { + Log.d(TAG"Closing and waiting for daemon worker thread..."); + workerThread.quit(); + workerThread.wait(); + Log.d(TAG"Waiting for daemon worker thread finished."); + if(m_Daemon.isRunning()) + { + Log.d(TAG"Stopping the daemon..."); + m_Daemon.stop(); + Log.d(TAG"Stopped the daemon."); + } + } +*/ + DaemonAndroidImpl::DaemonAndroidImpl () + //: + /*mutex(nullptr), */ + //m_IsRunning(false), + //m_RunningChangedCallback(nullptr) + { + } -void handle_signal(int sig) -{ - switch (sig) - { - case SIGHUP: - LogPrint(eLogInfo, "Daemon: Got SIGHUP, reopening tunnel configuration..."); - i2p::client::context.ReloadConfig(); - break; - case SIGUSR1: - LogPrint(eLogInfo, "Daemon: Got SIGUSR1, reopening logs..."); - i2p::log::Logger().Reopen (); - break; - case SIGINT: - if (i2p::context.AcceptsTunnels () && !Daemon.gracefulShutdownInterval) - { - i2p::context.SetAcceptsTunnels (false); - Daemon.gracefulShutdownInterval = 10*60; // 10 minutes - LogPrint(eLogInfo, "Graceful shutdown after ", Daemon.gracefulShutdownInterval, " seconds"); - } - else - Daemon.running = 0; - break; - case SIGABRT: - case SIGTERM: - Daemon.running = 0; // Exit loop - break; - case SIGPIPE: - LogPrint(eLogInfo, "SIGPIPE received"); - break; + DaemonAndroidImpl::~DaemonAndroidImpl () + { + //delete mutex; } -} -namespace i2p -{ - namespace util + bool DaemonAndroidImpl::init(int argc, char* argv[]) { - bool DaemonAndroid::start() - { - if (isDaemon) - { - pid_t pid; - pid = fork(); - if (pid > 0) // parent - ::exit (EXIT_SUCCESS); + //mutex=new QMutex(QMutex::Recursive); + //setRunningCallback(0); + //m_IsRunning=false; + return Daemon.init(argc,argv); + } - if (pid < 0) // error - { - LogPrint(eLogError, "Daemon: could not fork: ", strerror(errno)); - return false; - } + void DaemonAndroidImpl::start() + { + //QMutexLocker locker(mutex); + //setRunning(true); + Daemon.start(); + } - // child - umask(S_IWGRP | S_IRWXO); // 0027 - int sid = setsid(); - if (sid < 0) - { - LogPrint(eLogError, "Daemon: could not create process group."); - return false; - } - std::string d = i2p::fs::GetDataDir(); - if (chdir(d.c_str()) != 0) - { - LogPrint(eLogError, "Daemon: could not chdir: ", strerror(errno)); - return false; - } + void DaemonAndroidImpl::stop() + { + //QMutexLocker locker(mutex); + Daemon.stop(); + //setRunning(false); + } - // point std{in,out,err} descriptors to /dev/null - freopen("/dev/null", "r", stdin); - freopen("/dev/null", "w", stdout); - freopen("/dev/null", "w", stderr); - } + void DaemonAndroidImpl::restart() + { + //QMutexLocker locker(mutex); + stop(); + start(); + } + /* + void DaemonAndroidImpl::setRunningCallback(runningChangedCallback cb) + { + m_RunningChangedCallback = cb; + } - // set proc limits - struct rlimit limit; - uint16_t nfiles; i2p::config::GetOption("limits.openfiles", nfiles); - getrlimit(RLIMIT_NOFILE, &limit); - if (nfiles == 0) { - LogPrint(eLogInfo, "Daemon: using system limit in ", limit.rlim_cur, " max open files"); - } else if (nfiles <= limit.rlim_max) { - limit.rlim_cur = nfiles; - if (setrlimit(RLIMIT_NOFILE, &limit) == 0) { - LogPrint(eLogInfo, "Daemon: set max number of open files to ", - nfiles, " (system limit is ", limit.rlim_max, ")"); - } else { - LogPrint(eLogError, "Daemon: can't set max number of open files: ", strerror(errno)); - } - } else { - LogPrint(eLogError, "Daemon: limits.openfiles exceeds system limit: ", limit.rlim_max); - } - uint32_t cfsize; i2p::config::GetOption("limits.coresize", cfsize); - if (cfsize) // core file size set - { - cfsize *= 1024; - getrlimit(RLIMIT_CORE, &limit); - if (cfsize <= limit.rlim_max) { - limit.rlim_cur = cfsize; - if (setrlimit(RLIMIT_CORE, &limit) != 0) { - LogPrint(eLogError, "Daemon: can't set max size of coredump: ", strerror(errno)); - } else if (cfsize == 0) { - LogPrint(eLogInfo, "Daemon: coredumps disabled"); - } else { - LogPrint(eLogInfo, "Daemon: set max size of core files to ", cfsize / 1024, "Kb"); - } - } else { - LogPrint(eLogError, "Daemon: limits.coresize exceeds system limit: ", limit.rlim_max); - } - } + bool DaemonAndroidImpl::isRunning() + { + return m_IsRunning; + } - // Pidfile - // this code is c-styled and a bit ugly - std::string pidfile; i2p::config::GetOption("pidfile", pidfile); - if (pidfile == "") { - pidfile = i2p::fs::DataDirPath("i2pd.pid"); - } - if (pidfile != "") { - pidFH = open(pidfile.c_str(), O_RDWR | O_CREAT, 0600); - if (pidFH < 0) + void DaemonAndroidImpl::setRunning(bool newValue) + { + bool oldValue = m_IsRunning; + if(oldValue!=newValue) + { + m_IsRunning = newValue; + if(m_RunningChangedCallback) + m_RunningChangedCallback(); + } + } +*/ + static DaemonAndroidImpl daemon; + static char* argv[1]={strdup("tmp")}; + /** + * returns error details if failed + * returns "ok" if daemon initialized and started okay + */ + std::string start(/*int argc, char* argv[]*/) + { + try + { + //int result; + + { + //Log.d(TAG"Initialising the daemon..."); + bool daemonInitSuccess = daemon.init(1,argv); + if(!daemonInitSuccess) { - LogPrint(eLogError, "Daemon: could not create pid file ", pidfile, ": ", strerror(errno)); - return false; + //QMessageBox::critical(0, "Error", "Daemon init failed"); + return "Daemon init failed"; } - char pid[10]; - sprintf(pid, "%d\n", getpid()); - ftruncate(pidFH, 0); - if (write(pidFH, pid, strlen(pid)) < 0) + //Log.d(TAG"Initialised, creating the main window..."); + //MainWindow w; + //Log.d(TAG"Before main window.show()..."); + //w.show (); + { - LogPrint(eLogError, "Daemon: could not write pidfile: ", strerror(errno)); - return false; + //i2p::qt::Controller daemonQtController(daemon); + //Log.d(TAG"Starting the daemon..."); + //emit daemonQtController.startDaemon(); + //daemon.start (); + //Log.d(TAG"Starting GUI event loop..."); + //result = app.exec(); + //daemon.stop (); + daemon.start(); } } - gracefulShutdownInterval = 0; // not specified - // Signal handler - struct sigaction sa; - sa.sa_handler = handle_signal; - sigemptyset(&sa.sa_mask); - sa.sa_flags = SA_RESTART; - sigaction(SIGHUP, &sa, 0); - sigaction(SIGUSR1, &sa, 0); - sigaction(SIGABRT, &sa, 0); - sigaction(SIGTERM, &sa, 0); - sigaction(SIGINT, &sa, 0); - sigaction(SIGPIPE, &sa, 0); - - return Daemon_Singleton::start(); + //QMessageBox::information(&w, "Debug", "demon stopped"); + //Log.d(TAG"Exiting the application"); + //return result; } - - bool DaemonAndroid::stop() + catch (boost::exception& ex) { - i2p::fs::Remove(pidfile); - - return Daemon_Singleton::stop(); + std::stringstream ss; + ss << boost::diagnostic_information(ex); + return ss.str(); } - - void DaemonAndroid::run () + catch (std::exception& ex) { - while (running) - { - std::this_thread::sleep_for (std::chrono::seconds(1)); - if (gracefulShutdownInterval) - { - gracefulShutdownInterval--; // - 1 second - if (gracefulShutdownInterval <= 0 || i2p::tunnel::tunnels.CountTransitTunnels() <= 0) - { - LogPrint(eLogInfo, "Graceful shutdown"); - return; - } - } - } + std::stringstream ss; + ss << ex.what(); + return ss.str(); } + catch(...) + { + return "unknown exception"; + } + return "ok"; } -} -#endif + void stop() + { + daemon.stop(); + } +} +} diff --git a/android/jni/DaemonAndroid.h b/android/jni/DaemonAndroid.h index c62d7c76..9cc8219b 100644 --- a/android/jni/DaemonAndroid.h +++ b/android/jni/DaemonAndroid.h @@ -1,60 +1,87 @@ -#ifndef DAEMON_H__ -#define DAEMON_H__ +#ifndef DAEMON_ANDROID_H +#define DAEMON_ANDROID_H -#include #include namespace i2p { -namespace util +namespace android { - class Daemon_Singleton_Private; - class Daemon_Singleton - { - public: - virtual bool init(int argc, char* argv[]); - virtual bool start(); - virtual bool stop(); - virtual void run () {}; - - bool isDaemon; - bool running; - - protected: - Daemon_Singleton(); - virtual ~Daemon_Singleton(); - - bool IsService () const; - - // d-pointer for httpServer, httpProxy, etc. - class Daemon_Singleton_Private; - Daemon_Singleton_Private &d; - }; - -#if defined(ANDROID) -#define Daemon i2p::util::DaemonAndroid::Instance() - class DaemonAndroid : public Daemon_Singleton - { - public: - static DaemonAndroid& Instance() - { - static DaemonAndroid instance; - return instance; - } - - bool start(); - bool stop(); - void run (); - - private: - std::string pidfile; - int pidFH; - - public: - int gracefulShutdownInterval; // in seconds - }; -#endif + class DaemonAndroidImpl + { + public: + + DaemonAndroidImpl (); + ~DaemonAndroidImpl (); + + //typedef void (*runningChangedCallback)(); + + /** + * @return success + */ + bool init(int argc, char* argv[]); + void start(); + void stop(); + void restart(); + //void setRunningCallback(runningChangedCallback cb); + //bool isRunning(); + private: + //void setRunning(bool running); + private: + //QMutex* mutex; + //bool m_IsRunning; + //runningChangedCallback m_RunningChangedCallback; + }; + + /** + * returns "ok" if daemon init failed + * returns errinfo if daemon initialized and started okay + */ + std::string start(); + + // stops the daemon + void stop(); + + /* + class Worker : public QObject + { + Q_OBJECT + public: + + Worker (DaemonAndroidImpl& daemon); + + private: + + DaemonAndroidImpl& m_Daemon; + + public slots: + void startDaemon(); + void restartDaemon(); + void stopDaemon(); + + signals: + void resultReady(); + }; + + class Controller : public QObject + { + Q_OBJECT + QThread workerThread; + public: + Controller(DaemonAndroidImpl& daemon); + ~Controller(); + private: + DaemonAndroidImpl& m_Daemon; + + public slots: + void handleResults(){} + signals: + void startDaemon(); + void stopDaemon(); + void restartDaemon(); + }; + */ } } -#endif // DAEMON_H__ +#endif // DAEMON_ANDROID_H diff --git a/android/jni/i2pd_android.cpp b/android/jni/i2pd_android.cpp new file mode 100755 index 00000000..8791c90b --- /dev/null +++ b/android/jni/i2pd_android.cpp @@ -0,0 +1,66 @@ + +//#include +#include +#include "org_purplei2p_i2pd_I2PD_JNI.h" +#include "DaemonAndroid.h" +#include "RouterContext.h" +#include "Transports.h" + +JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_getABICompiledWith + (JNIEnv * env, jclass clazz) { +#if defined(__arm__) + #if defined(__ARM_ARCH_7A__) + #if defined(__ARM_NEON__) + #if defined(__ARM_PCS_VFP) + #define ABI "armeabi-v7a/NEON (hard-float)" + #else + #define ABI "armeabi-v7a/NEON" + #endif + #else + #if defined(__ARM_PCS_VFP) + #define ABI "armeabi-v7a (hard-float)" + #else + #define ABI "armeabi-v7a" + #endif + #endif + #else + #define ABI "armeabi" + #endif +#elif defined(__i386__) + #define ABI "x86" +#elif defined(__x86_64__) + #define ABI "x86_64" +#elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */ + #define ABI "mips64" +#elif defined(__mips__) + #define ABI "mips" +#elif defined(__aarch64__) + #define ABI "arm64-v8a" +#else + #define ABI "unknown" +#endif + + return env->NewStringUTF(ABI); +} + +JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_startDaemon + (JNIEnv * env, jclass clazz) { + return env->NewStringUTF(i2p::android::start().c_str()); +} + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopDaemon + (JNIEnv * env, jclass clazz) { + i2p::android::stop(); +} + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopAcceptingTunnels + (JNIEnv * env, jclass clazz) { + i2p::context.SetAcceptsTunnels (false); +} + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_onNetworkStateChanged + (JNIEnv * env, jclass clazz, jboolean isConnected) +{ + bool isConnectedBool = (bool) isConnected; + i2p::transport::transports.SetOnline (isConnectedBool); +} diff --git a/android/jni/org_purplei2p_i2pd_I2PD_JNI.h b/android/jni/org_purplei2p_i2pd_I2PD_JNI.h new file mode 100644 index 00000000..04923d22 --- /dev/null +++ b/android/jni/org_purplei2p_i2pd_I2PD_JNI.h @@ -0,0 +1,33 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class org_purplei2p_i2pd_I2PD_JNI */ + +#ifndef _Included_org_purplei2p_i2pd_I2PD_JNI +#define _Included_org_purplei2p_i2pd_I2PD_JNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: org_purplei2p_i2pd_I2PD_JNI + * Method: stringFromJNI + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_getABICompiledWith + (JNIEnv *, jclass); + +JNIEXPORT jstring JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_startDaemon + (JNIEnv *, jclass); + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopDaemon + (JNIEnv *, jclass); + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_stopAcceptingTunnels + (JNIEnv *, jclass); + +JNIEXPORT void JNICALL Java_org_purplei2p_i2pd_I2PD_1JNI_onNetworkStateChanged + (JNIEnv * env, jclass clazz, jboolean isConnected); + +#ifdef __cplusplus +} +#endif +#endif