-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpipe.go
112 lines (100 loc) · 2.39 KB
/
pipe.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package mapipe
import (
cxt "context"
"errors"
"fmt"
"io"
"time"
"github.com/dustin/go-humanize"
ctxio "github.com/jbenet/go-context/io"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
type xmitResult struct {
n int64
err error
from ma.Multiaddr
to ma.Multiaddr
}
func pipeConn(ctx1 cxt.Context, a, b manet.Conn, o Opts) error {
ctx, cancel := cxt.WithCancel(ctx1)
if a == nil || b == nil {
cancel()
return errors.New("attempt to pipe nil manet.Conn")
}
fmt.Fprintln(o.Trace.CW, "piping", a.RemoteMultiaddr(), "<-->", b.RemoteMultiaddr())
if o.MaxBW > 0 {
fmt.Fprintf(o.Trace.CW, "rate-limiting to %v/s\n", humanize.Bytes(o.MaxBW))
}
xmits := make(chan xmitResult, 2)
xmitRLC := func(c1, c2 manet.Conn) {
w := ctxio.NewWriter(ctx, io.MultiWriter(c1, o.Trace.AW))
r := ctxio.NewReader(ctx, c2)
n, err := rateLimitedCopy(w, r, o)
xmits <- xmitResult{n, err, c2.RemoteMultiaddr(), c1.RemoteMultiaddr()}
}
go xmitRLC(a, b)
go xmitRLC(b, a)
go func() {
<-ctx.Done()
a.Close()
b.Close()
}()
var err error
ignoreErr := func(e error) bool {
return e == io.EOF ||
e == io.ErrUnexpectedEOF ||
e == cxt.Canceled ||
e == cxt.DeadlineExceeded
}
printResults := func(x xmitResult) {
fmt.Fprintln(o.Trace.CW, "wrote", x.n, "bytes from", x.from, "to", x.to)
if x.err != nil && !ignoreErr(x.err) {
fmt.Fprintln(o.Trace.CW, x.from, "connection failed:", x.err)
err = x.err
}
}
printResults(<-xmits)
cancel() // stop when any side closes. this is same as nc behavior
printResults(<-xmits)
return err
}
func rateLimitedCopy(dst io.Writer, src io.Reader, o Opts) (written int64, err error) {
if o.MaxBW < 1 { // unlimited
return io.Copy(dst, src)
}
buf := make([]byte, o.MaxBW)
tstart := time.Now() // time now
telapsed := time.Duration(0)
texpected := time.Duration(0)
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er == io.EOF {
break
}
if er != nil {
err = er
break
}
telapsed = time.Since(tstart)
texpected = time.Second * time.Duration(written/int64(o.MaxBW))
if texpected > telapsed { // roughly how many seconds we should've waited
time.Sleep(texpected - telapsed)
}
}
return written, err
}