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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
|
// **********************************************************************
//
// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
const net = require("net");
const Ice = require("../Ice/ModuleRegistry").Ice;
Ice._ModuleRegistry.require(module,
[
"../Ice/Debug",
"../Ice/ExUtil",
"../Ice/SocketOperation",
"../Ice/Connection",
"../Ice/Exception",
"../Ice/LocalException",
"../Ice/Timer"
]);
const Debug = Ice.Debug;
const ExUtil = Ice.ExUtil;
const Network = Ice.Network;
const SocketOperation = Ice.SocketOperation;
const LocalException = Ice.LocalException;
const SocketException = Ice.SocketException;
const Timer = Ice.Timer;
const StateNeedConnect = 0;
const StateConnectPending = 1;
const StateProxyConnectRequest = 2;
const StateProxyConnectRequestPending = 3;
const StateConnected = 4;
const StateClosed = 5;
class TcpTransceiver
{
constructor(instance)
{
this._logger = instance.logger();
this._readBuffers = [];
this._readPosition = 0;
this._maxSendPacketSize = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.SndSize", 512 * 1024);
}
setCallbacks(connectedCallback, bytesAvailableCallback, bytesWrittenCallback)
{
this._connectedCallback = connectedCallback;
this._bytesAvailableCallback = bytesAvailableCallback;
this._bytesWrittenCallback = bytesWrittenCallback;
}
//
// Returns SocketOperation.None when initialization is complete.
//
initialize(readBuffer, writeBuffer)
{
try
{
if(this._exception)
{
throw this._exception;
}
if(this._state === StateNeedConnect)
{
this._state = StateConnectPending;
this._fd = net.createConnection({port: this._addr.port,
host: this._addr.host,
localAddress: this._sourceAddr});
this._fd.on("connect", () => this.socketConnected());
this._fd.on("data", buf => this.socketBytesAvailable(buf));
//
// The error callback can be triggered from the socket
// write(). We don't want it to dispached right away
// from within the write() so we delay the call with
// setImmediate. We do the same for close as a
// precaution. See also issue #6226.
//
this._fd.on("close", err => Timer.setImmediate(() => this.socketClosed(err)));
this._fd.on("error", err => Timer.setImmediate(() => this.socketError(err)));
return SocketOperation.Connect; // Waiting for connect to complete.
}
else if(this._state === StateConnectPending)
{
//
// Socket is connected.
//
this._desc = fdToString(this._fd, this._proxy, this._addr);
this._state = StateConnected;
}
else if(this._state === StateProxyConnectRequest)
{
//
// Write completed.
//
this._proxy.endWriteConnectRequest(writeBuffer);
this._state = StateProxyConnectRequestPending; // Wait for proxy response
return SocketOperation.Read;
}
else if(this._state === StateProxyConnectRequestPending)
{
//
// Read completed.
//
this._proxy.endReadConnectRequestResponse(readBuffer);
this._state = StateConnected;
}
}
catch(err)
{
if(!this._exception)
{
this._exception = translateError(this._state, err);
}
throw this._exception;
}
Debug.assert(this._state === StateConnected);
return SocketOperation.None;
}
register()
{
this._registered = true;
this._fd.resume();
if(this._exception)
{
this._bytesAvailableCallback();
}
}
unregister()
{
if(this._fd === null)
{
Debug.assert(this._exception); // Socket creation failed.
return;
}
this._registered = false;
this._fd.pause();
}
close()
{
if(this._fd === null)
{
Debug.assert(this._exception); // Socket creation failed.
return;
}
try
{
this._fd.destroy();
}
catch(ex)
{
throw translateError(this._state, ex);
}
finally
{
this._fd = null;
}
}
//
// Returns true if all of the data was flushed to the kernel buffer.
//
write(byteBuffer)
{
if(this._exception)
{
throw this._exception;
}
let packetSize = byteBuffer.remaining;
Debug.assert(packetSize > 0);
if(this._maxSendPacketSize > 0 && packetSize > this._maxSendPacketSize)
{
packetSize = this._maxSendPacketSize;
}
while(packetSize > 0)
{
const slice = byteBuffer.b.slice(byteBuffer.position, byteBuffer.position + packetSize);
let sync = true;
/*jshint -W083 */
sync = this._fd.write(new Buffer(slice), null, () =>
{
if(!sync)
{
this._bytesWrittenCallback();
}
});
/*jshint +W083 */
byteBuffer.position = byteBuffer.position + packetSize;
if(!sync)
{
return false; // Wait for callback to be called before sending more data.
}
if(this._maxSendPacketSize > 0 && byteBuffer.remaining > this._maxSendPacketSize)
{
packetSize = this._maxSendPacketSize;
}
else
{
packetSize = byteBuffer.remaining;
}
}
return true;
}
read(byteBuffer, moreData)
{
if(this._exception)
{
throw this._exception;
}
moreData.value = false;
if(this._readBuffers.length === 0)
{
return false; // No data available.
}
let avail = this._readBuffers[0].length - this._readPosition;
Debug.assert(avail > 0);
while(byteBuffer.remaining > 0)
{
if(avail > byteBuffer.remaining)
{
avail = byteBuffer.remaining;
}
this._readBuffers[0].copy(new Buffer(byteBuffer.b), byteBuffer.position, this._readPosition,
this._readPosition + avail);
byteBuffer.position += avail;
this._readPosition += avail;
if(this._readPosition === this._readBuffers[0].length)
{
//
// We've exhausted the current read buffer.
//
this._readPosition = 0;
this._readBuffers.shift();
if(this._readBuffers.length === 0)
{
break; // No more data - we're done.
}
else
{
avail = this._readBuffers[0].length;
}
}
}
moreData.value = this._readBuffers.length > 0;
return byteBuffer.remaining === 0;
}
type()
{
return "tcp";
}
getInfo()
{
Debug.assert(this._fd !== null);
const info = new Ice.TCPConnectionInfo();
info.localAddress = this._fd.localAddress;
info.localPort = this._fd.localPort;
info.remoteAddress = this._fd.remoteAddress;
info.remotePort = this._fd.remotePort;
info.rcvSize = -1;
info.sndSize = this._maxSendPacketSize;
return info;
}
checkSendSize(stream)
{
}
setBufferSize(rcvSize, sndSize)
{
this._maxSendPacketSize = sndSize;
}
toString()
{
return this._desc;
}
socketConnected()
{
Debug.assert(this._connectedCallback !== null);
this._connectedCallback();
}
socketBytesAvailable(buf)
{
Debug.assert(this._bytesAvailableCallback !== null);
//
// TODO: Should we set a limit on how much data we can read?
// We can call _fd.pause() to temporarily stop reading.
//
if(buf.length > 0)
{
this._readBuffers.push(buf);
this._bytesAvailableCallback();
}
}
socketClosed(err)
{
//
// Don't call the closed callback if an error occurred; the error callback
// will be called.
//
if(!err)
{
this.socketError(null);
}
}
socketError(err)
{
this._exception = translateError(this._state, err);
if(this._state < StateConnected)
{
this._connectedCallback();
}
else if(this._registered)
{
this._bytesAvailableCallback();
}
}
static createOutgoing(instance, addr, sourceAddr)
{
const transceiver = new TcpTransceiver(instance);
transceiver._fd = null;
transceiver._addr = addr;
transceiver._sourceAddr = sourceAddr;
transceiver._desc = "local address = <not connected>\nremote address = " + addr.host + ":" + addr.port;
transceiver._state = StateNeedConnect;
transceiver._registered = false;
transceiver._exception = null;
return transceiver;
}
static createIncoming(instance, fd)
{
const transceiver = new TcpTransceiver(instance);
transceiver._fd = fd;
transceiver._addr = null;
transceiver._sourceAddr = null;
transceiver._desc = fdToString(fd);
transceiver._state = StateConnected;
transceiver._registered = false;
transceiver._exception = null;
return transceiver;
}
}
function fdToString(fd, targetAddr)
{
if(fd === null)
{
return "<closed>";
}
return addressesToString(fd.localAddress, fd.localPort, fd.remoteAddress, fd.remotePort, targetAddr);
}
function translateError(state, err)
{
if(!err)
{
return new Ice.ConnectionLostException();
}
else if(state < StateConnected)
{
if(connectionRefused(err.code))
{
return new Ice.ConnectionRefusedException(err.code, err);
}
else if(connectionFailed(err.code))
{
return new Ice.ConnectFailedException(err.code, err);
}
}
else if(connectionLost(err.code))
{
return new Ice.ConnectionLostException(err.code, err);
}
return new Ice.SocketException(err.code, err);
}
function addressesToString(localHost, localPort, remoteHost, remotePort, targetAddr)
{
remoteHost = remoteHost === undefined ? null : remoteHost;
targetAddr = targetAddr === undefined ? null : targetAddr;
const s = [];
s.push("local address = ");
s.push(localHost + ":" + localPort);
if(remoteHost === null && targetAddr !== null)
{
remoteHost = targetAddr.host;
remotePort = targetAddr.port;
}
if(remoteHost === null)
{
s.push("\nremote address = <not connected>");
}
else
{
s.push("\nremote address = ");
s.push(remoteHost + ":" + remotePort);
}
return s.join("");
}
const ECONNABORTED = "ECONNABORTED";
const ECONNREFUSED = "ECONNREFUSED";
const ECONNRESET = "ECONNRESET";
const EHOSTUNREACH = "EHOSTUNREACH";
const ENETUNREACH = "ENETUNREACH";
const ENOTCONN = "ENOTCONN";
const EPIPE = "EPIPE";
const ESHUTDOWN = "ESHUTDOWN";
const ETIMEDOUT = "ETIMEDOUT";
function connectionRefused(err)
{
return err == ECONNREFUSED;
}
function connectionFailed(err)
{
return err == ECONNREFUSED || err == ETIMEDOUT ||
err == ENETUNREACH || err == EHOSTUNREACH ||
err == ECONNRESET || err == ESHUTDOWN ||
err == ECONNABORTED;
}
function connectionLost(err)
{
return err == ECONNRESET || err == ENOTCONN ||
err == ESHUTDOWN || err == ECONNABORTED ||
err == EPIPE;
}
Ice.TcpTransceiver = TcpTransceiver;
module.exports.Ice = Ice;
|