-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal.js
276 lines (267 loc) · 8.92 KB
/
local.js
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
const net = require('net');
const EventEmitter = require('events');
const mdns = require('multicast-dns')();
const crypto = require('crypto');
const frame = require('./frame.js');
const os = require('os');
const message = require('./msg.js');
const { AirId } = require("./util.js")
const util = require("./util.js")
const frameSize = util.c.FRAME_SIZE;
const VERSION = util.c.VERSION;
class Socket {
constructor(ip, port) {
this.isConnected = false;
this.ip = ip;
this.port = port;
this.socket = net.createConnection({ port: this.port, host: this.ip }, () => {
//console.log('socket connected to server!');
this.isConnected = true;
})
this.socket.setNoDelay(true);
this.socket.on('end', () => {
this.isConnected = false;
})
this.socket.on('error', (err) => {
console.error(err);
this.isConnected = false;
})
this.socket.on('close', () => {
this.isConnected = false;
})
}
send(msg) {
this.socket.write(msg);
}
end() {
this.socket.end();
}
}
class Local extends EventEmitter {
isInit = false
_server = null
airId = null
_processMdnsRecord(record) {
var data = {};
record.data.forEach((rec) => {
var r = Buffer.from(rec).toString().split('=');
data[r[0].trim()] = r[1].trim();
})
if (data.uid && data.host && data.sessionId && data.ver == VERSION) {
var resAirId = new AirId(data.uid, data.host, data.sessionId);
//console.log('Local peer', resAirId)
this.emit('localPeerFound', { airId: resAirId, appName: this.appName, deviceName: data.deviceName });
}
}
start(ipAddr) {
this._server = net.createServer(this._handleConnection);
this._server.on('error', (err) => {
console.error(err);
});
this._server.listen(() => {
//console.log('server listening', this._server.listening);
this.airId.sessionId = ipAddr + '#' + this._server.address().port;
mdns.on('response', (response) => {
response.answers.forEach(ans => {
//console.log('mdns ans',ans)
if (ans.name === this.appName + '.air.local' && ans.type == 'TXT') {
this._processMdnsRecord(ans)
}
});
})
mdns.on('query', (query) => {
if (query.questions[0] && query.questions[0].name === this.appName + '.air.local' && query.questions[0].type == 'TXT') {
if (query.questions[0].data)
this._processMdnsRecord(query.questions[0])
this.broadcast();
}
})
this.query();
});
}
stop() {
if (this._server) {
this._server.close();
this.airId.sessionId = null;
}
}
set ipAddr(ip) {
if (this._server)
this.stop();
this.start(ip)
}
get ipAddr() {
return this.airId.ipAddr
}
constructor(appName, deviceName, uid, host, ipAddr) {
super();
this.appName = appName;
this.deviceName = deviceName;
this.airId = new AirId(uid, host)
this.start(ipAddr);
this.isInit = true;
}
get _mdnsRec() {
return [
'ver=' + VERSION,
'uid=' + this.airId.uid,
'host=' + this.airId.host,
'sessionId=' + this.airId.sessionId,
'deviceName=' + this.deviceName
]
}
query() {
console.log('sending query')
mdns.query({
questions: [{
name: this.appName + '.air.local',
type: 'TXT',
data: this._mdnsRec
}]
})
}
broadcast() {
console.log('broadcasting..')
if (this._server)
mdns.respond({
answers: [{
name: this.appName + '.air.local',
type: 'TXT',
data: this._mdnsRec
}]
})
}
_handleConnection = (socket) => {
/////////////////////////////
var address = socket.remoteAddress;
var port = socket.remotePort;
if (net.isIPv6(address)) {
address = address.split('::ffff:')[1];
}
console.log('client connected', address + ':' + port);
var roaming = null;
var ongoing = null;
var done = (key, m) => {
socket.end();
if (m.from == undefined && m.uid && m.host && m.sessionid) {
var airId = new AirId(m.uid, m.host, m.sessionid);
//console.log('AIRID',airId,m)
}
else {
var airId = new AirId(m.from);
}
if (airId.isLocal) {
if (m.type == 'request') {
//console.log('req from local client', m);
this.emit('request', { key, message: m });
}
else if (m.type == 'response') {
//console.log('res from local client', m);
this.emit('response', { key, message: m });
}
}
else {
console.log("got a msg from global address in local server", address + ':' + port, m.type, m.from, m.body.length);
}
}
//console.log('client connected', address + ':' + port);
socket.on('end', () => {
//console.log('client disconnected');
});
socket.on('data', (msg) => {
var feed = msg;
if (roaming != null) {
feed = Buffer.concat([roaming, msg]);
}
const parsedFrame = frame.parse(feed);
roaming = parsedFrame.roaming;
parsedFrame.chunks.forEach((chunk) => {
var key = chunk.key;
var fin = chunk.fin;
var data = chunk.data;
if (ongoing != null) {
var stream = ongoing.data;
ongoing.count++;
console.log("storing chunk", ongoing.count, ' size: ' + data.length);
ongoing.data = Buffer.concat([stream, data]);
if (fin) {
var m = message.parse(ongoing.data);
done(key, m);
ongoing = null;
}
else {
//now is a good time to emit events for partial data receiving
}
}
else {
if (fin) {
var m = message.parse(data);
done(key, m);
}
else {
//more chunks r supposed to arrive, for reference store this chunk in ongoing
ongoing = { data, count: 1 };
}
}
})
});
}
_sendFrame(key, msg, ip, port) {
//console.log('sending frame', msg.toString(), ip, port)
var offset = 0;
var last = msg.length - 1;
var end = 0;
var chunk;
var fin = false;
var count = 0;
var socket = new Socket(ip, port);
const send = () => {
if (offset < last) {
end = offset + frameSize - 50;//
if (end > last) {
end = last;
}
chunk = msg.slice(offset, end);
fin = false;
if (end == last) {
fin = true;
}
var frm = frame.build(fin, key, chunk);
count++;
console.log("sending chunk", count, frm.length);
socket.send(frm, port, ip);
offset = end;
}
else
console.error('local: offset > last', offset, last);
}
const schedule = () => {
if (!fin) {
//console.log('SCHEDULING..');
send();
schedule();
}
}
if (msg.length > frameSize) {
//size too large to be sent together, break them up!
send();
if (!fin) {
schedule();
}
socket.end();
console.log('Message sent!');
}
else {
//msg can be sent at once
socket.send(frame.build(true, key, msg));
socket.end();
}
}
request(to, key, body = null) {
this._sendFrame(key, message.build({ type: 'request', to, from: this.airId, body }), to.ipAddr, to.port);
}
reply(to, key, status = 200, body = null) {
this._sendFrame(key, message.build({ type: 'response', to, from: this.airId, status, body }), to.ipAddr, to.port);
}
}
module.exports = Local;