propagate context deadlines to handshake.

Fixes https://github.com/libp2p/go-libp2p-noise/issues/75.
This commit is contained in:
Raúl Kripalani 2020-04-23 10:44:44 +01:00
parent 1ecc08a61b
commit ef4c4223d1
2 changed files with 32 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"time"
"github.com/flynn/noise" "github.com/flynn/noise"
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
@ -46,6 +47,13 @@ func (s *secureSession) runHandshake(ctx context.Context) error {
return err return err
} }
// set a deadline to complete the handshake, if one has been supplied.
// clear it after we're done.
if deadline, ok := ctx.Deadline(); ok {
s.SetDeadline(deadline)
defer s.SetDeadline(time.Time{})
}
if s.initiator { if s.initiator {
// stage 0 // // stage 0 //
// do not send the payload just yet, as it would be plaintext; not secret. // do not send the payload just yet, as it would be plaintext; not secret.

View File

@ -3,9 +3,11 @@ package noise
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"math/rand" "math/rand"
"net" "net"
"testing" "testing"
"time"
crypto "github.com/libp2p/go-libp2p-core/crypto" crypto "github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer" "github.com/libp2p/go-libp2p-core/peer"
@ -86,6 +88,28 @@ func connect(t *testing.T, initTransport, respTransport *Transport) (*secureSess
return initConn.(*secureSession), respConn.(*secureSession) return initConn.(*secureSession), respConn.(*secureSession)
} }
func TestDeadlines(t *testing.T) {
initTransport := newTestTransport(t, crypto.Ed25519, 2048)
respTransport := newTestTransport(t, crypto.Ed25519, 2048)
init, resp := newConnPair(t)
defer init.Close()
defer resp.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
_, err := initTransport.SecureOutbound(ctx, init, respTransport.localID)
if err == nil {
t.Fatalf("expected i/o timeout err; got: %s", err)
}
var neterr net.Error
if ok := errors.As(err, &neterr); !ok || !neterr.Timeout() {
t.Fatalf("expected i/o timeout err; got: %s", err)
}
}
func TestIDs(t *testing.T) { func TestIDs(t *testing.T) {
initTransport := newTestTransport(t, crypto.Ed25519, 2048) initTransport := newTestTransport(t, crypto.Ed25519, 2048)
respTransport := newTestTransport(t, crypto.Ed25519, 2048) respTransport := newTestTransport(t, crypto.Ed25519, 2048)