forked from thinkgos/go-iecp5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_session.go
550 lines (492 loc) · 14.3 KB
/
server_session.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
// Copyright 2020 thinkgos (thinkgo@aliyun.com). All rights reserved.
// Use of this source code is governed by a version 3 of the GNU General
// Public License, license that can be found in the LICENSE file.
package cs104
import (
"context"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/jiguorui/go-iecp5/asdu"
"github.com/jiguorui/go-iecp5/clog"
)
const (
initial uint32 = iota
disconnected
connected
)
// SrvSession the cs104 server session
type SrvSession struct {
config *Config
params *asdu.Params
conn net.Conn
handler ServerHandlerInterface
rcvASDU chan []byte // for received asdu
sendASDU chan []byte // for send asdu
rcvRaw chan []byte // for recvLoop raw cs104 frame
sendRaw chan []byte // for sendLoop raw cs104 frame
// see subclass 5.1 — Protection against loss and duplication of messages
seqNoSend uint16 // sequence number of next outbound I-frame
ackNoSend uint16 // outbound sequence number yet to be confirmed
seqNoRcv uint16 // sequence number of next inbound I-frame
ackNoRcv uint16 // inbound sequence number yet to be confirmed
// maps sendTime I-frames to their respective sequence number
pending []seqPending
//seqManage
status uint32
rwMux sync.RWMutex
clog.Clog
onConnection func(asdu.Connect)
connectionLost func(asdu.Connect)
wg sync.WaitGroup
cancel context.CancelFunc
ctx context.Context
}
// RecvLoop feeds t.rcvRaw.
func (sf *SrvSession) recvLoop() {
sf.Debug("recvLoop started!")
defer func() {
sf.cancel()
sf.wg.Done()
sf.Debug("recvLoop stopped!")
}()
for {
rawData := make([]byte, APDUSizeMax)
for rdCnt, length := 0, 2; rdCnt < length; {
byteCount, err := io.ReadFull(sf.conn, rawData[rdCnt:length])
if err != nil {
// See: https://github.com/golang/go/issues/4373
if err != io.EOF && err != io.ErrClosedPipe ||
strings.Contains(err.Error(), "use of closed network connection") {
sf.Error("receive failed, %v", err)
return
}
if e, ok := err.(net.Error); ok && !e.Temporary() {
sf.Error("receive failed, %v", err)
return
}
if byteCount == 0 && err == io.EOF {
sf.Error("remote connect closed, %v", err)
return
}
}
rdCnt += byteCount
if rdCnt == 0 {
continue
} else if rdCnt == 1 {
if rawData[0] != startFrame {
rdCnt = 0
continue
}
} else {
if rawData[0] != startFrame {
rdCnt, length = 0, 2
continue
}
length = int(rawData[1]) + 2
if length < APCICtlFiledSize+2 || length > APDUSizeMax {
rdCnt, length = 0, 2
continue
}
if rdCnt == length {
apdu := rawData[:length]
sf.Debug("RX Raw[% x]", apdu)
sf.rcvRaw <- apdu
}
}
}
}
}
// sendLoop drains t.sendTime.
func (sf *SrvSession) sendLoop() {
sf.Debug("sendLoop started!")
defer func() {
sf.cancel()
sf.wg.Done()
sf.Debug("sendLoop stopped!")
}()
for {
select {
case <-sf.ctx.Done():
return
case apdu := <-sf.sendRaw:
sf.Debug("TX Raw[% x]", apdu)
for wrCnt := 0; len(apdu) > wrCnt; {
byteCount, err := sf.conn.Write(apdu[wrCnt:])
if err != nil {
// See: https://github.com/golang/go/issues/4373
if err != io.EOF && err != io.ErrClosedPipe ||
strings.Contains(err.Error(), "use of closed network connection") {
sf.Error("sendRaw failed, %v", err)
return
}
if e, ok := err.(net.Error); !ok || !e.Temporary() {
sf.Error("sendRaw failed, %v", err)
return
}
// temporary error may be recoverable
}
wrCnt += byteCount
}
}
}
}
// run is the big fat state machine.
func (sf *SrvSession) run(ctx context.Context) {
sf.Debug("run started!")
// before any thing make sure init
sf.cleanUp()
sf.ctx, sf.cancel = context.WithCancel(ctx)
sf.setConnectStatus(connected)
sf.wg.Add(3)
go sf.recvLoop()
go sf.sendLoop()
go sf.handlerLoop()
// default: STOPDT, when connected establish and not enable "data transfer" yet
var isActive = false
var checkTicker = time.NewTicker(timeoutResolution)
// transmission timestamps for timeout calculation
var willNotTimeout = time.Now().Add(time.Hour * 24 * 365 * 100)
var unAckRcvSince = willNotTimeout
var idleTimeout3Sine = time.Now() // 空闲间隔发起testFrAlive
var testFrAliveSendSince = willNotTimeout // 当发起testFrAlive时,等待确认回复的超时间隔
// 对于server端,无需对应的U-Frame 无需判断
// var startDtActiveSendSince = willNotTimeout
// var stopDtActiveSendSince = willNotTimeout
sendSFrame := func(rcvSN uint16) {
sf.Debug("TX sFrame %v", sAPCI{rcvSN})
sf.sendRaw <- newSFrame(rcvSN)
}
sendUFrame := func(which byte) {
sf.Debug("TX uFrame %v", uAPCI{which})
sf.sendRaw <- newUFrame(which)
}
sendIFrame := func(asdu1 []byte) {
seqNo := sf.seqNoSend
iframe, err := newIFrame(seqNo, sf.seqNoRcv, asdu1)
if err != nil {
return
}
sf.ackNoRcv = sf.seqNoRcv
sf.seqNoSend = (seqNo + 1) & 32767
sf.pending = append(sf.pending, seqPending{seqNo & 32767, time.Now()})
sf.Debug("TX iFrame %v", iAPCI{seqNo, sf.seqNoRcv})
sf.sendRaw <- iframe
}
if sf.onConnection != nil {
sf.onConnection(sf)
}
defer func() {
sf.setConnectStatus(disconnected)
checkTicker.Stop()
_ = sf.conn.Close() // 连锁引发cancel
sf.wg.Wait()
if sf.connectionLost != nil {
sf.connectionLost(sf)
}
sf.Debug("run stopped!")
}()
for {
if isActive && seqNoCount(sf.ackNoSend, sf.seqNoSend) <= sf.config.SendUnAckLimitK {
select {
case o := <-sf.sendASDU:
sendIFrame(o)
idleTimeout3Sine = time.Now()
continue
case <-sf.ctx.Done():
return
default: // make no block
}
}
select {
case <-sf.ctx.Done():
return
case now := <-checkTicker.C:
// check all timeouts
if now.Sub(testFrAliveSendSince) >= sf.config.SendUnAckTimeout1 {
// now.Sub(startDtActiveSendSince) >= t.SendUnAckTimeout1 ||
// now.Sub(stopDtActiveSendSince) >= t.SendUnAckTimeout1 ||
sf.Error("test frame alive confirm timeout t₁")
return
}
// check oldest unacknowledged outbound
if sf.ackNoSend != sf.seqNoSend &&
//now.Sub(sf.peek()) >= sf.SendUnAckTimeout1 {
now.Sub(sf.pending[0].sendTime) >= sf.config.SendUnAckTimeout1 {
sf.ackNoSend++
sf.Error("fatal transmission timeout t₁")
//return
}
// 确定最早发送的i-Frame是否超时,超时则回复sFrame
if sf.ackNoRcv != sf.seqNoRcv &&
(now.Sub(unAckRcvSince) >= sf.config.RecvUnAckTimeout2 ||
now.Sub(idleTimeout3Sine) >= timeoutResolution) {
sendSFrame(sf.seqNoRcv)
sf.ackNoRcv = sf.seqNoRcv
}
// 空闲时间到,发送TestFrActive帧,保活
if now.Sub(idleTimeout3Sine) >= sf.config.IdleTimeout3 {
sendUFrame(uTestFrActive)
testFrAliveSendSince = time.Now()
idleTimeout3Sine = testFrAliveSendSince
}
case apdu := <-sf.rcvRaw:
idleTimeout3Sine = time.Now() // 每收到一个i帧,S帧,U帧, 重置空闲定时器, t3
apci, asduVal := parse(apdu)
switch head := apci.(type) {
case sAPCI:
sf.Debug("RX sFrame %v", head)
if !sf.updateAckNoOut(head.rcvSN) {
sf.Error("fatal incoming acknowledge either earlier than previous or later than sendTime")
return
}
case iAPCI:
sf.Debug("RX iFrame %v", head)
if !isActive {
sf.Warn("station not active")
break // not active, discard apdu
}
if !sf.updateAckNoOut(head.rcvSN) || head.sendSN != sf.seqNoRcv {
sf.Error("fatal incoming acknowledge either earlier than previous or later than sendTime")
return
}
sf.rcvASDU <- asduVal
if sf.ackNoRcv == sf.seqNoRcv { // first unacked
unAckRcvSince = time.Now()
}
sf.seqNoRcv = (sf.seqNoRcv + 1) & 32767
if seqNoCount(sf.ackNoRcv, sf.seqNoRcv) >= sf.config.RecvUnAckLimitW {
sendSFrame(sf.seqNoRcv)
sf.ackNoRcv = sf.seqNoRcv
}
case uAPCI:
sf.Debug("RX uFrame %v", head)
switch head.function {
case uStartDtActive:
sendUFrame(uStartDtConfirm)
isActive = true
// case uStartDtConfirm:
// isActive = true
// startDtActiveSendSince = willNotTimeout
case uStopDtActive:
sendUFrame(uStopDtConfirm)
isActive = false
// case uStopDtConfirm:
// isActive = false
// stopDtActiveSendSince = willNotTimeout
case uTestFrActive:
sendUFrame(uTestFrConfirm)
case uTestFrConfirm:
testFrAliveSendSince = willNotTimeout
default:
sf.Error("illegal U-Frame functions[0x%02x] ignored", head.function)
}
}
}
}
}
// handlerLoop handler iFrame asdu
func (sf *SrvSession) handlerLoop() {
sf.Debug("handlerLoop started")
defer func() {
sf.wg.Done()
sf.Debug("handlerLoop stopped")
}()
for {
select {
case <-sf.ctx.Done():
return
case rawAsdu := <-sf.rcvASDU:
asduPack := asdu.NewEmptyASDU(sf.params)
if err := asduPack.UnmarshalBinary(rawAsdu); err != nil {
sf.Error("asdu UnmarshalBinary failed,%+v", err)
continue
}
if err := sf.serverHandler(asduPack); err != nil {
sf.Error("serverHandler falied,%+v", err)
}
}
}
}
func (sf *SrvSession) setConnectStatus(status uint32) {
sf.rwMux.Lock()
atomic.StoreUint32(&sf.status, status)
sf.rwMux.Unlock()
}
func (sf *SrvSession) connectStatus() uint32 {
sf.rwMux.RLock()
status := atomic.LoadUint32(&sf.status)
sf.rwMux.RUnlock()
return status
}
func (sf *SrvSession) cleanUp() {
sf.ackNoRcv = 0
sf.ackNoSend = 0
sf.seqNoRcv = 0
sf.seqNoSend = 0
sf.pending = nil
// clear sending chan buffer
loop:
for {
select {
case <-sf.sendRaw:
case <-sf.rcvRaw:
case <-sf.rcvASDU:
case <-sf.sendASDU:
default:
break loop
}
}
}
// 回绕机制
func seqNoCount(nextAckNo, nextSeqNo uint16) uint16 {
if nextAckNo > nextSeqNo {
nextSeqNo += 32768
}
return nextSeqNo - nextAckNo
}
func (sf *SrvSession) updateAckNoOut(ackNo uint16) (ok bool) {
if ackNo == sf.ackNoSend {
return true
}
// new acks validate, ack 不能在 req seq 前面,出错
if seqNoCount(sf.ackNoSend, sf.seqNoSend) < seqNoCount(ackNo, sf.seqNoSend) {
return false
}
// confirm reception
for i, v := range sf.pending {
if v.seq == (ackNo - 1) {
sf.pending = sf.pending[i+1:]
break
}
}
sf.ackNoSend = ackNo
return true
}
func (sf *SrvSession) serverHandler(asduPack *asdu.ASDU) error {
defer func() {
if err := recover(); err != nil {
sf.Critical("server handler %+v", err)
}
}()
sf.Debug("ASDU %+v", asduPack)
switch asduPack.Identifier.Type {
case asdu.C_IC_NA_1: // InterrogationCmd
if !(asduPack.Identifier.Coa.Cause == asdu.Activation ||
asduPack.Identifier.Coa.Cause == asdu.Deactivation) {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, qoi := asduPack.GetInterrogationCmd()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return sf.handler.InterrogationHandler(sf, asduPack, qoi)
case asdu.C_CI_NA_1: // CounterInterrogationCmd
if asduPack.Identifier.Coa.Cause != asdu.Activation {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, qcc := asduPack.GetCounterInterrogationCmd()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return sf.handler.CounterInterrogationHandler(sf, asduPack, qcc)
case asdu.C_RD_NA_1: // ReadCmd
if asduPack.Identifier.Coa.Cause != asdu.Request {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
return sf.handler.ReadHandler(sf, asduPack, asduPack.GetReadCmd())
case asdu.C_CS_NA_1: // ClockSynchronizationCmd
if asduPack.Identifier.Coa.Cause != asdu.Activation {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, tm := asduPack.GetClockSynchronizationCmd()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return sf.handler.ClockSyncHandler(sf, asduPack, tm)
case asdu.C_TS_NA_1: // TestCommand
if asduPack.Identifier.Coa.Cause != asdu.Activation {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, _ := asduPack.GetTestCommand()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return asduPack.SendReplyMirror(sf, asdu.ActivationCon)
case asdu.C_RP_NA_1: // ResetProcessCmd
if asduPack.Identifier.Coa.Cause != asdu.Activation {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, qrp := asduPack.GetResetProcessCmd()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return sf.handler.ResetProcessHandler(sf, asduPack, qrp)
case asdu.C_CD_NA_1: // DelayAcquireCommand
if !(asduPack.Identifier.Coa.Cause == asdu.Activation ||
asduPack.Identifier.Coa.Cause == asdu.Spontaneous) {
return asduPack.SendReplyMirror(sf, asdu.UnknownCOT)
}
if asduPack.CommonAddr == asdu.InvalidCommonAddr {
return asduPack.SendReplyMirror(sf, asdu.UnknownCA)
}
ioa, msec := asduPack.GetDelayAcquireCommand()
if ioa != asdu.InfoObjAddrIrrelevant {
return asduPack.SendReplyMirror(sf, asdu.UnknownIOA)
}
return sf.handler.DelayAcquisitionHandler(sf, asduPack, msec)
}
if err := sf.handler.ASDUHandler(sf, asduPack); err != nil {
return asduPack.SendReplyMirror(sf, asdu.UnknownTypeID)
}
return nil
}
// IsConnected get server session connected state
func (sf *SrvSession) IsConnected() bool {
return sf.connectStatus() == connected
}
// Params get params
func (sf *SrvSession) Params() *asdu.Params {
return sf.params
}
// Send asdu frame
func (sf *SrvSession) Send(u *asdu.ASDU) error {
if !sf.IsConnected() {
return ErrUseClosedConnection
}
data, err := u.MarshalBinary()
if err != nil {
return err
}
select {
case sf.sendASDU <- data:
default:
return ErrBufferFulled
}
return nil
}
// UnderlyingConn got under net.conn
func (sf *SrvSession) UnderlyingConn() net.Conn {
return sf.conn
}