netbird/relay/client/dialer/ws/ws.go

60 lines
1.2 KiB
Go
Raw Normal View History

2024-06-28 11:17:06 +02:00
package ws
import (
"context"
"fmt"
"net"
2024-06-28 11:44:50 +02:00
"net/http"
2024-07-01 11:50:18 +02:00
"strings"
2024-06-19 18:16:23 +02:00
log "github.com/sirupsen/logrus"
"nhooyr.io/websocket"
2024-06-28 11:44:50 +02:00
nbnet "github.com/netbirdio/netbird/util/net"
)
func Dial(address string) (net.Conn, error) {
2024-07-01 11:50:18 +02:00
wsURL, err := prepareURL(address)
2024-06-19 18:16:23 +02:00
if err != nil {
return nil, err
}
opts := &websocket.DialOptions{
2024-06-28 11:44:50 +02:00
HTTPClient: httpClientNbDialer(),
2024-06-19 18:16:23 +02:00
}
2024-07-08 21:53:20 +02:00
wsConn, resp, err := websocket.Dial(context.Background(), wsURL, opts)
if err != nil {
2024-07-01 11:50:18 +02:00
log.Errorf("failed to dial to Relay server '%s': %s", wsURL, err)
return nil, err
}
2024-07-08 21:55:03 +02:00
if resp.Body != nil {
_ = resp.Body.Close()
}
conn := NewConn(wsConn, address)
return conn, nil
}
2024-06-28 11:44:50 +02:00
2024-07-01 11:50:18 +02:00
func prepareURL(address string) (string, error) {
if !strings.HasPrefix(address, "rel") {
return "", fmt.Errorf("unsupported scheme: %s", address)
}
return strings.Replace(address, "rel", "ws", 1), nil
}
2024-06-28 11:44:50 +02:00
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,
}
}