-
Notifications
You must be signed in to change notification settings - Fork 18
/
peer_conn.go
81 lines (65 loc) · 1.49 KB
/
peer_conn.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
package meshboi
import (
"net"
"time"
log "github.com/sirupsen/logrus"
"inet.af/netaddr"
)
const bufSize = 65535
// Represents a connection to a peer
type PeerConn struct {
// The IP address within the VPN
insideIP netaddr.IP
// The IP address over the internet
outsideAddr netaddr.IPPort
// Time of last contact
lastContacted time.Time
// the connection to the peer
conn net.Conn
outgoing chan []byte
tun TunConn
}
func NewPeerConn(insideIP netaddr.IP, outsideAddr netaddr.IPPort, conn net.Conn, tun TunConn) PeerConn {
return PeerConn{
insideIP: insideIP, // maybe these dont need to be inside the peer. could just be in the peer store
outsideAddr: outsideAddr,
conn: conn,
tun: tun,
lastContacted: time.Now(),
outgoing: make(chan []byte),
}
}
func (p *PeerConn) QueueData(data []byte) {
p.outgoing <- data
}
func (p *PeerConn) readLoop() {
b := make([]byte, bufSize)
for {
n, err := p.conn.Read(b)
if err != nil {
panic(err)
}
p.lastContacted = time.Now()
written, err := p.tun.Write(b[:n])
if err != nil {
panic(err)
}
if written != n {
log.Warn("Not all data written to tun")
}
}
}
// Chat starts the stdin readloop to dispatch messages to the hub
func (p *PeerConn) sendLoop() {
for {
data := <-p.outgoing
n, err := p.conn.Write(data)
if err != nil {
log.Error("Error sending over UDP conn: ", err)
continue
}
if n != len(data) {
log.Warn("Not all data written to peer")
}
}
}