|
| 1 | +package p2p |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + // "fmt" |
| 6 | + "net" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/ethereum/eth-go/ethutil" |
| 10 | +) |
| 11 | + |
| 12 | +type Connection struct { |
| 13 | + conn net.Conn |
| 14 | + // conn NetworkConnection |
| 15 | + timeout time.Duration |
| 16 | + in chan []byte |
| 17 | + out chan []byte |
| 18 | + err chan *PeerError |
| 19 | + closingIn chan chan bool |
| 20 | + closingOut chan chan bool |
| 21 | +} |
| 22 | + |
| 23 | +// const readBufferLength = 2 //for testing |
| 24 | + |
| 25 | +const readBufferLength = 1440 |
| 26 | +const partialsQueueSize = 10 |
| 27 | +const maxPendingQueueSize = 1 |
| 28 | +const defaultTimeout = 500 |
| 29 | + |
| 30 | +var magicToken = []byte{34, 64, 8, 145} |
| 31 | + |
| 32 | +func (self *Connection) Open() { |
| 33 | + go self.startRead() |
| 34 | + go self.startWrite() |
| 35 | +} |
| 36 | + |
| 37 | +func (self *Connection) Close() { |
| 38 | + self.closeIn() |
| 39 | + self.closeOut() |
| 40 | +} |
| 41 | + |
| 42 | +func (self *Connection) closeIn() { |
| 43 | + errc := make(chan bool) |
| 44 | + self.closingIn <- errc |
| 45 | + <-errc |
| 46 | +} |
| 47 | + |
| 48 | +func (self *Connection) closeOut() { |
| 49 | + errc := make(chan bool) |
| 50 | + self.closingOut <- errc |
| 51 | + <-errc |
| 52 | +} |
| 53 | + |
| 54 | +func NewConnection(conn net.Conn, errchan chan *PeerError) *Connection { |
| 55 | + return &Connection{ |
| 56 | + conn: conn, |
| 57 | + timeout: defaultTimeout, |
| 58 | + in: make(chan []byte), |
| 59 | + out: make(chan []byte), |
| 60 | + err: errchan, |
| 61 | + closingIn: make(chan chan bool, 1), |
| 62 | + closingOut: make(chan chan bool, 1), |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func (self *Connection) Read() <-chan []byte { |
| 67 | + return self.in |
| 68 | +} |
| 69 | + |
| 70 | +func (self *Connection) Write() chan<- []byte { |
| 71 | + return self.out |
| 72 | +} |
| 73 | + |
| 74 | +func (self *Connection) Error() <-chan *PeerError { |
| 75 | + return self.err |
| 76 | +} |
| 77 | + |
| 78 | +func (self *Connection) startRead() { |
| 79 | + payloads := make(chan []byte) |
| 80 | + done := make(chan *PeerError) |
| 81 | + pending := [][]byte{} |
| 82 | + var head []byte |
| 83 | + var wait time.Duration // initally 0 (no delay) |
| 84 | + read := time.After(wait * time.Millisecond) |
| 85 | + |
| 86 | + for { |
| 87 | + // if pending empty, nil channel blocks |
| 88 | + var in chan []byte |
| 89 | + if len(pending) > 0 { |
| 90 | + in = self.in // enable send case |
| 91 | + head = pending[0] |
| 92 | + } else { |
| 93 | + in = nil |
| 94 | + } |
| 95 | + |
| 96 | + select { |
| 97 | + case <-read: |
| 98 | + go self.read(payloads, done) |
| 99 | + case err := <-done: |
| 100 | + if err == nil { // no error but nothing to read |
| 101 | + if len(pending) < maxPendingQueueSize { |
| 102 | + wait = 100 |
| 103 | + } else if wait == 0 { |
| 104 | + wait = 100 |
| 105 | + } else { |
| 106 | + wait = 2 * wait |
| 107 | + } |
| 108 | + } else { |
| 109 | + self.err <- err // report error |
| 110 | + wait = 100 |
| 111 | + } |
| 112 | + read = time.After(wait * time.Millisecond) |
| 113 | + case payload := <-payloads: |
| 114 | + pending = append(pending, payload) |
| 115 | + if len(pending) < maxPendingQueueSize { |
| 116 | + wait = 0 |
| 117 | + } else { |
| 118 | + wait = 100 |
| 119 | + } |
| 120 | + read = time.After(wait * time.Millisecond) |
| 121 | + case in <- head: |
| 122 | + pending = pending[1:] |
| 123 | + case errc := <-self.closingIn: |
| 124 | + errc <- true |
| 125 | + close(self.in) |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +func (self *Connection) startWrite() { |
| 133 | + pending := [][]byte{} |
| 134 | + done := make(chan *PeerError) |
| 135 | + writing := false |
| 136 | + for { |
| 137 | + if len(pending) > 0 && !writing { |
| 138 | + writing = true |
| 139 | + go self.write(pending[0], done) |
| 140 | + } |
| 141 | + select { |
| 142 | + case payload := <-self.out: |
| 143 | + pending = append(pending, payload) |
| 144 | + case err := <-done: |
| 145 | + if err == nil { |
| 146 | + pending = pending[1:] |
| 147 | + writing = false |
| 148 | + } else { |
| 149 | + self.err <- err // report error |
| 150 | + } |
| 151 | + case errc := <-self.closingOut: |
| 152 | + errc <- true |
| 153 | + close(self.out) |
| 154 | + return |
| 155 | + } |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +func pack(payload []byte) (packet []byte) { |
| 160 | + length := ethutil.NumberToBytes(uint32(len(payload)), 32) |
| 161 | + // return error if too long? |
| 162 | + // Write magic token and payload length (first 8 bytes) |
| 163 | + packet = append(magicToken, length...) |
| 164 | + packet = append(packet, payload...) |
| 165 | + return |
| 166 | +} |
| 167 | + |
| 168 | +func avoidPanic(done chan *PeerError) { |
| 169 | + if rec := recover(); rec != nil { |
| 170 | + err := NewPeerError(MiscError, " %v", rec) |
| 171 | + logger.Debugln(err) |
| 172 | + done <- err |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +func (self *Connection) write(payload []byte, done chan *PeerError) { |
| 177 | + defer avoidPanic(done) |
| 178 | + var err *PeerError |
| 179 | + _, ok := self.conn.Write(pack(payload)) |
| 180 | + if ok != nil { |
| 181 | + err = NewPeerError(WriteError, " %v", ok) |
| 182 | + logger.Debugln(err) |
| 183 | + } |
| 184 | + done <- err |
| 185 | +} |
| 186 | + |
| 187 | +func (self *Connection) read(payloads chan []byte, done chan *PeerError) { |
| 188 | + //defer avoidPanic(done) |
| 189 | + |
| 190 | + partials := make(chan []byte, partialsQueueSize) |
| 191 | + errc := make(chan *PeerError) |
| 192 | + go self.readPartials(partials, errc) |
| 193 | + |
| 194 | + packet := []byte{} |
| 195 | + length := 8 |
| 196 | + start := true |
| 197 | + var err *PeerError |
| 198 | +out: |
| 199 | + for { |
| 200 | + // appends partials read via connection until packet is |
| 201 | + // - either parseable (>=8bytes) |
| 202 | + // - or complete (payload fully consumed) |
| 203 | + for len(packet) < length { |
| 204 | + partial, ok := <-partials |
| 205 | + if !ok { // partials channel is closed |
| 206 | + err = <-errc |
| 207 | + if err == nil && len(packet) > 0 { |
| 208 | + if start { |
| 209 | + err = NewPeerError(PacketTooShort, "%v", packet) |
| 210 | + } else { |
| 211 | + err = NewPeerError(PayloadTooShort, "%d < %d", len(packet), length) |
| 212 | + } |
| 213 | + } |
| 214 | + break out |
| 215 | + } |
| 216 | + packet = append(packet, partial...) |
| 217 | + } |
| 218 | + if start { |
| 219 | + // at least 8 bytes read, can validate packet |
| 220 | + if bytes.Compare(magicToken, packet[:4]) != 0 { |
| 221 | + err = NewPeerError(MagicTokenMismatch, " received %v", packet[:4]) |
| 222 | + break |
| 223 | + } |
| 224 | + length = int(ethutil.BytesToNumber(packet[4:8])) |
| 225 | + packet = packet[8:] |
| 226 | + |
| 227 | + if length > 0 { |
| 228 | + start = false // now consuming payload |
| 229 | + } else { //penalize peer but read on |
| 230 | + self.err <- NewPeerError(EmptyPayload, "") |
| 231 | + length = 8 |
| 232 | + } |
| 233 | + } else { |
| 234 | + // packet complete (payload fully consumed) |
| 235 | + payloads <- packet[:length] |
| 236 | + packet = packet[length:] // resclice packet |
| 237 | + start = true |
| 238 | + length = 8 |
| 239 | + } |
| 240 | + } |
| 241 | + |
| 242 | + // this stops partials read via the connection, should we? |
| 243 | + //if err != nil { |
| 244 | + // select { |
| 245 | + // case errc <- err |
| 246 | + // default: |
| 247 | + //} |
| 248 | + done <- err |
| 249 | +} |
| 250 | + |
| 251 | +func (self *Connection) readPartials(partials chan []byte, errc chan *PeerError) { |
| 252 | + defer close(partials) |
| 253 | + for { |
| 254 | + // Give buffering some time |
| 255 | + self.conn.SetReadDeadline(time.Now().Add(self.timeout * time.Millisecond)) |
| 256 | + buffer := make([]byte, readBufferLength) |
| 257 | + // read partial from connection |
| 258 | + bytesRead, err := self.conn.Read(buffer) |
| 259 | + if err == nil || err.Error() == "EOF" { |
| 260 | + if bytesRead > 0 { |
| 261 | + partials <- buffer[:bytesRead] |
| 262 | + } |
| 263 | + if err != nil && err.Error() == "EOF" { |
| 264 | + break |
| 265 | + } |
| 266 | + } else { |
| 267 | + // unexpected error, report to errc |
| 268 | + err := NewPeerError(ReadError, " %v", err) |
| 269 | + logger.Debugln(err) |
| 270 | + errc <- err |
| 271 | + return // will close partials channel |
| 272 | + } |
| 273 | + } |
| 274 | + close(errc) |
| 275 | +} |
0 commit comments