2021-06-13 17:23:10 +08:00
|
|
|
package tproxy
|
2020-03-08 21:58:49 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2022-06-12 19:37:27 +08:00
|
|
|
"net/netip"
|
2020-03-08 21:58:49 +08:00
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/common/pool"
|
|
|
|
)
|
|
|
|
|
2020-04-16 18:19:36 +08:00
|
|
|
type packet struct {
|
2022-11-11 23:36:06 +08:00
|
|
|
pc net.PacketConn
|
2022-06-12 19:37:27 +08:00
|
|
|
lAddr netip.AddrPort
|
2020-03-10 20:36:24 +08:00
|
|
|
buf []byte
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|
|
|
|
|
2020-04-16 18:19:36 +08:00
|
|
|
func (c *packet) Data() []byte {
|
2020-03-08 21:58:49 +08:00
|
|
|
return c.buf
|
|
|
|
}
|
|
|
|
|
2020-10-14 19:56:02 +08:00
|
|
|
// WriteBack opens a new socket binding `addr` to write UDP packet back
|
2020-04-16 18:19:36 +08:00
|
|
|
func (c *packet) WriteBack(b []byte, addr net.Addr) (n int, err error) {
|
2022-06-12 19:37:27 +08:00
|
|
|
tc, err := dialUDP("udp", addr.(*net.UDPAddr).AddrPort(), c.lAddr)
|
2020-03-08 21:58:49 +08:00
|
|
|
if err != nil {
|
|
|
|
n = 0
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n, err = tc.Write(b)
|
|
|
|
tc.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// LocalAddr returns the source IP/Port of UDP Packet
|
2020-04-16 18:19:36 +08:00
|
|
|
func (c *packet) LocalAddr() net.Addr {
|
2022-06-12 19:37:27 +08:00
|
|
|
return &net.UDPAddr{IP: c.lAddr.Addr().AsSlice(), Port: int(c.lAddr.Port()), Zone: c.lAddr.Addr().Zone()}
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|
|
|
|
|
2020-04-16 18:19:36 +08:00
|
|
|
func (c *packet) Drop() {
|
2020-04-25 00:30:40 +08:00
|
|
|
pool.Put(c.buf)
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|
2022-11-11 23:36:06 +08:00
|
|
|
|
|
|
|
func (c *packet) InAddr() net.Addr {
|
|
|
|
return c.pc.LocalAddr()
|
|
|
|
}
|