index.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. // Load modules
  2. var Dgram = require('dgram');
  3. var Dns = require('dns');
  4. var Hoek = require('hoek');
  5. // Declare internals
  6. var internals = {};
  7. exports.time = function (options, callback) {
  8. if (arguments.length !== 2) {
  9. callback = arguments[0];
  10. options = {};
  11. }
  12. var settings = Hoek.clone(options);
  13. settings.host = settings.host || 'pool.ntp.org';
  14. settings.port = settings.port || 123;
  15. settings.resolveReference = settings.resolveReference || false;
  16. // Declare variables used by callback
  17. var timeoutId = 0;
  18. var sent = 0;
  19. // Ensure callback is only called once
  20. var isFinished = false;
  21. var finish = function (err, result) {
  22. if (timeoutId) {
  23. clearTimeout(timeoutId);
  24. timeoutId = 0;
  25. }
  26. if (!isFinished) {
  27. isFinished = true;
  28. socket.removeAllListeners();
  29. socket.close();
  30. return callback(err, result);
  31. }
  32. };
  33. // Create UDP socket
  34. var socket = Dgram.createSocket('udp4');
  35. socket.once('error', function (err) {
  36. return finish(err);
  37. });
  38. // Listen to incoming messages
  39. socket.on('message', function (buffer, rinfo) {
  40. var received = Date.now();
  41. var message = new internals.NtpMessage(buffer);
  42. if (!message.isValid) {
  43. return finish(new Error('Invalid server response'), message);
  44. }
  45. if (message.originateTimestamp !== sent) {
  46. return finish(new Error('Wrong originate timestamp'), message);
  47. }
  48. // Timestamp Name ID When Generated
  49. // ------------------------------------------------------------
  50. // Originate Timestamp T1 time request sent by client
  51. // Receive Timestamp T2 time request received by server
  52. // Transmit Timestamp T3 time reply sent by server
  53. // Destination Timestamp T4 time reply received by client
  54. //
  55. // The roundtrip delay d and system clock offset t are defined as:
  56. //
  57. // d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2
  58. var T1 = message.originateTimestamp;
  59. var T2 = message.receiveTimestamp;
  60. var T3 = message.transmitTimestamp;
  61. var T4 = received;
  62. message.d = (T4 - T1) - (T3 - T2);
  63. message.t = ((T2 - T1) + (T3 - T4)) / 2;
  64. message.receivedLocally = received;
  65. if (!settings.resolveReference ||
  66. message.stratum !== 'secondary') {
  67. return finish(null, message);
  68. }
  69. // Resolve reference IP address
  70. Dns.reverse(message.referenceId, function (err, domains) {
  71. if (!err) {
  72. message.referenceHost = domains[0];
  73. }
  74. return finish(null, message);
  75. });
  76. });
  77. // Set timeout
  78. if (settings.timeout) {
  79. timeoutId = setTimeout(function () {
  80. timeoutId = 0;
  81. return finish(new Error('Timeout'));
  82. }, settings.timeout);
  83. }
  84. // Construct NTP message
  85. var message = new Buffer(48);
  86. for (var i = 0; i < 48; i++) { // Zero message
  87. message[i] = 0;
  88. }
  89. message[0] = (0 << 6) + (4 << 3) + (3 << 0) // Set version number to 4 and Mode to 3 (client)
  90. sent = Date.now();
  91. internals.fromMsecs(sent, message, 40); // Set transmit timestamp (returns as originate)
  92. // Send NTP request
  93. socket.send(message, 0, message.length, settings.port, settings.host, function (err, bytes) {
  94. if (err ||
  95. bytes !== 48) {
  96. return finish(err || new Error('Could not send entire message'));
  97. }
  98. });
  99. };
  100. internals.NtpMessage = function (buffer) {
  101. this.isValid = false;
  102. // Validate
  103. if (buffer.length !== 48) {
  104. return;
  105. }
  106. // Leap indicator
  107. var li = (buffer[0] >> 6);
  108. switch (li) {
  109. case 0: this.leapIndicator = 'no-warning'; break;
  110. case 1: this.leapIndicator = 'last-minute-61'; break;
  111. case 2: this.leapIndicator = 'last-minute-59'; break;
  112. case 3: this.leapIndicator = 'alarm'; break;
  113. }
  114. // Version
  115. var vn = ((buffer[0] & 0x38) >> 3);
  116. this.version = vn;
  117. // Mode
  118. var mode = (buffer[0] & 0x7);
  119. switch (mode) {
  120. case 1: this.mode = 'symmetric-active'; break;
  121. case 2: this.mode = 'symmetric-passive'; break;
  122. case 3: this.mode = 'client'; break;
  123. case 4: this.mode = 'server'; break;
  124. case 5: this.mode = 'broadcast'; break;
  125. case 0:
  126. case 6:
  127. case 7: this.mode = 'reserved'; break;
  128. }
  129. // Stratum
  130. var stratum = buffer[1];
  131. if (stratum === 0) {
  132. this.stratum = 'death';
  133. }
  134. else if (stratum === 1) {
  135. this.stratum = 'primary';
  136. }
  137. else if (stratum <= 15) {
  138. this.stratum = 'secondary';
  139. }
  140. else {
  141. this.stratum = 'reserved';
  142. }
  143. // Poll interval (msec)
  144. this.pollInterval = Math.round(Math.pow(2, buffer[2])) * 1000;
  145. // Precision (msecs)
  146. this.precision = Math.pow(2, buffer[3]) * 1000;
  147. // Root delay (msecs)
  148. var rootDelay = 256 * (256 * (256 * buffer[4] + buffer[5]) + buffer[6]) + buffer[7];
  149. this.rootDelay = 1000 * (rootDelay / 0x10000);
  150. // Root dispersion (msecs)
  151. this.rootDispersion = ((buffer[8] << 8) + buffer[9] + ((buffer[10] << 8) + buffer[11]) / Math.pow(2, 16)) * 1000;
  152. // Reference identifier
  153. this.referenceId = '';
  154. switch (this.stratum) {
  155. case 'death':
  156. case 'primary':
  157. this.referenceId = String.fromCharCode(buffer[12]) + String.fromCharCode(buffer[13]) + String.fromCharCode(buffer[14]) + String.fromCharCode(buffer[15]);
  158. break;
  159. case 'secondary':
  160. this.referenceId = '' + buffer[12] + '.' + buffer[13] + '.' + buffer[14] + '.' + buffer[15];
  161. break;
  162. }
  163. // Reference timestamp
  164. this.referenceTimestamp = internals.toMsecs(buffer, 16);
  165. // Originate timestamp
  166. this.originateTimestamp = internals.toMsecs(buffer, 24);
  167. // Receive timestamp
  168. this.receiveTimestamp = internals.toMsecs(buffer, 32);
  169. // Transmit timestamp
  170. this.transmitTimestamp = internals.toMsecs(buffer, 40);
  171. // Validate
  172. if (this.version === 4 &&
  173. this.stratum !== 'reserved' &&
  174. this.mode === 'server' &&
  175. this.originateTimestamp &&
  176. this.receiveTimestamp &&
  177. this.transmitTimestamp) {
  178. this.isValid = true;
  179. }
  180. return this;
  181. };
  182. internals.toMsecs = function (buffer, offset) {
  183. var seconds = 0;
  184. var fraction = 0;
  185. for (var i = 0; i < 4; ++i) {
  186. seconds = (seconds * 256) + buffer[offset + i];
  187. }
  188. for (i = 4; i < 8; ++i) {
  189. fraction = (fraction * 256) + buffer[offset + i];
  190. }
  191. return ((seconds - 2208988800 + (fraction / Math.pow(2, 32))) * 1000);
  192. };
  193. internals.fromMsecs = function (ts, buffer, offset) {
  194. var seconds = Math.floor(ts / 1000) + 2208988800;
  195. var fraction = Math.round((ts % 1000) / 1000 * Math.pow(2, 32));
  196. buffer[offset + 0] = (seconds & 0xFF000000) >> 24;
  197. buffer[offset + 1] = (seconds & 0x00FF0000) >> 16;
  198. buffer[offset + 2] = (seconds & 0x0000FF00) >> 8;
  199. buffer[offset + 3] = (seconds & 0x000000FF);
  200. buffer[offset + 4] = (fraction & 0xFF000000) >> 24;
  201. buffer[offset + 5] = (fraction & 0x00FF0000) >> 16;
  202. buffer[offset + 6] = (fraction & 0x0000FF00) >> 8;
  203. buffer[offset + 7] = (fraction & 0x000000FF);
  204. };
  205. // Offset singleton
  206. internals.last = {
  207. offset: 0,
  208. expires: 0,
  209. host: '',
  210. port: 0
  211. };
  212. exports.offset = function (options, callback) {
  213. if (arguments.length !== 2) {
  214. callback = arguments[0];
  215. options = {};
  216. }
  217. var now = Date.now();
  218. var clockSyncRefresh = options.clockSyncRefresh || 24 * 60 * 60 * 1000; // Daily
  219. if (internals.last.offset &&
  220. internals.last.host === options.host &&
  221. internals.last.port === options.port &&
  222. now < internals.last.expires) {
  223. process.nextTick(function () {
  224. callback(null, internals.last.offset);
  225. });
  226. return;
  227. }
  228. exports.time(options, function (err, time) {
  229. if (err) {
  230. return callback(err, 0);
  231. }
  232. internals.last = {
  233. offset: Math.round(time.t),
  234. expires: now + clockSyncRefresh,
  235. host: options.host,
  236. port: options.port
  237. };
  238. return callback(null, internals.last.offset);
  239. });
  240. };
  241. // Now singleton
  242. internals.now = {
  243. intervalId: 0
  244. };
  245. exports.start = function (options, callback) {
  246. if (arguments.length !== 2) {
  247. callback = arguments[0];
  248. options = {};
  249. }
  250. if (internals.now.intervalId) {
  251. process.nextTick(function () {
  252. callback();
  253. });
  254. return;
  255. }
  256. exports.offset(options, function (err, offset) {
  257. internals.now.intervalId = setInterval(function () {
  258. exports.offset(options, function () { });
  259. }, options.clockSyncRefresh || 24 * 60 * 60 * 1000); // Daily
  260. return callback();
  261. });
  262. };
  263. exports.stop = function () {
  264. if (!internals.now.intervalId) {
  265. return;
  266. }
  267. clearInterval(internals.now.intervalId);
  268. internals.now.intervalId = 0;
  269. };
  270. exports.isLive = function () {
  271. return !!internals.now.intervalId;
  272. };
  273. exports.now = function () {
  274. var now = Date.now();
  275. if (!exports.isLive() ||
  276. now >= internals.last.expires) {
  277. return now;
  278. }
  279. return now + internals.last.offset;
  280. };