plugin.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. "io/ioutil"
  33. "net"
  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 := ioutil.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. tokens := strings.Fields(line)
  79. if len(tokens) != 2 {
  80. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  81. }
  82. hwaddr, err := net.ParseMAC(tokens[0])
  83. if err != nil {
  84. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  85. }
  86. ipaddr := net.ParseIP(tokens[1])
  87. if ipaddr.To4() == nil {
  88. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  89. }
  90. records[hwaddr.String()] = ipaddr
  91. }
  92. return records, nil
  93. }
  94. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  95. // the specified file. The records have to be one per line, a mac address and an
  96. // IPv6 address.
  97. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  98. log.Infof("reading leases from %s", filename)
  99. data, err := ioutil.ReadFile(filename)
  100. if err != nil {
  101. return nil, err
  102. }
  103. records := make(map[string]net.IP)
  104. // TODO ignore comments
  105. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  106. line := string(lineBytes)
  107. if len(line) == 0 {
  108. continue
  109. }
  110. tokens := strings.Fields(line)
  111. if len(tokens) != 2 {
  112. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  113. }
  114. hwaddr, err := net.ParseMAC(tokens[0])
  115. if err != nil {
  116. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  117. }
  118. ipaddr := net.ParseIP(tokens[1])
  119. if ipaddr.To16() == nil || ipaddr.To4() != nil {
  120. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  121. }
  122. records[hwaddr.String()] = ipaddr
  123. }
  124. return records, nil
  125. }
  126. // Handler6 handles DHCPv6 packets for the file plugin
  127. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  128. m, err := req.GetInnerMessage()
  129. if err != nil {
  130. log.Errorf("BUG: could not decapsulate: %v", err)
  131. return nil, true
  132. }
  133. if m.Options.OneIANA() == nil {
  134. log.Debug("No address requested")
  135. return resp, false
  136. }
  137. mac, err := dhcpv6.ExtractMAC(req)
  138. if err != nil {
  139. log.Warningf("Could not find client MAC, passing")
  140. return resp, false
  141. }
  142. log.Debugf("looking up an IP address for MAC %s", mac.String())
  143. recLock.RLock()
  144. defer recLock.RUnlock()
  145. ipaddr, ok := StaticRecords[mac.String()]
  146. if !ok {
  147. log.Warningf("MAC address %s is unknown", mac.String())
  148. return resp, false
  149. }
  150. log.Debugf("found IP address %s for MAC %s", ipaddr, mac.String())
  151. resp.AddOption(&dhcpv6.OptIANA{
  152. IaId: m.Options.OneIANA().IaId,
  153. Options: dhcpv6.IdentityOptions{Options: []dhcpv6.Option{
  154. &dhcpv6.OptIAAddress{
  155. IPv6Addr: ipaddr,
  156. PreferredLifetime: 3600 * time.Second,
  157. ValidLifetime: 3600 * time.Second,
  158. },
  159. }},
  160. })
  161. return resp, false
  162. }
  163. // Handler4 handles DHCPv4 packets for the file plugin
  164. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  165. recLock.RLock()
  166. defer recLock.RUnlock()
  167. ipaddr, ok := StaticRecords[req.ClientHWAddr.String()]
  168. if !ok {
  169. log.Warningf("MAC address %s is unknown", req.ClientHWAddr.String())
  170. return resp, false
  171. }
  172. resp.YourIPAddr = ipaddr
  173. log.Debugf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  174. return resp, true
  175. }
  176. func setup6(args ...string) (handler.Handler6, error) {
  177. h6, _, err := setupFile(true, args...)
  178. return h6, err
  179. }
  180. func setup4(args ...string) (handler.Handler4, error) {
  181. _, h4, err := setupFile(false, args...)
  182. return h4, err
  183. }
  184. func setupFile(v6 bool, args ...string) (handler.Handler6, handler.Handler4, error) {
  185. var err error
  186. if len(args) < 1 {
  187. return nil, nil, errors.New("need a file name")
  188. }
  189. filename := args[0]
  190. if filename == "" {
  191. return nil, nil, errors.New("got empty file name")
  192. }
  193. // load initial database from lease file
  194. if err = loadFromFile(v6, filename); err != nil {
  195. return nil, nil, err
  196. }
  197. // when the 'autorefresh' argument was passed, watch the lease file for
  198. // changes and reload the lease mapping on any event
  199. if len(args) > 1 && args[1] == autoRefreshArg {
  200. // creates a new file watcher
  201. watcher, err := fsnotify.NewWatcher()
  202. if err != nil {
  203. return nil, nil, fmt.Errorf("failed to create watcher: %w", err)
  204. }
  205. // have file watcher watch over lease file
  206. if err = watcher.Add(filename); err != nil {
  207. return nil, nil, fmt.Errorf("failed to watch %s: %w", filename, err)
  208. }
  209. // very simple watcher on the lease file to trigger a refresh on any event
  210. // on the file
  211. go func() {
  212. for range watcher.Events {
  213. err := loadFromFile(v6, filename)
  214. if err != nil {
  215. log.Warningf("failed to refresh from %s: %s", filename, err)
  216. continue
  217. }
  218. log.Infof("updated to %d leases from %s", len(StaticRecords), filename)
  219. }
  220. }()
  221. }
  222. log.Infof("loaded %d leases from %s", len(StaticRecords), filename)
  223. return Handler6, Handler4, nil
  224. }
  225. func loadFromFile(v6 bool, filename string) error {
  226. var err error
  227. var records map[string]net.IP
  228. var protver int
  229. if v6 {
  230. protver = 6
  231. records, err = LoadDHCPv6Records(filename)
  232. } else {
  233. protver = 4
  234. records, err = LoadDHCPv4Records(filename)
  235. }
  236. if err != nil {
  237. return fmt.Errorf("failed to load DHCPv%d records: %w", protver, err)
  238. }
  239. recLock.Lock()
  240. defer recLock.Unlock()
  241. StaticRecords = records
  242. return nil
  243. }