plugin.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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" [autorefresh]
  21. // ...
  22. //
  23. // If the file path is not absolute, it is relative to the cwd where coredhcp is run.
  24. //
  25. // Optionally, when the 'autorefresh' argument is given, the plugin will try to refresh
  26. // the lease mapping during runtime whenever the lease file is updated.
  27. package file
  28. import (
  29. "bytes"
  30. "errors"
  31. "fmt"
  32. "net"
  33. "os"
  34. "strings"
  35. "sync"
  36. "time"
  37. "github.com/coredhcp/coredhcp/handler"
  38. "github.com/coredhcp/coredhcp/logger"
  39. "github.com/coredhcp/coredhcp/plugins"
  40. "github.com/fsnotify/fsnotify"
  41. "github.com/insomniacslk/dhcp/dhcpv4"
  42. "github.com/insomniacslk/dhcp/dhcpv6"
  43. )
  44. const (
  45. autoRefreshArg = "autorefresh"
  46. )
  47. var log = logger.GetLogger("plugins/file")
  48. // Plugin wraps plugin registration information
  49. var Plugin = plugins.Plugin{
  50. Name: "file",
  51. Setup6: setup6,
  52. Setup4: setup4,
  53. }
  54. var recLock sync.RWMutex
  55. // StaticRecords holds a MAC -> IP address mapping
  56. var StaticRecords map[string]net.IP
  57. // DHCPv6Records and DHCPv4Records are mappings between MAC addresses in
  58. // form of a string, to network configurations.
  59. var (
  60. DHCPv6Records map[string]net.IP
  61. DHCPv4Records map[string]net.IP
  62. )
  63. // LoadDHCPv4Records loads the DHCPv4Records global map with records stored on
  64. // the specified file. The records have to be one per line, a mac address and an
  65. // IPv4 address.
  66. func LoadDHCPv4Records(filename string) (map[string]net.IP, error) {
  67. log.Infof("reading leases from %s", filename)
  68. data, err := os.ReadFile(filename)
  69. if err != nil {
  70. return nil, err
  71. }
  72. records := make(map[string]net.IP)
  73. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  74. line := string(lineBytes)
  75. if len(line) == 0 {
  76. continue
  77. }
  78. if strings.HasPrefix(line, "#") {
  79. continue
  80. }
  81. tokens := strings.Fields(line)
  82. if len(tokens) != 2 {
  83. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  84. }
  85. hwaddr, err := net.ParseMAC(tokens[0])
  86. if err != nil {
  87. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  88. }
  89. ipaddr := net.ParseIP(tokens[1])
  90. if ipaddr.To4() == nil {
  91. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  92. }
  93. records[hwaddr.String()] = ipaddr
  94. }
  95. return records, nil
  96. }
  97. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  98. // the specified file. The records have to be one per line, a mac address and an
  99. // IPv6 address.
  100. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  101. log.Infof("reading leases from %s", filename)
  102. data, err := os.ReadFile(filename)
  103. if err != nil {
  104. return nil, err
  105. }
  106. records := make(map[string]net.IP)
  107. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  108. line := string(lineBytes)
  109. if len(line) == 0 {
  110. continue
  111. }
  112. if strings.HasPrefix(line, "#") {
  113. continue
  114. }
  115. tokens := strings.Fields(line)
  116. if len(tokens) != 2 {
  117. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  118. }
  119. hwaddr, err := net.ParseMAC(tokens[0])
  120. if err != nil {
  121. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  122. }
  123. ipaddr := net.ParseIP(tokens[1])
  124. if ipaddr.To16() == nil || ipaddr.To4() != nil {
  125. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  126. }
  127. records[hwaddr.String()] = ipaddr
  128. }
  129. return records, nil
  130. }
  131. // Handler6 handles DHCPv6 packets for the file plugin
  132. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  133. m, err := req.GetInnerMessage()
  134. if err != nil {
  135. log.Errorf("BUG: could not decapsulate: %v", err)
  136. return nil, true
  137. }
  138. if m.Options.OneIANA() == nil {
  139. log.Debug("No address requested")
  140. return resp, false
  141. }
  142. mac, err := dhcpv6.ExtractMAC(req)
  143. if err != nil {
  144. log.Warningf("Could not find client MAC, passing")
  145. return resp, false
  146. }
  147. log.Debugf("looking up an IP address for MAC %s", mac.String())
  148. recLock.RLock()
  149. defer recLock.RUnlock()
  150. ipaddr, ok := StaticRecords[mac.String()]
  151. if !ok {
  152. log.Warningf("MAC address %s is unknown", mac.String())
  153. return resp, false
  154. }
  155. log.Debugf("found IP address %s for MAC %s", ipaddr, mac.String())
  156. resp.AddOption(&dhcpv6.OptIANA{
  157. IaId: m.Options.OneIANA().IaId,
  158. Options: dhcpv6.IdentityOptions{Options: []dhcpv6.Option{
  159. &dhcpv6.OptIAAddress{
  160. IPv6Addr: ipaddr,
  161. PreferredLifetime: 3600 * time.Second,
  162. ValidLifetime: 3600 * time.Second,
  163. },
  164. }},
  165. })
  166. return resp, false
  167. }
  168. // Handler4 handles DHCPv4 packets for the file plugin
  169. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  170. recLock.RLock()
  171. defer recLock.RUnlock()
  172. ipaddr, ok := StaticRecords[req.ClientHWAddr.String()]
  173. if !ok {
  174. log.Warningf("MAC address %s is unknown", req.ClientHWAddr.String())
  175. return resp, false
  176. }
  177. resp.YourIPAddr = ipaddr
  178. log.Debugf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  179. return resp, true
  180. }
  181. func setup6(args ...string) (handler.Handler6, error) {
  182. h6, _, err := setupFile(true, args...)
  183. return h6, err
  184. }
  185. func setup4(args ...string) (handler.Handler4, error) {
  186. _, h4, err := setupFile(false, args...)
  187. return h4, err
  188. }
  189. func setupFile(v6 bool, args ...string) (handler.Handler6, handler.Handler4, error) {
  190. var err error
  191. if len(args) < 1 {
  192. return nil, nil, errors.New("need a file name")
  193. }
  194. filename := args[0]
  195. if filename == "" {
  196. return nil, nil, errors.New("got empty file name")
  197. }
  198. // load initial database from lease file
  199. if err = loadFromFile(v6, filename); err != nil {
  200. return nil, nil, err
  201. }
  202. // when the 'autorefresh' argument was passed, watch the lease file for
  203. // changes and reload the lease mapping on any event
  204. if len(args) > 1 && args[1] == autoRefreshArg {
  205. // creates a new file watcher
  206. watcher, err := fsnotify.NewWatcher()
  207. if err != nil {
  208. return nil, nil, fmt.Errorf("failed to create watcher: %w", err)
  209. }
  210. // have file watcher watch over lease file
  211. if err = watcher.Add(filename); err != nil {
  212. return nil, nil, fmt.Errorf("failed to watch %s: %w", filename, err)
  213. }
  214. // very simple watcher on the lease file to trigger a refresh on any event
  215. // on the file
  216. go func() {
  217. for range watcher.Events {
  218. err := loadFromFile(v6, filename)
  219. if err != nil {
  220. log.Warningf("failed to refresh from %s: %s", filename, err)
  221. continue
  222. }
  223. log.Infof("updated to %d leases from %s", len(StaticRecords), filename)
  224. }
  225. }()
  226. }
  227. log.Infof("loaded %d leases from %s", len(StaticRecords), filename)
  228. return Handler6, Handler4, nil
  229. }
  230. func loadFromFile(v6 bool, filename string) error {
  231. var err error
  232. var records map[string]net.IP
  233. var protver int
  234. if v6 {
  235. protver = 6
  236. records, err = LoadDHCPv6Records(filename)
  237. } else {
  238. protver = 4
  239. records, err = LoadDHCPv4Records(filename)
  240. }
  241. if err != nil {
  242. return fmt.Errorf("failed to load DHCPv%d records: %w", protver, err)
  243. }
  244. recLock.Lock()
  245. defer recLock.Unlock()
  246. StaticRecords = records
  247. return nil
  248. }