Browse Source

move go-ws-transport here

pull/1422/head
Marten Seemann 3 years ago
parent
commit
c32e485828
  1. 5
      p2p/transport/websocket/LICENSE-APACHE
  2. 19
      p2p/transport/websocket/LICENSE-MIT
  3. 137
      p2p/transport/websocket/addrs.go
  4. 81
      p2p/transport/websocket/addrs_test.go
  5. 151
      p2p/transport/websocket/conn.go
  6. 127
      p2p/transport/websocket/listener.go
  7. 155
      p2p/transport/websocket/websocket.go
  8. 350
      p2p/transport/websocket/websocket_test.go

5
p2p/transport/websocket/LICENSE-APACHE

@ -0,0 +1,5 @@
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

19
p2p/transport/websocket/LICENSE-MIT

@ -0,0 +1,19 @@
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

137
p2p/transport/websocket/addrs.go

@ -0,0 +1,137 @@
package websocket
import (
"fmt"
"net"
"net/url"
"strconv"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
// Addr is an implementation of net.Addr for WebSocket.
type Addr struct {
*url.URL
}
var _ net.Addr = (*Addr)(nil)
// Network returns the network type for a WebSocket, "websocket".
func (addr *Addr) Network() string {
return "websocket"
}
// NewAddr creates an Addr with `ws` scheme (insecure).
//
// Deprecated. Use NewAddrWithScheme.
func NewAddr(host string) *Addr {
// Older versions of the transport only supported insecure connections (i.e.
// WS instead of WSS). Assume that is the case here.
return NewAddrWithScheme(host, false)
}
// NewAddrWithScheme creates a new Addr using the given host string. isSecure
// should be true for WSS connections and false for WS.
func NewAddrWithScheme(host string, isSecure bool) *Addr {
scheme := "ws"
if isSecure {
scheme = "wss"
}
return &Addr{
URL: &url.URL{
Scheme: scheme,
Host: host,
},
}
}
func ConvertWebsocketMultiaddrToNetAddr(maddr ma.Multiaddr) (net.Addr, error) {
url, err := parseMultiaddr(maddr)
if err != nil {
return nil, err
}
return &Addr{URL: url}, nil
}
func ParseWebsocketNetAddr(a net.Addr) (ma.Multiaddr, error) {
wsa, ok := a.(*Addr)
if !ok {
return nil, fmt.Errorf("not a websocket address")
}
var (
tcpma ma.Multiaddr
err error
port int
host = wsa.Hostname()
)
// Get the port
if portStr := wsa.Port(); portStr != "" {
port, err = strconv.Atoi(portStr)
if err != nil {
return nil, fmt.Errorf("failed to parse port '%q': %s", portStr, err)
}
} else {
return nil, fmt.Errorf("invalid port in url: '%q'", wsa.URL)
}
// NOTE: Ignoring IPv6 zones...
// Detect if host is IP address or DNS
if ip := net.ParseIP(host); ip != nil {
// Assume IP address
tcpma, err = manet.FromNetAddr(&net.TCPAddr{
IP: ip,
Port: port,
})
if err != nil {
return nil, err
}
} else {
// Assume DNS name
tcpma, err = ma.NewMultiaddr(fmt.Sprintf("/dns/%s/tcp/%d", host, port))
if err != nil {
return nil, err
}
}
wsma, err := ma.NewMultiaddr("/" + wsa.Scheme)
if err != nil {
return nil, err
}
return tcpma.Encapsulate(wsma), nil
}
func parseMultiaddr(maddr ma.Multiaddr) (*url.URL, error) {
// Only look at the _last_ component.
maddr, wscomponent := ma.SplitLast(maddr)
if maddr == nil || wscomponent == nil {
return nil, fmt.Errorf("websocket addrs need at least two components")
}
var scheme string
switch wscomponent.Protocol().Code {
case ma.P_WS:
scheme = "ws"
case ma.P_WSS:
scheme = "wss"
default:
return nil, fmt.Errorf("not a websocket multiaddr")
}
network, host, err := manet.DialArgs(maddr)
if err != nil {
return nil, err
}
switch network {
case "tcp", "tcp4", "tcp6":
default:
return nil, fmt.Errorf("unsupported websocket network %s", network)
}
return &url.URL{
Scheme: scheme,
Host: host,
}, nil
}

81
p2p/transport/websocket/addrs_test.go

@ -0,0 +1,81 @@
package websocket
import (
"net/url"
"testing"
"github.com/stretchr/testify/require"
ma "github.com/multiformats/go-multiaddr"
)
func TestMultiaddrParsing(t *testing.T) {
addr, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/5555/ws")
if err != nil {
t.Fatal(err)
}
wsaddr, err := parseMultiaddr(addr)
if err != nil {
t.Fatal(err)
}
if wsaddr.String() != "ws://127.0.0.1:5555" {
t.Fatalf("expected ws://127.0.0.1:5555, got %s", wsaddr)
}
}
type httpAddr struct {
*url.URL
}
func (addr *httpAddr) Network() string {
return "http"
}
func TestParseWebsocketNetAddr(t *testing.T) {
notWs := &httpAddr{&url.URL{Host: "http://127.0.0.1:1234"}}
_, err := ParseWebsocketNetAddr(notWs)
if err.Error() != "not a websocket address" {
t.Fatalf("expect \"not a websocket address\", got \"%s\"", err)
}
wsAddr := NewAddrWithScheme("127.0.0.1:5555", false)
parsed, err := ParseWebsocketNetAddr(wsAddr)
if err != nil {
t.Fatal(err)
}
if parsed.String() != "/ip4/127.0.0.1/tcp/5555/ws" {
t.Fatalf("expected \"/ip4/127.0.0.1/tcp/5555/ws\", got \"%s\"", parsed.String())
}
}
func TestConvertWebsocketMultiaddrToNetAddr(t *testing.T) {
addr, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/5555/ws")
if err != nil {
t.Fatal(err)
}
wsaddr, err := ConvertWebsocketMultiaddrToNetAddr(addr)
if err != nil {
t.Fatal(err)
}
if wsaddr.String() != "ws://127.0.0.1:5555" {
t.Fatalf("expected ws://127.0.0.1:5555, got %s", wsaddr)
}
if wsaddr.Network() != "websocket" {
t.Fatalf("expected network: \"websocket\", got \"%s\"", wsaddr.Network())
}
}
func TestListeningOnDNSAddr(t *testing.T) {
ln, err := newListener(ma.StringCast("/dns/localhost/tcp/0/ws"), nil)
require.NoError(t, err)
addr := ln.Multiaddr()
first, rest := ma.SplitFirst(addr)
require.Equal(t, first.Protocol().Code, ma.P_DNS)
require.Equal(t, first.Value(), "localhost")
next, _ := ma.SplitFirst(rest)
require.Equal(t, next.Protocol().Code, ma.P_TCP)
require.NotEqual(t, next.Value(), "0")
}

151
p2p/transport/websocket/conn.go

@ -0,0 +1,151 @@
package websocket
import (
"io"
"net"
"sync"
"time"
ws "github.com/gorilla/websocket"
)
// GracefulCloseTimeout is the time to wait trying to gracefully close a
// connection before simply cutting it.
var GracefulCloseTimeout = 100 * time.Millisecond
// Conn implements net.Conn interface for gorilla/websocket.
type Conn struct {
*ws.Conn
secure bool
DefaultMessageType int
reader io.Reader
closeOnce sync.Once
readLock, writeLock sync.Mutex
}
var _ net.Conn = (*Conn)(nil)
// NewConn creates a Conn given a regular gorilla/websocket Conn.
func NewConn(raw *ws.Conn, secure bool) *Conn {
return &Conn{
Conn: raw,
secure: secure,
DefaultMessageType: ws.BinaryMessage,
}
}
func (c *Conn) Read(b []byte) (int, error) {
c.readLock.Lock()
defer c.readLock.Unlock()
if c.reader == nil {
if err := c.prepNextReader(); err != nil {
return 0, err
}
}
for {
n, err := c.reader.Read(b)
switch err {
case io.EOF:
c.reader = nil
if n > 0 {
return n, nil
}
if err := c.prepNextReader(); err != nil {
return 0, err
}
// explicitly looping
default:
return n, err
}
}
}
func (c *Conn) prepNextReader() error {
t, r, err := c.Conn.NextReader()
if err != nil {
if wserr, ok := err.(*ws.CloseError); ok {
if wserr.Code == 1000 || wserr.Code == 1005 {
return io.EOF
}
}
return err
}
if t == ws.CloseMessage {
return io.EOF
}
c.reader = r
return nil
}
func (c *Conn) Write(b []byte) (n int, err error) {
c.writeLock.Lock()
defer c.writeLock.Unlock()
if err := c.Conn.WriteMessage(c.DefaultMessageType, b); err != nil {
return 0, err
}
return len(b), nil
}
// Close closes the connection. Only the first call to Close will receive the
// close error, subsequent and concurrent calls will return nil.
// This method is thread-safe.
func (c *Conn) Close() error {
var err error
c.closeOnce.Do(func() {
err1 := c.Conn.WriteControl(
ws.CloseMessage,
ws.FormatCloseMessage(ws.CloseNormalClosure, "closed"),
time.Now().Add(GracefulCloseTimeout),
)
err2 := c.Conn.Close()
switch {
case err1 != nil:
err = err1
case err2 != nil:
err = err2
}
})
return err
}
func (c *Conn) LocalAddr() net.Addr {
return NewAddrWithScheme(c.Conn.LocalAddr().String(), c.secure)
}
func (c *Conn) RemoteAddr() net.Addr {
return NewAddrWithScheme(c.Conn.RemoteAddr().String(), c.secure)
}
func (c *Conn) SetDeadline(t time.Time) error {
if err := c.SetReadDeadline(t); err != nil {
return err
}
return c.SetWriteDeadline(t)
}
func (c *Conn) SetReadDeadline(t time.Time) error {
// Don't lock when setting the read deadline. That would prevent us from
// interrupting an in-progress read.
return c.Conn.SetReadDeadline(t)
}
func (c *Conn) SetWriteDeadline(t time.Time) error {
// Unlike the read deadline, we need to lock when setting the write
// deadline.
c.writeLock.Lock()
defer c.writeLock.Unlock()
return c.Conn.SetWriteDeadline(t)
}

127
p2p/transport/websocket/listener.go

@ -0,0 +1,127 @@
package websocket
import (
"crypto/tls"
"fmt"
"net"
"net/http"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
var (
wsma = ma.StringCast("/ws")
wssma = ma.StringCast("/wss")
)
type listener struct {
nl net.Listener
server http.Server
laddr ma.Multiaddr
closed chan struct{}
incoming chan *Conn
}
// newListener creates a new listener from a raw net.Listener.
// tlsConf may be nil (for unencrypted websockets).
func newListener(a ma.Multiaddr, tlsConf *tls.Config) (*listener, error) {
// Only look at the _last_ component.
maddr, wscomponent := ma.SplitLast(a)
isWSS := wscomponent.Equal(wssma)
if isWSS && tlsConf == nil {
return nil, fmt.Errorf("cannot listen on wss address %s without a tls.Config", a)
}
lnet, lnaddr, err := manet.DialArgs(maddr)
if err != nil {
return nil, err
}
nl, err := net.Listen(lnet, lnaddr)
if err != nil {
return nil, err
}
laddr, err := manet.FromNetAddr(nl.Addr())
if err != nil {
return nil, err
}
first, _ := ma.SplitFirst(a)
// Don't resolve dns addresses.
// We want to be able to announce domain names, so the peer can validate the TLS certificate.
if c := first.Protocol().Code; c == ma.P_DNS || c == ma.P_DNS4 || c == ma.P_DNS6 || c == ma.P_DNSADDR {
_, last := ma.SplitFirst(laddr)
laddr = first.Encapsulate(last)
}
ln := &listener{
nl: nl,
laddr: laddr.Encapsulate(wscomponent),
incoming: make(chan *Conn),
closed: make(chan struct{}),
}
ln.server = http.Server{Handler: ln}
if isWSS {
ln.server.TLSConfig = tlsConf
}
return ln, nil
}
func (l *listener) serve() {
defer close(l.closed)
if l.server.TLSConfig == nil {
l.server.Serve(l.nl)
} else {
l.server.ServeTLS(l.nl, "", "")
}
}
func (l *listener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
// The upgrader writes a response for us.
return
}
select {
case l.incoming <- NewConn(c, false):
case <-l.closed:
c.Close()
}
// The connection has been hijacked, it's safe to return.
}
func (l *listener) Accept() (manet.Conn, error) {
select {
case c, ok := <-l.incoming:
if !ok {
return nil, fmt.Errorf("listener is closed")
}
mnc, err := manet.WrapNetConn(c)
if err != nil {
c.Close()
return nil, err
}
return mnc, nil
case <-l.closed:
return nil, fmt.Errorf("listener is closed")
}
}
func (l *listener) Addr() net.Addr {
return l.nl.Addr()
}
func (l *listener) Close() error {
l.server.Close()
err := l.nl.Close()
<-l.closed
return err
}
func (l *listener) Multiaddr() ma.Multiaddr {
return l.laddr
}

155
p2p/transport/websocket/websocket.go

@ -0,0 +1,155 @@
// Package websocket implements a websocket based transport for go-libp2p.
package websocket
import (
"context"
"crypto/tls"
"net/http"
"time"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/transport"
ma "github.com/multiformats/go-multiaddr"
mafmt "github.com/multiformats/go-multiaddr-fmt"
manet "github.com/multiformats/go-multiaddr/net"
ws "github.com/gorilla/websocket"
)
// WsFmt is multiaddr formatter for WsProtocol
var WsFmt = mafmt.And(mafmt.TCP, mafmt.Base(ma.P_WS))
// This is _not_ WsFmt because we want the transport to stick to dialing fully
// resolved addresses.
var dialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_TCP), mafmt.Or(mafmt.Base(ma.P_WS), mafmt.Base(ma.P_WSS)))
func init() {
manet.RegisterFromNetAddr(ParseWebsocketNetAddr, "websocket")
manet.RegisterToNetAddr(ConvertWebsocketMultiaddrToNetAddr, "ws")
manet.RegisterToNetAddr(ConvertWebsocketMultiaddrToNetAddr, "wss")
}
// Default gorilla upgrader
var upgrader = ws.Upgrader{
// Allow requests from *all* origins.
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type Option func(*WebsocketTransport) error
// WithTLSClientConfig sets a TLS client configuration on the WebSocket Dialer. Only
// relevant for non-browser usages.
//
// Some useful use cases include setting InsecureSkipVerify to `true`, or
// setting user-defined trusted CA certificates.
func WithTLSClientConfig(c *tls.Config) Option {
return func(t *WebsocketTransport) error {
t.tlsClientConf = c
return nil
}
}
// WithTLSConfig sets a TLS configuration for the WebSocket listener.
func WithTLSConfig(conf *tls.Config) Option {
return func(t *WebsocketTransport) error {
t.tlsConf = conf
return nil
}
}
// WebsocketTransport is the actual go-libp2p transport
type WebsocketTransport struct {
upgrader transport.Upgrader
rcmgr network.ResourceManager
tlsClientConf *tls.Config
tlsConf *tls.Config
}
var _ transport.Transport = (*WebsocketTransport)(nil)
func New(u transport.Upgrader, rcmgr network.ResourceManager, opts ...Option) (*WebsocketTransport, error) {
if rcmgr == nil {
rcmgr = network.NullResourceManager
}
t := &WebsocketTransport{
upgrader: u,
rcmgr: rcmgr,
}
for _, opt := range opts {
if err := opt(t); err != nil {
return nil, err
}
}
return t, nil
}
func (t *WebsocketTransport) CanDial(a ma.Multiaddr) bool {
return dialMatcher.Matches(a)
}
func (t *WebsocketTransport) Protocols() []int {
return []int{ma.P_WS, ma.P_WSS}
}
func (t *WebsocketTransport) Proxy() bool {
return false
}
func (t *WebsocketTransport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (transport.CapableConn, error) {
connScope, err := t.rcmgr.OpenConnection(network.DirOutbound, true)
if err != nil {
return nil, err
}
macon, err := t.maDial(ctx, raddr)
if err != nil {
connScope.Done()
return nil, err
}
return t.upgrader.Upgrade(ctx, t, macon, network.DirOutbound, p, connScope)
}
func (t *WebsocketTransport) maDial(ctx context.Context, raddr ma.Multiaddr) (manet.Conn, error) {
wsurl, err := parseMultiaddr(raddr)
if err != nil {
return nil, err
}
isWss := wsurl.Scheme == "wss"
dialer := ws.Dialer{HandshakeTimeout: 30 * time.Second}
if isWss {
dialer.TLSClientConfig = t.tlsClientConf
}
wscon, _, err := dialer.DialContext(ctx, wsurl.String(), nil)
if err != nil {
return nil, err
}
mnc, err := manet.WrapNetConn(NewConn(wscon, isWss))
if err != nil {
wscon.Close()
return nil, err
}
return mnc, nil
}
func (t *WebsocketTransport) maListen(a ma.Multiaddr) (manet.Listener, error) {
l, err := newListener(a, t.tlsConf)
if err != nil {
return nil, err
}
go l.serve()
return l, nil
}
func (t *WebsocketTransport) Listen(a ma.Multiaddr) (transport.Listener, error) {
malist, err := t.maListen(a)
if err != nil {
return nil, err
}
return t.upgrader.UpgradeListener(t, malist), nil
}

350
p2p/transport/websocket/websocket_test.go

@ -0,0 +1,350 @@
package websocket
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io"
"io/ioutil"
"math/big"
"net"
"testing"
"time"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/sec"
"github.com/libp2p/go-libp2p-core/sec/insecure"
"github.com/libp2p/go-libp2p-core/test"
"github.com/libp2p/go-libp2p-core/transport"
csms "github.com/libp2p/go-conn-security-multistream"
mplex "github.com/libp2p/go-libp2p-mplex"
ttransport "github.com/libp2p/go-libp2p-testing/suites/transport"
tptu "github.com/libp2p/go-libp2p-transport-upgrader"
ma "github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/require"
)
func newUpgrader(t *testing.T) (peer.ID, transport.Upgrader) {
t.Helper()
id, m := newSecureMuxer(t)
u, err := tptu.New(m, new(mplex.Transport))
if err != nil {
t.Fatal(err)
}
return id, u
}
func newSecureMuxer(t *testing.T) (peer.ID, sec.SecureMuxer) {
t.Helper()
priv, _, err := test.RandTestKeyPair(crypto.Ed25519, 256)
if err != nil {
t.Fatal(err)
}
id, err := peer.IDFromPrivateKey(priv)
if err != nil {
t.Fatal(err)
}
var secMuxer csms.SSMuxer
secMuxer.AddTransport(insecure.ID, insecure.NewWithIdentity(id, priv))
return id, &secMuxer
}
func lastComponent(t *testing.T, a ma.Multiaddr) ma.Multiaddr {
t.Helper()
_, wscomponent := ma.SplitLast(a)
require.NotNil(t, wscomponent)
if wscomponent.Equal(wsma) {
return wsma
}
if wscomponent.Equal(wssma) {
return wssma
}
t.Fatal("expected a ws or wss component")
return nil
}
func generateTLSConfig(t *testing.T) *tls.Config {
t.Helper()
priv, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{},
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour), // valid for an hour
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, priv.Public(), priv)
require.NoError(t, err)
return &tls.Config{
Certificates: []tls.Certificate{{
PrivateKey: priv,
Certificate: [][]byte{certDER},
}},
}
}
func TestCanDial(t *testing.T) {
d := &WebsocketTransport{}
if !d.CanDial(ma.StringCast("/ip4/127.0.0.1/tcp/5555/ws")) {
t.Fatal("expected to match websocket maddr, but did not")
}
if !d.CanDial(ma.StringCast("/ip4/127.0.0.1/tcp/5555/wss")) {
t.Fatal("expected to match secure websocket maddr, but did not")
}
if d.CanDial(ma.StringCast("/ip4/127.0.0.1/tcp/5555")) {
t.Fatal("expected to not match tcp maddr, but did")
}
}
func TestDialWss(t *testing.T) {
if _, err := net.LookupIP("nyc-1.bootstrap.libp2p.io"); err != nil {
t.Skip("this test requries an internet connection and it seems like we currently don't have one")
}
raddr := ma.StringCast("/dns4/nyc-1.bootstrap.libp2p.io/tcp/443/wss")
rid, err := peer.Decode("QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm")
if err != nil {
t.Fatal(err)
}
tlsConfig := &tls.Config{InsecureSkipVerify: true}
_, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager, WithTLSClientConfig(tlsConfig))
if err != nil {
t.Fatal(err)
}
conn, err := tpt.Dial(context.Background(), raddr, rid)
if err != nil {
t.Fatal(err)
}
stream, err := conn.OpenStream(context.Background())
if err != nil {
t.Fatal(err)
}
defer stream.Close()
}
func TestWebsocketTransport(t *testing.T) {
t.Skip("This test is failing, see https://github.com/libp2p/go-ws-transport/issues/99")
_, ua := newUpgrader(t)
ta, err := New(ua, nil)
if err != nil {
t.Fatal(err)
}
_, ub := newUpgrader(t)
tb, err := New(ub, nil)
if err != nil {
t.Fatal(err)
}
ttransport.SubtestTransport(t, ta, tb, "/ip4/127.0.0.1/tcp/0/ws", "peerA")
}
func connectAndExchangeData(t *testing.T, laddr ma.Multiaddr, secure bool) {
var opts []Option
var tlsConf *tls.Config
if secure {
tlsConf = generateTLSConfig(t)
opts = append(opts, WithTLSConfig(tlsConf))
}
server, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager, opts...)
require.NoError(t, err)
l, err := tpt.Listen(laddr)
require.NoError(t, err)
if secure {
require.Equal(t, lastComponent(t, l.Multiaddr()), wssma)
} else {
require.Equal(t, lastComponent(t, l.Multiaddr()), wsma)
}
defer l.Close()
msg := []byte("HELLO WORLD")
go func() {
var opts []Option
if secure {
opts = append(opts, WithTLSClientConfig(&tls.Config{InsecureSkipVerify: true}))
}
_, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager, opts...)
require.NoError(t, err)
c, err := tpt.Dial(context.Background(), l.Multiaddr(), server)
require.NoError(t, err)
str, err := c.OpenStream(context.Background())
require.NoError(t, err)
defer str.Close()
_, err = str.Write(msg)
require.NoError(t, err)
}()
c, err := l.Accept()
require.NoError(t, err)
defer c.Close()
str, err := c.AcceptStream()
require.NoError(t, err)
defer str.Close()
out, err := ioutil.ReadAll(str)
require.NoError(t, err)
require.Equal(t, out, msg, "got wrong message")
}
func TestWebsocketConnection(t *testing.T) {
t.Run("unencrypted", func(t *testing.T) {
connectAndExchangeData(t, ma.StringCast("/ip4/127.0.0.1/tcp/0/ws"), false)
})
t.Run("encrypted", func(t *testing.T) {
connectAndExchangeData(t, ma.StringCast("/ip4/127.0.0.1/tcp/0/wss"), true)
})
}
func TestWebsocketListenSecureFailWithoutTLSConfig(t *testing.T) {
_, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager)
require.NoError(t, err)
addr := ma.StringCast("/ip4/127.0.0.1/tcp/0/wss")
_, err = tpt.Listen(addr)
require.EqualError(t, err, fmt.Sprintf("cannot listen on wss address %s without a tls.Config", addr))
}
func TestWebsocketListenSecureAndInsecure(t *testing.T) {
serverID, serverUpgrader := newUpgrader(t)
server, err := New(serverUpgrader, network.NullResourceManager, WithTLSConfig(generateTLSConfig(t)))
require.NoError(t, err)
lnInsecure, err := server.Listen(ma.StringCast("/ip4/127.0.0.1/tcp/0/ws"))
require.NoError(t, err)
lnSecure, err := server.Listen(ma.StringCast("/ip4/127.0.0.1/tcp/0/wss"))
require.NoError(t, err)
t.Run("insecure", func(t *testing.T) {
_, clientUpgrader := newUpgrader(t)
client, err := New(clientUpgrader, network.NullResourceManager, WithTLSClientConfig(&tls.Config{InsecureSkipVerify: true}))
require.NoError(t, err)
// dialing the insecure address should succeed
conn, err := client.Dial(context.Background(), lnInsecure.Multiaddr(), serverID)
require.NoError(t, err)
defer conn.Close()
require.Equal(t, lastComponent(t, conn.RemoteMultiaddr()).String(), wsma.String())
require.Equal(t, lastComponent(t, conn.LocalMultiaddr()).String(), wsma.String())
// dialing the secure address should fail
_, err = client.Dial(context.Background(), lnSecure.Multiaddr(), serverID)
require.NoError(t, err)
})
t.Run("secure", func(t *testing.T) {
_, clientUpgrader := newUpgrader(t)
client, err := New(clientUpgrader, network.NullResourceManager, WithTLSClientConfig(&tls.Config{InsecureSkipVerify: true}))
require.NoError(t, err)
// dialing the insecure address should succeed
conn, err := client.Dial(context.Background(), lnSecure.Multiaddr(), serverID)
require.NoError(t, err)
defer conn.Close()
require.Equal(t, lastComponent(t, conn.RemoteMultiaddr()), wssma)
require.Equal(t, lastComponent(t, conn.LocalMultiaddr()), wssma)
// dialing the insecure address should fail
_, err = client.Dial(context.Background(), lnInsecure.Multiaddr(), serverID)
require.NoError(t, err)
})
}
func TestConcurrentClose(t *testing.T) {
_, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager)
require.NoError(t, err)
l, err := tpt.maListen(ma.StringCast("/ip4/127.0.0.1/tcp/0/ws"))
if err != nil {
t.Fatal(err)
}
defer l.Close()
msg := []byte("HELLO WORLD")
go func() {
for i := 0; i < 100; i++ {
c, err := tpt.maDial(context.Background(), l.Multiaddr())
if err != nil {
t.Error(err)
return
}
go func() {
_, _ = c.Write(msg)
}()
go func() {
_ = c.Close()
}()
}
}()
for i := 0; i < 100; i++ {
c, err := l.Accept()
if err != nil {
t.Fatal(err)
}
c.Close()
}
}
func TestWriteZero(t *testing.T) {
_, u := newUpgrader(t)
tpt, err := New(u, network.NullResourceManager)
if err != nil {
t.Fatal(err)
}
l, err := tpt.maListen(ma.StringCast("/ip4/127.0.0.1/tcp/0/ws"))
if err != nil {
t.Fatal(err)
}
defer l.Close()
msg := []byte(nil)
go func() {
c, err := tpt.maDial(context.Background(), l.Multiaddr())
if err != nil {
t.Error(err)
return
}
defer c.Close()
for i := 0; i < 100; i++ {
n, err := c.Write(msg)
if n != 0 {
t.Errorf("expected to write 0 bytes, wrote %d", n)
}
if err != nil {
t.Error(err)
return
}
}
}()
c, err := l.Accept()
if err != nil {
t.Fatal(err)
}
defer c.Close()
buf := make([]byte, 100)
n, err := c.Read(buf)
if n != 0 {
t.Errorf("read %d bytes, expected 0", n)
}
if err != io.EOF {
t.Errorf("expected EOF, got err: %s", err)
}
}
Loading…
Cancel
Save