mirror of https://github.com/PurpleI2P/i2pd.git
I2P: End-to-End encrypted and anonymous Internet
https://i2pd.website/
67 lines
1.7 KiB
67 lines
1.7 KiB
8 years ago
|
#include <inttypes.h>
|
||
|
#include <string.h>
|
||
|
#include <boost/asio.hpp>
|
||
8 years ago
|
#include "Log.h"
|
||
8 years ago
|
#include "I2PEndian.h"
|
||
8 years ago
|
#include "Timestamp.h"
|
||
|
|
||
8 years ago
|
#ifdef WIN32
|
||
|
#ifndef _WIN64
|
||
|
#define _USE_32BIT_TIME_T
|
||
|
#endif
|
||
|
#endif
|
||
|
|
||
8 years ago
|
namespace i2p
|
||
|
{
|
||
|
namespace util
|
||
|
{
|
||
8 years ago
|
static int64_t g_TimeOffset = 0; // in seconds
|
||
8 years ago
|
|
||
|
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)
|
||
|
{
|
||
8 years ago
|
uint8_t buf[48];// 48 bytes NTP request/response
|
||
|
memset (buf, 0, 48);
|
||
|
htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
|
||
8 years ago
|
size_t len = 0;
|
||
|
try
|
||
|
{
|
||
8 years ago
|
socket.send_to (boost::asio::buffer (buf, 48), ep);
|
||
8 years ago
|
int i = 0;
|
||
|
while (!socket.available() && i < 10) // 10 seconds max
|
||
8 years ago
|
{
|
||
8 years ago
|
std::this_thread::sleep_for (std::chrono::seconds(1));
|
||
|
i++;
|
||
8 years ago
|
}
|
||
8 years ago
|
if (socket.available ())
|
||
|
len = socket.receive_from (boost::asio::buffer (buf, 48), ep);
|
||
8 years ago
|
}
|
||
|
catch (std::exception& e)
|
||
|
{
|
||
8 years ago
|
LogPrint (eLogError, "NTP error: ", e.what ());
|
||
8 years ago
|
}
|
||
8 years ago
|
if (len >= 8)
|
||
|
{
|
||
8 years ago
|
auto ourTs = GetSecondsSinceEpoch ();
|
||
8 years ago
|
uint32_t ts = bufbe32toh (buf + 32);
|
||
8 years ago
|
if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
|
||
8 years ago
|
g_TimeOffset = ts - ourTs;
|
||
|
LogPrint (eLogInfo, address, " time offset from system time is ", g_TimeOffset, " seconds");
|
||
8 years ago
|
}
|
||
8 years ago
|
}
|
||
|
}
|
||
8 years ago
|
}
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|