7 "github.com/anacrolix/log"
8 "github.com/anacrolix/missinggo/v2"
11 type listenPacketFunc func(network, addr string) (net.PacketConn, error)
13 type NewConnClientOpts struct {
14 // The network to operate to use, such as "udp4", "udp", "udp6".
18 // If non-nil, forces either IPv4 or IPv6 in the UDP tracker wire protocol.
20 // Logger to use for internal errors.
22 // Custom function to use as a substitute for net.ListenPacket
23 ListenPacket listenPacketFunc
26 // Manages a Client with a specific connection.
27 type ConnClient struct {
33 newOpts NewConnClientOpts
36 func (cc *ConnClient) reader() {
37 b := make([]byte, 0x800)
39 n, addr, err := cc.conn.ReadFrom(b)
41 // TODO: Do bad things to the dispatcher, and incoming calls to the client if we have a
45 // don't panic, just close the connection, fix https://github.com/anacrolix/torrent/issues/845
50 err = cc.d.Dispatch(b[:n], addr)
52 cc.newOpts.Logger.Levelf(log.Debug, "dispatching packet received on %v: %v", cc.conn.LocalAddr(), err)
57 func ipv6(opt *bool, network string, remoteAddr net.Addr) bool {
67 rip := missinggo.AddrIP(remoteAddr)
68 return rip.To16() != nil && rip.To4() == nil
71 // Allows a UDP Client to write packets to an endpoint without knowing about the network specifics.
72 type clientWriter struct {
78 func (me clientWriter) Write(p []byte) (n int, err error) {
79 addr, err := net.ResolveUDPAddr(me.network, me.address)
83 return me.pc.WriteTo(p, addr)
86 func NewConnClient(opts NewConnClientOpts) (cc *ConnClient, err error) {
87 var conn net.PacketConn
88 if opts.ListenPacket != nil {
89 conn, err = opts.ListenPacket(opts.Network, ":0")
91 conn, err = net.ListenPacket(opts.Network, ":0")
97 if opts.Logger.IsZero() {
98 opts.Logger = log.Default
102 Writer: clientWriter{
104 network: opts.Network,
111 cc.Client.Dispatcher = &cc.d
116 func (cc *ConnClient) Close() error {
118 return cc.conn.Close()
121 func (cc *ConnClient) Announce(
122 ctx context.Context, req AnnounceRequest, opts Options,
124 h AnnounceResponseHeader, nas AnnounceResponsePeers, err error,
126 return cc.Client.Announce(ctx, req, opts, func(addr net.Addr) bool {
127 return ipv6(cc.newOpts.Ipv6, cc.newOpts.Network, addr)
131 func (cc *ConnClient) LocalAddr() net.Addr {
132 return cc.conn.LocalAddr()