-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
clientconn.go
814 lines (736 loc) · 23.7 KB
/
clientconn.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
package client
import (
"context"
"errors"
"fmt"
"io"
"net"
"sync/atomic"
"time"
"github.com/plgd-dev/go-coap/v2/message"
"github.com/plgd-dev/go-coap/v2/message/codes"
coapNet "github.com/plgd-dev/go-coap/v2/net"
"github.com/plgd-dev/go-coap/v2/net/blockwise"
"github.com/plgd-dev/go-coap/v2/net/monitor/inactivity"
"github.com/plgd-dev/go-coap/v2/pkg/cache"
"github.com/plgd-dev/go-coap/v2/pkg/sync"
udpMessage "github.com/plgd-dev/go-coap/v2/udp/message"
"github.com/plgd-dev/go-coap/v2/udp/message/pool"
atomicTypes "go.uber.org/atomic"
)
// https://datatracker.ietf.org/doc/html/rfc7252#section-4.8.2
const ExchangeLifetime = 247 * time.Second
type (
HandlerFunc = func(*ResponseWriter, *pool.Message)
ErrorFunc = func(error)
GoPoolFunc = func(func()) error
EventFunc = func()
GetMIDFunc = func() uint16
)
type Session interface {
Context() context.Context
Close() error
MaxMessageSize() uint32
RemoteAddr() net.Addr
LocalAddr() net.Addr
WriteMessage(req *pool.Message) error
// WriteMulticast sends multicast to the remote multicast address.
// By default it is sent over all network interfaces and all compatible source IP addresses with hop limit 1.
// Via opts you can specify the network interface, source IP address, and hop limit.
WriteMulticastMessage(req *pool.Message, address *net.UDPAddr, opts ...coapNet.MulticastOption) error
Run(cc *ClientConn) error
AddOnClose(f EventFunc)
SetContextValue(key interface{}, val interface{})
Done() <-chan struct{}
}
type RequestsMap = sync.Map[uint64, *pool.Message]
// ClientConn represents a virtual connection to a conceptual endpoint, to perform COAPs commands.
type ClientConn struct {
// This field needs to be the first in the struct to ensure proper word alignment on 32-bit platforms.
// See: https://golang.org/pkg/sync/atomic/#pkg-note-BUG
sequence uint64
session Session
inactivityMonitor inactivity.Monitor
blockWise *blockwise.BlockWise
handler HandlerFunc
observationTokenHandler *HandlerContainer
observationRequests *RequestsMap
transmission *Transmission
messagePool *pool.Pool
goPool GoPoolFunc
errors ErrorFunc
responseMsgCache *cache.Cache
msgIDMutex *MutexMap
tokenHandlerContainer *HandlerContainer
midHandlerContainer *HandlerContainer
msgID uint32
blockwiseSZX blockwise.SZX
}
// Transmission is a threadsafe container for transmission related parameters
type Transmission struct {
nStart *atomicTypes.Duration
acknowledgeTimeout *atomicTypes.Duration
maxRetransmit *atomicTypes.Int32
}
func (t *Transmission) SetTransmissionNStart(d time.Duration) {
t.nStart.Store(d)
}
func (t *Transmission) SetTransmissionAcknowledgeTimeout(d time.Duration) {
t.acknowledgeTimeout.Store(d)
}
func (t *Transmission) SetTransmissionMaxRetransmit(d int32) {
t.maxRetransmit.Store(d)
}
func (cc *ClientConn) Transmission() *Transmission {
return cc.transmission
}
// NewClientConn creates connection over session and observation.
func NewClientConn(
session Session,
observationTokenHandler *HandlerContainer,
observationRequests *RequestsMap,
transmissionNStart time.Duration,
transmissionAcknowledgeTimeout time.Duration,
transmissionMaxRetransmit uint32,
handler HandlerFunc,
blockwiseSZX blockwise.SZX,
blockWise *blockwise.BlockWise,
goPool GoPoolFunc,
errors ErrorFunc,
getMID GetMIDFunc,
inactivityMonitor inactivity.Monitor,
responseMsgCache *cache.Cache,
messagePool *pool.Pool,
) *ClientConn {
if errors == nil {
errors = func(error) {
// default no-op
}
}
if getMID == nil {
getMID = udpMessage.GetMID
}
return &ClientConn{
msgID: uint32(getMID() - 0xffff/2),
session: session,
observationTokenHandler: observationTokenHandler,
observationRequests: observationRequests,
transmission: &Transmission{
atomicTypes.NewDuration(transmissionNStart),
atomicTypes.NewDuration(transmissionAcknowledgeTimeout),
atomicTypes.NewInt32(int32(transmissionMaxRetransmit)),
},
handler: handler,
blockwiseSZX: blockwiseSZX,
blockWise: blockWise,
tokenHandlerContainer: NewHandlerContainer(),
midHandlerContainer: NewHandlerContainer(),
goPool: goPool,
errors: errors,
msgIDMutex: NewMutexMap(),
responseMsgCache: responseMsgCache,
inactivityMonitor: inactivityMonitor,
messagePool: messagePool,
}
}
func (cc *ClientConn) Session() Session {
return cc.session
}
func (cc *ClientConn) getMID() uint16 {
return uint16(atomic.AddUint32(&cc.msgID, 1))
}
// Close closes connection without waiting for the end of the Run function.
func (cc *ClientConn) Close() error {
err := cc.session.Close()
if errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
func (cc *ClientConn) do(req *pool.Message) (*pool.Message, error) {
token := req.Token()
if token == nil {
return nil, fmt.Errorf("invalid token")
}
respChan := make(chan *pool.Message, 1)
err := cc.tokenHandlerContainer.Insert(token, func(w *ResponseWriter, r *pool.Message) {
r.Hijack()
select {
case respChan <- r:
default:
}
})
if err != nil {
return nil, fmt.Errorf("cannot add token handler: %w", err)
}
defer func() {
_, _ = cc.tokenHandlerContainer.Pop(token)
}()
err = cc.writeMessage(req)
if err != nil {
return nil, fmt.Errorf("cannot write request: %w", err)
}
select {
case <-req.Context().Done():
return nil, req.Context().Err()
case <-cc.session.Context().Done():
return nil, fmt.Errorf("connection was closed: %w", cc.session.Context().Err())
case resp := <-respChan:
return resp, nil
}
}
// Do sends an coap message and returns an coap response.
//
// An error is returned if by failure to speak COAP (such as a network connectivity problem).
// Any status code doesn't cause an error.
//
// Caller is responsible to release request and response.
func (cc *ClientConn) Do(req *pool.Message) (*pool.Message, error) {
if cc.blockWise == nil {
req.UpsertMessageID(cc.getMID())
return cc.do(req)
}
bwresp, err := cc.blockWise.Do(req, cc.blockwiseSZX, cc.session.MaxMessageSize(), func(bwreq blockwise.Message) (blockwise.Message, error) {
req := bwreq.(*pool.Message)
if req.Options().HasOption(message.Block1) || req.Options().HasOption(message.Block2) {
req.SetMessageID(cc.getMID())
} else {
req.UpsertMessageID(cc.getMID())
}
return cc.do(req)
})
if err != nil {
return nil, err
}
return bwresp.(*pool.Message), nil
}
func (cc *ClientConn) writeMessage(req *pool.Message) error {
respChan := make(chan struct{})
// Only confirmable messages ever match an message ID
if req.Type() == udpMessage.Confirmable {
err := cc.midHandlerContainer.Insert(req.MessageID(), func(w *ResponseWriter, r *pool.Message) {
close(respChan)
if r.IsSeparate() {
// separate message - just accept
return
}
cc.handleBW(w, r)
})
if err != nil {
return fmt.Errorf("cannot insert mid handler: %w", err)
}
defer func() {
_, _ = cc.midHandlerContainer.Pop(req.MessageID())
}()
}
err := cc.session.WriteMessage(req)
if err != nil {
return fmt.Errorf("cannot write request: %w", err)
}
if req.Type() != udpMessage.Confirmable {
// If the request is not confirmable, we do not need to wait for a response
// and skip retransmissions
close(respChan)
}
maxRetransmit := cc.transmission.maxRetransmit.Load()
for i := int32(0); i < maxRetransmit; i++ {
select {
case <-respChan:
return nil
case <-req.Context().Done():
return req.Context().Err()
case <-cc.Context().Done():
return fmt.Errorf("connection was closed: %w", cc.Context().Err())
case <-time.After(cc.transmission.acknowledgeTimeout.Load()):
select {
case <-req.Context().Done():
return req.Context().Err()
case <-cc.session.Context().Done():
return fmt.Errorf("connection was closed: %w", cc.Context().Err())
case <-time.After(cc.transmission.nStart.Load()):
err = cc.session.WriteMessage(req)
if err != nil {
return fmt.Errorf("cannot write request: %w", err)
}
}
}
}
return fmt.Errorf("timeout: retransmission(%v) was exhausted", cc.transmission.maxRetransmit.Load())
}
// WriteMessage sends an coap message.
func (cc *ClientConn) WriteMessage(req *pool.Message) error {
if cc.blockWise == nil {
req.UpsertMessageID(cc.getMID())
return cc.writeMessage(req)
}
return cc.blockWise.WriteMessage(cc.RemoteAddr(), req, cc.blockwiseSZX, cc.session.MaxMessageSize(), func(bwreq blockwise.Message) error {
req := bwreq.(*pool.Message)
if req.Options().HasOption(message.Block1) || req.Options().HasOption(message.Block2) {
req.SetMessageID(cc.getMID())
} else {
req.UpsertMessageID(cc.getMID())
}
return cc.writeMessage(req)
})
}
func newCommonRequest(ctx context.Context, messagePool *pool.Pool, code codes.Code, path string, opts ...message.Option) (*pool.Message, error) {
token, err := message.GetToken()
if err != nil {
return nil, fmt.Errorf("cannot get token: %w", err)
}
req := messagePool.AcquireMessage(ctx)
req.SetCode(code)
req.SetToken(token)
req.ResetOptionsTo(opts)
if err := req.SetPath(path); err != nil {
messagePool.ReleaseMessage(req)
return nil, err
}
req.SetType(udpMessage.Confirmable)
return req, nil
}
// NewGetRequest creates get request.
//
// Use ctx to set timeout.
func NewGetRequest(ctx context.Context, messagePool *pool.Pool, path string, opts ...message.Option) (*pool.Message, error) {
return newCommonRequest(ctx, messagePool, codes.GET, path, opts...)
}
// Get issues a GET to the specified path.
//
// Use ctx to set timeout.
//
// An error is returned if by failure to speak COAP (such as a network connectivity problem).
// Any status code doesn't cause an error.
func (cc *ClientConn) Get(ctx context.Context, path string, opts ...message.Option) (*pool.Message, error) {
req, err := NewGetRequest(ctx, cc.messagePool, path, opts...)
if err != nil {
return nil, fmt.Errorf("cannot create get request: %w", err)
}
defer cc.ReleaseMessage(req)
return cc.Do(req)
}
// NewPostRequest creates post request.
//
// Use ctx to set timeout.
//
// An error is returned if by failure to speak COAP (such as a network connectivity problem).
// Any status code doesn't cause an error.
//
// If payload is nil then content format is not used.
func NewPostRequest(ctx context.Context, messagePool *pool.Pool, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*pool.Message, error) {
req, err := newCommonRequest(ctx, messagePool, codes.POST, path, opts...)
if err != nil {
return nil, err
}
if payload != nil {
req.SetContentFormat(contentFormat)
req.SetBody(payload)
}
return req, nil
}
// Post issues a POST to the specified path.
//
// Use ctx to set timeout.
//
// An error is returned if by failure to speak COAP (such as a network connectivity problem).
// Any status code doesn't cause an error.
//
// If payload is nil then content format is not used.
func (cc *ClientConn) Post(ctx context.Context, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*pool.Message, error) {
req, err := NewPostRequest(ctx, cc.messagePool, path, contentFormat, payload, opts...)
if err != nil {
return nil, fmt.Errorf("cannot create post request: %w", err)
}
defer cc.ReleaseMessage(req)
return cc.Do(req)
}
// NewPutRequest creates put request.
//
// Use ctx to set timeout.
//
// If payload is nil then content format is not used.
func NewPutRequest(ctx context.Context, messagePool *pool.Pool, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*pool.Message, error) {
req, err := newCommonRequest(ctx, messagePool, codes.PUT, path, opts...)
if err != nil {
return nil, err
}
if payload != nil {
req.SetContentFormat(contentFormat)
req.SetBody(payload)
}
return req, nil
}
// Put issues a PUT to the specified path.
//
// Use ctx to set timeout.
//
// An error is returned if by failure to speak COAP (such as a network connectivity problem).
// Any status code doesn't cause an error.
//
// If payload is nil then content format is not used.
func (cc *ClientConn) Put(ctx context.Context, path string, contentFormat message.MediaType, payload io.ReadSeeker, opts ...message.Option) (*pool.Message, error) {
req, err := NewPutRequest(ctx, cc.messagePool, path, contentFormat, payload, opts...)
if err != nil {
return nil, fmt.Errorf("cannot create put request: %w", err)
}
defer cc.ReleaseMessage(req)
return cc.Do(req)
}
// NewDeleteRequest creates delete request.
//
// Use ctx to set timeout.
func NewDeleteRequest(ctx context.Context, messagePool *pool.Pool, path string, opts ...message.Option) (*pool.Message, error) {
return newCommonRequest(ctx, messagePool, codes.DELETE, path, opts...)
}
// Delete deletes the resource identified by the request path.
//
// Use ctx to set timeout.
func (cc *ClientConn) Delete(ctx context.Context, path string, opts ...message.Option) (*pool.Message, error) {
req, err := NewDeleteRequest(ctx, cc.messagePool, path, opts...)
if err != nil {
return nil, fmt.Errorf("cannot create delete request: %w", err)
}
defer cc.ReleaseMessage(req)
return cc.Do(req)
}
// Context returns the client's context.
//
// If connections was closed context is cancelled.
func (cc *ClientConn) Context() context.Context {
return cc.session.Context()
}
// Ping issues a PING to the client and waits for PONG response.
//
// Use ctx to set timeout.
func (cc *ClientConn) Ping(ctx context.Context) error {
resp := make(chan bool, 1)
receivedPong := func() {
select {
case resp <- true:
default:
}
}
cancel, err := cc.AsyncPing(receivedPong)
if err != nil {
return err
}
defer cancel()
select {
case <-resp:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// AsyncPing sends ping and receivedPong will be called when pong arrives. It returns cancellation of ping operation.
func (cc *ClientConn) AsyncPing(receivedPong func()) (func(), error) {
req := cc.AcquireMessage(cc.Context())
defer cc.ReleaseMessage(req)
req.SetType(udpMessage.Confirmable)
req.SetCode(codes.Empty)
mid := cc.getMID()
req.SetMessageID(mid)
err := cc.midHandlerContainer.Insert(mid, func(w *ResponseWriter, r *pool.Message) {
if r.Type() == udpMessage.Reset || r.Type() == udpMessage.Acknowledgement {
receivedPong()
}
})
if err != nil {
return nil, fmt.Errorf("cannot insert mid handler: %w", err)
}
removeMidHandler := func() {
_, _ = cc.midHandlerContainer.Pop(mid)
}
err = cc.session.WriteMessage(req)
if err != nil {
removeMidHandler()
return nil, fmt.Errorf("cannot write request: %w", err)
}
return removeMidHandler, nil
}
// Run reads and process requests from a connection, until the connection is closed.
func (cc *ClientConn) Run() error {
return cc.session.Run(cc)
}
// AddOnClose calls function on close connection event.
func (cc *ClientConn) AddOnClose(f EventFunc) {
cc.session.AddOnClose(f)
}
func (cc *ClientConn) RemoteAddr() net.Addr {
return cc.session.RemoteAddr()
}
func (cc *ClientConn) LocalAddr() net.Addr {
return cc.session.LocalAddr()
}
func (cc *ClientConn) sendPong(w *ResponseWriter, r *pool.Message) {
if err := w.SetResponse(codes.Empty, message.TextPlain, nil); err != nil {
cc.errors(fmt.Errorf("cannot send pong response: %w", err))
}
}
type bwResponseWriter struct {
w *ResponseWriter
}
func (b *bwResponseWriter) Message() blockwise.Message {
return b.w.response
}
func (b *bwResponseWriter) SetMessage(m blockwise.Message) {
b.w.cc.ReleaseMessage(b.w.response)
b.w.response = m.(*pool.Message)
}
func (b *bwResponseWriter) RemoteAddr() net.Addr {
return b.w.cc.RemoteAddr()
}
func (cc *ClientConn) handleBW(w *ResponseWriter, m *pool.Message) {
if cc.blockWise != nil {
bwr := bwResponseWriter{
w: w,
}
cc.blockWise.Handle(&bwr, m, cc.blockwiseSZX, cc.session.MaxMessageSize(), func(bw blockwise.ResponseWriter, br blockwise.Message) {
h, err := cc.tokenHandlerContainer.Pop(m.Token())
rw := bw.(*bwResponseWriter).w
rm := br.(*pool.Message)
if err == nil {
h(rw, rm)
return
}
cc.handler(rw, rm)
})
return
}
h, err := cc.tokenHandlerContainer.Pop(m.Token())
if err == nil {
h(w, m)
return
}
cc.handler(w, m)
}
func (cc *ClientConn) handle(w *ResponseWriter, r *pool.Message) {
if r.Code() == codes.Empty && r.Type() == udpMessage.Confirmable && len(r.Token()) == 0 && len(r.Options()) == 0 && r.Body() == nil {
cc.sendPong(w, r)
return
}
h, err := cc.midHandlerContainer.Pop(r.MessageID())
if err == nil {
h(w, r)
return
}
if r.IsSeparate() {
// msg was processed by token handler - just drop it.
return
}
cc.handleBW(w, r)
}
// Sequence acquires sequence number.
func (cc *ClientConn) Sequence() uint64 {
return atomic.AddUint64(&cc.sequence, 1)
}
func (cc *ClientConn) responseMsgCacheID(msgID uint16) string {
return fmt.Sprintf("resp-%v-%d", cc.RemoteAddr(), msgID)
}
func (cc *ClientConn) addResponseToCache(resp *pool.Message) error {
marshaledResp, err := resp.Marshal()
if err != nil {
return err
}
cacheMsg := make([]byte, len(marshaledResp))
copy(cacheMsg, marshaledResp)
cc.responseMsgCache.LoadOrStore(cc.responseMsgCacheID(resp.MessageID()), cache.NewElement(cacheMsg, time.Now().Add(ExchangeLifetime), nil))
return nil
}
func (cc *ClientConn) getResponseFromCache(mid uint16, resp *pool.Message) (bool, error) {
cachedResp := cc.responseMsgCache.Load(cc.responseMsgCacheID(mid))
if cachedResp == nil {
return false, nil
}
if rawMsg, ok := cachedResp.Data().([]byte); ok {
_, err := resp.Unmarshal(rawMsg)
if err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// CheckMyMessageID compare client msgID against peer messageID and if it is near < 0xffff/4 then incrase msgID.
// When msgIDs met it can cause issue because cache can send message to which doesn't bellows to request.
func (cc *ClientConn) CheckMyMessageID(req *pool.Message) {
if req.Type() == udpMessage.Confirmable && req.MessageID()-uint16(atomic.LoadUint32(&cc.msgID)) < 0xffff/4 {
atomic.AddUint32(&cc.msgID, 0xffff/2)
}
}
func (cc *ClientConn) checkResponseCache(req *pool.Message, w *ResponseWriter) (bool, error) {
if req.Type() == udpMessage.Confirmable || req.Type() == udpMessage.NonConfirmable {
if ok, err := cc.getResponseFromCache(req.MessageID(), w.response); ok {
w.response.SetMessageID(req.MessageID())
w.response.SetType(udpMessage.NonConfirmable)
if req.Type() == udpMessage.Confirmable {
// req could be changed from NonConfirmation to confirmation message.
w.response.SetType(udpMessage.Acknowledgement)
}
return true, nil
} else if err != nil {
return false, fmt.Errorf("cannot unmarshal response from cache: %w", err)
}
}
return false, nil
}
func isPongOrResetResponse(w *ResponseWriter) bool {
return w.response.IsModified() && (w.response.Type() == udpMessage.Reset || w.response.Code() == codes.Empty)
}
func sendJustAcknowledgeMessage(reqType udpMessage.Type, w *ResponseWriter) bool {
return reqType == udpMessage.Confirmable && !w.response.IsModified()
}
func (cc *ClientConn) processResponse(reqType udpMessage.Type, reqMessageID uint16, w *ResponseWriter) error {
switch {
case isPongOrResetResponse(w):
if reqType == udpMessage.Confirmable {
w.response.SetType(udpMessage.Acknowledgement)
w.response.SetMessageID(reqMessageID)
} else {
if w.response.Type() != udpMessage.Reset {
w.response.SetType(udpMessage.NonConfirmable)
}
w.response.SetMessageID(cc.getMID())
}
return nil
case sendJustAcknowledgeMessage(reqType, w):
// send message to separate(confirm received) message, if response is not modified
w.response.SetCode(codes.Empty)
w.response.SetType(udpMessage.Acknowledgement)
w.response.SetMessageID(reqMessageID)
w.response.SetToken(nil)
err := cc.addResponseToCache(w.response)
if err != nil {
return fmt.Errorf("cannot cache response: %w", err)
}
return nil
case !w.response.IsModified():
// don't send response
return nil
}
// send piggybacked response
w.response.SetType(udpMessage.Confirmable)
w.response.SetMessageID(cc.getMID())
if reqType == udpMessage.Confirmable {
w.response.SetType(udpMessage.Acknowledgement)
w.response.SetMessageID(reqMessageID)
}
if reqType == udpMessage.Confirmable || reqType == udpMessage.NonConfirmable {
err := cc.addResponseToCache(w.response)
if err != nil {
return fmt.Errorf("cannot cache response: %w", err)
}
}
return nil
}
func (cc *ClientConn) processReq(req *pool.Message, w *ResponseWriter) error {
defer cc.inactivityMonitor.Notify()
reqMid := req.MessageID()
// The same message ID can not be handled concurrently
// for deduplication to work
l := cc.msgIDMutex.Lock(reqMid)
defer l.Unlock()
if ok, err := cc.checkResponseCache(req, w); err != nil {
return err
} else if ok {
return nil
}
w.response.SetModified(false)
reqType := req.Type()
reqMessageID := req.MessageID()
cc.handle(w, req)
return cc.processResponse(reqType, reqMessageID, w)
}
func (cc *ClientConn) Process(datagram []byte) error {
if uint32(len(datagram)) > cc.session.MaxMessageSize() {
return fmt.Errorf("max message size(%v) was exceeded %v", cc.session.MaxMessageSize(), len(datagram))
}
req := cc.AcquireMessage(cc.Context())
_, err := req.Unmarshal(datagram)
if err != nil {
cc.ReleaseMessage(req)
return err
}
closeConnection := func() {
if errC := cc.Close(); errC != nil {
cc.errors(fmt.Errorf("cannot close connection: %w", errC))
}
}
req.SetSequence(cc.Sequence())
cc.CheckMyMessageID(req)
cc.inactivityMonitor.Notify()
err = cc.goPool(func() {
defer func() {
if !req.IsHijacked() {
cc.ReleaseMessage(req)
}
}()
resp := cc.AcquireMessage(cc.Context())
resp.SetToken(req.Token())
w := NewResponseWriter(resp, cc, req.Options())
defer func() {
cc.ReleaseMessage(w.response)
}()
errP := cc.processReq(req, w)
if errP != nil {
closeConnection()
cc.errors(fmt.Errorf("cannot write response: %w", errP))
return
}
if !w.response.IsModified() {
// nothing to send
return
}
errW := cc.writeMessage(w.response)
if errW != nil {
closeConnection()
cc.errors(fmt.Errorf("cannot write response: %w", errW))
}
})
if err != nil {
cc.ReleaseMessage(req)
return err
}
return nil
}
func (cc *ClientConn) Client() *Client {
return NewClient(cc)
}
// SetContextValue stores the value associated with key to context of connection.
func (cc *ClientConn) SetContextValue(key interface{}, val interface{}) {
cc.session.SetContextValue(key, val)
}
// Done signalizes that connection is not more processed.
func (cc *ClientConn) Done() <-chan struct{} {
return cc.session.Done()
}
// CheckExpirations checks and remove expired items from caches.
func (cc *ClientConn) CheckExpirations(now time.Time) {
cc.inactivityMonitor.CheckInactivity(now, cc)
if cc.blockWise != nil {
cc.blockWise.CheckExpirations(now)
}
}
func (cc *ClientConn) AcquireMessage(ctx context.Context) *pool.Message {
return cc.messagePool.AcquireMessage(ctx)
}
func (cc *ClientConn) ReleaseMessage(m *pool.Message) {
cc.messagePool.ReleaseMessage(m)
}
// WriteMulticastMessage sends multicast to the remote multicast address.
// By default it is sent over all network interfaces and all compatible source IP addresses with hop limit 1.
// Via opts you can specify the network interface, source IP address, and hop limit.
func (cc *ClientConn) WriteMulticastMessage(req *pool.Message, address *net.UDPAddr, options ...coapNet.MulticastOption) error {
if req.Type() == udpMessage.Confirmable {
return fmt.Errorf("multicast messages cannot be confirmable")
}
req.SetMessageID(cc.getMID())
err := cc.session.WriteMulticastMessage(req, address, options...)
if err != nil {
return fmt.Errorf("cannot write request: %w", err)
}
return nil
}
func (cc *ClientConn) InactivityMonitor() inactivity.Monitor {
return cc.inactivityMonitor
}