-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
326 lines (275 loc) · 8.78 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
package vv104
import (
"bytes"
"fmt"
"net"
"time"
)
func (state *State) startConnection() {
if state.Config.Mode == "server" {
logInfo.Println("Starting Server")
state.startServer()
} else if state.Config.Mode == "client" {
logInfo.Println("Starting Client")
state.startClient()
} else {
panic("can not start, config mode is neither server nor client")
}
}
func (state *State) startServer() {
logDebug.Println("startServer started")
defer logDebug.Println("startServer returned")
var err error
ipAndPortStr := state.Config.Ipv4Addr + ":" + fmt.Sprint(state.Config.Port)
ipAndPort, err := net.ResolveTCPAddr("tcp", ipAndPortStr)
if err != nil {
panic(err)
}
var l *net.TCPListener
l, err = net.ListenTCP("tcp", ipAndPort)
if err != nil {
panic(err)
}
l.SetDeadline(time.Now().Add(2 * time.Second))
defer l.Close()
state.Wg.Add(1)
defer state.Wg.Done()
for {
select {
default:
conn, err := l.Accept()
if err != nil {
if err, ok := err.(*net.OpError); ok && err.Timeout() {
// it was a timeout
// logDebug.Println("timeout")a
l.SetDeadline(time.Now().Add(2 * time.Second))
continue
}
// other problem
logError.Println("accept error (not timeout)", err)
continue
}
logInfo.Println("Connected from: ", conn.RemoteAddr())
state.TcpConnected = true
go state.receivingRoutine(conn)
go state.sendingRoutine(conn)
go state.connectionStateMachine()
go state.timerRoutine()
<-state.Ctx.Done() // todo? other criteria?
state.TcpConnected = false
return
case <-state.Ctx.Done():
logDebug.Println("startServer received Done(), returns")
state.TcpConnected = false
return
}
}
}
func (state *State) startClient() {
logDebug.Println("startClient started")
defer logDebug.Println("startClient returned")
var err error
ipAndPortStr := state.Config.Ipv4Addr + ":" + fmt.Sprint(state.Config.Port)
ipAndPort, err := net.ResolveTCPAddr("tcp", ipAndPortStr)
if err != nil {
panic(err)
}
state.Wg.Add(1)
defer state.Wg.Done()
for {
select {
default:
conn, err := net.DialTCP("tcp", nil, ipAndPort)
if err != nil {
logError.Println("dial error", err)
time.Sleep(1 * time.Second)
continue
}
logInfo.Println("Connected to:", conn.RemoteAddr())
state.TcpConnected = true
go state.receivingRoutine(conn)
go state.sendingRoutine(conn)
go state.connectionStateMachine()
go state.timerRoutine()
<-state.Ctx.Done() // todo? other criteria?
state.TcpConnected = false
return
case <-state.Ctx.Done():
logDebug.Println("startClient received Done(), returns")
state.TcpConnected = false
return
}
}
}
func (state *State) receivingRoutine(conn net.Conn) {
logDebug.Println("receivingRoutine started")
defer logDebug.Println("receivingRoutine returned")
defer conn.Close()
var bytesbuf bytes.Buffer
buf := make([]byte, 1024)
state.Wg.Add(1)
defer state.Wg.Done()
for {
select {
default:
err := conn.SetReadDeadline(time.Now().Add(3 * time.Second))
if err != nil {
logError.Println(err)
}
recvLen, err := conn.Read(buf)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
// logDebug.Println(err)
continue
}
logError.Println("Error reading:", err.Error())
logDebug.Println("Restart because of error reading, receivingRoutine returns")
state.Cancel()
return
}
bytesbuf.Write(buf[:recvLen]) // Read from conn directly into bytesbuf?
var receivedApdus []Apdu
receivedApdus, err = ParseApdu(&bytesbuf)
bytesbuf.Reset()
if err != nil {
logError.Println("error parsing:", err)
logDebug.Println("bytes:", bytesbuf)
continue
}
for _, receivedApdu := range receivedApdus {
if receivedApdu.Apci.FrameFormat == IFormatFrame {
// each received I-Format must be acknowledged
// this should be done directly after receiving (not in another goroutine, because of race conditions) (?)
state.recvAck.queueApdu(receivedApdu)
if state.recvAck.openFrames == 1 {
// was 0 before, new open frame
state.tickers.t2tickerReceivedItems.Reset(time.Duration(state.Config.T2) * time.Second)
}
weMustAck, seqNumberToAck := state.recvAck.checkForAck(state.Config.W)
if weMustAck {
// logDebug.Println("we must ack received items because w values open")
sframe := NewApdu()
sframe.Apci.FrameFormat = SFormatFrame
sframe.Apci.Rsn = seqNumberToAck
state.Chans.ToSend <- sframe
}
}
if receivedApdu.Apci.FrameFormat == IFormatFrame || receivedApdu.Apci.FrameFormat == SFormatFrame {
// each received I- or S-Format acknowledges some of our sent frames
state.sendAck.ackApdu(receivedApdu.Apci.Rsn, state.tickers.t2tickerSentItems, time.Duration(state.Config.T2)*time.Second)
}
state.Chans.Received <- receivedApdu
}
case <-state.Ctx.Done():
logError.Println("receivingRoutine received Done(), returns")
return
}
}
}
func (state *State) sendingRoutine(conn net.Conn) {
logDebug.Println("sendingRoutine started")
defer logDebug.Println("sendingRoutine returned")
defer conn.Close()
var apduToSend Apdu
var buf []byte
var err error
state.Wg.Add(1)
defer state.Wg.Done()
for {
select {
case apduToSend = <-state.Chans.ToSend:
buf, err = apduToSend.Serialize(*state)
// logDebug.Println(buf)
if err != nil {
logError.Println("error serializing apdu", err)
continue
}
if apduToSend.Apci.UFormat == StopDTAct || apduToSend.Apci.UFormat == StartDTAct {
// notify state machine
state.dt_act_sent = apduToSend.Apci.UFormat
apduNotify := NewApdu()
apduNotify.Asdu.TypeId = INTERNAL_STATE_MACHINE_NOTIFIER
state.Chans.Received <- apduNotify
}
if state.ConnState != STARTED {
if apduToSend.Apci.FrameFormat == IFormatFrame {
logError.Println("IEC 104 connection is not started. Can not send I-Format")
continue
}
} else {
// started
if state.sendAck.openFrames >= state.Config.K {
// we must not send anymore, wait for acknowledgement
logError.Println("we must not send anymore, wait for acknowledgement TODO")
// TODO block on a channel
}
}
logInfo.Println("TX>>:", state.Objects.objNameOrIoa(apduToSend.Asdu), apduToSend)
err := conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if err != nil {
logDebug.Println(err)
}
_, err = conn.Write(buf)
if err != nil {
logError.Println("error sending apdu", err)
logError.Println("Error sending:", err.Error())
logError.Println("Restart because of error sending, sendingRoutine returns")
state.Cancel()
return
}
if apduToSend.Apci.FrameFormat == SFormatFrame || apduToSend.Apci.FrameFormat == IFormatFrame {
// by sending an s- or i-format we have acknowledged items
state.recvAck.ackApdu(apduToSend.Apci.Rsn, state.tickers.t2tickerReceivedItems, time.Duration(state.Config.T2)*time.Second)
}
if apduToSend.Apci.FrameFormat == IFormatFrame {
// each sent frame must be ack'ed by the communication partner in a certain time
state.sendAck.queueApdu(apduToSend)
if state.sendAck.openFrames == 1 {
// was 0 before, new open frame
state.tickers.t2tickerSentItems.Reset(time.Duration(state.Config.T2+1) * time.Second)
}
}
case <-state.Ctx.Done():
logDebug.Println("sendingRoutine received Done(), returns")
return
}
}
}
func (state *State) timerRoutine() {
logDebug.Println("timerRoutine started")
defer logDebug.Println("timerRoutine returned")
state.Wg.Add(1)
defer state.Wg.Done()
state.tickers.t1ticker = time.NewTicker(time.Duration(state.Config.T1) * time.Second)
state.tickers.t2tickerReceivedItems = time.NewTicker(time.Duration(state.Config.T2) * time.Second)
state.tickers.t2tickerReceivedItems.Stop()
state.tickers.t2tickerSentItems = time.NewTicker(time.Duration(state.Config.T2+1) * time.Second)
state.tickers.t2tickerSentItems.Stop()
state.tickers.t3ticker = time.NewTicker(time.Duration(state.Config.T3-4) * time.Second)
for {
select {
// case <-state.tickers.t1ticker.C:
// logDebug.Println("t1 TIMEOUT")
case <-state.tickers.t2tickerReceivedItems.C:
if state.recvAck.openFrames > 0 {
// logDebug.Println("we must ack received items because t2 timeout")
sframe := NewApdu()
sframe.Apci.FrameFormat = SFormatFrame
sframe.Apci.Rsn = state.recvAck.seqNumber
state.Chans.ToSend <- sframe
}
case <-state.tickers.t2tickerSentItems.C:
logError.Println("the communication partner did not acknowledge in the specified time, quitting...")
state.Cancel()
case <-state.tickers.t3ticker.C:
// logDebug.Println("t3 TIMEOUT")
state.Chans.CommandsFromStdin <- "testfr_act"
case <-state.Ctx.Done():
logDebug.Println("timerRoutine received Done(), returns")
return
}
}
}
func checkIpV4Address(ipAddr string) bool {
return net.ParseIP(ipAddr) != nil
}