multiserver/proxy.go

63 lines
986 B
Go
Raw Permalink Normal View History

2021-01-24 05:00:26 -08:00
package main
2021-01-05 11:34:35 -08:00
import (
2021-03-02 08:47:07 -08:00
"errors"
"log"
2021-02-20 09:06:34 -08:00
"net"
)
2021-01-05 11:34:35 -08:00
2021-01-17 12:43:23 -08:00
// Proxy processes and forwards packets from src to dst
2021-03-29 09:57:30 -07:00
func Proxy(src, dst *Conn) {
if src == nil {
2021-04-02 04:39:35 -07:00
dst.CloseWith(AccessDeniedServerFail, "", false)
processLeave(dst)
return
} else if dst == nil {
src.Close()
return
}
2021-01-05 11:34:35 -08:00
for {
pkt, err := src.Recv()
if !src.Forward() {
return
} else if !dst.Forward() {
break
}
if err != nil {
2021-03-02 08:47:07 -08:00
if errors.Is(err, net.ErrClosed) {
2021-03-29 09:57:30 -07:00
if err = src.WhyClosed(); err != nil {
log.Print(src.Addr().String(), " disconnected with error: ", err)
} else {
log.Print(src.Addr().String(), " disconnected")
2021-01-05 11:34:35 -08:00
}
2021-01-09 03:26:30 -08:00
2021-01-06 05:42:55 -08:00
if !src.IsSrv() {
2021-03-29 09:57:30 -07:00
connectedConnsMu.Lock()
connectedConns--
connectedConnsMu.Unlock()
2021-01-10 13:37:42 -08:00
2021-01-14 07:54:30 -08:00
processLeave(src)
2021-01-06 05:42:55 -08:00
}
2021-01-09 03:26:30 -08:00
2021-01-05 11:34:35 -08:00
break
}
2021-01-09 03:26:30 -08:00
2021-01-05 11:34:35 -08:00
log.Print(err)
continue
}
2021-01-09 03:26:30 -08:00
2021-01-06 14:39:54 -08:00
// Process
2021-01-14 08:09:06 -08:00
if processPktCommand(src, dst, &pkt) {
2021-01-14 04:40:31 -08:00
continue
2021-01-06 14:39:54 -08:00
}
2021-01-09 03:26:30 -08:00
2021-01-06 14:39:54 -08:00
// Forward
2021-01-05 11:34:35 -08:00
if _, err := dst.Send(pkt); err != nil {
log.Print(err)
}
}
2021-01-09 03:26:30 -08:00
2021-01-05 11:34:35 -08:00
dst.Close()
}