i2pd/libi2pd/Timestamp.cpp

283 lines
6.8 KiB
C++
Raw Normal View History

/*
2024-02-27 20:33:07 +03:00
* Copyright (c) 2013-2024, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
2019-03-07 19:55:47 +03:00
#include <time.h>
#include <stdio.h>
2016-09-21 23:18:51 +03:00
#include <inttypes.h>
#include <string.h>
2018-11-14 19:06:53 +03:00
#include <chrono>
#include <future>
2016-09-21 23:18:51 +03:00
#include <boost/asio.hpp>
2018-11-14 19:06:53 +03:00
#include <boost/algorithm/string.hpp>
#include "Config.h"
2016-11-01 23:27:44 +03:00
#include "Log.h"
2021-07-24 23:01:11 +03:00
#include "RouterContext.h"
2016-09-21 23:18:51 +03:00
#include "I2PEndian.h"
2016-09-21 19:02:52 +03:00
#include "Timestamp.h"
#include "util.h"
2016-09-21 19:02:52 +03:00
#ifdef _WIN32
#ifndef _WIN64
#define _USE_32BIT_TIME_T
#endif
#endif
2016-09-21 19:02:52 +03:00
namespace i2p
{
namespace util
{
2018-11-14 19:06:53 +03:00
static uint64_t GetLocalMillisecondsSinceEpoch ()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count ();
2018-11-14 19:06:53 +03:00
}
2020-10-23 22:53:22 +03:00
static uint64_t GetLocalSecondsSinceEpoch ()
2018-11-14 19:06:53 +03:00
{
2020-10-23 22:53:22 +03:00
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()).count ();
2018-11-14 19:06:53 +03:00
}
2020-10-23 22:53:22 +03:00
static uint32_t GetLocalMinutesSinceEpoch ()
2018-11-14 19:06:53 +03:00
{
2020-10-23 22:53:22 +03:00
return std::chrono::duration_cast<std::chrono::minutes>(
std::chrono::system_clock::now().time_since_epoch()).count ();
}
2020-10-23 22:53:22 +03:00
static uint32_t GetLocalHoursSinceEpoch ()
{
return std::chrono::duration_cast<std::chrono::hours>(
std::chrono::system_clock::now().time_since_epoch()).count ();
2018-11-14 19:06:53 +03:00
}
2016-11-02 01:40:00 +03:00
static int64_t g_TimeOffset = 0; // in seconds
2016-09-21 23:18:51 +03:00
2018-11-14 19:06:53 +03:00
static void SyncTimeWithNTP (const std::string& address)
2016-09-21 23:18:51 +03:00
{
LogPrint (eLogInfo, "Timestamp: NTP request to ", address);
2016-09-21 23:18:51 +03:00
boost::asio::io_service service;
boost::system::error_code ec;
2021-07-24 01:34:51 +03:00
auto it = boost::asio::ip::udp::resolver (service).resolve (
boost::asio::ip::udp::resolver::query (address, "ntp"), ec);
2021-07-24 23:01:11 +03:00
if (!ec)
2016-09-21 23:18:51 +03:00
{
2021-07-24 23:01:11 +03:00
bool found = false;
boost::asio::ip::udp::resolver::iterator end;
boost::asio::ip::udp::endpoint ep;
while (it != end)
{
2021-07-24 23:01:11 +03:00
ep = *it;
if (!ep.address ().is_unspecified ())
{
if (ep.address ().is_v4 ())
{
if (i2p::context.SupportsV4 ()) found = true;
2021-07-24 23:01:11 +03:00
}
else if (ep.address ().is_v6 ())
{
if (i2p::util::net::IsYggdrasilAddress (ep.address ()))
{
if (i2p::context.SupportsMesh ()) found = true;
}
2021-07-24 23:01:11 +03:00
else if (i2p::context.SupportsV6 ()) found = true;
}
}
2021-07-24 23:01:11 +03:00
if (found) break;
it++;
}
if (!found)
{
LogPrint (eLogError, "Timestamp: can't find compatible address for ", address);
return;
}
2016-09-21 23:18:51 +03:00
boost::asio::ip::udp::socket socket (service);
2021-07-24 01:34:51 +03:00
socket.open (ep.protocol (), ec);
2016-09-21 23:18:51 +03:00
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
{
2018-01-06 06:48:51 +03:00
std::this_thread::sleep_for (std::chrono::seconds(1));
2016-11-02 01:40:00 +03:00
i++;
}
2016-11-02 01:40:00 +03:00
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)
{
2018-11-14 19:06:53 +03:00
LogPrint (eLogError, "Timestamp: NTP error: ", e.what ());
}
2016-09-21 23:18:51 +03:00
if (len >= 8)
{
2018-11-14 19:06:53 +03:00
auto ourTs = GetLocalSecondsSinceEpoch ();
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;
2018-11-14 20:27:11 +03:00
LogPrint (eLogInfo, "Timestamp: ", address, " time offset from system time is ", g_TimeOffset, " seconds");
}
2016-09-21 23:18:51 +03:00
}
2018-11-14 20:27:11 +03:00
else
LogPrint (eLogError, "Timestamp: Couldn't open UDP socket");
2016-09-21 23:18:51 +03:00
}
2018-11-14 20:27:11 +03:00
else
2021-07-24 01:34:51 +03:00
LogPrint (eLogError, "Timestamp: Couldn't resolve address ", address);
}
2018-11-14 19:06:53 +03:00
2018-11-16 20:49:04 +03:00
NTPTimeSync::NTPTimeSync (): m_IsRunning (false), m_Timer (m_Service)
2018-11-14 19:06:53 +03:00
{
2018-11-16 20:49:04 +03:00
i2p::config::GetOption("nettime.ntpsyncinterval", m_SyncInterval);
2018-11-14 19:06:53 +03:00
std::string ntpservers; i2p::config::GetOption("nettime.ntpservers", ntpservers);
2018-11-16 20:49:04 +03:00
boost::split (m_NTPServersList, ntpservers, boost::is_any_of(","), boost::token_compress_on);
}
NTPTimeSync::~NTPTimeSync ()
{
Stop ();
}
void NTPTimeSync::Start()
{
if (m_NTPServersList.size () > 0)
{
m_IsRunning = true;
LogPrint(eLogInfo, "Timestamp: NTP time sync starting");
m_Service.post (std::bind (&NTPTimeSync::Sync, this));
m_Thread.reset (new std::thread (std::bind (&NTPTimeSync::Run, this)));
}
else
LogPrint (eLogWarning, "Timestamp: No NTP server found");
}
void NTPTimeSync::Stop ()
{
if (m_IsRunning)
{
LogPrint(eLogInfo, "Timestamp: NTP time sync stopping");
m_IsRunning = false;
m_Timer.cancel ();
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
m_Thread.reset (nullptr);
}
}
}
void NTPTimeSync::Run ()
{
i2p::util::SetThreadName("Timesync");
2018-11-16 20:49:04 +03:00
while (m_IsRunning)
2018-11-14 19:06:53 +03:00
{
2018-11-16 20:49:04 +03:00
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "Timestamp: NTP time sync exception: ", ex.what ());
}
}
}
void NTPTimeSync::Sync ()
{
2018-11-16 20:49:04 +03:00
if (m_NTPServersList.size () > 0)
SyncTimeWithNTP (m_NTPServersList[rand () % m_NTPServersList.size ()]);
else
m_IsRunning = false;
2018-11-16 20:49:04 +03:00
if (m_IsRunning)
{
m_Timer.expires_from_now (boost::posix_time::hours (m_SyncInterval));
m_Timer.async_wait ([this](const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
Sync ();
});
2018-11-14 19:06:53 +03:00
}
}
uint64_t GetMillisecondsSinceEpoch ()
{
return GetLocalMillisecondsSinceEpoch () + g_TimeOffset*1000;
}
uint64_t GetSecondsSinceEpoch ()
{
return GetLocalSecondsSinceEpoch () + g_TimeOffset;
}
2020-10-23 22:53:22 +03:00
uint32_t GetMinutesSinceEpoch ()
{
return GetLocalMinutesSinceEpoch () + g_TimeOffset/60;
}
2020-10-23 22:53:22 +03:00
uint32_t GetHoursSinceEpoch ()
{
return GetLocalHoursSinceEpoch () + g_TimeOffset/3600;
2018-11-14 19:06:53 +03:00
}
2019-03-07 19:55:47 +03:00
2024-02-27 20:33:07 +03:00
uint64_t GetMonotonicMicroseconds()
2024-02-27 11:15:15 +03:00
{
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
2024-02-27 20:33:07 +03:00
uint64_t GetMonotonicMilliseconds()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
uint64_t GetMonotonicSeconds ()
{
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
2019-03-07 19:55:47 +03:00
void GetCurrentDate (char * date)
{
2019-04-12 21:05:07 +03:00
GetDateString (GetSecondsSinceEpoch (), date);
}
void GetNextDayDate (char * date)
{
GetDateString (GetSecondsSinceEpoch () + 24*60*60, date);
}
2019-04-12 21:05:07 +03:00
void GetDateString (uint64_t timestamp, char * date)
{
using clock = std::chrono::system_clock;
auto t = clock::to_time_t (clock::time_point (std::chrono::seconds(timestamp)));
2019-03-07 19:55:47 +03:00
struct tm tm;
#ifdef _WIN32
gmtime_s(&tm, &t);
sprintf_s(date, 9, "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
#else
gmtime_r(&t, &tm);
sprintf(date, "%04i%02i%02i", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
#endif
}
void AdjustTimeOffset (int64_t offset)
{
g_TimeOffset += offset;
}
2016-09-21 19:02:52 +03:00
}
}