4 #include <sys/socket.h>
6 #include <netinet/in.h>
17 #include "interface.h"
19 extern int GetRandInt(int nMax);
22 * NTP uses two fixed point formats. The first (l_fp) is the "long"
23 * format and is 64 bits long with the decimal between bits 31 and 32.
24 * This is used for time stamps in the NTP packet header (in network
25 * byte order) and for internal computations of offsets (in local host
26 * byte order). We use the same structure for both signed and unsigned
27 * values, which is a big hack but saves rewriting all the operators
28 * twice. Just to confuse this, we also sometimes just carry the
29 * fractional part in calculations, in both signed and unsigned forms.
30 * Anyway, an l_fp looks like:
33 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
34 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
38 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
39 * REF http://www.eecis.udel.edu/~mills/database/rfc/rfc2030.txt
55 inline void Ntp2Unix(const uint32_t &n, time_t &u) {
56 // Ntp's time scale starts in 1900, Unix in 1970.
58 u = n - 0x83aa7e80; // 2208988800 1970 - 1900 in seconds
61 inline void ntohl_fp(l_fp *n, l_fp *h) {
62 (h)->Ul_i.Xl_ui = ntohl((n)->Ul_i.Xl_ui);
63 (h)->Ul_f.Xl_uf = ntohl((n)->Ul_f.Xl_uf);
67 uint8_t li_vn_mode; /* leap indicator, version and mode */
68 uint8_t stratum; /* peer stratum */
69 uint8_t ppoll; /* peer poll interval */
70 int8_t precision; /* peer clock precision */
71 uint32_t rootdelay; /* distance to primary clock */
72 uint32_t rootdispersion; /* clock dispersion */
73 uint32_t refid; /* reference clock ID */
74 l_fp ref; /* time peer clock was last updated */
75 l_fp org; /* originate time stamp */
76 l_fp rec; /* receive time stamp */
77 l_fp xmt; /* transmit time stamp */
79 uint32_t exten[1]; /* misused */
80 uint8_t mac[5 * sizeof(uint32_t)]; /* mac */
83 const int nServersCount = 154;
85 std::string NtpServers[nServersCount] = {
102 // Russian Federation
124 "ntp1.niiftri.irkutsk.ru",
125 "ntp2.niiftri.irkutsk.ru",
137 "timex.cs.columbia.edu",
139 "sundial.columbia.edu",
147 "ntp-01.caltech.edu",
148 "ntp-02.caltech.edu",
149 "ntp-03.caltech.edu",
150 "ntp-04.caltech.edu",
151 "nist0-pa.ustiming.org",
152 "nist1-pa.ustiming.org",
153 "nist2-pa.ustiming.org",
160 "nist1-macon.macon.ga.us",
161 "nist.netservicesgroup.com",
163 "time-a.timefreq.bldrdoc.gov",
164 "time-b.timefreq.bldrdoc.gov",
165 "time-c.timefreq.bldrdoc.gov",
166 "utcnist.colorado.edu",
167 "utcnist2.colorado.edu",
168 "nist1-lv.ustiming.org",
181 "bonehed.lcs.mit.edu",
182 "ntp-s1.cise.ufl.edu",
185 "ntp1.meraka.csir.co.za",
189 "ntp1.neology.co.za",
190 "ntp2.neology.co.za",
191 "tick.meraka.csir.co.za",
192 "tock.meraka.csir.co.za",
194 "ntp1.meraka.csir.co.za",
195 "ntp2.meraka.csir.co.za",
227 "ntp.cis.strath.ac.uk",
238 "timelord.uregina.ca",
254 "augean.eleceng.adelaide.edu.au",
272 // ... To be continued
275 bool InitWithHost(const std::string &strHostName, SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) {
277 sockfd = INVALID_SOCKET;
279 std::vector<CNetAddr> vIP;
280 bool fRet = LookupHost(strHostName.c_str(), vIP, 10, true);
285 struct sockaddr_in servaddr;
286 servaddr.sin_family = AF_INET;
287 servaddr.sin_port = htons(123);
290 for(unsigned int i = 0; i < vIP.size(); i++) {
291 if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)) != false) {
300 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
302 if (sockfd == INVALID_SOCKET)
303 return false; // socket initialization error
305 if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 ) {
306 return false; // "connection" error
310 *pcliaddr = *((struct sockaddr *) &servaddr);
311 servlen = sizeof(servaddr);
316 bool InitWithRandom(SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) {
318 for (int nAttempt = 0; nAttempt < nServersCount; nAttempt++) {
319 int nServerNum = GetRandInt(nServersCount);
320 if (InitWithHost(NtpServers[nServerNum], sockfd, servlen, pcliaddr)) {
328 int64_t DoReq(SOCKET sockfd, socklen_t servlen, struct sockaddr cliaddr) {
333 if (ioctlsocket(sockfd, FIONBIO, &nOne) == SOCKET_ERROR) {
334 printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
336 if (fcntl(sockfd, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) {
337 printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
342 struct timeval timeout = {10, 0};
343 struct pkt *msg = new pkt;
344 struct pkt *prt = new pkt;
345 time_t seconds_transmit;
353 msg->rootdispersion=0;
355 msg->ref.Ul_i.Xl_i=0;
356 msg->ref.Ul_f.Xl_f=0;
357 msg->org.Ul_i.Xl_i=0;
358 msg->org.Ul_f.Xl_f=0;
359 msg->rec.Ul_i.Xl_i=0;
360 msg->rec.Ul_f.Xl_f=0;
361 msg->xmt.Ul_i.Xl_i=0;
362 msg->xmt.Ul_f.Xl_f=0;
364 int retcode = sendto(sockfd, (char *) msg, len, 0, &cliaddr, servlen);
366 printf("sendto() failed: %d\n", retcode);
367 seconds_transmit = -3;
373 FD_SET(sockfd, &fdset);
375 retcode = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
377 printf("recvfrom() error\n");
378 seconds_transmit = -4;
382 recvfrom(sockfd, (char *) msg, len, 0, NULL, NULL);
383 ntohl_fp(&msg->xmt, &prt->xmt);
384 Ntp2Unix(prt->xmt.Ul_i.Xl_ui, seconds_transmit);
391 return seconds_transmit;
394 int64_t NtpGetTime(CNetAddr& ip) {
395 struct sockaddr cliaddr;
400 if (!InitWithRandom(sockfd, servlen, &cliaddr))
403 ip = CNetAddr(((sockaddr_in *)&cliaddr)->sin_addr);
404 int64_t nTime = DoReq(sockfd, servlen, cliaddr);
411 int64_t NtpGetTime(const std::string &strHostName)
413 struct sockaddr cliaddr;
418 if (!InitWithHost(strHostName, sockfd, servlen, &cliaddr))
421 int64_t nTime = DoReq(sockfd, servlen, cliaddr);
428 // NTP server, which we unconditionally trust. This may be your own installation of ntpd somewhere, for example.
429 // "localhost" means "trust no one"
430 std::string strTrustedUpstream = "localhost";
433 int64_t nNtpOffset = INT64_MAX;
435 int64_t GetNtpOffset() {
439 void ThreadNtpSamples(void* parg) {
440 const int64_t nMaxOffset = nOneDay; // Not a real limit, just sanity threshold.
442 printf("Trying to find NTP server at localhost...\n");
444 std::string strLocalHost = "127.0.0.1";
445 if (NtpGetTime(strLocalHost) == GetTime()) {
446 printf("There is NTP server active at localhost, we don't need NTP thread.\n");
452 printf("ThreadNtpSamples started\n");
453 vnThreadsRunning[THREAD_NTP]++;
455 // Make this thread recognisable as time synchronization thread
456 RenameThread("novacoin-ntp-samples");
458 CMedianFilter<int64_t> vTimeOffsets(200,0);
461 if (strTrustedUpstream != "localhost") {
462 // Trying to get new offset sample from trusted NTP server.
463 int64_t nClockOffset = NtpGetTime(strTrustedUpstream) - GetTime();
465 if (abs64(nClockOffset) < nMaxOffset) {
466 // Everything seems right, remember new trusted offset.
467 printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", strTrustedUpstream.c_str(), nClockOffset);
468 nNtpOffset = nClockOffset;
471 // Something went wrong, disable trusted offset sampling.
472 nNtpOffset = INT64_MAX;
473 strTrustedUpstream = "localhost";
475 int nSleepMinutes = 1 + GetRandInt(9); // Sleep for 1-10 minutes.
476 for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
483 // Now, trying to get 2-4 samples from random NTP servers.
484 int nSamplesCount = 2 + GetRandInt(2);
486 for (int i = 0; i < nSamplesCount; i++) {
488 int64_t nClockOffset = NtpGetTime(ip) - GetTime();
490 if (abs64(nClockOffset) < nMaxOffset) { // Skip the deliberately wrong timestamps
491 printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", ip.ToString().c_str(), nClockOffset);
492 vTimeOffsets.input(nClockOffset);
496 if (vTimeOffsets.size() > 1) {
497 nNtpOffset = vTimeOffsets.median();
500 // Not enough offsets yet, try to collect additional samples later.
501 nNtpOffset = INT64_MAX;
502 int nSleepMinutes = 1 + GetRandInt(4); // Sleep for 1-5 minutes.
503 for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
509 if (GetNodesOffset() == INT_MAX && abs64(nNtpOffset) > 40 * 60)
511 // If there is not enough node offsets data and NTP time offset is greater than 40 minutes then give a warning.
512 std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
513 strMiscWarning = strMessage;
514 printf("*** %s\n", strMessage.c_str());
515 uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
518 printf("nNtpOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNtpOffset, nNtpOffset/60);
520 int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours.
521 for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++)
525 vnThreadsRunning[THREAD_NTP]--;
526 printf("ThreadNtpSamples exited\n");