41 for (
size_t i = 0; i <
from.size(); ++i) {
73 throw std::runtime_error(
87 hasher.
Write(dest.data(), dest.size());
94 throw std::runtime_error(
132 }
catch (
const std::runtime_error &
e) {
133 Log(
"Error listening: %s",
e.what());
151 const std::string &
peer_dest = conn.
sock->RecvUntilTerminator(
158 }
catch (
const std::runtime_error &
e) {
159 Log(
"Error accepting: %s",
e.what());
178 std::unique_ptr<Sock> sock;
191 *sock,
strprintf(
"NAMING LOOKUP NAME=%s",
to.ToStringIP()));
197 strprintf(
"STREAM CONNECT ID=%s DESTINATION=%s SILENT=false",
203 if (result ==
"OK") {
204 conn.
sock = std::move(sock);
208 if (result ==
"INVALID_ID") {
211 throw std::runtime_error(
"Invalid session id");
214 if (result ==
"CANT_REACH_PEER" || result ==
"TIMEOUT") {
219 }
catch (
const std::runtime_error &
e) {
220 Log(
"Error connecting to %s: %s",
to.ToString(),
e.what());
229 const auto &pos =
keys.find(key);
230 if (pos ==
keys.end() || !pos->second.has_value()) {
231 throw std::runtime_error(
232 strprintf(
"Missing %s= in the reply to \"%s\": \"%s\"", key,
235 return pos->second.value();
238 template <
typename... Args>
244 const std::string &request,
252 reply.
request = request.substr(0, 14) ==
"SESSION CREATE"
253 ?
"SESSION CREATE ..."
266 const auto &pos = std::find(
kv.begin(),
kv.end(),
'=');
267 if (pos !=
kv.end()) {
268 reply.
keys.emplace(std::string{
kv.begin(), pos},
269 std::string{pos + 1,
kv.end()});
271 reply.
keys.emplace(std::string{
kv.begin(),
kv.end()},
278 "Unexpected reply to \"%s\": \"%s\"", request, reply.
full));
288 throw std::runtime_error(
"Cannot create socket");
293 throw std::runtime_error(
318 sock,
"DEST GENERATE SIGNATURE_TYPE=7",
false);
331 throw std::runtime_error(
332 strprintf(
"Cannot save I2P private key to %s",
376 *sock,
strprintf(
"SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s",
383 LogPrintf(
"I2P: SAM session created: session id=%s, my address=%s\n",
394 const std::string &result = reply.
Get(
"RESULT");
396 if (result ==
"OK") {
400 if (result ==
"INVALID_ID") {
412 Log(
"Destroying incomplete session");
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
A hasher class for SHA-256.
CSHA256 & Write(const uint8_t *data, size_t len)
static const size_t OUTPUT_SIZE
void Finalize(uint8_t hash[OUTPUT_SIZE])
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToString() const
A helper class for interruptible sleeps.
RAII helper class that manages a socket.
virtual void SendComplete(const std::string &data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
virtual std::string RecvUntilTerminator(uint8_t terminator, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt, size_t max_data) const
Read from socket until a terminator character is encountered.
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
const fs::path m_private_key_file
The name of the file where this peer's private key is stored (in binary).
Reply SendRequestAndGetReply(const Sock &sock, const std::string &request, bool check_result_ok=true) const
Send request and get a reply from the SAM proxy.
bool Listen(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start listening for an incoming connection.
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
const CService m_control_host
The host and port of the SAM control service.
Session(const fs::path &private_key_file, const CService &control_host, CThreadInterrupt *interrupt)
Construct a session.
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
void CheckControlSock() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check the control socket for errors and possibly disconnect.
std::unique_ptr< Sock > StreamAccept() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy and issue "STREAM ACCEPT" request using the existing session i...
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
~Session()
Destroy the session, closing the internally used sockets.
void GenerateAndSavePrivateKey(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy, set m_private_key to it and save it on disk to m_priva...
bool Connect(const CService &to, Connection &conn, bool &proxy_error) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Connect to an I2P peer.
CThreadInterrupt *const m_interrupt
Cease network activity when this is signaled.
void DestGenerate(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy and set m_private_key to it.
void Log(const std::string &fmt, const Args &...args) const
Log a message in the BCLog::I2P category.
Mutex m_mutex
Mutex protecting the members that can be concurrently accessed.
bool Accept(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait for and accept a new incoming connection.
uint16_t be16toh(uint16_t big_endian_16bits)
#define LogPrint(category,...)
static auto quoted(const std::string &s)
static std::string PathToString(const path &path)
Convert path object to byte string.
static constexpr size_t MAX_MSG_SIZE
The maximum size of an incoming message from the I2P SAM proxy (in bytes).
static CNetAddr DestB64ToAddr(const std::string &dest)
Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
static std::string SwapBase64(const std::string &from)
Swap Standard Base64 <-> I2P Base64.
static CNetAddr DestBinToAddr(const Binary &dest)
Derive the .b32.i2p address of an I2P destination (binary).
std::vector< uint8_t > Binary
Binary data.
static Binary DecodeI2PBase64(const std::string &i2p_b64)
Decode an I2P-style Base64 string.
std::vector< T > Split(const Span< const char > &sp, char sep)
Split a string on every instance of sep, returning a vector.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
static constexpr uint16_t I2P_SAM31_PORT
SAM 3.1 and earlier do not support specifying ports and force the port to 0.
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
uint256 GetRandHash() noexcept
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
An established connection with another peer.
std::unique_ptr< Sock > sock
Connected socket.
CService me
Our I2P address.
CService peer
The peer's I2P address.
A reply from the SAM proxy.
std::string Get(const std::string &key) const
Get the value of a given key.
std::string full
Full, unparsed reply.
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
std::string request
Request, used for detailed error reporting.
std::string EncodeBase64(Span< const uint8_t > input)
std::string EncodeBase32(Span< const uint8_t > input, bool pad)
Base32 encode.
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)