14 "github.com/anacrolix/missinggo"
15 "github.com/anacrolix/missinggo/pproffd"
17 "github.com/anacrolix/torrent/util"
23 ActionConnect Action = iota
28 connectRequestConnectionId = 0x41727101980
31 optionTypeEndOfOptions = 0
36 type ConnectionRequest struct {
42 type ConnectionResponse struct {
46 type ResponseHeader struct {
51 type RequestHeader struct {
57 type AnnounceResponseHeader struct {
64 RegisterClientScheme("udp", newClient)
67 func newClient(url *url.URL) Client {
73 func newTransactionId() int32 {
74 return int32(rand.Uint32())
77 func timeout(contiguousTimeouts int) (d time.Duration) {
78 if contiguousTimeouts > 8 {
79 contiguousTimeouts = 8
82 for ; contiguousTimeouts > 0; contiguousTimeouts-- {
88 type udpClient struct {
89 contiguousTimeouts int
90 connectionIdReceived time.Time
96 func (c *udpClient) URL() string {
100 func (c *udpClient) String() string {
104 func (c *udpClient) Announce(req *AnnounceRequest) (res AnnounceResponse, err error) {
106 err = ErrNotConnected
109 reqURI := c.url.RequestURI()
110 // Clearly this limits the request URI to 255 bytes. BEP 41 supports
111 // longer but I'm not fussed.
112 options := append([]byte{optionTypeURLData, byte(len(reqURI))}, []byte(reqURI)...)
113 b, err := c.request(ActionAnnounce, req, options)
117 var h AnnounceResponseHeader
118 err = readBody(b, &h)
121 err = io.ErrUnexpectedEOF
123 err = fmt.Errorf("error parsing announce response: %s", err)
126 res.Interval = h.Interval
127 res.Leechers = h.Leechers
128 res.Seeders = h.Seeders
129 cps, err := util.UnmarshalIPv4CompactPeers(b.Bytes())
133 for _, cp := range cps {
134 res.Peers = append(res.Peers, Peer{
142 // body is the binary serializable request body. trailer is optional data
143 // following it, such as for BEP 41.
144 func (c *udpClient) write(h *RequestHeader, body interface{}, trailer []byte) (err error) {
146 err = binary.Write(&buf, binary.BigEndian, h)
151 err = binary.Write(&buf, binary.BigEndian, body)
156 _, err = buf.Write(trailer)
160 n, err := c.socket.Write(buf.Bytes())
165 panic("write should send all or error")
170 func read(r io.Reader, data interface{}) error {
171 return binary.Read(r, binary.BigEndian, data)
174 func write(w io.Writer, data interface{}) error {
175 return binary.Write(w, binary.BigEndian, data)
178 // args is the binary serializable request body. trailer is optional data
179 // following it, such as for BEP 41.
180 func (c *udpClient) request(action Action, args interface{}, options []byte) (responseBody *bytes.Buffer, err error) {
181 tid := newTransactionId()
182 err = c.write(&RequestHeader{
183 ConnectionId: c.connectionId,
190 c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts)))
191 b := make([]byte, 0x800) // 2KiB
194 n, err = c.socket.Read(b)
195 if opE, ok := err.(*net.OpError); ok {
197 c.contiguousTimeouts++
204 buf := bytes.NewBuffer(b[:n])
206 err = binary.Read(buf, binary.BigEndian, &h)
208 case io.ErrUnexpectedEOF:
214 if h.TransactionId != tid {
217 c.contiguousTimeouts = 0
218 if h.Action == ActionError {
219 err = errors.New(buf.String())
226 func readBody(r io.Reader, data ...interface{}) (err error) {
227 for _, datum := range data {
228 err = binary.Read(r, binary.BigEndian, datum)
236 func (c *udpClient) connected() bool {
237 return !c.connectionIdReceived.IsZero() && time.Now().Before(c.connectionIdReceived.Add(time.Minute))
240 func (c *udpClient) Connect() (err error) {
244 c.connectionId = connectRequestConnectionId
246 hmp := missinggo.SplitHostPort(c.url.Host)
251 c.socket, err = net.Dial("udp", hmp.String())
255 c.socket = pproffd.WrapNetConn(c.socket)
257 b, err := c.request(ActionConnect, nil, nil)
261 var res ConnectionResponse
262 err = readBody(b, &res)
266 c.connectionId = res.ConnectionId
267 c.connectionIdReceived = time.Now()