-
Notifications
You must be signed in to change notification settings - Fork 11
/
listener.go
68 lines (58 loc) · 1.33 KB
/
listener.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
package libtorrent
import (
"fmt"
"net"
)
type Listener struct {
port uint16
torrents map[string]*Torrent
listener net.Listener
}
func NewListener(port uint16) (l *Listener) {
l = &Listener{
port: port,
torrents: make(map[string]*Torrent),
}
return
}
func (l *Listener) AddTorrent(tor *Torrent) {
infoHash := fmt.Sprintf("%x", tor.InfoHash())
l.torrents[infoHash] = tor
}
func (l *Listener) Listen() (err error) {
port := fmt.Sprintf(":%d", l.port)
if l.listener, err = net.Listen("tcp", port); err != nil {
return
}
// Begin accepting incoming peers
go func() {
for {
conn, err := l.listener.Accept()
if err != nil {
logger.Error("Listener unexpectedly quit: %s", err)
return
}
go func() {
hs, err := parseHandshake(conn)
if err != nil {
logger.Error("%s Initial handshake failed: %s", conn.RemoteAddr(), err)
conn.Close()
return
}
infoHash := fmt.Sprintf("%x", hs.infoHash)
if tor, ok := l.torrents[infoHash]; ok {
logger.Debug("%s Incoming peer connection: %s", conn.RemoteAddr(), hs.peerId)
tor.AddPeer(conn, hs)
} else {
logger.Info("%s Incoming peer connection using expired/invalid infohash", conn.RemoteAddr())
conn.Close()
}
return
}()
}
}()
return
}
func (l *Listener) Close() error {
return l.listener.Close()
}