2023-04-22 08:25:13 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2023-05-01 14:37:52 +00:00
|
|
|
"fmt"
|
2023-04-22 08:25:13 +00:00
|
|
|
"net"
|
2023-04-30 06:46:44 +00:00
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
"git.wntrmute.dev/kyle/kdhcp/log"
|
2023-05-01 18:50:45 +00:00
|
|
|
"github.com/insomniacslk/dhcp/dhcpv4"
|
2023-04-22 08:25:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2023-05-01 14:37:52 +00:00
|
|
|
cfg *Config
|
|
|
|
conn net.PacketConn
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
func (srv *Server) Listen() (err error) {
|
|
|
|
if srv.conn != nil {
|
|
|
|
srv.conn.Close()
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
log.Debugf("attempting to set up packet listener on %s 0.0.0.0:%d", DefaultNetwork, srv.cfg.Port)
|
|
|
|
srv.conn, err = net.ListenPacket(DefaultNetwork, fmt.Sprintf(":%d", srv.cfg.Port))
|
2023-04-22 08:25:13 +00:00
|
|
|
if err != nil {
|
2023-05-01 14:37:52 +00:00
|
|
|
return err
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
return nil
|
|
|
|
}
|
2023-04-22 08:25:13 +00:00
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
func (srv *Server) Close() error {
|
|
|
|
if srv.conn != nil {
|
|
|
|
return srv.conn.Close()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2023-04-22 08:25:13 +00:00
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
func (srv *Server) ReadFrom() (*Packet, error) {
|
|
|
|
b := make([]byte, srv.cfg.MaxPacketSize)
|
|
|
|
n, addr, err := srv.conn.ReadFrom(b)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|
|
|
|
|
2023-05-01 18:50:45 +00:00
|
|
|
packet := &Packet{
|
2023-05-01 14:37:52 +00:00
|
|
|
Data: b[:n],
|
|
|
|
Addr: addr,
|
2023-05-01 18:50:45 +00:00
|
|
|
}
|
|
|
|
packet.Raw, err = dhcpv4.FromBytes(b[:n])
|
|
|
|
if err != nil {
|
|
|
|
return packet, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return packet, nil
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServer(cfg *Config) (*Server, error) {
|
2023-05-01 14:37:52 +00:00
|
|
|
srv := &Server{
|
|
|
|
cfg: cfg,
|
|
|
|
}
|
|
|
|
|
|
|
|
err := srv.Listen()
|
2023-04-22 08:25:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-05-01 14:37:52 +00:00
|
|
|
return srv, nil
|
2023-04-22 08:25:13 +00:00
|
|
|
}
|