File: Timestamp.cpp

package info (click to toggle)
i2pd 2.58.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: cpp: 59,663; makefile: 224; sh: 138
file content (279 lines) | stat: -rw-r--r-- 6,860 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
* 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
*/

#include <time.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <chrono>
#include <future>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include "Config.h"
#include "Log.h"
#include "RouterContext.h"
#include "I2PEndian.h"
#include "Timestamp.h"
#include "util.h"

#ifdef _WIN32
	#ifndef _WIN64
		#define _USE_32BIT_TIME_T
	#endif
#endif

namespace i2p
{
namespace util
{
	static uint64_t GetLocalMillisecondsSinceEpoch ()
	{
		return std::chrono::duration_cast<std::chrono::milliseconds>(
			std::chrono::system_clock::now().time_since_epoch()).count ();
	}

	static uint64_t GetLocalSecondsSinceEpoch ()
	{
		return std::chrono::duration_cast<std::chrono::seconds>(
			std::chrono::system_clock::now().time_since_epoch()).count ();
	}

	static uint32_t GetLocalMinutesSinceEpoch ()
	{
		return std::chrono::duration_cast<std::chrono::minutes>(
			std::chrono::system_clock::now().time_since_epoch()).count ();
	}

	static uint32_t GetLocalHoursSinceEpoch ()
	{
		return std::chrono::duration_cast<std::chrono::hours>(
			std::chrono::system_clock::now().time_since_epoch()).count ();
	}

	static int64_t g_TimeOffset = 0; // in seconds

	static void SyncTimeWithNTP (const std::string& address)
	{
		LogPrint (eLogInfo, "Timestamp: NTP request to ", address);
		boost::asio::io_context service;
		boost::system::error_code ec;
		auto endpoints = boost::asio::ip::udp::resolver (service).resolve (address, "ntp", ec);
		if (!ec)
		{
			bool found = false;
			boost::asio::ip::udp::endpoint ep;
			for (const auto& it: endpoints)
			{
				ep = it;
				if (!ep.address ().is_unspecified ())
				{
					if (ep.address ().is_v4 ())
					{
						if (i2p::context.SupportsV4 ()) found = true;
					}
					else if (ep.address ().is_v6 ())
					{
						if (i2p::util::net::IsYggdrasilAddress (ep.address ()))
						{
							if (i2p::context.SupportsMesh ()) found = true;
						}
						else if (i2p::context.SupportsV6 ()) found = true;
					}
				}
				if (found) break;
			}
			if (!found)
			{
				LogPrint (eLogError, "Timestamp: can't find compatible address for ", address);
				return;
			}

			boost::asio::ip::udp::socket socket (service);
			socket.open (ep.protocol (), ec);
			if (!ec)
			{
				uint8_t buf[48];// 48 bytes NTP request/response
				memset (buf, 0, 48);
				htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
				size_t len = 0;
				try
				{
					socket.send_to (boost::asio::buffer (buf, 48), ep);
					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);
				}
				catch (std::exception& e)
				{
					LogPrint (eLogError, "Timestamp: NTP error: ", e.what ());
				}
				if (len >= 8)
				{
					auto ourTs = GetLocalSecondsSinceEpoch ();
					uint32_t ts = bufbe32toh (buf + 32);
					if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
					g_TimeOffset = ts - ourTs;
					LogPrint (eLogInfo, "Timestamp: ", address, " time offset from system time is ", g_TimeOffset, " seconds");
				}
			}
			else
				LogPrint (eLogError, "Timestamp: Couldn't open UDP socket");
		}
		else
			LogPrint (eLogError, "Timestamp: Couldn't resolve address ", address);
	}

	NTPTimeSync::NTPTimeSync (): m_IsRunning (false), m_Timer (m_Service)
	{
		i2p::config::GetOption("nettime.ntpsyncinterval", m_SyncInterval);
		std::string ntpservers; i2p::config::GetOption("nettime.ntpservers", ntpservers);
		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");
			boost::asio::post (m_Service, 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");

		while (m_IsRunning)
		{
			try
			{
				m_Service.run ();
			}
			catch (std::exception& ex)
			{
				LogPrint (eLogError, "Timestamp: NTP time sync exception: ", ex.what ());
			}
		}
	}

	void NTPTimeSync::Sync ()
	{
		if (m_NTPServersList.size () > 0)
			SyncTimeWithNTP (m_NTPServersList[rand () % m_NTPServersList.size ()]);
		else
			m_IsRunning = false;

		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 ();
			});
		}
	}

	uint64_t GetMillisecondsSinceEpoch ()
	{
		return GetLocalMillisecondsSinceEpoch () + g_TimeOffset*1000;
	}

	uint64_t GetSecondsSinceEpoch ()
	{
		return GetLocalSecondsSinceEpoch () + g_TimeOffset;
	}

	uint32_t GetMinutesSinceEpoch ()
	{
		return GetLocalMinutesSinceEpoch () + g_TimeOffset/60;
	}

	uint32_t GetHoursSinceEpoch ()
	{
		return GetLocalHoursSinceEpoch () + g_TimeOffset/3600;
	}

	uint64_t GetMonotonicMicroseconds()
	{
		return std::chrono::duration_cast<std::chrono::microseconds>(
			std::chrono::steady_clock::now().time_since_epoch()).count();
	}

	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();
	}	
	
	void GetCurrentDate (char * date)
	{
		GetDateString (GetSecondsSinceEpoch (), date);
	}

	void GetNextDayDate (char * date)
	{
		GetDateString (GetSecondsSinceEpoch () + 24*60*60, date);
	}	
	
	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)));
		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;
	}
}
}