mirror of
https://github.com/netbirdio/netbird.git
synced 2024-11-25 17:43:38 +01:00
0c039274a4
This update adds new relay integration for NetBird clients. The new relay is based on web sockets and listens on a single port. - Adds new relay implementation with websocket with single port relaying mechanism - refactor peer connection logic, allowing upgrade and downgrade from/to P2P connection - peer connections are faster since it connects first to relay and then upgrades to P2P - maintains compatibility with old clients by not using the new relay - updates infrastructure scripts with new relay service
68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package ws
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"nhooyr.io/websocket"
|
|
|
|
"github.com/netbirdio/netbird/relay/server/listener/ws"
|
|
nbnet "github.com/netbirdio/netbird/util/net"
|
|
)
|
|
|
|
func Dial(address string) (net.Conn, error) {
|
|
wsURL, err := prepareURL(address)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
opts := &websocket.DialOptions{
|
|
HTTPClient: httpClientNbDialer(),
|
|
}
|
|
|
|
parsedURL, err := url.Parse(wsURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
parsedURL.Path = ws.URLPath
|
|
|
|
wsConn, resp, err := websocket.Dial(context.Background(), parsedURL.String(), opts)
|
|
if err != nil {
|
|
log.Errorf("failed to dial to Relay server '%s': %s", wsURL, err)
|
|
return nil, err
|
|
}
|
|
if resp.Body != nil {
|
|
_ = resp.Body.Close()
|
|
}
|
|
|
|
conn := NewConn(wsConn, address)
|
|
return conn, nil
|
|
}
|
|
|
|
func prepareURL(address string) (string, error) {
|
|
if !strings.HasPrefix(address, "rel:") && !strings.HasPrefix(address, "rels:") {
|
|
return "", fmt.Errorf("unsupported scheme: %s", address)
|
|
}
|
|
|
|
return strings.Replace(address, "rel", "ws", 1), nil
|
|
}
|
|
|
|
func httpClientNbDialer() *http.Client {
|
|
customDialer := nbnet.NewDialer()
|
|
|
|
customTransport := &http.Transport{
|
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return customDialer.DialContext(ctx, network, addr)
|
|
},
|
|
}
|
|
|
|
return &http.Client{
|
|
Transport: customTransport,
|
|
}
|
|
}
|