14 "github.com/anacrolix/torrent/util"
26 optionTypeEndOfOptions = 0
31 type ConnectionRequest struct {
37 type ConnectionResponse struct {
41 type ResponseHeader struct {
46 type RequestHeader struct {
52 type AnnounceResponseHeader struct {
59 RegisterClientScheme("udp", newClient)
62 func newClient(url *url.URL) Client {
68 func newTransactionId() int32 {
69 return int32(rand.Uint32())
72 func timeout(contiguousTimeouts int) (d time.Duration) {
73 if contiguousTimeouts > 8 {
74 contiguousTimeouts = 8
77 for ; contiguousTimeouts > 0; contiguousTimeouts-- {
83 type udpClient struct {
84 contiguousTimeouts int
85 connectionIdReceived time.Time
91 func (c *udpClient) URL() string {
95 func (c *udpClient) String() string {
99 func (c *udpClient) Announce(req *AnnounceRequest) (res AnnounceResponse, err error) {
101 err = ErrNotConnected
104 reqURI := c.url.RequestURI()
105 // Clearly this limits the request URI to 255 bytes. BEP 41 supports
106 // longer but I'm not fussed.
107 options := append([]byte{optionTypeURLData, byte(len(reqURI))}, []byte(reqURI)...)
108 b, err := c.request(Announce, req, options)
112 var h AnnounceResponseHeader
113 err = readBody(b, &h)
116 err = io.ErrUnexpectedEOF
118 err = fmt.Errorf("error parsing announce response: %s", err)
121 res.Interval = h.Interval
122 res.Leechers = h.Leechers
123 res.Seeders = h.Seeders
125 var p util.CompactPeer
126 err = binary.Read(b, binary.BigEndian, &p)
135 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) {
145 buf := &bytes.Buffer{}
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.Reader, 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, 0x10000) // IP limits packet size to 64KB
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 == Error {
219 err = errors.New(buf.String())
221 responseBody = bytes.NewReader(buf.Bytes())
226 func readBody(r *bytes.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 = 0x41727101980
246 c.socket, err = net.Dial("udp", c.url.Host)
251 b, err := c.request(Connect, nil, nil)
255 var res ConnectionResponse
256 err = readBody(b, &res)
260 c.connectionId = res.ConnectionId
261 c.connectionIdReceived = time.Now()