57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
|
package networking
|
||
|
|
||
|
import (
|
||
|
"crypto/tls"
|
||
|
"log"
|
||
|
"net"
|
||
|
)
|
||
|
|
||
|
type ServerTLSConfigProvider interface {
|
||
|
GetServerTLSConfig() *tls.Config
|
||
|
}
|
||
|
|
||
|
type Server[T any] struct {
|
||
|
listener net.Listener
|
||
|
C chan Connection[T]
|
||
|
}
|
||
|
|
||
|
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider) (Server[T], error) {
|
||
|
|
||
|
listener, err := tls.Listen("tcp", "127.0.0.1:8080", serverTLSConfigProvider.GetServerTLSConfig())
|
||
|
if err != nil {
|
||
|
return Server[T]{}, err
|
||
|
}
|
||
|
return Server[T]{
|
||
|
listener: listener,
|
||
|
C: make(chan Connection[T]),
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func (s *Server[T]) ListenLoop() {
|
||
|
|
||
|
for {
|
||
|
listenerConn, err := s.listener.Accept()
|
||
|
if err != nil {
|
||
|
log.Println("Server could not accept connection")
|
||
|
continue
|
||
|
}
|
||
|
tlsConn, ok := listenerConn.(*tls.Conn)
|
||
|
if !ok {
|
||
|
log.Println("Connection is not a TLS connection")
|
||
|
continue
|
||
|
}
|
||
|
if err := tlsConn.Handshake(); err != nil {
|
||
|
log.Println(err)
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
state := tlsConn.ConnectionState()
|
||
|
if len(state.PeerCertificates) == 0 {
|
||
|
log.Println("Client did not provide a certificate")
|
||
|
continue
|
||
|
}
|
||
|
conn := NewConnection[T](tlsConn)
|
||
|
s.C <- conn
|
||
|
}
|
||
|
}
|