-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy.go
72 lines (56 loc) · 1.49 KB
/
copy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package netx
import (
"errors"
"io"
"strings"
"sync"
"github.com/panjf2000/ants/v2"
"github.com/starudream/go-lib/log"
"github.com/starudream/secret-tunnel/constant"
"github.com/starudream/secret-tunnel/internal/pool"
"github.com/starudream/secret-tunnel/internal/unitx"
)
func Copy(c1, c2 io.ReadWriteCloser, kvs ...string) (in int64, out int64) {
wg := &sync.WaitGroup{}
wg.Add(2)
go connCopy(c1, c2, &in, wg)
go connCopy(c2, c1, &out, wg)
wg.Wait()
if constant.Debug() {
l := log.Debug()
for i := 0; i < len(kvs); i += 2 {
l = l.Str(kvs[i], kvs[i+1])
}
l.CallerSkipFrame(1).Msgf("copy stats, in: %s, out: %s", unitx.HumanSize(float64(in)), unitx.HumanSize(float64(out)))
}
return
}
func connCopy(dst, src io.ReadWriteCloser, n *int64, wg *sync.WaitGroup) {
_ = copyPool.Invoke(&pfCopyItem{dst: dst, src: src, n: n, wg: wg})
}
var copyPool, _ = ants.NewPoolWithFunc(10000, pfCopy, ants.WithNonblocking(false))
type pfCopyItem struct {
dst io.ReadWriteCloser
src io.ReadWriteCloser
n *int64
wg *sync.WaitGroup
}
func (c *pfCopyItem) Done() {
_ = c.dst.Close()
_ = c.src.Close()
c.wg.Done()
}
func pfCopy(v any) {
i, ok := v.(*pfCopyItem)
if !ok {
return
}
defer i.Done()
buf := pool.GetBuf(constant.MessageSize)
defer pool.PutBuf(buf)
var err error
*i.n, err = io.CopyBuffer(i.dst, i.src, buf)
if err != nil && !errors.Is(err, io.EOF) && !strings.Contains(err.Error(), "use of closed network connection") {
log.Warn().Msgf("copy buffer error: %v", err)
}
}