open-vault/vendor/layeh.com/radius/server-packet.go

242 lines
4.8 KiB
Go
Raw Normal View History

2017-09-05 22:06:47 +00:00
package radius
import (
"context"
"errors"
"net"
"sync"
"sync/atomic"
)
type packetResponseWriter struct {
// listener that received the packet
conn net.PacketConn
addr net.Addr
}
func (r *packetResponseWriter) Write(packet *Packet) error {
encoded, err := packet.Encode()
2017-09-05 22:06:47 +00:00
if err != nil {
return err
}
if _, err := r.conn.WriteTo(encoded, r.addr); err != nil {
2017-09-05 22:06:47 +00:00
return err
}
return nil
}
// PacketServer listens for RADIUS requests on a packet-based protocols (e.g.
// UDP).
type PacketServer struct {
// The address on which the server listens. Defaults to :1812.
Addr string
2017-09-05 22:06:47 +00:00
// The network on which the server listens. Defaults to udp.
Network string
// The source from which the secret is obtained for parsing and validating
// the request.
2017-09-05 22:06:47 +00:00
SecretSource SecretSource
// Handler which is called to process the request.
Handler Handler
2017-09-05 22:06:47 +00:00
// Skip incoming packet authenticity validation.
// This should only be set to true for debugging purposes.
InsecureSkipVerify bool
2018-07-09 16:41:21 +00:00
shutdownRequested int32
mu sync.Mutex
ctx context.Context
ctxDone context.CancelFunc
listeners map[net.PacketConn]uint
lastActive chan struct{} // closed when the last active item finishes
activeCount int32
}
func (s *PacketServer) initLocked() {
if s.ctx == nil {
s.ctx, s.ctxDone = context.WithCancel(context.Background())
s.listeners = make(map[net.PacketConn]uint)
s.lastActive = make(chan struct{})
}
}
func (s *PacketServer) activeAdd() {
atomic.AddInt32(&s.activeCount, 1)
}
func (s *PacketServer) activeDone() {
if atomic.AddInt32(&s.activeCount, -1) == -1 {
close(s.lastActive)
}
2017-09-05 22:06:47 +00:00
}
// TODO: logger on PacketServer
// Serve accepts incoming connections on conn.
func (s *PacketServer) Serve(conn net.PacketConn) error {
if s.Handler == nil {
return errors.New("radius: nil Handler")
}
if s.SecretSource == nil {
return errors.New("radius: nil SecretSource")
}
s.mu.Lock()
2018-07-09 16:41:21 +00:00
s.initLocked()
if atomic.LoadInt32(&s.shutdownRequested) == 1 {
2017-09-05 22:06:47 +00:00
s.mu.Unlock()
return ErrServerShutdown
}
2018-07-09 16:41:21 +00:00
2017-09-05 22:06:47 +00:00
s.listeners[conn]++
s.mu.Unlock()
2018-07-09 16:41:21 +00:00
type requestKey struct {
2017-09-05 22:06:47 +00:00
IP string
Identifier byte
}
var (
2018-07-09 16:41:21 +00:00
requestsLock sync.Mutex
requests = map[requestKey]struct{}{}
2017-09-05 22:06:47 +00:00
)
2018-07-09 16:41:21 +00:00
s.activeAdd()
2017-09-05 22:06:47 +00:00
defer func() {
s.mu.Lock()
s.listeners[conn]--
if s.listeners[conn] == 0 {
delete(s.listeners, conn)
}
s.mu.Unlock()
2018-07-09 16:41:21 +00:00
s.activeDone()
2017-09-05 22:06:47 +00:00
}()
var buff [MaxPacketLength]byte
2017-09-05 22:06:47 +00:00
for {
n, remoteAddr, err := conn.ReadFrom(buff[:])
if err != nil {
2018-07-09 16:41:21 +00:00
if atomic.LoadInt32(&s.shutdownRequested) == 1 {
return ErrServerShutdown
2017-09-05 22:06:47 +00:00
}
if ne, ok := err.(net.Error); ok && !ne.Temporary() {
return err
}
continue
}
2018-07-09 16:41:21 +00:00
s.activeAdd()
2017-09-05 22:06:47 +00:00
go func(buff []byte, remoteAddr net.Addr) {
2018-07-09 16:41:21 +00:00
defer s.activeDone()
secret, err := s.SecretSource.RADIUSSecret(s.ctx, remoteAddr)
2017-09-05 22:06:47 +00:00
if err != nil {
return
}
if len(secret) == 0 {
return
}
if !s.InsecureSkipVerify && !IsAuthenticRequest(buff, secret) {
return
}
packet, err := Parse(buff, secret)
if err != nil {
return
}
2018-07-09 16:41:21 +00:00
key := requestKey{
2017-09-05 22:06:47 +00:00
IP: remoteAddr.String(),
Identifier: packet.Identifier,
}
2018-07-09 16:41:21 +00:00
requestsLock.Lock()
if _, ok := requests[key]; ok {
requestsLock.Unlock()
2017-09-05 22:06:47 +00:00
return
}
2018-07-09 16:41:21 +00:00
requests[key] = struct{}{}
requestsLock.Unlock()
2017-09-05 22:06:47 +00:00
response := packetResponseWriter{
conn: conn,
addr: remoteAddr,
}
defer func() {
2018-07-09 16:41:21 +00:00
requestsLock.Lock()
delete(requests, key)
requestsLock.Unlock()
2017-09-05 22:06:47 +00:00
}()
request := Request{
LocalAddr: conn.LocalAddr(),
RemoteAddr: remoteAddr,
Packet: packet,
2018-07-09 16:41:21 +00:00
ctx: s.ctx,
2017-09-05 22:06:47 +00:00
}
s.Handler.ServeRADIUS(&response, &request)
2018-07-09 16:41:21 +00:00
}(append([]byte(nil), buff[:n]...), remoteAddr)
2017-09-05 22:06:47 +00:00
}
}
// ListenAndServe starts a RADIUS server on the address given in s.
func (s *PacketServer) ListenAndServe() error {
if s.Handler == nil {
return errors.New("radius: nil Handler")
}
if s.SecretSource == nil {
return errors.New("radius: nil SecretSource")
}
addrStr := ":1812"
if s.Addr != "" {
addrStr = s.Addr
}
network := "udp"
if s.Network != "" {
network = s.Network
}
pc, err := net.ListenPacket(network, addrStr)
if err != nil {
return err
}
defer pc.Close()
return s.Serve(pc)
}
2018-07-09 16:41:21 +00:00
// Shutdown gracefully stops the server. It first closes all listeners and then
// waits for any running handlers to complete.
2017-09-05 22:06:47 +00:00
//
2018-07-09 16:41:21 +00:00
// Shutdown returns after nil all handlers have completed. ctx.Err() is
// returned if ctx is canceled.
//
2018-07-11 20:04:02 +00:00
// Any Serve methods return ErrShutdown after Shutdown is called.
2017-09-05 22:06:47 +00:00
func (s *PacketServer) Shutdown(ctx context.Context) error {
s.mu.Lock()
2018-07-09 16:41:21 +00:00
s.initLocked()
if atomic.CompareAndSwapInt32(&s.shutdownRequested, 0, 1) {
2017-09-05 22:06:47 +00:00
for listener := range s.listeners {
listener.Close()
}
2018-07-09 16:41:21 +00:00
s.ctxDone()
s.activeDone()
}
2017-09-05 22:06:47 +00:00
s.mu.Unlock()
select {
2018-07-09 16:41:21 +00:00
case <-s.lastActive:
2017-09-05 22:06:47 +00:00
return nil
case <-ctx.Done():
return ctx.Err()
}
}