summaryrefslogtreecommitdiffhomepage
path: root/dhcpv6/server6
diff options
context:
space:
mode:
authorAndrea Barberio <insomniac@slackware.it>2019-01-27 23:48:44 +0000
committerinsomniac <insomniacslk@users.noreply.github.com>2019-01-28 11:21:18 +0000
commit82434691f0602844a2156a4d2037d43c51900b73 (patch)
tree87219ad692783ca5487affc728d12d38b3388b1b /dhcpv6/server6
parent64f29461718b0dac77d8156ceceacce086fe14b2 (diff)
dhcpv6: moved client into dhcpv6/client6
Diffstat (limited to 'dhcpv6/server6')
-rw-r--r--dhcpv6/server6/server.go163
-rw-r--r--dhcpv6/server6/server_test.go79
2 files changed, 242 insertions, 0 deletions
diff --git a/dhcpv6/server6/server.go b/dhcpv6/server6/server.go
new file mode 100644
index 0000000..5c84f97
--- /dev/null
+++ b/dhcpv6/server6/server.go
@@ -0,0 +1,163 @@
+package server6
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "sync"
+ "time"
+
+ "github.com/insomniacslk/dhcp/dhcpv6"
+)
+
+/*
+ To use the DHCPv6 server code you have to call NewServer with two arguments:
+ - a handler function, that will be called every time a valid DHCPv6 packet is
+ received, and
+ - an address to listen on.
+
+ The handler is a function that takes as input a packet connection, that can be
+ used to reply to the client; a peer address, that identifies the client sending
+ the request, and the DHCPv6 packet itself. Just implement your custom logic in
+ the handler.
+
+ The address to listen on is used to know IP address, port and optionally the
+ scope to create and UDP6 socket to listen on for DHCPv6 traffic.
+
+ Example program:
+
+
+package main
+
+import (
+ "log"
+ "net"
+
+ "github.com/insomniacslk/dhcp/dhcpv6"
+)
+
+func handler(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6) {
+ // this function will just print the received DHCPv6 message, without replying
+ log.Print(m.Summary())
+}
+
+func main() {
+ laddr := net.UDPAddr{
+ IP: net.ParseIP("::1"),
+ Port: dhcpv6.DefaultServerPort,
+ }
+ server := dhcpv6.NewServer(laddr, handler)
+
+ defer server.Close()
+ if err := server.ActivateAndServe(); err != nil {
+ log.Panic(err)
+ }
+}
+
+*/
+
+// Handler is a type that defines the handler function to be called every time a
+// valid DHCPv6 message is received
+type Handler func(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6)
+
+// Server represents a DHCPv6 server object
+type Server struct {
+ conn net.PacketConn
+ connMutex sync.Mutex
+ shouldStop chan bool
+ Handler Handler
+ localAddr net.UDPAddr
+}
+
+// LocalAddr returns the local address of the listening socket, or nil if not
+// listening
+func (s *Server) LocalAddr() net.Addr {
+ s.connMutex.Lock()
+ defer s.connMutex.Unlock()
+ if s.conn == nil {
+ return nil
+ }
+ return s.conn.LocalAddr()
+}
+
+// ActivateAndServe starts the DHCPv6 server. The listener will run in
+// background, and can be interrupted with `Server.Close`.
+func (s *Server) ActivateAndServe() error {
+ s.connMutex.Lock()
+ if s.conn != nil {
+ // this may panic if s.conn is closed but not reset properly. For that
+ // you should use `Server.Close`.
+ s.Close()
+ }
+ conn, err := net.ListenUDP("udp6", &s.localAddr)
+ if err != nil {
+ s.connMutex.Unlock()
+ return err
+ }
+ s.conn = conn
+ s.connMutex.Unlock()
+ var (
+ pc *net.UDPConn
+ ok bool
+ )
+ if pc, ok = s.conn.(*net.UDPConn); !ok {
+ return fmt.Errorf("error: not an UDPConn")
+ }
+ if pc == nil {
+ return fmt.Errorf("ActivateAndServe: invalid nil PacketConn")
+ }
+ log.Printf("Server listening on %s", pc.LocalAddr())
+ log.Print("Ready to handle requests")
+ for {
+ select {
+ case <-s.shouldStop:
+ break
+ case <-time.After(time.Millisecond):
+ }
+ pc.SetReadDeadline(time.Now().Add(time.Second))
+ rbuf := make([]byte, 4096) // FIXME this is bad
+ n, peer, err := pc.ReadFrom(rbuf)
+ if err != nil {
+ switch err.(type) {
+ case net.Error:
+ if !err.(net.Error).Timeout() {
+ return err
+ }
+ // if timeout, silently skip and continue
+ default:
+ // complain and continue
+ log.Printf("Error reading from packet conn: %v", err)
+ }
+ continue
+ }
+ log.Printf("Handling request from %v", peer)
+ m, err := dhcpv6.FromBytes(rbuf[:n])
+ if err != nil {
+ log.Printf("Error parsing DHCPv6 request: %v", err)
+ continue
+ }
+ go s.Handler(pc, peer, m)
+ }
+}
+
+// Close sends a termination request to the server, and closes the UDP listener
+func (s *Server) Close() error {
+ s.shouldStop <- true
+ s.connMutex.Lock()
+ defer s.connMutex.Unlock()
+ if s.conn != nil {
+ ret := s.conn.Close()
+ s.conn = nil
+ return ret
+ }
+ return nil
+}
+
+// NewServer initializes and returns a new Server object
+func NewServer(addr net.UDPAddr, handler Handler) *Server {
+ return &Server{
+ localAddr: addr,
+ Handler: handler,
+ shouldStop: make(chan bool, 1),
+ }
+}
diff --git a/dhcpv6/server6/server_test.go b/dhcpv6/server6/server_test.go
new file mode 100644
index 0000000..2365b96
--- /dev/null
+++ b/dhcpv6/server6/server_test.go
@@ -0,0 +1,79 @@
+package server6
+
+import (
+ "log"
+ "net"
+ "testing"
+ "time"
+
+ "github.com/insomniacslk/dhcp/dhcpv6"
+ "github.com/insomniacslk/dhcp/dhcpv6/client6"
+ "github.com/insomniacslk/dhcp/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+// utility function to set up a client and a server instance and run it in
+// background. The caller needs to call Server.Close() once finished.
+func setUpClientAndServer(handler Handler) (*client6.Client, *Server) {
+ laddr := net.UDPAddr{
+ IP: net.ParseIP("::1"),
+ Port: 0,
+ }
+ s := NewServer(laddr, handler)
+ go s.ActivateAndServe()
+
+ c := client6.NewClient()
+ c.LocalAddr = &net.UDPAddr{
+ IP: net.ParseIP("::1"),
+ }
+ for {
+ if s.LocalAddr() != nil {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ log.Printf("Waiting for server to run...")
+ }
+ c.RemoteAddr = &net.UDPAddr{
+ IP: net.ParseIP("::1"),
+ Port: s.LocalAddr().(*net.UDPAddr).Port,
+ }
+
+ return c, s
+}
+
+func TestNewServer(t *testing.T) {
+ laddr := net.UDPAddr{
+ IP: net.ParseIP("::1"),
+ Port: 0,
+ }
+ handler := func(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6) {}
+ s := NewServer(laddr, handler)
+ defer s.Close()
+
+ require.NotNil(t, s)
+ require.Nil(t, s.conn)
+ require.Equal(t, laddr, s.localAddr)
+ require.NotNil(t, s.Handler)
+}
+
+func TestServerActivateAndServe(t *testing.T) {
+ handler := func(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6) {
+ adv, err := dhcpv6.NewAdvertiseFromSolicit(m)
+ if err != nil {
+ log.Printf("NewAdvertiseFromSolicit failed: %v", err)
+ return
+ }
+ if _, err := conn.WriteTo(adv.ToBytes(), peer); err != nil {
+ log.Printf("Cannot reply to client: %v", err)
+ }
+ }
+ c, s := setUpClientAndServer(handler)
+ defer s.Close()
+
+ ifaces, err := interfaces.GetLoopbackInterfaces()
+ require.NoError(t, err)
+ require.NotEqual(t, 0, len(ifaces))
+
+ _, _, err = c.Solicit(ifaces[0].Name)
+ require.NoError(t, err)
+}