proxyport/app/proxy.go

92 lines
1.4 KiB
Go
Raw Normal View History

2023-01-18 14:33:17 +08:00
package app
import (
"git.makemake.in/test/mycommon/mylog"
"io"
2023-01-19 11:34:30 +08:00
"math/rand"
2023-01-18 14:33:17 +08:00
"net"
2023-01-19 11:34:30 +08:00
"sync"
"time"
)
var (
wg = &sync.WaitGroup{}
2023-01-18 14:33:17 +08:00
)
func Run() {
2023-01-19 11:34:30 +08:00
rand.Seed(time.Now().UnixNano())
for name, item := range ProxyMap {
wg.Add(1)
go listenTcp(name, item)
2023-01-18 14:33:17 +08:00
}
2023-01-19 11:34:30 +08:00
wg.Wait()
2023-01-18 14:33:17 +08:00
}
2023-01-19 11:34:30 +08:00
func listenTcp(name string, item ProxyItem) {
defer wg.Done()
listen, err := net.Listen("tcp", item.LocalAddr)
2023-01-18 14:33:17 +08:00
if err != nil {
2023-01-19 11:34:30 +08:00
mylog.Errorf("[%s] listen err: %s", name, err)
2023-01-18 14:33:17 +08:00
return
}
2023-01-19 11:34:30 +08:00
mylog.Infof("[%s] listen %s", name, item.LocalAddr)
2023-01-18 14:33:17 +08:00
for {
conn, err := listen.Accept()
if err != nil {
2023-01-19 11:34:30 +08:00
mylog.Errorf("conn accept err: %s", item.LocalAddr, err)
2023-01-18 14:33:17 +08:00
return
}
go proxyTcp(conn, item)
}
}
func proxyTcp(conn net.Conn, item ProxyItem) {
2023-01-19 11:34:30 +08:00
randRemoteAddr := item.RemoteAddr[rand.Intn(len(item.RemoteAddr))]
2023-01-18 14:33:17 +08:00
2023-01-19 11:34:30 +08:00
remoteConn, err := net.Dial("tcp", randRemoteAddr)
if err != nil {
mylog.Errorf("connect remote err: %s\n", err)
return
2023-01-18 14:33:17 +08:00
}
2023-01-19 11:34:30 +08:00
go copyConn(randRemoteAddr, conn, remoteConn)
2023-01-18 14:33:17 +08:00
}
2023-01-19 11:34:30 +08:00
func copyConn(addr string, conn, remoteConn net.Conn) {
mylog.Infof("start proxy: %s", addr)
wg2 := &sync.WaitGroup{}
wg2.Add(2)
2023-01-18 14:33:17 +08:00
2023-01-19 11:34:30 +08:00
go func() {
_, err := io.Copy(conn, remoteConn)
if err != nil {
mylog.Error(err)
return
}
wg2.Done()
2023-01-18 14:33:17 +08:00
}()
2023-01-19 11:34:30 +08:00
go func() {
_, err := io.Copy(remoteConn, conn)
if err != nil {
mylog.Error(err)
return
}
wg2.Done()
}()
wg2.Wait()
mylog.Infof("stop proxy: %s", addr)
2023-01-18 14:33:17 +08:00
}