-
Notifications
You must be signed in to change notification settings - Fork 269
/
client.go
1335 lines (1126 loc) · 38.8 KB
/
client.go
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
// Copyright 2018-2020 opcua authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
package opcua
import (
"context"
"crypto/rand"
"expvar"
"fmt"
"io"
"log"
"reflect"
"sort"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/errors"
"github.com/gopcua/opcua/id"
"github.com/gopcua/opcua/stats"
"github.com/gopcua/opcua/ua"
"github.com/gopcua/opcua/uacp"
"github.com/gopcua/opcua/uasc"
)
// FindServers returns the servers known to a server or discovery server.
func FindServers(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ApplicationDescription, error) {
opts = append(opts, AutoReconnect(false))
c, err := NewClient(endpoint, opts...)
if err != nil {
return nil, err
}
if err := c.Dial(ctx); err != nil {
return nil, err
}
defer c.Close(ctx)
res, err := c.FindServers(ctx)
if err != nil {
return nil, err
}
return res.Servers, nil
}
// FindServersOnNetwork returns the servers known to a server or discovery server. Unlike FindServers, this service is only implemented by discovery servers.
func FindServersOnNetwork(ctx context.Context, endpoint string, opts ...Option) ([]*ua.ServerOnNetwork, error) {
opts = append(opts, AutoReconnect(false))
c, err := NewClient(endpoint, opts...)
if err != nil {
return nil, err
}
if err := c.Dial(ctx); err != nil {
return nil, err
}
defer c.Close(ctx)
res, err := c.FindServersOnNetwork(ctx)
if err != nil {
return nil, err
}
return res.Servers, nil
}
// GetEndpoints returns the available endpoint descriptions for the server.
func GetEndpoints(ctx context.Context, endpoint string, opts ...Option) ([]*ua.EndpointDescription, error) {
opts = append(opts, AutoReconnect(false))
c, err := NewClient(endpoint, opts...)
if err != nil {
return nil, err
}
if err := c.Dial(ctx); err != nil {
return nil, err
}
defer c.Close(ctx)
res, err := c.GetEndpoints(ctx)
if err != nil {
return nil, err
}
return res.Endpoints, nil
}
// SelectEndpoint returns the endpoint with the highest security level which matches
// security policy and security mode. policy and mode can be omitted so that
// only one of them has to match.
func SelectEndpoint(endpoints []*ua.EndpointDescription, policy string, mode ua.MessageSecurityMode) (*ua.EndpointDescription, error) {
if len(endpoints) == 0 {
return nil, errors.Errorf("no endpoints available")
}
sort.Sort(sort.Reverse(bySecurityLevel(endpoints)))
policy = ua.FormatSecurityPolicyURI(policy)
// don't care -> return highest security level
if policy == "" && mode == ua.MessageSecurityModeInvalid {
return endpoints[0], nil
}
for _, p := range endpoints {
// match only security mode
if policy == "" && p.SecurityMode == mode {
return p, nil
}
// match only security policy
if p.SecurityPolicyURI == policy && mode == ua.MessageSecurityModeInvalid {
return p, nil
}
// match both
if p.SecurityPolicyURI == policy && p.SecurityMode == mode {
return p, nil
}
}
return nil, errors.Errorf("no matching endpoint found for policy %s and mode %s", policy, mode)
}
type bySecurityLevel []*ua.EndpointDescription
func (a bySecurityLevel) Len() int { return len(a) }
func (a bySecurityLevel) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a bySecurityLevel) Less(i, j int) bool { return a[i].SecurityLevel < a[j].SecurityLevel }
// Client is a high-level client for an OPC/UA server.
// It establishes a secure channel and a session.
type Client struct {
// endpointURL is the endpoint URL the client connects to.
endpointURL string
// cfg is the configuration for the client.
cfg *Config
// conn is the open connection
conn *uacp.Conn
// sechan is the open secure channel.
atomicSechan atomic.Value // *uasc.SecureChannel
sechanErr chan error
// atomicSession is the active atomicSession.
atomicSession atomic.Value // *Session
// subMux guards subs and pendingAcks.
subMux sync.RWMutex
// subs is the set of active subscriptions by id.
subs map[uint32]*Subscription
// pendingAcks contains the pending subscription acknowledgements
// for all active subscriptions.
pendingAcks []*ua.SubscriptionAcknowledgement
// pausech pauses the subscription publish loop
pausech chan struct{}
// resumech resumes subscription publish loop
resumech chan struct{}
// mcancel stops subscription publish loop
mcancel func()
// timeout for sending PublishRequests
atomicPublishTimeout atomic.Value // time.Duration
// atomicState of the client
atomicState atomic.Value // ConnState
// list of cached atomicNamespaces on the server
atomicNamespaces atomic.Value // []string
// monitorOnce ensures only one connection monitor is running
monitorOnce sync.Once
}
// NewClient creates a new Client.
//
// When no options are provided the new client is created from
// DefaultClientConfig() and DefaultSessionConfig(). If no authentication method
// is configured, a UserIdentityToken for anonymous authentication will be set.
// See #Client.CreateSession for details.
//
// To modify configuration you can provide any number of Options as opts. See
// #Option for details.
//
// https://godoc.org/github.com/gopcua/opcua#Option
func NewClient(endpoint string, opts ...Option) (*Client, error) {
cfg, err := ApplyConfig(opts...)
if err != nil {
return nil, err
}
c := Client{
endpointURL: endpoint,
cfg: cfg,
sechanErr: make(chan error, 1),
subs: make(map[uint32]*Subscription),
pendingAcks: make([]*ua.SubscriptionAcknowledgement, 0),
pausech: make(chan struct{}, 2),
resumech: make(chan struct{}, 2),
}
c.pauseSubscriptions(context.Background())
c.setPublishTimeout(uasc.MaxTimeout)
c.setState(Closed)
c.setSecureChannel(nil)
c.setSession(nil)
c.setNamespaces([]string{})
return &c, nil
}
// reconnectAction is a list of actions for the client reconnection logic.
type reconnectAction uint8
const (
none reconnectAction = iota // no reconnection action
createSecureChannel // recreate secure channel action
restoreSession // ask the server to repair session
recreateSession // ask the client to repair session
restoreSubscriptions // republish or recreate subscriptions
transferSubscriptions // move subscriptions from one session to another
abortReconnect // the reconnecting is not possible
)
// Connect establishes a secure channel and creates a new session.
func (c *Client) Connect(ctx context.Context) error {
// todo(fs): the secure channel is 'nil' during a re-connect
// todo(fs): but we expect this method to be called once during startup
// todo(fs): so this is probably safe
if c.SecureChannel() != nil {
return errors.Errorf("already connected")
}
c.setState(Connecting)
if err := c.Dial(ctx); err != nil {
stats.RecordError(err)
return err
}
s, err := c.CreateSession(ctx, c.cfg.session)
if err != nil {
c.Close(ctx)
stats.RecordError(err)
return err
}
if err := c.ActivateSession(ctx, s); err != nil {
c.Close(ctx)
stats.RecordError(err)
return err
}
c.setState(Connected)
mctx, mcancel := context.WithCancel(context.Background())
c.mcancel = mcancel
c.monitorOnce.Do(func() {
go c.monitor(mctx)
go c.monitorSubscriptions(mctx)
})
// todo(fs): we might need to guard this with an option in case of a broken
// todo(fs): server. For the sake of simplicity we left the option out but
// todo(fs): see the discussion in https://github.com/gopcua/opcua/pull/512
// todo(fs): and you should find a commit that implements this option.
if err := c.UpdateNamespaces(ctx); err != nil {
c.Close(ctx)
stats.RecordError(err)
return err
}
return nil
}
// monitor manages connection alteration
func (c *Client) monitor(ctx context.Context) {
dlog := debug.NewPrefixLogger("client: monitor: ")
dlog.Printf("start")
defer dlog.Printf("done")
defer c.mcancel()
defer c.setState(Closed)
action := none
for {
select {
case <-ctx.Done():
return
case err, ok := <-c.sechanErr:
stats.RecordError(err)
// return if channel or connection is closed
if !ok || err == io.EOF && c.State() == Closed {
dlog.Print("closed")
return
}
// the subscriptions don't exist for session.
// skip this error and continue monitor loop
if errors.Is(err, ua.StatusBadNoSubscription) {
continue
}
// tell the handler the connection is disconnected
c.setState(Disconnected)
dlog.Print("disconnected")
if !c.cfg.sechan.AutoReconnect {
// the connection is closed and should not be restored
action = abortReconnect
dlog.Print("auto-reconnect disabled")
return
}
dlog.Print("auto-reconnecting")
switch {
case errors.Is(err, io.EOF):
// the connection has been closed
action = createSecureChannel
case errors.Is(err, syscall.ECONNREFUSED):
// the connection has been refused by the server
action = abortReconnect
case errors.Is(err, ua.StatusBadSecureChannelIDInvalid):
// the secure channel has been rejected by the server
action = createSecureChannel
case errors.Is(err, ua.StatusBadSessionIDInvalid):
// the session has been rejected by the server
action = recreateSession
case errors.Is(err, ua.StatusBadSubscriptionIDInvalid):
// the subscription has been rejected by the server
action = transferSubscriptions
case errors.Is(err, ua.StatusBadCertificateInvalid):
// todo(unknownet): recreate server certificate
fallthrough
default:
// unknown error has occured
action = createSecureChannel
}
c.pauseSubscriptions(ctx)
var (
subsToRepublish []uint32 // subscription ids for which to send republish requests
subsToRecreate []uint32 // subscription ids which need to be recreated as new subscriptions
availableSeqs map[uint32][]uint32 // available sequence numbers per subscription
activeSubs int // number of active subscriptions to resume/recreate
)
for action != none {
select {
case <-ctx.Done():
return
default:
switch action {
case createSecureChannel:
dlog.Printf("action: createSecureChannel")
// recreate a secure channel by brute forcing
// a reconnection to the server
// close previous secure channel
//
// todo(fs): the two calls to Close() trigger a double-close on both the
// todo(fs): secure channel and the UACP connection. I have guarded for this
// todo(fs): with a sync.Once but that feels like a band-aid. We need to investigate
// todo(fs): why we are trying to create a new secure channel when we shut the client
// todo(fs): down.
//
// https://github.com/gopcua/opcua/pull/470
c.conn.Close()
if sc := c.SecureChannel(); sc != nil {
sc.Close()
c.setSecureChannel(nil)
}
c.setState(Reconnecting)
dlog.Printf("trying to recreate secure channel")
for {
if err := c.Dial(ctx); err != nil {
select {
case <-ctx.Done():
return
case <-time.After(c.cfg.sechan.ReconnectInterval):
dlog.Printf("trying to recreate secure channel")
continue
}
}
break
}
dlog.Printf("secure channel recreated")
action = restoreSession
case restoreSession:
dlog.Printf("action: restoreSession")
// try to reactivate the session,
// This only works if the session is still open on the server
// otherwise recreate it
c.setState(Reconnecting)
s := c.Session()
if s == nil {
dlog.Printf("no session to restore")
action = recreateSession
continue
}
dlog.Printf("trying to restore session")
if err := c.ActivateSession(ctx, s); err != nil {
dlog.Printf("restore session failed: %v", err)
action = recreateSession
continue
}
dlog.Printf("session restored")
// todo(fs): see comment about guarding this with an option in Connect()
dlog.Printf("trying to update namespaces")
if err := c.UpdateNamespaces(ctx); err != nil {
dlog.Printf("updating namespaces failed: %v", err)
action = createSecureChannel
continue
}
dlog.Printf("namespaces updated")
action = restoreSubscriptions
case recreateSession:
dlog.Printf("action: recreateSession")
c.setState(Reconnecting)
// create a new session to replace the previous one
// clear any previous session as we know the server has closed it
// this also prevents any unnecessary calls to CloseSession
c.setSession(nil)
dlog.Printf("trying to recreate session")
s, err := c.CreateSession(ctx, c.cfg.session)
if err != nil {
dlog.Printf("recreate session failed: %v", err)
action = createSecureChannel
continue
}
if err := c.ActivateSession(ctx, s); err != nil {
dlog.Printf("reactivate session failed: %v", err)
action = createSecureChannel
continue
}
dlog.Print("session recreated")
// todo(fs): see comment about guarding this with an option in Connect()
dlog.Printf("trying to update namespaces")
if err := c.UpdateNamespaces(ctx); err != nil {
dlog.Printf("updating namespaces failed: %v", err)
action = createSecureChannel
continue
}
dlog.Printf("namespaces updated")
action = transferSubscriptions
case transferSubscriptions:
dlog.Printf("action: transferSubscriptions")
// transfer subscriptions from the old to the new session
// and try to republish the subscriptions.
// Restore the subscriptions where republishing fails.
subIDs := c.SubscriptionIDs()
availableSeqs = map[uint32][]uint32{}
subsToRecreate = nil
subsToRepublish = nil
// try to transfer all subscriptions to the new session and
// recreate them all if that fails.
res, err := c.transferSubscriptions(ctx, subIDs)
switch {
case errors.Is(err, ua.StatusBadServiceUnsupported):
dlog.Printf("transfer subscriptions not supported. Recreating all subscriptions: %v", err)
subsToRepublish = nil
subsToRecreate = subIDs
case err != nil:
dlog.Printf("transfer subscriptions failed. Recreating all subscriptions: %v", err)
subsToRepublish = nil
subsToRecreate = subIDs
default:
// otherwise, try a republish for the subscriptions that were transferred
// and recreate the rest.
for i := range res.Results {
transferResult := res.Results[i]
switch transferResult.StatusCode {
case ua.StatusBadSubscriptionIDInvalid:
dlog.Printf("sub %d: transfer subscription failed", subIDs[i])
subsToRecreate = append(subsToRecreate, subIDs[i])
default:
subsToRepublish = append(subsToRepublish, subIDs[i])
availableSeqs[subIDs[i]] = transferResult.AvailableSequenceNumbers
}
}
}
action = restoreSubscriptions
case restoreSubscriptions:
dlog.Printf("action: restoreSubscriptions")
// try to republish the previous subscriptions from the server
// otherwise restore them.
// Assume that subsToRecreate and subsToRepublish have been
// populated in the previous step.
activeSubs = 0
for _, subID := range subsToRepublish {
if err := c.republishSubscription(ctx, subID, availableSeqs[subID]); err != nil {
dlog.Printf("republish of subscription %d failed", subID)
subsToRecreate = append(subsToRecreate, subID)
}
activeSubs++
}
for _, subID := range subsToRecreate {
if err := c.recreateSubscription(ctx, subID); err != nil {
dlog.Printf("recreate subscripitions failed: %v", err)
action = recreateSession
continue
}
activeSubs++
}
c.setState(Connected)
action = none
case abortReconnect:
dlog.Printf("action: abortReconnect")
// non recoverable disconnection
// stop the client
// todo(unknownet): should we store the error?
dlog.Printf("reconnection not recoverable")
return
}
}
}
// clear sechan errors from reconnection
for len(c.sechanErr) > 0 {
<-c.sechanErr
}
switch {
case activeSubs > 0:
dlog.Printf("resuming %d subscriptions", activeSubs)
c.resumeSubscriptions(ctx)
dlog.Printf("resumed %d subscriptions", activeSubs)
default:
dlog.Printf("no subscriptions to resume")
}
}
}
}
// Dial establishes a secure channel.
func (c *Client) Dial(ctx context.Context) error {
stats.Client().Add("Dial", 1)
if c.SecureChannel() != nil {
return errors.Errorf("secure channel already connected")
}
var err error
var d = NewDialer(c.cfg)
c.conn, err = d.Dial(ctx, c.endpointURL)
if err != nil {
return err
}
sc, err := uasc.NewSecureChannel(c.endpointURL, c.conn, c.cfg.sechan, c.sechanErr)
if err != nil {
c.conn.Close()
return err
}
if err := sc.Open(ctx); err != nil {
c.conn.Close()
return err
}
c.setSecureChannel(sc)
return nil
}
// Close closes the session and the secure channel.
func (c *Client) Close(ctx context.Context) error {
stats.Client().Add("Close", 1)
// try to close the session but ignore any error
// so that we close the underlying channel and connection.
c.CloseSession(ctx)
c.setState(Closed)
if c.mcancel != nil {
c.mcancel()
}
if sc := c.SecureChannel(); sc != nil {
sc.Close()
c.setSecureChannel(nil)
}
// https://github.com/gopcua/opcua/pull/462
//
// do not close the c.sechanErr channel since it leads to
// race conditions and it gets garbage collected anyway.
// There is nothing we can do with this error while
// shutting down the client so I think it is safe to ignore
// them.
// close the connection but ignore the error since there isn't
// anything we can do about it anyway
if c.conn != nil {
c.conn.Close()
}
return nil
}
// State returns the current connection state.
func (c *Client) State() ConnState {
return c.atomicState.Load().(ConnState)
}
func (c *Client) setState(s ConnState) {
c.atomicState.Store(s)
n := new(expvar.Int)
n.Set(int64(s))
stats.Client().Set("State", n)
}
// Namespaces returns the currently cached list of namespaces.
func (c *Client) Namespaces() []string {
return c.atomicNamespaces.Load().([]string)
}
func (c *Client) setNamespaces(ns []string) {
c.atomicNamespaces.Store(ns)
}
func (c *Client) publishTimeout() time.Duration {
return c.atomicPublishTimeout.Load().(time.Duration)
}
func (c *Client) setPublishTimeout(d time.Duration) {
c.atomicPublishTimeout.Store(d)
}
// SecureChannel returns the active secure channel.
// During reconnect this value can change.
// Make sure to capture the value in a method before using it.
func (c *Client) SecureChannel() *uasc.SecureChannel {
return c.atomicSechan.Load().(*uasc.SecureChannel)
}
func (c *Client) setSecureChannel(sc *uasc.SecureChannel) {
c.atomicSechan.Store(sc)
stats.Client().Add("SecureChannel", 1)
}
// Session returns the active session.
// During reconnect this value can change.
// Make sure to capture the value in a method before using it.
func (c *Client) Session() *Session {
return c.atomicSession.Load().(*Session)
}
func (c *Client) setSession(s *Session) {
c.atomicSession.Store(s)
stats.Client().Add("Session", 1)
}
// Session is a OPC/UA session as described in Part 4, 5.6.
type Session struct {
cfg *uasc.SessionConfig
// resp is the response to the CreateSession request which contains all
// necessary parameters to activate the session.
resp *ua.CreateSessionResponse
// serverCertificate is the certificate used to generate the signatures for
// the ActivateSessionRequest methods
serverCertificate []byte
// serverNonce is the secret nonce received from the server during Create and Activate
// Session response. Used to generate the signatures for the ActivateSessionRequest
// and User Authorization
serverNonce []byte
// revisedTimeout is the actual maximum time that a Session shall remain open without activity.
revisedTimeout time.Duration
}
// RevisedTimeout return actual maximum time that a Session shall remain open without activity.
// This value is provided by the server in response to CreateSession.
func (s *Session) RevisedTimeout() time.Duration {
return s.revisedTimeout
}
// CreateSession creates a new session which is not yet activated and not
// associated with the client. Call ActivateSession to both activate and
// associate the session with the client.
//
// If no UserIdentityToken is given explicitly before calling CreateSesion,
// it automatically sets anonymous identity token with the same PolicyID
// that the server sent in Create Session Response. The default PolicyID
// "Anonymous" wii be set if it's missing in response.
//
// See Part 4, 5.6.2
func (c *Client) CreateSession(ctx context.Context, cfg *uasc.SessionConfig) (*Session, error) {
if c.SecureChannel() == nil {
return nil, ua.StatusBadServerNotConnected
}
nonce := make([]byte, 32)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
name := cfg.SessionName
if name == "" {
name = fmt.Sprintf("gopcua-%d", time.Now().UnixNano())
}
req := &ua.CreateSessionRequest{
ClientDescription: cfg.ClientDescription,
EndpointURL: c.endpointURL,
SessionName: name,
ClientNonce: nonce,
ClientCertificate: c.cfg.sechan.Certificate,
RequestedSessionTimeout: float64(cfg.SessionTimeout / time.Millisecond),
}
var s *Session
// for the CreateSessionRequest the authToken is always nil.
// use c.SecureChannel().SendRequest() to enforce this.
err := c.SecureChannel().SendRequest(ctx, req, nil, func(v ua.Response) error {
var res *ua.CreateSessionResponse
if err := safeAssign(v, &res); err != nil {
return err
}
err := c.SecureChannel().VerifySessionSignature(res.ServerCertificate, nonce, res.ServerSignature.Signature)
if err != nil {
log.Printf("error verifying session signature: %s", err)
return nil
}
// Ensure we have a valid identity token that the server will accept before trying to activate a session
if c.cfg.session.UserIdentityToken == nil {
opt := AuthAnonymous()
// todo(sr): opt returns an error but we concluded that this call cannot
// todo(sr): fail and that we do not want to stop creating the session
// todo(sr): hence we ignore it.
opt(c.cfg)
p := anonymousPolicyID(res.ServerEndpoints)
opt = AuthPolicyID(p)
// todo(sr): opt returns an error but we concluded that this call cannot
// todo(sr): fail and that we do not want to stop creating the session
// todo(sr): hence we ignore it.
opt(c.cfg)
}
s = &Session{
cfg: cfg,
resp: res,
serverNonce: res.ServerNonce,
serverCertificate: res.ServerCertificate,
revisedTimeout: time.Duration(res.RevisedSessionTimeout) * time.Millisecond,
}
return nil
})
return s, err
}
const defaultAnonymousPolicyID = "Anonymous"
func anonymousPolicyID(endpoints []*ua.EndpointDescription) string {
for _, e := range endpoints {
if e.SecurityMode != ua.MessageSecurityModeNone || e.SecurityPolicyURI != ua.SecurityPolicyURINone {
continue
}
for _, t := range e.UserIdentityTokens {
if t.TokenType == ua.UserTokenTypeAnonymous {
return t.PolicyID
}
}
}
return defaultAnonymousPolicyID
}
// ActivateSession activates the session and associates it with the client. If
// the client already has a session it will be closed. To retain the current
// session call DetachSession.
//
// See Part 4, 5.6.3
func (c *Client) ActivateSession(ctx context.Context, s *Session) error {
if c.SecureChannel() == nil {
return ua.StatusBadServerNotConnected
}
stats.Client().Add("ActivateSession", 1)
sig, sigAlg, err := c.SecureChannel().NewSessionSignature(s.serverCertificate, s.serverNonce)
if err != nil {
log.Printf("error creating session signature: %s", err)
return nil
}
switch tok := s.cfg.UserIdentityToken.(type) {
case *ua.AnonymousIdentityToken:
// nothing to do
case *ua.UserNameIdentityToken:
pass, passAlg, err := c.SecureChannel().EncryptUserPassword(s.cfg.AuthPolicyURI, s.cfg.AuthPassword, s.serverCertificate, s.serverNonce)
if err != nil {
log.Printf("error encrypting user password: %s", err)
return err
}
tok.Password = pass
tok.EncryptionAlgorithm = passAlg
case *ua.X509IdentityToken:
tokSig, tokSigAlg, err := c.SecureChannel().NewUserTokenSignature(s.cfg.AuthPolicyURI, s.serverCertificate, s.serverNonce)
if err != nil {
log.Printf("error creating session signature: %s", err)
return err
}
s.cfg.UserTokenSignature = &ua.SignatureData{
Algorithm: tokSigAlg,
Signature: tokSig,
}
case *ua.IssuedIdentityToken:
tok.EncryptionAlgorithm = ""
}
req := &ua.ActivateSessionRequest{
ClientSignature: &ua.SignatureData{
Algorithm: sigAlg,
Signature: sig,
},
ClientSoftwareCertificates: nil,
LocaleIDs: s.cfg.LocaleIDs,
UserIdentityToken: ua.NewExtensionObject(s.cfg.UserIdentityToken),
UserTokenSignature: s.cfg.UserTokenSignature,
}
return c.SecureChannel().SendRequest(ctx, req, s.resp.AuthenticationToken, func(v ua.Response) error {
var res *ua.ActivateSessionResponse
if err := safeAssign(v, &res); err != nil {
return err
}
// save the nonce for the next request
s.serverNonce = res.ServerNonce
// close the previous session
//
// https://github.com/gopcua/opcua/issues/474
//
// We decided not to check the error of CloseSession() since we
// can't do much about it anyway and it creates a race in the
// re-connection logic.
c.CloseSession(ctx)
c.setSession(s)
return nil
})
}
// CloseSession closes the current session.
//
// See Part 4, 5.6.4
func (c *Client) CloseSession(ctx context.Context) error {
stats.Client().Add("CloseSession", 1)
if err := c.closeSession(ctx, c.Session()); err != nil {
return err
}
c.setSession(nil)
return nil
}
// closeSession closes the given session.
func (c *Client) closeSession(ctx context.Context, s *Session) error {
if s == nil {
return nil
}
req := &ua.CloseSessionRequest{DeleteSubscriptions: true}
var res *ua.CloseSessionResponse
return c.Send(ctx, req, func(v ua.Response) error {
return safeAssign(v, &res)
})
}
// DetachSession removes the session from the client without closing it. The
// caller is responsible to close or re-activate the session. If the client
// does not have an active session the function returns no error.
func (c *Client) DetachSession(ctx context.Context) (*Session, error) {
stats.Client().Add("DetachSession", 1)
s := c.Session()
c.setSession(nil)
return s, nil
}
// Send sends the request via the secure channel and registers a handler for
// the response. If the client has an active session it injects the
// authentication token.
func (c *Client) Send(ctx context.Context, req ua.Request, h func(ua.Response) error) error {
stats.Client().Add("Send", 1)
err := c.sendWithTimeout(ctx, req, c.cfg.sechan.RequestTimeout, h)
stats.RecordError(err)
return err
}
// sendWithTimeout sends the request via the secure channel with a custom timeout and registers a handler for
// the response. If the client has an active session it injects the
// authentication token.
func (c *Client) sendWithTimeout(ctx context.Context, req ua.Request, timeout time.Duration, h uasc.ResponseHandler) error {
sc := c.SecureChannel()
if sc == nil {
return ua.StatusBadServerNotConnected
}
var authToken *ua.NodeID
if s := c.Session(); s != nil {
authToken = s.resp.AuthenticationToken
}
return c.SecureChannel().SendRequestWithTimeout(ctx, req, authToken, timeout, h)
}
// Node returns a node object which accesses its attributes
// through this client connection.
func (c *Client) Node(id *ua.NodeID) *Node {
return &Node{ID: id, c: c}
}
// NodeFromExpandedNodeID returns a node object which accesses its attributes
// through this client connection. This is usually needed when working with node ids returned
// from browse responses by the server.
func (c *Client) NodeFromExpandedNodeID(id *ua.ExpandedNodeID) *Node {
return &Node{ID: ua.NewNodeIDFromExpandedNodeID(id), c: c}
}
// FindServers finds the servers available at an endpoint
func (c *Client) FindServers(ctx context.Context) (*ua.FindServersResponse, error) {
stats.Client().Add("FindServers", 1)
req := &ua.FindServersRequest{
EndpointURL: c.endpointURL,
}
var res *ua.FindServersResponse
err := c.Send(ctx, req, func(v ua.Response) error {
return safeAssign(v, &res)
})
return res, err
}
// FindServersOnNetwork finds the servers available at an endpoint
func (c *Client) FindServersOnNetwork(ctx context.Context) (*ua.FindServersOnNetworkResponse, error) {
stats.Client().Add("FindServersOnNetwork", 1)
req := &ua.FindServersOnNetworkRequest{}
var res *ua.FindServersOnNetworkResponse
err := c.Send(ctx, req, func(v ua.Response) error {
return safeAssign(v, &res)
})
return res, err
}