2023-01-08 09:26:04 +00:00
|
|
|
package udpproxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2024-03-08 02:29:01 +00:00
|
|
|
"strings"
|
2023-01-08 09:26:04 +00:00
|
|
|
"time"
|
2024-03-08 02:29:01 +00:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2023-01-08 09:26:04 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Session struct {
|
|
|
|
serverConn *net.UDPConn
|
|
|
|
proxyConn *net.UDPConn
|
|
|
|
caddr *net.UDPAddr
|
|
|
|
updateTime time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func createSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn) (*Session, error) {
|
|
|
|
serverConn, err := net.DialUDP("udp", nil, raddr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
session := &Session{
|
|
|
|
serverConn: serverConn,
|
|
|
|
proxyConn: proxyConn,
|
|
|
|
caddr: caddr,
|
|
|
|
updateTime: time.Now(),
|
|
|
|
}
|
|
|
|
|
|
|
|
go session.listen()
|
|
|
|
|
|
|
|
return session, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) listen() error {
|
|
|
|
for {
|
2023-01-08 10:59:43 +00:00
|
|
|
buf := make([]byte, 2048)
|
|
|
|
n, err := s.serverConn.Read(buf)
|
2023-01-08 09:26:04 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-01-08 11:04:44 +00:00
|
|
|
go s.proxyFrom(buf[:n])
|
2023-01-08 09:26:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) proxyFrom(buf []byte) error {
|
|
|
|
s.updateTime = time.Now()
|
|
|
|
_, err := s.proxyConn.WriteToUDP(buf, s.caddr)
|
|
|
|
if err != nil {
|
2023-01-08 11:13:24 +00:00
|
|
|
log.Println(err)
|
2023-01-08 09:26:04 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) proxyTo(buf []byte) error {
|
|
|
|
s.updateTime = time.Now()
|
|
|
|
_, err := s.serverConn.Write(buf)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
return err
|
|
|
|
}
|
2024-03-08 02:29:01 +00:00
|
|
|
parts := strings.Split(string(buf), " ")
|
2024-03-08 02:42:01 +00:00
|
|
|
log.Info("From [", s.caddr.IP, "] To [", s.serverConn.RemoteAddr().String(), "] Command: ", strings.Join(parts[2:], " "))
|
2023-01-08 09:26:04 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|