go-tunnel/helper.go

60 lines
1.5 KiB
Go
Raw Normal View History

2020-10-21 18:00:15 +02:00
package tunnel
import (
"io"
2020-10-23 17:08:42 +02:00
"github.com/pkg/errors"
2020-10-23 18:26:50 +02:00
"github.com/xtaci/kcp-go/v5"
2020-10-21 18:00:15 +02:00
)
2020-10-24 13:35:27 +02:00
const bufSize = 4096
2020-10-21 18:00:15 +02:00
2020-10-24 13:35:27 +02:00
// 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)
2020-10-23 17:08:42 +02:00
}
2020-10-24 13:35:27 +02:00
// 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)
2020-10-23 17:08:42 +02:00
}
2020-10-23 13:42:44 +02:00
2020-10-24 13:35:27 +02:00
// fallback to standard io.CopyBuffer
buf := make([]byte, bufSize)
return io.CopyBuffer(dst, src, buf)
2020-10-21 18:00:15 +02:00
}
2020-10-23 18:26:50 +02:00
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)
}
}