You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/transport/internet/udp/hub.go

112 lines
2.4 KiB

package udp
9 years ago
import (
"net"
8 years ago
"sync"
9 years ago
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
9 years ago
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/transport/internet/internal"
9 years ago
)
type UDPPayloadHandler func(*alloc.Buffer, *proxy.SessionInfo)
9 years ago
type UDPHub struct {
8 years ago
sync.RWMutex
9 years ago
conn *net.UDPConn
option ListenOption
9 years ago
accepting bool
}
type ListenOption struct {
Callback UDPPayloadHandler
ReceiveOriginalDest bool
}
func ListenUDP(address v2net.Address, port v2net.Port, option ListenOption) (*UDPHub, error) {
9 years ago
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: address.IP(),
9 years ago
Port: int(port),
})
if err != nil {
return nil, err
}
if option.ReceiveOriginalDest {
fd, err := internal.GetSysFd(udpConn)
if err != nil {
log.Warning("UDP|Listener: Failed to get fd: ", err)
return nil, err
}
err = SetOriginalDestOptions(fd)
if err != nil {
log.Warning("UDP|Listener: Failed to set socket options: ", err)
return nil, err
}
}
9 years ago
hub := &UDPHub{
conn: udpConn,
option: option,
9 years ago
}
go hub.start()
return hub, nil
}
func (this *UDPHub) Close() {
8 years ago
this.Lock()
defer this.Unlock()
9 years ago
this.accepting = false
this.conn.Close()
}
func (this *UDPHub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
return this.conn.WriteToUDP(payload, &net.UDPAddr{
IP: dest.Address().IP(),
Port: int(dest.Port()),
})
}
func (this *UDPHub) start() {
8 years ago
this.Lock()
this.accepting = true
8 years ago
this.Unlock()
oobBytes := make([]byte, 256)
8 years ago
for this.Running() {
9 years ago
buffer := alloc.NewBuffer()
nBytes, noob, _, addr, err := ReadUDPMsg(this.conn, buffer.Value, oobBytes)
9 years ago
if err != nil {
log.Info("UDP|Hub: Failed to read UDP msg: ", err)
9 years ago
buffer.Release()
continue
}
buffer.Slice(0, nBytes)
session := new(proxy.SessionInfo)
session.Source = v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
if this.option.ReceiveOriginalDest && noob > 0 {
session.Destination = RetrieveOriginalDest(oobBytes[:noob])
}
go this.option.Callback(buffer, session)
9 years ago
}
}
8 years ago
func (this *UDPHub) Running() bool {
this.RLock()
defer this.RUnlock()
return this.accepting
}
// Connection return the net.Conn underneath this hub.
// Private: Visible for testing only
func (this *UDPHub) Connection() net.Conn {
return this.conn
}
8 years ago
func (this *UDPHub) Addr() net.Addr {
return this.conn.LocalAddr()
}