netbird/relay/client/manager.go

102 lines
2.2 KiB
Go
Raw Normal View History

2024-05-23 13:24:02 +02:00
package client
import (
"context"
2024-05-29 16:40:26 +02:00
"fmt"
2024-05-26 22:14:33 +02:00
"net"
"sync"
2024-05-23 13:24:02 +02:00
)
type Manager struct {
ctx context.Context
srvAddress string
peerID string
relayClient *Client
reconnectGuard *Guard
2024-05-23 13:24:02 +02:00
relayClients map[string]*Client
relayClientsMutex sync.Mutex
2024-05-23 13:24:02 +02:00
}
func NewManager(ctx context.Context, serverAddress string, peerID string) *Manager {
return &Manager{
2024-05-29 16:40:26 +02:00
ctx: ctx,
srvAddress: serverAddress,
peerID: peerID,
relayClients: make(map[string]*Client),
2024-05-23 13:24:02 +02:00
}
}
2024-05-29 16:40:26 +02:00
func (m *Manager) Serve() error {
m.relayClient = NewClient(m.ctx, m.srvAddress, m.peerID)
m.reconnectGuard = NewGuard(m.ctx, m.relayClient)
m.relayClient.SetOnDisconnectListener(m.reconnectGuard.OnDisconnected)
2024-05-29 16:40:26 +02:00
err := m.relayClient.Connect()
if err != nil {
return err
2024-05-23 13:24:02 +02:00
}
return nil
2024-05-26 22:14:33 +02:00
}
func (m *Manager) OpenConn(serverAddress, peerKey string) (net.Conn, error) {
2024-05-29 16:40:26 +02:00
if m.relayClient == nil {
return nil, fmt.Errorf("relay client not connected")
}
foreign, err := m.isForeignServer(serverAddress)
2024-05-29 16:40:26 +02:00
if err != nil {
return nil, err
2024-05-29 16:40:26 +02:00
}
if foreign {
return m.openConnVia(serverAddress, peerKey)
} else {
return m.relayClient.OpenConn(peerKey)
}
2024-05-26 22:14:33 +02:00
}
func (m *Manager) RelayAddress() (net.Addr, error) {
2024-05-29 16:40:26 +02:00
if m.relayClient == nil {
return nil, fmt.Errorf("relay client not connected")
}
return m.relayClient.RelayRemoteAddress()
}
2024-05-29 16:40:26 +02:00
func (m *Manager) openConnVia(serverAddress, peerKey string) (net.Conn, error) {
2024-05-29 16:40:26 +02:00
relayClient, ok := m.relayClients[serverAddress]
if ok {
return relayClient.OpenConn(peerKey)
}
relayClient = NewClient(m.ctx, serverAddress, m.peerID)
err := relayClient.Connect()
2024-05-29 16:40:26 +02:00
if err != nil {
return nil, err
}
relayClient.SetOnDisconnectListener(func() {
m.deleteRelayConn(serverAddress)
})
2024-05-29 16:40:26 +02:00
conn, err := relayClient.OpenConn(peerKey)
if err != nil {
return nil, err
}
m.relayClients[serverAddress] = relayClient
2024-05-29 16:40:26 +02:00
return conn, nil
2024-05-23 13:24:02 +02:00
}
func (m *Manager) deleteRelayConn(address string) {
delete(m.relayClients, address)
}
func (m *Manager) isForeignServer(address string) (bool, error) {
rAddr, err := m.relayClient.RelayRemoteAddress()
if err != nil {
return false, fmt.Errorf("relay client not connected")
}
return rAddr.String() != address, nil
}