15 "github.com/anacrolix/dht/v2/krpc"
16 "github.com/anacrolix/missinggo"
17 "github.com/anacrolix/missinggo/pproffd"
18 "github.com/pkg/errors"
24 ActionConnect Action = iota
29 connectRequestConnectionId = 0x41727101980
32 optionTypeEndOfOptions = 0
37 type ConnectionRequest struct {
43 type ConnectionResponse struct {
47 type ResponseHeader struct {
52 type RequestHeader struct {
58 type AnnounceResponseHeader struct {
64 func newTransactionId() int32 {
65 return int32(rand.Uint32())
68 func timeout(contiguousTimeouts int) (d time.Duration) {
69 if contiguousTimeouts > 8 {
70 contiguousTimeouts = 8
73 for ; contiguousTimeouts > 0; contiguousTimeouts-- {
79 type udpAnnounce struct {
80 contiguousTimeouts int
81 connectionIdReceived time.Time
88 func (c *udpAnnounce) Close() error {
90 return c.socket.Close()
95 func (c *udpAnnounce) ipv6() bool {
96 if c.a.UdpNetwork == "udp6" {
99 rip := missinggo.AddrIP(c.socket.RemoteAddr())
100 return rip.To16() != nil && rip.To4() == nil
103 func (c *udpAnnounce) Do(req AnnounceRequest) (res AnnounceResponse, err error) {
108 reqURI := c.url.RequestURI()
112 } else if req.IPAddress == 0 && c.a.ClientIp4.IP != nil {
113 req.IPAddress = binary.BigEndian.Uint32(c.a.ClientIp4.IP.To4())
115 // Clearly this limits the request URI to 255 bytes. BEP 41 supports
116 // longer but I'm not fussed.
117 options := append([]byte{optionTypeURLData, byte(len(reqURI))}, []byte(reqURI)...)
118 b, err := c.request(ActionAnnounce, req, options)
122 var h AnnounceResponseHeader
123 err = readBody(b, &h)
126 err = io.ErrUnexpectedEOF
128 err = fmt.Errorf("error parsing announce response: %s", err)
131 res.Interval = h.Interval
132 res.Leechers = h.Leechers
133 res.Seeders = h.Seeders
134 nas := func() interface {
135 encoding.BinaryUnmarshaler
136 NodeAddrs() []krpc.NodeAddr
139 return &krpc.CompactIPv6NodeAddrs{}
141 return &krpc.CompactIPv4NodeAddrs{}
144 err = nas.UnmarshalBinary(b.Bytes())
148 for _, cp := range nas.NodeAddrs() {
149 res.Peers = append(res.Peers, Peer{}.FromNodeAddr(cp))
154 // body is the binary serializable request body. trailer is optional data
155 // following it, such as for BEP 41.
156 func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) {
158 err = binary.Write(&buf, binary.BigEndian, h)
163 err = binary.Write(&buf, binary.BigEndian, body)
168 _, err = buf.Write(trailer)
172 n, err := c.socket.Write(buf.Bytes())
177 panic("write should send all or error")
182 func read(r io.Reader, data interface{}) error {
183 return binary.Read(r, binary.BigEndian, data)
186 func write(w io.Writer, data interface{}) error {
187 return binary.Write(w, binary.BigEndian, data)
190 // args is the binary serializable request body. trailer is optional data
191 // following it, such as for BEP 41.
192 func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) {
193 tid := newTransactionId()
194 if err := errors.Wrap(
197 ConnectionId: c.connectionId,
205 c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts)))
206 b := make([]byte, 0x800) // 2KiB
211 readDone = make(chan struct{})
214 defer close(readDone)
215 n, readErr = c.socket.Read(b)
219 ctx = context.Background()
223 return nil, ctx.Err()
226 if opE, ok := readErr.(*net.OpError); ok && opE.Timeout() {
227 c.contiguousTimeouts++
230 return nil, errors.Wrap(readErr, "reading from socket")
232 buf := bytes.NewBuffer(b[:n])
234 err := binary.Read(buf, binary.BigEndian, &h)
238 case io.ErrUnexpectedEOF, io.EOF:
242 if h.TransactionId != tid {
245 c.contiguousTimeouts = 0
246 if h.Action == ActionError {
247 err = errors.New(buf.String())
253 func readBody(r io.Reader, data ...interface{}) (err error) {
254 for _, datum := range data {
255 err = binary.Read(r, binary.BigEndian, datum)
263 func (c *udpAnnounce) connected() bool {
264 return !c.connectionIdReceived.IsZero() && time.Now().Before(c.connectionIdReceived.Add(time.Minute))
267 func (c *udpAnnounce) dialNetwork() string {
268 if c.a.UdpNetwork != "" {
269 return c.a.UdpNetwork
274 func (c *udpAnnounce) connect() (err error) {
278 c.connectionId = connectRequestConnectionId
280 hmp := missinggo.SplitHostMaybePort(c.url.Host)
285 c.socket, err = net.Dial(c.dialNetwork(), hmp.String())
289 c.socket = pproffd.WrapNetConn(c.socket)
291 b, err := c.request(ActionConnect, nil, nil)
295 var res ConnectionResponse
296 err = readBody(b, &res)
300 c.connectionId = res.ConnectionId
301 c.connectionIdReceived = time.Now()
305 // TODO: Split on IPv6, as BEP 15 says response peer decoding depends on
307 func announceUDP(opt Announce, _url *url.URL) (AnnounceResponse, error) {
313 return ua.Do(opt.Request)