backend.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package backend
  2. import (
  3. "context"
  4. "dhcp/data"
  5. "dhcp/handler"
  6. "errors"
  7. "net"
  8. "net/netip"
  9. )
  10. var errParseSubnet = errors.New("failed to parse subnet mask")
  11. type Backend struct{}
  12. func NewBackend() handler.BackendReader {
  13. return &Backend{}
  14. }
  15. func (b *Backend) GetByMac(ctx context.Context, addr net.HardwareAddr, s string) (*data.DHCP, error) {
  16. dp, err := GetDhcp(addr.String())
  17. if err != nil {
  18. return nil, err
  19. }
  20. dhcp, err := translate(dp)
  21. if err != nil {
  22. return nil, err
  23. }
  24. return dhcp, nil
  25. }
  26. func (b *Backend) GetByIP(ctx context.Context, ip net.IP, s string) (*data.DHCP, error) {
  27. return nil, nil
  28. }
  29. func translate(dp Dhcp) (*data.DHCP, error) {
  30. var d data.DHCP
  31. if dp.MACAddress != "" {
  32. d.MACAddress = net.HardwareAddr(dp.MACAddress)
  33. }
  34. if dp.IPAddress != "" {
  35. ip, err := netip.ParseAddr(dp.IPAddress)
  36. if err != nil {
  37. return nil, err
  38. }
  39. d.IPAddress = ip
  40. }
  41. if len(dp.DomainSearch) > 0 {
  42. d.DomainSearch = dp.DomainSearch
  43. }
  44. if dp.SubnetMask != "" {
  45. sm := net.ParseIP(dp.SubnetMask)
  46. if sm == nil {
  47. return nil, errParseSubnet
  48. }
  49. d.SubnetMask = net.IPMask(sm.To4())
  50. }
  51. if dp.DefaultGateway != "" {
  52. dg, err := netip.ParseAddr(dp.DefaultGateway)
  53. if err != nil {
  54. return nil, err
  55. }
  56. d.DefaultGateway = dg
  57. }
  58. if len(dp.NameServers) > 0 {
  59. for _, s := range dp.NameServers {
  60. ip := net.ParseIP(string(s))
  61. if ip == nil {
  62. break
  63. }
  64. d.NameServers = append(d.NameServers, ip)
  65. }
  66. }
  67. if dp.DomainName != "" {
  68. d.DomainName = dp.DomainName
  69. }
  70. if dp.BroadcastAddress != "" {
  71. ba, err := netip.ParseAddr(dp.BroadcastAddress)
  72. if err != nil {
  73. return nil, err
  74. }
  75. d.BroadcastAddress = ba
  76. }
  77. if len(dp.NTPServers) > 0 {
  78. for _, s := range dp.NTPServers {
  79. ip := net.ParseIP(string(s))
  80. if ip == nil {
  81. break
  82. }
  83. d.NTPServers = append(d.NTPServers, ip)
  84. }
  85. }
  86. if dp.VLANID != "" {
  87. d.VLANID = dp.VLANID
  88. }
  89. d.LeaseTime = uint32(dp.LeaseTime)
  90. if dp.DomainSearch != nil {
  91. d.DomainSearch = dp.DomainSearch
  92. }
  93. if dp.ServerIP != "" {
  94. d.ServerIP = net.ParseIP(dp.ServerIP)
  95. }
  96. return &d, nil
  97. }