node-opcua-server 2.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.mocharc.yml +10 -0
  2. package/LICENSE +20 -0
  3. package/dist/base_server.d.ts +110 -0
  4. package/dist/base_server.js +476 -0
  5. package/dist/base_server.js.map +1 -0
  6. package/dist/factory.d.ts +10 -0
  7. package/dist/factory.js +24 -0
  8. package/dist/factory.js.map +1 -0
  9. package/dist/history_server_capabilities.d.ts +35 -0
  10. package/dist/history_server_capabilities.js +44 -0
  11. package/dist/history_server_capabilities.js.map +1 -0
  12. package/dist/i_channel_data.d.ts +13 -0
  13. package/dist/i_channel_data.js +3 -0
  14. package/dist/i_channel_data.js.map +1 -0
  15. package/dist/i_register_server_manager.d.ts +16 -0
  16. package/dist/i_register_server_manager.js +3 -0
  17. package/dist/i_register_server_manager.js.map +1 -0
  18. package/dist/i_server_side_publish_engine.d.ts +36 -0
  19. package/dist/i_server_side_publish_engine.js +50 -0
  20. package/dist/i_server_side_publish_engine.js.map +1 -0
  21. package/dist/i_socket_data.d.ts +11 -0
  22. package/dist/i_socket_data.js +3 -0
  23. package/dist/i_socket_data.js.map +1 -0
  24. package/dist/index.d.ts +14 -0
  25. package/dist/index.js +27 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/monitored_item.d.ts +173 -0
  28. package/dist/monitored_item.js +1006 -0
  29. package/dist/monitored_item.js.map +1 -0
  30. package/dist/node_sampler.d.ts +3 -0
  31. package/dist/node_sampler.js +76 -0
  32. package/dist/node_sampler.js.map +1 -0
  33. package/dist/opcua_server.d.ts +668 -0
  34. package/dist/opcua_server.js +2407 -0
  35. package/dist/opcua_server.js.map +1 -0
  36. package/dist/queue.d.ts +11 -0
  37. package/dist/queue.js +71 -0
  38. package/dist/queue.js.map +1 -0
  39. package/dist/register_server_manager.d.ts +92 -0
  40. package/dist/register_server_manager.js +574 -0
  41. package/dist/register_server_manager.js.map +1 -0
  42. package/dist/register_server_manager_hidden.d.ts +17 -0
  43. package/dist/register_server_manager_hidden.js +28 -0
  44. package/dist/register_server_manager_hidden.js.map +1 -0
  45. package/dist/register_server_manager_mdns_only.d.ts +19 -0
  46. package/dist/register_server_manager_mdns_only.js +58 -0
  47. package/dist/register_server_manager_mdns_only.js.map +1 -0
  48. package/dist/server_capabilities.d.ts +61 -0
  49. package/dist/server_capabilities.js +109 -0
  50. package/dist/server_capabilities.js.map +1 -0
  51. package/dist/server_end_point.d.ts +180 -0
  52. package/dist/server_end_point.js +825 -0
  53. package/dist/server_end_point.js.map +1 -0
  54. package/dist/server_engine.d.ts +311 -0
  55. package/dist/server_engine.js +1659 -0
  56. package/dist/server_engine.js.map +1 -0
  57. package/dist/server_publish_engine.d.ts +109 -0
  58. package/dist/server_publish_engine.js +531 -0
  59. package/dist/server_publish_engine.js.map +1 -0
  60. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -0
  61. package/dist/server_publish_engine_for_orphan_subscriptions.js +50 -0
  62. package/dist/server_publish_engine_for_orphan_subscriptions.js.map +1 -0
  63. package/dist/server_session.d.ts +176 -0
  64. package/dist/server_session.js +734 -0
  65. package/dist/server_session.js.map +1 -0
  66. package/dist/server_subscription.d.ts +393 -0
  67. package/dist/server_subscription.js +1313 -0
  68. package/dist/server_subscription.js.map +1 -0
  69. package/dist/sessions_compatible_for_transfer.d.ts +2 -0
  70. package/dist/sessions_compatible_for_transfer.js +36 -0
  71. package/dist/sessions_compatible_for_transfer.js.map +1 -0
  72. package/dist/validate_filter.d.ts +5 -0
  73. package/dist/validate_filter.js +64 -0
  74. package/dist/validate_filter.js.map +1 -0
  75. package/package.json +88 -0
  76. package/source/base_server.ts +617 -0
  77. package/source/factory.ts +25 -0
  78. package/source/history_server_capabilities.ts +75 -0
  79. package/source/i_channel_data.ts +17 -0
  80. package/source/i_register_server_manager.ts +24 -0
  81. package/source/i_server_side_publish_engine.ts +77 -0
  82. package/source/i_socket_data.ts +11 -0
  83. package/source/index.ts +14 -0
  84. package/source/monitored_item.ts +1303 -0
  85. package/source/node_sampler.ts +82 -0
  86. package/source/opcua_server.ts +3742 -0
  87. package/source/queue.ts +73 -0
  88. package/source/register_server_manager.ts +744 -0
  89. package/source/register_server_manager_hidden.ts +33 -0
  90. package/source/register_server_manager_mdns_only.ts +69 -0
  91. package/source/server_capabilities.ts +177 -0
  92. package/source/server_end_point.ts +1182 -0
  93. package/source/server_engine.ts +2167 -0
  94. package/source/server_publish_engine.ts +657 -0
  95. package/source/server_publish_engine_for_orphan_subscriptions.ts +52 -0
  96. package/source/server_session.ts +931 -0
  97. package/source/server_subscription.ts +1792 -0
  98. package/source/sessions_compatible_for_transfer.ts +33 -0
  99. package/source/validate_filter.ts +86 -0
  100. package/test_helpers/create_certificates.js +1 -0
