coredhcp.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package coredhcp
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "github.com/coredhcp/coredhcp/config"
  7. "github.com/coredhcp/coredhcp/handler"
  8. "github.com/coredhcp/coredhcp/logger"
  9. "github.com/coredhcp/coredhcp/plugins"
  10. "github.com/insomniacslk/dhcp/dhcpv4"
  11. "github.com/insomniacslk/dhcp/dhcpv4/server4"
  12. "github.com/insomniacslk/dhcp/dhcpv6"
  13. "github.com/insomniacslk/dhcp/dhcpv6/server6"
  14. )
  15. var log = logger.GetLogger()
  16. // Server is a CoreDHCP server structure that holds information about
  17. // DHCPv6 and DHCPv4 servers, and their respective handlers.
  18. type Server struct {
  19. Handlers6 []handler.Handler6
  20. Handlers4 []handler.Handler4
  21. Config *config.Config
  22. Server6 *server6.Server
  23. Server4 *server4.Server
  24. errors chan error
  25. }
  26. // LoadPlugins reads a Config object and loads the plugins as specified in the
  27. // `plugins` section, in order. For a plugin to be available, it must have been
  28. // previously registered with plugins.RegisterPlugin. This is normally done at
  29. // plugin import time.
  30. // This function returns the list of loaded v6 plugins, the list of loaded v4
  31. // plugins, and an error if any.
  32. func (s *Server) LoadPlugins(conf *config.Config) ([]*plugins.Plugin, []*plugins.Plugin, error) {
  33. log.Print("Loading plugins...")
  34. loadedPlugins6 := make([]*plugins.Plugin, 0)
  35. loadedPlugins4 := make([]*plugins.Plugin, 0)
  36. if conf.Server6 == nil && conf.Server4 == nil {
  37. return nil, nil, errors.New("no configuration found for either DHCPv6 or DHCPv4")
  38. }
  39. // now load the plugins. We need to call its setup function with
  40. // the arguments extracted above. The setup function is mapped in
  41. // plugins.RegisteredPlugins .
  42. // Load DHCPv6 plugins.
  43. if conf.Server6 != nil {
  44. for _, pluginConf := range conf.Server6.Plugins {
  45. if plugin, ok := plugins.RegisteredPlugins[pluginConf.Name]; ok {
  46. log.Printf("DHCPv6: loading plugin `%s`", pluginConf.Name)
  47. if plugin.Setup6 == nil {
  48. log.Warningf("DHCPv6: plugin `%s` has no setup function for DHCPv6", pluginConf.Name)
  49. continue
  50. }
  51. h6, err := plugin.Setup6(pluginConf.Args...)
  52. if err != nil {
  53. return nil, nil, err
  54. }
  55. loadedPlugins6 = append(loadedPlugins6, plugin)
  56. if h6 == nil {
  57. return nil, nil, config.ConfigErrorFromString("no DHCPv6 handler for plugin %s", pluginConf.Name)
  58. }
  59. s.Handlers6 = append(s.Handlers6, h6)
  60. } else {
  61. return nil, nil, config.ConfigErrorFromString("DHCPv6: unknown plugin `%s`", pluginConf.Name)
  62. }
  63. }
  64. }
  65. // Load DHCPv4 plugins. Yes, duplicated code, there's not really much that
  66. // can be deduplicated here.
  67. if conf.Server4 != nil {
  68. for _, pluginConf := range conf.Server4.Plugins {
  69. if plugin, ok := plugins.RegisteredPlugins[pluginConf.Name]; ok {
  70. log.Printf("DHCPv4: loading plugin `%s`", pluginConf.Name)
  71. if plugin.Setup4 == nil {
  72. log.Warningf("DHCPv4: plugin `%s` has no setup function for DHCPv4", pluginConf.Name)
  73. continue
  74. }
  75. h4, err := plugin.Setup4(pluginConf.Args...)
  76. if err != nil {
  77. return nil, nil, err
  78. }
  79. loadedPlugins4 = append(loadedPlugins4, plugin)
  80. if h4 == nil {
  81. return nil, nil, config.ConfigErrorFromString("no DHCPv4 handler for plugin %s", pluginConf.Name)
  82. }
  83. s.Handlers4 = append(s.Handlers4, h4)
  84. //s.Handlers4 = append(s.Handlers4, h4)
  85. } else {
  86. return nil, nil, config.ConfigErrorFromString("DHCPv4: unknown plugin `%s`", pluginConf.Name)
  87. }
  88. }
  89. }
  90. return loadedPlugins6, loadedPlugins4, nil
  91. }
  92. // MainHandler6 runs for every received DHCPv6 packet. It will run every
  93. // registered handler in sequence, and reply with the resulting response.
  94. // It will not reply if the resulting response is `nil`.
  95. func (s *Server) MainHandler6(conn net.PacketConn, peer net.Addr, req dhcpv6.DHCPv6) {
  96. var (
  97. resp, tmp dhcpv6.DHCPv6
  98. stop bool
  99. err error
  100. )
  101. // Create a suitable basic response packet
  102. switch req.Type() {
  103. case dhcpv6.MessageTypeSolicit:
  104. tmp, err = dhcpv6.NewAdvertiseFromSolicit(req.(*dhcpv6.Message))
  105. case dhcpv6.MessageTypeRequest, dhcpv6.MessageTypeConfirm, dhcpv6.MessageTypeRenew,
  106. dhcpv6.MessageTypeRebind, dhcpv6.MessageTypeRelease, dhcpv6.MessageTypeInformationRequest:
  107. tmp, err = dhcpv6.NewReplyFromMessage(req.(*dhcpv6.Message))
  108. default:
  109. err = fmt.Errorf("MainHandler6: message type %d not supported", req.Type())
  110. }
  111. if err != nil {
  112. log.Printf("MainHandler6: NewReplyFromDHCPv6Message failed: %v", err)
  113. return
  114. }
  115. resp = tmp
  116. for _, handler := range s.Handlers6 {
  117. resp, stop = handler(req, resp)
  118. if stop {
  119. break
  120. }
  121. }
  122. if resp != nil {
  123. if _, err := conn.WriteTo(resp.ToBytes(), peer); err != nil {
  124. log.Printf("MainHandler6: conn.Write to %v failed: %v", peer, err)
  125. }
  126. } else {
  127. log.Print("MainHandler6: dropping request because response is nil")
  128. }
  129. }
  130. // MainHandler4 is like MainHandler6, but for DHCPv4 packets.
  131. func (s *Server) MainHandler4(conn net.PacketConn, peer net.Addr, req *dhcpv4.DHCPv4) {
  132. var (
  133. resp, tmp *dhcpv4.DHCPv4
  134. err error
  135. stop bool
  136. )
  137. if req.OpCode != dhcpv4.OpcodeBootRequest {
  138. log.Printf("MainHandler4: unsupported opcode %d. Only BootRequest (%d) is supported", req.OpCode, dhcpv4.OpcodeBootRequest)
  139. return
  140. }
  141. tmp, err = dhcpv4.NewReplyFromRequest(req)
  142. if err != nil {
  143. log.Printf("MainHandler4: failed to build reply: %v", err)
  144. return
  145. }
  146. resp = tmp
  147. for _, handler := range s.Handlers4 {
  148. resp, stop = handler(req, resp)
  149. if stop {
  150. break
  151. }
  152. }
  153. if resp != nil {
  154. if _, err := conn.WriteTo(resp.ToBytes(), peer); err != nil {
  155. log.Printf("MainHandler4: conn.Write to %v failed: %v", peer, err)
  156. }
  157. } else {
  158. log.Print("MainHandler4: dropping request because response is nil")
  159. }
  160. }
  161. // Start will start the server asynchronously. See `Wait` to wait until
  162. // the execution ends.
  163. func (s *Server) Start() error {
  164. _, _, err := s.LoadPlugins(s.Config)
  165. if err != nil {
  166. return err
  167. }
  168. // listen
  169. if s.Config.Server6 != nil {
  170. log.Printf("Starting DHCPv6 listener on %v", s.Config.Server6.Listener)
  171. go func() {
  172. s.Server6 = server6.NewServer(*s.Config.Server6.Listener, s.MainHandler6)
  173. s.errors <- s.Server6.ActivateAndServe()
  174. }()
  175. }
  176. if s.Config.Server4 != nil {
  177. log.Printf("Starting DHCPv4 listener on %v", s.Config.Server4.Listener)
  178. go func() {
  179. s.Server4 = server4.NewServer(*s.Config.Server4.Listener, s.MainHandler4)
  180. s.errors <- s.Server4.ActivateAndServe()
  181. }()
  182. }
  183. return nil
  184. }
  185. // Wait waits until the end of the execution of the server.
  186. func (s *Server) Wait() error {
  187. log.Print("Waiting")
  188. if s.Server6 != nil {
  189. s.Server6.Close()
  190. }
  191. if s.Server4 != nil {
  192. s.Server4.Close()
  193. }
  194. return <-s.errors
  195. }
  196. // NewServer creates a Server instance with the provided configuration.
  197. func NewServer(config *config.Config) *Server {
  198. return &Server{Config: config, errors: make(chan error, 1)}
  199. }