go-tunnel/helper.go

60 lines
1.5 KiB
Go

package tunnel
import (
"io"
"github.com/pkg/errors"
"github.com/xtaci/kcp-go/v5"
)
const bufSize = 4096
// From https://github.com/xtaci/kcptun/blob/master/generic/copy.go
// Copyright https://github.com/xtaci
func Copy(dst io.Writer, src io.Reader) (written int64, err error) {
// If the reader has a WriteTo method, use it to do the copy.
// Avoids an allocation and a copy.
if wt, ok := src.(io.WriterTo); ok {
return wt.WriteTo(dst)
}
// Similarly, if the writer has a ReadFrom method, use it to do the copy.
if rt, ok := dst.(io.ReaderFrom); ok {
return rt.ReadFrom(src)
}
// fallback to standard io.CopyBuffer
buf := make([]byte, bufSize)
return io.CopyBuffer(dst, src, buf)
}
func createBlockCrypt(algorithm string, pass []byte) (kcp.BlockCrypt, error) {
switch algorithm {
case "sm4":
return kcp.NewSM4BlockCrypt(pass[:16])
case "tea":
return kcp.NewTEABlockCrypt(pass[:16])
case "xor":
return kcp.NewSimpleXORBlockCrypt(pass)
case "none":
return kcp.NewNoneBlockCrypt(pass)
case "aes-128":
return kcp.NewAESBlockCrypt(pass[:16])
case "aes-192":
return kcp.NewAESBlockCrypt(pass[:24])
case "blowfish":
return kcp.NewBlowfishBlockCrypt(pass)
case "twofish":
return kcp.NewTwofishBlockCrypt(pass)
case "cast5":
return kcp.NewCast5BlockCrypt(pass[:16])
case "3des":
return kcp.NewTripleDESBlockCrypt(pass[:24])
case "xtea":
return kcp.NewXTEABlockCrypt(pass[:16])
case "salsa20":
return kcp.NewSalsa20BlockCrypt(pass)
default:
return nil, errors.Errorf("unknown algorithm '%s'", algorithm)
}
}