2018-12-11 22:01:50 +01:00
|
|
|
package versionhandshake
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"time"
|
2019-03-22 19:41:12 +01:00
|
|
|
|
2018-12-11 22:01:50 +01:00
|
|
|
"github.com/zrepl/zrepl/transport"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HandshakeConnecter struct {
|
|
|
|
connecter transport.Connecter
|
2019-03-22 19:41:12 +01:00
|
|
|
timeout time.Duration
|
2018-12-11 22:01:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c HandshakeConnecter) Connect(ctx context.Context) (transport.Wire, error) {
|
|
|
|
conn, err := c.connecter.Connect(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
dl, ok := ctx.Deadline()
|
|
|
|
if !ok {
|
|
|
|
dl = time.Now().Add(c.timeout)
|
|
|
|
}
|
|
|
|
if err := DoHandshakeCurrentVersion(conn, dl); err != nil {
|
|
|
|
conn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Connecter(connecter transport.Connecter, timeout time.Duration) HandshakeConnecter {
|
|
|
|
return HandshakeConnecter{
|
|
|
|
connecter: connecter,
|
2019-03-22 19:41:12 +01:00
|
|
|
timeout: timeout,
|
2018-12-11 22:01:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// wrapper type that performs a a protocol version handshake before returning the connection
|
|
|
|
type HandshakeListener struct {
|
2019-03-22 19:41:12 +01:00
|
|
|
l transport.AuthenticatedListener
|
2018-12-11 22:01:50 +01:00
|
|
|
timeout time.Duration
|
|
|
|
}
|
|
|
|
|
2019-03-22 19:41:12 +01:00
|
|
|
func (l HandshakeListener) Addr() net.Addr { return l.l.Addr() }
|
2018-12-11 22:01:50 +01:00
|
|
|
|
|
|
|
func (l HandshakeListener) Close() error { return l.l.Close() }
|
|
|
|
|
|
|
|
func (l HandshakeListener) Accept(ctx context.Context) (*transport.AuthConn, error) {
|
|
|
|
conn, err := l.l.Accept(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
dl, ok := ctx.Deadline()
|
|
|
|
if !ok {
|
|
|
|
dl = time.Now().Add(l.timeout) // shadowing
|
|
|
|
}
|
|
|
|
if err := DoHandshakeCurrentVersion(conn, dl); err != nil {
|
2019-03-15 15:59:47 +01:00
|
|
|
err.isAcceptError = true
|
2018-12-11 22:01:50 +01:00
|
|
|
conn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Listener(l transport.AuthenticatedListener, timeout time.Duration) transport.AuthenticatedListener {
|
|
|
|
return HandshakeListener{l, timeout}
|
|
|
|
}
|