"Fossies" - the Fresh Open Source Software Archive

Member "AdGuardHome-0.104.3/internal/dhcpd/dhcphttp.go" (19 Nov 2020, 14350 Bytes) of package /linux/misc/dns/AdGuardHome-0.104.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Go source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 package dhcpd
    2 
    3 import (
    4     "encoding/json"
    5     "fmt"
    6     "io/ioutil"
    7     "net"
    8     "net/http"
    9     "os"
   10     "strings"
   11     "time"
   12 
   13     "github.com/AdguardTeam/AdGuardHome/internal/util"
   14     "github.com/AdguardTeam/golibs/jsonutil"
   15     "github.com/AdguardTeam/golibs/log"
   16 )
   17 
   18 func httpError(r *http.Request, w http.ResponseWriter, code int, format string, args ...interface{}) {
   19     text := fmt.Sprintf(format, args...)
   20     log.Info("DHCP: %s %s: %s", r.Method, r.URL, text)
   21     http.Error(w, text, code)
   22 }
   23 
   24 // []Lease -> JSON
   25 func convertLeases(inputLeases []Lease, includeExpires bool) []map[string]string {
   26     leases := []map[string]string{}
   27     for _, l := range inputLeases {
   28         lease := map[string]string{
   29             "mac":      l.HWAddr.String(),
   30             "ip":       l.IP.String(),
   31             "hostname": l.Hostname,
   32         }
   33 
   34         if includeExpires {
   35             lease["expires"] = l.Expiry.Format(time.RFC3339)
   36         }
   37 
   38         leases = append(leases, lease)
   39     }
   40     return leases
   41 }
   42 
   43 type v4ServerConfJSON struct {
   44     GatewayIP     string `json:"gateway_ip"`
   45     SubnetMask    string `json:"subnet_mask"`
   46     RangeStart    string `json:"range_start"`
   47     RangeEnd      string `json:"range_end"`
   48     LeaseDuration uint32 `json:"lease_duration"`
   49 }
   50 
   51 func v4ServerConfToJSON(c V4ServerConf) v4ServerConfJSON {
   52     return v4ServerConfJSON{
   53         GatewayIP:     c.GatewayIP,
   54         SubnetMask:    c.SubnetMask,
   55         RangeStart:    c.RangeStart,
   56         RangeEnd:      c.RangeEnd,
   57         LeaseDuration: c.LeaseDuration,
   58     }
   59 }
   60 
   61 func v4JSONToServerConf(j v4ServerConfJSON) V4ServerConf {
   62     return V4ServerConf{
   63         GatewayIP:     j.GatewayIP,
   64         SubnetMask:    j.SubnetMask,
   65         RangeStart:    j.RangeStart,
   66         RangeEnd:      j.RangeEnd,
   67         LeaseDuration: j.LeaseDuration,
   68     }
   69 }
   70 
   71 type v6ServerConfJSON struct {
   72     RangeStart    string `json:"range_start"`
   73     LeaseDuration uint32 `json:"lease_duration"`
   74 }
   75 
   76 func v6ServerConfToJSON(c V6ServerConf) v6ServerConfJSON {
   77     return v6ServerConfJSON{
   78         RangeStart:    c.RangeStart,
   79         LeaseDuration: c.LeaseDuration,
   80     }
   81 }
   82 
   83 func v6JSONToServerConf(j v6ServerConfJSON) V6ServerConf {
   84     return V6ServerConf{
   85         RangeStart:    j.RangeStart,
   86         LeaseDuration: j.LeaseDuration,
   87     }
   88 }
   89 
   90 func (s *Server) handleDHCPStatus(w http.ResponseWriter, r *http.Request) {
   91     leases := convertLeases(s.Leases(LeasesDynamic), true)
   92     staticLeases := convertLeases(s.Leases(LeasesStatic), false)
   93 
   94     v4conf := V4ServerConf{}
   95     s.srv4.WriteDiskConfig4(&v4conf)
   96 
   97     v6conf := V6ServerConf{}
   98     s.srv6.WriteDiskConfig6(&v6conf)
   99 
  100     status := map[string]interface{}{
  101         "enabled":        s.conf.Enabled,
  102         "interface_name": s.conf.InterfaceName,
  103         "v4":             v4ServerConfToJSON(v4conf),
  104         "v6":             v6ServerConfToJSON(v6conf),
  105         "leases":         leases,
  106         "static_leases":  staticLeases,
  107     }
  108 
  109     w.Header().Set("Content-Type", "application/json")
  110     err := json.NewEncoder(w).Encode(status)
  111     if err != nil {
  112         httpError(r, w, http.StatusInternalServerError, "Unable to marshal DHCP status json: %s", err)
  113         return
  114     }
  115 }
  116 
  117 type staticLeaseJSON struct {
  118     HWAddr   string `json:"mac"`
  119     IP       string `json:"ip"`
  120     Hostname string `json:"hostname"`
  121 }
  122 
  123 type dhcpServerConfigJSON struct {
  124     Enabled       bool             `json:"enabled"`
  125     InterfaceName string           `json:"interface_name"`
  126     V4            v4ServerConfJSON `json:"v4"`
  127     V6            v6ServerConfJSON `json:"v6"`
  128 }
  129 
  130 func (s *Server) handleDHCPSetConfig(w http.ResponseWriter, r *http.Request) {
  131     newconfig := dhcpServerConfigJSON{}
  132     newconfig.Enabled = s.conf.Enabled
  133     newconfig.InterfaceName = s.conf.InterfaceName
  134 
  135     js, err := jsonutil.DecodeObject(&newconfig, r.Body)
  136     if err != nil {
  137         httpError(r, w, http.StatusBadRequest, "Failed to parse new DHCP config json: %s", err)
  138         return
  139     }
  140 
  141     var s4 DHCPServer
  142     var s6 DHCPServer
  143     v4Enabled := false
  144     v6Enabled := false
  145 
  146     if js.Exists("v4") {
  147         v4conf := v4JSONToServerConf(newconfig.V4)
  148         v4conf.Enabled = newconfig.Enabled
  149         if len(v4conf.RangeStart) == 0 {
  150             v4conf.Enabled = false
  151         }
  152         v4Enabled = v4conf.Enabled
  153         v4conf.InterfaceName = newconfig.InterfaceName
  154 
  155         c4 := V4ServerConf{}
  156         s.srv4.WriteDiskConfig4(&c4)
  157         v4conf.notify = c4.notify
  158         v4conf.ICMPTimeout = c4.ICMPTimeout
  159 
  160         s4, err = v4Create(v4conf)
  161         if err != nil {
  162             httpError(r, w, http.StatusBadRequest, "Invalid DHCPv4 configuration: %s", err)
  163             return
  164         }
  165     }
  166 
  167     if js.Exists("v6") {
  168         v6conf := v6JSONToServerConf(newconfig.V6)
  169         v6conf.Enabled = newconfig.Enabled
  170         if len(v6conf.RangeStart) == 0 {
  171             v6conf.Enabled = false
  172         }
  173         v6Enabled = v6conf.Enabled
  174         v6conf.InterfaceName = newconfig.InterfaceName
  175         v6conf.notify = s.onNotify
  176         s6, err = v6Create(v6conf)
  177         if err != nil {
  178             httpError(r, w, http.StatusBadRequest, "Invalid DHCPv6 configuration: %s", err)
  179             return
  180         }
  181     }
  182 
  183     if newconfig.Enabled && !v4Enabled && !v6Enabled {
  184         httpError(r, w, http.StatusBadRequest, "DHCPv4 or DHCPv6 configuration must be complete")
  185         return
  186     }
  187 
  188     s.Stop()
  189 
  190     if js.Exists("enabled") {
  191         s.conf.Enabled = newconfig.Enabled
  192     }
  193 
  194     if js.Exists("interface_name") {
  195         s.conf.InterfaceName = newconfig.InterfaceName
  196     }
  197 
  198     if s4 != nil {
  199         s.srv4 = s4
  200     }
  201     if s6 != nil {
  202         s.srv6 = s6
  203     }
  204     s.conf.ConfigModified()
  205     s.dbLoad()
  206 
  207     if s.conf.Enabled {
  208         staticIP, err := HasStaticIP(newconfig.InterfaceName)
  209         if !staticIP && err == nil {
  210             err = SetStaticIP(newconfig.InterfaceName)
  211             if err != nil {
  212                 httpError(r, w, http.StatusInternalServerError, "Failed to configure static IP: %s", err)
  213                 return
  214             }
  215         }
  216 
  217         err = s.Start()
  218         if err != nil {
  219             httpError(r, w, http.StatusBadRequest, "Failed to start DHCP server: %s", err)
  220             return
  221         }
  222     }
  223 }
  224 
  225 type netInterfaceJSON struct {
  226     Name         string   `json:"name"`
  227     GatewayIP    string   `json:"gateway_ip"`
  228     HardwareAddr string   `json:"hardware_address"`
  229     Addrs4       []string `json:"ipv4_addresses"`
  230     Addrs6       []string `json:"ipv6_addresses"`
  231     Flags        string   `json:"flags"`
  232 }
  233 
  234 func (s *Server) handleDHCPInterfaces(w http.ResponseWriter, r *http.Request) {
  235     response := map[string]interface{}{}
  236 
  237     ifaces, err := util.GetValidNetInterfaces()
  238     if err != nil {
  239         httpError(r, w, http.StatusInternalServerError, "Couldn't get interfaces: %s", err)
  240         return
  241     }
  242 
  243     for _, iface := range ifaces {
  244         if iface.Flags&net.FlagLoopback != 0 {
  245             // it's a loopback, skip it
  246             continue
  247         }
  248         if iface.Flags&net.FlagBroadcast == 0 {
  249             // this interface doesn't support broadcast, skip it
  250             continue
  251         }
  252         addrs, err := iface.Addrs()
  253         if err != nil {
  254             httpError(r, w, http.StatusInternalServerError, "Failed to get addresses for interface %s: %s", iface.Name, err)
  255             return
  256         }
  257 
  258         jsonIface := netInterfaceJSON{
  259             Name:         iface.Name,
  260             HardwareAddr: iface.HardwareAddr.String(),
  261         }
  262 
  263         if iface.Flags != 0 {
  264             jsonIface.Flags = iface.Flags.String()
  265         }
  266         // we don't want link-local addresses in json, so skip them
  267         for _, addr := range addrs {
  268             ipnet, ok := addr.(*net.IPNet)
  269             if !ok {
  270                 // not an IPNet, should not happen
  271                 httpError(r, w, http.StatusInternalServerError, "SHOULD NOT HAPPEN: got iface.Addrs() element %s that is not net.IPNet, it is %T", addr, addr)
  272                 return
  273             }
  274             // ignore link-local
  275             if ipnet.IP.IsLinkLocalUnicast() {
  276                 continue
  277             }
  278             if ipnet.IP.To4() != nil {
  279                 jsonIface.Addrs4 = append(jsonIface.Addrs4, ipnet.IP.String())
  280             } else {
  281                 jsonIface.Addrs6 = append(jsonIface.Addrs6, ipnet.IP.String())
  282             }
  283         }
  284         if len(jsonIface.Addrs4)+len(jsonIface.Addrs6) != 0 {
  285             jsonIface.GatewayIP = getGatewayIP(iface.Name)
  286             response[iface.Name] = jsonIface
  287         }
  288     }
  289 
  290     err = json.NewEncoder(w).Encode(response)
  291     if err != nil {
  292         httpError(r, w, http.StatusInternalServerError, "Failed to marshal json with available interfaces: %s", err)
  293         return
  294     }
  295 }
  296 
  297 // Perform the following tasks:
  298 // . Search for another DHCP server running
  299 // . Check if a static IP is configured for the network interface
  300 // Respond with results
  301 func (s *Server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) {
  302     body, err := ioutil.ReadAll(r.Body)
  303     if err != nil {
  304         msg := fmt.Sprintf("failed to read request body: %s", err)
  305         log.Error(msg)
  306         http.Error(w, msg, http.StatusBadRequest)
  307         return
  308     }
  309 
  310     interfaceName := strings.TrimSpace(string(body))
  311     if interfaceName == "" {
  312         msg := "empty interface name specified"
  313         log.Error(msg)
  314         http.Error(w, msg, http.StatusBadRequest)
  315         return
  316     }
  317 
  318     found4, err4 := CheckIfOtherDHCPServersPresentV4(interfaceName)
  319 
  320     staticIP := map[string]interface{}{}
  321     isStaticIP, err := HasStaticIP(interfaceName)
  322     staticIPStatus := "yes"
  323     if err != nil {
  324         staticIPStatus = "error"
  325         staticIP["error"] = err.Error()
  326     } else if !isStaticIP {
  327         staticIPStatus = "no"
  328         staticIP["ip"] = util.GetSubnet(interfaceName)
  329     }
  330     staticIP["static"] = staticIPStatus
  331 
  332     v4 := map[string]interface{}{}
  333     othSrv := map[string]interface{}{}
  334     foundVal := "no"
  335     if found4 {
  336         foundVal = "yes"
  337     } else if err4 != nil {
  338         foundVal = "error"
  339         othSrv["error"] = err4.Error()
  340     }
  341     othSrv["found"] = foundVal
  342     v4["other_server"] = othSrv
  343     v4["static_ip"] = staticIP
  344 
  345     found6, err6 := CheckIfOtherDHCPServersPresentV6(interfaceName)
  346 
  347     v6 := map[string]interface{}{}
  348     othSrv = map[string]interface{}{}
  349     foundVal = "no"
  350     if found6 {
  351         foundVal = "yes"
  352     } else if err6 != nil {
  353         foundVal = "error"
  354         othSrv["error"] = err6.Error()
  355     }
  356     othSrv["found"] = foundVal
  357     v6["other_server"] = othSrv
  358 
  359     result := map[string]interface{}{}
  360     result["v4"] = v4
  361     result["v6"] = v6
  362 
  363     w.Header().Set("Content-Type", "application/json")
  364     err = json.NewEncoder(w).Encode(result)
  365     if err != nil {
  366         httpError(r, w, http.StatusInternalServerError, "Failed to marshal DHCP found json: %s", err)
  367         return
  368     }
  369 }
  370 
  371 func (s *Server) handleDHCPAddStaticLease(w http.ResponseWriter, r *http.Request) {
  372     lj := staticLeaseJSON{}
  373     err := json.NewDecoder(r.Body).Decode(&lj)
  374     if err != nil {
  375         httpError(r, w, http.StatusBadRequest, "json.Decode: %s", err)
  376         return
  377     }
  378 
  379     ip := net.ParseIP(lj.IP)
  380     if ip != nil && ip.To4() == nil {
  381         mac, err := net.ParseMAC(lj.HWAddr)
  382         if err != nil {
  383             httpError(r, w, http.StatusBadRequest, "invalid MAC")
  384             return
  385         }
  386 
  387         lease := Lease{
  388             IP:     ip,
  389             HWAddr: mac,
  390         }
  391 
  392         err = s.srv6.AddStaticLease(lease)
  393         if err != nil {
  394             httpError(r, w, http.StatusBadRequest, "%s", err)
  395             return
  396         }
  397         return
  398     }
  399 
  400     ip, _ = parseIPv4(lj.IP)
  401     if ip == nil {
  402         httpError(r, w, http.StatusBadRequest, "invalid IP")
  403         return
  404     }
  405 
  406     mac, err := net.ParseMAC(lj.HWAddr)
  407     if err != nil {
  408         httpError(r, w, http.StatusBadRequest, "invalid MAC")
  409         return
  410     }
  411 
  412     lease := Lease{
  413         IP:       ip,
  414         HWAddr:   mac,
  415         Hostname: lj.Hostname,
  416     }
  417     err = s.srv4.AddStaticLease(lease)
  418     if err != nil {
  419         httpError(r, w, http.StatusBadRequest, "%s", err)
  420         return
  421     }
  422 }
  423 
  424 func (s *Server) handleDHCPRemoveStaticLease(w http.ResponseWriter, r *http.Request) {
  425     lj := staticLeaseJSON{}
  426     err := json.NewDecoder(r.Body).Decode(&lj)
  427     if err != nil {
  428         httpError(r, w, http.StatusBadRequest, "json.Decode: %s", err)
  429         return
  430     }
  431 
  432     ip := net.ParseIP(lj.IP)
  433     if ip != nil && ip.To4() == nil {
  434         mac, err := net.ParseMAC(lj.HWAddr)
  435         if err != nil {
  436             httpError(r, w, http.StatusBadRequest, "invalid MAC")
  437             return
  438         }
  439 
  440         lease := Lease{
  441             IP:     ip,
  442             HWAddr: mac,
  443         }
  444 
  445         err = s.srv6.RemoveStaticLease(lease)
  446         if err != nil {
  447             httpError(r, w, http.StatusBadRequest, "%s", err)
  448             return
  449         }
  450         return
  451     }
  452 
  453     ip, _ = parseIPv4(lj.IP)
  454     if ip == nil {
  455         httpError(r, w, http.StatusBadRequest, "invalid IP")
  456         return
  457     }
  458 
  459     mac, _ := net.ParseMAC(lj.HWAddr)
  460 
  461     lease := Lease{
  462         IP:       ip,
  463         HWAddr:   mac,
  464         Hostname: lj.Hostname,
  465     }
  466     err = s.srv4.RemoveStaticLease(lease)
  467     if err != nil {
  468         httpError(r, w, http.StatusBadRequest, "%s", err)
  469         return
  470     }
  471 }
  472 
  473 func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) {
  474     s.Stop()
  475 
  476     err := os.Remove(s.conf.DBFilePath)
  477     if err != nil && !os.IsNotExist(err) {
  478         log.Error("DHCP: os.Remove: %s: %s", s.conf.DBFilePath, err)
  479     }
  480 
  481     oldconf := s.conf
  482     s.conf = ServerConfig{}
  483     s.conf.WorkDir = oldconf.WorkDir
  484     s.conf.HTTPRegister = oldconf.HTTPRegister
  485     s.conf.ConfigModified = oldconf.ConfigModified
  486     s.conf.DBFilePath = oldconf.DBFilePath
  487 
  488     v4conf := V4ServerConf{}
  489     v4conf.ICMPTimeout = 1000
  490     v4conf.notify = s.onNotify
  491     s.srv4, _ = v4Create(v4conf)
  492 
  493     v6conf := V6ServerConf{}
  494     v6conf.notify = s.onNotify
  495     s.srv6, _ = v6Create(v6conf)
  496 
  497     s.conf.ConfigModified()
  498 }
  499 
  500 func (s *Server) registerHandlers() {
  501     s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/status", s.handleDHCPStatus)
  502     s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/interfaces", s.handleDHCPInterfaces)
  503     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/set_config", s.handleDHCPSetConfig)
  504     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/find_active_dhcp", s.handleDHCPFindActiveServer)
  505     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/add_static_lease", s.handleDHCPAddStaticLease)
  506     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/remove_static_lease", s.handleDHCPRemoveStaticLease)
  507     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset", s.handleReset)
  508 }
  509 
  510 // jsonError is a generic JSON error response.
  511 type jsonError struct {
  512     // Message is the error message, an opaque string.
  513     Message string `json:"message"`
  514 }
  515 
  516 // notImplemented returns a handler that replies to any request with an HTTP 501
  517 // Not Implemented status and a JSON error with the provided message msg.
  518 //
  519 // TODO(a.garipov): Either take the logger from the server after we've
  520 // refactored logging or make this not a method of *Server.
  521 func (s *Server) notImplemented(msg string) (f func(http.ResponseWriter, *http.Request)) {
  522     return func(w http.ResponseWriter, _ *http.Request) {
  523         w.Header().Set("Content-Type", "application/json")
  524         w.WriteHeader(http.StatusNotImplemented)
  525 
  526         err := json.NewEncoder(w).Encode(&jsonError{
  527             Message: msg,
  528         })
  529         if err != nil {
  530             log.Debug("writing 501 json response: %s", err)
  531         }
  532     }
  533 }
  534 
  535 func (s *Server) registerNotImplementedHandlers() {
  536     h := s.notImplemented("dhcp is not supported on windows")
  537 
  538     s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/status", h)
  539     s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/interfaces", h)
  540     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/set_config", h)
  541     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/find_active_dhcp", h)
  542     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/add_static_lease", h)
  543     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/remove_static_lease", h)
  544     s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset", h)
  545 }