/
connection.go
1057 lines (849 loc) · 22.8 KB
/
connection.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
package ospc
import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"sync"
quic "github.com/quic-go/quic-go"
)
var ErrConnectionClosed = errors.New("connection closed")
var ErrHandedOff = errors.New("connection handed off")
// Connection
type Connection struct {
base *baseConnection
}
func (c *Connection) LocalAgent() *Agent {
return c.base.localAgent
}
func (c *Connection) RemoteAgent() *Agent {
return c.base.RemoteAgent()
}
// Handoff the underlying quick connection for use by another protocol.
// func (c *Connection) Handoff() (quic.Connection, error) {
// return c.base.Handoff()
// }
// Close the connection and all associated steams.
func (c *Connection) Close() error {
return c.base.Close()
}
type AgentState struct {
StateToken string // 8 characters in the range [0-9A-Za-z]
RequestId uint64
}
func newAgentState() AgentState {
s := AgentState{
RequestId: 1,
}
s.newStateToken()
return s
}
func (s *AgentState) newStateToken() {
s.StateToken = randomAlphaNum(8)
}
func (s *AgentState) nextRequestID() uint64 {
id := s.RequestId
s.RequestId++
return id
}
func randomAlphaNum(length int) string {
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
return randomCharset(chars, length)
}
func randomAT(length int) string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
return randomCharset(chars, length)
}
func randomCharset(chars string, length int) string {
var result string
max := big.NewInt(int64(len(chars)))
for i := 0; i < length; i++ {
randomIndex, _ := rand.Int(rand.Reader, max)
result += string(chars[randomIndex.Int64()])
}
return result
}
// baseConnection is the actual connection handler implementation.
type baseConnection struct {
conn quic.Connection
mu sync.Mutex
agentRole AgentRole
agentState AgentState
localAgent *Agent
remoteAgent *Agent
exchangeInfoState *exchangeInfoState
authenticationRole AuthenticationRole
authNotify chan struct{}
authenticationState *authenticationState
connectedState *connectedState
acceptCancel context.CancelFunc
close chan struct{}
closeErr error
done chan struct{}
}
func newBaseConnection(conn quic.Connection, localAgent *Agent, remoteAgent *Agent, role AgentRole) *baseConnection {
bConn := &baseConnection{
mu: sync.Mutex{},
agentRole: role,
agentState: newAgentState(), // TODO: reconnect
localAgent: localAgent,
remoteAgent: remoteAgent,
conn: conn,
authNotify: make(chan struct{}),
close: make(chan struct{}),
done: make(chan struct{}),
}
return bConn
}
func (c *baseConnection) RemoteAgent() *Agent {
return c.remoteAgent
}
type exchangeInfoState struct {
requestId uint64
done chan exchangeInfoResult
}
type exchangeInfoResult struct {
conn *baseConnection
err error
}
func (c *baseConnection) exchangeInfo(ctx context.Context, done chan exchangeInfoResult) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.exchangeInfoState != nil {
fmt.Println("Already requesting remote AgentInfo")
return nil
}
stream, err := c.openStream(ctx)
if err != nil {
return err
}
// Auth Info
localAuthInfo := c.localAgent.AuthenticationInfo()
authMsg := &msgAuthCapabilities{
PskEaseOfInput: uint64(localAuthInfo.PSKConfig.EaseOfInput),
PskInputMethods: []msgPskInputMethod{msgPskInputMethodNumeric},
PskMinBitsOfEntropy: uint64(localAuthInfo.PSKConfig.Entropy),
}
err = writeMessage(authMsg, stream)
if err != nil {
return err
}
// Remote AgentInfo
state := &exchangeInfoState{
requestId: c.agentState.nextRequestID(),
done: done,
}
infoMsg := &msgAgentInfoRequest{
RequestID: state.requestId,
}
err = writeMessage(infoMsg, stream)
if err != nil {
return err
}
c.exchangeInfoState = state
return nil
}
func (c *baseConnection) openStream(ctx context.Context) (quic.Stream, error) {
stream, err := c.conn.OpenStreamSync(ctx)
if err != nil {
return nil, err
}
bStream := newBaseStream(stream, c.handleMessage)
c.handleStream(bStream)
return stream, nil
}
func (c *baseConnection) handleAgentInfoRequest(msg *msgAgentInfoRequest, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
localInfo := c.localAgent.Info()
infoMsg := &msgAgentInfoResponse{
RequestID: msg.RequestID,
AgentInfo: msgPartAgentInfo{
DisplayName: localInfo.DisplayName,
ModelName: localInfo.ModelName,
Capabilities: []agentCapability{agentCapabilityExchangeData},
// StateToken: , // TODO: State token
Locales: localInfo.Locales,
},
}
err := writeMessage(infoMsg, stream)
if err != nil {
return err
}
return nil
}
func (c *baseConnection) handleAgentInfoResponse(msg *msgAgentInfoResponse, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.exchangeInfoState == nil {
fmt.Println("ignoring unsolicited AgentInfoResponse")
return nil
}
if c.exchangeInfoState.requestId != msg.RequestID {
fmt.Println("ignoring AgentInfoResponse with wrong request ID")
return nil
}
c.remoteAgent.setInfo(AgentInfo{
DisplayName: msg.AgentInfo.DisplayName,
ModelName: msg.AgentInfo.ModelName,
})
c.checkAgentInfoComplete()
return nil
}
func (c *baseConnection) handleAuthCapabilities(msg *msgAuthCapabilities, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
c.remoteAgent.setAuthenticationInfo(AgentAuthenticationInfo{
PSKConfig: PSKConfig{
EaseOfInput: int(msg.PskEaseOfInput),
Entropy: int(msg.PskMinBitsOfEntropy),
},
})
c.checkAgentInfoComplete()
return nil
}
// caller should hold connection lock.
func (c *baseConnection) checkAgentInfoComplete() {
if c.exchangeInfoState != nil &&
c.remoteAgent.HasInfo() &&
c.remoteAgent.HasAuthenticationInfo() {
state := c.exchangeInfoState
c.determineAuthenticationRole()
result := exchangeInfoResult{
conn: c,
}
select {
case state.done <- result:
c.exchangeInfoState = nil
case <-c.close:
return
}
}
}
type AuthenticationRole int
const (
AuthenticationRolePresenter AuthenticationRole = 0
AuthenticationRoleConsumer AuthenticationRole = 1
)
func (t AuthenticationRole) String() string {
switch t {
case AuthenticationRolePresenter:
return "Presenter"
case AuthenticationRoleConsumer:
return "Consumer"
default:
return fmt.Sprintf("Unknown AuthenticationRole: %d", t)
}
}
// GetAuthenticationRole determines if the agent should act as presenter or consumer of the PSK.
// Only correct after auth-capabilities exchange.
func (c *baseConnection) GetAuthenticationRole() AuthenticationRole {
c.mu.Lock()
defer c.mu.Unlock()
return c.authenticationRole
}
// Caller should hold connection lock.
func (c *baseConnection) determineAuthenticationRole() {
c.authenticationRole = c.getAuthenticationRole()
}
// Caller should hold connection lock.
func (c *baseConnection) getAuthenticationRole() AuthenticationRole {
localAuthInfo := c.localAgent.AuthenticationInfo()
remoteAuthInfo := c.remoteAgent.AuthenticationInfo()
if localAuthInfo.PSKConfig.EaseOfInput == remoteAuthInfo.PSKConfig.EaseOfInput {
if c.agentRole == AgentRoleServer {
return AuthenticationRolePresenter
}
return AuthenticationRoleConsumer
}
if localAuthInfo.PSKConfig.EaseOfInput < remoteAuthInfo.PSKConfig.EaseOfInput {
return AuthenticationRolePresenter
}
return AuthenticationRoleConsumer
}
// GeneratePSK creates a PSK based on the negotiated config.
func (c *baseConnection) GeneratePSK() ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
localAuthInfo := c.localAgent.AuthenticationInfo()
remoteAuthInfo := c.remoteAgent.AuthenticationInfo()
minBits := maxInt(
localAuthInfo.PSKConfig.Entropy,
remoteAuthInfo.PSKConfig.Entropy,
)
// We round up to full byte
buf := make([]byte, (minBits+7)/8)
_, err := rand.Read(buf)
if err != nil {
return nil, err
}
return buf, nil
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
type authenticationStatus int
const (
authStatusNew = iota + 1
authStatusRequested
authStatusAwaitPSK
authStatusAwaitHandshake
authStatusAwaitConfirmation
authStatusAwaitResult
authStatusDone
)
func (s authenticationStatus) String() string {
switch s {
case authStatusNew:
return "authStatus: New"
case authStatusRequested:
return "authStatus: Requested"
case authStatusAwaitPSK:
return "authStatus: AwaitPSK"
case authStatusAwaitHandshake:
return "authStatus: AwaitHandshake"
case authStatusAwaitConfirmation:
return "authStatus: AwaitConfirmation"
case authStatusAwaitResult:
return "authStatus: AwaitResult"
case authStatusDone:
return "authStatus: Done"
default:
return fmt.Sprintf("Invalid authStatus (%d)", s)
}
}
type authenticationState struct {
stream quic.Stream
status authenticationStatus
localPSK []byte
spakeState *spakeState
remotePublic []byte
sharedSecret *spakeSecret
remoteConfirmation []byte
remoteResult msgResult
done chan struct{}
}
// Caller should hold connection lock
func (c *baseConnection) newAuthenticationState(stream quic.Stream) (*authenticationState, error) {
if stream == nil {
var err error
stream, err = c.openStream(context.Background())
if err != nil {
return nil, err
}
}
c.authenticationState = &authenticationState{
stream: stream,
status: authStatusNew,
done: make(chan struct{}),
}
return c.authenticationState, nil
}
// AcceptAuthenticate is used to handle an incoming authentication request.
// It has to be called for every UnauthenticatedConnection.
func (c *baseConnection) AcceptAuthenticate(ctx context.Context) (role AuthenticationRole, err error) {
c.mu.Lock()
close := c.close
authNotify := c.authNotify
c.mu.Unlock()
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-close:
return 0, c.err()
case <-authNotify:
return c.GetAuthenticationRole(), nil
}
}
// RequestAuthenticatePSK is used to request authentication.
// As collecting agent it sends a auth-spake2-need-psk message.
// As presenting agent it's a no-op.
func (c *baseConnection) RequestAuthenticatePSK() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.authenticationRole == AuthenticationRolePresenter {
// No-op as presenter
return nil
}
authState := c.authenticationState
if authState != nil {
return errors.New("already authenticating")
}
return c.authenticatePSKProgress()
}
// Caller should hold connection lock
func (c *baseConnection) doAuthNotify() {
// close := c.close
authNotify := c.authNotify
close(authNotify)
}
// Caller should hold connection lock.
func (c *baseConnection) getAuthInitiationToken() (string, error) {
// TODO: wire up auth-initiation-token
// For an advertising agent, the at field in its mDNS TXT record must be used as the
// auth-initiation-token in the the first authentication message sent to or from that agent.
at := "todo"
return at, nil
}
// Caller should hold connection lock.
func (c *baseConnection) validateAuthInitiationToken(token string) error {
// TODO: wire up auth-initiation-token
// Agents should discard any authentication message whose auth-initiation-token is set and
// does not match the at provided by the advertising agent.
if token == "todo" {
return nil
}
return errors.New("invalid auth-initiation-token")
}
// Authenticate is used to authenticate. It will block until authentication is complete
// or the context is closed.
func (c *baseConnection) AuthenticatePSK(ctx context.Context, psk []byte) (*Connection, error) {
err := c.authenticatePSK(psk)
if err != nil {
return nil, err
}
c.mu.Lock()
close := c.close
done := c.authenticationState.done
c.mu.Unlock()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-close:
return nil, c.err()
case <-done:
return c.finishAuthentication()
}
}
func (c *baseConnection) finishAuthentication() (*Connection, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.authenticationState.remoteResult != msgResultSuccess {
return nil, fmt.Errorf("authentication failed: %d", c.authenticationState.remoteResult)
}
// c.authenticationState = nil
c.connectedState = &connectedState{
acceptDataChannel: make(chan *DataChannel),
acceptTransport: make(chan *Transport),
acceptTransportStream: make(chan *baseStream),
}
return &Connection{
base: c,
}, nil
}
func (c *baseConnection) authenticatePSK(psk []byte) error {
c.mu.Lock()
defer c.mu.Unlock()
if psk == nil {
return errors.New("no psk provided")
}
authState := c.authenticationState
if authState == nil {
var err error
authState, err = c.newAuthenticationState(nil)
if err != nil {
return err
}
}
if authState.localPSK != nil {
return fmt.Errorf("already authenticating")
}
authState.localPSK = psk
return c.authenticatePSKProgress()
}
// Caller should hold connection lock
func (c *baseConnection) authenticatePSKProgress() error {
authState := c.authenticationState
if authState == nil {
var err error
authState, err = c.newAuthenticationState(nil)
if err != nil {
return err
}
}
// fmt.Printf("%s %s\n", c.localInfo.Nickname, c.authenticationState.status)
role := c.authenticationRole
if authState.status == authStatusNew {
if role == AuthenticationRolePresenter {
if authState.localPSK == nil {
c.doAuthNotify()
}
} else {
if authState.remotePublic == nil {
err := c.sendAuthSpake2NeedPsk()
if err != nil {
return err
}
} else if authState.localPSK == nil {
c.doAuthNotify()
}
}
authState.status = authStatusAwaitPSK
}
if authState.status == authStatusAwaitPSK {
if authState.localPSK == nil {
return nil // continue waiting
}
if role == AuthenticationRolePresenter {
client, err := newSpakeClient(authState.localPSK)
if err != nil {
return err
}
authState.spakeState = client
} else {
server, err := newSpakeServer(authState.localPSK)
if err != nil {
return err
}
authState.spakeState = server
}
err := c.sendAuthSpake2Handshake()
if err != nil {
return err
}
authState.status = authStatusAwaitHandshake
}
if authState.status == authStatusAwaitHandshake {
if authState.remotePublic == nil {
return nil // continue waiting
}
secret, err := authState.spakeState.DeriveSecret(authState.remotePublic)
if err != nil {
return err
}
authState.sharedSecret = secret
err = c.sendAuthSpake2Confirmation()
if err != nil {
return err
}
authState.status = authStatusAwaitConfirmation
}
if authState.status == authStatusAwaitConfirmation {
if authState.remoteConfirmation == nil {
return nil // continue waiting
}
err := authState.sharedSecret.Verify(authState.remoteConfirmation)
if err != nil {
return err
}
err = c.sendAuthStatus()
if err != nil {
return err
}
authState.status = authStatusAwaitResult
}
if authState.status == authStatusAwaitResult {
if authState.remoteResult == 0 {
return nil // continue waiting
}
close(authState.done)
authState.status = authStatusDone
}
if authState.status == authStatusDone {
return nil
}
return errors.New("invalid authentication status")
}
// Caller should hold connection lock
func (c *baseConnection) sendAuthSpake2NeedPsk() error {
authState := c.authenticationState
at, err := c.getAuthInitiationToken()
if err != nil {
return err
}
msg := &msgAuthSpake2NeedPsk{
AuthInitiationToken: at,
}
err = writeMessage(msg, authState.stream)
if err != nil {
return err
}
return nil
}
// Caller should hold connection lock
func (c *baseConnection) sendAuthSpake2Handshake() error {
authState := c.authenticationState
publicValue := authState.spakeState.GetLocalPublic()
at, err := c.getAuthInitiationToken()
if err != nil {
return err
}
msg := &msgAuthSpake2Handshake{
AuthInitiationToken: at,
Payload: publicValue,
}
err = writeMessage(msg, authState.stream)
if err != nil {
return err
}
return nil
}
// Caller should hold connection lock
func (c *baseConnection) sendAuthSpake2Confirmation() error {
authState := c.authenticationState
confirmation := authState.sharedSecret.DeriveConfirmation()
msg := &msgAuthSpake2Confirmation{
Payload: confirmation,
}
err := writeMessage(msg, authState.stream)
if err != nil {
return err
}
return nil
}
// Caller should hold connection lock
func (c *baseConnection) sendAuthStatus() error {
authState := c.authenticationState
msg := &msgAuthStatus{
Result: msgResultSuccess,
}
err := writeMessage(msg, authState.stream)
if err != nil {
return err
}
return nil
}
func (c *baseConnection) handleAuthSpake2NeedPsk(msg *msgAuthSpake2NeedPsk, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.authenticationRole == AuthenticationRoleConsumer ||
c.authenticationState != nil {
fmt.Println("ignoring spake2-need-psk")
return nil
}
_, err := c.newAuthenticationState(stream)
if err != nil {
return err
}
return c.authenticatePSKProgress()
}
func (c *baseConnection) handleAuthSpake2Handshake(msg *msgAuthSpake2Handshake, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
err := c.validateAuthInitiationToken(msg.AuthInitiationToken)
if err != nil {
return err
}
authState := c.authenticationState
if authState == nil {
authState, err = c.newAuthenticationState(stream)
if err != nil {
return err
}
}
authState.remotePublic = msg.Payload
return c.authenticatePSKProgress()
}
func (c *baseConnection) handleAuthSpake2Confirmation(msg *msgAuthSpake2Confirmation, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
authState := c.authenticationState
if authState == nil {
return errors.New("unsolicited auth-spake2-confirmation")
}
authState.remoteConfirmation = msg.Payload
return c.authenticatePSKProgress()
}
func (c *baseConnection) handleAuthStatus(msg *msgAuthStatus, stream quic.Stream) error {
c.mu.Lock()
defer c.mu.Unlock()
authState := c.authenticationState
if authState == nil {
return errors.New("unsolicited auth-status")
}
authState.remoteResult = msg.Result
return c.authenticatePSKProgress()
}
func (c *baseConnection) run() {
c.mu.Lock()
defer c.mu.Unlock()
acceptCtx, acceptCancel := context.WithCancel(context.Background())
c.acceptCancel = acceptCancel
// Steam accept loop
go func() {
for {
s, err := c.conn.AcceptStream(acceptCtx)
if err != nil {
fmt.Printf("AcceptStream error: %s\n", err)
c.closeWithError(fmt.Errorf("acceptStream error: %v", err))
return
}
bStream := newBaseStream(s, c.handleMessage)
c.handleStream(bStream)
}
}()
}
func (c *baseConnection) handleStream(stream *baseStream) {
go func() {
for {
handler := stream.Handler()
if handler == nil {
return
}
msg, err := readMessage(stream.stream)
if err == quic.ErrServerClosed {
return
} else if err != nil {
fmt.Printf("failed to read message: %v\n", err)
// c.closeWithError(fmt.Errorf("failed to read message: %v", err))
return
}
err = handler(msg, stream)
if err != nil {
fmt.Printf("failed to handle message: %v\n", err)
c.closeWithError(fmt.Errorf("failed to handle message: %v", err))
return
}
}
}()
}
func (c *baseConnection) handleMessage(msg interface{}, stream *baseStream) (err error) {
switch typedMsg := msg.(type) {
case *msgAgentInfoRequest:
err = c.handleAgentInfoRequest(typedMsg, stream.stream)
case *msgAgentInfoResponse:
err = c.handleAgentInfoResponse(typedMsg, stream.stream)
case *msgAuthCapabilities:
err = c.handleAuthCapabilities(typedMsg, stream.stream)
case *msgAuthSpake2NeedPsk:
err = c.handleAuthSpake2NeedPsk(typedMsg, stream.stream)
case *msgAuthSpake2Handshake:
err = c.handleAuthSpake2Handshake(typedMsg, stream.stream)
case *msgAuthSpake2Confirmation:
err = c.handleAuthSpake2Confirmation(typedMsg, stream.stream)
case *msgAuthStatus:
err = c.handleAuthStatus(typedMsg, stream.stream)
case *msgDataExchangeStartRequest:
err = c.handleDataExchangeStartRequest(typedMsg, stream)
case *msgDataTransportStartRequest:
err = c.handleDataTransportStartRequest(typedMsg, struct{}{})
case *msgDataTransportStreamRequest:
err = c.handleDataTransportStreamRequest(typedMsg, stream)
default:
fmt.Printf("baseConnection: unhandled message type: %T\n", typedMsg)
}
if err != nil {
return err
}
return nil
}
type connectedState struct {
acceptDataChannel chan *DataChannel
acceptTransport chan *Transport
acceptTransportStream chan *baseStream
}
func (c *baseConnection) handleDataExchangeStartRequest(msg *msgDataExchangeStartRequest, stream *baseStream) error {
dc := &DataChannel{
DataChannelParameters: DataChannelParameters{
Label: msg.Label,
ID: msg.ExchangeId,
Protocol: msg.Protocol,
},
stream: stream.stream,
}
stream.SetHandler(nil)
// TODO: send data-exchange-start-response
c.mu.Lock()
close := c.close
accept := c.connectedState.acceptDataChannel
c.mu.Unlock()
select {
case <-close:
return c.err()
case accept <- dc:
return nil
}
}
func (c *baseConnection) handleDataTransportStartRequest(msg *msgDataTransportStartRequest, info struct{}) error {
c.mu.Lock()
t, err := c.createDataTransport()
if err != nil {
c.mu.Unlock()
return err
}
c.mu.Unlock()
// TODO: send data-transport-start-response
c.mu.Lock()
close := c.close
accept := c.connectedState.acceptTransport
c.mu.Unlock()
select {
case <-close:
return c.err()
case accept <- t:
return nil
}
}
// Caller should hold the connection lock
func (c *baseConnection) createDataTransport() (*Transport, error) {
t := &Transport{
conn: c,
}
return t, nil
}
func (c *baseConnection) handleDataTransportStreamRequest(msg *msgDataTransportStreamRequest, stream *baseStream) error {
// Stop message handling for this stream
stream.SetHandler(nil)
// TODO: send data-transport-stream-response
c.mu.Lock()
close := c.close
accept := c.connectedState.acceptTransportStream
c.mu.Unlock()
if accept == nil {
fmt.Printf("handleDataTransportStreamRequest: no transport, ignoring stream request\n")
return nil // No-one is listening
}
select {
case <-close: