-
Notifications
You must be signed in to change notification settings - Fork 7
/
lpd.go
128 lines (108 loc) · 2.4 KB
/
lpd.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
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"net"
"net/http"
"strings"
"time"
)
var (
request_template = "BT-SEARCH * HTTP/1.1\r\n" +
"Host: 239.192.152.143:6771\r\n" +
"Port: %d\r\n" +
"Infohash: %X\r\n\r\n"
)
type Announce struct {
peer string
infohash string
}
type Announcer struct {
btPort int
addr *net.UDPAddr
conn *net.UDPConn
announces chan *Announce
activeAnnounces map[string]*time.Ticker
}
func NewAnnouncer(listenPort int) (lpd *Announcer, err error) {
addr, err := net.ResolveUDPAddr("udp4", "239.192.152.143:6771")
if err != nil {
return
}
conn, err := net.ListenMulticastUDP("udp4", nil, addr)
if err != nil {
return
}
activeAnnounces := make(map[string]*time.Ticker)
lpd = &Announcer{
btPort: listenPort,
addr: addr,
conn: conn,
announces: make(chan *Announce),
activeAnnounces: activeAnnounces,
}
go lpd.run()
return
}
func (lpd *Announcer) run() {
for {
answer := make([]byte, 256)
_, from, err := lpd.conn.ReadFromUDP(answer)
if err != nil {
log.Println("Error reading from UDP: ", err)
continue
}
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(answer)))
if err != nil {
log.Println("Error reading HTTP request from UDP: ", err)
continue
}
if req.Method != "BT-SEARCH" {
log.Println("Invalid method: ", req.Method)
}
ih := req.Header.Get("Infohash")
if ih == "" {
log.Println("No Infohash")
continue
}
ih = strings.ToLower(ih)
port := req.Header.Get("Port")
if port == "" {
log.Println("No port")
continue
}
addr, err := net.ResolveTCPAddr("tcp4", from.IP.String()+":"+port)
if err != nil {
log.Println(err)
continue
}
lpd.announces <- &Announce{addr.String(), ih}
}
}
func (lpd *Announcer) Announce(ih string) {
go func() {
requestMessage := []byte(fmt.Sprintf(request_template, lpd.btPort,
ih))
// Announce at launch, then every 5 minutes
_, err := lpd.conn.WriteToUDP(requestMessage, lpd.addr)
if err != nil {
log.Println(err)
}
ticker := time.NewTicker(5 * time.Minute)
lpd.activeAnnounces[ih] = ticker
for _ = range ticker.C {
_, err := lpd.conn.WriteToUDP(requestMessage, lpd.addr)
if err != nil {
log.Println(err)
}
}
}()
}
func (lpd *Announcer) StopAnnouncing(ih string) {
if ticker, ok := lpd.activeAnnounces[ih]; ok {
ticker.Stop()
delete(lpd.activeAnnounces, ih)
}
}