samserver.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // acetone, 2024
  2. // I hate copyright of any kind. This is a public domain.
  3. // Original source: https://notabug.org/acetone/samty
  4. #include "samserver.h"
  5. Samty::SAMServer::SAMServer(const Configuration &samConfiguration,
  6. PendingConnectionCallbackPointer callback)
  7. : m_streamSession (samConfiguration),
  8. m_connectionCallback (callback)
  9. {
  10. }
  11. std::string Samty::SAMServer::myAddress() const
  12. {
  13. const auto ident = m_streamSession.getMyDestination();
  14. if (not ident.isOk()) return std::string();
  15. return ident.dest33().empty() ? ident.dest32() : ident.dest33();
  16. }
  17. bool Samty::SAMServer::isOk() const
  18. {
  19. return not m_streamSession.isSick();
  20. }
  21. std::string Samty::SAMServer::errorString() const
  22. {
  23. return m_streamSession.errorString();
  24. }
  25. bool Samty::SAMServer::start()
  26. {
  27. if (m_started.load() or !isOk()) return false;
  28. m_mainThread = std::thread(&SAMServer::loop, this);
  29. m_started.store(true);
  30. return true;
  31. }
  32. void Samty::SAMServer::stop()
  33. {
  34. if (!m_started.load()) return;
  35. m_started.store(false);
  36. m_streamSession.closeSocket();
  37. if (m_mainThread.joinable())
  38. {
  39. m_mainThread.join();
  40. }
  41. }
  42. void Samty::SAMServer::loop()
  43. {
  44. while (m_started.load())
  45. {
  46. auto acceptResult = m_streamSession.accept(false);
  47. if (!acceptResult.isOk)
  48. {
  49. std::cerr << "Samty::SAMServer::loop() Accept failed" << std::endl;
  50. continue;
  51. }
  52. std::unique_ptr<I2pSocket> socket = std::move(acceptResult.value);
  53. std::string b32 = socket->readDestination();
  54. if (b32.empty())
  55. {
  56. std::cerr << "Samty::SAMServer::loop() Incoming destination reading failed" << std::endl;
  57. continue;
  58. }
  59. m_connectionCallback(b32, std::move(socket));
  60. }
  61. }