go-tunnel/server_config.go

85 lines
1.9 KiB
Go
Raw Normal View History

2020-10-21 18:00:15 +02:00
package tunnel
import (
"crypto/sha1"
"github.com/pkg/errors"
"github.com/xtaci/kcp-go/v5"
"golang.org/x/crypto/pbkdf2"
)
2020-10-23 18:26:50 +02:00
type ConfigureConnFunc func(conn *kcp.UDPSession) error
2020-10-21 18:00:15 +02:00
type ServerConfig struct {
2020-10-23 18:26:50 +02:00
Address string
BlockCrypt kcp.BlockCrypt
DataShards int
ParityShards int
Hooks *ServerHooks
ConfigureConn ConfigureConnFunc
2020-10-21 18:00:15 +02:00
}
func DefaultServerConfig() *ServerConfig {
unencryptedBlock, err := kcp.NewNoneBlockCrypt(nil)
if err != nil { // should never happen
panic(errors.WithStack(err))
}
return &ServerConfig{
Address: ":36543",
BlockCrypt: unencryptedBlock,
DataShards: 3,
ParityShards: 10,
Hooks: &ServerHooks{
onClientConnect: DefaultOnClientConnect,
onClientDisconnect: DefaultOnClientDisconnect,
onClientAuth: DefaultOnClientAuth,
},
}
}
type ServerConfigFunc func(c *ServerConfig)
func WithServerAddress(address string) ServerConfigFunc {
return func(conf *ServerConfig) {
conf.Address = address
}
}
2020-10-23 18:26:50 +02:00
func WithServerBlockCrypt(alg string, pass, salt string, iterations, keyLen int) ServerConfigFunc {
2020-10-21 18:00:15 +02:00
return func(conf *ServerConfig) {
2020-10-23 18:26:50 +02:00
key := pbkdf2.Key([]byte(pass), []byte(salt), iterations, keyLen, sha1.New)
2020-10-21 18:00:15 +02:00
2020-10-23 18:26:50 +02:00
block, err := createBlockCrypt(alg, key)
2020-10-21 18:00:15 +02:00
if err != nil {
2020-10-23 18:26:50 +02:00
panic(errors.Wrap(err, "could not create block crypt"))
2020-10-21 18:00:15 +02:00
}
conf.BlockCrypt = block
}
}
func WithServerOnClientAuth(fn OnClientAuthFunc) ServerConfigFunc {
return func(conf *ServerConfig) {
conf.Hooks.onClientAuth = fn
}
}
func WithServerOnClientConnect(fn OnClientConnectFunc) ServerConfigFunc {
return func(conf *ServerConfig) {
conf.Hooks.onClientConnect = fn
}
}
func WithServerOnClientDisconnect(fn OnClientDisconnectFunc) ServerConfigFunc {
return func(conf *ServerConfig) {
conf.Hooks.onClientDisconnect = fn
}
}
2020-10-23 18:26:50 +02:00
func WithServerConfigureConn(fn ConfigureConnFunc) ServerConfigFunc {
return func(conf *ServerConfig) {
conf.ConfigureConn = fn
}
}