node-opcua-server 2.98.0 → 2.98.2

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