-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
176 lines (154 loc) · 4.52 KB
/
Copy pathclient.ts
File metadata and controls
176 lines (154 loc) · 4.52 KB
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
import dgram from 'dgram';
import { NTPParser, ParsedNTPPacket } from './parser.js';
export interface NTPClientConfig {
host?: string;
port?: number;
timeout?: number;
fallbackServers?: string[];
}
export interface NTPQueryResult {
buffer: Buffer;
hexDump: string;
parsed: ParsedNTPPacket;
serverAddress: string;
clientReceiveTime: Date;
clientOriginateTime: Date;
usedServer?: string;
}
/**
* NTP Client - Sends NTP requests and retrieves responses
*/
export class NTPClient {
private host: string;
private port: number;
private timeout: number;
private fallbackServers: string[];
constructor(config: NTPClientConfig = {}) {
this.host = config.host || 'time.hixbe.com';
this.port = config.port || 123;
this.timeout = config.timeout || 5000;
// Default fallback servers if none provided
this.fallbackServers = config.fallbackServers || ['time.google.com', 'pool.ntp.org'];
}
/**
* Send NTP request and receive response with automatic fallback
*/
async query(): Promise<NTPQueryResult> {
const servers = [this.host, ...this.fallbackServers];
let lastError: Error | null = null;
for (const server of servers) {
try {
return await this.queryServer(server);
} catch (error) {
lastError = error as Error;
// Continue to next server
}
}
// All servers failed
throw new Error(
`NTP query failed for all servers (${servers.join(', ')}): ${lastError?.message}`
);
}
/**
* Query a specific NTP server
*/
private async queryServer(host: string): Promise<NTPQueryResult> {
return new Promise((resolve, reject) => {
const client = dgram.createSocket('udp4');
const timeoutId = setTimeout(() => {
client.close();
reject(new Error(`NTP request timeout after ${this.timeout}ms to ${host}`));
}, this.timeout);
client.on('message', (buffer, rinfo) => {
clearTimeout(timeoutId);
client.close();
try {
const clientReceiveTime = new Date();
const parsed = NTPParser.parsePacket(buffer);
resolve({
buffer,
hexDump: this.hexDump(buffer),
parsed,
serverAddress: rinfo.address,
clientReceiveTime,
clientOriginateTime: new Date(Date.now() - this.timeout / 2),
usedServer: host,
});
} catch (error) {
reject(error);
}
});
client.on('error', (error) => {
clearTimeout(timeoutId);
client.close();
reject(error);
});
// Create NTP request packet
const ntpPacket = this.createRequestPacket();
try {
client.send(ntpPacket, 0, ntpPacket.length, this.port, host, (error) => {
if (error) {
clearTimeout(timeoutId);
client.close();
reject(error);
}
});
} catch (error) {
clearTimeout(timeoutId);
client.close();
reject(error);
}
});
}
/**
* Get current NTP time from server
*/
async getTime(): Promise<Date> {
const result = await this.query();
return result.parsed.timestamps.transmit.date;
}
/**
* Get time offset between local and NTP server
*/
async getOffset(): Promise<number> {
const result = await this.query();
const serverTime = result.parsed.timestamps.transmit.date.getTime();
const localTime = result.clientReceiveTime.getTime();
return serverTime - localTime;
}
/**
* Create NTP request packet (client mode)
*/
private createRequestPacket(): Buffer {
const packet = Buffer.alloc(48, 0);
// First byte: LI (0), VN (3), Mode (3 = client)
packet[0] = 0x23;
// Add transmit timestamp (current time)
const now = new Date();
const unixSeconds = Math.floor(now.getTime() / 1000);
const ntpSeconds = unixSeconds + 2208988800;
const fraction = Math.random() * 0x100000000;
packet.writeUInt32BE(ntpSeconds, 40);
packet.writeUInt32BE(Math.floor(fraction), 44);
return packet;
}
/**
* Generate hex dump of buffer
*/
private hexDump(buffer: Buffer): string {
let dump = '';
for (let i = 0; i < buffer.length; i += 16) {
const hex = buffer
.slice(i, i + 16)
.toString('hex')
.match(/.{1,2}/g)
?.join(' ');
const ascii = buffer
.slice(i, i + 16)
.toString('ascii')
.replace(/[^\x20-\x7E]/g, '.');
dump += `${String(i).padStart(4, '0')}: ${hex?.padEnd(48)} ${ascii}\n`;
}
return dump;
}
}