open-vault/vendor/layeh.com/radius/client.go

93 lines
1.9 KiB
Go
Raw Normal View History

2017-09-05 22:06:47 +00:00
package radius
2017-02-07 21:04:27 +00:00
import (
2017-09-05 22:06:47 +00:00
"context"
2017-02-07 21:04:27 +00:00
"net"
"time"
)
2017-09-05 22:06:47 +00:00
// Client is a RADIUS client that can exchange packets with a RADIUS server.
2017-02-07 21:04:27 +00:00
type Client struct {
// Network on which to make the connection. Defaults to "udp".
Net string
2017-09-05 22:06:47 +00:00
// Dialer to use when making the outgoing connections.
Dialer net.Dialer
2017-02-07 21:04:27 +00:00
2017-09-05 22:06:47 +00:00
// Interval on which to resend packet (zero or negative value means no
// retry).
2017-02-07 21:04:27 +00:00
Retry time.Duration
2017-09-05 22:06:47 +00:00
InsecureSkipVerify bool
2017-02-07 21:04:27 +00:00
}
2017-09-05 22:06:47 +00:00
// DefaultClient is the RADIUS client used by the Exchange function.
var DefaultClient = &Client{}
// Exchange uses DefaultClient to send the given RADIUS packet to the server at
// address addr and waits for a response.
func Exchange(ctx context.Context, packet *Packet, addr string) (*Packet, error) {
return DefaultClient.Exchange(ctx, packet, addr)
}
// Exchange sends the packet to the given server and waits for a response. ctx
// must be non-nil.
func (c *Client) Exchange(ctx context.Context, packet *Packet, addr string) (*Packet, error) {
if ctx == nil {
panic("nil context")
}
2017-02-07 21:04:27 +00:00
wire, err := packet.Encode()
if err != nil {
return nil, err
}
connNet := c.Net
if connNet == "" {
connNet = "udp"
}
2017-09-05 22:06:47 +00:00
conn, err := c.Dialer.DialContext(ctx, connNet, addr)
2017-02-07 21:04:27 +00:00
if err != nil {
return nil, err
}
2017-09-05 22:06:47 +00:00
defer conn.Close()
2017-02-07 21:04:27 +00:00
2017-09-05 22:06:47 +00:00
if deadline, deadlineSet := ctx.Deadline(); deadlineSet {
conn.SetDeadline(deadline)
2017-02-07 21:04:27 +00:00
}
conn.Write(wire)
if c.Retry > 0 {
retry := time.NewTicker(c.Retry)
2017-09-05 22:06:47 +00:00
defer retry.Stop()
2017-02-07 21:04:27 +00:00
end := make(chan struct{})
defer close(end)
go func() {
for {
select {
case <-retry.C:
conn.Write(wire)
2017-09-05 22:06:47 +00:00
case <-ctx.Done():
return
2017-02-07 21:04:27 +00:00
case <-end:
return
}
}
}()
}
2017-09-05 22:06:47 +00:00
var incoming [MaxPacketLength]byte
2017-02-07 21:04:27 +00:00
for {
n, err := conn.Read(incoming[:])
if err != nil {
return nil, err
}
2017-09-05 22:06:47 +00:00
received, err := Parse(incoming[:n], packet.Secret)
if err == nil && (!c.InsecureSkipVerify && IsAuthenticResponse(incoming[:n], wire, packet.Secret)) {
2017-02-07 21:04:27 +00:00
return received, nil
}
}
}