2024-06-28 11:17:06 +02:00
|
|
|
package ws
|
2024-06-03 21:38:37 +02:00
|
|
|
|
|
|
|
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-03 21:38:37 +02:00
|
|
|
|
2024-06-19 18:16:23 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
2024-06-03 21:38:37 +02:00
|
|
|
"nhooyr.io/websocket"
|
2024-06-28 11:44:50 +02:00
|
|
|
|
|
|
|
nbnet "github.com/netbirdio/netbird/util/net"
|
2024-06-03 21:38:37 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
2024-06-03 21:38:37 +02:00
|
|
|
if err != nil {
|
2024-07-01 11:50:18 +02:00
|
|
|
log.Errorf("failed to dial to Relay server '%s': %s", wsURL, err)
|
2024-06-03 21:38:37 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2024-07-08 21:55:03 +02:00
|
|
|
if resp.Body != nil {
|
|
|
|
_ = resp.Body.Close()
|
|
|
|
}
|
2024-07-10 10:12:49 +02:00
|
|
|
|
2024-07-16 11:02:32 +02:00
|
|
|
conn := NewConn(wsConn, address)
|
2024-06-03 21:38:37 +02:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|