forked from layeh/radius
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server-packet.go
259 lines (219 loc) · 5.45 KB
/
server-packet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package radius
import (
"context"
"errors"
"log"
"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()
if err != nil {
return err
}
if _, err := r.conn.WriteTo(encoded, r.addr); err != nil {
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
// 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.
SecretSource SecretSource
// Handler which is called to process the request.
Handler Handler
// Skip incoming packet authenticity validation.
// This should only be set to true for debugging purposes.
InsecureSkipVerify bool
// ErrorLog specifies an optional logger for errors
// around packet accepting, processing, and validation.
// If nil, logging is done via the log package's standard logger.
ErrorLog *log.Logger
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)
}
}
func (s *PacketServer) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// 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()
s.initLocked()
if atomic.LoadInt32(&s.shutdownRequested) == 1 {
s.mu.Unlock()
return ErrServerShutdown
}
s.listeners[conn]++
s.mu.Unlock()
type requestKey struct {
IP string
Identifier byte
}
var (
requestsLock sync.Mutex
requests = map[requestKey]struct{}{}
)
s.activeAdd()
defer func() {
s.mu.Lock()
s.listeners[conn]--
if s.listeners[conn] == 0 {
delete(s.listeners, conn)
}
s.mu.Unlock()
s.activeDone()
}()
var buff [MaxPacketLength]byte
for {
n, remoteAddr, err := conn.ReadFrom(buff[:])
if err != nil {
if atomic.LoadInt32(&s.shutdownRequested) == 1 {
return ErrServerShutdown
}
if ne, ok := err.(net.Error); ok && !ne.Temporary() {
return err
}
s.logf("radius: could not read packet: %v", err)
continue
}
s.activeAdd()
go func(buff []byte, remoteAddr net.Addr) {
defer s.activeDone()
secret, err := s.SecretSource.RADIUSSecret(s.ctx, remoteAddr)
if err != nil {
s.logf("radius: error fetching from secret source: %v", err)
return
}
if len(secret) == 0 {
s.logf("radius: empty secret returned from secret source")
return
}
if !s.InsecureSkipVerify && !IsAuthenticRequest(buff, secret) {
s.logf("radius: packet validation failed; bad secret")
return
}
packet, err := Parse(buff, nil, secret)
if err != nil {
s.logf("radius: unable to parse packet: %v", err)
return
}
key := requestKey{
IP: remoteAddr.String(),
Identifier: packet.Identifier,
}
requestsLock.Lock()
if _, ok := requests[key]; ok {
requestsLock.Unlock()
return
}
requests[key] = struct{}{}
requestsLock.Unlock()
response := packetResponseWriter{
conn: conn,
addr: remoteAddr,
}
defer func() {
requestsLock.Lock()
delete(requests, key)
requestsLock.Unlock()
}()
request := Request{
LocalAddr: conn.LocalAddr(),
RemoteAddr: remoteAddr,
Packet: packet,
ctx: s.ctx,
}
s.Handler.ServeRADIUS(&response, &request)
}(append([]byte(nil), buff[:n]...), remoteAddr)
}
}
// 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)
}
// Shutdown gracefully stops the server. It first closes all listeners and then
// waits for any running handlers to complete.
//
// Shutdown returns after nil all handlers have completed. ctx.Err() is
// returned if ctx is canceled.
//
// Any Serve methods return ErrShutdown after Shutdown is called.
func (s *PacketServer) Shutdown(ctx context.Context) error {
s.mu.Lock()
s.initLocked()
if atomic.CompareAndSwapInt32(&s.shutdownRequested, 0, 1) {
for listener := range s.listeners {
listener.Close()
}
s.ctxDone()
s.activeDone()
}
s.mu.Unlock()
select {
case <-s.lastActive:
return nil
case <-ctx.Done():
return ctx.Err()
}
}