-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathutils.js
More file actions
307 lines (253 loc) · 8.39 KB
/
Copy pathutils.js
File metadata and controls
307 lines (253 loc) · 8.39 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/**
* Protocol primitives for node-zklib.
*
* Contains: checksum, header (de)serialization for both TCP and UDP framings,
* comm-key derivation (makeCommKey), and the fixed-width record decoders
* (decodeUserData*, decodeRecordData*, decodeRecordRealTimeLog*) that parse
* the device's binary reply payloads.
*
* Wire-format reference:
* https://github.com/adrobinoga/zk-protocol/blob/master/protocol.md
*/
const { USHRT_MAX, COMMANDS, PROTOCOL, AUTH } = require('./constants')
const { log } = require('./helpers/errorLog')
const parseTimeToDate = (time)=>{
const second = time % 60;
time = (time - second) / 60;
const minute = time % 60;
time = (time - minute) / 60;
const hour = time % 24;
time = (time - hour) / 24;
const day = time % 31 + 1;
time = (time - (day - 1)) / 31;
const month = time % 12;
time = (time - month) / 12;
const year = time + 2000;
return new Date(year, month, day, hour, minute, second);
}
const parseHexToTime = (hex)=>{
const time = {
year: hex.readUIntLE(0,1),
month:hex.readUIntLE(1,1),
date: hex.readUIntLE(2,1),
hour: hex.readUIntLE(3,1),
minute: hex.readUIntLE(4,1),
second: hex.readUIntLE(5,1)
}
return new Date(2000+ time.year, time.month - 1 , time.date, time.hour, time.minute, time.second)
}
const createChkSum = (buf)=>{
let chksum = 0;
for (let i = 0; i < buf.length; i += 2) {
if (i == buf.length - 1) {
chksum += buf[i];
} else {
chksum += buf.readUInt16LE(i);
}
chksum %= USHRT_MAX;
}
chksum = USHRT_MAX - chksum - 1;
return chksum;
}
module.exports.createUDPHeader = (command , sessionId, replyId, data)=>{
const dataBuffer = Buffer.from(data);
const buf = Buffer.alloc(8 + dataBuffer.length);
buf.writeUInt16LE(command, 0);
buf.writeUInt16LE(0, 2);
buf.writeUInt16LE(sessionId, 4);
buf.writeUInt16LE(replyId, 6);
dataBuffer.copy(buf, 8);
const chksum2 = createChkSum(buf);
buf.writeUInt16LE(chksum2, 2);
replyId = (replyId + 1) % USHRT_MAX;
buf.writeUInt16LE(replyId, 6);
return buf
}
module.exports.createTCPHeader = (command , sessionId, replyId, data)=>{
const dataBuffer = Buffer.from(data);
const buf = Buffer.alloc(8 + dataBuffer.length);
buf.writeUInt16LE(command, 0);
buf.writeUInt16LE(0, 2);
buf.writeUInt16LE(sessionId, 4);
buf.writeUInt16LE(replyId, 6);
dataBuffer.copy(buf, 8);
const chksum2 = createChkSum(buf);
buf.writeUInt16LE(chksum2, 2);
replyId = (replyId + 1) % USHRT_MAX;
buf.writeUInt16LE(replyId, 6);
// Frame: <magic 4B> <0x13 fixed byte> <reserved 1B> <payloadLen 2B LE>
// The 0x13 byte is a fixed protocol constant required by the device.
const prefixBuf = Buffer.concat([
PROTOCOL.TCP_MAGIC_PREFIX,
Buffer.from([0x13, 0x00, 0x00, 0x00]),
])
prefixBuf.writeUInt16LE(buf.length, 4)
return Buffer.concat([prefixBuf, buf]);
}
const removeTcpHeader = (buf)=>{
if (buf.length < PROTOCOL.TCP_PREFIX_LEN) {
return buf;
}
// If the magic prefix isn't present, the buffer wasn't TCP-framed — leave it alone.
if (buf.compare(PROTOCOL.TCP_MAGIC_PREFIX, 0, 4, 0, 4) !== 0) {
return buf;
}
return buf.slice(PROTOCOL.TCP_PREFIX_LEN);
}
module.exports.removeTcpHeader = removeTcpHeader
module.exports.decodeUserData28 = (userData)=>{
const user = {
uid: userData.readUIntLE(0, 2),
role: userData.readUIntLE(2, 1),
name: userData
.slice(8,8+8)
.toString('ascii')
.split('\0')
.shift(),
userId: userData.readUIntLE(24,4)
};
return user;
}
module.exports.decodeUserData72 = (userData)=>{
const user = {
uid: userData.readUIntLE(0, 2),
role: userData.readUIntLE(2, 1),
password: userData
.subarray(3, 3+8)
.toString('ascii')
.split('\0')
.shift(),
name: userData
.slice(11)
.toString('ascii')
.split('\0')
.shift(),
cardno: userData.readUIntLE(35,4),
userId: userData
.slice(48, 48+9)
.toString('ascii')
.split('\0')
.shift(),
};
return user;
}
module.exports.decodeRecordData40 = (recordData)=>{
const record = {
userSn: recordData.readUIntLE(0, 2),
deviceUserId: recordData
.slice(2, 2+9)
.toString('ascii')
.split('\0')
.shift(),
recordTime: parseTimeToDate(recordData.readUInt32LE(27)),
}
return record
}
module.exports.decodeRecordData16 = (recordData)=>{
const record = {
deviceUserId: recordData.readUIntLE(0, 2),
recordTime: parseTimeToDate(recordData.readUInt32LE(4))
}
return record
}
module.exports.decodeRecordRealTimeLog18 = (recordData)=>{
const userId = recordData.readUIntLE(8,1)
const attTime = parseHexToTime(recordData.subarray(12,18))
return {userId , attTime}
}
module.exports.decodeRecordRealTimeLog52 =(recordData)=>{
const payload = removeTcpHeader(recordData)
const recvData = payload.subarray(8)
const userId = recvData.slice(0 , 9)
.toString('ascii')
.split('\0')
.shift()
const attTime = parseHexToTime(recvData.subarray(26,26+6))
return { userId, attTime}
}
// Header layout (8 bytes, little-endian):
// 0..1 commandId
// 2..3 checksum
// 4..5 sessionId
// 6..7 replyId
const decodeUDPHeader = (header) => {
const commandId = header.readUIntLE(0, 2)
const checkSum = header.readUIntLE(2, 2)
const sessionId = header.readUIntLE(4, 2)
const replyId = header.readUIntLE(6, 2)
return { commandId, checkSum, sessionId, replyId }
}
module.exports.decodeUDPHeader = decodeUDPHeader
module.exports.decodeTCPHeader = (header) => {
const recvData = header.subarray(PROTOCOL.TCP_PREFIX_LEN)
const payloadSize = header.readUIntLE(4,2)
const commandId = recvData.readUIntLE(0,2)
const checkSum = recvData.readUIntLE(2,2)
const sessionId = recvData.readUIntLE(4,2)
const replyId = recvData.readUIntLE(6,2)
return { commandId , checkSum , sessionId , replyId , payloadSize }
}
module.exports.exportErrorMessage = (commandValue)=>{
const keys = Object.keys(COMMANDS)
for(let i =0 ; i< keys.length; i++){
if (COMMANDS[keys[i]] === commandValue){
return keys[i].toString()
}
}
return 'AN UNKNOWN ERROR'
}
// True when the packet is an unsolicited real-time attendance event.
// Mirror of isEventPacketUDP but on TCP frames; checks both the command and
// the event flag because TCP frames carry a wider envelope.
module.exports.isEventPacketTCP = (data) => {
try {
data = removeTcpHeader(data)
const commandId = data.readUIntLE(0, 2)
const event = data.readUIntLE(4, 2)
return event === COMMANDS.EF_ATTLOG && commandId === COMMANDS.CMD_REG_EVENT
} catch (err) {
log(`[isEventPacketTCP] ${err.toString()} ${data.toString('hex')}`)
return false
}
}
// True when the packet is an unsolicited real-time event (CMD_REG_EVENT) rather
// than a reply to our last request. Used to skip event packets while waiting on
// a data reply — they would otherwise be parsed as part of the data stream.
module.exports.isEventPacketUDP = (data) => {
const commandId = decodeUDPHeader(data.subarray(0, PROTOCOL.ZK_HEADER_LEN)).commandId
return commandId === COMMANDS.CMD_REG_EVENT
}
module.exports.makeCommKey = (key, sessionId, ticks = AUTH.COMM_KEY_TICKS) => {
// Ensure key and sessionId are integers
key = Math.floor(key);
sessionId = Math.floor(sessionId);
let k = 0;
// Reverse the bits of 'key'
for (let i = 0; i < 32; i++) {
if (key & (1 << i)) {
k = (k << 1) | 1;
} else {
k = k << 1;
}
}
// Add sessionId
k += sessionId;
// Convert to 4-byte buffer (Little Endian)
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setUint32(0, k, true);
let bytes = new Uint8Array(buffer);
// XOR with 'ZKSO'
const xorKey = AUTH.COMM_KEY_XOR.map(c => c.charCodeAt(0));
bytes = bytes.map((b, i) => b ^ xorKey[i]);
// Swap 16-bit pairs
const swapped = new Uint8Array([bytes[2], bytes[3], bytes[0], bytes[1]]);
// Apply 'ticks' XOR transformation
const B = ticks & 0xff;
return [
swapped[0] ^ B,
swapped[1] ^ B,
B,
swapped[3] ^ B
];
}