plugin.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. // Package file enables static mapping of MAC <--> IP addresses.
  5. // The mapping is stored in a text file, where each mapping is described by one line containing
  6. // two fields separated by spaces: MAC address, and IP address. For example:
  7. //
  8. // $ cat file_leases.txt
  9. // 00:11:22:33:44:55 10.0.0.1
  10. // 01:23:45:67:89:01 10.0.10.10
  11. //
  12. // To specify the plugin configuration in the server6/server4 sections of the config file, just
  13. // pass the leases file name as plugin argument, e.g.:
  14. //
  15. // $ cat config.yml
  16. //
  17. // server6:
  18. // ...
  19. // plugins:
  20. // - file: "file_leases.txt"
  21. // ...
  22. //
  23. // If the file path is not absolute, it is relative to the cwd where coredhcp is run.
  24. package file
  25. import (
  26. "bytes"
  27. "errors"
  28. "fmt"
  29. "io/ioutil"
  30. "net"
  31. "strings"
  32. "time"
  33. "github.com/coredhcp/coredhcp/handler"
  34. "github.com/coredhcp/coredhcp/logger"
  35. "github.com/coredhcp/coredhcp/plugins"
  36. "github.com/insomniacslk/dhcp/dhcpv4"
  37. "github.com/insomniacslk/dhcp/dhcpv6"
  38. )
  39. var log = logger.GetLogger("plugins/file")
  40. // Plugin wraps plugin registration information
  41. var Plugin = plugins.Plugin{
  42. Name: "file",
  43. Setup6: setup6,
  44. Setup4: setup4,
  45. }
  46. // StaticRecords holds a MAC -> IP address mapping
  47. var StaticRecords map[string]net.IP
  48. // DHCPv6Records and DHCPv4Records are mappings between MAC addresses in
  49. // form of a string, to network configurations.
  50. var (
  51. DHCPv6Records map[string]net.IP
  52. DHCPv4Records map[string]net.IP
  53. )
  54. // LoadDHCPv4Records loads the DHCPv4Records global map with records stored on
  55. // the specified file. The records have to be one per line, a mac address and an
  56. // IPv4 address.
  57. func LoadDHCPv4Records(filename string) (map[string]net.IP, error) {
  58. log.Infof("reading leases from %s", filename)
  59. data, err := ioutil.ReadFile(filename)
  60. if err != nil {
  61. return nil, err
  62. }
  63. records := make(map[string]net.IP)
  64. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  65. line := string(lineBytes)
  66. if len(line) == 0 {
  67. continue
  68. }
  69. tokens := strings.Fields(line)
  70. if len(tokens) != 2 {
  71. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  72. }
  73. hwaddr, err := net.ParseMAC(tokens[0])
  74. if err != nil {
  75. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  76. }
  77. ipaddr := net.ParseIP(tokens[1])
  78. if ipaddr.To4() == nil {
  79. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  80. }
  81. records[hwaddr.String()] = ipaddr
  82. }
  83. return records, nil
  84. }
  85. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  86. // the specified file. The records have to be one per line, a mac address and an
  87. // IPv6 address.
  88. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  89. log.Infof("reading leases from %s", filename)
  90. data, err := ioutil.ReadFile(filename)
  91. if err != nil {
  92. return nil, err
  93. }
  94. records := make(map[string]net.IP)
  95. // TODO ignore comments
  96. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  97. line := string(lineBytes)
  98. if len(line) == 0 {
  99. continue
  100. }
  101. tokens := strings.Fields(line)
  102. if len(tokens) != 2 {
  103. return nil, fmt.Errorf("malformed line: %s", line)
  104. }
  105. hwaddr, err := net.ParseMAC(tokens[0])
  106. if err != nil {
  107. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  108. }
  109. ipaddr := net.ParseIP(tokens[1])
  110. if ipaddr.To16() == nil {
  111. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  112. }
  113. records[hwaddr.String()] = ipaddr
  114. }
  115. return records, nil
  116. }
  117. // Handler6 handles DHCPv6 packets for the file plugin
  118. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  119. m, err := req.GetInnerMessage()
  120. if err != nil {
  121. log.Errorf("BUG: could not decapsulate: %v", err)
  122. return nil, true
  123. }
  124. if m.Options.OneIANA() == nil {
  125. log.Debug("No address requested")
  126. return resp, false
  127. }
  128. mac, err := dhcpv6.ExtractMAC(req)
  129. if err != nil {
  130. log.Warningf("Could not find client MAC, passing")
  131. return resp, false
  132. }
  133. log.Debugf("looking up an IP address for MAC %s", mac.String())
  134. ipaddr, ok := StaticRecords[mac.String()]
  135. if !ok {
  136. log.Warningf("MAC address %s is unknown", mac.String())
  137. return resp, false
  138. }
  139. log.Debugf("found IP address %s for MAC %s", ipaddr, mac.String())
  140. resp.AddOption(&dhcpv6.OptIANA{
  141. IaId: m.Options.OneIANA().IaId,
  142. Options: dhcpv6.IdentityOptions{Options: []dhcpv6.Option{
  143. &dhcpv6.OptIAAddress{
  144. IPv6Addr: ipaddr,
  145. PreferredLifetime: 3600 * time.Second,
  146. ValidLifetime: 3600 * time.Second,
  147. },
  148. }},
  149. })
  150. return resp, false
  151. }
  152. // Handler4 handles DHCPv4 packets for the file plugin
  153. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  154. ipaddr, ok := StaticRecords[req.ClientHWAddr.String()]
  155. if !ok {
  156. log.Warningf("MAC address %s is unknown", req.ClientHWAddr.String())
  157. return resp, false
  158. }
  159. resp.YourIPAddr = ipaddr
  160. log.Debugf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  161. return resp, true
  162. }
  163. func setup6(args ...string) (handler.Handler6, error) {
  164. h6, _, err := setupFile(true, args...)
  165. return h6, err
  166. }
  167. func setup4(args ...string) (handler.Handler4, error) {
  168. _, h4, err := setupFile(false, args...)
  169. return h4, err
  170. }
  171. func setupFile(v6 bool, args ...string) (handler.Handler6, handler.Handler4, error) {
  172. var err error
  173. var records map[string]net.IP
  174. if len(args) < 1 {
  175. return nil, nil, errors.New("need a file name")
  176. }
  177. filename := args[0]
  178. if filename == "" {
  179. return nil, nil, errors.New("got empty file name")
  180. }
  181. if v6 {
  182. records, err = LoadDHCPv6Records(filename)
  183. } else {
  184. records, err = LoadDHCPv4Records(filename)
  185. }
  186. if err != nil {
  187. return nil, nil, fmt.Errorf("failed to load DHCPv6 records: %v", err)
  188. }
  189. StaticRecords = records
  190. log.Infof("loaded %d leases from %s", len(records), filename)
  191. return Handler6, Handler4, nil
  192. }