| 156 | } |
| 157 | |
| 158 | bool Session::Accept(Connection& conn) |
| 159 | { |
| 160 | AssertLockNotHeld(m_mutex); |
| 161 | |
| 162 | std::string errmsg; |
| 163 | bool disconnect{false}; |
| 164 | |
| 165 | while (!m_interrupt->interrupted()) { |
| 166 | Sock::Event occurred; |
| 167 | if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RecvEvent, &occurred)) { |
| 168 | errmsg = "wait on socket failed"; |
| 169 | break; |
| 170 | } |
| 171 | |
| 172 | if (occurred == 0) { |
| 173 | // Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO. |
| 174 | continue; |
| 175 | } |
| 176 | |
| 177 | std::string peer_dest; |
| 178 | try { |
| 179 | peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE); |
| 180 | } catch (const std::runtime_error& e) { |
| 181 | errmsg = e.what(); |
| 182 | break; |
| 183 | } |
| 184 | |
| 185 | CNetAddr peer_addr; |
| 186 | try { |
| 187 | peer_addr = DestB64ToAddr(peer_dest); |
| 188 | } catch (const std::runtime_error& e) { |
| 189 | // The I2P router is expected to send the Base64 of the connecting peer, |
| 190 | // but it may happen that something like this is sent instead: |
| 191 | // STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed" |
| 192 | // In that case consider the session damaged and close it right away, |
| 193 | // even if the control socket is alive. |
| 194 | if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) { |
| 195 | errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest); |
| 196 | disconnect = true; |
| 197 | } else { |
| 198 | errmsg = e.what(); |
| 199 | } |
| 200 | break; |
| 201 | } |
| 202 | |
| 203 | conn.peer = CService(peer_addr, I2P_SAM31_PORT); |
| 204 | |
| 205 | return true; |
| 206 | } |
| 207 | |
| 208 | if (m_interrupt->interrupted()) { |
| 209 | LogDebug(BCLog::I2P, "Accept was interrupted\n"); |
| 210 | } else { |
| 211 | LogDebug(BCLog::I2P, "Error accepting%s: %s\n", disconnect ? " (will close the session)" : "", errmsg); |
| 212 | } |
| 213 | if (disconnect) { |
| 214 | LOCK(m_mutex); |
| 215 | Disconnect(); |
no test coverage detected