forked from DNAProject/DNA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
link.go
234 lines (198 loc) · 5.37 KB
/
link.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
/*
* Copyright (C) 2018 The DNA Authors
* This file is part of The DNA library.
*
* The DNA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The DNA. If not, see <http://www.gnu.org/licenses/>.
*/
package link
import (
"bufio"
"errors"
"fmt"
"net"
"time"
comm "github.com/dnaproject2/DNA/common"
"github.com/dnaproject2/DNA/common/log"
"github.com/dnaproject2/DNA/p2pserver/common"
"github.com/dnaproject2/DNA/p2pserver/message/types"
)
//Link used to establish
type Link struct {
id uint64
addr string // The address of the node
conn net.Conn // Connect socket with the peer node
port uint16 // The server port of the node
time time.Time // The latest time the node activity
recvChan chan *types.MsgPayload //msgpayload channel
reqRecord map[string]int64 //Map RequestId to Timestamp, using for rejecting duplicate request in specific time
}
func NewLink() *Link {
link := &Link{
reqRecord: make(map[string]int64, 0),
}
return link
}
//SetID set peer id to link
func (this *Link) SetID(id uint64) {
this.id = id
}
//GetID return if from peer
func (this *Link) GetID() uint64 {
return this.id
}
//If there is connection return true
func (this *Link) Valid() bool {
return this.conn != nil
}
//set message channel for link layer
func (this *Link) SetChan(msgchan chan *types.MsgPayload) {
this.recvChan = msgchan
}
//get address
func (this *Link) GetAddr() string {
return this.addr
}
//set address
func (this *Link) SetAddr(addr string) {
this.addr = addr
}
//set port number
func (this *Link) SetPort(p uint16) {
this.port = p
}
//get port number
func (this *Link) GetPort() uint16 {
return this.port
}
//get connection
func (this *Link) GetConn() net.Conn {
return this.conn
}
//set connection
func (this *Link) SetConn(conn net.Conn) {
this.conn = conn
}
//record latest message time
func (this *Link) UpdateRXTime(t time.Time) {
this.time = t
}
//GetRXTime return the latest message time
func (this *Link) GetRXTime() time.Time {
return this.time
}
func (this *Link) Rx() {
conn := this.conn
if conn == nil {
return
}
reader := bufio.NewReaderSize(conn, common.MAX_BUF_LEN)
for {
msg, payloadSize, err := types.ReadMessage(reader)
if err != nil {
log.Infof("[p2p]error read from %s :%s", this.GetAddr(), err.Error())
break
}
t := time.Now()
this.UpdateRXTime(t)
if !this.needSendMsg(msg) {
log.Debugf("skip handle msgType:%s from:%d", msg.CmdType(), this.id)
continue
}
this.addReqRecord(msg)
this.recvChan <- &types.MsgPayload{
Id: this.id,
Addr: this.addr,
PayloadSize: payloadSize,
Payload: msg,
}
}
this.disconnectNotify()
}
//disconnectNotify push disconnect msg to channel
func (this *Link) disconnectNotify() {
log.Debugf("[p2p]call disconnectNotify for %s", this.GetAddr())
this.CloseConn()
msg, _ := types.MakeEmptyMessage(common.DISCONNECT_TYPE)
discMsg := &types.MsgPayload{
Id: this.id,
Addr: this.addr,
Payload: msg,
}
this.recvChan <- discMsg
}
//close connection
func (this *Link) CloseConn() {
if this.conn != nil {
this.conn.Close()
this.conn = nil
}
}
func (this *Link) Send(msg types.Message) error {
sink := comm.NewZeroCopySink(nil)
types.WriteMessage(sink, msg)
return this.SendRaw(sink.Bytes())
}
func (this *Link) SendRaw(rawPacket []byte) error {
conn := this.conn
if conn == nil {
return errors.New("[p2p]tx link invalid")
}
nByteCnt := len(rawPacket)
log.Tracef("[p2p]TX buf length: %d\n", nByteCnt)
nCount := nByteCnt / common.PER_SEND_LEN
if nCount == 0 {
nCount = 1
}
conn.SetWriteDeadline(time.Now().Add(time.Duration(nCount*common.WRITE_DEADLINE) * time.Second))
_, err := conn.Write(rawPacket)
if err != nil {
log.Infof("[p2p]error sending messge to %s :%s", this.GetAddr(), err.Error())
this.disconnectNotify()
return err
}
return nil
}
//needSendMsg check whether the msg is needed to push to channel
func (this *Link) needSendMsg(msg types.Message) bool {
if msg.CmdType() != common.GET_DATA_TYPE {
return true
}
var dataReq = msg.(*types.DataReq)
reqID := fmt.Sprintf("%x%s", dataReq.DataType, dataReq.Hash.ToHexString())
now := time.Now().Unix()
if t, ok := this.reqRecord[reqID]; ok {
if int(now-t) < common.REQ_INTERVAL {
return false
}
}
return true
}
//addReqRecord add request record by removing outdated request records
func (this *Link) addReqRecord(msg types.Message) {
if msg.CmdType() != common.GET_DATA_TYPE {
return
}
now := time.Now().Unix()
if len(this.reqRecord) >= common.MAX_REQ_RECORD_SIZE-1 {
for id := range this.reqRecord {
t := this.reqRecord[id]
if int(now-t) > common.REQ_INTERVAL {
delete(this.reqRecord, id)
}
}
}
var dataReq = msg.(*types.DataReq)
reqID := fmt.Sprintf("%x%s", dataReq.DataType, dataReq.Hash.ToHexString())
this.reqRecord[reqID] = now
}