forked from diegoguarnieri/radius
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
100 lines (85 loc) · 1.98 KB
/
client.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
package radius
import (
"net"
"time"
)
// Client is a RADIUS client that can send and receive packets to and from a
// RADIUS server.
type Client struct {
// Network on which to make the connection. Defaults to "udp".
Net string
// Local address to use for outgoing connections (can be nil).
LocalAddr net.Addr
// Timeouts for various operations. Default values for each field is 10
// seconds.
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
// Interval on which to resend packet.
Retry time.Duration
}
// Exchange sends the packet to the given server address and waits for a
// response. nil and an error is returned upon failure.
func (c *Client) Exchange(packet *Packet, addr string) (*Packet, error) {
wire, err := packet.Encode()
if err != nil {
return nil, err
}
connNet := c.Net
if connNet == "" {
connNet = "udp"
}
const defaultTimeout = 10 * time.Second
dialTimeout := c.DialTimeout
if dialTimeout == 0 {
dialTimeout = defaultTimeout
}
dialer := net.Dialer{
Timeout: dialTimeout,
LocalAddr: c.LocalAddr,
}
conn, err := dialer.Dial(connNet, addr)
if err != nil {
return nil, err
}
writeTimeout := c.WriteTimeout
if writeTimeout == 0 {
writeTimeout = defaultTimeout
}
conn.SetWriteDeadline(time.Now().Add(writeTimeout))
conn.Write(wire)
if c.Retry > 0 {
retry := time.NewTicker(c.Retry)
end := make(chan struct{})
defer close(end)
go func() {
for {
select {
case <-retry.C:
conn.Write(wire)
case <-end:
retry.Stop()
return
}
}
}()
}
var incoming [maxPacketSize]byte
readTimeout := c.ReadTimeout
if readTimeout == 0 {
readTimeout = defaultTimeout
}
conn.SetReadDeadline(time.Now().Add(readTimeout))
for {
n, err := conn.Read(incoming[:])
if err != nil {
conn.Close()
return nil, err
}
received, err := Parse(incoming[:n], packet.Secret, packet.Dictionary)
if err == nil && received.IsAuthentic(packet) {
conn.Close()
return received, nil
}
}
}