2018-09-04 23:33:07 +00:00
|
|
|
package sshforward
|
|
|
|
|
|
|
|
import (
|
|
|
|
io "io"
|
|
|
|
|
2019-06-01 23:52:35 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-09-04 23:33:07 +00:00
|
|
|
context "golang.org/x/net/context"
|
|
|
|
"golang.org/x/sync/errgroup"
|
|
|
|
)
|
|
|
|
|
2020-07-18 21:51:19 +00:00
|
|
|
type Stream interface {
|
|
|
|
SendMsg(m interface{}) error
|
|
|
|
RecvMsg(m interface{}) error
|
|
|
|
}
|
|
|
|
|
|
|
|
func Copy(ctx context.Context, conn io.ReadWriteCloser, stream Stream, closeStream func() error) error {
|
2018-09-04 23:33:07 +00:00
|
|
|
g, ctx := errgroup.WithContext(ctx)
|
|
|
|
|
|
|
|
g.Go(func() (retErr error) {
|
|
|
|
p := &BytesMessage{}
|
|
|
|
for {
|
|
|
|
if err := stream.RecvMsg(p); err != nil {
|
2019-08-26 22:34:55 +00:00
|
|
|
conn.Close()
|
2018-09-04 23:33:07 +00:00
|
|
|
if err == io.EOF {
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-01 23:52:35 +00:00
|
|
|
return errors.WithStack(err)
|
2018-09-04 23:33:07 +00:00
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
conn.Close()
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
if _, err := conn.Write(p.Data); err != nil {
|
|
|
|
conn.Close()
|
2019-06-01 23:52:35 +00:00
|
|
|
return errors.WithStack(err)
|
2018-09-04 23:33:07 +00:00
|
|
|
}
|
|
|
|
p.Data = p.Data[:0]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
g.Go(func() (retErr error) {
|
|
|
|
for {
|
|
|
|
buf := make([]byte, 32*1024)
|
|
|
|
n, err := conn.Read(buf)
|
|
|
|
switch {
|
|
|
|
case err == io.EOF:
|
2019-08-26 22:34:55 +00:00
|
|
|
if closeStream != nil {
|
|
|
|
closeStream()
|
|
|
|
}
|
2018-09-04 23:33:07 +00:00
|
|
|
return nil
|
|
|
|
case err != nil:
|
2019-06-01 23:52:35 +00:00
|
|
|
return errors.WithStack(err)
|
2018-09-04 23:33:07 +00:00
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
p := &BytesMessage{Data: buf[:n]}
|
|
|
|
if err := stream.SendMsg(p); err != nil {
|
2019-06-01 23:52:35 +00:00
|
|
|
return errors.WithStack(err)
|
2018-09-04 23:33:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return g.Wait()
|
|
|
|
}
|