aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/connection.go
blob: e999cbe55f7b1cafd31d7eacb37182de92d299bb (plain) (blame)
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
package p2p

import (
    "bytes"
    // "fmt"
    "net"
    "time"

    "github.com/ethereum/eth-go/ethutil"
)

type Connection struct {
    conn net.Conn
    // conn       NetworkConnection
    timeout    time.Duration
    in         chan []byte
    out        chan []byte
    err        chan *PeerError
    closingIn  chan chan bool
    closingOut chan chan bool
}

// const readBufferLength = 2 //for testing

const readBufferLength = 1440
const partialsQueueSize = 10
const maxPendingQueueSize = 1
const defaultTimeout = 500

var magicToken = []byte{34, 64, 8, 145}

func (self *Connection) Open() {
    go self.startRead()
    go self.startWrite()
}

func (self *Connection) Close() {
    self.closeIn()
    self.closeOut()
}

func (self *Connection) closeIn() {
    errc := make(chan bool)
    self.closingIn <- errc
    <-errc
}

func (self *Connection) closeOut() {
    errc := make(chan bool)
    self.closingOut <- errc
    <-errc
}

func NewConnection(conn net.Conn, errchan chan *PeerError) *Connection {
    return &Connection{
        conn:       conn,
        timeout:    defaultTimeout,
        in:         make(chan []byte),
        out:        make(chan []byte),
        err:        errchan,
        closingIn:  make(chan chan bool, 1),
        closingOut: make(chan chan bool, 1),
    }
}

func (self *Connection) Read() <-chan []byte {
    return self.in
}

func (self *Connection) Write() chan<- []byte {
    return self.out
}

func (self *Connection) Error() <-chan *PeerError {
    return self.err
}

func (self *Connection) startRead() {
    payloads := make(chan []byte)
    done := make(chan *PeerError)
    pending := [][]byte{}
    var head []byte
    var wait time.Duration // initally 0 (no delay)
    read := time.After(wait * time.Millisecond)

    for {
        // if pending empty, nil channel blocks
        var in chan []byte
        if len(pending) > 0 {
            in = self.in // enable send case
            head = pending[0]
        } else {
            in = nil
        }

        select {
        case <-read:
            go self.read(payloads, done)
        case err := <-done:
            if err == nil { // no error but nothing to read
                if len(pending) < maxPendingQueueSize {
                    wait = 100
                } else if wait == 0 {
                    wait = 100
                } else {
                    wait = 2 * wait
                }
            } else {
                self.err <- err // report error
                wait = 100
            }
            read = time.After(wait * time.Millisecond)
        case payload := <-payloads:
            pending = append(pending, payload)
            if len(pending) < maxPendingQueueSize {
                wait = 0
            } else {
                wait = 100
            }
            read = time.After(wait * time.Millisecond)
        case in <- head:
            pending = pending[1:]
        case errc := <-self.closingIn:
            errc <- true
            close(self.in)
            return
        }

    }
}

func (self *Connection) startWrite() {
    pending := [][]byte{}
    done := make(chan *PeerError)
    writing := false
    for {
        if len(pending) > 0 && !writing {
            writing = true
            go self.write(pending[0], done)
        }
        select {
        case payload := <-self.out:
            pending = append(pending, payload)
        case err := <-done:
            if err == nil {
                pending = pending[1:]
                writing = false
            } else {
                self.err <- err // report error
            }
        case errc := <-self.closingOut:
            errc <- true
            close(self.out)
            return
        }
    }
}

func pack(payload []byte) (packet []byte) {
    length := ethutil.NumberToBytes(uint32(len(payload)), 32)
    // return error if too long?
    // Write magic token and payload length (first 8 bytes)
    packet = append(magicToken, length...)
    packet = append(packet, payload...)
    return
}

func avoidPanic(done chan *PeerError) {
    if rec := recover(); rec != nil {
        err := NewPeerError(MiscError, " %v", rec)
        logger.Debugln(err)
        done <- err
    }
}

func (self *Connection) write(payload []byte, done chan *PeerError) {
    defer avoidPanic(done)
    var err *PeerError
    _, ok := self.conn.Write(pack(payload))
    if ok != nil {
        err = NewPeerError(WriteError, " %v", ok)
        logger.Debugln(err)
    }
    done <- err
}

func (self *Connection) read(payloads chan []byte, done chan *PeerError) {
    //defer avoidPanic(done)

    partials := make(chan []byte, partialsQueueSize)
    errc := make(chan *PeerError)
    go self.readPartials(partials, errc)

    packet := []byte{}
    length := 8
    start := true
    var err *PeerError
out:
    for {
        // appends partials read via connection until packet is
        // - either parseable (>=8bytes)
        // - or complete (payload fully consumed)
        for len(packet) < length {
            partial, ok := <-partials
            if !ok { // partials channel is closed
                err = <-errc
                if err == nil && len(packet) > 0 {
                    if start {
                        err = NewPeerError(PacketTooShort, "%v", packet)
                    } else {
                        err = NewPeerError(PayloadTooShort, "%d < %d", len(packet), length)
                    }
                }
                break out
            }
            packet = append(packet, partial...)
        }
        if start {
            // at least 8 bytes read, can validate packet
            if bytes.Compare(magicToken, packet[:4]) != 0 {
                err = NewPeerError(MagicTokenMismatch, " received %v", packet[:4])
                break
            }
            length = int(ethutil.BytesToNumber(packet[4:8]))
            packet = packet[8:]

            if length > 0 {
                start = false // now consuming payload
            } else { //penalize peer but read on
                self.err <- NewPeerError(EmptyPayload, "")
                length = 8
            }
        } else {
            // packet complete (payload fully consumed)
            payloads <- packet[:length]
            packet = packet[length:] // resclice packet
            start = true
            length = 8
        }
    }

    // this stops partials read via the connection, should we?
    //if err != nil {
    //  select {
    //    case errc <- err
    //  default:
    //}
    done <- err
}

func (self *Connection) readPartials(partials chan []byte, errc chan *PeerError) {
    defer close(partials)
    for {
        // Give buffering some time
        self.conn.SetReadDeadline(time.Now().Add(self.timeout * time.Millisecond))
        buffer := make([]byte, readBufferLength)
        // read partial from connection
        bytesRead, err := self.conn.Read(buffer)
        if err == nil || err.Error() == "EOF" {
            if bytesRead > 0 {
                partials <- buffer[:bytesRead]
            }
            if err != nil && err.Error() == "EOF" {
                break
            }
        } else {
            // unexpected error, report to errc
            err := NewPeerError(ReadError, " %v", err)
            logger.Debugln(err)
            errc <- err
            return // will close partials channel
        }
    }
    close(errc)
}