LCOV - code coverage report
Current view: top level - src - i2p.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 260 0.0 %
Date: 2023-11-10 23:46:46 Functions: 0 27 0.0 %
Branches: 0 577 0.0 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2020-2022 The Bitcoin Core developers
       2                 :            : // Distributed under the MIT software license, see the accompanying
       3                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :            : 
       5                 :            : #include <chainparams.h>
       6                 :            : #include <common/args.h>
       7                 :            : #include <compat/compat.h>
       8                 :            : #include <compat/endian.h>
       9                 :            : #include <crypto/sha256.h>
      10                 :            : #include <i2p.h>
      11                 :            : #include <logging.h>
      12                 :            : #include <netaddress.h>
      13                 :            : #include <netbase.h>
      14                 :            : #include <random.h>
      15                 :            : #include <sync.h>
      16                 :            : #include <tinyformat.h>
      17                 :            : #include <util/fs.h>
      18                 :            : #include <util/readwritefile.h>
      19                 :            : #include <util/sock.h>
      20                 :            : #include <util/spanparsing.h>
      21                 :            : #include <util/strencodings.h>
      22                 :            : #include <util/threadinterrupt.h>
      23                 :            : 
      24                 :            : #include <chrono>
      25                 :            : #include <memory>
      26                 :            : #include <stdexcept>
      27                 :            : #include <string>
      28                 :            : 
      29                 :            : namespace i2p {
      30                 :            : 
      31                 :            : /**
      32                 :            :  * Swap Standard Base64 <-> I2P Base64.
      33                 :            :  * Standard Base64 uses `+` and `/` as last two characters of its alphabet.
      34                 :            :  * I2P Base64 uses `-` and `~` respectively.
      35                 :            :  * So it is easy to detect in which one is the input and convert to the other.
      36                 :            :  * @param[in] from Input to convert.
      37                 :            :  * @return converted `from`
      38                 :            :  */
      39                 :          0 : static std::string SwapBase64(const std::string& from)
      40                 :            : {
      41                 :          0 :     std::string to;
      42         [ #  # ]:          0 :     to.resize(from.size());
      43         [ #  # ]:          0 :     for (size_t i = 0; i < from.size(); ++i) {
      44   [ #  #  #  #  :          0 :         switch (from[i]) {
                      # ]
      45                 :            :         case '-':
      46         [ #  # ]:          0 :             to[i] = '+';
      47                 :          0 :             break;
      48                 :            :         case '~':
      49         [ #  # ]:          0 :             to[i] = '/';
      50                 :          0 :             break;
      51                 :            :         case '+':
      52         [ #  # ]:          0 :             to[i] = '-';
      53                 :          0 :             break;
      54                 :            :         case '/':
      55         [ #  # ]:          0 :             to[i] = '~';
      56                 :          0 :             break;
      57                 :            :         default:
      58         [ #  # ]:          0 :             to[i] = from[i];
      59                 :          0 :             break;
      60                 :            :         }
      61                 :          0 :     }
      62                 :          0 :     return to;
      63         [ #  # ]:          0 : }
      64                 :            : 
      65                 :            : /**
      66                 :            :  * Decode an I2P-style Base64 string.
      67                 :            :  * @param[in] i2p_b64 I2P-style Base64 string.
      68                 :            :  * @return decoded `i2p_b64`
      69                 :            :  * @throw std::runtime_error if decoding fails
      70                 :            :  */
      71                 :          0 : static Binary DecodeI2PBase64(const std::string& i2p_b64)
      72                 :            : {
      73                 :          0 :     const std::string& std_b64 = SwapBase64(i2p_b64);
      74         [ #  # ]:          0 :     auto decoded = DecodeBase64(std_b64);
      75         [ #  # ]:          0 :     if (!decoded) {
      76 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
         [ #  # ][ #  # ]
      77                 :            :     }
      78                 :          0 :     return std::move(*decoded);
      79                 :          0 : }
      80                 :            : 
      81                 :            : /**
      82                 :            :  * Derive the .b32.i2p address of an I2P destination (binary).
      83                 :            :  * @param[in] dest I2P destination.
      84                 :            :  * @return the address that corresponds to `dest`
      85                 :            :  * @throw std::runtime_error if conversion fails
      86                 :            :  */
      87                 :          0 : static CNetAddr DestBinToAddr(const Binary& dest)
      88                 :            : {
      89                 :          0 :     CSHA256 hasher;
      90                 :          0 :     hasher.Write(dest.data(), dest.size());
      91                 :            :     unsigned char hash[CSHA256::OUTPUT_SIZE];
      92                 :          0 :     hasher.Finalize(hash);
      93                 :            : 
      94                 :          0 :     CNetAddr addr;
      95 [ #  # ][ #  # ]:          0 :     const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
      96 [ #  # ][ #  # ]:          0 :     if (!addr.SetSpecial(addr_str)) {
      97 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str));
         [ #  # ][ #  # ]
      98                 :            :     }
      99                 :            : 
     100                 :          0 :     return addr;
     101         [ #  # ]:          0 : }
     102                 :            : 
     103                 :            : /**
     104                 :            :  * Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
     105                 :            :  * @param[in] dest I2P destination.
     106                 :            :  * @return the address that corresponds to `dest`
     107                 :            :  * @throw std::runtime_error if conversion fails
     108                 :            :  */
     109                 :          0 : static CNetAddr DestB64ToAddr(const std::string& dest)
     110                 :            : {
     111                 :          0 :     const Binary& decoded = DecodeI2PBase64(dest);
     112         [ #  # ]:          0 :     return DestBinToAddr(decoded);
     113                 :          0 : }
     114                 :            : 
     115                 :            : namespace sam {
     116                 :            : 
     117         [ #  # ]:          0 : Session::Session(const fs::path& private_key_file,
     118                 :            :                  const CService& control_host,
     119                 :            :                  CThreadInterrupt* interrupt)
     120                 :          0 :     : m_private_key_file{private_key_file},
     121         [ #  # ]:          0 :       m_control_host{control_host},
     122                 :          0 :       m_interrupt{interrupt},
     123                 :          0 :       m_transient{false}
     124                 :            : {
     125                 :          0 : }
     126                 :            : 
     127         [ #  # ]:          0 : Session::Session(const CService& control_host, CThreadInterrupt* interrupt)
     128         [ #  # ]:          0 :     : m_control_host{control_host},
     129                 :          0 :       m_interrupt{interrupt},
     130                 :          0 :       m_transient{true}
     131                 :            : {
     132                 :          0 : }
     133                 :            : 
     134                 :          0 : Session::~Session()
     135                 :            : {
     136 [ #  # ][ #  # ]:          0 :     LOCK(m_mutex);
     137         [ #  # ]:          0 :     Disconnect();
     138                 :          0 : }
     139                 :            : 
     140                 :          0 : bool Session::Listen(Connection& conn)
     141                 :            : {
     142                 :            :     try {
     143 [ #  # ][ #  # ]:          0 :         LOCK(m_mutex);
     144         [ #  # ]:          0 :         CreateIfNotCreatedAlready();
     145         [ #  # ]:          0 :         conn.me = m_my_addr;
     146         [ #  # ]:          0 :         conn.sock = StreamAccept();
     147                 :          0 :         return true;
     148         [ #  # ]:          0 :     } catch (const std::runtime_error& e) {
     149 [ #  # ][ #  # ]:          0 :         Log("Error listening: %s", e.what());
     150         [ #  # ]:          0 :         CheckControlSock();
     151         [ #  # ]:          0 :     }
     152                 :          0 :     return false;
     153                 :          0 : }
     154                 :            : 
     155                 :          0 : bool Session::Accept(Connection& conn)
     156                 :            : {
     157                 :          0 :     AssertLockNotHeld(m_mutex);
     158                 :            : 
     159                 :          0 :     std::string errmsg;
     160                 :          0 :     bool disconnect{false};
     161                 :            : 
     162         [ #  # ]:          0 :     while (!*m_interrupt) {
     163                 :            :         Sock::Event occurred;
     164 [ #  # ][ #  # ]:          0 :         if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
                 [ #  # ]
     165         [ #  # ]:          0 :             errmsg = "wait on socket failed";
     166                 :          0 :             break;
     167                 :            :         }
     168                 :            : 
     169         [ #  # ]:          0 :         if (occurred == 0) {
     170                 :            :             // Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
     171                 :          0 :             continue;
     172                 :            :         }
     173                 :            : 
     174                 :          0 :         std::string peer_dest;
     175                 :            :         try {
     176 [ #  # ][ #  # ]:          0 :             peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
     177         [ #  # ]:          0 :         } catch (const std::runtime_error& e) {
     178         [ #  # ]:          0 :             errmsg = e.what();
     179                 :            :             break;
     180 [ #  # ][ #  # ]:          0 :         }
     181                 :            : 
     182         [ #  # ]:          0 :         CNetAddr peer_addr;
     183                 :            :         try {
     184         [ #  # ]:          0 :             peer_addr = DestB64ToAddr(peer_dest);
     185         [ #  # ]:          0 :         } catch (const std::runtime_error& e) {
     186                 :            :             // The I2P router is expected to send the Base64 of the connecting peer,
     187                 :            :             // but it may happen that something like this is sent instead:
     188                 :            :             // STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"
     189                 :            :             // In that case consider the session damaged and close it right away,
     190                 :            :             // even if the control socket is alive.
     191         [ #  # ]:          0 :             if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) {
     192         [ #  # ]:          0 :                 errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest);
     193                 :          0 :                 disconnect = true;
     194                 :          0 :             } else {
     195         [ #  # ]:          0 :                 errmsg = e.what();
     196                 :            :             }
     197                 :            :             break;
     198 [ #  # ][ #  # ]:          0 :         }
     199                 :            : 
     200         [ #  # ]:          0 :         conn.peer = CService(peer_addr, I2P_SAM31_PORT);
     201                 :            : 
     202                 :          0 :         return true;
     203         [ #  # ]:          0 :     }
     204                 :            : 
     205 [ #  # ][ #  # ]:          0 :     Log("Error accepting%s: %s", disconnect ? " (will close the session)" : "", errmsg);
     206         [ #  # ]:          0 :     if (disconnect) {
     207 [ #  # ][ #  # ]:          0 :         LOCK(m_mutex);
     208         [ #  # ]:          0 :         Disconnect();
     209                 :          0 :     } else {
     210         [ #  # ]:          0 :         CheckControlSock();
     211                 :            :     }
     212                 :          0 :     return false;
     213                 :          0 : }
     214                 :            : 
     215                 :          0 : bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)
     216                 :            : {
     217                 :            :     // Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy
     218                 :            :     // when connecting (SAM 3.1 does not use ports) and it forces/defaults it to I2P_SAM31_PORT.
     219         [ #  # ]:          0 :     if (to.GetPort() != I2P_SAM31_PORT) {
     220                 :          0 :         proxy_error = false;
     221                 :          0 :         return false;
     222                 :            :     }
     223                 :            : 
     224                 :          0 :     proxy_error = true;
     225                 :            : 
     226                 :          0 :     std::string session_id;
     227                 :          0 :     std::unique_ptr<Sock> sock;
     228         [ #  # ]:          0 :     conn.peer = to;
     229                 :            : 
     230                 :            :     try {
     231                 :            :         {
     232 [ #  # ][ #  # ]:          0 :             LOCK(m_mutex);
     233         [ #  # ]:          0 :             CreateIfNotCreatedAlready();
     234         [ #  # ]:          0 :             session_id = m_session_id;
     235         [ #  # ]:          0 :             conn.me = m_my_addr;
     236         [ #  # ]:          0 :             sock = Hello();
     237                 :          0 :         }
     238                 :            : 
     239                 :          0 :         const Reply& lookup_reply =
     240 [ #  # ][ #  # ]:          0 :             SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringAddr()));
                 [ #  # ]
     241                 :            : 
     242 [ #  # ][ #  # ]:          0 :         const std::string& dest = lookup_reply.Get("VALUE");
     243                 :            : 
     244         [ #  # ]:          0 :         const Reply& connect_reply = SendRequestAndGetReply(
     245         [ #  # ]:          0 :             *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest),
     246                 :            :             false);
     247                 :            : 
     248 [ #  # ][ #  # ]:          0 :         const std::string& result = connect_reply.Get("RESULT");
     249                 :            : 
     250 [ #  # ][ #  # ]:          0 :         if (result == "OK") {
     251                 :          0 :             conn.sock = std::move(sock);
     252                 :          0 :             return true;
     253                 :            :         }
     254                 :            : 
     255 [ #  # ][ #  # ]:          0 :         if (result == "INVALID_ID") {
     256 [ #  # ][ #  # ]:          0 :             LOCK(m_mutex);
     257         [ #  # ]:          0 :             Disconnect();
     258         [ #  # ]:          0 :             throw std::runtime_error("Invalid session id");
     259                 :          0 :         }
     260                 :            : 
     261 [ #  # ][ #  # ]:          0 :         if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
         [ #  # ][ #  # ]
     262                 :          0 :             proxy_error = false;
     263                 :          0 :         }
     264                 :            : 
     265 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
                 [ #  # ]
     266         [ #  # ]:          0 :     } catch (const std::runtime_error& e) {
     267 [ #  # ][ #  # ]:          0 :         Log("Error connecting to %s: %s", to.ToStringAddrPort(), e.what());
                 [ #  # ]
     268         [ #  # ]:          0 :         CheckControlSock();
     269                 :          0 :         return false;
     270 [ #  # ][ #  # ]:          0 :     }
     271                 :          0 : }
     272                 :            : 
     273                 :            : // Private methods
     274                 :            : 
     275                 :          0 : std::string Session::Reply::Get(const std::string& key) const
     276                 :            : {
     277                 :          0 :     const auto& pos = keys.find(key);
     278 [ #  # ][ #  # ]:          0 :     if (pos == keys.end() || !pos->second.has_value()) {
     279 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(
                 [ #  # ]
     280         [ #  # ]:          0 :             strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full));
     281                 :            :     }
     282                 :          0 :     return pos->second.value();
     283                 :          0 : }
     284                 :            : 
     285                 :            : template <typename... Args>
     286                 :          0 : void Session::Log(const std::string& fmt, const Args&... args) const
     287                 :            : {
     288 [ #  # ][ #  # ]:          0 :     LogPrint(BCLog::I2P, "%s\n", tfm::format(fmt, args...));
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
     289                 :          0 : }
     290                 :            : 
     291                 :          0 : Session::Reply Session::SendRequestAndGetReply(const Sock& sock,
     292                 :            :                                                const std::string& request,
     293                 :            :                                                bool check_result_ok) const
     294                 :            : {
     295 [ #  # ][ #  # ]:          0 :     sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
     296                 :            : 
     297                 :          0 :     Reply reply;
     298                 :            : 
     299                 :            :     // Don't log the full "SESSION CREATE ..." because it contains our private key.
     300 [ #  # ][ #  # ]:          0 :     reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request;
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     301                 :            : 
     302                 :            :     // It could take a few minutes for the I2P router to reply as it is querying the I2P network
     303                 :            :     // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking
     304                 :            :     // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is
     305                 :            :     // signaled.
     306                 :            :     static constexpr auto recv_timeout = 3min;
     307                 :            : 
     308 [ #  # ][ #  # ]:          0 :     reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);
     309                 :            : 
     310 [ #  # ][ #  # ]:          0 :     for (const auto& kv : spanparsing::Split(reply.full, ' ')) {
                 [ #  # ]
     311         [ #  # ]:          0 :         const auto& pos = std::find(kv.begin(), kv.end(), '=');
     312         [ #  # ]:          0 :         if (pos != kv.end()) {
     313 [ #  # ][ #  # ]:          0 :             reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});
                 [ #  # ]
     314                 :          0 :         } else {
     315 [ #  # ][ #  # ]:          0 :             reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);
     316                 :            :         }
     317                 :            :     }
     318                 :            : 
     319 [ #  # ][ #  # ]:          0 :     if (check_result_ok && reply.Get("RESULT") != "OK") {
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
     320 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(
                 [ #  # ]
     321         [ #  # ]:          0 :             strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full));
     322                 :            :     }
     323                 :            : 
     324                 :          0 :     return reply;
     325         [ #  # ]:          0 : }
     326                 :            : 
     327                 :          0 : std::unique_ptr<Sock> Session::Hello() const
     328                 :            : {
     329                 :          0 :     auto sock = CreateSock(m_control_host);
     330                 :            : 
     331         [ #  # ]:          0 :     if (!sock) {
     332         [ #  # ]:          0 :         throw std::runtime_error("Cannot create socket");
     333                 :            :     }
     334                 :            : 
     335 [ #  # ][ #  # ]:          0 :     if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) {
     336 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToStringAddrPort()));
         [ #  # ][ #  # ]
     337                 :            :     }
     338                 :            : 
     339 [ #  # ][ #  # ]:          0 :     SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
     340                 :            : 
     341                 :          0 :     return sock;
     342         [ #  # ]:          0 : }
     343                 :            : 
     344                 :          0 : void Session::CheckControlSock()
     345                 :            : {
     346                 :          0 :     LOCK(m_mutex);
     347                 :            : 
     348                 :          0 :     std::string errmsg;
     349 [ #  # ][ #  # ]:          0 :     if (m_control_sock && !m_control_sock->IsConnected(errmsg)) {
                 [ #  # ]
     350 [ #  # ][ #  # ]:          0 :         Log("Control socket error: %s", errmsg);
     351         [ #  # ]:          0 :         Disconnect();
     352                 :          0 :     }
     353                 :          0 : }
     354                 :            : 
     355                 :          0 : void Session::DestGenerate(const Sock& sock)
     356                 :            : {
     357                 :            :     // https://geti2p.net/spec/common-structures#key-certificates
     358                 :            :     // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations".
     359                 :            :     // Use "7" because i2pd <2.24.0 does not recognize the textual form.
     360                 :            :     // If SIGNATURE_TYPE is not specified, then the default one is DSA_SHA1.
     361 [ #  # ][ #  # ]:          0 :     const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
     362                 :            : 
     363 [ #  # ][ #  # ]:          0 :     m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
                 [ #  # ]
     364                 :          0 : }
     365                 :            : 
     366                 :          0 : void Session::GenerateAndSavePrivateKey(const Sock& sock)
     367                 :            : {
     368                 :          0 :     DestGenerate(sock);
     369                 :            : 
     370                 :            :     // umask is set to 0077 in common/system.cpp, which is ok.
     371 [ #  # ][ #  # ]:          0 :     if (!WriteBinaryFile(m_private_key_file,
     372         [ #  # ]:          0 :                          std::string(m_private_key.begin(), m_private_key.end()))) {
     373 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(
                 [ #  # ]
     374 [ #  # ][ #  # ]:          0 :             strprintf("Cannot save I2P private key to %s", fs::quoted(fs::PathToString(m_private_key_file))));
                 [ #  # ]
     375                 :            :     }
     376                 :          0 : }
     377                 :            : 
     378                 :          0 : Binary Session::MyDestination() const
     379                 :            : {
     380                 :            :     // From https://geti2p.net/spec/common-structures#destination:
     381                 :            :     // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be
     382                 :            :     // non-zero"
     383                 :            :     static constexpr size_t DEST_LEN_BASE = 387;
     384                 :            :     static constexpr size_t CERT_LEN_POS = 385;
     385                 :            : 
     386                 :            :     uint16_t cert_len;
     387                 :            : 
     388         [ #  # ]:          0 :     if (m_private_key.size() < CERT_LEN_POS + sizeof(cert_len)) {
     389 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("The private key is too short (%d < %d)",
         [ #  # ][ #  # ]
     390                 :          0 :                                            m_private_key.size(),
     391                 :          0 :                                            CERT_LEN_POS + sizeof(cert_len)));
     392                 :            :     }
     393                 :            : 
     394                 :          0 :     memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
     395                 :          0 :     cert_len = be16toh(cert_len);
     396                 :            : 
     397                 :          0 :     const size_t dest_len = DEST_LEN_BASE + cert_len;
     398                 :            : 
     399         [ #  # ]:          0 :     if (dest_len > m_private_key.size()) {
     400 [ #  # ][ #  # ]:          0 :         throw std::runtime_error(strprintf("Certificate length (%d) designates that the private key should "
         [ #  # ][ #  # ]
     401                 :            :                                            "be %d bytes, but it is only %d bytes",
     402                 :            :                                            cert_len,
     403                 :            :                                            dest_len,
     404                 :          0 :                                            m_private_key.size()));
     405                 :            :     }
     406                 :            : 
     407         [ #  # ]:          0 :     return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
     408                 :          0 : }
     409                 :            : 
     410                 :          0 : void Session::CreateIfNotCreatedAlready()
     411                 :            : {
     412                 :          0 :     std::string errmsg;
     413 [ #  # ][ #  # ]:          0 :     if (m_control_sock && m_control_sock->IsConnected(errmsg)) {
                 [ #  # ]
     414                 :          0 :         return;
     415                 :            :     }
     416                 :            : 
     417                 :          0 :     const auto session_type = m_transient ? "transient" : "persistent";
     418 [ #  # ][ #  # ]:          0 :     const auto session_id = GetRandHash().GetHex().substr(0, 10); // full is overkill, too verbose in the logs
     419                 :            : 
     420 [ #  # ][ #  # ]:          0 :     Log("Creating %s SAM session %s with %s", session_type, session_id, m_control_host.ToStringAddrPort());
                 [ #  # ]
     421                 :            : 
     422         [ #  # ]:          0 :     auto sock = Hello();
     423                 :            : 
     424         [ #  # ]:          0 :     if (m_transient) {
     425                 :            :         // The destination (private key) is generated upon session creation and returned
     426                 :            :         // in the reply in DESTINATION=.
     427         [ #  # ]:          0 :         const Reply& reply = SendRequestAndGetReply(
     428                 :          0 :             *sock,
     429         [ #  # ]:          0 :             strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT SIGNATURE_TYPE=7 "
     430                 :            :                       "inbound.quantity=1 outbound.quantity=1",
     431                 :            :                       session_id));
     432                 :            : 
     433 [ #  # ][ #  # ]:          0 :         m_private_key = DecodeI2PBase64(reply.Get("DESTINATION"));
                 [ #  # ]
     434                 :          0 :     } else {
     435                 :            :         // Read our persistent destination (private key) from disk or generate
     436                 :            :         // one and save it to disk. Then use it when creating the session.
     437         [ #  # ]:          0 :         const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);
     438         [ #  # ]:          0 :         if (read_ok) {
     439 [ #  # ][ #  # ]:          0 :             m_private_key.assign(data.begin(), data.end());
                 [ #  # ]
     440                 :          0 :         } else {
     441         [ #  # ]:          0 :             GenerateAndSavePrivateKey(*sock);
     442                 :            :         }
     443                 :            : 
     444 [ #  # ][ #  # ]:          0 :         const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));
                 [ #  # ]
     445                 :            : 
     446         [ #  # ]:          0 :         SendRequestAndGetReply(*sock,
     447         [ #  # ]:          0 :                                strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s "
     448                 :            :                                          "inbound.quantity=3 outbound.quantity=3",
     449                 :            :                                          session_id,
     450                 :          0 :                                          private_key_b64));
     451                 :          0 :     }
     452                 :            : 
     453 [ #  # ][ #  # ]:          0 :     m_my_addr = CService(DestBinToAddr(MyDestination()), I2P_SAM31_PORT);
                 [ #  # ]
     454         [ #  # ]:          0 :     m_session_id = session_id;
     455                 :          0 :     m_control_sock = std::move(sock);
     456                 :            : 
     457 [ #  # ][ #  # ]:          0 :     Log("%s SAM session %s created, my address=%s",
     458 [ #  # ][ #  # ]:          0 :         Capitalize(session_type),
     459                 :          0 :         m_session_id,
     460         [ #  # ]:          0 :         m_my_addr.ToStringAddrPort());
     461         [ #  # ]:          0 : }
     462                 :            : 
     463                 :          0 : std::unique_ptr<Sock> Session::StreamAccept()
     464                 :            : {
     465                 :          0 :     auto sock = Hello();
     466                 :            : 
     467         [ #  # ]:          0 :     const Reply& reply = SendRequestAndGetReply(
     468         [ #  # ]:          0 :         *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false);
     469                 :            : 
     470 [ #  # ][ #  # ]:          0 :     const std::string& result = reply.Get("RESULT");
     471                 :            : 
     472 [ #  # ][ #  # ]:          0 :     if (result == "OK") {
     473                 :          0 :         return sock;
     474                 :            :     }
     475                 :            : 
     476 [ #  # ][ #  # ]:          0 :     if (result == "INVALID_ID") {
     477                 :            :         // If our session id is invalid, then force session re-creation on next usage.
     478         [ #  # ]:          0 :         Disconnect();
     479                 :          0 :     }
     480                 :            : 
     481 [ #  # ][ #  # ]:          0 :     throw std::runtime_error(strprintf("\"%s\"", reply.full));
         [ #  # ][ #  # ]
     482         [ #  # ]:          0 : }
     483                 :            : 
     484                 :          0 : void Session::Disconnect()
     485                 :            : {
     486         [ #  # ]:          0 :     if (m_control_sock) {
     487         [ #  # ]:          0 :         if (m_session_id.empty()) {
     488 [ #  # ][ #  # ]:          0 :             Log("Destroying incomplete SAM session");
     489                 :          0 :         } else {
     490 [ #  # ][ #  # ]:          0 :             Log("Destroying SAM session %s", m_session_id);
     491                 :            :         }
     492                 :          0 :         m_control_sock.reset();
     493                 :          0 :     }
     494                 :          0 :     m_session_id.clear();
     495                 :          0 : }
     496                 :            : } // namespace sam
     497                 :            : } // namespace i2p

Generated by: LCOV version 1.14