@@ -0,0 +1,825 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OPCUAServerEndPoint = void 0;
4
+ /**
5
+ * @module node-opcua-server
6
+ */
7
+ // tslint:disable:no-console
8
+ const async = require("async");
9
+ const chalk = require("chalk");
10
+ const events_1 = require("events");
11
+ const net = require("net");
12
+ const node_opcua_assert_1 = require("node-opcua-assert");
13
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
14
+ const node_opcua_debug_1 = require("node-opcua-debug");
15
+ const node_opcua_hostname_1 = require("node-opcua-hostname");
16
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
17
+ const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
18
+ const node_opcua_service_endpoints_2 = require("node-opcua-service-endpoints");
19
+ const node_opcua_service_endpoints_3 = require("node-opcua-service-endpoints");
20
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
21
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
22
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
23
+ const default_transportProfileUri = "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary";
24
+ function extractSocketData(socket, reason) {
25
+ const { bytesRead, bytesWritten, remoteAddress, remoteFamily, remotePort, localAddress, localPort } = socket;
26
+ const data = {
27
+ bytesRead,
28
+ bytesWritten,
29
+ localAddress,
30
+ localPort,
31
+ remoteAddress,
32
+ remoteFamily,
33
+ remotePort,
34
+ timestamp: new Date(),
35
+ reason
36
+ };
37
+ return data;
38
+ }
39
+ function extractChannelData(channel) {
40
+ const { channelId, clientCertificate, clientNonce, clientSecurityHeader, securityHeader, securityMode, securityPolicy, timeout, transactionsCount } = channel;
41
+ const channelData = {
42
+ channelId,
43
+ clientCertificate,
44
+ clientNonce,
45
+ clientSecurityHeader,
46
+ securityHeader,
47
+ securityMode,
48
+ securityPolicy,
49
+ timeout,
50
+ transactionsCount
51
+ };
52
+ return channelData;
53
+ }
54
+ function dumpChannelInfo(channels) {
55
+ function dumpChannel(channel) {
56
+ var _a;
57
+ console.log("------------------------------------------------------");
58
+ console.log(" channelId = ", channel.channelId);
59
+ console.log(" timeout = ", channel.timeout);
60
+ console.log(" remoteAddress = ", channel.remoteAddress);
61
+ console.log(" remotePort = ", channel.remotePort);
62
+ console.log("");
63
+ console.log(" bytesWritten = ", channel.bytesWritten);
64
+ console.log(" bytesRead = ", channel.bytesRead);
65
+ const socket = (_a = channel.transport) === null || _a === void 0 ? void 0 : _a._socket;
66
+ if (!socket) {
67
+ console.log(" SOCKET IS CLOSED");
68
+ }
69
+ }
70
+ for (const channel of channels) {
71
+ dumpChannel(channel);
72
+ }
73
+ console.log("------------------------------------------------------");
74
+ }
75
+ const emptyCertificate = Buffer.alloc(0);
76
+ const emptyPrivateKeyPEM = "";
77
+ let OPCUAServerEndPointCounter = 0;
78
+ function getUniqueName(name, collection) {
79
+ if (collection[name]) {
80
+ let counter = 0;
81
+ while (collection[name + "_" + counter.toString()]) {
82
+ counter++;
83
+ }
84
+ name = name + "_" + counter.toString();
85
+ collection[name] = 1;
86
+ return name;
87
+ }
88
+ else {
89
+ collection[name] = 1;
90
+ return name;
91
+ }
92
+ }
93
+ /**
94
+ * OPCUAServerEndPoint a Server EndPoint.
95
+ * A sever end point is listening to one port
96
+ * note:
97
+ * see OPCUA Release 1.03 part 4 page 108 7.1 ApplicationDescription
98
+ */
99
+ class OPCUAServerEndPoint extends events_1.EventEmitter {
100
+ constructor(options) {
101
+ super();
102
+ this._started = false;
103
+ this._counter = OPCUAServerEndPointCounter++;
104
+ this._policy_deduplicator = {};
105
+ (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "certificate"), "expecting a certificateChain instead");
106
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "certificateChain"), "expecting a certificateChain");
107
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "privateKey"));
108
+ this.certificateManager = options.certificateManager;
109
+ options.port = options.port || 0;
110
+ this.port = parseInt(options.port.toString(), 10);
111
+ (0, node_opcua_assert_1.assert)(typeof this.port === "number");
112
+ this._certificateChain = options.certificateChain;
113
+ this._privateKey = options.privateKey;
114
+ this._channels = {};
115
+ this.defaultSecureTokenLifetime = options.defaultSecureTokenLifetime || 600000;
116
+ this.maxConnections = options.maxConnections || 20;
117
+ this.timeout = options.timeout || 30000;
118
+ this._server = undefined;
119
+ this._setup_server();
120
+ this._endpoints = [];
121
+ this.objectFactory = options.objectFactory;
122
+ this.bytesWrittenInOldChannels = 0;
123
+ this.bytesReadInOldChannels = 0;
124
+ this.transactionsCountOldChannels = 0;
125
+ this.securityTokenCountOldChannels = 0;
126
+ this.serverInfo = options.serverInfo;
127
+ (0, node_opcua_assert_1.assert)(this.serverInfo !== null && typeof this.serverInfo === "object");
128
+ }
129
+ dispose() {
130
+ this._certificateChain = emptyCertificate;
131
+ this._privateKey = emptyPrivateKeyPEM;
132
+ (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "OPCUAServerEndPoint channels must have been deleted");
133
+ this._channels = {};
134
+ this.serverInfo = new node_opcua_service_endpoints_3.ApplicationDescription({});
135
+ this._endpoints = [];
136
+ (0, node_opcua_assert_1.assert)(this._endpoints.length === 0, "endpoints must have been deleted");
137
+ this._endpoints = [];
138
+ this._server = undefined;
139
+ this._listen_callback = null;
140
+ this.removeAllListeners();
141
+ }
142
+ toString() {
143
+ const privateKey1 = (0, node_opcua_crypto_1.convertPEMtoDER)(this.getPrivateKey());
144
+ const txt = " end point" +
145
+ this._counter +
146
+ " port = " +
147
+ this.port +
148
+ " l = " +
149
+ this._endpoints.length +
150
+ " " +
151
+ (0, node_opcua_crypto_1.makeSHA1Thumbprint)(this.getCertificateChain()).toString("hex") +
152
+ " " +
153
+ (0, node_opcua_crypto_1.makeSHA1Thumbprint)(privateKey1).toString("hex");
154
+ return txt;
155
+ }
156
+ getChannels() {
157
+ return Object.values(this._channels);
158
+ }
159
+ /**
160
+ * Returns the X509 DER form of the server certificate
161
+ */
162
+ getCertificate() {
163
+ return (0, node_opcua_crypto_1.split_der)(this.getCertificateChain())[0];
164
+ }
165
+ /**
166
+ * Returns the X509 DER form of the server certificate
167
+ */
168
+ getCertificateChain() {
169
+ return this._certificateChain;
170
+ }
171
+ /**
172
+ * the private key
173
+ */
174
+ getPrivateKey() {
175
+ return this._privateKey;
176
+ }
177
+ /**
178
+ * The number of active channel on this end point.
179
+ */
180
+ get currentChannelCount() {
181
+ return Object.keys(this._channels).length;
182
+ }
183
+ /**
184
+ * @method getEndpointDescription
185
+ * @param securityMode
186
+ * @param securityPolicy
187
+ * @return endpoint_description {EndpointDescription|null}
188
+ */
189
+ getEndpointDescription(securityMode, securityPolicy, endpointUrl) {
190
+ const endpoints = this.endpointDescriptions();
191
+ const arr = endpoints.filter(matching_endpoint.bind(this, securityMode, securityPolicy, endpointUrl));
192
+ if (endpointUrl && endpointUrl.length > 0 && !(arr.length === 0 || arr.length === 1)) {
193
+ errorLog("Several matching endpoints have been found : ");
194
+ for (const a of arr) {
195
+ errorLog(" ", a.endpointUrl, node_opcua_secure_channel_1.MessageSecurityMode[securityMode], securityPolicy);
196
+ }
197
+ }
198
+ return arr.length === 0 ? null : arr[0];
199
+ }
200
+ addEndpointDescription(securityMode, securityPolicy, options) {
201
+ if (!options) {
202
+ options = {
203
+ hostname: (0, node_opcua_hostname_1.getFullyQualifiedDomainName)(),
204
+ securityPolicies: [node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256]
205
+ };
206
+ }
207
+ options.allowAnonymous = options.allowAnonymous === undefined ? true : options.allowAnonymous;
208
+ // istanbul ignore next
209
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.None) {
210
+ throw new Error(" invalid security ");
211
+ }
212
+ // istanbul ignore next
213
+ if (securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None && securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
214
+ throw new Error(" invalid security ");
215
+ }
216
+ //
217
+ const port = this.port;
218
+ // resource Path is a string added at the end of the url such as "/UA/Server"
219
+ const resourcePath = (options.resourcePath || "").replace(/\\/g, "/");
220
+ (0, node_opcua_assert_1.assert)(resourcePath.length === 0 || resourcePath.charAt(0) === "/", "resourcePath should start with /");
221
+ const hostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
222
+ const endpointUrl = `opc.tcp://${hostname}:${port}${resourcePath}`;
223
+ const endpoint_desc = this.getEndpointDescription(securityMode, securityPolicy, endpointUrl);
224
+ // istanbul ignore next
225
+ if (endpoint_desc) {
226
+ throw new Error(" endpoint already exist");
227
+ }
228
+ // now build endpointUrl
229
+ this._endpoints.push(_makeEndpointDescription({
230
+ collection: this._policy_deduplicator,
231
+ endpointUrl,
232
+ hostname,
233
+ port,
234
+ server: this.serverInfo,
235
+ serverCertificateChain: this.getCertificateChain(),
236
+ securityMode,
237
+ securityPolicy,
238
+ allowAnonymous: options.allowAnonymous,
239
+ allowUnsecurePassword: options.allowUnsecurePassword,
240
+ resourcePath: options.resourcePath,
241
+ restricted: !!options.restricted,
242
+ securityPolicies: (options === null || options === void 0 ? void 0 : options.securityPolicies) || []
243
+ }));
244
+ }
245
+ addRestrictedEndpointDescription(options) {
246
+ options = Object.assign({}, options);
247
+ options.restricted = true;
248
+ return this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, options);
249
+ }
250
+ addStandardEndpointDescriptions(options) {
251
+ options = options || {};
252
+ options.securityModes = options.securityModes || defaultSecurityModes;
253
+ options.securityPolicies = options.securityPolicies || defaultSecurityPolicies;
254
+ const defaultHostname = options.hostname || (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
255
+ let hostnames = [defaultHostname];
256
+ options.alternateHostname = options.alternateHostname || [];
257
+ if (typeof options.alternateHostname === "string") {
258
+ options.alternateHostname = [options.alternateHostname];
259
+ }
260
+ // remove duplicates if any (uniq)
261
+ hostnames = [...new Set(hostnames.concat(options.alternateHostname))];
262
+ for (const alternateHostname of hostnames) {
263
+ const optionsE = options;
264
+ optionsE.hostname = alternateHostname;
265
+ if (options.securityModes.indexOf(node_opcua_secure_channel_1.MessageSecurityMode.None) >= 0) {
266
+ this.addEndpointDescription(node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.SecurityPolicy.None, optionsE);
267
+ }
268
+ else {
269
+ if (!options.disableDiscovery) {
270
+ this.addRestrictedEndpointDescription(optionsE);
271
+ }
272
+ }
273
+ for (const securityMode of options.securityModes) {
274
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
275
+ continue;
276
+ }
277
+ for (const securityPolicy of options.securityPolicies) {
278
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
279
+ continue;
280
+ }
281
+ this.addEndpointDescription(securityMode, securityPolicy, optionsE);
282
+ }
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * returns the list of end point descriptions.
288
+ */
289
+ endpointDescriptions() {
290
+ return this._endpoints;
291
+ }
292
+ /**
293
+ * @method listen
294
+ * @async
295
+ */
296
+ listen(callback) {
297
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
298
+ (0, node_opcua_assert_1.assert)(!this._started, "OPCUAServerEndPoint is already listening");
299
+ this._listen_callback = callback;
300
+ this._server.on("error", (err) => {
301
+ debugLog(chalk.red.bold(" error") + " port = " + this.port, err);
302
+ this._started = false;
303
+ this._end_listen(err);
304
+ });
305
+ this._server.on("listening", () => {
306
+ debugLog("server is listening");
307
+ });
308
+ this._server.listen(this.port,
309
+ /*"::",*/ (err) => {
310
+ // 'listening' listener
311
+ debugLog(chalk.green.bold("LISTENING TO PORT "), this.port, "err ", err);
312
+ (0, node_opcua_assert_1.assert)(!err, " cannot listen to port ");
313
+ this._started = true;
314
+ this._end_listen();
315
+ });
316
+ }
317
+ killClientSockets(callback) {
318
+ for (const channel of this.getChannels()) {
319
+ const hacked_channel = channel;
320
+ if (hacked_channel.transport && hacked_channel.transport._socket) {
321
+ // hacked_channel.transport._socket.close();
322
+ hacked_channel.transport._socket.destroy();
323
+ hacked_channel.transport._socket.emit("error", new Error("EPIPE"));
324
+ }
325
+ }
326
+ callback();
327
+ }
328
+ suspendConnection(callback) {
329
+ if (!this._started) {
330
+ return callback(new Error("Connection already suspended !!"));
331
+ }
332
+ // Stops the server from accepting new connections and keeps existing connections.
333
+ // (note from nodejs doc: This function is asynchronous, the server is finally closed
334
+ // when all connections are ended and the server emits a 'close' event.
335
+ // The optional callback will be called once the 'close' event occurs.
336
+ // Unlike that event, it will be called with an Error as its only argument
337
+ // if the server was not open when it was closed.
338
+ this._server.close(() => {
339
+ this._started = false;
340
+ debugLog("Connection has been closed !" + this.port);
341
+ });
342
+ this._started = false;
343
+ callback();
344
+ }
345
+ restoreConnection(callback) {
346
+ this.listen(callback);
347
+ }
348
+ abruptlyInterruptChannels() {
349
+ for (const channel of Object.values(this._channels)) {
350
+ channel.abruptlyInterrupt();
351
+ }
352
+ }
353
+ /**
354
+ * @method shutdown
355
+ * @async
356
+ */
357
+ shutdown(callback) {
358
+ debugLog("OPCUAServerEndPoint#shutdown ");
359
+ if (this._started) {
360
+ // make sure we don't accept new connection any more ...
361
+ this.suspendConnection(() => {
362
+ // shutdown all opened channels ...
363
+ const _channels = Object.values(this._channels);
364
+ async.each(_channels, (channel, callback1) => {
365
+ this.shutdown_channel(channel, callback1);
366
+ }, (err) => {
367
+ /* istanbul ignore next */
368
+ if (!(Object.keys(this._channels).length === 0)) {
369
+ errorLog(" Bad !");
370
+ }
371
+ (0, node_opcua_assert_1.assert)(Object.keys(this._channels).length === 0, "channel must have unregistered themselves");
372
+ callback(err || undefined);
373
+ });
374
+ });
375
+ }
376
+ else {
377
+ callback();
378
+ }
379
+ }
380
+ /**
381
+ * @method start
382
+ * @async
383
+ * @param callback
384
+ */
385
+ start(callback) {
386
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
387
+ this.listen(callback);
388
+ }
389
+ get bytesWritten() {
390
+ const channels = Object.values(this._channels);
391
+ return (this.bytesWrittenInOldChannels +
392
+ channels.reduce((accumulated, channel) => {
393
+ return accumulated + channel.bytesWritten;
394
+ }, 0));
395
+ }
396
+ get bytesRead() {
397
+ const channels = Object.values(this._channels);
398
+ return (this.bytesReadInOldChannels +
399
+ channels.reduce((accumulated, channel) => {
400
+ return accumulated + channel.bytesRead;
401
+ }, 0));
402
+ }
403
+ get transactionsCount() {
404
+ const channels = Object.values(this._channels);
405
+ return (this.transactionsCountOldChannels +
406
+ channels.reduce((accumulated, channel) => {
407
+ return accumulated + channel.transactionsCount;
408
+ }, 0));
409
+ }
410
+ get securityTokenCount() {
411
+ const channels = Object.values(this._channels);
412
+ return (this.securityTokenCountOldChannels +
413
+ channels.reduce((accumulated, channel) => {
414
+ return accumulated + channel.securityTokenCount;
415
+ }, 0));
416
+ }
417
+ get activeChannelCount() {
418
+ return Object.keys(this._channels).length;
419
+ }
420
+ _dump_statistics() {
421
+ const self = this;
422
+ self._server.getConnections((err, count) => {
423
+ debugLog(chalk.cyan("CONCURRENT CONNECTION = "), count);
424
+ });
425
+ debugLog(chalk.cyan("MAX CONNECTIONS = "), self._server.maxConnections);
426
+ }
427
+ _setup_server() {
428
+ (0, node_opcua_assert_1.assert)(!this._server);
429
+ this._server = net.createServer({ pauseOnConnect: true }, this._on_client_connection.bind(this));
430
+ // xx console.log(" Server with max connections ", self.maxConnections);
431
+ this._server.maxConnections = this.maxConnections + 1; // plus one extra
432
+ this._listen_callback = null;
433
+ this._server
434
+ .on("connection", (socket) => {
435
+ // istanbul ignore next
436
+ if (doDebug) {
437
+ this._dump_statistics();
438
+ debugLog("server connected with : " + socket.remoteAddress + ":" + socket.remotePort);
439
+ }
440
+ })
441
+ .on("close", () => {
442
+ debugLog("server closed : all connections have ended");
443
+ })
444
+ .on("error", (err) => {
445
+ // this could be because the port is already in use
446
+ debugLog(chalk.red.bold("server error: "), err.message);
447
+ });
448
+ }
449
+ _on_client_connection(socket) {
450
+ // a client is attempting a connection on the socket
451
+ socket.setNoDelay(true);
452
+ debugLog("OPCUAServerEndPoint#_on_client_connection", this._started);
453
+ if (!this._started) {
454
+ debugLog(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
455
+ "SERVER END POINT IS PROBABLY SHUTTING DOWN !!! - Connection is refused"));
456
+ socket.end();
457
+ return;
458
+ }
459
+ const establish_connection = () => {
460
+ const nbConnections = Object.keys(this._channels).length;
461
+ debugLog(" nbConnections ", nbConnections, " self._server.maxConnections", this._server.maxConnections, this.maxConnections);
462
+ if (nbConnections >= this.maxConnections) {
463
+ console.log(chalk.bgWhite.cyan("OPCUAServerEndPoint#_on_client_connection " +
464
+ "The maximum number of connection has been reached - Connection is refused"));
465
+ const reason = "maxConnections reached (" + this.maxConnections + ")";
466
+ const socketData = extractSocketData(socket, reason);
467
+ this.emit("connectionRefused", socketData);
468
+ socket.end();
469
+ socket.destroy();
470
+ return;
471
+ }
472
+ debugLog("OPCUAServerEndPoint._on_client_connection successful => New Channel");
473
+ const channel = new node_opcua_secure_channel_1.ServerSecureChannelLayer({
474
+ defaultSecureTokenLifetime: this.defaultSecureTokenLifetime,
475
+ // objectFactory: this.objectFactory,
476
+ parent: this,
477
+ timeout: this.timeout
478
+ });
479
+ socket.resume();
480
+ this._preregisterChannel(channel);
481
+ channel.init(socket, (err) => {
482
+ this._un_pre_registerChannel(channel);
483
+ debugLog(chalk.yellow.bold("Channel#init done"), err);
484
+ if (err) {
485
+ const reason = "openSecureChannel has Failed " + err.message;
486
+ const socketData = extractSocketData(socket, reason);
487
+ const channelData = extractChannelData(channel);
488
+ this.emit("openSecureChannelFailure", socketData, channelData);
489
+ socket.end();
490
+ socket.destroy();
491
+ }
492
+ else {
493
+ debugLog("server receiving a client connection");
494
+ this._registerChannel(channel);
495
+ }
496
+ });
497
+ channel.on("message", (message) => {
498
+ // forward
499
+ this.emit("message", message, channel, this);
500
+ });
501
+ };
502
+ // Each SecureChannel exists until it is explicitly closed or until the last token has expired and the overlap
503
+ // period has elapsed. A Server application should limit the number of SecureChannels.
504
+ // To protect against misbehaving Clients and denial of service attacks, the Server shall close the oldest
505
+ // SecureChannel that has no Session assigned before reaching the maximum number of supported SecureChannels.
506
+ this._prevent_DDOS_Attack(establish_connection);
507
+ }
508
+ _preregisterChannel(channel) {
509
+ // _preregisterChannel is used to keep track of channel for which
510
+ // that are in early stage of the hand shaking process.
511
+ // e.g HEL/ACK and OpenSecureChannel may not have been received yet
512
+ // as they will need to be interrupted when OPCUAServerEndPoint is closed
513
+ (0, node_opcua_assert_1.assert)(this._started, "OPCUAServerEndPoint must be started");
514
+ (0, node_opcua_assert_1.assert)(!this._channels.hasOwnProperty(channel.hashKey), " channel already preregistered!");
515
+ this._channels[channel.hashKey] = channel;
516
+ channel._unpreregisterChannelEvent = () => {
517
+ debugLog("Channel received an abort event during the preregistration phase");
518
+ this._un_pre_registerChannel(channel);
519
+ channel.dispose();
520
+ };
521
+ channel.on("abort", channel._unpreregisterChannelEvent);
522
+ }
523
+ _un_pre_registerChannel(channel) {
524
+ if (!this._channels[channel.hashKey]) {
525
+ debugLog("Already un preregistered ?", channel.hashKey);
526
+ return;
527
+ }
528
+ delete this._channels[channel.hashKey];
529
+ (0, node_opcua_assert_1.assert)(typeof channel._unpreregisterChannelEvent === "function");
530
+ channel.removeListener("abort", channel._unpreregisterChannelEvent);
531
+ channel._unpreregisterChannelEvent = null;
532
+ }
533
+ /**
534
+ * @method _registerChannel
535
+ * @param channel
536
+ * @private
537
+ */
538
+ _registerChannel(channel) {
539
+ if (this._started) {
540
+ debugLog(chalk.red("_registerChannel = "), "channel.hashKey = ", channel.hashKey);
541
+ (0, node_opcua_assert_1.assert)(!this._channels[channel.hashKey]);
542
+ this._channels[channel.hashKey] = channel;
543
+ /**
544
+ * @event newChannel
545
+ * @param channel
546
+ */
547
+ this.emit("newChannel", channel);
548
+ channel.on("abort", () => {
549
+ this._unregisterChannel(channel);
550
+ });
551
+ }
552
+ else {
553
+ debugLog("OPCUAServerEndPoint#_registerChannel called when end point is shutdown !");
554
+ debugLog(" -> channel will be forcefully terminated");
555
+ channel.close();
556
+ channel.dispose();
557
+ }
558
+ }
559
+ /**
560
+ * @method _unregisterChannel
561
+ * @param channel
562
+ * @private
563
+ */
564
+ _unregisterChannel(channel) {
565
+ debugLog("_un-registerChannel channel.hashKey", channel.hashKey);
566
+ if (!this._channels.hasOwnProperty(channel.hashKey)) {
567
+ return;
568
+ }
569
+ (0, node_opcua_assert_1.assert)(this._channels.hasOwnProperty(channel.hashKey), "channel is not registered");
570
+ /**
571
+ * @event closeChannel
572
+ * @param channel
573
+ */
574
+ this.emit("closeChannel", channel);
575
+ // keep trace of statistics data from old channel for our own accumulated stats.
576
+ this.bytesWrittenInOldChannels += channel.bytesWritten;
577
+ this.bytesReadInOldChannels += channel.bytesRead;
578
+ this.transactionsCountOldChannels += channel.transactionsCount;
579
+ delete this._channels[channel.hashKey];
580
+ // istanbul ignore next
581
+ if (doDebug) {
582
+ this._dump_statistics();
583
+ debugLog("un-registering channel - Count = ", this.currentChannelCount);
584
+ }
585
+ /// channel.dispose();
586
+ }
587
+ _end_listen(err) {
588
+ (0, node_opcua_assert_1.assert)(typeof this._listen_callback === "function");
589
+ this._listen_callback(err);
590
+ this._listen_callback = null;
591
+ }
592
+ /**
593
+ * shutdown_channel
594
+ * @param channel
595
+ * @param inner_callback
596
+ */
597
+ shutdown_channel(channel, inner_callback) {
598
+ (0, node_opcua_assert_1.assert)(typeof inner_callback === "function");
599
+ channel.once("close", () => {
600
+ // xx console.log(" ON CLOSED !!!!");
601
+ });
602
+ channel.close(() => {
603
+ this._unregisterChannel(channel);
604
+ setImmediate(inner_callback);
605
+ });
606
+ }
607
+ /**
608
+ * @private
609
+ */
610
+ _prevent_DDOS_Attack(establish_connection) {
611
+ const nbConnections = this.activeChannelCount;
612
+ if (nbConnections >= this.maxConnections) {
613
+ // istanbul ignore next
614
+ console.log(chalk.bgRed.white("PREVENTING DDOS ATTACK => Closing unused channels"));
615
+ const unused_channels = this.getChannels().filter((channel1) => {
616
+ return !channel1.isOpened && !channel1.hasSession;
617
+ });
618
+ if (unused_channels.length === 0) {
619
+ // all channels are in used , we cannot get any
620
+ // istanbul ignore next
621
+ console.log(" - all channel are used !!!!");
622
+ dumpChannelInfo(this.getChannels());
623
+ setImmediate(establish_connection);
624
+ return;
625
+ }
626
+ // istanbul ignore next
627
+ if (doDebug) {
628
+ console.log(" - Unused channels that can be clobbered", unused_channels.map((channel1) => channel1.hashKey).join(" "));
629
+ }
630
+ const channel = unused_channels[0];
631
+ channel.close(() => {
632
+ // istanbul ignore next
633
+ if (doDebug) {
634
+ console.log(" _ Unused channel has been closed ", channel.hashKey);
635
+ }
636
+ this._unregisterChannel(channel);
637
+ establish_connection();
638
+ });
639
+ }
640
+ else {
641
+ setImmediate(establish_connection);
642
+ }
643
+ }
644
+ }
645
+ exports.OPCUAServerEndPoint = OPCUAServerEndPoint;
646
+ function estimateSecurityLevel(securityMode, securityPolicy) {
647
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
648
+ return 1;
649
+ }
650
+ let offset = 100;
651
+ if (securityMode === node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt) {
652
+ offset = 200;
653
+ }
654
+ switch (securityPolicy) {
655
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic128:
656
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15:
657
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic192:
658
+ return 2; // deprecated => low
659
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic192Rsa15:
660
+ return 3; // deprecated => low
661
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256:
662
+ return 4; // deprecated => low
663
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256Rsa15:
664
+ return 4 + offset;
665
+ case node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256:
666
+ return 6 + offset;
667
+ case node_opcua_secure_channel_1.SecurityPolicy.Aes128_Sha256_RsaOaep:
668
+ return 1;
669
+ default:
670
+ case node_opcua_secure_channel_1.SecurityPolicy.None:
671
+ return 1;
672
+ }
673
+ }
674
+ /**
675
+ * @private
676
+ */
677
+ function _makeEndpointDescription(options) {
678
+ (0, node_opcua_assert_1.assert)(isFinite(options.port), "expecting a valid port number");
679
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(options, "serverCertificateChain"));
680
+ (0, node_opcua_assert_1.assert)(!Object.prototype.hasOwnProperty.call(options, "serverCertificate"));
681
+ (0, node_opcua_assert_1.assert)(!!options.securityMode); // s.MessageSecurityMode
682
+ (0, node_opcua_assert_1.assert)(!!options.securityPolicy);
683
+ (0, node_opcua_assert_1.assert)(options.server !== null && typeof options.server === "object");
684
+ (0, node_opcua_assert_1.assert)(!!options.hostname && typeof options.hostname === "string");
685
+ (0, node_opcua_assert_1.assert)(typeof options.restricted === "boolean");
686
+ const u = (n) => getUniqueName(n, options.collection);
687
+ options.securityLevel =
688
+ options.securityLevel === undefined
689
+ ? estimateSecurityLevel(options.securityMode, options.securityPolicy)
690
+ : options.securityLevel;
691
+ (0, node_opcua_assert_1.assert)(isFinite(options.securityLevel), "expecting a valid securityLevel");
692
+ const securityPolicyUri = (0, node_opcua_secure_channel_1.toURI)(options.securityPolicy);
693
+ const userIdentityTokens = [];
694
+ if (options.securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
695
+ if (options.allowUnsecurePassword) {
696
+ userIdentityTokens.push({
697
+ policyId: u("username_unsecure"),
698
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
699
+ issuedTokenType: null,
700
+ issuerEndpointUrl: null,
701
+ securityPolicyUri: null
702
+ });
703
+ }
704
+ const onlyCertificateLessConnection = options.onlyCertificateLessConnection === undefined ? false : options.onlyCertificateLessConnection;
705
+ if (!onlyCertificateLessConnection) {
706
+ if (options.securityPolicies.indexOf(node_opcua_secure_channel_1.SecurityPolicy.Basic256) >= 0) {
707
+ userIdentityTokens.push({
708
+ policyId: u("username_basic256"),
709
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
710
+ issuedTokenType: null,
711
+ issuerEndpointUrl: null,
712
+ securityPolicyUri: node_opcua_secure_channel_1.SecurityPolicy.Basic256
713
+ });
714
+ }
715
+ if (options.securityPolicies.indexOf(node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15) >= 0) {
716
+ userIdentityTokens.push({
717
+ policyId: u("username_basic128Rsa15"),
718
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
719
+ issuedTokenType: null,
720
+ issuerEndpointUrl: null,
721
+ securityPolicyUri: node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15
722
+ });
723
+ }
724
+ if (options.securityPolicies.indexOf(node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256) >= 0) {
725
+ userIdentityTokens.push({
726
+ policyId: u("username_basic256Sha256"),
727
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
728
+ issuedTokenType: null,
729
+ issuerEndpointUrl: null,
730
+ securityPolicyUri: node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256
731
+ });
732
+ }
733
+ // X509
734
+ if (options.securityPolicies.indexOf(node_opcua_secure_channel_1.SecurityPolicy.Basic256) >= 0) {
735
+ userIdentityTokens.push({
736
+ policyId: u("certificate_basic256"),
737
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
738
+ issuedTokenType: null,
739
+ issuerEndpointUrl: null,
740
+ securityPolicyUri: node_opcua_secure_channel_1.SecurityPolicy.Basic256
741
+ });
742
+ }
743
+ // Certificate
744
+ if (options.securityPolicies.indexOf(node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256) >= 0) {
745
+ userIdentityTokens.push({
746
+ policyId: u("certificate_basic256Sha256"),
747
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.Certificate,
748
+ issuedTokenType: null,
749
+ issuerEndpointUrl: null,
750
+ securityPolicyUri: node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256
751
+ });
752
+ }
753
+ }
754
+ }
755
+ else {
756
+ // note:
757
+ // when channel session security is not "None",
758
+ // userIdentityTokens can be left to null.
759
+ // in this case this mean that secure policy will be the same as connection security policy
760
+ userIdentityTokens.push({
761
+ policyId: u("usernamePassword"),
762
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.UserName,
763
+ issuedTokenType: null,
764
+ issuerEndpointUrl: null,
765
+ securityPolicyUri: null
766
+ });
767
+ userIdentityTokens.push({
768
+ policyId: u("certificateX509"),
769
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.Certificate,
770
+ issuedTokenType: null,
771
+ issuerEndpointUrl: null,
772
+ securityPolicyUri: null
773
+ });
774
+ }
775
+ if (options.allowAnonymous) {
776
+ userIdentityTokens.push({
777
+ policyId: u("anonymous"),
778
+ tokenType: node_opcua_service_endpoints_1.UserTokenType.Anonymous,
779
+ issuedTokenType: null,
780
+ issuerEndpointUrl: null,
781
+ securityPolicyUri: null
782
+ });
783
+ }
784
+ // return the endpoint object
785
+ const endpoint = new node_opcua_service_endpoints_2.EndpointDescription({
786
+ endpointUrl: options.endpointUrl,
787
+ server: undefined,
788
+ serverCertificate: options.serverCertificateChain,
789
+ securityMode: options.securityMode,
790
+ securityPolicyUri,
791
+ userIdentityTokens,
792
+ securityLevel: options.securityLevel,
793
+ transportProfileUri: default_transportProfileUri
794
+ });
795
+ endpoint.__defineGetter__("endpointUrl", () => {
796
+ return (0, node_opcua_hostname_1.resolveFullyQualifiedDomainName)(options.endpointUrl);
797
+ });
798
+ endpoint.server = options.server;
799
+ endpoint.restricted = options.restricted;
800
+ return endpoint;
801
+ }
802
+ /**
803
+ * return true if the end point matches security mode and policy
804
+ * @param endpoint
805
+ * @param securityMode
806
+ * @param securityPolicy
807
+ * @internal
808
+ *
809
+ */
810
+ function matching_endpoint(securityMode, securityPolicy, endpointUrl, endpoint) {
811
+ (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_service_endpoints_2.EndpointDescription);
812
+ const endpoint_securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(endpoint.securityPolicyUri);
813
+ if (endpointUrl && endpoint.endpointUrl !== endpointUrl) {
814
+ return false;
815
+ }
816
+ return endpoint.securityMode === securityMode && endpoint_securityPolicy === securityPolicy;
817
+ }
818
+ const defaultSecurityModes = [node_opcua_secure_channel_1.MessageSecurityMode.None, node_opcua_secure_channel_1.MessageSecurityMode.Sign, node_opcua_secure_channel_1.MessageSecurityMode.SignAndEncrypt];
819
+ const defaultSecurityPolicies = [
820
+ node_opcua_secure_channel_1.SecurityPolicy.Basic128Rsa15,
821
+ node_opcua_secure_channel_1.SecurityPolicy.Basic256,
822
+ // xx UNUSED!! SecurityPolicy.Basic256Rsa15,
823
+ node_opcua_secure_channel_1.SecurityPolicy.Basic256Sha256
824
+ ];
825
+ //# sourceMappingURL=server_end_point.js.map