-
-
Notifications
You must be signed in to change notification settings - Fork 621
/
protocol.go
82 lines (65 loc) · 1.34 KB
/
protocol.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
package udp
import (
"bytes"
"encoding/binary"
"io"
)
type Action int32
const (
ActionConnect Action = iota
ActionAnnounce
ActionScrape
ActionError
)
const ConnectRequestConnectionId = 0x41727101980
const (
// BEP 41
optionTypeEndOfOptions = 0
optionTypeNOP = 1
optionTypeURLData = 2
)
type TransactionId = int32
type ConnectionId = uint64
type ConnectionRequest struct {
ConnectionId ConnectionId
Action Action
TransactionId TransactionId
}
type ConnectionResponse struct {
ConnectionId ConnectionId
}
type ResponseHeader struct {
Action Action
TransactionId TransactionId
}
type RequestHeader struct {
ConnectionId ConnectionId
Action Action
TransactionId TransactionId
} // 16 bytes
type AnnounceResponseHeader struct {
Interval int32
Leechers int32
Seeders int32
}
type InfoHash = [20]byte
func marshal(data interface{}) (b []byte, err error) {
var buf bytes.Buffer
err = Write(&buf, data)
b = buf.Bytes()
return
}
func mustMarshal(data interface{}) []byte {
b, err := marshal(data)
if err != nil {
panic(err)
}
return b
}
// This is for fixed-size, builtin types only I think.
func Write(w io.Writer, data interface{}) error {
return binary.Write(w, binary.BigEndian, data)
}
func Read(r io.Reader, data interface{}) error {
return binary.Read(r, binary.BigEndian, data)
}