-
Notifications
You must be signed in to change notification settings - Fork 387
/
UDPCommunicationsModule.go
331 lines (276 loc) · 8.25 KB
/
UDPCommunicationsModule.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package bacnetip
import (
"context"
"fmt"
"github.com/apache/plc4x/plc4go/spi/options"
"github.com/rs/zerolog"
"net"
"time"
"github.com/apache/plc4x/plc4go/protocols/bacnetip/readwrite/model"
"github.com/libp2p/go-reuseport"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
//go:generate go run ../../tools/plc4xgenerator/gen.go -type=UDPActor
type UDPActor struct {
director *UDPDirector
timeout uint32
timer *OneShotFunctionTask
peer string
}
func NewUDPActor(director *UDPDirector, peer string) *UDPActor {
a := &UDPActor{}
// keep track of the director
a.director = director
// associated with a peer
a.peer = peer
// Add a timer
a.timeout = director.timeout
if a.timeout > 0 {
a.timer = FunctionTask(a.idleTimeout)
when := time.Now().Add(time.Duration(a.timeout) * time.Millisecond)
a.timer.InstallTask(&when, nil)
}
// tell the director this is a new actor
a.director.AddActor(a)
return a
}
func (a *UDPActor) idleTimeout() error {
log.Debug().Msg("idleTimeout")
// tell the director this is gone
a.director.DelActor(a)
return nil
}
func (a *UDPActor) Indication(pdu _PDU) error {
log.Debug().Stringer("pdu", pdu).Msg("Indication")
// reschedule the timer
if a.timer != nil {
when := time.Now().Add(time.Duration(a.timeout) * time.Millisecond)
a.timer.InstallTask(&when, nil)
}
// put it in the outbound queue for the director
a.director.request <- pdu
return nil
}
func (a *UDPActor) Response(pdu _PDU) error {
log.Debug().Stringer("pdu", pdu).Msg("Response")
// reschedule the timer
if a.timer != nil {
when := time.Now().Add(time.Duration(a.timeout) * time.Millisecond)
a.timer.InstallTask(&when, nil)
}
// process this as a response from the director
return a.director.Response(pdu)
}
func (a *UDPActor) HandleError(err error) {
log.Debug().Err(err).Msg("HandleError")
if err != nil {
a.director.ActorError(err)
}
}
type UDPDirector struct {
*Server
*ServiceAccessPoint
timeout uint32
reuse bool
address AddressTuple[string, uint16]
udpConn *net.UDPConn
actorClass func(*UDPDirector, string) *UDPActor
request chan _PDU
peers map[string]*UDPActor
running bool
passLogToModel bool
log zerolog.Logger
}
func NewUDPDirector(address AddressTuple[string, uint16], timeout *int, reuse *bool, sid *int, sapID *int) (*UDPDirector, error) {
d := &UDPDirector{}
var err error
d.Server, err = NewServer(sid, d)
if err != nil {
return nil, errors.Wrap(err, "error creating server")
}
d.ServiceAccessPoint, err = NewServiceAccessPoint(sapID, d)
if err != nil {
return nil, errors.Wrap(err, "error creating service access point")
}
// check the actor class
d.actorClass = NewUDPActor
// save the timeout for actors
if timeout != nil {
d.timeout = uint32(*timeout)
}
if reuse != nil {
d.reuse = *reuse
}
// save the address
d.address = address
// ask the dispatcher for a socket
resolvedAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", address.Left, address.Right))
if err != nil {
return nil, errors.Wrap(err, "error resolving udp address")
}
if d.reuse {
if packetConn, err := reuseport.ListenPacket("udp", resolvedAddress.String()); err != nil {
return nil, errors.Wrap(err, "error connecting to local address")
} else {
d.udpConn = packetConn.(*net.UDPConn)
}
} else {
if d.udpConn, err = net.ListenUDP("udp", resolvedAddress); err != nil {
return nil, errors.Wrap(err, "error connecting to local address")
}
}
d.running = true
go func() {
for d.running {
d.handleRead()
}
}()
// create the request queue
d.request = make(chan _PDU)
go func() {
for d.running {
pdu := <-d.request
serialize, err := pdu.GetMessage().Serialize()
if err != nil {
log.Error().Err(err).Msg("Error building message")
continue
}
// TODO: wonky address object
destination := pdu.GetPDUDestination()
addr := net.IPv4(destination.AddrAddress[0], destination.AddrAddress[1], destination.AddrAddress[2], destination.AddrAddress[3])
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", addr, *destination.AddrPort))
if err != nil {
log.Error().Err(err).Msg("Error resolving address")
continue
}
writtenBytes, err := d.udpConn.WriteToUDP(serialize, udpAddr)
if err != nil {
log.Error().Err(err).Msg("Error writing bytes")
continue
}
log.Debug().Int("writtenBytes", writtenBytes).Msg("written bytes")
}
}()
// start with an empty peer pool
d.peers = map[string]*UDPActor{}
return d, nil
}
// AddActor adds an actor when a new one is connected
func (d *UDPDirector) AddActor(actor *UDPActor) {
log.Debug().Stringer("actor", actor).Msg("AddActor %v")
d.peers[actor.peer] = actor
// tell the ASE there is a new client
if d.serviceElement != nil {
// TODO: not sure how to realize that
//d.SapRequest(actor)
}
}
// DelActor removes an actor when the socket is closed.
func (d *UDPDirector) DelActor(actor *UDPActor) {
log.Debug().Stringer("actor", actor).Msg("DelActor")
delete(d.peers, actor.peer)
// tell the ASE the client has gone away
if d.serviceElement != nil {
// TODO: not sure how to realize that
//d.SapRequest(actor)
}
}
func (d *UDPDirector) GetActor(address Address) *UDPActor {
return d.peers[address.String()]
}
func (d *UDPDirector) ActorError(err error) {
// tell the ASE the actor had an error
if d.serviceElement != nil {
// TODO: not sure how to realize that
//d.SapRequest(actor, err)
}
}
func (d *UDPDirector) Close() error {
d.running = false
return d.udpConn.Close()
}
func (d *UDPDirector) handleRead() {
log.Debug().Stringer("address", &d.address).Msg("handleRead")
readBytes := make([]byte, 1500) // TODO: check if that is sufficient
var sourceAddr *net.UDPAddr
if _, addr, err := d.udpConn.ReadFromUDP(readBytes); err != nil {
log.Error().Err(err).Msg("error reading")
return
} else {
sourceAddr = addr
}
ctxForModel := options.GetLoggerContextForModel(context.TODO(), d.log, options.WithPassLoggerToModel(d.passLogToModel))
bvlc, err := model.BVLCParse(ctxForModel, readBytes)
if err != nil {
// pass along to a handler
d.handleError(errors.Wrap(err, "error parsing bvlc"))
return
}
saddr, err := NewAddress(sourceAddr)
if err != nil {
// pass along to a handler
d.handleError(errors.Wrap(err, "error parsing source address"))
return
}
daddr, err := NewAddress(d.udpConn.LocalAddr())
if err != nil {
// pass along to a handler
d.handleError(errors.Wrap(err, "error parsing destination address"))
return
}
pdu := NewPDU(bvlc, WithPDUSource(saddr), WithPDUDestination(daddr))
// send the PDU up to the client
go func() {
if err := d._response(pdu); err != nil {
log.Debug().Err(err).Msg("errored")
}
}()
}
func (d *UDPDirector) handleError(err error) {
log.Debug().Err(err).Msg("handleError")
}
// Indication Client requests are queued for delivery.
func (d *UDPDirector) Indication(pdu _PDU) error {
log.Debug().Stringer("pdu", pdu).Msg("Indication")
// get the destination
addr := pdu.GetPDUDestination()
// get the peer
peer, ok := d.peers[addr.String()]
if !ok {
peer = d.actorClass(d, (*addr).String())
}
// send the message
return peer.Indication(pdu)
}
// _response Incoming datagrams are routed through an actor.
func (d *UDPDirector) _response(pdu _PDU) error {
log.Debug().Stringer("pdu", pdu).Msg("_response")
// get the destination
addr := pdu.GetPDUSource()
// get the peer
peer, ok := d.peers[addr.String()]
if !ok {
peer = d.actorClass(d, addr.String())
}
// send the message
return peer.Response(pdu)
}