/
opcua_server.ts
3882 lines (3404 loc) · 159 KB
/
opcua_server.ts
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable complexity */
/**
* @module node-opcua-server
*/
// tslint:disable:no-console
// tslint:disable:max-line-length
// tslint:disable:unified-signatures
import { randomBytes } from "crypto";
import { EventEmitter } from "events";
import { callbackify, types } from "util";
import * as async from "async";
import chalk from "chalk";
import { extractFullyQualifiedDomainName, getFullyQualifiedDomainName } from "node-opcua-hostname";
import { assert } from "node-opcua-assert";
import * as utils from "node-opcua-utils";
import {
AddressSpace,
PseudoVariantBoolean,
PseudoVariantByteString,
PseudoVariantDateTime,
PseudoVariantDuration,
PseudoVariantExtensionObject,
PseudoVariantExtensionObjectArray,
PseudoVariantLocalizedText,
PseudoVariantNodeId,
PseudoVariantString,
RaiseEventData,
SessionContext,
UAObject,
UAVariable,
ISessionContext,
UAView,
EventTypeLike,
UAObjectType,
PseudoVariantStringPredefined,
innerBrowse,
innerBrowseNext
} from "node-opcua-address-space";
import { getDefaultCertificateManager, OPCUACertificateManager } from "node-opcua-certificate-manager";
import { ServerState } from "node-opcua-common";
import { Certificate, exploreCertificate, Nonce } from "node-opcua-crypto";
import {
AttributeIds,
filterDiagnosticOperationLevel,
filterDiagnosticServiceLevel,
NodeClass,
RESPONSE_DIAGNOSTICS_MASK_ALL
} from "node-opcua-data-model";
import { DataValue } from "node-opcua-data-value";
import { dump, make_debugLog, make_errorLog, make_warningLog } from "node-opcua-debug";
import { NodeId } from "node-opcua-nodeid";
import { ObjectRegistry } from "node-opcua-object-registry";
import {
AsymmetricAlgorithmSecurityHeader,
computeSignature,
fromURI,
getCryptoFactory,
Message,
MessageSecurityMode,
nonceAlreadyBeenUsed,
Request,
Response,
SecurityPolicy,
ServerSecureChannelLayer,
SignatureData,
verifySignature
} from "node-opcua-secure-channel";
import { BrowseNextRequest, BrowseNextResponse, BrowseRequest, BrowseResponse } from "node-opcua-service-browse";
import { CallRequest, CallResponse } from "node-opcua-service-call";
import { ApplicationType, UserTokenType } from "node-opcua-service-endpoints";
import { HistoryReadRequest, HistoryReadResponse, HistoryReadResult, HistoryUpdateResponse } from "node-opcua-service-history";
import {
AddNodesResponse,
AddReferencesResponse,
DeleteNodesResponse,
DeleteReferencesResponse
} from "node-opcua-service-node-management";
import { QueryFirstResponse, QueryNextResponse } from "node-opcua-service-query";
import { ReadRequest, ReadResponse, ReadValueId, TimestampsToReturn } from "node-opcua-service-read";
import {
RegisterNodesRequest,
RegisterNodesResponse,
UnregisterNodesRequest,
UnregisterNodesResponse
} from "node-opcua-service-register-node";
import {
ActivateSessionRequest,
ActivateSessionResponse,
AnonymousIdentityToken,
CloseSessionRequest,
CloseSessionResponse,
CreateSessionRequest,
CreateSessionResponse,
UserNameIdentityToken,
X509IdentityToken
} from "node-opcua-service-session";
import {
CreateMonitoredItemsRequest,
CreateMonitoredItemsResponse,
CreateSubscriptionRequest,
CreateSubscriptionResponse,
DeleteMonitoredItemsRequest,
DeleteMonitoredItemsResponse,
DeleteSubscriptionsRequest,
DeleteSubscriptionsResponse,
ModifyMonitoredItemsRequest,
ModifyMonitoredItemsResponse,
ModifySubscriptionRequest,
ModifySubscriptionResponse,
MonitoredItemModifyResult,
PublishRequest,
PublishResponse,
RepublishRequest,
RepublishResponse,
SetMonitoringModeRequest,
SetMonitoringModeResponse,
SetPublishingModeRequest,
SetPublishingModeResponse,
SetTriggeringRequest,
SetTriggeringResponse,
TransferSubscriptionsRequest,
TransferSubscriptionsResponse
} from "node-opcua-service-subscription";
import {
TranslateBrowsePathsToNodeIdsRequest,
TranslateBrowsePathsToNodeIdsResponse
} from "node-opcua-service-translate-browse-path";
import { WriteRequest, WriteResponse } from "node-opcua-service-write";
import { CallbackT, ErrorCallback, StatusCode, StatusCodes } from "node-opcua-status-code";
import {
ApplicationDescriptionOptions,
BrowseResult,
BuildInfo,
CallMethodResultOptions,
CancelResponse,
EndpointDescription,
MonitoredItemModifyRequest,
MonitoringMode,
UserIdentityToken,
UserTokenPolicy,
BuildInfoOptions,
MonitoredItemCreateResult,
IssuedIdentityToken,
BrowseResultOptions,
ServiceFault,
ServerDiagnosticsSummaryDataType,
BrowseDescriptionOptions
} from "node-opcua-types";
import { DataType } from "node-opcua-variant";
import { VariantArrayType } from "node-opcua-variant";
import { matchUri } from "node-opcua-utils";
import { UAString } from "node-opcua-basic-types";
import { ObjectIds, ObjectTypeIds } from "node-opcua-constants";
import { OPCUABaseServer, OPCUABaseServerOptions } from "./base_server";
import { Factory } from "./factory";
import { IRegisterServerManager } from "./i_register_server_manager";
import { MonitoredItem } from "./monitored_item";
import { RegisterServerManager } from "./register_server_manager";
import { RegisterServerManagerHidden } from "./register_server_manager_hidden";
import { RegisterServerManagerMDNSONLY } from "./register_server_manager_mdns_only";
import { ServerCapabilitiesOptions } from "./server_capabilities";
import { EndpointDescriptionEx, OPCUAServerEndPoint } from "./server_end_point";
import { ClosingReason, CreateSessionOption, ServerEngine } from "./server_engine";
import { ServerSession } from "./server_session";
import { CreateMonitoredItemHook, DeleteMonitoredItemHook, Subscription } from "./server_subscription";
import { ISocketData } from "./i_socket_data";
import { IChannelData } from "./i_channel_data";
import { UAUserManagerBase, makeUserManager, UserManagerOptions } from "./user_manager";
import { bindRoleSet } from "./user_manager_ua";
import { SamplingFunc } from "./sampling_func";
function isSubscriptionIdInvalid(subscriptionId: number): boolean {
return subscriptionId < 0 || subscriptionId >= 0xffffffff;
}
// tslint:disable-next-line:no-var-requires
const thenify = require("thenify");
// tslint:disable-next-line:no-var-requires
const package_info = require("../package.json");
const debugLog = make_debugLog(__filename);
const errorLog = make_errorLog(__filename);
const warningLog = make_warningLog(__filename);
const default_maxConnectionsPerEndpoint = 10;
function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
const response = new ServiceFault({
responseHeader: { serviceResult: statusCode }
});
return channel.send_response("MSG", response, message);
}
const default_build_info: BuildInfoOptions = {
manufacturerName: "NodeOPCUA : MIT Licence ( see http://node-opcua.github.io/)",
productName: "NodeOPCUA-Server",
productUri: null, // << should be same as default_server_info.productUri?
softwareVersion: package_info.version,
buildNumber: "0",
buildDate: new Date(2020, 1, 1)
// xx buildDate: fs.statSync(package_json_file).mtime
};
const minSessionTimeout = 100; // 100 milliseconds
const defaultSessionTimeout = 1000 * 30; // 30 seconds
const maxSessionTimeout = 1000 * 60 * 50; // 50 minutes
let unnamed_session_count = 0;
type ResponseClassType =
| typeof BrowseResponse
| typeof BrowseNextResponse
| typeof CallResponse
| typeof CreateMonitoredItemsResponse
| typeof CreateSubscriptionResponse
| typeof DeleteSubscriptionsResponse
| typeof HistoryReadResponse
| typeof ModifyMonitoredItemsResponse
| typeof ModifySubscriptionResponse
| typeof ReadResponse
| typeof RegisterNodesResponse
| typeof RepublishResponse
| typeof SetPublishingModeResponse
| typeof SetTriggeringResponse
| typeof TransferSubscriptionsResponse
| typeof TranslateBrowsePathsToNodeIdsResponse
| typeof UnregisterNodesResponse
| typeof WriteResponse;
function _adjust_session_timeout(sessionTimeout: number) {
let revisedSessionTimeout = sessionTimeout || defaultSessionTimeout;
revisedSessionTimeout = Math.min(revisedSessionTimeout, maxSessionTimeout);
revisedSessionTimeout = Math.max(revisedSessionTimeout, minSessionTimeout);
return revisedSessionTimeout;
}
function channel_has_session(channel: ServerSecureChannelLayer, session: ServerSession): boolean {
if (session.channel === channel) {
assert(Object.prototype.hasOwnProperty.call(channel.sessionTokens, session.authenticationToken.toString()));
return true;
}
return false;
}
function moveSessionToChannel(session: ServerSession, channel: ServerSecureChannelLayer) {
debugLog("moveSessionToChannel sessionId", session.nodeId, " channelId=", channel.channelId);
if (session.publishEngine) {
session.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
}
session._detach_channel();
session._attach_channel(channel);
assert(session.channel!.channelId === channel.channelId);
}
async function _attempt_to_close_some_old_unactivated_session(server: OPCUAServer) {
const session = server.engine!.getOldestInactiveSession();
if (session) {
await server.engine!.closeSession(session.authenticationToken, false, "Forcing");
}
}
function getRequiredEndpointInfo(endpoint: EndpointDescription) {
assert(endpoint instanceof EndpointDescription);
// https://reference.opcfoundation.org/v104/Core/docs/Part4/5.6.2/
// https://reference.opcfoundation.org/v105/Core/docs/Part4/5.6.2/
const e = new EndpointDescription({
endpointUrl: endpoint.endpointUrl,
securityLevel: endpoint.securityLevel,
securityMode: endpoint.securityMode,
securityPolicyUri: endpoint.securityPolicyUri,
server: {
applicationUri: endpoint.server.applicationUri,
applicationType: endpoint.server.applicationType,
applicationName: endpoint.server.applicationName,
productUri: endpoint.server.productUri
},
transportProfileUri: endpoint.transportProfileUri,
userIdentityTokens: endpoint.userIdentityTokens
});
// reduce even further by explicitly setting unwanted members to null
e.server.applicationName = null as any;
// xx e.server.applicationType = null as any;
e.server.gatewayServerUri = null;
e.server.discoveryProfileUri = null;
e.server.discoveryUrls = null;
e.serverCertificate = null as any;
return e;
}
// serverUri String This value is only specified if the EndpointDescription has a gatewayServerUri.
// This value is the applicationUri from the EndpointDescription which is the applicationUri for the
// underlying Server. The type EndpointDescription is defined in 7.10.
function _serverEndpointsForCreateSessionResponse(server: OPCUAServer, endpointUrl: string | null, serverUri: string | null) {
serverUri = null; // unused then
// https://reference.opcfoundation.org/v104/Core/docs/Part4/5.6.2/
// https://reference.opcfoundation.org/v105/Core/docs/Part4/5.6.2/
return server
._get_endpoints(endpointUrl)
.filter((e) => !(e as any).restricted) // remove restricted endpoints
.filter((e) => matchUri(e.endpointUrl, endpointUrl))
.map(getRequiredEndpointInfo);
}
function adjustSecurityPolicy(channel: ServerSecureChannelLayer, userTokenPolicy_securityPolicyUri: UAString): SecurityPolicy {
// check that userIdentityToken
let securityPolicy = fromURI(userTokenPolicy_securityPolicyUri);
// if the security policy is not specified we use the session security policy
if (securityPolicy === SecurityPolicy.Invalid) {
securityPolicy = fromURI((channel.clientSecurityHeader! as AsymmetricAlgorithmSecurityHeader).securityPolicyUri);
assert(securityPolicy !== SecurityPolicy.Invalid);
}
return securityPolicy;
}
function findUserTokenByPolicy(
endpoint_description: EndpointDescription,
userTokenType: UserTokenType,
policyId: SecurityPolicy | string | null
): UserTokenPolicy | null {
assert(endpoint_description instanceof EndpointDescription);
const r = endpoint_description.userIdentityTokens!.filter(
(userIdentity: UserTokenPolicy) =>
userIdentity.tokenType === userTokenType && (!policyId || userIdentity.policyId === policyId)
);
return r.length === 0 ? null : r[0];
}
function findUserTokenPolicy(endpoint_description: EndpointDescription, userTokenType: UserTokenType): UserTokenPolicy | null {
assert(endpoint_description instanceof EndpointDescription);
const r = endpoint_description.userIdentityTokens!.filter((userIdentity: UserTokenPolicy) => {
assert(userIdentity.tokenType !== undefined);
return userIdentity.tokenType === userTokenType;
});
return r.length === 0 ? null : r[0];
}
function createAnonymousIdentityToken(endpoint_desc: EndpointDescription) {
assert(endpoint_desc instanceof EndpointDescription);
const userTokenPolicy = findUserTokenPolicy(endpoint_desc, UserTokenType.Anonymous);
if (!userTokenPolicy) {
throw new Error("Cannot find ANONYMOUS user token policy in end point description");
}
return new AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
}
function sameIdentityToken(token1: UserIdentityToken, token2: UserIdentityToken): boolean {
if (token1 instanceof UserNameIdentityToken) {
if (!(token2 instanceof UserNameIdentityToken)) {
return false;
}
if (token1.userName !== token2.userName) {
return false;
}
if (token1.password.toString("hex") !== token2.password.toString("hex")) {
return false;
}
} else if (token1 instanceof AnonymousIdentityToken) {
if (!(token2 instanceof AnonymousIdentityToken)) {
return false;
}
if (token1.policyId !== token2.policyId) {
return false;
}
return true;
}
assert(false, " Not implemented yet");
return false;
}
function getTokenType(userIdentityToken: UserIdentityToken): UserTokenType {
if (userIdentityToken instanceof AnonymousIdentityToken) {
return UserTokenType.Anonymous;
} else if (userIdentityToken instanceof UserNameIdentityToken) {
return UserTokenType.UserName;
} else if (userIdentityToken instanceof IssuedIdentityToken) {
return UserTokenType.IssuedToken;
} else if (userIdentityToken instanceof X509IdentityToken) {
return UserTokenType.Certificate;
}
return UserTokenType.Invalid;
}
function thumbprint(certificate?: Certificate): string {
return certificate ? certificate.toString("base64") : "";
}
/*=== private
*
* perform the read operation on a given node for a monitored item.
* this method DOES NOT apply to Variable Values attribute
*
* @param self
* @param oldValue
* @param node
* @param itemToMonitor
* @private
*/
function monitoredItem_read_and_record_value(
self: MonitoredItem,
context: ISessionContext,
oldValue: DataValue,
node: UAVariable,
itemToMonitor: any,
callback: (err: Error | null, dataValue?: DataValue) => void
) {
assert(self instanceof MonitoredItem);
assert(oldValue instanceof DataValue);
assert(itemToMonitor.attributeId === AttributeIds.Value);
const dataValue = node.readAttribute(context, itemToMonitor.attributeId, itemToMonitor.indexRange, itemToMonitor.dataEncoding);
callback(null, dataValue);
}
/*== private
* @method monitoredItem_read_and_record_value_async
* this method applies to Variable Values attribute
* @param self
* @param oldValue
* @param node
* @param itemToMonitor
* @private
*/
function monitoredItem_read_and_record_value_async(
self: MonitoredItem,
context: ISessionContext,
oldValue: DataValue,
node: UAVariable,
itemToMonitor: any,
callback: (err: Error | null, dataValue?: DataValue) => void
) {
assert(context instanceof SessionContext);
assert(itemToMonitor.attributeId === AttributeIds.Value);
assert(self instanceof MonitoredItem);
assert(oldValue instanceof DataValue);
// do it asynchronously ( this is only valid for value attributes )
assert(itemToMonitor.attributeId === AttributeIds.Value);
node.readValueAsync(context, (err: Error | null, dataValue?: DataValue) => {
callback(err, dataValue);
});
}
function build_scanning_node_function(addressSpace: AddressSpace, itemToMonitor: any): SamplingFunc {
assert(itemToMonitor instanceof ReadValueId);
const node = addressSpace.findNode(itemToMonitor.nodeId) as UAVariable;
/* istanbul ignore next */
if (!node) {
errorLog(" INVALID NODE ID , ", itemToMonitor.nodeId.toString());
dump(itemToMonitor);
return (
_sessionContext: ISessionContext,
_oldData: DataValue,
callback: (err: Error | null, dataValue?: DataValue) => void
) => {
callback(
null,
new DataValue({
statusCode: StatusCodes.BadNodeIdUnknown,
value: { dataType: DataType.Null, value: 0 }
})
);
};
}
///// !!monitoredItem.setNode(node);
if (itemToMonitor.attributeId === AttributeIds.Value) {
const monitoredItem_read_and_record_value_func =
itemToMonitor.attributeId === AttributeIds.Value && typeof node.readValueAsync === "function"
? monitoredItem_read_and_record_value_async
: monitoredItem_read_and_record_value;
return function func(
this: MonitoredItem,
sessionContext: ISessionContext,
oldDataValue: DataValue,
callback: (err: Error | null, dataValue?: DataValue) => void
) {
assert(this instanceof MonitoredItem);
assert(oldDataValue instanceof DataValue);
assert(typeof callback === "function");
monitoredItem_read_and_record_value_func(this, sessionContext, oldDataValue, node, itemToMonitor, callback);
};
} else {
// Attributes, other than the Value Attribute, are only monitored for a change in value.
// The filter is not used for these Attributes. Any change in value for these Attributes
// causes a Notification to be generated.
// only record value when it has changed
return function func(
this: MonitoredItem,
sessionContext: ISessionContext,
oldDataValue: DataValue,
callback: (err: Error | null, dataValue?: DataValue) => void
) {
assert(this instanceof MonitoredItem);
assert(oldDataValue instanceof DataValue);
assert(typeof callback === "function");
const newDataValue = node.readAttribute(sessionContext, itemToMonitor.attributeId);
callback(null, newDataValue);
};
}
}
function prepareMonitoredItem(context: ISessionContext, addressSpace: AddressSpace, monitoredItem: MonitoredItem) {
const itemToMonitor = monitoredItem.itemToMonitor;
const readNodeFunc = build_scanning_node_function(addressSpace, itemToMonitor);
monitoredItem.samplingFunc = readNodeFunc;
}
function isMonitoringModeValid(monitoringMode: MonitoringMode): boolean {
assert(MonitoringMode.Invalid !== undefined);
return monitoringMode !== MonitoringMode.Invalid && monitoringMode <= MonitoringMode.Reporting;
}
function _installRegisterServerManager(self: OPCUAServer) {
assert(self instanceof OPCUAServer);
assert(!self.registerServerManager);
/* istanbul ignore next */
if (!self.registerServerMethod) {
throw new Error("Internal Error");
}
switch (self.registerServerMethod) {
case RegisterServerMethod.HIDDEN:
self.registerServerManager = new RegisterServerManagerHidden({
server: self
});
break;
case RegisterServerMethod.MDNS:
self.registerServerManager = new RegisterServerManagerMDNSONLY({
server: self
});
break;
case RegisterServerMethod.LDS:
self.registerServerManager = new RegisterServerManager({
discoveryServerEndpointUrl: self.discoveryServerEndpointUrl,
server: self
});
break;
/* istanbul ignore next */
default:
throw new Error("Invalid switch");
}
self.registerServerManager.on("serverRegistrationPending", () => {
/**
* emitted when the server is trying to registered the LDS
* but when the connection to the lds has failed
* serverRegistrationPending is sent when the backoff signal of the
* connection process is raised
* @event serverRegistrationPending
*/
debugLog("serverRegistrationPending");
self.emit("serverRegistrationPending");
});
self.registerServerManager.on("serverRegistered", () => {
/**
* emitted when the server is successfully registered to the LDS
* @event serverRegistered
*/
debugLog("serverRegistered");
self.emit("serverRegistered");
});
self.registerServerManager.on("serverRegistrationRenewed", () => {
/**
* emitted when the server has successfully renewed its registration to the LDS
* @event serverRegistrationRenewed
*/
debugLog("serverRegistrationRenewed");
self.emit("serverRegistrationRenewed");
});
self.registerServerManager.on("serverUnregistered", () => {
debugLog("serverUnregistered");
/**
* emitted when the server is successfully unregistered to the LDS
* ( for instance during shutdown)
* @event serverUnregistered
*/
self.emit("serverUnregistered");
});
}
function validate_applicationUri(channel: ServerSecureChannelLayer, request: CreateSessionRequest): boolean {
const applicationUri = request.clientDescription.applicationUri!;
const clientCertificate = request.clientCertificate;
// if session is insecure there is no need to check certificate information
if (channel.securityMode === MessageSecurityMode.None) {
return true; // assume correct
}
if (!clientCertificate || clientCertificate.length === 0) {
return true; // can't check
}
const e = exploreCertificate(clientCertificate);
const uniformResourceIdentifier = e.tbsCertificate.extensions!.subjectAltName?.uniformResourceIdentifier ?? null;
const applicationUriFromCert =
uniformResourceIdentifier && uniformResourceIdentifier.length > 0 ? uniformResourceIdentifier[0] : null;
/* istanbul ignore next */
if (applicationUriFromCert !== applicationUri) {
errorLog("BadCertificateUriInvalid!");
errorLog("applicationUri = ", applicationUri);
errorLog("applicationUriFromCert = ", applicationUriFromCert);
}
return applicationUriFromCert === applicationUri;
}
function validate_security_endpoint(
server: OPCUAServer,
request: CreateSessionRequest,
channel: ServerSecureChannelLayer
): {
errCode: StatusCode;
endpoint?: EndpointDescription;
} {
debugLog("validate_security_endpoint = ", request.endpointUrl);
let endpoints = server._get_endpoints(request.endpointUrl);
// endpointUrl String The network address that the Client used to access the Session Endpoint.
// The HostName portion of the URL should be one of the HostNames for the application that are
// specified in the Server’s ApplicationInstanceCertificate (see 7.2). The Server shall raise an
// AuditUrlMismatchEventType event if the URL does not match the Server’s HostNames.
// AuditUrlMismatchEventType event type is defined in Part 5.
// The Server uses this information for diagnostics and to determine the set of
// EndpointDescriptions to return in the response.
// ToDo: check endpointUrl validity and emit an AuditUrlMismatchEventType event if not
if (endpoints.length === 0) {
// we have a UrlMismatch here
const ua_server = server.engine.addressSpace!.rootFolder.objects.server;
errorLog("Cannot find suitable endpoints in available endpoints. endpointUri =", request.endpointUrl);
ua_server.raiseEvent("AuditUrlMismatchEventType", {
endpointUrl: { dataType: DataType.String, value: request.endpointUrl }
});
if (OPCUAServer.requestExactEndpointUrl) {
return { errCode: StatusCodes.BadServiceUnsupported };
} else {
endpoints = server._get_endpoints(null);
}
}
// ignore restricted endpoints
endpoints = endpoints.filter((e: EndpointDescription) => !(e as EndpointDescriptionEx).restricted);
const endpoints_matching_security_mode = endpoints.filter((e: EndpointDescription) => {
return e.securityMode === channel.securityMode;
});
if (endpoints_matching_security_mode.length === 0) {
return { errCode: StatusCodes.BadSecurityModeRejected };
}
const endpoints_matching_security_policy = endpoints_matching_security_mode.filter((e: EndpointDescription) => {
return e.securityPolicyUri === channel.securityHeader!.securityPolicyUri;
});
if (endpoints_matching_security_policy.length === 0) {
return { errCode: StatusCodes.BadSecurityPolicyRejected };
}
if (endpoints_matching_security_policy.length !== 1) {
debugLog("endpoints_matching_security_policy= ", endpoints_matching_security_policy.length);
}
return { errCode: StatusCodes.Good, endpoint: endpoints_matching_security_policy[0] };
}
export function filterDiagnosticInfo(returnDiagnostics: number, response: CallResponse): void {
if (RESPONSE_DIAGNOSTICS_MASK_ALL & returnDiagnostics) {
response.responseHeader.serviceDiagnostics = filterDiagnosticServiceLevel(
returnDiagnostics,
response.responseHeader.serviceDiagnostics
);
if (response.diagnosticInfos && response.diagnosticInfos.length > 0) {
response.diagnosticInfos = response.diagnosticInfos.map((d) => filterDiagnosticOperationLevel(returnDiagnostics, d));
} else {
response.diagnosticInfos = [];
}
if (response.results) {
for (const entry of response.results) {
if (entry.inputArgumentDiagnosticInfos && entry.inputArgumentDiagnosticInfos.length > 0) {
entry.inputArgumentDiagnosticInfos = entry.inputArgumentDiagnosticInfos.map((d) =>
filterDiagnosticOperationLevel(returnDiagnostics, d)
);
} else {
entry.inputArgumentDiagnosticInfos = [];
}
}
}
}
}
export enum RegisterServerMethod {
HIDDEN = 1, // the server doesn't expose itself to the external world
MDNS = 2, // the server publish itself to the mDNS Multicast network directly
LDS = 3 // the server registers itself to the LDS or LDS-ME (Local Discovery Server)
}
export interface OPCUAServerEndpointOptions {
/**
* the primary hostname of the endpoint.
* @default getFullyQualifiedDomainName()
*/
hostname?: string;
/**
* the TCP port to listen to.
* @default 26543
*/
port?: number;
/**
* the possible security policies that the server will expose
* @default [SecurityPolicy.None, SecurityPolicy.Basic128Rsa15, SecurityPolicy.Basic256Sha256, SecurityPolicy.Aes128_Sha256_RsaOaep, SecurityPolicy.Aes256_Sha256_RsaPss ]
*/
securityPolicies?: SecurityPolicy[];
/**
* the possible security mode that the server will expose
* @default [MessageSecurityMode.None, MessageSecurityMode.Sign, MessageSecurityMode.SignAndEncrypt]
*/
securityModes?: MessageSecurityMode[];
/**
* tells if the server default endpoints should allow anonymous connection.
* @default true
*/
allowAnonymous?: boolean;
/** alternate hostname or IP to use */
alternateHostname?: string | string[];
/**
* true, if discovery service on secure channel shall be disabled
*/
disableDiscovery?: boolean;
}
export interface OPCUAServerOptions extends OPCUABaseServerOptions, OPCUAServerEndpointOptions {
alternateEndpoints?: OPCUAServerEndpointOptions[];
/**
* the server certificate full path filename
*
* the certificate should be in PEM format
*/
certificateFile?: string;
/**
* the server private key full path filename
*
* This file should contains the private key that has been used to generate
* the server certificate file.
*
* the private key should be in PEM format
*
*/
privateKeyFile?: string;
/**
* the default secure token life time in ms.
*/
defaultSecureTokenLifetime?: number;
/**
* the HEL/ACK transaction timeout in ms.
*
* Use a large value ( i.e 15000 ms) for slow connections or embedded devices.
* @default 10000
*/
timeout?: number;
/**
* the maximum number of simultaneous sessions allowed.
* @default 10
* @deprecated use serverCapabilities: { maxSessions: } instead
*/
maxAllowedSessionNumber?: number;
/**
* the maximum number authorized simultaneous connections per endpoint
* @default 10
*/
maxConnectionsPerEndpoint?: number;
/**
* the nodeset.xml file(s) to load
*
* node-opcua comes with pre-installed node-set files that can be used
*
* example:
*
* ```javascript
* import { nodesets } from "node-opcua-nodesets";
* const server = new OPCUAServer({
* nodeset_filename: [
* nodesets.standard,
* nodesets.di,
* nodesets.adi,
* nodesets.machinery,
* ],
* });
* ```
*/
nodeset_filename?: string[] | string;
/**
* the server Info
*
* this object contains the value that will populate the
* Root/ObjectS/Server/ServerInfo OPCUA object in the address space.
*/
serverInfo?: ApplicationDescriptionOptions;
/*{
applicationUri?: string;
productUri?: string;
applicationName?: LocalizedTextLike | string;
gatewayServerUri?: string | null;
discoveryProfileUri?: string | null;
discoveryUrls?: string[];
};
*/
buildInfo?: {
productName?: string;
productUri?: string | null; // << should be same as default_server_info.productUri?
manufacturerName?: string;
softwareVersion?: string;
buildNumber?: string;
buildDate?: Date;
};
/**
* an object that implements user authentication methods
*/
userManager?: UserManagerOptions;
/** resource Path is a string added at the end of the url such as "/UA/Server" */
resourcePath?: string;
/**
*
*/
serverCapabilities?: ServerCapabilitiesOptions;
/**
* if server shall raise AuditingEvent
* @default true
*/
isAuditing?: boolean;
/**
* strategy used by the server to declare itself to a discovery server
*
* - HIDDEN: the server doesn't expose itself to the external world
* - MDNS: the server publish itself to the mDNS Multicast network directly
* - LDS: the server registers itself to the LDS or LDS-ME (Local Discovery Server)
*
* @default .HIDDEN - by default the server
* will not register itself to the local discovery server
*
*/
registerServerMethod?: RegisterServerMethod;
/**
*
* @default "opc.tcp://localhost:4840"]
*/
discoveryServerEndpointUrl?: string;
/**
*
* supported server capabilities for the Multicast (mDNS)
* @default ["NA"]
* the possible values are any of node-opcua-discovery.serverCapabilities)
*
*/
capabilitiesForMDNS?: string[];
/**
* user Certificate Manager
* this certificate manager holds the X509 certificates used
* by client that uses X509 certificate token to impersonate a user
*/
userCertificateManager?: OPCUACertificateManager;
/**
* Server Certificate Manager
*
* this certificate manager will be used by the server to access
* and store certificates from the connecting clients
*/
serverCertificateManager?: OPCUACertificateManager;
/**
*
*/
onCreateMonitoredItem?: CreateMonitoredItemHook;
onDeleteMonitoredItem?: DeleteMonitoredItemHook;
}
export interface OPCUAServer {
/**
*
*/
engine: ServerEngine;
/**
*
*/
registerServerMethod: RegisterServerMethod;
/**
*
*/
discoveryServerEndpointUrl: string;
/**
*
*/
registerServerManager?: IRegisterServerManager;
/**
*
*/
capabilitiesForMDNS: string[];
/**
*
*/
userCertificateManager: OPCUACertificateManager;
}
const g_requestExactEndpointUrl = !!process.env.NODEOPCUA_SERVER_REQUEST_EXACT_ENDPOINT_URL;
/**
*
*/
export class OPCUAServer extends OPCUABaseServer {
static defaultShutdownTimeout = 100; // 250 ms
/**
* if requestExactEndpointUrl is set to true the server will only accept createSession that have a endpointUrl that strictly matches
* one of the provided endpoint.
* This mean that if the server expose a endpoint with url such as opc.tcp://MYHOSTNAME:1234, client will not be able to reach the server
* with the ip address of the server.
* requestExactEndpointUrl = true => emulates the Prosys Server behavior
* requestExactEndpointUrl = false => emulates the Unified Automation behavior.
*/
static requestExactEndpointUrl: boolean = g_requestExactEndpointUrl;
/**
* total number of bytes written by the server since startup
*/
public get bytesWritten(): number {
return this.endpoints.reduce((accumulated: number, endpoint: OPCUAServerEndPoint) => {
return accumulated + endpoint.bytesWritten;
}, 0);
}
/**
* total number of bytes read by the server since startup
*/
public get bytesRead(): number {
return this.endpoints.reduce((accumulated: number, endpoint: OPCUAServerEndPoint) => {
return accumulated + endpoint.bytesRead;
}, 0);
}
/**
* Number of transactions processed by the server since startup
*/
public get transactionsCount(): number {
return this.endpoints.reduce((accumulated: number, endpoint: OPCUAServerEndPoint) => {
return accumulated + endpoint.transactionsCount;
}, 0);
}
/**
* The server build info
*/
public get buildInfo(): BuildInfo {
return this.engine.buildInfo;
}
/**
* the number of connected channel on all existing end points
*/
public get currentChannelCount(): number {
// TODO : move to base
return this.endpoints.reduce((currentValue: number, endPoint: OPCUAServerEndPoint) => {
return currentValue + endPoint.currentChannelCount;
}, 0);
}
/**
* The number of active subscriptions from all sessions
*/
public get currentSubscriptionCount(): number {
return this.engine ? this.engine.currentSubscriptionCount : 0;
}
/**
* the number of session activation requests that have been rejected
*/
public get rejectedSessionCount(): number {
return this.engine ? this.engine.rejectedSessionCount : 0;
}