2024-04-17 15:44:38 +01:00
|
|
|
package networking
|
|
|
|
|
|
|
|
import (
|
2024-04-18 13:06:16 +01:00
|
|
|
"crypto/tls"
|
2024-04-17 15:44:38 +01:00
|
|
|
"fmt"
|
2024-04-18 17:15:47 +01:00
|
|
|
"log"
|
2024-04-17 15:44:38 +01:00
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
2024-04-18 13:06:16 +01:00
|
|
|
type ServerTLSConfigProvider interface {
|
2024-04-19 02:19:22 +01:00
|
|
|
GetServerTLSConfig() *tls.Config
|
2024-04-18 13:06:16 +01:00
|
|
|
}
|
|
|
|
|
2024-04-17 15:44:38 +01:00
|
|
|
type Server[T any] struct {
|
|
|
|
listener net.Listener
|
|
|
|
C chan Connection[T]
|
|
|
|
}
|
|
|
|
|
2024-04-18 17:15:47 +01:00
|
|
|
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider, port int) Server[T] {
|
2024-04-17 15:44:38 +01:00
|
|
|
|
2024-04-19 02:19:22 +01:00
|
|
|
listener, err := tls.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port), serverTLSConfigProvider.GetServerTLSConfig())
|
2024-04-17 15:44:38 +01:00
|
|
|
if err != nil {
|
|
|
|
panic("Server could not bind to address")
|
|
|
|
}
|
2024-04-18 17:15:47 +01:00
|
|
|
return Server[T]{
|
|
|
|
listener: listener,
|
|
|
|
C: make(chan Connection[T]),
|
|
|
|
}
|
2024-04-17 15:44:38 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server[T]) ListenLoop() {
|
|
|
|
|
|
|
|
for {
|
|
|
|
listenerConn, err := s.listener.Accept()
|
|
|
|
if err != nil {
|
|
|
|
panic("Server could not accept connection")
|
|
|
|
}
|
2024-04-18 17:15:47 +01:00
|
|
|
tlsConn, ok := listenerConn.(*tls.Conn)
|
|
|
|
if !ok {
|
|
|
|
panic("Connection is not a TLS connection")
|
|
|
|
}
|
2024-04-19 02:19:22 +01:00
|
|
|
tlsConn.Handshake()
|
2024-04-18 17:15:47 +01:00
|
|
|
|
|
|
|
state := tlsConn.ConnectionState()
|
|
|
|
if len(state.PeerCertificates) == 0 {
|
|
|
|
log.Panicln("Client did not provide a certificate")
|
|
|
|
}
|
|
|
|
conn := NewConnection[T](tlsConn)
|
2024-04-17 15:44:38 +01:00
|
|
|
s.C <- conn
|
|
|
|
}
|
|
|
|
}
|