Timestamp.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <inttypes.h>
  4. #include <string.h>
  5. #include <chrono>
  6. #include <future>
  7. #include <boost/asio.hpp>
  8. #include <boost/algorithm/string.hpp>
  9. #include "Config.h"
  10. #include "Log.h"
  11. #include "I2PEndian.h"
  12. #include "Timestamp.h"
  13. #ifdef WIN32
  14. #ifndef _WIN64
  15. #define _USE_32BIT_TIME_T
  16. #endif
  17. #endif
  18. namespace i2p
  19. {
  20. namespace util
  21. {
  22. static uint64_t GetLocalMillisecondsSinceEpoch ()
  23. {
  24. return std::chrono::duration_cast<std::chrono::milliseconds>(
  25. std::chrono::system_clock::now().time_since_epoch()).count ();
  26. }
  27. static uint32_t GetLocalHoursSinceEpoch ()
  28. {
  29. return std::chrono::duration_cast<std::chrono::hours>(
  30. std::chrono::system_clock::now().time_since_epoch()).count ();
  31. }
  32. static uint64_t GetLocalSecondsSinceEpoch ()
  33. {
  34. return std::chrono::duration_cast<std::chrono::seconds>(
  35. std::chrono::system_clock::now().time_since_epoch()).count ();
  36. }
  37. static int64_t g_TimeOffset = 0; // in seconds
  38. static void SyncTimeWithNTP (const std::string& address)
  39. {
  40. LogPrint (eLogInfo, "Timestamp: NTP request to ", address);
  41. boost::asio::io_service service;
  42. boost::asio::ip::udp::resolver::query query (boost::asio::ip::udp::v4 (), address, "ntp");
  43. boost::system::error_code ec;
  44. auto it = boost::asio::ip::udp::resolver (service).resolve (query, ec);
  45. if (!ec && it != boost::asio::ip::udp::resolver::iterator())
  46. {
  47. auto ep = (*it).endpoint (); // take first one
  48. boost::asio::ip::udp::socket socket (service);
  49. socket.open (boost::asio::ip::udp::v4 (), ec);
  50. if (!ec)
  51. {
  52. uint8_t buf[48];// 48 bytes NTP request/response
  53. memset (buf, 0, 48);
  54. htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
  55. size_t len = 0;
  56. try
  57. {
  58. socket.send_to (boost::asio::buffer (buf, 48), ep);
  59. int i = 0;
  60. while (!socket.available() && i < 10) // 10 seconds max
  61. {
  62. std::this_thread::sleep_for (std::chrono::seconds(1));
  63. i++;
  64. }
  65. if (socket.available ())
  66. len = socket.receive_from (boost::asio::buffer (buf, 48), ep);
  67. }
  68. catch (std::exception& e)
  69. {
  70. LogPrint (eLogError, "Timestamp: NTP error: ", e.what ());
  71. }
  72. if (len >= 8)
  73. {
  74. auto ourTs = GetLocalSecondsSinceEpoch ();
  75. uint32_t ts = bufbe32toh (buf + 32);
  76. if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
  77. g_TimeOffset = ts - ourTs;
  78. LogPrint (eLogInfo, "Timestamp: ", address, " time offset from system time is ", g_TimeOffset, " seconds");
  79. }
  80. }
  81. else
  82. LogPrint (eLogError, "Timestamp: Couldn't open UDP socket");
  83. }
  84. else
  85. LogPrint (eLogError, "Timestamp: Couldn't resove address ", address);
  86. }
  87. NTPTimeSync::NTPTimeSync (): m_IsRunning (false), m_Timer (m_Service)
  88. {
  89. i2p::config::GetOption("nettime.ntpsyncinterval", m_SyncInterval);
  90. std::string ntpservers; i2p::config::GetOption("nettime.ntpservers", ntpservers);
  91. boost::split (m_NTPServersList, ntpservers, boost::is_any_of(","), boost::token_compress_on);
  92. }
  93. NTPTimeSync::~NTPTimeSync ()
  94. {
  95. Stop ();
  96. }
  97. void NTPTimeSync::Start()
  98. {
  99. if (m_NTPServersList.size () > 0)
  100. {
  101. m_IsRunning = true;
  102. LogPrint(eLogInfo, "Timestamp: NTP time sync starting");
  103. m_Service.post (std::bind (&NTPTimeSync::Sync, this));
  104. m_Thread.reset (new std::thread (std::bind (&NTPTimeSync::Run, this)));
  105. }
  106. else
  107. LogPrint (eLogWarning, "Timestamp: No NTP server found");
  108. }
  109. void NTPTimeSync::Stop ()
  110. {
  111. if (m_IsRunning)
  112. {
  113. LogPrint(eLogInfo, "Timestamp: NTP time sync stopping");
  114. m_IsRunning = false;
  115. m_Timer.cancel ();
  116. m_Service.stop ();
  117. if (m_Thread)
  118. {
  119. m_Thread->join ();
  120. m_Thread.reset (nullptr);
  121. }
  122. }
  123. }
  124. void NTPTimeSync::Run ()
  125. {
  126. while (m_IsRunning)
  127. {
  128. try
  129. {
  130. m_Service.run ();
  131. }
  132. catch (std::exception& ex)
  133. {
  134. LogPrint (eLogError, "Timestamp: NTP time sync exception: ", ex.what ());
  135. }
  136. }
  137. }
  138. void NTPTimeSync::Sync ()
  139. {
  140. if (m_NTPServersList.size () > 0)
  141. SyncTimeWithNTP (m_NTPServersList[rand () % m_NTPServersList.size ()]);
  142. else
  143. m_IsRunning = false;
  144. if (m_IsRunning)
  145. {
  146. m_Timer.expires_from_now (boost::posix_time::hours (m_SyncInterval));
  147. m_Timer.async_wait ([this](const boost::system::error_code& ecode)
  148. {
  149. if (ecode != boost::asio::error::operation_aborted)
  150. Sync ();
  151. });
  152. }
  153. }
  154. uint64_t GetMillisecondsSinceEpoch ()
  155. {
  156. return GetLocalMillisecondsSinceEpoch () + g_TimeOffset*1000;
  157. }
  158. uint32_t GetHoursSinceEpoch ()
  159. {
  160. return GetLocalHoursSinceEpoch () + g_TimeOffset/3600;
  161. }
  162. uint64_t GetSecondsSinceEpoch ()
  163. {
  164. return GetLocalSecondsSinceEpoch () + g_TimeOffset;
  165. }
  166. void GetCurrentDate (char * date)
  167. {
  168. GetDateString (GetSecondsSinceEpoch (), date);
  169. }
  170. void GetDateString (uint64_t timestamp, char * date)
  171. {
  172. using clock = std::chrono::system_clock;
  173. auto t = clock::to_time_t (clock::time_point (std::chrono::seconds(timestamp)));
  174. struct tm tm;
  175. #ifdef _WIN32
  176. gmtime_s(&tm, &t);
  177. sprintf_s(date, 9, "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
  178. #else
  179. gmtime_r(&t, &tm);
  180. sprintf(date, "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
  181. #endif
  182. }
  183. }
  184. }