i2pd/Timestamp.cpp

61 lines
1.6 KiB
C++
Raw Normal View History

2016-09-21 23:18:51 +03:00
#include <inttypes.h>
#include <string.h>
#include <boost/asio.hpp>
2016-11-01 23:27:44 +03:00
#include "Log.h"
2016-09-21 23:18:51 +03:00
#include "I2PEndian.h"
2016-09-21 19:02:52 +03:00
#include "Timestamp.h"
namespace i2p
{
namespace util
{
2016-11-02 01:40:00 +03:00
static int64_t g_TimeOffset = 0; // in seconds
2016-09-21 23:18:51 +03:00
void SyncTimeWithNTP (const std::string& address)
{
boost::asio::io_service service;
boost::asio::ip::udp::resolver::query query (boost::asio::ip::udp::v4 (), address, "ntp");
boost::system::error_code ec;
auto it = boost::asio::ip::udp::resolver (service).resolve (query, ec);
if (!ec && it != boost::asio::ip::udp::resolver::iterator())
{
auto ep = (*it).endpoint (); // take first one
boost::asio::ip::udp::socket socket (service);
socket.open (boost::asio::ip::udp::v4 (), ec);
if (!ec)
{
2016-11-01 23:27:44 +03:00
uint8_t buf[48];// 48 bytes NTP request/response
memset (buf, 0, 48);
htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
2016-09-21 23:18:51 +03:00
size_t len = 0;
try
{
2016-11-01 23:27:44 +03:00
socket.send_to (boost::asio::buffer (buf, 48), ep);
2016-11-02 01:40:00 +03:00
int i = 0;
while (!socket.available() && i < 10) // 10 seconds max
{
std::this_thread::sleep_for (std::chrono::seconds(1));
i++;
}
if (socket.available ())
len = socket.receive_from (boost::asio::buffer (buf, 48), ep);
2016-09-21 23:18:51 +03:00
}
catch (std::exception& e)
{
2016-11-02 01:40:00 +03:00
LogPrint (eLogError, "NTP error: ", e.what ());
2016-09-21 23:18:51 +03:00
}
if (len >= 8)
{
2016-11-02 01:40:00 +03:00
auto ourTs = GetSecondsSinceEpoch ();
2016-11-01 23:27:44 +03:00
uint32_t ts = bufbe32toh (buf + 32);
2016-09-21 23:18:51 +03:00
if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
2016-11-02 01:40:00 +03:00
g_TimeOffset = ts - ourTs;
LogPrint (eLogInfo, address, " time offset from system time is ", g_TimeOffset, " seconds");
2016-09-21 23:18:51 +03:00
}
}
}
}
2016-09-21 19:02:52 +03:00
}
}