2024-05-17 17:43:28 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-06-27 02:36:44 +02:00
|
|
|
"context"
|
2024-05-26 22:14:33 +02:00
|
|
|
"errors"
|
|
|
|
"sync"
|
2024-06-27 02:36:44 +02:00
|
|
|
"time"
|
2024-05-17 17:43:28 +02:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/relay/server/listener"
|
2024-05-19 12:41:06 +02:00
|
|
|
"github.com/netbirdio/netbird/relay/server/listener/udp"
|
2024-06-27 02:36:44 +02:00
|
|
|
"github.com/netbirdio/netbird/relay/server/listener/ws"
|
2024-06-26 15:26:19 +02:00
|
|
|
)
|
|
|
|
|
2024-05-17 17:43:28 +02:00
|
|
|
type Server struct {
|
2024-06-27 02:36:44 +02:00
|
|
|
relay *Relay
|
|
|
|
uDPListener listener.Listener
|
|
|
|
wSListener listener.Listener
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServer() *Server {
|
|
|
|
return &Server{
|
2024-06-27 02:36:44 +02:00
|
|
|
relay: NewRelay(),
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Server) Listen(address string) error {
|
2024-05-26 22:14:33 +02:00
|
|
|
wg := sync.WaitGroup{}
|
|
|
|
wg.Add(2)
|
|
|
|
|
2024-06-27 02:36:44 +02:00
|
|
|
r.wSListener = ws.NewListener(address)
|
2024-05-26 22:14:33 +02:00
|
|
|
var wslErr error
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
2024-06-27 02:36:44 +02:00
|
|
|
wslErr = r.wSListener.Listen(r.relay.Accept)
|
2024-05-26 22:14:33 +02:00
|
|
|
if wslErr != nil {
|
|
|
|
log.Errorf("failed to bind ws server: %s", wslErr)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-06-27 02:36:44 +02:00
|
|
|
r.uDPListener = udp.NewListener(address)
|
2024-05-26 22:14:33 +02:00
|
|
|
var udpLErr error
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
2024-06-27 02:36:44 +02:00
|
|
|
udpLErr = r.uDPListener.Listen(r.relay.Accept)
|
2024-05-26 22:14:33 +02:00
|
|
|
if udpLErr != nil {
|
|
|
|
log.Errorf("failed to bind ws server: %s", udpLErr)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
err := errors.Join(wslErr, udpLErr)
|
|
|
|
return err
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Server) Close() error {
|
2024-05-26 22:14:33 +02:00
|
|
|
var wErr error
|
2024-06-27 02:36:44 +02:00
|
|
|
// stop service new connections
|
|
|
|
if r.wSListener != nil {
|
|
|
|
wErr = r.wSListener.Close()
|
2024-05-26 22:14:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var uErr error
|
2024-06-27 02:36:44 +02:00
|
|
|
if r.uDPListener != nil {
|
|
|
|
uErr = r.uDPListener.Close()
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
2024-06-05 19:49:30 +02:00
|
|
|
|
2024-06-27 02:36:44 +02:00
|
|
|
// close accepted connections gracefully
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
r.relay.Close(ctx)
|
2024-06-05 19:49:30 +02:00
|
|
|
|
2024-05-26 22:14:33 +02:00
|
|
|
err := errors.Join(wErr, uErr)
|
|
|
|
return err
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|