backend.go 2.1 KB

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