plugin.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package file
  2. /*
  3. The `file` plugin enables static mapping of MAC <--> IP addresses.
  4. The mapping is stored in a text file, where each mapping is described by one line containing
  5. two fields separated by spaces: MAC address, and IP address. For example:
  6. $ cat file_leases.txt
  7. 00:11:22:33:44:55 10.0.0.1
  8. 01:23:45:67:89:01 10.0.10.10
  9. To specify the plugin configuration in the server6/server4 sections of the config file, just
  10. pass the leases file name as plugin argument, e.g.:
  11. $ cat config.yml
  12. server6:
  13. ...
  14. plugins:
  15. - file: "file_leases.txt"
  16. ...
  17. If the file path is not absolute, it is relative to the cwd where coredhcp is run.
  18. */
  19. import (
  20. "bytes"
  21. "errors"
  22. "fmt"
  23. "io/ioutil"
  24. "net"
  25. "strings"
  26. "github.com/coredhcp/coredhcp/handler"
  27. "github.com/coredhcp/coredhcp/logger"
  28. "github.com/coredhcp/coredhcp/plugins"
  29. "github.com/insomniacslk/dhcp/dhcpv4"
  30. "github.com/insomniacslk/dhcp/dhcpv6"
  31. )
  32. var log = logger.GetLogger("plugins/file")
  33. func init() {
  34. plugins.RegisterPlugin("file", setupFile6, setupFile4)
  35. }
  36. // StaticRecords holds a MAC -> IP address mapping
  37. var StaticRecords map[string]net.IP
  38. // DHCPv6Records and DHCPv4Records are mappings between MAC addresses in
  39. // form of a string, to network configurations.
  40. var (
  41. DHCPv6Records map[string]net.IP
  42. DHCPv4Records map[string]net.IP
  43. )
  44. // LoadDHCPv4Records loads the DHCPv4Records global map with records stored on
  45. // the specified file. The records have to be one per line, a mac address and an
  46. // IPv4 address.
  47. func LoadDHCPv4Records(filename string) (map[string]net.IP, error) {
  48. log.Printf("reading leases from %s", filename)
  49. data, err := ioutil.ReadFile(filename)
  50. if err != nil {
  51. return nil, err
  52. }
  53. records := make(map[string]net.IP)
  54. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  55. line := string(lineBytes)
  56. if len(line) == 0 {
  57. continue
  58. }
  59. tokens := strings.Fields(line)
  60. if len(tokens) != 2 {
  61. return nil, fmt.Errorf("malformed line, want 2 fields, got %d: %s", len(tokens), line)
  62. }
  63. hwaddr, err := net.ParseMAC(tokens[0])
  64. if err != nil {
  65. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  66. }
  67. ipaddr := net.ParseIP(tokens[1])
  68. if ipaddr.To4() == nil {
  69. return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
  70. }
  71. records[hwaddr.String()] = ipaddr
  72. }
  73. return records, nil
  74. }
  75. // LoadDHCPv6Records loads the DHCPv6Records global map with records stored on
  76. // the specified file. The records have to be one per line, a mac address and an
  77. // IPv6 address.
  78. func LoadDHCPv6Records(filename string) (map[string]net.IP, error) {
  79. log.Printf("reading leases from %s", filename)
  80. data, err := ioutil.ReadFile(filename)
  81. if err != nil {
  82. return nil, err
  83. }
  84. records := make(map[string]net.IP)
  85. // TODO ignore comments
  86. for _, lineBytes := range bytes.Split(data, []byte{'\n'}) {
  87. line := string(lineBytes)
  88. if len(line) == 0 {
  89. continue
  90. }
  91. tokens := strings.Fields(line)
  92. if len(tokens) != 2 {
  93. return nil, fmt.Errorf("malformed line: %s", line)
  94. }
  95. hwaddr, err := net.ParseMAC(tokens[0])
  96. if err != nil {
  97. return nil, fmt.Errorf("malformed hardware address: %s", tokens[0])
  98. }
  99. ipaddr := net.ParseIP(tokens[1])
  100. if ipaddr.To16() == nil {
  101. return nil, fmt.Errorf("expected an IPv6 address, got: %v", ipaddr)
  102. }
  103. records[hwaddr.String()] = ipaddr
  104. }
  105. return records, nil
  106. }
  107. // Handler6 handles DHCPv6 packets for the file plugin
  108. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  109. mac, err := dhcpv6.ExtractMAC(req)
  110. if err != nil {
  111. return nil, false
  112. }
  113. log.Printf("looking up an IP address for MAC %s", mac.String())
  114. ipaddr, ok := StaticRecords[mac.String()]
  115. if !ok {
  116. log.Warningf("MAC address %s is unknown", mac.String())
  117. return nil, false
  118. }
  119. log.Printf("found IP address %s for MAC %s", ipaddr, mac.String())
  120. resp.AddOption(&dhcpv6.OptIANA{
  121. // FIXME copy this field from the client, reject/drop if missing
  122. IaId: [4]byte{0xaa, 0xbb, 0xcc, 0xdd},
  123. Options: []dhcpv6.Option{
  124. &dhcpv6.OptIAAddress{
  125. IPv6Addr: ipaddr,
  126. PreferredLifetime: 3600,
  127. ValidLifetime: 3600,
  128. },
  129. },
  130. })
  131. resp.AddOption(&dhcpv6.OptDNSRecursiveNameServer{
  132. NameServers: []net.IP{
  133. // FIXME this must be read from the config file
  134. net.ParseIP("2001:4860:4860::8888"),
  135. net.ParseIP("2001:4860:4860::4444"),
  136. },
  137. })
  138. if oro := req.GetOption(dhcpv6.OptionORO); len(oro) > 0 {
  139. for _, code := range oro[0].(*dhcpv6.OptRequestedOption).RequestedOptions() {
  140. if code == dhcpv6.OptionBootfileURL {
  141. // bootfile URL is requested
  142. // FIXME this field should come from the configuration, not
  143. // being hardcoded
  144. resp.AddOption(
  145. &dhcpv6.OptBootFileURL{BootFileURL: []byte("http://[2001:db8::0:1]/nbp")},
  146. )
  147. }
  148. }
  149. }
  150. return resp, true
  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.Printf("found IP address %s for MAC %s", ipaddr, req.ClientHWAddr.String())
  161. return resp, true
  162. }
  163. func setupFile6(args ...string) (handler.Handler6, error) {
  164. h6, _, err := setupFile(true, args...)
  165. return h6, err
  166. }
  167. func setupFile4(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.Printf("loaded %d leases from %s", len(records), filename)
  191. return Handler6, Handler4, nil
  192. }