2021-12-30 17:04:45 -05:00
|
|
|
package udp
|
|
|
|
|
|
|
|
import (
|
|
|
|
gonet "net"
|
|
|
|
|
2021-12-31 16:22:16 -05:00
|
|
|
"github.com/v2fly/v2ray-core/v5/common/signal"
|
|
|
|
"github.com/v2fly/v2ray-core/v5/transport/internet"
|
2021-12-30 17:04:45 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type dataHandler func(content []byte, address gonet.Addr)
|
|
|
|
|
|
|
|
type copyHandler struct {
|
|
|
|
onData []dataHandler
|
|
|
|
}
|
|
|
|
|
|
|
|
type CopyOption func(*copyHandler)
|
|
|
|
|
|
|
|
func CopyPacketConn(dst internet.AbstractPacketConnWriter, src internet.AbstractPacketConnReader, options ...CopyOption) error {
|
|
|
|
var handler copyHandler
|
|
|
|
for _, option := range options {
|
|
|
|
option(&handler)
|
|
|
|
}
|
|
|
|
var buffer [2048]byte
|
|
|
|
for {
|
|
|
|
n, addr, err := src.ReadFrom(buffer[:])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, handler := range handler.onData {
|
|
|
|
handler(buffer[:n], addr)
|
|
|
|
}
|
|
|
|
|
2021-12-31 16:22:16 -05:00
|
|
|
_, err = dst.WriteTo(buffer[:n], addr)
|
2021-12-30 17:04:45 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func UpdateActivity(timer signal.ActivityUpdater) CopyOption {
|
|
|
|
return func(handler *copyHandler) {
|
|
|
|
handler.onData = append(handler.onData, func(content []byte, address gonet.Addr) {
|
|
|
|
timer.Update()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|