-
Notifications
You must be signed in to change notification settings - Fork 0
/
listen_dtls.go
90 lines (73 loc) · 1.71 KB
/
listen_dtls.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package coap
import (
"time"
"github.com/qwerty-iot/dtls/v2"
)
type DtlsListener struct {
name string
socket *dtls.Listener
handler *Server
shutdown bool
}
func (l *DtlsListener) listen(name string, listener *dtls.Listener, handler *Server) error {
l.socket = listener
l.name = name
l.handler = handler
go l.reader()
return nil
}
func (l *DtlsListener) reader() {
rawReq, peer := l.socket.Read()
if l.shutdown {
logDebug(nil, nil, "coap: port is shutdown")
return
}
//launch new reader
go l.reader()
var req Message
if err := req.unmarshalBinary(rawReq); err != nil {
logError(nil, err, "coap: error parsing COAP header")
return
}
req.Meta.RemoteAddr = peer.RemoteAddr()
req.Meta.DtlsPeer = peer
req.Meta.ListenerName = l.name
req.Meta.ReceivedAt = time.Now().UTC()
req.Meta.Server = l.handler
rsp := l.handler.handleMessage(&req)
if rsp != nil {
rawRsp, err := rsp.marshalBinary()
if err != nil {
logError(nil, err, "coap: error marshaling COAP response")
return
}
if rawRsp != nil {
err := peer.Write(rawRsp)
if err != nil {
logWarn(nil, err, "coap: error writing coap response")
}
}
}
return
}
func (l *DtlsListener) FindPeer(addr string) *dtls.Peer {
if l == nil {
return nil
}
peer, _ := l.socket.FindPeer(addr)
return peer
}
func (l *DtlsListener) ClosePeer(addr string) {
if l == nil {
return
}
l.socket.RemovePeerByAddr(addr, dtls.AlertDesc_Noop)
return
}
func (l *DtlsListener) Close() {
l.shutdown = true
_ = l.socket.Shutdown()
}