From 21ea715217190a1373c9611623c48bffc49efce0 Mon Sep 17 00:00:00 2001 From: qydysky Date: Tue, 4 Aug 2020 15:34:13 +0800 Subject: [PATCH] 36 --- Net.go | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-- Port.go | 8 ++--- 2 files changed, 109 insertions(+), 6 deletions(-) diff --git a/Net.go b/Net.go index 0e9b60d..7244698 100644 --- a/Net.go +++ b/Net.go @@ -1,10 +1,14 @@ package part import ( - "net" + "net" + "sync" + // "errors" ) -type netl struct{} +type netl struct{ + RV []interface{} +} func Net() *netl{ return &netl{} @@ -18,4 +22,103 @@ func (*netl) TestDial(network,address string) bool { } conn.Close() return true +} + +func (t *netl) Forward(targetaddr,targetnetwork *string, Need_Accept bool) { + proxylistener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + Logf().E("[part/Forward]Unable to listen, error:", err.Error()) + } + const max = 1000 + var accept_chan chan bool = make(chan bool,max) + t.RV = append(t.RV,proxylistener.Addr().(*net.TCPAddr).Port,accept_chan,err) + + defer proxylistener.Close() + + tcpBridge2 := func (a, b net.Conn) { + + fin:=make(chan bool,1) + var wg sync.WaitGroup + + wg.Add(2) + go func(){ + defer func() { + a.Close() + b.Close() + fin <- true + wg.Done() + }() + + buf := make([]byte, 20480) + + for { + select { + case <-fin: + return; + default: + n, err := a.Read(buf) + + if err != nil {return} + b.Write(buf[:n]) + } + } + }() + + go func(){ + defer func() { + a.Close() + b.Close() + fin <- true + wg.Done() + }() + + buf := make([]byte, 20480) + + for { + select { + case <-fin: + return; + default: + n, err := b.Read(buf) + + if err != nil {return} + a.Write(buf[:n]) + } + } + }() + + wg.Wait() + } + + for { + + proxyconn, err := proxylistener.Accept() + if err != nil { + Logf().E("[part/Forward]Unable to accept a request:", err.Error()) + continue + } + + if Need_Accept { + if len(accept_chan) == max { + Logf().E("[part/Forward] accept channel full.Skip") + <- accept_chan + } + accept_chan <- true + } + if *targetaddr == "" || *targetnetwork == "" { + proxyconn.Close() + Logf().I("[part/Forward]Stop!", *targetaddr, *targetnetwork) + break + } + + targetconn, err := net.Dial(*targetnetwork, *targetaddr) + if err != nil { + Logf().E("[part/Forward]Unable to connect:", *targetaddr, err.Error()) + proxyconn.Close() + continue + } + + go tcpBridge2(proxyconn,targetconn) + } + } \ No newline at end of file diff --git a/Port.go b/Port.go index 5b1c1e0..4c9b046 100644 --- a/Port.go +++ b/Port.go @@ -1,7 +1,7 @@ package part import ( - "net" + // "net" ) type port struct {} @@ -24,13 +24,13 @@ func (*port) Del(key string) { delete(port_map,key) } -func (*port) Set(key string,l net.Listener) int { +func (*port) Set(key string,l int) int { port_buf<-true defer func(){ <-port_buf }() - port_map[key] = l.Addr().(*net.TCPAddr).Port - return l.Addr().(*net.TCPAddr).Port + port_map[key] = l + return l } func (*port) New(key string) int { -- 2.39.2