text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "bytes" "fmt" "net" "net/netip" "slices" "strings" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/go-ping/ping" "github.com/insomniacslk/dhcp/dhcpv4" "github.com/insomniacslk/dhcp/dhcpv4/server4" ) // v4Server is a DHCPv4 server. // // TODO(a.garipov): Think about unifying this and v6Server. type v4Server struct { conf *V4ServerConf srv *server4.Server // implicitOpts are the options listed in Appendix A of RFC 2131 initialized // with default values. It must not have intersections with [explicitOpts]. implicitOpts dhcpv4.Options // explicitOpts are the options parsed from the configuration. It must not // have intersections with [implicitOpts]. explicitOpts dhcpv4.Options // leasesLock protects leases, hostsIndex, ipIndex, and leasedOffsets. leasesLock sync.Mutex // leasedOffsets contains offsets from conf.ipRange.start that have been // leased. leasedOffsets *bitSet // leases contains all dynamic and static leases. leases []*dhcpsvc.Lease // hostsIndex is the set of all hostnames of all known DHCP clients. hostsIndex map[string]*dhcpsvc.Lease // ipIndex is an index of leases by their IP addresses. ipIndex map[netip.Addr]*dhcpsvc.Lease } func (s *v4Server) enabled() (ok bool) { return s.conf != nil && s.conf.Enabled } // WriteDiskConfig4 - write configuration func (s *v4Server) WriteDiskConfig4(c *V4ServerConf) { if s.conf != nil { *c = *s.conf } } // WriteDiskConfig6 - write configuration func (s *v4Server) WriteDiskConfig6(c *V6ServerConf) { } // normalizeHostname normalizes a hostname sent by the client. If err is not // nil, norm is an empty string. func normalizeHostname(hostname string) (norm string, err error) { defer func() { err = errors.Annotate(err, "normalizing %q: %w", hostname) }() if hostname == "" { return "", nil } norm = strings.ToLower(hostname) parts := strings.FieldsFunc(norm, func(c rune) (ok bool) { return c != '.' && !netutil.IsValidHostOuterRune(c) }) if len(parts) == 0 { return "", fmt.Errorf("no valid parts") } norm = strings.Join(parts, "-") norm = strings.TrimSuffix(norm, "-") return norm, nil } // validHostnameForClient accepts the hostname sent by the client and its IP and // returns either a normalized version of that hostname, or a new hostname // generated from the IP address, or an empty string. func (s *v4Server) validHostnameForClient(cliHostname string, ip netip.Addr) (hostname string) { hostname, err := normalizeHostname(cliHostname) if err != nil { log.Info("dhcpv4: %s", err) } if hostname == "" { hostname = aghnet.GenerateHostname(ip) } err = netutil.ValidateHostname(hostname) if err != nil { log.Info("dhcpv4: %s", err) hostname = "" } return hostname } // HostByIP implements the [Interface] interface for *v4Server. func (s *v4Server) HostByIP(ip netip.Addr) (host string) { s.leasesLock.Lock() defer s.leasesLock.Unlock() if l, ok := s.ipIndex[ip]; ok { return l.Hostname } return "" } // IPByHost implements the [Interface] interface for *v4Server. func (s *v4Server) IPByHost(host string) (ip netip.Addr) { s.leasesLock.Lock() defer s.leasesLock.Unlock() if l, ok := s.hostsIndex[host]; ok { return l.IP } return netip.Addr{} } // ResetLeases resets leases. func (s *v4Server) ResetLeases(leases []*dhcpsvc.Lease) (err error) { defer func() { err = errors.Annotate(err, "dhcpv4: %w") }() if s.conf == nil { return nil } s.leasesLock.Lock() defer s.leasesLock.Unlock() s.leasedOffsets = newBitSet() s.hostsIndex = make(map[string]*dhcpsvc.Lease, len(leases)) s.ipIndex = make(map[netip.Addr]*dhcpsvc.Lease, len(leases)) s.leases = nil for _, l := range leases { if !l.IsStatic { l.Hostname = s.validHostnameForClient(l.Hostname, l.IP) } err = s.addLease(l) if err != nil { // TODO(a.garipov): Wrap and bubble up the error. log.Error("dhcpv4: reset: re-adding a lease for %s (%s): %s", l.IP, l.HWAddr, err) continue } } return nil } // getLeasesRef returns the actual leases slice. For internal use only. func (s *v4Server) getLeasesRef() []*dhcpsvc.Lease { return s.leases } // isBlocklisted returns true if this lease holds a blocklisted IP. // // TODO(a.garipov): Make a method of *Lease? func (s *v4Server) isBlocklisted(l *dhcpsvc.Lease) (ok bool) { if len(l.HWAddr) == 0 { return false } for _, b := range l.HWAddr { if b != 0 { return false } } return true } // GetLeases returns the list of current DHCP leases. It is safe for concurrent // use. func (s *v4Server) GetLeases(flags GetLeasesFlags) (leases []*dhcpsvc.Lease) { // The function shouldn't return nil, because zero-length slice behaves // differently in cases like marshalling. Our front-end also requires // a non-nil value in the response. leases = []*dhcpsvc.Lease{} getDynamic := flags&LeasesDynamic != 0 getStatic := flags&LeasesStatic != 0 s.leasesLock.Lock() defer s.leasesLock.Unlock() now := time.Now() for _, l := range s.leases { if getDynamic && l.Expiry.After(now) && !s.isBlocklisted(l) { leases = append(leases, l.Clone()) continue } if getStatic && l.IsStatic { leases = append(leases, l.Clone()) } } return leases } // FindMACbyIP implements the [Interface] for *v4Server. func (s *v4Server) FindMACbyIP(ip netip.Addr) (mac net.HardwareAddr) { if !ip.Is4() { return nil } now := time.Now() s.leasesLock.Lock() defer s.leasesLock.Unlock() if l, ok := s.ipIndex[ip]; ok { if l.IsStatic || l.Expiry.After(now) { return l.HWAddr } } return nil } // defaultHwAddrLen is the default length of a hardware (MAC) address. const defaultHwAddrLen = 6 // Add the specified IP to the black list for a time period func (s *v4Server) blocklistLease(l *dhcpsvc.Lease) { l.HWAddr = make(net.HardwareAddr, defaultHwAddrLen) l.Hostname = "" l.Expiry = time.Now().Add(s.conf.leaseTime) } // rmLeaseByIndex removes a lease by its index in the leases slice. func (s *v4Server) rmLeaseByIndex(i int) { n := len(s.leases) if i >= n { // TODO(a.garipov): Better error handling. log.Debug("dhcpv4: can't remove lease at index %d: no such lease", i) return } l := s.leases[i] s.leases = append(s.leases[:i], s.leases[i+1:]...) r := s.conf.ipRange leaseIP := net.IP(l.IP.AsSlice()) offset, ok := r.offset(leaseIP) if ok { s.leasedOffsets.set(offset, false) } delete(s.hostsIndex, l.Hostname) delete(s.ipIndex, l.IP) log.Debug("dhcpv4: removed lease %s (%s)", l.IP, l.HWAddr) } // Remove a dynamic lease with the same properties // Return error if a static lease is found // // TODO(s.chzhen): Refactor the code. func (s *v4Server) rmDynamicLease(lease *dhcpsvc.Lease) (err error) { for i, l := range s.leases { isStatic := l.IsStatic if bytes.Equal(l.HWAddr, lease.HWAddr) || l.IP == lease.IP { if isStatic { return errors.Error("static lease already exists") } s.rmLeaseByIndex(i) if i == len(s.leases) { break } l = s.leases[i] } if !isStatic && l.Hostname == lease.Hostname { l.Hostname = "" } } return nil } const ( // ErrDupHostname is returned by addLease, validateStaticLease when the // modified lease has a not empty non-unique hostname. ErrDupHostname = errors.Error("hostname is not unique") // ErrDupIP is returned by addLease, validateStaticLease when the modified // lease has a non-unique IP address. ErrDupIP = errors.Error("ip address is not unique") ) // addLease adds a dynamic or static lease. func (s *v4Server) addLease(l *dhcpsvc.Lease) (err error) { r := s.conf.ipRange leaseIP := net.IP(l.IP.AsSlice()) offset, inOffset := r.offset(leaseIP) if l.IsStatic { // TODO(a.garipov, d.seregin): Subnet can be nil when dhcp server is // disabled. if sn := s.conf.subnet; !sn.Contains(l.IP) { return fmt.Errorf("subnet %s does not contain the ip %q", sn, l.IP) } } else if !inOffset { return fmt.Errorf("lease %s (%s) out of range, not adding", l.IP, l.HWAddr) } // TODO(e.burkov): l must have a valid hostname here, investigate. if l.Hostname != "" { if _, ok := s.hostsIndex[l.Hostname]; ok { return ErrDupHostname } s.hostsIndex[l.Hostname] = l } s.ipIndex[l.IP] = l s.leases = append(s.leases, l) s.leasedOffsets.set(offset, true) return nil } // rmLease removes a lease with the same properties. func (s *v4Server) rmLease(lease *dhcpsvc.Lease) (err error) { if len(s.leases) == 0 { return nil } for i, l := range s.leases { if l.IP == lease.IP { if !bytes.Equal(l.HWAddr, lease.HWAddr) || l.Hostname != lease.Hostname { return fmt.Errorf("lease for ip %s is different: %+v", lease.IP, l) } s.rmLeaseByIndex(i) return nil } } return errors.Error("lease not found") } // ErrUnconfigured is returned from the server's method when it requires the // server to be configured and it's not. const ErrUnconfigured errors.Error = "server is unconfigured" // AddStaticLease implements the DHCPServer interface for *v4Server. It is // safe for concurrent use. func (s *v4Server) AddStaticLease(l *dhcpsvc.Lease) (err error) { defer func() { err = errors.Annotate(err, "dhcpv4: adding static lease: %w") }() if s.conf == nil { return ErrUnconfigured } l.IP = l.IP.Unmap() if !l.IP.Is4() { return fmt.Errorf("invalid IP %q: only IPv4 is supported", l.IP) } else if gwIP := s.conf.GatewayIP; gwIP == l.IP { return fmt.Errorf("can't assign the gateway IP %q to the lease", gwIP) } l.IsStatic = true err = netutil.ValidateMAC(l.HWAddr) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } if hostname := l.Hostname; hostname != "" { hostname, err = normalizeHostname(hostname) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } err = netutil.ValidateHostname(hostname) if err != nil { return fmt.Errorf("validating hostname: %w", err) } // Don't check for hostname uniqueness, since we try to emulate dnsmasq // here, which means that rmDynamicLease below will simply empty the // hostname of the dynamic lease if there even is one. In case a static // lease with the same name already exists, addLease will return an // error and the lease won't be added. l.Hostname = hostname } err = s.updateStaticLease(l) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } s.conf.notify(LeaseChangedDBStore) s.conf.notify(LeaseChangedAddedStatic) return nil } // UpdateStaticLease updates IP, hostname of the static lease. func (s *v4Server) UpdateStaticLease(l *dhcpsvc.Lease) (err error) { defer func() { if err != nil { err = errors.Annotate(err, "dhcpv4: updating static lease: %w") return } s.conf.notify(LeaseChangedDBStore) s.conf.notify(LeaseChangedRemovedStatic) }() s.leasesLock.Lock() defer s.leasesLock.Unlock() found := s.findLease(l.HWAddr) if found == nil { return fmt.Errorf("can't find lease %s", l.HWAddr) } err = s.validateStaticLease(l) if err != nil { return err } err = s.rmLease(found) if err != nil { return fmt.Errorf("removing previous lease for %s (%s): %w", l.IP, l.HWAddr, err) } err = s.addLease(l) if err != nil { return fmt.Errorf("adding updated static lease for %s (%s): %w", l.IP, l.HWAddr, err) } return nil } // validateStaticLease returns an error if the static lease is invalid. func (s *v4Server) validateStaticLease(l *dhcpsvc.Lease) (err error) { hostname, err := normalizeHostname(l.Hostname) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } err = netutil.ValidateHostname(hostname) if err != nil { return fmt.Errorf("validating hostname: %w", err) } dup, ok := s.hostsIndex[hostname] if ok && !bytes.Equal(dup.HWAddr, l.HWAddr) { return ErrDupHostname } dup, ok = s.ipIndex[l.IP] if ok && !bytes.Equal(dup.HWAddr, l.HWAddr) { return ErrDupIP } l.Hostname = hostname if gwIP := s.conf.GatewayIP; gwIP == l.IP { return fmt.Errorf("can't assign the gateway IP %q to the lease", gwIP) } if sn := s.conf.subnet; !sn.Contains(l.IP) { return fmt.Errorf("subnet %s does not contain the ip %q", sn, l.IP) } return nil } // updateStaticLease safe removes dynamic lease with the same properties and // then adds a static lease l. func (s *v4Server) updateStaticLease(l *dhcpsvc.Lease) (err error) { s.leasesLock.Lock() defer s.leasesLock.Unlock() err = s.rmDynamicLease(l) if err != nil { return fmt.Errorf("removing dynamic leases for %s (%s): %w", l.IP, l.HWAddr, err) } err = s.addLease(l) if err != nil { return fmt.Errorf("adding static lease for %s (%s): %w", l.IP, l.HWAddr, err) } return nil } // RemoveStaticLease removes a static lease. It is safe for concurrent use. func (s *v4Server) RemoveStaticLease(l *dhcpsvc.Lease) (err error) { defer func() { err = errors.Annotate(err, "dhcpv4: %w") }() if s.conf == nil { return ErrUnconfigured } if !l.IP.Is4() { return fmt.Errorf("invalid IP") } err = netutil.ValidateMAC(l.HWAddr) if err != nil { return fmt.Errorf("validating lease: %w", err) } defer func() { if err != nil { return } s.conf.notify(LeaseChangedDBStore) s.conf.notify(LeaseChangedRemovedStatic) }() s.leasesLock.Lock() defer s.leasesLock.Unlock() return s.rmLease(l) } // addrAvailable sends an ICP request to the specified IP address. It returns // true if the remote host doesn't reply, which probably means that the IP // address is available. // // TODO(a.garipov): I'm not sure that this is the best way to do this. func (s *v4Server) addrAvailable(target net.IP) (avail bool) { if s.conf.ICMPTimeout == 0 { return true } pinger, err := ping.NewPinger(target.String()) if err != nil { log.Error("dhcpv4: ping.NewPinger(): %s", err) return true } pinger.SetPrivileged(true) pinger.Timeout = time.Duration(s.conf.ICMPTimeout) * time.Millisecond pinger.Count = 1 reply := false pinger.OnRecv = func(_ *ping.Packet) { reply = true } log.Debug("dhcpv4: sending icmp echo to %s", target) err = pinger.Run() if err != nil { log.Error("dhcpv4: pinger.Run(): %s", err) return true } if reply { log.Info("dhcpv4: ip conflict: %s is already used by another device", target) return false } log.Debug("dhcpv4: icmp procedure is complete: %q", target) return true } // findLease finds a lease by its MAC-address. func (s *v4Server) findLease(mac net.HardwareAddr) (l *dhcpsvc.Lease) { for _, l = range s.leases { if bytes.Equal(mac, l.HWAddr) { return l } } return nil } // nextIP generates a new free IP. func (s *v4Server) nextIP() (ip net.IP) { r := s.conf.ipRange ip = r.find(func(next net.IP) (ok bool) { offset, ok := r.offset(next) if !ok { // Shouldn't happen. return false } return !s.leasedOffsets.isSet(offset) }) return ip.To4() } // Find an expired lease and return its index or -1 func (s *v4Server) findExpiredLease() int { now := time.Now() for i, lease := range s.leases { if !lease.IsStatic && lease.Expiry.Before(now) { return i } } return -1 } // reserveLease reserves a lease for a client by its MAC-address. It returns // nil if it couldn't allocate a new lease. func (s *v4Server) reserveLease(mac net.HardwareAddr) (l *dhcpsvc.Lease, err error) { l = &dhcpsvc.Lease{HWAddr: slices.Clone(mac)} nextIP := s.nextIP() if nextIP == nil { i := s.findExpiredLease() if i < 0 { return nil, nil } copy(s.leases[i].HWAddr, mac) return s.leases[i], nil } netIP, ok := netip.AddrFromSlice(nextIP) if !ok { return nil, errors.Error("invalid ip") } l.IP = netIP err = s.addLease(l) if err != nil { return nil, err } return l, nil } // commitLease refreshes l's values. It takes the desired hostname into account // when setting it into the lease, but generates a unique one if the provided // can't be used. func (s *v4Server) commitLease(l *dhcpsvc.Lease, hostname string) { prev := l.Hostname hostname = s.validHostnameForClient(hostname, l.IP) if _, ok := s.hostsIndex[hostname]; ok { log.Info("dhcpv4: hostname %q already exists", hostname) if prev == "" { // The lease is just allocated due to DHCPDISCOVER. hostname = aghnet.GenerateHostname(l.IP) } else { hostname = prev } } if l.Hostname != hostname { l.Hostname = hostname } l.Expiry = time.Now().Add(s.conf.leaseTime) if prev != "" && prev != l.Hostname { delete(s.hostsIndex, prev) } if l.Hostname != "" { s.hostsIndex[l.Hostname] = l } s.ipIndex[l.IP] = l } // allocateLease allocates a new lease for the MAC address. If there are no IP // addresses left, both l and err are nil. func (s *v4Server) allocateLease(mac net.HardwareAddr) (l *dhcpsvc.Lease, err error) { for { l, err = s.reserveLease(mac) if err != nil { return nil, fmt.Errorf("reserving a lease: %w", err) } else if l == nil { return nil, nil } leaseIP := l.IP.AsSlice() if s.addrAvailable(leaseIP) { return l, nil } s.blocklistLease(l) } } // handleDiscover is the handler for the DHCP Discover request. func (s *v4Server) handleDiscover(req, resp *dhcpv4.DHCPv4) (l *dhcpsvc.Lease, err error) { mac := req.ClientHWAddr defer s.conf.notify(LeaseChangedDBStore) s.leasesLock.Lock() defer s.leasesLock.Unlock() l = s.findLease(mac) if l != nil { reqIP := req.RequestedIPAddress() leaseIP := net.IP(l.IP.AsSlice()) if len(reqIP) != 0 && !reqIP.Equal(leaseIP) { log.Debug("dhcpv4: different RequestedIP: %s != %s", reqIP, leaseIP) } resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeOffer)) return l, nil } l, err = s.allocateLease(mac) if err != nil { return nil, err } else if l == nil { log.Debug("dhcpv4: no more ip addresses") return nil, nil } resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeOffer)) return l, nil } // OptionFQDN returns a DHCPv4 option for sending the FQDN to the client // requested another hostname. // // See path_to_url func OptionFQDN(fqdn string) (opt dhcpv4.Option) { optData := []byte{ // Set only S and O DHCP client FQDN option flags. // // See path_to_url#section-2.1. 1<<0 | 1<<1, // The RCODE fields should be set to 0xFF in the server responses. // // See path_to_url#section-2.2. 0xFF, 0xFF, } optData = append(optData, fqdn...) return dhcpv4.OptGeneric(dhcpv4.OptionFQDN, optData) } // checkLease checks if the pair of mac and ip is already leased. The mismatch // is true when the existing lease has the same hardware address but differs in // its IP address. func (s *v4Server) checkLease(mac net.HardwareAddr, ip net.IP) (l *dhcpsvc.Lease, mismatch bool) { s.leasesLock.Lock() defer s.leasesLock.Unlock() netIP, ok := netip.AddrFromSlice(ip) if !ok { log.Info("check lease: invalid IP: %s", ip) return nil, false } for _, l = range s.leases { if !bytes.Equal(l.HWAddr, mac) { continue } if l.IP == netIP { return l, false } log.Debug( `dhcpv4: mismatched OptionRequestedIPAddress in req msg for %s`, mac, ) return nil, true } return nil, false } // handleSelecting handles the DHCPREQUEST generated during SELECTING state. func (s *v4Server) handleSelecting( req *dhcpv4.DHCPv4, reqIP net.IP, sid net.IP, ) (l *dhcpsvc.Lease, needsReply bool) { // Client inserts the address of the selected server in server identifier, // ciaddr MUST be zero. mac := req.ClientHWAddr if !sid.Equal(s.conf.dnsIPAddrs[0].AsSlice()) { log.Debug("dhcpv4: bad server identifier in req msg for %s: %s", mac, sid) return nil, false } else if ciaddr := req.ClientIPAddr; ciaddr != nil && !ciaddr.IsUnspecified() { log.Debug("dhcpv4: non-zero ciaddr in selecting req msg for %s", mac) return nil, false } // Requested IP address MUST be filled in with the yiaddr value from the // chosen DHCPOFFER. if ip4 := reqIP.To4(); ip4 == nil { log.Debug("dhcpv4: bad requested address in req msg for %s: %s", mac, reqIP) return nil, false } var mismatch bool if l, mismatch = s.checkLease(mac, reqIP); mismatch { return nil, true } else if l == nil { log.Debug("dhcpv4: no reserved lease for %s", mac) } return l, true } // handleInitReboot handles the DHCPREQUEST generated during INIT-REBOOT state. func (s *v4Server) handleInitReboot( req *dhcpv4.DHCPv4, reqIP net.IP, ) (l *dhcpsvc.Lease, needsReply bool) { mac := req.ClientHWAddr ip4 := reqIP.To4() if ip4 == nil { log.Debug("dhcpv4: bad requested address in req msg for %s: %s", mac, reqIP) return nil, false } // ciaddr MUST be zero. The client is seeking to verify a previously // allocated, cached configuration. if ciaddr := req.ClientIPAddr; ciaddr != nil && !ciaddr.IsUnspecified() { log.Debug("dhcpv4: non-zero ciaddr in init-reboot req msg for %s", mac) return nil, false } if !s.conf.subnet.Contains(netip.AddrFrom4([4]byte(ip4))) { // If the DHCP server detects that the client is on the wrong net then // the server SHOULD send a DHCPNAK message to the client. log.Debug("dhcpv4: wrong subnet in init-reboot req msg for %s: %s", mac, reqIP) return nil, true } var mismatch bool if l, mismatch = s.checkLease(mac, reqIP); mismatch { return nil, true } else if l == nil { // If the DHCP server has no record of this client, then it MUST remain // silent, and MAY output a warning to the network administrator. log.Info("dhcpv4: warning: no existing lease for %s", mac) return nil, false } return l, true } // handleRenew handles the DHCPREQUEST generated during RENEWING or REBINDING // state. func (s *v4Server) handleRenew(req *dhcpv4.DHCPv4) (l *dhcpsvc.Lease, needsReply bool) { mac := req.ClientHWAddr // ciaddr MUST be filled in with client's IP address. ciaddr := req.ClientIPAddr if ciaddr == nil || ciaddr.IsUnspecified() || ciaddr.To4() == nil { log.Debug("dhcpv4: bad ciaddr in renew req msg for %s: %s", mac, ciaddr) return nil, false } var mismatch bool if l, mismatch = s.checkLease(mac, ciaddr); mismatch { return nil, true } else if l == nil { // If the DHCP server has no record of this client, then it MUST remain // silent, and MAY output a warning to the network administrator. log.Info("dhcpv4: warning: no existing lease for %s", mac) return nil, false } return l, true } // handleByRequestType handles the DHCPREQUEST according to the state during // which it's generated by client. func (s *v4Server) handleByRequestType(req *dhcpv4.DHCPv4) (lease *dhcpsvc.Lease, needsReply bool) { reqIP, sid := req.RequestedIPAddress(), req.ServerIdentifier() if sid != nil && !sid.IsUnspecified() { // If the DHCPREQUEST message contains a server identifier option, the // message is in response to a DHCPOFFER message. Otherwise, the // message is a request to verify or extend an existing lease. return s.handleSelecting(req, reqIP, sid) } if reqIP != nil && !reqIP.IsUnspecified() { // Requested IP address option MUST be filled in with client's notion of // its previously assigned address. return s.handleInitReboot(req, reqIP) } // Server identifier MUST NOT be filled in, requested IP address option MUST // NOT be filled in. return s.handleRenew(req) } // handleRequest is the handler for a DHCPREQUEST message. // // See path_to_url#section-4.3.2. func (s *v4Server) handleRequest(req, resp *dhcpv4.DHCPv4) (lease *dhcpsvc.Lease, needsReply bool) { lease, needsReply = s.handleByRequestType(req) if lease == nil { return nil, needsReply } resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck)) hostname := req.HostName() isRequested := hostname != "" || req.ParameterRequestList().Has(dhcpv4.OptionHostName) defer func() { s.conf.notify(LeaseChangedAdded) s.conf.notify(LeaseChangedDBStore) }() s.leasesLock.Lock() defer s.leasesLock.Unlock() if lease.IsStatic { if lease.Hostname != "" { // TODO(e.burkov): This option is used to update the server's DNS // mapping. The option should only be answered when it has been // requested. resp.UpdateOption(OptionFQDN(lease.Hostname)) } return lease, needsReply } s.commitLease(lease, hostname) if isRequested { resp.UpdateOption(dhcpv4.OptHostName(lease.Hostname)) } return lease, needsReply } // handleDecline is the handler for the DHCP Decline request. func (s *v4Server) handleDecline(req, resp *dhcpv4.DHCPv4) (err error) { s.conf.notify(LeaseChangedDBStore) s.leasesLock.Lock() defer s.leasesLock.Unlock() mac := req.ClientHWAddr reqIP := req.RequestedIPAddress() if reqIP == nil { reqIP = req.ClientIPAddr } oldLease := s.findLeaseForIP(reqIP, mac) if oldLease == nil { log.Info("dhcpv4: lease with IP %s for %s not found", reqIP, mac) return nil } err = s.rmDynamicLease(oldLease) if err != nil { return fmt.Errorf("removing old lease for %s: %w", mac, err) } newLease, err := s.allocateLease(mac) if err != nil { return fmt.Errorf("allocating new lease for %s: %w", mac, err) } else if newLease == nil { log.Info("dhcpv4: allocating new lease for %s: no more IP addresses", mac) resp.YourIPAddr = make([]byte, 4) resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck)) return nil } newLease.Hostname = oldLease.Hostname newLease.Expiry = time.Now().Add(s.conf.leaseTime) err = s.addLease(newLease) if err != nil { return fmt.Errorf("adding new lease for %s: %w", mac, err) } log.Info("dhcpv4: changed IP from %s to %s for %s", reqIP, newLease.IP, mac) resp.YourIPAddr = newLease.IP.AsSlice() resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck)) return nil } // findLeaseForIP returns a lease for provided ip and mac. func (s *v4Server) findLeaseForIP(ip net.IP, mac net.HardwareAddr) (l *dhcpsvc.Lease) { netIP, ok := netip.AddrFromSlice(ip) if !ok { log.Info("dhcpv4: invalid IP: %s", ip) return nil } for _, il := range s.leases { if bytes.Equal(il.HWAddr, mac) && il.IP == netIP { return il } } return nil } // handleRelease is the handler for the DHCP Release request. func (s *v4Server) handleRelease(req, resp *dhcpv4.DHCPv4) (err error) { mac := req.ClientHWAddr reqIP := req.RequestedIPAddress() if reqIP == nil { reqIP = req.ClientIPAddr } // TODO(a.garipov): Add a separate notification type for dynamic lease // removal? defer s.conf.notify(LeaseChangedDBStore) n := 0 s.leasesLock.Lock() defer s.leasesLock.Unlock() netIP, ok := netip.AddrFromSlice(reqIP) if !ok { log.Info("dhcpv4: invalid IP: %s", reqIP) return nil } for _, l := range s.leases { if !bytes.Equal(l.HWAddr, mac) || l.IP != netIP { continue } err = s.rmDynamicLease(l) if err != nil { err = fmt.Errorf("removing dynamic lease for %s: %w", mac, err) return } n++ } log.Info("dhcpv4: released %d dynamic leases for %s", n, mac) resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck)) return nil } // messageHandler describes a DHCPv4 message handler function. type messageHandler func( s *v4Server, req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4, ) (rCode int, l *dhcpsvc.Lease, err error) // messageHandlers is a map of handlers for various messages with message types // keys. var messageHandlers = map[dhcpv4.MessageType]messageHandler{ dhcpv4.MessageTypeDiscover: func( s *v4Server, req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4, ) (rCode int, l *dhcpsvc.Lease, err error) { l, err = s.handleDiscover(req, resp) if err != nil { return 0, nil, fmt.Errorf("handling discover: %s", err) } if l == nil { return 0, nil, nil } return 1, l, nil }, dhcpv4.MessageTypeRequest: func( s *v4Server, req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4, ) (rCode int, l *dhcpsvc.Lease, err error) { var toReply bool l, toReply = s.handleRequest(req, resp) if l == nil { if toReply { return 0, nil, nil } // Drop the packet. return -1, nil, nil } return 1, l, nil }, dhcpv4.MessageTypeDecline: func( s *v4Server, req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4, ) (rCode int, l *dhcpsvc.Lease, err error) { err = s.handleDecline(req, resp) if err != nil { return 0, nil, fmt.Errorf("handling decline: %s", err) } return 1, nil, nil }, dhcpv4.MessageTypeRelease: func( s *v4Server, req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4, ) (rCode int, l *dhcpsvc.Lease, err error) { err = s.handleRelease(req, resp) if err != nil { return 0, nil, fmt.Errorf("handling release: %s", err) } return 1, nil, nil }, } // handle processes request, it finds a lease associated with MAC address and // prepares response. // // Possible return values are: // - "1": OK, // - "0": error, reply with Nak, // - "-1": error, don't reply. func (s *v4Server) handle(req, resp *dhcpv4.DHCPv4) (rCode int) { var err error // Include server's identifier option since any reply should contain it. // // See path_to_url#page-29. resp.UpdateOption(dhcpv4.OptServerIdentifier(s.conf.dnsIPAddrs[0].AsSlice())) handler := messageHandlers[req.MessageType()] if handler == nil { s.updateOptions(req, resp) return 1 } rCode, l, err := handler(s, req, resp) if err != nil { log.Error("dhcpv4: %s", err) return 0 } if rCode != 1 { return rCode } if l != nil { resp.YourIPAddr = l.IP.AsSlice() } s.updateOptions(req, resp) return 1 } // updateOptions updates the options of the response in accordance with the // request and RFC 2131. // // See path_to_url#section-4.3.1. func (s *v4Server) updateOptions(req, resp *dhcpv4.DHCPv4) { // Set IP address lease time for all DHCPOFFER messages and DHCPACK messages // replied for DHCPREQUEST. // // TODO(e.burkov): Inspect why this is always set to configured value. resp.UpdateOption(dhcpv4.OptIPAddressLeaseTime(s.conf.leaseTime)) // If the server recognizes the parameter as a parameter defined in the Host // Requirements Document, the server MUST include the default value for that // parameter. for _, code := range req.ParameterRequestList() { if val := s.implicitOpts.Get(code); val != nil { resp.UpdateOption(dhcpv4.OptGeneric(code, val)) } } // If the server has been explicitly configured with a default value for the // parameter or the parameter has a non-default value on the client's // subnet, the server MUST include that value in an appropriate option. for code, val := range s.explicitOpts { if val != nil { resp.Options[code] = val } else { // Delete options explicitly configured to be removed. delete(resp.Options, code) } } } // client(0.0.0.0:68) -> (Request:ClientMAC,Type=Discover,ClientID,ReqIP,HostName) -> server(255.255.255.255:67) // client(255.255.255.255:68) <- (Reply:YourIP,ClientMAC,Type=Offer,ServerID,SubnetMask,LeaseTime) <- server(<IP>:67) // client(0.0.0.0:68) -> (Request:ClientMAC,Type=Request,ClientID,ReqIP||ClientIP,HostName,ServerID,ParamReqList) -> server(255.255.255.255:67) // client(255.255.255.255:68) <- (Reply:YourIP,ClientMAC,Type=ACK,ServerID,SubnetMask,LeaseTime) <- server(<IP>:67) func (s *v4Server) packetHandler(conn net.PacketConn, peer net.Addr, req *dhcpv4.DHCPv4) { log.Debug("dhcpv4: received message: %s", req.Summary()) switch req.MessageType() { case dhcpv4.MessageTypeDiscover, dhcpv4.MessageTypeRequest, dhcpv4.MessageTypeDecline, dhcpv4.MessageTypeRelease: // Go on. default: log.Debug("dhcpv4: unsupported message type %d", req.MessageType()) return } resp, err := dhcpv4.NewReplyFromRequest(req) if err != nil { log.Debug("dhcpv4: dhcpv4.New: %s", err) return } err = netutil.ValidateMAC(req.ClientHWAddr) if err != nil { log.Error("dhcpv4: invalid ClientHWAddr: %s", err) return } r := s.handle(req, resp) if r < 0 { return } else if r == 0 { resp.Options.Update(dhcpv4.OptMessageType(dhcpv4.MessageTypeNak)) } s.send(peer, conn, req, resp) } // Start starts the IPv4 DHCP server. func (s *v4Server) Start() (err error) { defer func() { err = errors.Annotate(err, "dhcpv4: %w") }() if !s.enabled() { return nil } ifaceName := s.conf.InterfaceName iface, err := net.InterfaceByName(ifaceName) if err != nil { return fmt.Errorf("finding interface %s by name: %w", ifaceName, err) } log.Debug("dhcpv4: starting...") dnsIPAddrs, err := aghnet.IfaceDNSIPAddrs( iface, aghnet.IPVersion4, defaultMaxAttempts, defaultBackoff, ) if err != nil { return fmt.Errorf("interface %s: %w", ifaceName, err) } if len(dnsIPAddrs) == 0 { // No available IP addresses which may appear later. return nil } s.configureDNSIPAddrs(dnsIPAddrs) var c net.PacketConn if c, err = s.newDHCPConn(iface); err != nil { return err } s.srv, err = server4.NewServer( iface.Name, nil, s.packetHandler, server4.WithConn(c), server4.WithDebugLogger(), ) if err != nil { return err } log.Info("dhcpv4: listening") go func() { if sErr := s.srv.Serve(); errors.Is(sErr, net.ErrClosed) { log.Info("dhcpv4: server is closed") } else if sErr != nil { log.Error("dhcpv4: srv.Serve: %s", sErr) } }() // Signal to the clients containers in packages home and dnsforward that // it should reload the DHCP clients. s.conf.notify(LeaseChangedAdded) return nil } // configureDNSIPAddrs updates v4Server configuration with provided slice of // dns IP addresses. func (s *v4Server) configureDNSIPAddrs(dnsIPAddrs []net.IP) { // Update the value of Domain Name Server option separately from others if // not assigned yet since its value is available only at server's start. // // TODO(e.burkov): Initialize as implicit option with the rest of default // options when it will be possible to do before the call to Start. if !s.explicitOpts.Has(dhcpv4.OptionDomainNameServer) { s.implicitOpts.Update(dhcpv4.OptDNS(dnsIPAddrs...)) } for _, ip := range dnsIPAddrs { vAddr, err := netutil.IPToAddr(ip, netutil.AddrFamilyIPv4) if err != nil { continue } s.conf.dnsIPAddrs = append(s.conf.dnsIPAddrs, vAddr) } } // Stop - stop server func (s *v4Server) Stop() (err error) { if s.srv == nil { return } log.Debug("dhcpv4: stopping") err = s.srv.Close() if err != nil { return fmt.Errorf("closing dhcpv4 srv: %w", err) } // Signal to the clients containers in packages home and dnsforward that // it should remove all DHCP clients. s.conf.notify(LeaseChangedRemovedAll) s.srv = nil return nil } // Create DHCPv4 server func v4Create(conf *V4ServerConf) (srv *v4Server, err error) { s := &v4Server{ hostsIndex: map[string]*dhcpsvc.Lease{}, ipIndex: map[netip.Addr]*dhcpsvc.Lease{}, } err = conf.Validate() if err != nil { // TODO(a.garipov): Don't use a disabled server in other places or just // use an interface. return s, err } s.conf = &V4ServerConf{} *s.conf = *conf // TODO(a.garipov, d.seregin): Check that every lease is inside the IPRange. s.leasedOffsets = newBitSet() if conf.LeaseDuration == 0 { s.conf.leaseTime = timeutil.Day s.conf.LeaseDuration = uint32(s.conf.leaseTime.Seconds()) } else { s.conf.leaseTime = time.Second * time.Duration(conf.LeaseDuration) } s.prepareOptions() return s, nil } ```
/content/code_sandbox/internal/dhcpd/v4_unix.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
10,778
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "encoding/json" "fmt" "io" "net" "net/http" "net/netip" "os" "slices" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" ) type v4ServerConfJSON struct { GatewayIP netip.Addr `json:"gateway_ip"` SubnetMask netip.Addr `json:"subnet_mask"` RangeStart netip.Addr `json:"range_start"` RangeEnd netip.Addr `json:"range_end"` LeaseDuration uint32 `json:"lease_duration"` } func (j *v4ServerConfJSON) toServerConf() *V4ServerConf { if j == nil { return &V4ServerConf{} } return &V4ServerConf{ GatewayIP: j.GatewayIP, SubnetMask: j.SubnetMask, RangeStart: j.RangeStart, RangeEnd: j.RangeEnd, LeaseDuration: j.LeaseDuration, } } type v6ServerConfJSON struct { RangeStart netip.Addr `json:"range_start"` LeaseDuration uint32 `json:"lease_duration"` } func v6JSONToServerConf(j *v6ServerConfJSON) V6ServerConf { if j == nil { return V6ServerConf{} } return V6ServerConf{ RangeStart: j.RangeStart.AsSlice(), LeaseDuration: j.LeaseDuration, } } // dhcpStatusResponse is the response for /control/dhcp/status endpoint. type dhcpStatusResponse struct { IfaceName string `json:"interface_name"` V4 V4ServerConf `json:"v4"` V6 V6ServerConf `json:"v6"` Leases []*leaseDynamic `json:"leases"` StaticLeases []*leaseStatic `json:"static_leases"` Enabled bool `json:"enabled"` } // leaseStatic is the JSON form of static DHCP lease. type leaseStatic struct { HWAddr string `json:"mac"` IP netip.Addr `json:"ip"` Hostname string `json:"hostname"` } // leasesToStatic converts list of leases to their JSON form. func leasesToStatic(leases []*dhcpsvc.Lease) (static []*leaseStatic) { static = make([]*leaseStatic, len(leases)) for i, l := range leases { static[i] = &leaseStatic{ HWAddr: l.HWAddr.String(), IP: l.IP, Hostname: l.Hostname, } } return static } // toLease converts leaseStatic to Lease or returns error. func (l *leaseStatic) toLease() (lease *dhcpsvc.Lease, err error) { addr, err := net.ParseMAC(l.HWAddr) if err != nil { return nil, fmt.Errorf("couldn't parse MAC address: %w", err) } return &dhcpsvc.Lease{ HWAddr: addr, IP: l.IP, Hostname: l.Hostname, IsStatic: true, }, nil } // leaseDynamic is the JSON form of dynamic DHCP lease. type leaseDynamic struct { HWAddr string `json:"mac"` IP netip.Addr `json:"ip"` Hostname string `json:"hostname"` Expiry string `json:"expires"` } // leasesToDynamic converts list of leases to their JSON form. func leasesToDynamic(leases []*dhcpsvc.Lease) (dynamic []*leaseDynamic) { dynamic = make([]*leaseDynamic, len(leases)) for i, l := range leases { dynamic[i] = &leaseDynamic{ HWAddr: l.HWAddr.String(), IP: l.IP, Hostname: l.Hostname, // The front-end is waiting for RFC 3999 format of the time // value. // // See path_to_url Expiry: l.Expiry.Format(time.RFC3339), } } return dynamic } func (s *server) handleDHCPStatus(w http.ResponseWriter, r *http.Request) { status := &dhcpStatusResponse{ Enabled: s.conf.Enabled, IfaceName: s.conf.InterfaceName, V4: V4ServerConf{}, V6: V6ServerConf{}, } s.srv4.WriteDiskConfig4(&status.V4) s.srv6.WriteDiskConfig6(&status.V6) leases := s.Leases() slices.SortFunc(leases, func(a, b *dhcpsvc.Lease) (res int) { if a.IsStatic == b.IsStatic { return 0 } else if a.IsStatic { return -1 } else { return 1 } }) dynamicIdx := slices.IndexFunc(leases, func(l *dhcpsvc.Lease) (ok bool) { return !l.IsStatic }) if dynamicIdx == -1 { dynamicIdx = len(leases) } status.Leases = leasesToDynamic(leases[dynamicIdx:]) status.StaticLeases = leasesToStatic(leases[:dynamicIdx]) aghhttp.WriteJSONResponseOK(w, r, status) } func (s *server) enableDHCP(ifaceName string) (code int, err error) { var hasStaticIP bool hasStaticIP, err = aghnet.IfaceHasStaticIP(ifaceName) if err != nil { if errors.Is(err, os.ErrPermission) { // ErrPermission may happen here on Linux systems where AdGuard Home // is installed using Snap. That doesn't necessarily mean that the // machine doesn't have a static IP, so we can assume that it has // and go on. If the machine doesn't, we'll get an error later. // // See path_to_url // // TODO(a.garipov): I was thinking about moving this into // IfaceHasStaticIP, but then we wouldn't be able to log it. Think // about it more. log.Info("error while checking static ip: %s; "+ "assuming machine has static ip and going on", err) hasStaticIP = true } else if errors.Is(err, aghnet.ErrNoStaticIPInfo) { // Couldn't obtain a definitive answer. Assume static IP an go on. log.Info("can't check for static ip; " + "assuming machine has static ip and going on") hasStaticIP = true } else { err = fmt.Errorf("checking static ip: %w", err) return http.StatusInternalServerError, err } } if !hasStaticIP { err = aghnet.IfaceSetStaticIP(ifaceName) if err != nil { err = fmt.Errorf("setting static ip: %w", err) return http.StatusInternalServerError, err } } err = s.Start() if err != nil { return http.StatusBadRequest, fmt.Errorf("starting dhcp server: %w", err) } return 0, nil } type dhcpServerConfigJSON struct { V4 *v4ServerConfJSON `json:"v4"` V6 *v6ServerConfJSON `json:"v6"` InterfaceName string `json:"interface_name"` Enabled aghalg.NullBool `json:"enabled"` } func (s *server) handleDHCPSetConfigV4( conf *dhcpServerConfigJSON, ) (srv DHCPServer, enabled bool, err error) { if conf.V4 == nil { return nil, false, nil } v4Conf := conf.V4.toServerConf() v4Conf.Enabled = conf.Enabled == aghalg.NBTrue if !v4Conf.RangeStart.IsValid() { v4Conf.Enabled = false } v4Conf.InterfaceName = conf.InterfaceName // Set the default values for the fields not configurable via web API. c4 := &V4ServerConf{ notify: s.onNotify, ICMPTimeout: s.conf.Conf4.ICMPTimeout, Options: s.conf.Conf4.Options, } s.srv4.WriteDiskConfig4(c4) v4Conf.notify = c4.notify v4Conf.ICMPTimeout = c4.ICMPTimeout v4Conf.Options = c4.Options srv4, err := v4Create(v4Conf) return srv4, srv4.enabled(), err } func (s *server) handleDHCPSetConfigV6( conf *dhcpServerConfigJSON, ) (srv6 DHCPServer, enabled bool, err error) { if conf.V6 == nil { return nil, false, nil } v6Conf := v6JSONToServerConf(conf.V6) v6Conf.Enabled = conf.Enabled == aghalg.NBTrue if len(v6Conf.RangeStart) == 0 { v6Conf.Enabled = false } // Don't overwrite the RA/SLAAC settings from the config file. // // TODO(a.garipov): Perhaps include them into the request to allow // changing them from the HTTP API? v6Conf.RASLAACOnly = s.conf.Conf6.RASLAACOnly v6Conf.RAAllowSLAAC = s.conf.Conf6.RAAllowSLAAC enabled = v6Conf.Enabled v6Conf.InterfaceName = conf.InterfaceName v6Conf.notify = s.onNotify srv6, err = v6Create(v6Conf) return srv6, enabled, err } // createServers returns DHCPv4 and DHCPv6 servers created from the provided // configuration conf. func (s *server) createServers(conf *dhcpServerConfigJSON) (srv4, srv6 DHCPServer, err error) { srv4, v4Enabled, err := s.handleDHCPSetConfigV4(conf) if err != nil { return nil, nil, fmt.Errorf("bad dhcpv4 configuration: %w", err) } srv6, v6Enabled, err := s.handleDHCPSetConfigV6(conf) if err != nil { return nil, nil, fmt.Errorf("bad dhcpv6 configuration: %w", err) } if conf.Enabled == aghalg.NBTrue && !v4Enabled && !v6Enabled { return nil, nil, fmt.Errorf("dhcpv4 or dhcpv6 configuration must be complete") } return srv4, srv6, nil } // handleDHCPSetConfig is the handler for the POST /control/dhcp/set_config // HTTP API. func (s *server) handleDHCPSetConfig(w http.ResponseWriter, r *http.Request) { conf := &dhcpServerConfigJSON{} conf.Enabled = aghalg.BoolToNullBool(s.conf.Enabled) conf.InterfaceName = s.conf.InterfaceName err := json.NewDecoder(r.Body).Decode(conf) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "failed to parse new dhcp config json: %s", err) return } srv4, srv6, err := s.createServers(conf) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } err = s.Stop() if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "stopping dhcp: %s", err) return } s.setConfFromJSON(conf, srv4, srv6) s.conf.ConfigModified() err = s.dbLoad() if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "loading leases db: %s", err) return } if s.conf.Enabled { var code int code, err = s.enableDHCP(conf.InterfaceName) if err != nil { aghhttp.Error(r, w, code, "enabling dhcp: %s", err) } } } // setConfFromJSON sets configuration parameters in s from the new configuration // decoded from JSON. func (s *server) setConfFromJSON(conf *dhcpServerConfigJSON, srv4, srv6 DHCPServer) { if conf.Enabled != aghalg.NBNull { s.conf.Enabled = conf.Enabled == aghalg.NBTrue } if conf.InterfaceName != "" { s.conf.InterfaceName = conf.InterfaceName } if srv4 != nil { s.srv4 = srv4 } if srv6 != nil { s.srv6 = srv6 } } type netInterfaceJSON struct { Name string `json:"name"` HardwareAddr string `json:"hardware_address"` Flags string `json:"flags"` GatewayIP netip.Addr `json:"gateway_ip"` Addrs4 []netip.Addr `json:"ipv4_addresses"` Addrs6 []netip.Addr `json:"ipv6_addresses"` } // handleDHCPInterfaces is the handler for the GET /control/dhcp/interfaces // HTTP API. func (s *server) handleDHCPInterfaces(w http.ResponseWriter, r *http.Request) { resp := map[string]*netInterfaceJSON{} ifaces, err := net.Interfaces() if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't get interfaces: %s", err) return } for _, iface := range ifaces { if iface.Flags&net.FlagLoopback != 0 { // It's a loopback, skip it. continue } if iface.Flags&net.FlagBroadcast == 0 { // This interface doesn't support broadcast, skip it. continue } jsonIface, iErr := newNetInterfaceJSON(iface) if iErr != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "%s", iErr) return } if jsonIface != nil { resp[iface.Name] = jsonIface } } aghhttp.WriteJSONResponseOK(w, r, resp) } // newNetInterfaceJSON creates a JSON object from a [net.Interface] iface. func newNetInterfaceJSON(iface net.Interface) (out *netInterfaceJSON, err error) { addrs, err := iface.Addrs() if err != nil { return nil, fmt.Errorf( "failed to get addresses for interface %s: %w", iface.Name, err, ) } out = &netInterfaceJSON{ Name: iface.Name, HardwareAddr: iface.HardwareAddr.String(), } if iface.Flags != 0 { out.Flags = iface.Flags.String() } // We don't want link-local addresses in JSON, so skip them. for _, addr := range addrs { ipNet, ok := addr.(*net.IPNet) if !ok { // Not an IPNet, should not happen. return nil, fmt.Errorf("got iface.Addrs() element %[1]s that is not"+ " net.IPNet, it is %[1]T", addr) } // Ignore link-local. // // TODO(e.burkov): Try to listen DHCP on LLA as well. if ipNet.IP.IsLinkLocalUnicast() { continue } vAddr, iErr := netutil.IPToAddrNoMapped(ipNet.IP) if iErr != nil { // Not an IPNet, should not happen. return nil, fmt.Errorf("failed to convert IP address %[1]s: %w", addr, iErr) } if vAddr.Is4() { out.Addrs4 = append(out.Addrs4, vAddr) } else { out.Addrs6 = append(out.Addrs6, vAddr) } } if len(out.Addrs4)+len(out.Addrs6) == 0 { return nil, nil } out.GatewayIP = aghnet.GatewayIP(iface.Name) return out, nil } // dhcpSearchOtherResult contains information about other DHCP server for // specific network interface. type dhcpSearchOtherResult struct { Found string `json:"found,omitempty"` Error string `json:"error,omitempty"` } // dhcpStaticIPStatus contains information about static IP address for DHCP // server. type dhcpStaticIPStatus struct { Static string `json:"static"` IP string `json:"ip,omitempty"` Error string `json:"error,omitempty"` } // dhcpSearchV4Result contains information about DHCPv4 server for specific // network interface. type dhcpSearchV4Result struct { OtherServer dhcpSearchOtherResult `json:"other_server"` StaticIP dhcpStaticIPStatus `json:"static_ip"` } // dhcpSearchV6Result contains information about DHCPv6 server for specific // network interface. type dhcpSearchV6Result struct { OtherServer dhcpSearchOtherResult `json:"other_server"` } // dhcpSearchResult is a response for /control/dhcp/find_active_dhcp endpoint. type dhcpSearchResult struct { V4 dhcpSearchV4Result `json:"v4"` V6 dhcpSearchV6Result `json:"v6"` } // findActiveServerReq is the JSON structure for the request to find active DHCP // servers. type findActiveServerReq struct { Interface string `json:"interface"` } // handleDHCPFindActiveServer performs the following tasks: // 1. searches for another DHCP server in the network; // 2. check if a static IP is configured for the network interface; // 3. responds with the results. func (s *server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) { if aghhttp.WriteTextPlainDeprecated(w, r) { return } req := &findActiveServerReq{} err := json.NewDecoder(r.Body).Decode(req) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err) return } ifaceName := req.Interface if ifaceName == "" { aghhttp.Error(r, w, http.StatusBadRequest, "empty interface name") return } result := &dhcpSearchResult{ V4: dhcpSearchV4Result{ OtherServer: dhcpSearchOtherResult{ Found: "no", }, StaticIP: dhcpStaticIPStatus{ Static: "yes", }, }, V6: dhcpSearchV6Result{ OtherServer: dhcpSearchOtherResult{ Found: "no", }, }, } if isStaticIP, serr := aghnet.IfaceHasStaticIP(ifaceName); serr != nil { result.V4.StaticIP.Static = "error" result.V4.StaticIP.Error = serr.Error() } else if !isStaticIP { result.V4.StaticIP.Static = "no" // TODO(e.burkov): The returned IP should only be of version 4. result.V4.StaticIP.IP = aghnet.GetSubnet(ifaceName).String() } setOtherDHCPResult(ifaceName, result) aghhttp.WriteJSONResponseOK(w, r, result) } // setOtherDHCPResult sets the results of the check for another DHCP server in // result. func setOtherDHCPResult(ifaceName string, result *dhcpSearchResult) { found4, found6, err4, err6 := aghnet.CheckOtherDHCP(ifaceName) if err4 != nil { result.V4.OtherServer.Found = "error" result.V4.OtherServer.Error = err4.Error() } else if found4 { result.V4.OtherServer.Found = "yes" } if err6 != nil { result.V6.OtherServer.Found = "error" result.V6.OtherServer.Error = err6.Error() } else if found6 { result.V6.OtherServer.Found = "yes" } } // parseLease parses a lease from r. If there is no error returns DHCPServer // and *Lease. r must be non-nil. func (s *server) parseLease(r io.Reader) (srv DHCPServer, lease *dhcpsvc.Lease, err error) { l := &leaseStatic{} err = json.NewDecoder(r).Decode(l) if err != nil { return nil, nil, fmt.Errorf("decoding json: %w", err) } if !l.IP.IsValid() { return nil, nil, errors.Error("invalid ip") } l.IP = l.IP.Unmap() lease, err = l.toLease() if err != nil { return nil, nil, fmt.Errorf("parsing: %w", err) } if lease.IP.Is4() { srv = s.srv4 } else { srv = s.srv6 } return srv, lease, nil } // handleDHCPAddStaticLease is the handler for the POST // /control/dhcp/add_static_lease HTTP API. func (s *server) handleDHCPAddStaticLease(w http.ResponseWriter, r *http.Request) { srv, lease, err := s.parseLease(r.Body) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } if err = srv.AddStaticLease(lease); err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) } } // handleDHCPRemoveStaticLease is the handler for the POST // /control/dhcp/remove_static_lease HTTP API. func (s *server) handleDHCPRemoveStaticLease(w http.ResponseWriter, r *http.Request) { srv, lease, err := s.parseLease(r.Body) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } if err = srv.RemoveStaticLease(lease); err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) } } // handleDHCPUpdateStaticLease is the handler for the POST // /control/dhcp/update_static_lease HTTP API. func (s *server) handleDHCPUpdateStaticLease(w http.ResponseWriter, r *http.Request) { srv, lease, err := s.parseLease(r.Body) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } if err = srv.UpdateStaticLease(lease); err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) } } func (s *server) handleReset(w http.ResponseWriter, r *http.Request) { err := s.Stop() if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "stopping dhcp: %s", err) return } err = os.Remove(s.conf.dbFilePath) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Error("dhcp: removing db: %s", err) } s.conf = &ServerConfig{ ConfigModified: s.conf.ConfigModified, HTTPRegister: s.conf.HTTPRegister, LocalDomainName: s.conf.LocalDomainName, DataDir: s.conf.DataDir, dbFilePath: s.conf.dbFilePath, } v4conf := &V4ServerConf{ LeaseDuration: DefaultDHCPLeaseTTL, ICMPTimeout: DefaultDHCPTimeoutICMP, notify: s.onNotify, } s.srv4, _ = v4Create(v4conf) v6conf := V6ServerConf{ LeaseDuration: DefaultDHCPLeaseTTL, notify: s.onNotify, } s.srv6, _ = v6Create(v6conf) s.conf.ConfigModified() } func (s *server) handleResetLeases(w http.ResponseWriter, r *http.Request) { err := s.resetLeases() if err != nil { msg := "resetting leases: %s" aghhttp.Error(r, w, http.StatusInternalServerError, msg, err) return } } func (s *server) registerHandlers() { if s.conf.HTTPRegister == nil { return } s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/status", s.handleDHCPStatus) s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/interfaces", s.handleDHCPInterfaces) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/set_config", s.handleDHCPSetConfig) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/find_active_dhcp", s.handleDHCPFindActiveServer) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/add_static_lease", s.handleDHCPAddStaticLease) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/remove_static_lease", s.handleDHCPRemoveStaticLease) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/update_static_lease", s.handleDHCPUpdateStaticLease) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset", s.handleReset) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset_leases", s.handleResetLeases) } ```
/content/code_sandbox/internal/dhcpd/http_unix.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
5,635
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "fmt" "net" "net/netip" "strings" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/stringutil" "github.com/AdguardTeam/golibs/testutil" "github.com/insomniacslk/dhcp/dhcpv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var ( DefaultRangeStart = netip.MustParseAddr("192.168.10.100") DefaultRangeEnd = netip.MustParseAddr("192.168.10.200") DefaultGatewayIP = netip.MustParseAddr("192.168.10.1") DefaultSelfIP = netip.MustParseAddr("192.168.10.2") DefaultSubnetMask = netip.MustParseAddr("255.255.255.0") ) // defaultV4ServerConf returns the default configuration for *v4Server to use in // tests. func defaultV4ServerConf() (conf *V4ServerConf) { return &V4ServerConf{ Enabled: true, RangeStart: DefaultRangeStart, RangeEnd: DefaultRangeEnd, GatewayIP: DefaultGatewayIP, SubnetMask: DefaultSubnetMask, notify: testNotify, dnsIPAddrs: []netip.Addr{DefaultSelfIP}, } } // defaultSrv prepares the default DHCPServer to use in tests. The underlying // type of s is *v4Server. func defaultSrv(t *testing.T) (s DHCPServer) { t.Helper() var err error s, err = v4Create(defaultV4ServerConf()) require.NoError(t, err) return s } func TestV4Server_leasing(t *testing.T) { const ( staticName = "static-client" anotherName = "another-client" ) staticIP := netip.MustParseAddr("192.168.10.10") anotherIP := DefaultRangeStart staticMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} anotherMAC := net.HardwareAddr{0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB} s := defaultSrv(t) t.Run("add_static", func(t *testing.T) { err := s.AddStaticLease(&dhcpsvc.Lease{ Hostname: staticName, HWAddr: staticMAC, IP: staticIP, IsStatic: true, }) require.NoError(t, err) t.Run("same_name", func(t *testing.T) { err = s.AddStaticLease(&dhcpsvc.Lease{ Hostname: staticName, HWAddr: anotherMAC, IP: anotherIP, IsStatic: true, }) assert.ErrorIs(t, err, ErrDupHostname) }) t.Run("same_mac", func(t *testing.T) { wantErrMsg := "dhcpv4: adding static lease: removing " + "dynamic leases for " + anotherIP.String() + " (" + staticMAC.String() + "): static lease already exists" err = s.AddStaticLease(&dhcpsvc.Lease{ Hostname: anotherName, HWAddr: staticMAC, IP: anotherIP, IsStatic: true, }) testutil.AssertErrorMsg(t, wantErrMsg, err) }) t.Run("same_ip", func(t *testing.T) { wantErrMsg := "dhcpv4: adding static lease: removing " + "dynamic leases for " + staticIP.String() + " (" + anotherMAC.String() + "): static lease already exists" err = s.AddStaticLease(&dhcpsvc.Lease{ Hostname: anotherName, HWAddr: anotherMAC, IP: staticIP, IsStatic: true, }) testutil.AssertErrorMsg(t, wantErrMsg, err) }) }) t.Run("add_dynamic", func(t *testing.T) { s4, ok := s.(*v4Server) require.True(t, ok) discoverAnOffer := func( t *testing.T, name string, netIP netip.Addr, mac net.HardwareAddr, ) (resp *dhcpv4.DHCPv4) { testutil.CleanupAndRequireSuccess(t, func() (err error) { return s.ResetLeases(s.GetLeases(LeasesStatic)) }) ip := net.IP(netIP.AsSlice()) req, err := dhcpv4.NewDiscovery( mac, dhcpv4.WithOption(dhcpv4.OptHostName(name)), dhcpv4.WithOption(dhcpv4.OptRequestedIPAddress(ip)), dhcpv4.WithOption(dhcpv4.OptClientIdentifier([]byte{1, 2, 3, 4, 5, 6, 8})), dhcpv4.WithGatewayIP(DefaultGatewayIP.AsSlice()), ) require.NoError(t, err) resp = &dhcpv4.DHCPv4{} res := s4.handle(req, resp) require.Positive(t, res) require.Equal(t, dhcpv4.MessageTypeOffer, resp.MessageType()) resp.ClientHWAddr = mac return resp } t.Run("same_name", func(t *testing.T) { resp := discoverAnOffer(t, staticName, anotherIP, anotherMAC) req, err := dhcpv4.NewRequestFromOffer(resp, dhcpv4.WithOption( dhcpv4.OptHostName(staticName), )) require.NoError(t, err) res := s4.handle(req, resp) require.Positive(t, res) var netIP netip.Addr netIP, ok = netip.AddrFromSlice(resp.YourIPAddr) require.True(t, ok) assert.Equal(t, aghnet.GenerateHostname(netIP), resp.HostName()) }) t.Run("same_mac", func(t *testing.T) { resp := discoverAnOffer(t, anotherName, anotherIP, staticMAC) req, err := dhcpv4.NewRequestFromOffer(resp, dhcpv4.WithOption( dhcpv4.OptHostName(anotherName), )) require.NoError(t, err) res := s4.handle(req, resp) require.Positive(t, res) fqdnOptData := resp.Options.Get(dhcpv4.OptionFQDN) require.Len(t, fqdnOptData, 3+len(staticName)) assert.Equal(t, []uint8(staticName), fqdnOptData[3:]) ip := net.IP(staticIP.AsSlice()) assert.Equal(t, ip, resp.YourIPAddr) }) t.Run("same_ip", func(t *testing.T) { resp := discoverAnOffer(t, anotherName, staticIP, anotherMAC) req, err := dhcpv4.NewRequestFromOffer(resp, dhcpv4.WithOption( dhcpv4.OptHostName(anotherName), )) require.NoError(t, err) res := s4.handle(req, resp) require.Positive(t, res) assert.NotEqual(t, staticIP, resp.YourIPAddr) }) }) } func TestV4Server_AddRemove_static(t *testing.T) { s := defaultSrv(t) ls := s.GetLeases(LeasesStatic) require.Empty(t, ls) testCases := []struct { lease *dhcpsvc.Lease name string wantErrMsg string }{{ lease: &dhcpsvc.Lease{ Hostname: "success.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), }, name: "success", wantErrMsg: "", }, { lease: &dhcpsvc.Lease{ Hostname: "probably-router.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: DefaultGatewayIP, }, name: "with_gateway_ip", wantErrMsg: "dhcpv4: adding static lease: " + `can't assign the gateway IP "192.168.10.1" to the lease`, }, { lease: &dhcpsvc.Lease{ Hostname: "ip6.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("ffff::1"), }, name: "ipv6", wantErrMsg: `dhcpv4: adding static lease: ` + `invalid IP "ffff::1": only IPv4 is supported`, }, { lease: &dhcpsvc.Lease{ Hostname: "bad-mac.local", HWAddr: net.HardwareAddr{0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), }, name: "bad_mac", wantErrMsg: `dhcpv4: adding static lease: bad mac address "aa:aa": ` + `bad mac address length 2, allowed: [6 8 20]`, }, { lease: &dhcpsvc.Lease{ Hostname: "bad-lbl-.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), }, name: "bad_hostname", wantErrMsg: `dhcpv4: adding static lease: validating hostname: ` + `bad hostname "bad-lbl-.local": ` + `bad hostname label "bad-lbl-": bad hostname label rune '-'`, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { err := s.AddStaticLease(tc.lease) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) if tc.wantErrMsg != "" { return } err = s.RemoveStaticLease(&dhcpsvc.Lease{ IP: tc.lease.IP, HWAddr: tc.lease.HWAddr, }) diffErrMsg := fmt.Sprintf("dhcpv4: lease for ip %s is different: %+v", tc.lease.IP, tc.lease) testutil.AssertErrorMsg(t, diffErrMsg, err) // Remove static lease. err = s.RemoveStaticLease(tc.lease) require.NoError(t, err) }) ls = s.GetLeases(LeasesStatic) require.Emptyf(t, ls, "after %s", tc.name) } } func TestV4_AddReplace(t *testing.T) { sIface := defaultSrv(t) s, ok := sIface.(*v4Server) require.True(t, ok) dynLeases := []dhcpsvc.Lease{{ Hostname: "dynamic-1.local", HWAddr: net.HardwareAddr{0x11, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), }, { Hostname: "dynamic-2.local", HWAddr: net.HardwareAddr{0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.151"), }} for i := range dynLeases { err := s.addLease(&dynLeases[i]) require.NoError(t, err) } stLeases := []*dhcpsvc.Lease{{ Hostname: "static-1.local", HWAddr: net.HardwareAddr{0x33, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), }, { Hostname: "static-2.local", HWAddr: net.HardwareAddr{0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.152"), }} for _, l := range stLeases { err := s.AddStaticLease(l) require.NoError(t, err) } ls := s.GetLeases(LeasesStatic) require.Len(t, ls, 2) for i, l := range ls { assert.Equal(t, stLeases[i].IP, l.IP) assert.Equal(t, stLeases[i].HWAddr, l.HWAddr) assert.True(t, l.IsStatic) } } func TestV4Server_handle_optionsPriority(t *testing.T) { defaultIP := netip.MustParseAddr("192.168.1.1") knownIP := net.IP{1, 2, 3, 4} // prepareSrv creates a *v4Server and sets the opt6IPs in the initial // configuration of the server as the value for DHCP option 6. prepareSrv := func(t *testing.T, opt6IPs []net.IP) (s *v4Server) { t.Helper() conf := defaultV4ServerConf() if len(opt6IPs) > 0 { b := &strings.Builder{} stringutil.WriteToBuilder(b, "6 ips ", opt6IPs[0].String()) for _, ip := range opt6IPs[1:] { stringutil.WriteToBuilder(b, ",", ip.String()) } conf.Options = []string{b.String()} } else { defer func() { s.implicitOpts.Update(dhcpv4.OptDNS(defaultIP.AsSlice())) }() } var err error s, err = v4Create(conf) require.NoError(t, err) s.conf.dnsIPAddrs = []netip.Addr{defaultIP} return s } // checkResp creates a discovery message with DHCP option 6 requested amd // asserts the response to contain wantIPs in this option. checkResp := func(t *testing.T, s *v4Server, wantIPs []net.IP) { t.Helper() mac := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} req, err := dhcpv4.NewDiscovery(mac, dhcpv4.WithRequestedOptions( dhcpv4.OptionDomainNameServer, )) require.NoError(t, err) var resp *dhcpv4.DHCPv4 resp, err = dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) res := s.handle(req, resp) require.Equal(t, 1, res) o := resp.GetOneOption(dhcpv4.OptionDomainNameServer) require.NotEmpty(t, o) wantData := []byte{} for _, ip := range wantIPs { wantData = append(wantData, ip...) } assert.Equal(t, o, wantData) } t.Run("default", func(t *testing.T) { s := prepareSrv(t, nil) checkResp(t, s, []net.IP{defaultIP.AsSlice()}) }) t.Run("explicitly_configured", func(t *testing.T) { s := prepareSrv(t, []net.IP{knownIP, knownIP}) checkResp(t, s, []net.IP{knownIP, knownIP}) }) } func TestV4Server_updateOptions(t *testing.T) { testIP := net.IP{1, 2, 3, 4} dontWant := func(c dhcpv4.OptionCode) (opt dhcpv4.Option) { return dhcpv4.OptGeneric(c, nil) } testCases := []struct { name string wantOpts dhcpv4.Options reqMods []dhcpv4.Modifier confOpts []string }{{ name: "requested_default", wantOpts: dhcpv4.OptionsFromList( dhcpv4.OptBroadcastAddress(netutil.IPv4bcast()), ), reqMods: []dhcpv4.Modifier{ dhcpv4.WithRequestedOptions(dhcpv4.OptionBroadcastAddress), }, confOpts: nil, }, { name: "requested_non-default", wantOpts: dhcpv4.OptionsFromList( dhcpv4.OptBroadcastAddress(testIP), ), reqMods: []dhcpv4.Modifier{ dhcpv4.WithRequestedOptions(dhcpv4.OptionBroadcastAddress), }, confOpts: []string{ fmt.Sprintf("%d ip %s", dhcpv4.OptionBroadcastAddress, testIP), }, }, { name: "non-requested_default", wantOpts: dhcpv4.OptionsFromList( dontWant(dhcpv4.OptionBroadcastAddress), ), reqMods: nil, confOpts: nil, }, { name: "non-requested_non-default", wantOpts: dhcpv4.OptionsFromList( dhcpv4.OptBroadcastAddress(testIP), ), reqMods: nil, confOpts: []string{ fmt.Sprintf("%d ip %s", dhcpv4.OptionBroadcastAddress, testIP), }, }, { name: "requested_deleted", wantOpts: dhcpv4.OptionsFromList( dontWant(dhcpv4.OptionBroadcastAddress), ), reqMods: []dhcpv4.Modifier{ dhcpv4.WithRequestedOptions(dhcpv4.OptionBroadcastAddress), }, confOpts: []string{ fmt.Sprintf("%d del", dhcpv4.OptionBroadcastAddress), }, }, { name: "requested_non-default_deleted", wantOpts: dhcpv4.OptionsFromList( dontWant(dhcpv4.OptionBroadcastAddress), ), reqMods: []dhcpv4.Modifier{ dhcpv4.WithRequestedOptions(dhcpv4.OptionBroadcastAddress), }, confOpts: []string{ fmt.Sprintf("%d ip %s", dhcpv4.OptionBroadcastAddress, testIP), fmt.Sprintf("%d del", dhcpv4.OptionBroadcastAddress), }, }} for _, tc := range testCases { req, err := dhcpv4.New(tc.reqMods...) require.NoError(t, err) resp, err := dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) conf := defaultV4ServerConf() conf.Options = tc.confOpts s, err := v4Create(conf) require.NoError(t, err) require.IsType(t, (*v4Server)(nil), s) t.Run(tc.name, func(t *testing.T) { s.updateOptions(req, resp) for c, v := range tc.wantOpts { if v == nil { assert.NotContains(t, resp.Options, c) continue } assert.Equal(t, v, resp.Options.Get(dhcpv4.GenericOptionCode(c))) } }) } } func TestV4StaticLease_Get(t *testing.T) { sIface := defaultSrv(t) s, ok := sIface.(*v4Server) require.True(t, ok) dnsAddr := netip.MustParseAddr("192.168.10.1") s.conf.dnsIPAddrs = []netip.Addr{dnsAddr} s.implicitOpts.Update(dhcpv4.OptDNS(dnsAddr.AsSlice())) l := &dhcpsvc.Lease{ Hostname: "static-1.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.150"), } err := s.AddStaticLease(l) require.NoError(t, err) var req, resp *dhcpv4.DHCPv4 mac := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} t.Run("discover", func(t *testing.T) { req, err = dhcpv4.NewDiscovery(mac, dhcpv4.WithRequestedOptions( dhcpv4.OptionDomainNameServer, )) require.NoError(t, err) resp, err = dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) assert.Equal(t, 1, s.handle(req, resp)) }) // Don't continue if we got any errors in the previous subtest. require.NoError(t, err) t.Run("offer", func(t *testing.T) { assert.Equal(t, dhcpv4.MessageTypeOffer, resp.MessageType()) assert.Equal(t, mac, resp.ClientHWAddr) ip := net.IP(l.IP.AsSlice()) assert.True(t, ip.Equal(resp.YourIPAddr)) assert.True(t, resp.Router()[0].Equal(s.conf.GatewayIP.AsSlice())) assert.True(t, resp.ServerIdentifier().Equal(s.conf.GatewayIP.AsSlice())) ones, _ := resp.SubnetMask().Size() assert.Equal(t, s.conf.subnet.Bits(), ones) assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds()) }) t.Run("request", func(t *testing.T) { req, err = dhcpv4.NewRequestFromOffer(resp) require.NoError(t, err) resp, err = dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) assert.Equal(t, 1, s.handle(req, resp)) }) require.NoError(t, err) t.Run("ack", func(t *testing.T) { assert.Equal(t, dhcpv4.MessageTypeAck, resp.MessageType()) assert.Equal(t, mac, resp.ClientHWAddr) ip := net.IP(l.IP.AsSlice()) assert.True(t, ip.Equal(resp.YourIPAddr)) assert.True(t, resp.Router()[0].Equal(s.conf.GatewayIP.AsSlice())) assert.True(t, resp.ServerIdentifier().Equal(s.conf.GatewayIP.AsSlice())) ones, _ := resp.SubnetMask().Size() assert.Equal(t, s.conf.subnet.Bits(), ones) assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds()) }) dnsAddrs := resp.DNS() require.Len(t, dnsAddrs, 1) assert.True(t, dnsAddrs[0].Equal(s.conf.GatewayIP.AsSlice())) t.Run("check_lease", func(t *testing.T) { ls := s.GetLeases(LeasesStatic) require.Len(t, ls, 1) assert.Equal(t, l.IP, ls[0].IP) assert.Equal(t, mac, ls[0].HWAddr) }) } func TestV4DynamicLease_Get(t *testing.T) { conf := defaultV4ServerConf() conf.Options = []string{ "81 hex 303132", "82 ip 1.2.3.4", } s, err := v4Create(conf) require.NoError(t, err) s.conf.dnsIPAddrs = []netip.Addr{netip.MustParseAddr("192.168.10.1")} s.implicitOpts.Update(dhcpv4.OptDNS(s.conf.dnsIPAddrs[0].AsSlice())) var req, resp *dhcpv4.DHCPv4 mac := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} t.Run("discover", func(t *testing.T) { req, err = dhcpv4.NewDiscovery(mac, dhcpv4.WithRequestedOptions( dhcpv4.OptionFQDN, dhcpv4.OptionRelayAgentInformation, )) require.NoError(t, err) resp, err = dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) assert.Equal(t, 1, s.handle(req, resp)) }) // Don't continue if we got any errors in the previous subtest. require.NoError(t, err) t.Run("offer", func(t *testing.T) { assert.Equal(t, dhcpv4.MessageTypeOffer, resp.MessageType()) assert.Equal(t, mac, resp.ClientHWAddr) assert.True(t, resp.YourIPAddr.Equal(s.conf.RangeStart.AsSlice())) assert.True(t, resp.ServerIdentifier().Equal(s.conf.GatewayIP.AsSlice())) router := resp.Router() require.Len(t, router, 1) assert.True(t, router[0].Equal(s.conf.GatewayIP.AsSlice())) ones, _ := resp.SubnetMask().Size() assert.Equal(t, s.conf.subnet.Bits(), ones) assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds()) assert.Equal(t, []byte("012"), resp.Options.Get(dhcpv4.OptionFQDN)) rai := resp.RelayAgentInfo() require.NotNil(t, rai) assert.Equal(t, net.IP{1, 2, 3, 4}, net.IP(rai.ToBytes())) }) t.Run("request", func(t *testing.T) { req, err = dhcpv4.NewRequestFromOffer(resp) require.NoError(t, err) resp, err = dhcpv4.NewReplyFromRequest(req) require.NoError(t, err) assert.Equal(t, 1, s.handle(req, resp)) }) require.NoError(t, err) t.Run("ack", func(t *testing.T) { assert.Equal(t, dhcpv4.MessageTypeAck, resp.MessageType()) assert.Equal(t, mac, resp.ClientHWAddr) assert.True(t, resp.YourIPAddr.Equal(s.conf.RangeStart.AsSlice())) router := resp.Router() require.Len(t, router, 1) assert.True(t, router[0].Equal(s.conf.GatewayIP.AsSlice())) assert.True(t, resp.ServerIdentifier().Equal(s.conf.GatewayIP.AsSlice())) ones, _ := resp.SubnetMask().Size() assert.Equal(t, s.conf.subnet.Bits(), ones) assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds()) }) dnsAddrs := resp.DNS() require.Len(t, dnsAddrs, 1) assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) // check lease t.Run("check_lease", func(t *testing.T) { ls := s.GetLeases(LeasesDynamic) require.Len(t, ls, 1) ip := netip.MustParseAddr("192.168.10.100") assert.Equal(t, ip, ls[0].IP) assert.Equal(t, mac, ls[0].HWAddr) }) } func TestNormalizeHostname(t *testing.T) { testCases := []struct { name string hostname string wantErrMsg string want string }{{ name: "success", hostname: "example.com", wantErrMsg: "", want: "example.com", }, { name: "success_empty", hostname: "", wantErrMsg: "", want: "", }, { name: "success_spaces", hostname: "my device 01", wantErrMsg: "", want: "my-device-01", }, { name: "success_underscores", hostname: "my_device_01", wantErrMsg: "", want: "my-device-01", }, { name: "error_part", hostname: "device !!!", wantErrMsg: "", want: "device", }, { name: "error_part_spaces", hostname: "device ! ! !", wantErrMsg: "", want: "device", }, { name: "error", hostname: "!!!", wantErrMsg: `normalizing "!!!": no valid parts`, want: "", }, { name: "error_spaces", hostname: "! ! !", wantErrMsg: `normalizing "! ! !": no valid parts`, want: "", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got, err := normalizeHostname(tc.hostname) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) assert.Equal(t, tc.want, got) }) } } // fakePacketConn is a mock implementation of net.PacketConn to simplify // testing. type fakePacketConn struct { // writeTo is used to substitute net.PacketConn's WriteTo method. writeTo func(p []byte, addr net.Addr) (n int, err error) // net.PacketConn is embedded here simply to make *fakePacketConn a // net.PacketConn without actually implementing all methods. net.PacketConn } // WriteTo implements net.PacketConn interface for *fakePacketConn. func (fc *fakePacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { return fc.writeTo(p, addr) } func TestV4Server_FindMACbyIP(t *testing.T) { const ( staticName = "static-client" anotherName = "another-client" ) staticIP := netip.MustParseAddr("192.168.10.10") staticMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} anotherIP := netip.MustParseAddr("192.168.100.100") anotherMAC := net.HardwareAddr{0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB} s := &v4Server{ leases: []*dhcpsvc.Lease{{ Hostname: staticName, HWAddr: staticMAC, IP: staticIP, IsStatic: true, }, { Expiry: time.Unix(10, 0), Hostname: anotherName, HWAddr: anotherMAC, IP: anotherIP, }}, } s.ipIndex = map[netip.Addr]*dhcpsvc.Lease{ staticIP: s.leases[0], anotherIP: s.leases[1], } s.hostsIndex = map[string]*dhcpsvc.Lease{ staticName: s.leases[0], anotherName: s.leases[1], } testCases := []struct { want net.HardwareAddr ip netip.Addr name string }{{ name: "basic", ip: staticIP, want: staticMAC, }, { name: "not_found", ip: netip.MustParseAddr("1.2.3.4"), want: nil, }, { name: "expired", ip: anotherIP, want: nil, }, { name: "v6", ip: netip.MustParseAddr("ffff::1"), want: nil, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { mac := s.FindMACbyIP(tc.ip) require.Equal(t, tc.want, mac) }) } } func TestV4Server_handleDecline(t *testing.T) { const ( dynamicName = "dynamic-client" anotherName = "another-client" ) dynamicIP := netip.MustParseAddr("192.168.10.200") dynamicMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} s := defaultSrv(t) s4, ok := s.(*v4Server) require.True(t, ok) s4.leases = []*dhcpsvc.Lease{{ Hostname: dynamicName, HWAddr: dynamicMAC, IP: dynamicIP, }} req, err := dhcpv4.New( dhcpv4.WithOption(dhcpv4.OptRequestedIPAddress(net.IP(dynamicIP.AsSlice()))), ) require.NoError(t, err) req.ClientIPAddr = net.IP(dynamicIP.AsSlice()) req.ClientHWAddr = dynamicMAC resp := &dhcpv4.DHCPv4{} err = s4.handleDecline(req, resp) require.NoError(t, err) wantResp := &dhcpv4.DHCPv4{ YourIPAddr: net.IP(s4.conf.RangeStart.AsSlice()), Options: dhcpv4.OptionsFromList( dhcpv4.OptMessageType(dhcpv4.MessageTypeAck), ), } require.Equal(t, wantResp, resp) } func TestV4Server_handleRelease(t *testing.T) { const ( dynamicName = "dynamic-client" anotherName = "another-client" ) dynamicIP := netip.MustParseAddr("192.168.10.200") dynamicMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} s := defaultSrv(t) s4, ok := s.(*v4Server) require.True(t, ok) s4.leases = []*dhcpsvc.Lease{{ Hostname: dynamicName, HWAddr: dynamicMAC, IP: dynamicIP, }} req, err := dhcpv4.New( dhcpv4.WithOption(dhcpv4.OptRequestedIPAddress(net.IP(dynamicIP.AsSlice()))), ) require.NoError(t, err) req.ClientIPAddr = net.IP(dynamicIP.AsSlice()) req.ClientHWAddr = dynamicMAC resp := &dhcpv4.DHCPv4{} err = s4.handleRelease(req, resp) require.NoError(t, err) wantResp := &dhcpv4.DHCPv4{ Options: dhcpv4.OptionsFromList( dhcpv4.OptMessageType(dhcpv4.MessageTypeAck), ), } require.Equal(t, wantResp, resp) } ```
/content/code_sandbox/internal/dhcpd/v4_unix_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
7,713
```go //go:build windows package dhcpd import ( "net/http" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghos" ) // jsonError is a generic JSON error response. // // TODO(a.garipov): Merge together with the implementations in .../home and // other packages after refactoring the web handler registering. type jsonError struct { // Message is the error message, an opaque string. Message string `json:"message"` } // notImplemented is a handler that replies to any request with an HTTP 501 Not // Implemented status and a JSON error with the provided message msg. // // TODO(a.garipov): Either take the logger from the server after we've // refactored logging or make this not a method of *Server. func (s *server) notImplemented(w http.ResponseWriter, r *http.Request) { aghhttp.WriteJSONResponse(w, r, http.StatusNotImplemented, &jsonError{ Message: aghos.Unsupported("dhcp").Error(), }) } // registerHandlers sets the handlers for DHCP HTTP API that always respond with // an HTTP 501, since DHCP server doesn't work on Windows yet. // // TODO(a.garipov): This needs refactoring. We shouldn't even try and // initialize a DHCP server on Windows, but there are currently too many // interconnected parts--such as HTTP handlers and frontend--to make that work // properly. func (s *server) registerHandlers() { s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/status", s.notImplemented) s.conf.HTTPRegister(http.MethodGet, "/control/dhcp/interfaces", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/set_config", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/find_active_dhcp", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/add_static_lease", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/remove_static_lease", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/update_static_lease", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset", s.notImplemented) s.conf.HTTPRegister(http.MethodPost, "/control/dhcp/reset_leases", s.notImplemented) } ```
/content/code_sandbox/internal/dhcpd/http_windows.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
509
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "net" "net/netip" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/insomniacslk/dhcp/dhcpv6" "github.com/insomniacslk/dhcp/iana" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func notify6(flags uint32) { } func TestV6_AddRemove_static(t *testing.T) { s, err := v6Create(V6ServerConf{ Enabled: true, RangeStart: net.ParseIP("2001::1"), notify: notify6, }) require.NoError(t, err) require.Empty(t, s.GetLeases(LeasesStatic)) // Add static lease. l := &dhcpsvc.Lease{ IP: netip.MustParseAddr("2001::1"), HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, } err = s.AddStaticLease(l) require.NoError(t, err) // Try to add the same static lease. err = s.AddStaticLease(l) require.Error(t, err) ls := s.GetLeases(LeasesStatic) require.Len(t, ls, 1) assert.Equal(t, l.IP, ls[0].IP) assert.Equal(t, l.HWAddr, ls[0].HWAddr) assert.True(t, ls[0].IsStatic) // Try to remove non-existent static lease. err = s.RemoveStaticLease(&dhcpsvc.Lease{ IP: netip.MustParseAddr("2001::2"), HWAddr: l.HWAddr, }) require.Error(t, err) // Remove static lease. err = s.RemoveStaticLease(l) require.NoError(t, err) assert.Empty(t, s.GetLeases(LeasesStatic)) } func TestV6_AddReplace(t *testing.T) { sIface, err := v6Create(V6ServerConf{ Enabled: true, RangeStart: net.ParseIP("2001::1"), notify: notify6, }) require.NoError(t, err) s, ok := sIface.(*v6Server) require.True(t, ok) // Add dynamic leases. dynLeases := []*dhcpsvc.Lease{{ IP: netip.MustParseAddr("2001::1"), HWAddr: net.HardwareAddr{0x11, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, }, { IP: netip.MustParseAddr("2001::2"), HWAddr: net.HardwareAddr{0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, }} for _, l := range dynLeases { s.addLease(l) } stLeases := []*dhcpsvc.Lease{{ IP: netip.MustParseAddr("2001::1"), HWAddr: net.HardwareAddr{0x33, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, }, { IP: netip.MustParseAddr("2001::3"), HWAddr: net.HardwareAddr{0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, }} for _, l := range stLeases { err = s.AddStaticLease(l) require.NoError(t, err) } ls := s.GetLeases(LeasesStatic) require.Len(t, ls, 2) for i, l := range ls { assert.Equal(t, stLeases[i].IP, l.IP) assert.Equal(t, stLeases[i].HWAddr, l.HWAddr) assert.True(t, l.IsStatic) } } func TestV6GetLease(t *testing.T) { var err error sIface, err := v6Create(V6ServerConf{ Enabled: true, RangeStart: net.ParseIP("2001::1"), notify: notify6, }) require.NoError(t, err) s, ok := sIface.(*v6Server) require.True(t, ok) dnsAddr := net.ParseIP("2000::1") s.conf.dnsIPAddrs = []net.IP{dnsAddr} s.sid = &dhcpv6.DUIDLL{ HWType: iana.HWTypeEthernet, LinkLayerAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, } l := &dhcpsvc.Lease{ IP: netip.MustParseAddr("2001::1"), HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, } err = s.AddStaticLease(l) require.NoError(t, err) var req, resp, msg *dhcpv6.Message mac := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} t.Run("solicit", func(t *testing.T) { req, err = dhcpv6.NewSolicit(mac) require.NoError(t, err) msg, err = req.GetInnerMessage() require.NoError(t, err) resp, err = dhcpv6.NewAdvertiseFromSolicit(msg) require.NoError(t, err) assert.True(t, s.process(msg, req, resp)) }) require.NoError(t, err) resp.AddOption(dhcpv6.OptServerID(s.sid)) var oia *dhcpv6.OptIANA var oiaAddr *dhcpv6.OptIAAddress t.Run("advertise", func(t *testing.T) { require.Equal(t, dhcpv6.MessageTypeAdvertise, resp.Type()) oia = resp.Options.OneIANA() oiaAddr = oia.Options.OneAddress() ip := net.IP(l.IP.AsSlice()) assert.Equal(t, ip, oiaAddr.IPv6Addr) assert.Equal(t, s.conf.leaseTime.Seconds(), oiaAddr.ValidLifetime.Seconds()) }) t.Run("request", func(t *testing.T) { req, err = dhcpv6.NewRequestFromAdvertise(resp) require.NoError(t, err) msg, err = req.GetInnerMessage() require.NoError(t, err) resp, err = dhcpv6.NewReplyFromMessage(msg) require.NoError(t, err) assert.True(t, s.process(msg, req, resp)) }) require.NoError(t, err) t.Run("reply", func(t *testing.T) { require.Equal(t, dhcpv6.MessageTypeReply, resp.Type()) oia = resp.Options.OneIANA() oiaAddr = oia.Options.OneAddress() ip := net.IP(l.IP.AsSlice()) assert.Equal(t, ip, oiaAddr.IPv6Addr) assert.Equal(t, s.conf.leaseTime.Seconds(), oiaAddr.ValidLifetime.Seconds()) }) dnsAddrs := resp.Options.DNS() require.Len(t, dnsAddrs, 1) assert.Equal(t, dnsAddr, dnsAddrs[0]) t.Run("lease", func(t *testing.T) { ls := s.GetLeases(LeasesStatic) require.Len(t, ls, 1) assert.Equal(t, l.IP, ls[0].IP) assert.Equal(t, l.HWAddr, ls[0].HWAddr) }) } func TestV6GetDynamicLease(t *testing.T) { sIface, err := v6Create(V6ServerConf{ Enabled: true, RangeStart: net.ParseIP("2001::2"), notify: notify6, }) require.NoError(t, err) s, ok := sIface.(*v6Server) require.True(t, ok) dnsAddr := net.ParseIP("2000::1") s.conf.dnsIPAddrs = []net.IP{dnsAddr} s.sid = &dhcpv6.DUIDLL{ HWType: iana.HWTypeEthernet, LinkLayerAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, } var req, resp, msg *dhcpv6.Message mac := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} t.Run("solicit", func(t *testing.T) { req, err = dhcpv6.NewSolicit(mac) require.NoError(t, err) msg, err = req.GetInnerMessage() require.NoError(t, err) resp, err = dhcpv6.NewAdvertiseFromSolicit(msg) require.NoError(t, err) assert.True(t, s.process(msg, req, resp)) }) require.NoError(t, err) resp.AddOption(dhcpv6.OptServerID(s.sid)) var oia *dhcpv6.OptIANA var oiaAddr *dhcpv6.OptIAAddress t.Run("advertise", func(t *testing.T) { require.Equal(t, dhcpv6.MessageTypeAdvertise, resp.Type()) oia = resp.Options.OneIANA() oiaAddr = oia.Options.OneAddress() assert.Equal(t, "2001::2", oiaAddr.IPv6Addr.String()) }) t.Run("request", func(t *testing.T) { req, err = dhcpv6.NewRequestFromAdvertise(resp) require.NoError(t, err) msg, err = req.GetInnerMessage() require.NoError(t, err) resp, err = dhcpv6.NewReplyFromMessage(msg) require.NoError(t, err) assert.True(t, s.process(msg, req, resp)) }) require.NoError(t, err) t.Run("reply", func(t *testing.T) { require.Equal(t, dhcpv6.MessageTypeReply, resp.Type()) oia = resp.Options.OneIANA() oiaAddr = oia.Options.OneAddress() assert.Equal(t, "2001::2", oiaAddr.IPv6Addr.String()) }) dnsAddrs := resp.Options.DNS() require.Len(t, dnsAddrs, 1) assert.Equal(t, dnsAddr, dnsAddrs[0]) t.Run("lease", func(t *testing.T) { ls := s.GetLeases(LeasesDynamic) require.Len(t, ls, 1) assert.Equal(t, "2001::2", ls[0].IP.String()) assert.Equal(t, mac, ls[0].HWAddr) }) } func TestIP6InRange(t *testing.T) { start := net.ParseIP("2001::2") testCases := []struct { ip net.IP want bool }{{ ip: net.ParseIP("2001::1"), want: false, }, { ip: net.ParseIP("2002::2"), want: false, }, { ip: start, want: true, }, { ip: net.ParseIP("2001::3"), want: true, }} for _, tc := range testCases { t.Run(tc.ip.String(), func(t *testing.T) { assert.Equal(t, tc.want, ip6InRange(start, tc.ip)) }) } } func TestV6_FindMACbyIP(t *testing.T) { const ( staticName = "static-client" anotherName = "another-client" ) staticIP := netip.MustParseAddr("2001::1") staticMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA} anotherIP := netip.MustParseAddr("2001::100") anotherMAC := net.HardwareAddr{0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB} s := &v6Server{ leases: []*dhcpsvc.Lease{{ Hostname: staticName, HWAddr: staticMAC, IP: staticIP, IsStatic: true, }, { Expiry: time.Unix(10, 0), Hostname: anotherName, HWAddr: anotherMAC, IP: anotherIP, }}, } s.leases = []*dhcpsvc.Lease{{ Hostname: staticName, HWAddr: staticMAC, IP: staticIP, IsStatic: true, }, { Expiry: time.Unix(10, 0), Hostname: anotherName, HWAddr: anotherMAC, IP: anotherIP, }} testCases := []struct { want net.HardwareAddr ip netip.Addr name string }{{ name: "basic", ip: staticIP, want: staticMAC, }, { name: "not_found", ip: netip.MustParseAddr("ffff::1"), want: nil, }, { name: "expired", ip: anotherIP, want: nil, }, { name: "v4", ip: netip.MustParseAddr("1.2.3.4"), want: nil, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { mac := s.FindMACbyIP(tc.ip) require.Equal(t, tc.want, mac) }) } } ```
/content/code_sandbox/internal/dhcpd/v6_unix_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,040
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "net" "net/netip" "path/filepath" "slices" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } func testNotify(flags uint32) { } // Leases database store/load. func TestDB(t *testing.T) { var err error s := server{ conf: &ServerConfig{ dbFilePath: filepath.Join(t.TempDir(), dataFilename), }, } s.srv4, err = v4Create(&V4ServerConf{ Enabled: true, RangeStart: netip.MustParseAddr("192.168.10.100"), RangeEnd: netip.MustParseAddr("192.168.10.200"), GatewayIP: netip.MustParseAddr("192.168.10.1"), SubnetMask: netip.MustParseAddr("255.255.255.0"), notify: testNotify, }) require.NoError(t, err) s.srv6, err = v6Create(V6ServerConf{}) require.NoError(t, err) leases := []*dhcpsvc.Lease{{ Expiry: time.Now().Add(time.Hour), Hostname: "static-1.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, IP: netip.MustParseAddr("192.168.10.100"), }, { Hostname: "static-2.local", HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xBB}, IP: netip.MustParseAddr("192.168.10.101"), }} srv4, ok := s.srv4.(*v4Server) require.True(t, ok) err = srv4.addLease(leases[0]) require.NoError(t, err) err = s.srv4.AddStaticLease(leases[1]) require.NoError(t, err) err = s.dbStore() require.NoError(t, err) err = s.srv4.ResetLeases(nil) require.NoError(t, err) err = s.dbLoad() require.NoError(t, err) ll := s.srv4.GetLeases(LeasesAll) require.Len(t, ll, len(leases)) assert.Equal(t, leases[0].HWAddr, ll[0].HWAddr) assert.Equal(t, leases[0].IP, ll[0].IP) assert.Equal(t, leases[0].Expiry.Unix(), ll[0].Expiry.Unix()) assert.Equal(t, leases[1].HWAddr, ll[1].HWAddr) assert.Equal(t, leases[1].IP, ll[1].IP) assert.True(t, ll[1].IsStatic) } func TestV4Server_badRange(t *testing.T) { testCases := []struct { name string gatewayIP netip.Addr subnetMask netip.Addr wantErrMsg string }{{ name: "gateway_in_range", gatewayIP: netip.MustParseAddr("192.168.10.120"), subnetMask: netip.MustParseAddr("255.255.255.0"), wantErrMsg: "dhcpv4: gateway ip 192.168.10.120 in the ip range: " + "192.168.10.20-192.168.10.200", }, { name: "outside_range_start", gatewayIP: netip.MustParseAddr("192.168.10.1"), subnetMask: netip.MustParseAddr("255.255.255.240"), wantErrMsg: "dhcpv4: range start 192.168.10.20 is outside network " + "192.168.10.1/28", }, { name: "outside_range_end", gatewayIP: netip.MustParseAddr("192.168.10.1"), subnetMask: netip.MustParseAddr("255.255.255.224"), wantErrMsg: "dhcpv4: range end 192.168.10.200 is outside network " + "192.168.10.1/27", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { conf := V4ServerConf{ Enabled: true, RangeStart: netip.MustParseAddr("192.168.10.20"), RangeEnd: netip.MustParseAddr("192.168.10.200"), GatewayIP: tc.gatewayIP, SubnetMask: tc.subnetMask, notify: testNotify, } _, err := v4Create(&conf) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) }) } } // cloneUDPAddr returns a deep copy of a. func cloneUDPAddr(a *net.UDPAddr) (clone *net.UDPAddr) { return &net.UDPAddr{ IP: slices.Clone(a.IP), Port: a.Port, Zone: a.Zone, } } ```
/content/code_sandbox/internal/dhcpd/dhcpd_unix_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,209
```go package dhcpd import ( "fmt" "net" "net/netip" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/errors" ) // ServerConfig is the configuration for the DHCP server. The order of YAML // fields is important, since the YAML configuration file follows it. type ServerConfig struct { // Called when the configuration is changed by HTTP request ConfigModified func() `yaml:"-"` // Register an HTTP handler HTTPRegister aghhttp.RegisterFunc `yaml:"-"` Enabled bool `yaml:"enabled"` InterfaceName string `yaml:"interface_name"` // LocalDomainName is the domain name used for DHCP hosts. For example, a // DHCP client with the hostname "myhost" can be addressed as "myhost.lan" // when LocalDomainName is "lan". // // TODO(e.burkov): Probably, remove this field. See the TODO on // [Interface.Enabled]. LocalDomainName string `yaml:"local_domain_name"` Conf4 V4ServerConf `yaml:"dhcpv4"` Conf6 V6ServerConf `yaml:"dhcpv6"` // WorkDir is used to store DHCP leases. // // Deprecated: Remove it when migration of DHCP leases will not be needed. WorkDir string `yaml:"-"` // DataDir is used to store DHCP leases. DataDir string `yaml:"-"` // dbFilePath is the path to the file with stored DHCP leases. dbFilePath string `yaml:"-"` } // DHCPServer - DHCP server interface type DHCPServer interface { // ResetLeases resets leases. ResetLeases(leases []*dhcpsvc.Lease) (err error) // GetLeases returns deep clones of the current leases. GetLeases(flags GetLeasesFlags) (leases []*dhcpsvc.Lease) // AddStaticLease - add a static lease AddStaticLease(l *dhcpsvc.Lease) (err error) // RemoveStaticLease - remove a static lease RemoveStaticLease(l *dhcpsvc.Lease) (err error) // UpdateStaticLease updates IP, hostname of the lease. UpdateStaticLease(l *dhcpsvc.Lease) (err error) // FindMACbyIP returns a MAC address by the IP address of its lease, if // there is one. FindMACbyIP(ip netip.Addr) (mac net.HardwareAddr) // HostByIP returns a hostname by the IP address of its lease, if there is // one. HostByIP(ip netip.Addr) (host string) // IPByHost returns an IP address by the hostname of its lease, if there is // one. IPByHost(host string) (ip netip.Addr) // WriteDiskConfig4 - copy disk configuration WriteDiskConfig4(c *V4ServerConf) // WriteDiskConfig6 - copy disk configuration WriteDiskConfig6(c *V6ServerConf) // Start - start server Start() (err error) // Stop - stop server Stop() (err error) getLeasesRef() []*dhcpsvc.Lease } // V4ServerConf - server configuration type V4ServerConf struct { Enabled bool `yaml:"-" json:"-"` InterfaceName string `yaml:"-" json:"-"` GatewayIP netip.Addr `yaml:"gateway_ip" json:"gateway_ip"` SubnetMask netip.Addr `yaml:"subnet_mask" json:"subnet_mask"` // broadcastIP is the broadcasting address pre-calculated from the // configured gateway IP and subnet mask. broadcastIP netip.Addr // The first & the last IP address for dynamic leases // Bytes [0..2] of the last allowed IP address must match the first IP RangeStart netip.Addr `yaml:"range_start" json:"range_start"` RangeEnd netip.Addr `yaml:"range_end" json:"range_end"` LeaseDuration uint32 `yaml:"lease_duration" json:"lease_duration"` // in seconds // IP conflict detector: time (ms) to wait for ICMP reply // 0: disable ICMPTimeout uint32 `yaml:"icmp_timeout_msec" json:"-"` // Custom Options. // // Option with arbitrary hexadecimal data: // DEC_CODE hex HEX_DATA // where DEC_CODE is a decimal DHCPv4 option code in range [1..255] // // Option with IP data (only 1 IP is supported): // DEC_CODE ip IP_ADDR Options []string `yaml:"options" json:"-"` ipRange *ipRange leaseTime time.Duration // the time during which a dynamic lease is considered valid dnsIPAddrs []netip.Addr // IPv4 addresses to return to DHCP clients as DNS server addresses // subnet contains the DHCP server's subnet. The IP is the IP of the // gateway. subnet netip.Prefix // notify is a way to signal to other components that leases have been // changed. notify must be called outside of locked sections, since the // clients might want to get the new data. // // TODO(a.garipov): This is utter madness and must be refactored. It just // begs for deadlock bugs and other nastiness. notify func(uint32) } // errNilConfig is an error returned by validation method if the config is nil. const errNilConfig errors.Error = "nil config" // ensureV4 returns an unmapped version of ip. An error is returned if the // passed ip is not an IPv4. func ensureV4(ip netip.Addr, kind string) (ip4 netip.Addr, err error) { ip4 = ip.Unmap() if !ip4.IsValid() || !ip4.Is4() { return netip.Addr{}, fmt.Errorf("%v is not an IPv4 %s", ip, kind) } return ip4, nil } // Validate returns an error if c is not a valid configuration. // // TODO(e.burkov): Don't set the config fields when the server itself will stop // containing the config. func (c *V4ServerConf) Validate() (err error) { defer func() { err = errors.Annotate(err, "dhcpv4: %w") }() if c == nil { return errNilConfig } gatewayIP, err := ensureV4(c.GatewayIP, "address") if err != nil { // Don't wrap the error since it's informative enough as is and there is // an annotation deferred already. return err } subnetMask, err := ensureV4(c.SubnetMask, "subnet mask") if err != nil { // Don't wrap the error since it's informative enough as is and there is // an annotation deferred already. return err } maskLen, _ := net.IPMask(subnetMask.AsSlice()).Size() c.subnet = netip.PrefixFrom(gatewayIP, maskLen) c.broadcastIP = aghnet.BroadcastFromPref(c.subnet) rangeStart, err := ensureV4(c.RangeStart, "address") if err != nil { // Don't wrap the error since it's informative enough as is and there is // an annotation deferred already. return err } rangeEnd, err := ensureV4(c.RangeEnd, "address") if err != nil { // Don't wrap the error since it's informative enough as is and there is // an annotation deferred already. return err } c.ipRange, err = newIPRange(rangeStart.AsSlice(), rangeEnd.AsSlice()) if err != nil { // Don't wrap the error since it's informative enough as is and there is // an annotation deferred already. return err } if c.ipRange.contains(gatewayIP.AsSlice()) { return fmt.Errorf("gateway ip %v in the ip range: %v-%v", gatewayIP, c.RangeStart, c.RangeEnd, ) } if !c.subnet.Contains(rangeStart) { return fmt.Errorf("range start %v is outside network %v", c.RangeStart, c.subnet, ) } if !c.subnet.Contains(rangeEnd) { return fmt.Errorf("range end %v is outside network %v", c.RangeEnd, c.subnet, ) } return nil } // V6ServerConf - server configuration type V6ServerConf struct { Enabled bool `yaml:"-" json:"-"` InterfaceName string `yaml:"-" json:"-"` // The first IP address for dynamic leases // The last allowed IP address ends with 0xff byte RangeStart net.IP `yaml:"range_start" json:"range_start"` LeaseDuration uint32 `yaml:"lease_duration" json:"lease_duration"` // in seconds RASLAACOnly bool `yaml:"ra_slaac_only" json:"-"` // send ICMPv6.RA packets without MO flags RAAllowSLAAC bool `yaml:"ra_allow_slaac" json:"-"` // send ICMPv6.RA packets with MO flags ipStart net.IP // starting IP address for dynamic leases leaseTime time.Duration // the time during which a dynamic lease is considered valid dnsIPAddrs []net.IP // IPv6 addresses to return to DHCP clients as DNS server addresses // Server calls this function when leases data changes notify func(uint32) } ```
/content/code_sandbox/internal/dhcpd/config.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,138
```go package dhcpd import ( "math" "testing" "testing/quick" "github.com/stretchr/testify/assert" ) func TestBitSet(t *testing.T) { t.Run("nil", func(t *testing.T) { var s *bitSet ok := s.isSet(0) assert.False(t, ok) assert.NotPanics(t, func() { s.set(0, true) }) ok = s.isSet(0) assert.False(t, ok) assert.NotPanics(t, func() { s.set(0, false) }) ok = s.isSet(0) assert.False(t, ok) }) t.Run("non_nil", func(t *testing.T) { s := newBitSet() ok := s.isSet(0) assert.False(t, ok) s.set(0, true) ok = s.isSet(0) assert.True(t, ok) s.set(0, false) ok = s.isSet(0) assert.False(t, ok) }) t.Run("non_nil_long", func(t *testing.T) { s := newBitSet() s.set(0, true) s.set(math.MaxUint64, true) assert.Len(t, s.words, 2) ok := s.isSet(0) assert.True(t, ok) ok = s.isSet(math.MaxUint64) assert.True(t, ok) }) t.Run("compare_to_map", func(t *testing.T) { m := map[uint64]struct{}{} s := newBitSet() mapFunc := func(setNew, checkOld, delOld uint64) (ok bool) { m[setNew] = struct{}{} delete(m, delOld) _, ok = m[checkOld] return ok } setFunc := func(setNew, checkOld, delOld uint64) (ok bool) { s.set(setNew, true) s.set(delOld, false) ok = s.isSet(checkOld) return ok } err := quick.CheckEqual(mapFunc, setFunc, &quick.Config{ MaxCount: 10_000, MaxCountScale: 10, }) assert.NoError(t, err) }) } ```
/content/code_sandbox/internal/dhcpd/bitset_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
508
```go //go:build linux package dhcpd import ( "fmt" "net" "os" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/insomniacslk/dhcp/dhcpv4" "github.com/insomniacslk/dhcp/dhcpv4/server4" "github.com/mdlayher/ethernet" "github.com/mdlayher/packet" ) // dhcpUnicastAddr is the combination of MAC and IP addresses for responding to // the unconfigured host. type dhcpUnicastAddr struct { // packet.Addr is embedded here to make *dhcpUcastAddr a net.Addr without // actually implementing all methods. It also contains the client's // hardware address. packet.Addr // yiaddr is an IP address just allocated by server for the host. yiaddr net.IP } // dhcpConn is the net.PacketConn capable of handling both net.UDPAddr and // net.HardwareAddr. type dhcpConn struct { // udpConn is the connection for UDP addresses. udpConn net.PacketConn // bcastIP is the broadcast address specific for the configured // interface's subnet. bcastIP net.IP // rawConn is the connection for MAC addresses. rawConn net.PacketConn // srcMAC is the hardware address of the configured network interface. srcMAC net.HardwareAddr // srcIP is the IP address of the configured network interface. srcIP net.IP } // newDHCPConn creates the special connection for DHCP server. func (s *v4Server) newDHCPConn(iface *net.Interface) (c net.PacketConn, err error) { var ucast net.PacketConn if ucast, err = packet.Listen(iface, packet.Raw, int(ethernet.EtherTypeIPv4), nil); err != nil { return nil, fmt.Errorf("creating raw udp connection: %w", err) } // Create the UDP connection. var bcast net.PacketConn bcast, err = server4.NewIPv4UDPConn(iface.Name, &net.UDPAddr{ // TODO(e.burkov): Listening on zeroes makes the server handle // requests from all the interfaces. Inspect the ways to // specify the interface-specific listening addresses. // // See path_to_url IP: net.IP{0, 0, 0, 0}, Port: dhcpv4.ServerPort, }) if err != nil { return nil, fmt.Errorf("creating ipv4 udp connection: %w", err) } return &dhcpConn{ udpConn: bcast, bcastIP: s.conf.broadcastIP.AsSlice(), rawConn: ucast, srcMAC: iface.HardwareAddr, srcIP: s.conf.dnsIPAddrs[0].AsSlice(), }, nil } // WriteTo implements net.PacketConn for *dhcpConn. It selects the underlying // connection to write to based on the type of addr. func (c *dhcpConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { switch addr := addr.(type) { case *dhcpUnicastAddr: // Unicast the message to the client's MAC address. Use the raw // connection. // // Note: unicasting is performed on the only network interface // that is configured. For now it may be not what users expect // so additionally broadcast the message via UDP connection. // // See path_to_url var rerr error n, rerr = c.unicast(p, addr) _, uerr := c.broadcast(p, &net.UDPAddr{ IP: netutil.IPv4bcast(), Port: dhcpv4.ClientPort, }) return n, wrapErrs("writing to", uerr, rerr) case *net.UDPAddr: if addr.IP.Equal(net.IPv4bcast) { // Broadcast the message for the client which supports // it. Use the UDP connection. return c.broadcast(p, addr) } // Unicast the message to the client's IP address. Use the UDP // connection. return c.udpConn.WriteTo(p, addr) default: return 0, fmt.Errorf("addr has an unexpected type %T", addr) } } // ReadFrom implements net.PacketConn for *dhcpConn. func (c *dhcpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { return c.udpConn.ReadFrom(p) } // unicast wraps respData with required frames and writes it to the peer. func (c *dhcpConn) unicast(respData []byte, peer *dhcpUnicastAddr) (n int, err error) { var data []byte data, err = c.buildEtherPkt(respData, peer) if err != nil { return 0, err } return c.rawConn.WriteTo(data, &peer.Addr) } // Close implements net.PacketConn for *dhcpConn. func (c *dhcpConn) Close() (err error) { rerr := c.rawConn.Close() if errors.Is(rerr, os.ErrClosed) { // Ignore the error since the actual file is closed already. rerr = nil } return wrapErrs("closing", c.udpConn.Close(), rerr) } // LocalAddr implements net.PacketConn for *dhcpConn. func (c *dhcpConn) LocalAddr() (a net.Addr) { return c.udpConn.LocalAddr() } // SetDeadline implements net.PacketConn for *dhcpConn. func (c *dhcpConn) SetDeadline(t time.Time) (err error) { return wrapErrs("setting deadline on", c.udpConn.SetDeadline(t), c.rawConn.SetDeadline(t)) } // SetReadDeadline implements net.PacketConn for *dhcpConn. func (c *dhcpConn) SetReadDeadline(t time.Time) error { return wrapErrs( "setting reading deadline on", c.udpConn.SetReadDeadline(t), c.rawConn.SetReadDeadline(t), ) } // SetWriteDeadline implements net.PacketConn for *dhcpConn. func (c *dhcpConn) SetWriteDeadline(t time.Time) error { return wrapErrs( "setting writing deadline on", c.udpConn.SetWriteDeadline(t), c.rawConn.SetWriteDeadline(t), ) } // ipv4DefaultTTL is the default Time to Live value in seconds as recommended by // RFC-1700. // // See path_to_url const ipv4DefaultTTL = 64 // buildEtherPkt wraps the payload with IPv4, UDP and Ethernet frames. // Validation of the payload is a caller's responsibility. func (c *dhcpConn) buildEtherPkt(payload []byte, peer *dhcpUnicastAddr) (pkt []byte, err error) { udpLayer := &layers.UDP{ SrcPort: dhcpv4.ServerPort, DstPort: dhcpv4.ClientPort, } ipv4Layer := &layers.IPv4{ Version: uint8(layers.IPProtocolIPv4), Flags: layers.IPv4DontFragment, TTL: ipv4DefaultTTL, Protocol: layers.IPProtocolUDP, SrcIP: c.srcIP, DstIP: peer.yiaddr, } // Ignore the error since it's only returned for invalid network layer's // type. _ = udpLayer.SetNetworkLayerForChecksum(ipv4Layer) ethLayer := &layers.Ethernet{ SrcMAC: c.srcMAC, DstMAC: peer.HardwareAddr, EthernetType: layers.EthernetTypeIPv4, } buf := gopacket.NewSerializeBuffer() setts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } err = gopacket.SerializeLayers( buf, setts, ethLayer, ipv4Layer, udpLayer, gopacket.Payload(payload), ) if err != nil { return nil, fmt.Errorf("serializing layers: %w", err) } return buf.Bytes(), nil } // send writes resp for peer to conn considering the req's parameters according // to RFC-2131. // // See path_to_url#section-4.1. func (s *v4Server) send(peer net.Addr, conn net.PacketConn, req, resp *dhcpv4.DHCPv4) { switch giaddr, ciaddr, mtype := req.GatewayIPAddr, req.ClientIPAddr, resp.MessageType(); { case giaddr != nil && !giaddr.IsUnspecified(): // Send any return messages to the server port on the BOOTP relay agent // whose address appears in giaddr. peer = &net.UDPAddr{ IP: giaddr, Port: dhcpv4.ServerPort, } if mtype == dhcpv4.MessageTypeNak { // Set the broadcast bit in the DHCPNAK, so that the relay agent // broadcasts it to the client, because the client may not have a // correct network address or subnet mask, and the client may not be // answering ARP requests. resp.SetBroadcast() } case mtype == dhcpv4.MessageTypeNak: // Broadcast any DHCPNAK messages to 0xffffffff. case ciaddr != nil && !ciaddr.IsUnspecified(): // Unicast DHCPOFFER and DHCPACK messages to the address in ciaddr. peer = &net.UDPAddr{ IP: ciaddr, Port: dhcpv4.ClientPort, } case !req.IsBroadcast() && req.ClientHWAddr != nil: // Unicast DHCPOFFER and DHCPACK messages to the client's hardware // address and yiaddr. peer = &dhcpUnicastAddr{ Addr: packet.Addr{HardwareAddr: req.ClientHWAddr}, yiaddr: resp.YourIPAddr, } default: // Go on since peer is already set to broadcast. } pktData := resp.ToBytes() log.Debug("dhcpv4: sending %d bytes to %s: %s", len(pktData), peer, resp.Summary()) _, err := conn.WriteTo(pktData, peer) if err != nil { log.Error("dhcpv4: conn.Write to %s failed: %s", peer, err) } } ```
/content/code_sandbox/internal/dhcpd/conn_linux.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,369
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "net/netip" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // defaultResponse is a helper that returns the response with default // configuration. func defaultResponse() *dhcpStatusResponse { conf4 := defaultV4ServerConf() conf4.LeaseDuration = 86400 resp := &dhcpStatusResponse{ V4: *conf4, V6: V6ServerConf{}, Leases: []*leaseDynamic{}, StaticLeases: []*leaseStatic{}, Enabled: true, } return resp } // handleLease is the helper function that calls handler with provided static // lease as body and returns modified response recorder. func handleLease(t *testing.T, lease *leaseStatic, handler http.HandlerFunc) (w *httptest.ResponseRecorder) { t.Helper() w = httptest.NewRecorder() b := &bytes.Buffer{} err := json.NewEncoder(b).Encode(lease) require.NoError(t, err) var r *http.Request r, err = http.NewRequest(http.MethodPost, "", b) require.NoError(t, err) handler(w, r) return w } // checkStatus is a helper that asserts the response of // [*server.handleDHCPStatus]. func checkStatus(t *testing.T, s *server, want *dhcpStatusResponse) { w := httptest.NewRecorder() b := &bytes.Buffer{} err := json.NewEncoder(b).Encode(&want) require.NoError(t, err) r, err := http.NewRequest(http.MethodPost, "", b) require.NoError(t, err) s.handleDHCPStatus(w, r) assert.Equal(t, http.StatusOK, w.Code) assert.JSONEq(t, b.String(), w.Body.String()) } func TestServer_handleDHCPStatus(t *testing.T) { const ( staticName = "static-client" staticMAC = "aa:aa:aa:aa:aa:aa" ) staticIP := netip.MustParseAddr("192.168.10.10") staticLease := &leaseStatic{ HWAddr: staticMAC, IP: staticIP, Hostname: staticName, } s, err := Create(&ServerConfig{ Enabled: true, Conf4: *defaultV4ServerConf(), DataDir: t.TempDir(), ConfigModified: func() {}, }) require.NoError(t, err) ok := t.Run("status", func(t *testing.T) { resp := defaultResponse() checkStatus(t, s, resp) }) require.True(t, ok) ok = t.Run("add_static_lease", func(t *testing.T) { w := handleLease(t, staticLease, s.handleDHCPAddStaticLease) assert.Equal(t, http.StatusOK, w.Code) resp := defaultResponse() resp.StaticLeases = []*leaseStatic{staticLease} checkStatus(t, s, resp) }) require.True(t, ok) ok = t.Run("add_invalid_lease", func(t *testing.T) { w := handleLease(t, staticLease, s.handleDHCPAddStaticLease) assert.Equal(t, http.StatusBadRequest, w.Code) }) require.True(t, ok) ok = t.Run("remove_static_lease", func(t *testing.T) { w := handleLease(t, staticLease, s.handleDHCPRemoveStaticLease) assert.Equal(t, http.StatusOK, w.Code) resp := defaultResponse() checkStatus(t, s, resp) }) require.True(t, ok) ok = t.Run("set_config", func(t *testing.T) { w := httptest.NewRecorder() resp := defaultResponse() resp.Enabled = false b := &bytes.Buffer{} err = json.NewEncoder(b).Encode(&resp) require.NoError(t, err) var r *http.Request r, err = http.NewRequest(http.MethodPost, "", b) require.NoError(t, err) s.handleDHCPSetConfig(w, r) assert.Equal(t, http.StatusOK, w.Code) checkStatus(t, s, resp) }) require.True(t, ok) } func TestServer_HandleUpdateStaticLease(t *testing.T) { const ( leaseV4Name = "static-client-v4" leaseV4MAC = "44:44:44:44:44:44" leaseV6Name = "static-client-v6" leaseV6MAC = "66:66:66:66:66:66" ) leaseV4IP := netip.MustParseAddr("192.168.10.10") leaseV6IP := netip.MustParseAddr("2001::6") const ( leaseV4Pos = iota leaseV6Pos ) leases := []*leaseStatic{ leaseV4Pos: { HWAddr: leaseV4MAC, IP: leaseV4IP, Hostname: leaseV4Name, }, leaseV6Pos: { HWAddr: leaseV6MAC, IP: leaseV6IP, Hostname: leaseV6Name, }, } s, err := Create(&ServerConfig{ Enabled: true, Conf4: *defaultV4ServerConf(), Conf6: V6ServerConf{}, DataDir: t.TempDir(), ConfigModified: func() {}, }) require.NoError(t, err) for _, l := range leases { w := handleLease(t, l, s.handleDHCPAddStaticLease) assert.Equal(t, http.StatusOK, w.Code) } testCases := []struct { name string pos int lease *leaseStatic }{{ name: "update_v4_name", pos: leaseV4Pos, lease: &leaseStatic{ HWAddr: leaseV4MAC, IP: leaseV4IP, Hostname: "updated-client-v4", }, }, { name: "update_v4_ip", pos: leaseV4Pos, lease: &leaseStatic{ HWAddr: leaseV4MAC, IP: netip.MustParseAddr("192.168.10.200"), Hostname: "updated-client-v4", }, }, { name: "update_v6_name", pos: leaseV6Pos, lease: &leaseStatic{ HWAddr: leaseV6MAC, IP: leaseV6IP, Hostname: "updated-client-v6", }, }, { name: "update_v6_ip", pos: leaseV6Pos, lease: &leaseStatic{ HWAddr: leaseV6MAC, IP: netip.MustParseAddr("2001::666"), Hostname: "updated-client-v6", }, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { w := handleLease(t, tc.lease, s.handleDHCPUpdateStaticLease) assert.Equal(t, http.StatusOK, w.Code) resp := defaultResponse() leases[tc.pos] = tc.lease resp.StaticLeases = leases checkStatus(t, s, resp) }) } } func TestServer_HandleUpdateStaticLease_validation(t *testing.T) { const ( leaseV4Name = "static-client-v4" leaseV4MAC = "44:44:44:44:44:44" anotherV4Name = "another-client-v4" anotherV4MAC = "55:55:55:55:55:55" ) leaseV4IP := netip.MustParseAddr("192.168.10.10") anotherV4IP := netip.MustParseAddr("192.168.10.20") leases := []*leaseStatic{{ HWAddr: leaseV4MAC, IP: leaseV4IP, Hostname: leaseV4Name, }, { HWAddr: anotherV4MAC, IP: anotherV4IP, Hostname: anotherV4Name, }} s, err := Create(&ServerConfig{ Enabled: true, Conf4: *defaultV4ServerConf(), Conf6: V6ServerConf{}, DataDir: t.TempDir(), ConfigModified: func() {}, }) require.NoError(t, err) for _, l := range leases { w := handleLease(t, l, s.handleDHCPAddStaticLease) assert.Equal(t, http.StatusOK, w.Code) } testCases := []struct { lease *leaseStatic name string want string }{{ name: "v4_unknown_mac", lease: &leaseStatic{ HWAddr: "aa:aa:aa:aa:aa:aa", IP: leaseV4IP, Hostname: leaseV4Name, }, want: "dhcpv4: updating static lease: can't find lease aa:aa:aa:aa:aa:aa\n", }, { name: "update_v4_same_ip", lease: &leaseStatic{ HWAddr: leaseV4MAC, IP: anotherV4IP, Hostname: leaseV4Name, }, want: "dhcpv4: updating static lease: ip address is not unique\n", }, { name: "update_v4_same_name", lease: &leaseStatic{ HWAddr: leaseV4MAC, IP: leaseV4IP, Hostname: anotherV4Name, }, want: "dhcpv4: updating static lease: hostname is not unique\n", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { w := handleLease(t, tc.lease, s.handleDHCPUpdateStaticLease) assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, tc.want, w.Body.String()) }) } } ```
/content/code_sandbox/internal/dhcpd/http_unix_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,293
```go //go:build windows package dhcpd // 'u-root/u-root' package, a dependency of 'insomniacslk/dhcp' package, doesn't build on Windows import ( "net" "net/netip" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" ) type winServer struct{} // type check var _ DHCPServer = winServer{} func (winServer) ResetLeases(_ []*dhcpsvc.Lease) (err error) { return nil } func (winServer) GetLeases(_ GetLeasesFlags) (leases []*dhcpsvc.Lease) { return nil } func (winServer) getLeasesRef() []*dhcpsvc.Lease { return nil } func (winServer) AddStaticLease(_ *dhcpsvc.Lease) (err error) { return nil } func (winServer) RemoveStaticLease(_ *dhcpsvc.Lease) (err error) { return nil } func (winServer) UpdateStaticLease(_ *dhcpsvc.Lease) (err error) { return nil } func (winServer) FindMACbyIP(_ netip.Addr) (mac net.HardwareAddr) { return nil } func (winServer) WriteDiskConfig4(_ *V4ServerConf) {} func (winServer) WriteDiskConfig6(_ *V6ServerConf) {} func (winServer) Start() (err error) { return nil } func (winServer) Stop() (err error) { return nil } func (winServer) HostByIP(_ netip.Addr) (host string) { return "" } func (winServer) IPByHost(_ string) (ip netip.Addr) { return netip.Addr{} } func v4Create(_ *V4ServerConf) (s DHCPServer, err error) { return winServer{}, nil } func v6Create(_ V6ServerConf) (s DHCPServer, err error) { return winServer{}, nil } ```
/content/code_sandbox/internal/dhcpd/v46_windows.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
436
```go package aghtest import ( "crypto/sha256" "encoding/hex" "fmt" "net" "net/netip" "strings" "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/errors" "github.com/miekg/dns" ) // Additional Upstream Testing Utilities // Upstream is a mock implementation of upstream.Upstream. // // TODO(a.garipov): Replace with UpstreamMock and rename it to just Upstream. type Upstream struct { // CName is a map of hostname to canonical name. CName map[string][]string // IPv4 is a map of hostname to IPv4. IPv4 map[string][]net.IP // IPv6 is a map of hostname to IPv6. IPv6 map[string][]net.IP } var _ upstream.Upstream = (*Upstream)(nil) // Exchange implements the [upstream.Upstream] interface for *Upstream. // // TODO(a.garipov): Split further into handlers. func (u *Upstream) Exchange(m *dns.Msg) (resp *dns.Msg, err error) { resp = new(dns.Msg).SetReply(m) if len(m.Question) == 0 { return nil, fmt.Errorf("question should not be empty") } q := m.Question[0] name := q.Name for _, cname := range u.CName[name] { resp.Answer = append(resp.Answer, &dns.CNAME{ Hdr: dns.RR_Header{Name: name, Rrtype: dns.TypeCNAME}, Target: cname, }) } qtype := q.Qtype hdr := dns.RR_Header{ Name: name, Rrtype: qtype, } switch qtype { case dns.TypeA: for _, ip := range u.IPv4[name] { resp.Answer = append(resp.Answer, &dns.A{Hdr: hdr, A: ip}) } case dns.TypeAAAA: for _, ip := range u.IPv6[name] { resp.Answer = append(resp.Answer, &dns.AAAA{Hdr: hdr, AAAA: ip}) } } if len(resp.Answer) == 0 { resp.SetRcode(m, dns.RcodeNameError) } return resp, nil } // Address implements [upstream.Upstream] interface for *Upstream. func (u *Upstream) Address() string { return "todo.upstream.example" } // Close implements [upstream.Upstream] interface for *Upstream. func (u *Upstream) Close() (err error) { return nil } // MatchedResponse is a test helper that returns a response with answer if req // has question type qt, and target targ. Otherwise, it returns nil. // // req must not be nil and req.Question must have a length of 1. Answer is // interpreted in the following ways: // // - For A and AAAA queries, answer must be an IP address of the corresponding // protocol version. // // - For PTR queries, answer should be a domain name in the response. // // If the answer does not correspond to the question type, MatchedResponse panics. // Panics are used instead of [testing.TB], because the helper is intended to // use in [UpstreamMock.OnExchange] callbacks, which are usually called in a // separate goroutine. // // TODO(a.garipov): Consider adding version with DNS class as well. func MatchedResponse(req *dns.Msg, qt uint16, targ, answer string) (resp *dns.Msg) { if req == nil || len(req.Question) != 1 { panic(fmt.Errorf("bad req: %+v", req)) } q := req.Question[0] targ = dns.Fqdn(targ) if q.Qclass != dns.ClassINET || q.Qtype != qt || q.Name != targ { return nil } respHdr := dns.RR_Header{ Name: targ, Rrtype: qt, Class: dns.ClassINET, Ttl: 60, } resp = new(dns.Msg).SetReply(req) switch qt { case dns.TypeA: resp.Answer = mustAnsA(respHdr, answer) case dns.TypeAAAA: resp.Answer = mustAnsAAAA(respHdr, answer) case dns.TypePTR: resp.Answer = []dns.RR{&dns.PTR{ Hdr: respHdr, Ptr: answer, }} default: panic(fmt.Errorf("aghtest: bad question type: %s", dns.Type(qt))) } return resp } // mustAnsA returns valid answer records if s is a valid IPv4 address. // Otherwise, mustAnsA panics. func mustAnsA(respHdr dns.RR_Header, s string) (ans []dns.RR) { ip, err := netip.ParseAddr(s) if err != nil || !ip.Is4() { panic(fmt.Errorf("aghtest: bad A answer: %+v", s)) } return []dns.RR{&dns.A{ Hdr: respHdr, A: ip.AsSlice(), }} } // mustAnsAAAA returns valid answer records if s is a valid IPv6 address. // Otherwise, mustAnsAAAA panics. func mustAnsAAAA(respHdr dns.RR_Header, s string) (ans []dns.RR) { ip, err := netip.ParseAddr(s) if err != nil || !ip.Is6() { panic(fmt.Errorf("aghtest: bad AAAA answer: %+v", s)) } return []dns.RR{&dns.AAAA{ Hdr: respHdr, AAAA: ip.AsSlice(), }} } // NewUpstreamMock returns an [*UpstreamMock], fields OnAddress and OnClose of // which are set to stubs that return "upstream.example" and nil respectively. // The field OnExchange is set to onExc. func NewUpstreamMock(onExc func(req *dns.Msg) (resp *dns.Msg, err error)) (u *UpstreamMock) { return &UpstreamMock{ OnAddress: func() (addr string) { return "upstream.example" }, OnExchange: onExc, OnClose: func() (err error) { return nil }, } } // NewBlockUpstream returns an [*UpstreamMock] that works like an upstream that // supports hash-based safe-browsing/adult-blocking feature. If shouldBlock is // true, hostname's actual hash is returned, blocking it. Otherwise, it returns // a different hash. func NewBlockUpstream(hostname string, shouldBlock bool) (u *UpstreamMock) { hash := sha256.Sum256([]byte(hostname)) hashStr := hex.EncodeToString(hash[:]) if !shouldBlock { hashStr = hex.EncodeToString(hash[:])[:2] + strings.Repeat("ab", 28) } ans := &dns.TXT{ Hdr: dns.RR_Header{ Name: "", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 60, }, Txt: []string{hashStr}, } respTmpl := &dns.Msg{ Answer: []dns.RR{ans}, } return &UpstreamMock{ OnAddress: func() (addr string) { return "sbpc.upstream.example" }, OnExchange: func(req *dns.Msg) (resp *dns.Msg, err error) { resp = respTmpl.Copy() resp.SetReply(req) resp.Answer[0].(*dns.TXT).Hdr.Name = req.Question[0].Name return resp, nil }, OnClose: func() (err error) { return nil }, } } // ErrUpstream is the error returned from the [*UpstreamMock] created by // [NewErrorUpstream]. const ErrUpstream errors.Error = "test upstream error" // NewErrorUpstream returns an [*UpstreamMock] that returns [ErrUpstream] from // its Exchange method. func NewErrorUpstream() (u *UpstreamMock) { return &UpstreamMock{ OnAddress: func() (addr string) { return "error.upstream.example" }, OnExchange: func(_ *dns.Msg) (resp *dns.Msg, err error) { return nil, errors.Error("test upstream error") }, OnClose: func() (err error) { return nil }, } } ```
/content/code_sandbox/internal/aghtest/upstream.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,843
```go package aghtest_test import ( "github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/client" "github.com/AdguardTeam/AdGuardHome/internal/dnsforward" "github.com/AdguardTeam/AdGuardHome/internal/filtering" ) // Put interface checks that cause import cycles here. // type check var _ filtering.Resolver = (*aghtest.Resolver)(nil) // type check var _ dnsforward.ClientsContainer = (*aghtest.ClientsContainer)(nil) // type check // // TODO(s.chzhen): It's here to avoid the import cycle. Remove it. var _ client.AddressProcessor = (*aghtest.AddressProcessor)(nil) // type check // // TODO(s.chzhen): It's here to avoid the import cycle. Remove it. var _ client.AddressUpdater = (*aghtest.AddressUpdater)(nil) ```
/content/code_sandbox/internal/aghtest/interface_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
204
```go // Package aghtest contains utilities for testing. package aghtest import ( "crypto/sha256" "io" "net/http" "net/http/httptest" "net/netip" "net/url" "testing" "time" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/testutil" "github.com/miekg/dns" "github.com/stretchr/testify/require" ) const ( // ReqHost is the common request host for filtering tests. ReqHost = "www.host.example" // ReqFQDN is the common request FQDN for filtering tests. ReqFQDN = ReqHost + "." ) // ReplaceLogWriter moves logger output to w and uses Cleanup method of t to // revert changes. func ReplaceLogWriter(t testing.TB, w io.Writer) { t.Helper() prev := log.Writer() t.Cleanup(func() { log.SetOutput(prev) }) log.SetOutput(w) } // ReplaceLogLevel sets logging level to l and uses Cleanup method of t to // revert changes. func ReplaceLogLevel(t testing.TB, l log.Level) { t.Helper() switch l { case log.INFO, log.DEBUG, log.ERROR: // Go on. default: t.Fatalf("wrong l value (must be one of %v, %v, %v)", log.INFO, log.DEBUG, log.ERROR) } prev := log.GetLevel() t.Cleanup(func() { log.SetLevel(prev) }) log.SetLevel(l) } // HostToIPs is a helper that generates one IPv4 and one IPv6 address from host. func HostToIPs(host string) (ipv4, ipv6 netip.Addr) { hash := sha256.Sum256([]byte(host)) return netip.AddrFrom4([4]byte(hash[:4])), netip.AddrFrom16([16]byte(hash[4:20])) } // StartHTTPServer is a helper that starts the HTTP server, which is configured // to return data on every request, and returns the client and server URL. func StartHTTPServer(t testing.TB, data []byte) (c *http.Client, u *url.URL) { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(data) })) t.Cleanup(srv.Close) u, err := url.Parse(srv.URL) require.NoError(t, err) return srv.Client(), u } // testTimeout is a timeout for tests. // // TODO(e.burkov): Move into agdctest. const testTimeout = 1 * time.Second // StartLocalhostUpstream is a test helper that starts a DNS server on // localhost. func StartLocalhostUpstream(t *testing.T, h dns.Handler) (addr *url.URL) { t.Helper() startCh := make(chan netip.AddrPort) defer close(startCh) errCh := make(chan error) srv := &dns.Server{ Addr: "127.0.0.1:0", Net: string(proxy.ProtoTCP), Handler: h, ReadTimeout: testTimeout, WriteTimeout: testTimeout, } srv.NotifyStartedFunc = func() { addrPort := srv.Listener.Addr() startCh <- netutil.NetAddrToAddrPort(addrPort) } go func() { errCh <- srv.ListenAndServe() }() select { case addrPort := <-startCh: addr = &url.URL{ Scheme: string(proxy.ProtoTCP), Host: addrPort.String(), } testutil.CleanupAndRequireSuccess(t, func() (err error) { return <-errCh }) testutil.CleanupAndRequireSuccess(t, srv.Shutdown) case err := <-errCh: require.NoError(t, err) case <-time.After(testTimeout): require.FailNow(t, "timeout exceeded") } return addr } ```
/content/code_sandbox/internal/aghtest/aghtest.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
866
```go //go:build darwin || freebsd || linux || openbsd package dhcpd import ( "encoding/hex" "fmt" "net" "strconv" "strings" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/insomniacslk/dhcp/dhcpv4" ) // The aliases for DHCP option types available for explicit declaration. // // TODO(e.burkov): Add an option for classless routes. const ( typDel = "del" typBool = "bool" typDur = "dur" typHex = "hex" typIP = "ip" typIPs = "ips" typText = "text" typU8 = "u8" typU16 = "u16" ) // parseDHCPOptionHex parses a DHCP option as a hex-encoded string. func parseDHCPOptionHex(s string) (val dhcpv4.OptionValue, err error) { var data []byte data, err = hex.DecodeString(s) if err != nil { return nil, fmt.Errorf("decoding hex: %w", err) } return dhcpv4.OptionGeneric{Data: data}, nil } // parseDHCPOptionIP parses a DHCP option as a single IP address. func parseDHCPOptionIP(s string) (val dhcpv4.OptionValue, err error) { var ip net.IP // All DHCPv4 options require IPv4, so don't put the 16-byte version. // Otherwise, the clients will receive weird data that looks like four IPv4 // addresses. // // See path_to_url if ip, err = netutil.ParseIPv4(s); err != nil { return nil, err } return dhcpv4.IP(ip), nil } // parseDHCPOptionIPs parses a DHCP option as a comma-separates list of IP // addresses. func parseDHCPOptionIPs(s string) (val dhcpv4.OptionValue, err error) { var ips dhcpv4.IPs var ip dhcpv4.OptionValue for i, ipStr := range strings.Split(s, ",") { ip, err = parseDHCPOptionIP(ipStr) if err != nil { return nil, fmt.Errorf("parsing ip at index %d: %w", i, err) } ips = append(ips, net.IP(ip.(dhcpv4.IP))) } return ips, nil } // parseDHCPOptionDur parses a DHCP option as a duration in a human-readable // form. func parseDHCPOptionDur(s string) (val dhcpv4.OptionValue, err error) { var v timeutil.Duration err = v.UnmarshalText([]byte(s)) if err != nil { return nil, fmt.Errorf("decoding dur: %w", err) } return dhcpv4.Duration(v.Duration), nil } // parseDHCPOptionUint parses a DHCP option as an unsigned integer. bitSize is // expected to be 8 or 16. func parseDHCPOptionUint(s string, bitSize int) (val dhcpv4.OptionValue, err error) { var v uint64 v, err = strconv.ParseUint(s, 10, bitSize) if err != nil { return nil, fmt.Errorf("decoding u%d: %w", bitSize, err) } switch bitSize { case 8: return dhcpv4.OptionGeneric{Data: []byte{uint8(v)}}, nil case 16: return dhcpv4.Uint16(v), nil default: return nil, fmt.Errorf("unsupported size of integer %d", bitSize) } } // parseDHCPOptionBool parses a DHCP option as a boolean value. See // [strconv.ParseBool] for available values. func parseDHCPOptionBool(s string) (val dhcpv4.OptionValue, err error) { var v bool v, err = strconv.ParseBool(s) if err != nil { return nil, fmt.Errorf("decoding bool: %w", err) } rawVal := [1]byte{} if v { rawVal[0] = 1 } return dhcpv4.OptionGeneric{Data: rawVal[:]}, nil } // parseDHCPOptionVal parses a DHCP option value considering typ. func parseDHCPOptionVal(typ, valStr string) (val dhcpv4.OptionValue, err error) { switch typ { case typBool: val, err = parseDHCPOptionBool(valStr) case typDel: val = dhcpv4.OptionGeneric{Data: nil} case typDur: val, err = parseDHCPOptionDur(valStr) case typHex: val, err = parseDHCPOptionHex(valStr) case typIP: val, err = parseDHCPOptionIP(valStr) case typIPs: val, err = parseDHCPOptionIPs(valStr) case typText: val = dhcpv4.String(valStr) case typU8: val, err = parseDHCPOptionUint(valStr, 8) case typU16: val, err = parseDHCPOptionUint(valStr, 16) default: err = fmt.Errorf("unknown option type %q", typ) } return val, err } // parseDHCPOption parses an option. For the del option value is ignored. The // examples of possible option strings: // // - 1 bool true // - 2 del // - 3 dur 2h5s // - 4 hex 736f636b733a2f2f70726f78792e6578616d706c652e6f7267 // - 5 ip 192.168.1.1 // - 6 ips 192.168.1.1,192.168.1.2 // - 7 text path_to_url // - 8 u8 255 // - 9 u16 65535 func parseDHCPOption(s string) (code dhcpv4.OptionCode, val dhcpv4.OptionValue, err error) { defer func() { err = errors.Annotate(err, "invalid option string %q: %w", s) }() s = strings.TrimSpace(s) parts := strings.SplitN(s, " ", 3) var valStr string if pl := len(parts); pl < 3 { if pl < 2 || parts[1] != typDel { return nil, nil, errors.Error("bad option format") } } else { valStr = parts[2] } var code64 uint64 code64, err = strconv.ParseUint(parts[0], 10, 8) if err != nil { return nil, nil, fmt.Errorf("parsing option code: %w", err) } val, err = parseDHCPOptionVal(parts[1], valStr) if err != nil { // Don't wrap an error since it's informative enough as is and there // also the deferred annotation. return nil, nil, err } return dhcpv4.GenericOptionCode(code64), val, nil } // prepareOptions builds the set of DHCP options according to host requirements // document and values from conf. func (s *v4Server) prepareOptions() { // Set default values of host configuration parameters listed in Appendix A // of RFC-2131. s.implicitOpts = dhcpv4.OptionsFromList( // IP-Layer Per Host // An Internet host that includes embedded gateway code MUST have a // configuration switch to disable the gateway function, and this switch // MUST default to the non-gateway mode. // // See path_to_url#section-3.3.5. dhcpv4.OptGeneric(dhcpv4.OptionIPForwarding, []byte{0x0}), // A host that supports non-local source-routing MUST have a // configurable switch to disable forwarding, and this switch MUST // default to disabled. // // See path_to_url#section-3.3.5. dhcpv4.OptGeneric(dhcpv4.OptionNonLocalSourceRouting, []byte{0x0}), // Do not set the Policy Filter Option since it only makes sense when // the non-local source routing is enabled. // The minimum legal value is 576. // // See path_to_url#section-4.4. dhcpv4.Option{ Code: dhcpv4.OptionMaximumDatagramAssemblySize, Value: dhcpv4.Uint16(576), }, // Set the current recommended default time to live for the Internet // Protocol which is 64. // // See path_to_url#ip-parameters-2. dhcpv4.OptGeneric(dhcpv4.OptionDefaultIPTTL, []byte{0x40}), // For example, after the PTMU estimate is decreased, the timeout should // be set to 10 minutes; once this timer expires and a larger MTU is // attempted, the timeout can be set to a much smaller value. // // See path_to_url#section-6.6. dhcpv4.Option{ Code: dhcpv4.OptionPathMTUAgingTimeout, Value: dhcpv4.Duration(10 * time.Minute), }, // There is a table describing the MTU values representing all major // data-link technologies in use in the Internet so that each set of // similar MTUs is associated with a plateau value equal to the lowest // MTU in the group. // // See path_to_url#section-7. dhcpv4.OptGeneric(dhcpv4.OptionPathMTUPlateauTable, []byte{ 0x0, 0x44, 0x1, 0x28, 0x1, 0xFC, 0x3, 0xEE, 0x5, 0xD4, 0x7, 0xD2, 0x11, 0x0, 0x1F, 0xE6, 0x45, 0xFA, }), // IP-Layer Per Interface // Don't set the Interface MTU because client may choose the value on // their own since it's listed in the [Host Requirements RFC]. It also // seems the values listed there sometimes appear obsolete, see // path_to_url // // [Host Requirements RFC]: path_to_url#section-3.3.3. // Set the All Subnets Are Local Option to false since commonly the // connected hosts aren't expected to be multihomed. // // See path_to_url#section-3.3.3. dhcpv4.OptGeneric(dhcpv4.OptionAllSubnetsAreLocal, []byte{0x00}), // Set the Perform Mask Discovery Option to false to provide the subnet // mask by options only. // // See path_to_url#section-3.2.2.9. dhcpv4.OptGeneric(dhcpv4.OptionPerformMaskDiscovery, []byte{0x00}), // A system MUST NOT send an Address Mask Reply unless it is an // authoritative agent for address masks. An authoritative agent may be // a host or a gateway, but it MUST be explicitly configured as a // address mask agent. // // See path_to_url#section-3.2.2.9. dhcpv4.OptGeneric(dhcpv4.OptionMaskSupplier, []byte{0x00}), // Set the Perform Router Discovery Option to true as per Router // Discovery Document. // // See path_to_url#section-5.1. dhcpv4.OptGeneric(dhcpv4.OptionPerformRouterDiscovery, []byte{0x01}), // The all-routers address is preferred wherever possible. // // See path_to_url#section-5.1. dhcpv4.Option{ Code: dhcpv4.OptionRouterSolicitationAddress, Value: dhcpv4.IP(netutil.IPv4allrouter()), }, // Don't set the Static Routes Option since it should be set up by // system administrator. // // See path_to_url#section-3.3.1.2. // A datagram with the destination address of limited broadcast will be // received by every host on the connected physical network but will not // be forwarded outside that network. // // See path_to_url#section-3.2.1.3. dhcpv4.OptBroadcastAddress(netutil.IPv4bcast()), // Link-Layer Per Interface // If the system does not dynamically negotiate use of the trailer // protocol on a per-destination basis, the default configuration MUST // disable the protocol. // // See path_to_url#section-2.3.1. dhcpv4.OptGeneric(dhcpv4.OptionTrailerEncapsulation, []byte{0x00}), // For proxy ARP situations, the timeout needs to be on the order of a // minute. // // See path_to_url#section-2.3.2.1. dhcpv4.Option{ Code: dhcpv4.OptionArpCacheTimeout, Value: dhcpv4.Duration(time.Minute), }, // An Internet host that implements sending both the RFC-894 and the // RFC-1042 encapsulations MUST provide a configuration switch to select // which is sent, and this switch MUST default to RFC-894. // // See path_to_url#section-2.3.3. dhcpv4.OptGeneric(dhcpv4.OptionEthernetEncapsulation, []byte{0x00}), // TCP Per Host // A fixed value must be at least big enough for the Internet diameter, // i.e., the longest possible path. A reasonable value is about twice // the diameter, to allow for continued Internet growth. // // See path_to_url#section-3.2.1.7. dhcpv4.Option{ Code: dhcpv4.OptionDefaulTCPTTL, Value: dhcpv4.Duration(60 * time.Second), }, // The interval MUST be configurable and MUST default to no less than // two hours. // // See path_to_url#section-4.2.3.6. dhcpv4.Option{ Code: dhcpv4.OptionTCPKeepaliveInterval, Value: dhcpv4.Duration(2 * time.Hour), }, // Unfortunately, some misbehaved TCP implementations fail to respond to // a probe segment unless it contains data. // // See path_to_url#section-4.2.3.6. dhcpv4.OptGeneric(dhcpv4.OptionTCPKeepaliveGarbage, []byte{0x01}), // Values From Configuration dhcpv4.OptRouter(s.conf.GatewayIP.AsSlice()), dhcpv4.OptSubnetMask(s.conf.SubnetMask.AsSlice()), ) // Set values for explicitly configured options. s.explicitOpts = dhcpv4.Options{} for i, o := range s.conf.Options { code, val, err := parseDHCPOption(o) if err != nil { log.Error("dhcpv4: bad option string at index %d: %s", i, err) continue } s.explicitOpts.Update(dhcpv4.Option{Code: code, Value: val}) // Remove those from the implicit options. delete(s.implicitOpts, code.Code()) } log.Debug("dhcpv4: implicit options:\n%s", s.implicitOpts.Summary(nil)) log.Debug("dhcpv4: explicit options:\n%s", s.explicitOpts.Summary(nil)) if len(s.explicitOpts) == 0 { s.explicitOpts = nil } } ```
/content/code_sandbox/internal/dhcpd/options_unix.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,695
```yaml # This is a file showing example configuration for AdGuard Home. # # TODO(a.garipov): Move to the top level once the rewrite is over. dns: addresses: - '0.0.0.0:53' bootstrap_dns: - '9.9.9.10' - '149.112.112.10' - '2620:fe::10' - '2620:fe::fe:10' upstream_dns: - '8.8.8.8' dns64_prefixes: - '1234::/64' upstream_timeout: 1s bootstrap_prefer_ipv6: true use_dns64: true http: pprof: enabled: true port: 6060 addresses: - '0.0.0.0:3000' secure_addresses: [] timeout: 5s force_https: true log: verbose: true ```
/content/code_sandbox/internal/next/AdGuardHome.example.yaml
yaml
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
213
```go package aghtest import ( "context" "net" "net/netip" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/rdns" "github.com/AdguardTeam/AdGuardHome/internal/whois" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/upstream" "github.com/miekg/dns" ) // Interface Mocks // // Keep entities in this file in alphabetic order. // Module adguard-home // Package aghos // FSWatcher is a fake [aghos.FSWatcher] implementation for tests. type FSWatcher struct { OnStart func() (err error) OnClose func() (err error) OnEvents func() (e <-chan struct{}) OnAdd func(name string) (err error) } // type check var _ aghos.FSWatcher = (*FSWatcher)(nil) // Start implements the [aghos.FSWatcher] interface for *FSWatcher. func (w *FSWatcher) Start() (err error) { return w.OnStart() } // Close implements the [aghos.FSWatcher] interface for *FSWatcher. func (w *FSWatcher) Close() (err error) { return w.OnClose() } // Events implements the [aghos.FSWatcher] interface for *FSWatcher. func (w *FSWatcher) Events() (e <-chan struct{}) { return w.OnEvents() } // Add implements the [aghos.FSWatcher] interface for *FSWatcher. func (w *FSWatcher) Add(name string) (err error) { return w.OnAdd(name) } // Package agh // ServiceWithConfig is a fake [agh.ServiceWithConfig] implementation for tests. type ServiceWithConfig[ConfigType any] struct { OnStart func() (err error) OnShutdown func(ctx context.Context) (err error) OnConfig func() (c ConfigType) } // type check var _ agh.ServiceWithConfig[struct{}] = (*ServiceWithConfig[struct{}])(nil) // Start implements the [agh.ServiceWithConfig] interface for // *ServiceWithConfig. func (s *ServiceWithConfig[_]) Start() (err error) { return s.OnStart() } // Shutdown implements the [agh.ServiceWithConfig] interface for // *ServiceWithConfig. func (s *ServiceWithConfig[_]) Shutdown(ctx context.Context) (err error) { return s.OnShutdown(ctx) } // Config implements the [agh.ServiceWithConfig] interface for // *ServiceWithConfig. func (s *ServiceWithConfig[ConfigType]) Config() (c ConfigType) { return s.OnConfig() } // Package client // AddressProcessor is a fake [client.AddressProcessor] implementation for // tests. type AddressProcessor struct { OnProcess func(ip netip.Addr) OnClose func() (err error) } // Process implements the [client.AddressProcessor] interface for // *AddressProcessor. func (p *AddressProcessor) Process(ip netip.Addr) { p.OnProcess(ip) } // Close implements the [client.AddressProcessor] interface for // *AddressProcessor. func (p *AddressProcessor) Close() (err error) { return p.OnClose() } // AddressUpdater is a fake [client.AddressUpdater] implementation for tests. type AddressUpdater struct { OnUpdateAddress func(ip netip.Addr, host string, info *whois.Info) } // UpdateAddress implements the [client.AddressUpdater] interface for // *AddressUpdater. func (p *AddressUpdater) UpdateAddress(ip netip.Addr, host string, info *whois.Info) { p.OnUpdateAddress(ip, host, info) } // Package dnsforward // ClientsContainer is a fake [dnsforward.ClientsContainer] implementation for // tests. type ClientsContainer struct { OnUpstreamConfigByID func( id string, boot upstream.Resolver, ) (conf *proxy.CustomUpstreamConfig, err error) } // UpstreamConfigByID implements the [dnsforward.ClientsContainer] interface // for *ClientsContainer. func (c *ClientsContainer) UpstreamConfigByID( id string, boot upstream.Resolver, ) (conf *proxy.CustomUpstreamConfig, err error) { return c.OnUpstreamConfigByID(id, boot) } // Package filtering // Resolver is a fake [filtering.Resolver] implementation for tests. type Resolver struct { OnLookupIP func(ctx context.Context, network, host string) (ips []net.IP, err error) } // LookupIP implements the [filtering.Resolver] interface for *Resolver. func (r *Resolver) LookupIP(ctx context.Context, network, host string) (ips []net.IP, err error) { return r.OnLookupIP(ctx, network, host) } // Package rdns // Exchanger is a fake [rdns.Exchanger] implementation for tests. type Exchanger struct { OnExchange func(ip netip.Addr) (host string, ttl time.Duration, err error) } // type check var _ rdns.Exchanger = (*Exchanger)(nil) // Exchange implements [rdns.Exchanger] interface for *Exchanger. func (e *Exchanger) Exchange(ip netip.Addr) (host string, ttl time.Duration, err error) { return e.OnExchange(ip) } // Module dnsproxy // Package upstream // UpstreamMock is a fake [upstream.Upstream] implementation for tests. // // TODO(a.garipov): Replace with all uses of Upstream with UpstreamMock and // rename it to just Upstream. type UpstreamMock struct { OnAddress func() (addr string) OnExchange func(req *dns.Msg) (resp *dns.Msg, err error) OnClose func() (err error) } // type check var _ upstream.Upstream = (*UpstreamMock)(nil) // Address implements the [upstream.Upstream] interface for *UpstreamMock. func (u *UpstreamMock) Address() (addr string) { return u.OnAddress() } // Exchange implements the [upstream.Upstream] interface for *UpstreamMock. func (u *UpstreamMock) Exchange(req *dns.Msg) (resp *dns.Msg, err error) { return u.OnExchange(req) } // Close implements the [upstream.Upstream] interface for *UpstreamMock. func (u *UpstreamMock) Close() (err error) { return u.OnClose() } ```
/content/code_sandbox/internal/aghtest/interface.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,396
```go // Package agh contains common entities and interfaces of AdGuard Home. package agh import "context" // Service is the interface for API servers. // // TODO(a.garipov): Consider adding a context to Start. // // TODO(a.garipov): Consider adding a Wait method or making an extension // interface for that. type Service interface { // Start starts the service. It does not block. Start() (err error) // Shutdown gracefully stops the service. ctx is used to determine // a timeout before trying to stop the service less gracefully. Shutdown(ctx context.Context) (err error) } // type check var _ Service = EmptyService{} // EmptyService is a [Service] that does nothing. // // TODO(a.garipov): Remove if unnecessary. type EmptyService struct{} // Start implements the [Service] interface for EmptyService. func (EmptyService) Start() (err error) { return nil } // Shutdown implements the [Service] interface for EmptyService. func (EmptyService) Shutdown(_ context.Context) (err error) { return nil } // ServiceWithConfig is an extension of the [Service] interface for services // that can return their configuration. // // TODO(a.garipov): Consider removing this generic interface if we figure out // how to make it testable in a better way. type ServiceWithConfig[ConfigType any] interface { Service Config() (c ConfigType) } // type check var _ ServiceWithConfig[struct{}] = (*EmptyServiceWithConfig[struct{}])(nil) // EmptyServiceWithConfig is a ServiceWithConfig that does nothing. Its Config // method returns Conf. // // TODO(a.garipov): Remove if unnecessary. type EmptyServiceWithConfig[ConfigType any] struct { EmptyService Conf ConfigType } // Config implements the [ServiceWithConfig] interface for // *EmptyServiceWithConfig. func (s *EmptyServiceWithConfig[ConfigType]) Config() (conf ConfigType) { return s.Conf } ```
/content/code_sandbox/internal/next/agh/agh.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
434
```go package dnssvc_test import ( "net/netip" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/golibs/testutil" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } // testTimeout is the common timeout for tests. const testTimeout = 1 * time.Second func TestService(t *testing.T) { const ( listenAddr = "127.0.0.1:0" bootstrapAddr = "127.0.0.1:0" upstreamAddr = "upstream.example" ) upstreamErrCh := make(chan error, 1) upstreamStartedCh := make(chan struct{}) upstreamSrv := &dns.Server{ Addr: bootstrapAddr, Net: "udp", Handler: dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) { pt := testutil.PanicT{} resp := (&dns.Msg{}).SetReply(req) resp.Answer = append(resp.Answer, &dns.A{ Hdr: dns.RR_Header{}, A: netip.MustParseAddrPort(bootstrapAddr).Addr().AsSlice(), }) writeErr := w.WriteMsg(resp) require.NoError(pt, writeErr) }), NotifyStartedFunc: func() { close(upstreamStartedCh) }, } go func() { listenErr := upstreamSrv.ListenAndServe() if listenErr != nil { // Log these immediately to see what happens. t.Logf("upstream listen error: %s", listenErr) } upstreamErrCh <- listenErr }() _, _ = testutil.RequireReceive(t, upstreamStartedCh, testTimeout) c := &dnssvc.Config{ Addresses: []netip.AddrPort{netip.MustParseAddrPort(listenAddr)}, BootstrapServers: []string{upstreamSrv.PacketConn.LocalAddr().String()}, UpstreamServers: []string{upstreamAddr}, DNS64Prefixes: nil, UpstreamTimeout: testTimeout, BootstrapPreferIPv6: false, UseDNS64: false, } svc, err := dnssvc.New(c) require.NoError(t, err) err = svc.Start() require.NoError(t, err) gotConf := svc.Config() require.NotNil(t, gotConf) require.Len(t, gotConf.Addresses, 1) addr := gotConf.Addresses[0] t.Run("dns", func(t *testing.T) { req := &dns.Msg{ MsgHdr: dns.MsgHdr{ Id: dns.Id(), RecursionDesired: true, }, Question: []dns.Question{{ Name: "example.com.", Qtype: dns.TypeA, Qclass: dns.ClassINET, }}, } cli := &dns.Client{} ctx := testutil.ContextWithTimeout(t, testTimeout) var resp *dns.Msg require.Eventually(t, func() (ok bool) { var excErr error resp, _, excErr = cli.ExchangeContext(ctx, req, addr.String()) return excErr == nil }, testTimeout, testTimeout/10) assert.NotNil(t, resp) }) err = svc.Shutdown(testutil.ContextWithTimeout(t, testTimeout)) require.NoError(t, err) err = upstreamSrv.Shutdown() require.NoError(t, err) err, ok := testutil.RequireReceive(t, upstreamErrCh, testTimeout) require.True(t, ok) require.NoError(t, err) } ```
/content/code_sandbox/internal/next/dnssvc/dnssvc_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
825
```go // Package dnssvc contains the AdGuard Home DNS service. // // TODO(a.garipov): Define, if all methods of a *Service should work with a nil // receiver. package dnssvc import ( "context" "fmt" "net" "net/netip" "sync/atomic" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" // TODO(a.garipov): Add a dnsproxy proxy package to shield us from changes // and replacement of module dnsproxy. "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/errors" ) // Service is the AdGuard Home DNS service. A nil *Service is a valid // [agh.Service] that does nothing. // // TODO(a.garipov): Consider saving a [*proxy.Config] instance for those // fields that are only used in [New] and [Service.Config]. type Service struct { proxy *proxy.Proxy bootstraps []string bootstrapResolvers []*upstream.UpstreamResolver upstreams []string dns64Prefixes []netip.Prefix upsTimeout time.Duration running atomic.Bool bootstrapPreferIPv6 bool useDNS64 bool } // New returns a new properly initialized *Service. If c is nil, svc is a nil // *Service that does nothing. The fields of c must not be modified after // calling New. func New(c *Config) (svc *Service, err error) { if c == nil { return nil, nil } svc = &Service{ bootstraps: c.BootstrapServers, upstreams: c.UpstreamServers, dns64Prefixes: c.DNS64Prefixes, upsTimeout: c.UpstreamTimeout, bootstrapPreferIPv6: c.BootstrapPreferIPv6, useDNS64: c.UseDNS64, } upstreams, resolvers, err := addressesToUpstreams( c.UpstreamServers, c.BootstrapServers, c.UpstreamTimeout, c.BootstrapPreferIPv6, ) if err != nil { return nil, fmt.Errorf("converting upstreams: %w", err) } svc.bootstrapResolvers = resolvers svc.proxy, err = proxy.New(&proxy.Config{ UDPListenAddr: udpAddrs(c.Addresses), TCPListenAddr: tcpAddrs(c.Addresses), UpstreamConfig: &proxy.UpstreamConfig{ Upstreams: upstreams, }, UseDNS64: c.UseDNS64, DNS64Prefs: c.DNS64Prefixes, }) if err != nil { return nil, fmt.Errorf("proxy: %w", err) } return svc, nil } // addressesToUpstreams is a wrapper around [upstream.AddressToUpstream]. It // accepts a slice of addresses and other upstream parameters, and returns a // slice of upstreams. func addressesToUpstreams( upsStrs []string, bootstraps []string, timeout time.Duration, preferIPv6 bool, ) (upstreams []upstream.Upstream, boots []*upstream.UpstreamResolver, err error) { opts := &upstream.Options{ Timeout: timeout, PreferIPv6: preferIPv6, } boots, err = aghnet.ParseBootstraps(bootstraps, opts) if err != nil { // Don't wrap the error, since it's informative enough as is. return nil, nil, err } // TODO(e.burkov): Add system hosts resolver here. var bootstrap upstream.ParallelResolver for _, r := range boots { bootstrap = append(bootstrap, upstream.NewCachingResolver(r)) } upstreams = make([]upstream.Upstream, len(upsStrs)) for i, upsStr := range upsStrs { upstreams[i], err = upstream.AddressToUpstream(upsStr, &upstream.Options{ Bootstrap: bootstrap, Timeout: timeout, PreferIPv6: preferIPv6, }) if err != nil { return nil, boots, fmt.Errorf("upstream at index %d: %w", i, err) } } return upstreams, boots, nil } // tcpAddrs converts []netip.AddrPort into []*net.TCPAddr. func tcpAddrs(addrPorts []netip.AddrPort) (tcpAddrs []*net.TCPAddr) { if addrPorts == nil { return nil } tcpAddrs = make([]*net.TCPAddr, len(addrPorts)) for i, a := range addrPorts { tcpAddrs[i] = net.TCPAddrFromAddrPort(a) } return tcpAddrs } // udpAddrs converts []netip.AddrPort into []*net.UDPAddr. func udpAddrs(addrPorts []netip.AddrPort) (udpAddrs []*net.UDPAddr) { if addrPorts == nil { return nil } udpAddrs = make([]*net.UDPAddr, len(addrPorts)) for i, a := range addrPorts { udpAddrs[i] = net.UDPAddrFromAddrPort(a) } return udpAddrs } // type check var _ agh.Service = (*Service)(nil) // Start implements the [agh.Service] interface for *Service. svc may be nil. // After Start exits, all DNS servers have tried to start, but there is no // guarantee that they did. Errors from the servers are written to the log. func (svc *Service) Start() (err error) { if svc == nil { return nil } defer func() { // TODO(a.garipov): [proxy.Proxy.Start] doesn't actually have any way to // tell when all servers are actually up, so at best this is merely an // assumption. svc.running.Store(err == nil) }() return svc.proxy.Start(context.Background()) } // Shutdown implements the [agh.Service] interface for *Service. svc may be // nil. func (svc *Service) Shutdown(ctx context.Context) (err error) { if svc == nil { return nil } errs := []error{ svc.proxy.Shutdown(ctx), } for _, b := range svc.bootstrapResolvers { errs = append(errs, errors.Annotate(b.Close(), "closing bootstrap %s: %w", b.Address())) } return errors.Join(errs...) } // Config returns the current configuration of the web service. Config must not // be called simultaneously with Start. If svc was initialized with ":0" // addresses, addrs will not return the actual bound ports until Start is // finished. func (svc *Service) Config() (c *Config) { // TODO(a.garipov): Do we need to get the TCP addresses separately? var addrs []netip.AddrPort if svc.running.Load() { udpAddrs := svc.proxy.Addrs(proxy.ProtoUDP) addrs = make([]netip.AddrPort, len(udpAddrs)) for i, a := range udpAddrs { addrs[i] = a.(*net.UDPAddr).AddrPort() } } else { conf := svc.proxy.Config udpAddrs := conf.UDPListenAddr addrs = make([]netip.AddrPort, len(udpAddrs)) for i, a := range udpAddrs { addrs[i] = a.AddrPort() } } c = &Config{ Addresses: addrs, BootstrapServers: svc.bootstraps, UpstreamServers: svc.upstreams, DNS64Prefixes: svc.dns64Prefixes, UpstreamTimeout: svc.upsTimeout, BootstrapPreferIPv6: svc.bootstrapPreferIPv6, UseDNS64: svc.useDNS64, } return c } ```
/content/code_sandbox/internal/next/dnssvc/dnssvc.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,790
```go package dnssvc import ( "net/netip" "time" ) // Config is the AdGuard Home DNS service configuration structure. // // TODO(a.garipov): Add timeout for incoming requests. type Config struct { // Addresses are the addresses on which to serve plain DNS queries. Addresses []netip.AddrPort // BootstrapServers are the addresses of DNS servers used for bootstrapping // the upstream DNS server addresses. BootstrapServers []string // UpstreamServers are the upstream DNS server addresses to use. UpstreamServers []string // DNS64Prefixes is a slice of NAT64 prefixes to be used for DNS64. See // also [Config.UseDNS64]. DNS64Prefixes []netip.Prefix // UpstreamTimeout is the timeout for upstream requests. UpstreamTimeout time.Duration // BootstrapPreferIPv6, if true, instructs the bootstrapper to prefer IPv6 // addresses to IPv4 ones when bootstrapping. BootstrapPreferIPv6 bool // UseDNS64, if true, enables DNS64 protection for incoming requests. UseDNS64 bool } ```
/content/code_sandbox/internal/next/dnssvc/config.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
248
```go package websvc // Path constants const ( PathRoot = "/" PathFrontend = "/*filepath" PathHealthCheck = "/health-check" PathV1SettingsAll = "/api/v1/settings/all" PathV1SettingsDNS = "/api/v1/settings/dns" PathV1SettingsHTTP = "/api/v1/settings/http" PathV1SystemInfo = "/api/v1/system/info" ) ```
/content/code_sandbox/internal/next/websvc/path.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
89
```go package websvc import ( "net" "sync" "sync/atomic" "testing" "github.com/AdguardTeam/golibs/testutil/fakenet" "github.com/stretchr/testify/assert" ) func TestWaitListener_Accept(t *testing.T) { var accepted atomic.Bool var l net.Listener = &fakenet.Listener{ OnAccept: func() (conn net.Conn, err error) { accepted.Store(true) return nil, nil }, OnAddr: func() (addr net.Addr) { panic("not implemented") }, OnClose: func() (err error) { panic("not implemented") }, } wg := &sync.WaitGroup{} wg.Add(1) go func() { var wrapper net.Listener = &waitListener{ Listener: l, firstAcceptWG: wg, } _, _ = wrapper.Accept() }() wg.Wait() assert.Eventually(t, accepted.Load, testTimeout, testTimeout/10) } ```
/content/code_sandbox/internal/next/websvc/waitlistener_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
215
```go package websvc_test import ( "crypto/tls" "encoding/json" "net/http" "net/netip" "net/url" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestService_HandleGetSettingsAll(t *testing.T) { // TODO(a.garipov): Add all currently supported parameters. wantDNS := &websvc.HTTPAPIDNSSettings{ Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:53")}, BootstrapServers: []string{"94.140.14.140", "94.140.14.141"}, UpstreamServers: []string{"94.140.14.14", "1.1.1.1"}, UpstreamTimeout: aghhttp.JSONDuration(1 * time.Second), BootstrapPreferIPv6: true, } wantWeb := &websvc.HTTPAPIHTTPSettings{ Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:80")}, SecureAddresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:443")}, Timeout: aghhttp.JSONDuration(5 * time.Second), ForceHTTPS: true, } confMgr := newConfigManager() confMgr.onDNS = func() (s agh.ServiceWithConfig[*dnssvc.Config]) { c, err := dnssvc.New(&dnssvc.Config{ Addresses: wantDNS.Addresses, UpstreamServers: wantDNS.UpstreamServers, BootstrapServers: wantDNS.BootstrapServers, UpstreamTimeout: time.Duration(wantDNS.UpstreamTimeout), BootstrapPreferIPv6: true, }) require.NoError(t, err) return c } svc, err := websvc.New(&websvc.Config{ Pprof: &websvc.PprofConfig{ Enabled: false, }, TLS: &tls.Config{ Certificates: []tls.Certificate{{}}, }, Addresses: wantWeb.Addresses, SecureAddresses: wantWeb.SecureAddresses, Timeout: time.Duration(wantWeb.Timeout), ForceHTTPS: true, }) require.NoError(t, err) confMgr.onWeb = func() (s agh.ServiceWithConfig[*websvc.Config]) { return svc } _, addr := newTestServer(t, confMgr) u := &url.URL{ Scheme: "http", Host: addr.String(), Path: websvc.PathV1SettingsAll, } body := httpGet(t, u, http.StatusOK) resp := &websvc.RespGetV1SettingsAll{} err = json.Unmarshal(body, resp) require.NoError(t, err) assert.Equal(t, wantDNS, resp.DNS) assert.Equal(t, wantWeb, resp.HTTP) } ```
/content/code_sandbox/internal/next/websvc/settings_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
723
```go package websvc_test import ( "encoding/json" "net/http" "net/url" "runtime" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestService_handleGetV1SystemInfo(t *testing.T) { confMgr := newConfigManager() _, addr := newTestServer(t, confMgr) u := &url.URL{ Scheme: "http", Host: addr.String(), Path: websvc.PathV1SystemInfo, } body := httpGet(t, u, http.StatusOK) resp := &websvc.RespGetV1SystemInfo{} err := json.Unmarshal(body, resp) require.NoError(t, err) // TODO(a.garipov): Consider making version.Channel and version.Version // testable and test these better. assert.NotEmpty(t, resp.Channel) assert.Equal(t, resp.Arch, runtime.GOARCH) assert.Equal(t, resp.OS, runtime.GOOS) assert.Equal(t, testStart, time.Time(resp.Start)) } ```
/content/code_sandbox/internal/next/websvc/system_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
241
```go package websvc_test import ( "context" "encoding/json" "net/http" "net/netip" "net/url" "sync/atomic" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestService_HandlePatchSettingsDNS(t *testing.T) { wantDNS := &websvc.HTTPAPIDNSSettings{ Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.1.1:53")}, BootstrapServers: []string{"1.0.0.1"}, UpstreamServers: []string{"1.1.1.1"}, DNS64Prefixes: []netip.Prefix{netip.MustParsePrefix("1234::/64")}, UpstreamTimeout: aghhttp.JSONDuration(2 * time.Second), BootstrapPreferIPv6: true, UseDNS64: true, } var started atomic.Bool confMgr := newConfigManager() confMgr.onDNS = func() (s agh.ServiceWithConfig[*dnssvc.Config]) { return &aghtest.ServiceWithConfig[*dnssvc.Config]{ OnStart: func() (err error) { started.Store(true) return nil }, OnShutdown: func(_ context.Context) (err error) { panic("not implemented") }, OnConfig: func() (c *dnssvc.Config) { panic("not implemented") }, } } confMgr.onUpdateDNS = func(ctx context.Context, c *dnssvc.Config) (err error) { return nil } _, addr := newTestServer(t, confMgr) u := &url.URL{ Scheme: "http", Host: addr.String(), Path: websvc.PathV1SettingsDNS, } req := jobj{ "addresses": wantDNS.Addresses, "bootstrap_servers": wantDNS.BootstrapServers, "upstream_servers": wantDNS.UpstreamServers, "dns64_prefixes": wantDNS.DNS64Prefixes, "upstream_timeout": wantDNS.UpstreamTimeout, "bootstrap_prefer_ipv6": wantDNS.BootstrapPreferIPv6, "use_dns64": wantDNS.UseDNS64, } respBody := httpPatch(t, u, req, http.StatusOK) resp := &websvc.HTTPAPIDNSSettings{} err := json.Unmarshal(respBody, resp) require.NoError(t, err) assert.True(t, started.Load()) assert.Equal(t, wantDNS, resp) assert.Equal(t, wantDNS, resp) } ```
/content/code_sandbox/internal/next/websvc/dns_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
661
```go package websvc import ( "net/http" "runtime" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/version" ) // System Handlers // RespGetV1SystemInfo describes the response of the GET /api/v1/system/info // HTTP API. type RespGetV1SystemInfo struct { Arch string `json:"arch"` Channel string `json:"channel"` OS string `json:"os"` NewVersion string `json:"new_version,omitempty"` Start aghhttp.JSONTime `json:"start"` Version string `json:"version"` } // handleGetV1SystemInfo is the handler for the GET /api/v1/system/info HTTP // API. func (svc *Service) handleGetV1SystemInfo(w http.ResponseWriter, r *http.Request) { aghhttp.WriteJSONResponseOK(w, r, &RespGetV1SystemInfo{ Arch: runtime.GOARCH, Channel: version.Channel(), OS: runtime.GOOS, // TODO(a.garipov): Fill this when we have an updater. NewVersion: "", Start: aghhttp.JSONTime(svc.start), Version: version.Version(), }) } ```
/content/code_sandbox/internal/next/websvc/system.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
284
```go package websvc import "time" // testTimeout is the common timeout for tests. const testTimeout = 1 * time.Second ```
/content/code_sandbox/internal/next/websvc/websvc_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
29
```go package websvc import ( "encoding/json" "fmt" "net/http" "net/netip" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" ) // DNS Settings Handlers // ReqPatchSettingsDNS describes the request to the PATCH /api/v1/settings/dns // HTTP API. type ReqPatchSettingsDNS struct { // TODO(a.garipov): Add more as we go. Addresses []netip.AddrPort `json:"addresses"` BootstrapServers []string `json:"bootstrap_servers"` UpstreamServers []string `json:"upstream_servers"` DNS64Prefixes []netip.Prefix `json:"dns64_prefixes"` UpstreamTimeout aghhttp.JSONDuration `json:"upstream_timeout"` BootstrapPreferIPv6 bool `json:"bootstrap_prefer_ipv6"` UseDNS64 bool `json:"use_dns64"` } // HTTPAPIDNSSettings are the DNS settings as used by the HTTP API. See the // DnsSettings object in the OpenAPI specification. type HTTPAPIDNSSettings struct { // TODO(a.garipov): Add more as we go. Addresses []netip.AddrPort `json:"addresses"` BootstrapServers []string `json:"bootstrap_servers"` UpstreamServers []string `json:"upstream_servers"` DNS64Prefixes []netip.Prefix `json:"dns64_prefixes"` UpstreamTimeout aghhttp.JSONDuration `json:"upstream_timeout"` BootstrapPreferIPv6 bool `json:"bootstrap_prefer_ipv6"` UseDNS64 bool `json:"use_dns64"` } // handlePatchSettingsDNS is the handler for the PATCH /api/v1/settings/dns HTTP // API. func (svc *Service) handlePatchSettingsDNS(w http.ResponseWriter, r *http.Request) { req := &ReqPatchSettingsDNS{ Addresses: []netip.AddrPort{}, BootstrapServers: []string{}, UpstreamServers: []string{}, } // TODO(a.garipov): Validate nulls and proper JSON patch. err := json.NewDecoder(r.Body).Decode(&req) if err != nil { aghhttp.WriteJSONResponseError(w, r, fmt.Errorf("decoding: %w", err)) return } newConf := &dnssvc.Config{ Addresses: req.Addresses, BootstrapServers: req.BootstrapServers, UpstreamServers: req.UpstreamServers, DNS64Prefixes: req.DNS64Prefixes, UpstreamTimeout: time.Duration(req.UpstreamTimeout), BootstrapPreferIPv6: req.BootstrapPreferIPv6, UseDNS64: req.UseDNS64, } ctx := r.Context() err = svc.confMgr.UpdateDNS(ctx, newConf) if err != nil { aghhttp.WriteJSONResponseError(w, r, fmt.Errorf("updating: %w", err)) return } newSvc := svc.confMgr.DNS() err = newSvc.Start() if err != nil { aghhttp.WriteJSONResponseError(w, r, fmt.Errorf("starting new service: %w", err)) return } aghhttp.WriteJSONResponseOK(w, r, &HTTPAPIDNSSettings{ Addresses: newConf.Addresses, BootstrapServers: newConf.BootstrapServers, UpstreamServers: newConf.UpstreamServers, DNS64Prefixes: newConf.DNS64Prefixes, UpstreamTimeout: aghhttp.JSONDuration(newConf.UpstreamTimeout), BootstrapPreferIPv6: newConf.BootstrapPreferIPv6, UseDNS64: newConf.UseDNS64, }) } ```
/content/code_sandbox/internal/next/websvc/dns.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
847
```go package websvc import ( "net/http" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" ) // All Settings Handlers // RespGetV1SettingsAll describes the response of the GET /api/v1/settings/all // HTTP API. type RespGetV1SettingsAll struct { // TODO(a.garipov): Add more as we go. DNS *HTTPAPIDNSSettings `json:"dns"` HTTP *HTTPAPIHTTPSettings `json:"http"` } // handleGetSettingsAll is the handler for the GET /api/v1/settings/all HTTP // API. func (svc *Service) handleGetSettingsAll(w http.ResponseWriter, r *http.Request) { dnsSvc := svc.confMgr.DNS() dnsConf := dnsSvc.Config() webSvc := svc.confMgr.Web() httpConf := webSvc.Config() // TODO(a.garipov): Add all currently supported parameters. aghhttp.WriteJSONResponseOK(w, r, &RespGetV1SettingsAll{ DNS: &HTTPAPIDNSSettings{ Addresses: dnsConf.Addresses, BootstrapServers: dnsConf.BootstrapServers, UpstreamServers: dnsConf.UpstreamServers, DNS64Prefixes: dnsConf.DNS64Prefixes, UpstreamTimeout: aghhttp.JSONDuration(dnsConf.UpstreamTimeout), BootstrapPreferIPv6: dnsConf.BootstrapPreferIPv6, UseDNS64: dnsConf.UseDNS64, }, HTTP: &HTTPAPIHTTPSettings{ Addresses: httpConf.Addresses, SecureAddresses: httpConf.SecureAddresses, Timeout: aghhttp.JSONDuration(httpConf.Timeout), ForceHTTPS: httpConf.ForceHTTPS, }, }) } ```
/content/code_sandbox/internal/next/websvc/settings.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
394
```go package websvc import ( "net" "sync" ) // Wait Listener // waitListener is a wrapper around a listener that also calls wg.Done() on the // first call to Accept. It is useful in situations where it is important to // catch the precise moment of the first call to Accept, for example when // starting an HTTP server. // // TODO(a.garipov): Move to aghnet? type waitListener struct { net.Listener firstAcceptWG *sync.WaitGroup firstAcceptOnce sync.Once } // type check var _ net.Listener = (*waitListener)(nil) // Accept implements the [net.Listener] interface for *waitListener. func (l *waitListener) Accept() (conn net.Conn, err error) { l.firstAcceptOnce.Do(l.firstAcceptWG.Done) return l.Listener.Accept() } ```
/content/code_sandbox/internal/next/websvc/waitlistener.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
179
```go package websvc import ( "context" "encoding/json" "fmt" "net/http" "net/netip" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/golibs/log" ) // HTTP Settings Handlers // ReqPatchSettingsHTTP describes the request to the PATCH /api/v1/settings/http // HTTP API. type ReqPatchSettingsHTTP struct { // TODO(a.garipov): Add more as we go. // // TODO(a.garipov): Add wait time. Addresses []netip.AddrPort `json:"addresses"` SecureAddresses []netip.AddrPort `json:"secure_addresses"` Timeout aghhttp.JSONDuration `json:"timeout"` } // HTTPAPIHTTPSettings are the HTTP settings as used by the HTTP API. See the // HttpSettings object in the OpenAPI specification. type HTTPAPIHTTPSettings struct { // TODO(a.garipov): Add more as we go. Addresses []netip.AddrPort `json:"addresses"` SecureAddresses []netip.AddrPort `json:"secure_addresses"` Timeout aghhttp.JSONDuration `json:"timeout"` ForceHTTPS bool `json:"force_https"` } // handlePatchSettingsHTTP is the handler for the PATCH /api/v1/settings/http // HTTP API. func (svc *Service) handlePatchSettingsHTTP(w http.ResponseWriter, r *http.Request) { req := &ReqPatchSettingsHTTP{} // TODO(a.garipov): Validate nulls and proper JSON patch. err := json.NewDecoder(r.Body).Decode(&req) if err != nil { aghhttp.WriteJSONResponseError(w, r, fmt.Errorf("decoding: %w", err)) return } newConf := &Config{ Pprof: &PprofConfig{ Port: svc.pprofPort, Enabled: svc.pprof != nil, }, ConfigManager: svc.confMgr, Frontend: svc.frontend, TLS: svc.tls, Addresses: req.Addresses, SecureAddresses: req.SecureAddresses, Timeout: time.Duration(req.Timeout), ForceHTTPS: svc.forceHTTPS, } aghhttp.WriteJSONResponseOK(w, r, &HTTPAPIHTTPSettings{ Addresses: newConf.Addresses, SecureAddresses: newConf.SecureAddresses, Timeout: aghhttp.JSONDuration(newConf.Timeout), ForceHTTPS: newConf.ForceHTTPS, }) cancelUpd := func() {} updCtx := context.Background() ctx := r.Context() if deadline, ok := ctx.Deadline(); ok { updCtx, cancelUpd = context.WithDeadline(updCtx, deadline) } // Launch the new HTTP service in a separate goroutine to let this handler // finish and thus, this server to shutdown. go svc.relaunch(updCtx, cancelUpd, newConf) } // relaunch updates the web service in the configuration manager and starts it. // It is intended to be used as a goroutine. func (svc *Service) relaunch(ctx context.Context, cancel context.CancelFunc, newConf *Config) { defer log.OnPanic("websvc: relaunching") defer cancel() err := svc.confMgr.UpdateWeb(ctx, newConf) if err != nil { log.Error("websvc: updating web: %s", err) return } // TODO(a.garipov): Consider better ways to do this. const maxUpdDur = 5 * time.Second updStart := time.Now() var newSvc agh.ServiceWithConfig[*Config] for newSvc = svc.confMgr.Web(); newSvc == svc; { if time.Since(updStart) >= maxUpdDur { log.Error("websvc: failed to update svc after %s", maxUpdDur) return } log.Debug("websvc: waiting for new websvc to be configured") time.Sleep(100 * time.Millisecond) } err = newSvc.Start() if err != nil { log.Error("websvc: new svc failed to start with error: %s", err) } } ```
/content/code_sandbox/internal/next/websvc/http.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
933
```go package websvc_test import ( "bytes" "context" "encoding/json" "io" "io/fs" "net/http" "net/netip" "net/url" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/testutil/fakefs" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } // testTimeout is the common timeout for tests. const testTimeout = 1 * time.Second // testStart is the server start value for tests. var testStart = time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC) // type check var _ websvc.ConfigManager = (*configManager)(nil) // configManager is a [websvc.ConfigManager] for tests. type configManager struct { onDNS func() (svc agh.ServiceWithConfig[*dnssvc.Config]) onWeb func() (svc agh.ServiceWithConfig[*websvc.Config]) onUpdateDNS func(ctx context.Context, c *dnssvc.Config) (err error) onUpdateWeb func(ctx context.Context, c *websvc.Config) (err error) } // DNS implements the [websvc.ConfigManager] interface for *configManager. func (m *configManager) DNS() (svc agh.ServiceWithConfig[*dnssvc.Config]) { return m.onDNS() } // Web implements the [websvc.ConfigManager] interface for *configManager. func (m *configManager) Web() (svc agh.ServiceWithConfig[*websvc.Config]) { return m.onWeb() } // UpdateDNS implements the [websvc.ConfigManager] interface for *configManager. func (m *configManager) UpdateDNS(ctx context.Context, c *dnssvc.Config) (err error) { return m.onUpdateDNS(ctx, c) } // UpdateWeb implements the [websvc.ConfigManager] interface for *configManager. func (m *configManager) UpdateWeb(ctx context.Context, c *websvc.Config) (err error) { return m.onUpdateWeb(ctx, c) } // newConfigManager returns a *configManager all methods of which panic. func newConfigManager() (m *configManager) { return &configManager{ onDNS: func() (svc agh.ServiceWithConfig[*dnssvc.Config]) { panic("not implemented") }, onWeb: func() (svc agh.ServiceWithConfig[*websvc.Config]) { panic("not implemented") }, onUpdateDNS: func(_ context.Context, _ *dnssvc.Config) (err error) { panic("not implemented") }, onUpdateWeb: func(_ context.Context, _ *websvc.Config) (err error) { panic("not implemented") }, } } // newTestServer creates and starts a new web service instance as well as its // sole address. It also registers a cleanup procedure, which shuts the // instance down. // // TODO(a.garipov): Use svc or remove it. func newTestServer( t testing.TB, confMgr websvc.ConfigManager, ) (svc *websvc.Service, addr netip.AddrPort) { t.Helper() c := &websvc.Config{ Pprof: &websvc.PprofConfig{ Enabled: false, }, ConfigManager: confMgr, Frontend: &fakefs.FS{ OnOpen: func(_ string) (_ fs.File, _ error) { return nil, fs.ErrNotExist }, }, TLS: nil, Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:0")}, SecureAddresses: nil, Timeout: testTimeout, Start: testStart, ForceHTTPS: false, } svc, err := websvc.New(c) require.NoError(t, err) err = svc.Start() require.NoError(t, err) testutil.CleanupAndRequireSuccess(t, func() (err error) { return svc.Shutdown(testutil.ContextWithTimeout(t, testTimeout)) }) c = svc.Config() require.NotNil(t, c) require.Len(t, c.Addresses, 1) return svc, c.Addresses[0] } // jobj is a utility alias for JSON objects. type jobj map[string]any // httpGet is a helper that performs an HTTP GET request and returns the body of // the response as well as checks that the status code is correct. // // TODO(a.garipov): Add helpers for other methods. func httpGet(t testing.TB, u *url.URL, wantCode int) (body []byte) { t.Helper() req, err := http.NewRequest(http.MethodGet, u.String(), nil) require.NoErrorf(t, err, "creating req") httpCli := &http.Client{ Timeout: testTimeout, } resp, err := httpCli.Do(req) require.NoErrorf(t, err, "performing req") require.Equal(t, wantCode, resp.StatusCode) testutil.CleanupAndRequireSuccess(t, resp.Body.Close) body, err = io.ReadAll(resp.Body) require.NoErrorf(t, err, "reading body") return body } // httpPatch is a helper that performs an HTTP PATCH request with JSON-encoded // reqBody as the request body and returns the body of the response as well as // checks that the status code is correct. // // TODO(a.garipov): Add helpers for other methods. func httpPatch(t testing.TB, u *url.URL, reqBody any, wantCode int) (body []byte) { t.Helper() b, err := json.Marshal(reqBody) require.NoErrorf(t, err, "marshaling reqBody") req, err := http.NewRequest(http.MethodPatch, u.String(), bytes.NewReader(b)) require.NoErrorf(t, err, "creating req") httpCli := &http.Client{ Timeout: testTimeout, } resp, err := httpCli.Do(req) require.NoErrorf(t, err, "performing req") require.Equal(t, wantCode, resp.StatusCode) testutil.CleanupAndRequireSuccess(t, resp.Body.Close) body, err = io.ReadAll(resp.Body) require.NoErrorf(t, err, "reading body") return body } func TestService_Start_getHealthCheck(t *testing.T) { confMgr := newConfigManager() _, addr := newTestServer(t, confMgr) u := &url.URL{ Scheme: "http", Host: addr.String(), Path: websvc.PathHealthCheck, } body := httpGet(t, u, http.StatusOK) assert.Equal(t, []byte("OK"), body) } ```
/content/code_sandbox/internal/next/websvc/websvc_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,498
```go package websvc_test import ( "context" "crypto/tls" "encoding/json" "net/http" "net/netip" "net/url" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestService_HandlePatchSettingsHTTP(t *testing.T) { wantWeb := &websvc.HTTPAPIHTTPSettings{ Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.1.1:80")}, SecureAddresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.1.1:443")}, Timeout: aghhttp.JSONDuration(10 * time.Second), ForceHTTPS: false, } svc, err := websvc.New(&websvc.Config{ Pprof: &websvc.PprofConfig{ Enabled: false, }, TLS: &tls.Config{ Certificates: []tls.Certificate{{}}, }, Addresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:80")}, SecureAddresses: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:443")}, Timeout: 5 * time.Second, ForceHTTPS: true, }) require.NoError(t, err) confMgr := newConfigManager() confMgr.onWeb = func() (s agh.ServiceWithConfig[*websvc.Config]) { return svc } confMgr.onUpdateWeb = func(ctx context.Context, c *websvc.Config) (err error) { return nil } _, addr := newTestServer(t, confMgr) u := &url.URL{ Scheme: "http", Host: addr.String(), Path: websvc.PathV1SettingsHTTP, } req := jobj{ "addresses": wantWeb.Addresses, "secure_addresses": wantWeb.SecureAddresses, "timeout": wantWeb.Timeout, "force_https": wantWeb.ForceHTTPS, } respBody := httpPatch(t, u, req, http.StatusOK) resp := &websvc.HTTPAPIHTTPSettings{} err = json.Unmarshal(respBody, resp) require.NoError(t, err) assert.Equal(t, wantWeb, resp) } ```
/content/code_sandbox/internal/next/websvc/http_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
554
```go // Package websvc contains the AdGuard Home HTTP API service. // // NOTE: Packages other than cmd must not import this package, as it imports // most other packages. // // TODO(a.garipov): Add tests. package websvc import ( "context" "crypto/tls" "fmt" "io" "io/fs" "net" "net/http" "net/netip" "runtime" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/mathutil" "github.com/AdguardTeam/golibs/netutil/httputil" httptreemux "github.com/dimfeld/httptreemux/v5" ) // ConfigManager is the configuration manager interface. type ConfigManager interface { DNS() (svc agh.ServiceWithConfig[*dnssvc.Config]) Web() (svc agh.ServiceWithConfig[*Config]) UpdateDNS(ctx context.Context, c *dnssvc.Config) (err error) UpdateWeb(ctx context.Context, c *Config) (err error) } // Service is the AdGuard Home web service. A nil *Service is a valid // [agh.Service] that does nothing. type Service struct { confMgr ConfigManager frontend fs.FS tls *tls.Config pprof *http.Server start time.Time overrideAddr netip.AddrPort servers []*http.Server timeout time.Duration pprofPort uint16 forceHTTPS bool } // New returns a new properly initialized *Service. If c is nil, svc is a nil // *Service that does nothing. The fields of c must not be modified after // calling New. // // TODO(a.garipov): Get rid of this special handling of nil or explain it // better. func New(c *Config) (svc *Service, err error) { if c == nil { return nil, nil } svc = &Service{ confMgr: c.ConfigManager, frontend: c.Frontend, tls: c.TLS, start: c.Start, overrideAddr: c.OverrideAddress, timeout: c.Timeout, forceHTTPS: c.ForceHTTPS, } mux := newMux(svc) if svc.overrideAddr != (netip.AddrPort{}) { svc.servers = []*http.Server{newSrv(svc.overrideAddr, nil, mux, c.Timeout)} } else { for _, a := range c.Addresses { svc.servers = append(svc.servers, newSrv(a, nil, mux, c.Timeout)) } for _, a := range c.SecureAddresses { svc.servers = append(svc.servers, newSrv(a, c.TLS, mux, c.Timeout)) } } svc.setupPprof(c.Pprof) return svc, nil } // setupPprof sets the pprof properties of svc. func (svc *Service) setupPprof(c *PprofConfig) { if !c.Enabled { // Set to zero explicitly in case pprof used to be enabled before a // reconfiguration took place. runtime.SetBlockProfileRate(0) runtime.SetMutexProfileFraction(0) return } runtime.SetBlockProfileRate(1) runtime.SetMutexProfileFraction(1) pprofMux := http.NewServeMux() httputil.RoutePprof(pprofMux) svc.pprofPort = c.Port addr := netip.AddrPortFrom(netip.AddrFrom4([4]byte{127, 0, 0, 1}), c.Port) // TODO(a.garipov): Consider making pprof timeout configurable. svc.pprof = newSrv(addr, nil, pprofMux, 10*time.Minute) } // newSrv returns a new *http.Server with the given parameters. func newSrv( addr netip.AddrPort, tlsConf *tls.Config, h http.Handler, timeout time.Duration, ) (srv *http.Server) { addrStr := addr.String() srv = &http.Server{ Addr: addrStr, Handler: h, TLSConfig: tlsConf, ReadTimeout: timeout, WriteTimeout: timeout, IdleTimeout: timeout, ReadHeaderTimeout: timeout, } if tlsConf == nil { srv.ErrorLog = log.StdLog("websvc: plain http: "+addrStr, log.ERROR) } else { srv.ErrorLog = log.StdLog("websvc: https: "+addrStr, log.ERROR) } return srv } // newMux returns a new HTTP request multiplexer for the AdGuard Home web // service. func newMux(svc *Service) (mux *httptreemux.ContextMux) { mux = httptreemux.NewContextMux() routes := []struct { handler http.HandlerFunc method string pattern string isJSON bool }{{ handler: svc.handleGetHealthCheck, method: http.MethodGet, pattern: PathHealthCheck, isJSON: false, }, { handler: http.FileServer(http.FS(svc.frontend)).ServeHTTP, method: http.MethodGet, pattern: PathFrontend, isJSON: false, }, { handler: http.FileServer(http.FS(svc.frontend)).ServeHTTP, method: http.MethodGet, pattern: PathRoot, isJSON: false, }, { handler: svc.handleGetSettingsAll, method: http.MethodGet, pattern: PathV1SettingsAll, isJSON: true, }, { handler: svc.handlePatchSettingsDNS, method: http.MethodPatch, pattern: PathV1SettingsDNS, isJSON: true, }, { handler: svc.handlePatchSettingsHTTP, method: http.MethodPatch, pattern: PathV1SettingsHTTP, isJSON: true, }, { handler: svc.handleGetV1SystemInfo, method: http.MethodGet, pattern: PathV1SystemInfo, isJSON: true, }} for _, r := range routes { var hdlr http.Handler if r.isJSON { hdlr = jsonMw(r.handler) } else { hdlr = r.handler } mux.Handle(r.method, r.pattern, logMw(hdlr)) } return mux } // addrs returns all addresses on which this server serves the HTTP API. addrs // must not be called simultaneously with Start. If svc was initialized with // ":0" addresses, addrs will not return the actual bound ports until Start is // finished. func (svc *Service) addrs() (addrs, secureAddrs []netip.AddrPort) { if svc.overrideAddr != (netip.AddrPort{}) { return []netip.AddrPort{svc.overrideAddr}, nil } for _, srv := range svc.servers { // Use MustParseAddrPort, since no errors should technically happen // here, because all servers must have a valid address. addrPort := netip.MustParseAddrPort(srv.Addr) // [srv.Serve] will set TLSConfig to an almost empty value, so, instead // of relying only on the nilness of TLSConfig, check the length of the // certificates field as well. if srv.TLSConfig == nil || len(srv.TLSConfig.Certificates) == 0 { addrs = append(addrs, addrPort) } else { secureAddrs = append(secureAddrs, addrPort) } } return addrs, secureAddrs } // handleGetHealthCheck is the handler for the GET /health-check HTTP API. func (svc *Service) handleGetHealthCheck(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "OK") } // type check var _ agh.Service = (*Service)(nil) // Start implements the [agh.Service] interface for *Service. svc may be nil. // After Start exits, all HTTP servers have tried to start, possibly failing and // writing error messages to the log. func (svc *Service) Start() (err error) { if svc == nil { return nil } pprofEnabled := svc.pprof != nil srvNum := len(svc.servers) + mathutil.BoolToNumber[int](pprofEnabled) wg := &sync.WaitGroup{} wg.Add(srvNum) for _, srv := range svc.servers { go serve(srv, wg) } if pprofEnabled { go serve(svc.pprof, wg) } wg.Wait() return nil } // serve starts and runs srv and writes all errors into its log. func serve(srv *http.Server, wg *sync.WaitGroup) { addr := srv.Addr defer log.OnPanic(addr) var proto string var l net.Listener var err error if srv.TLSConfig == nil { proto = "http" l, err = net.Listen("tcp", addr) } else { proto = "https" l, err = tls.Listen("tcp", addr, srv.TLSConfig) } if err != nil { srv.ErrorLog.Printf("starting srv %s: binding: %s", addr, err) } // Update the server's address in case the address had the port zero, which // would mean that a random available port was automatically chosen. srv.Addr = l.Addr().String() log.Info("websvc: starting srv %s://%s", proto, srv.Addr) l = &waitListener{ Listener: l, firstAcceptWG: wg, } err = srv.Serve(l) if err != nil && !errors.Is(err, http.ErrServerClosed) { srv.ErrorLog.Printf("starting srv %s: %s", addr, err) } } // Shutdown implements the [agh.Service] interface for *Service. svc may be // nil. func (svc *Service) Shutdown(ctx context.Context) (err error) { if svc == nil { return nil } defer func() { err = errors.Annotate(err, "shutting down: %w") }() var errs []error for _, srv := range svc.servers { shutdownErr := srv.Shutdown(ctx) if shutdownErr != nil { errs = append(errs, fmt.Errorf("srv %s: %w", srv.Addr, shutdownErr)) } } if svc.pprof != nil { shutdownErr := svc.pprof.Shutdown(ctx) if shutdownErr != nil { errs = append(errs, fmt.Errorf("pprof srv %s: %w", svc.pprof.Addr, shutdownErr)) } } return errors.Join(errs...) } ```
/content/code_sandbox/internal/next/websvc/websvc.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,444
```go package websvc import ( "crypto/tls" "io/fs" "net/netip" "time" ) // Config is the AdGuard Home web service configuration structure. type Config struct { // Pprof is the configuration for the pprof debug API. It must not be nil. Pprof *PprofConfig // ConfigManager is used to show information about services as well as // dynamically reconfigure them. ConfigManager ConfigManager // Frontend is the filesystem with the frontend and other statically // compiled files. Frontend fs.FS // TLS is the optional TLS configuration. If TLS is not nil, // SecureAddresses must not be empty. TLS *tls.Config // Start is the time of start of AdGuard Home. Start time.Time // OverrideAddress is the initial or override address for the HTTP API. If // set, it is used instead of [Addresses] and [SecureAddresses]. OverrideAddress netip.AddrPort // Addresses are the addresses on which to serve the plain HTTP API. Addresses []netip.AddrPort // SecureAddresses are the addresses on which to serve the HTTPS API. If // SecureAddresses is not empty, TLS must not be nil. SecureAddresses []netip.AddrPort // Timeout is the timeout for all server operations. Timeout time.Duration // ForceHTTPS tells if all requests to Addresses should be redirected to a // secure address instead. // // TODO(a.garipov): Use; define rules, which address to redirect to. ForceHTTPS bool } // PprofConfig is the configuration for the pprof debug API. type PprofConfig struct { Port uint16 `yaml:"port"` Enabled bool `yaml:"enabled"` } // Config returns the current configuration of the web service. Config must not // be called simultaneously with Start. If svc was initialized with ":0" // addresses, addrs will not return the actual bound ports until Start is // finished. func (svc *Service) Config() (c *Config) { c = &Config{ Pprof: &PprofConfig{ Port: svc.pprofPort, Enabled: svc.pprof != nil, }, ConfigManager: svc.confMgr, TLS: svc.tls, // Leave Addresses and SecureAddresses empty and get the actual // addresses that include the :0 ones later. Start: svc.start, Timeout: svc.timeout, ForceHTTPS: svc.forceHTTPS, } c.Addresses, c.SecureAddresses = svc.addrs() return c } ```
/content/code_sandbox/internal/next/websvc/config.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
569
```go package configmgr import ( "fmt" "github.com/AdguardTeam/golibs/timeutil" "golang.org/x/exp/constraints" ) // numberOrDuration is the constraint for integer types along with // timeutil.Duration. type numberOrDuration interface { constraints.Integer | timeutil.Duration } // newMustBePositiveError returns an error about the value that must be positive // but isn't. prop is the name of the property to mention in the error message. // // TODO(a.garipov): Consider moving such helpers to golibs and use in AdGuardDNS // as well. func newMustBePositiveError[T numberOrDuration](prop string, v T) (err error) { if s, ok := any(v).(fmt.Stringer); ok { return fmt.Errorf("%s must be positive, got %s", prop, s) } return fmt.Errorf("%s must be positive, got %d", prop, v) } ```
/content/code_sandbox/internal/next/configmgr/error.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
204
```go package websvc import ( "net/http" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/golibs/httphdr" "github.com/AdguardTeam/golibs/log" ) // Middlewares // jsonMw sets the content type of the response to application/json. func jsonMw(h http.Handler) (wrapped http.HandlerFunc) { f := func(w http.ResponseWriter, r *http.Request) { w.Header().Set(httphdr.ContentType, aghhttp.HdrValApplicationJSON) h.ServeHTTP(w, r) } return http.HandlerFunc(f) } // logMw logs the queries with level debug. func logMw(h http.Handler) (wrapped http.HandlerFunc) { f := func(w http.ResponseWriter, r *http.Request) { start := time.Now() m, u := r.Method, r.RequestURI log.Debug("websvc: %s %s started", m, u) defer func() { log.Debug("websvc: %s %s finished in %s", m, u, time.Since(start)) }() h.ServeHTTP(w, r) } return http.HandlerFunc(f) } ```
/content/code_sandbox/internal/next/websvc/middleware.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
259
```go package configmgr import ( "fmt" "net/netip" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/timeutil" ) // Configuration Structures // config is the top-level on-disk configuration structure. type config struct { DNS *dnsConfig `yaml:"dns"` HTTP *httpConfig `yaml:"http"` Log *logConfig `yaml:"log"` // TODO(a.garipov): Use. SchemaVersion int `yaml:"schema_version"` } const errNoConf errors.Error = "configuration not found" // validate returns an error if the configuration structure is invalid. func (c *config) validate() (err error) { if c == nil { return errNoConf } // TODO(a.garipov): Add more validations. // Keep this in the same order as the fields in the config. validators := []struct { validate func() (err error) name string }{{ validate: c.DNS.validate, name: "dns", }, { validate: c.HTTP.validate, name: "http", }, { validate: c.Log.validate, name: "log", }} for _, v := range validators { err = v.validate() if err != nil { return fmt.Errorf("%s: %w", v.name, err) } } return nil } // dnsConfig is the on-disk DNS configuration. type dnsConfig struct { Addresses []netip.AddrPort `yaml:"addresses"` BootstrapDNS []string `yaml:"bootstrap_dns"` UpstreamDNS []string `yaml:"upstream_dns"` DNS64Prefixes []netip.Prefix `yaml:"dns64_prefixes"` UpstreamTimeout timeutil.Duration `yaml:"upstream_timeout"` BootstrapPreferIPv6 bool `yaml:"bootstrap_prefer_ipv6"` UseDNS64 bool `yaml:"use_dns64"` } // validate returns an error if the DNS configuration structure is invalid. // // TODO(a.garipov): Add more validations. func (c *dnsConfig) validate() (err error) { // TODO(a.garipov): Add more validations. switch { case c == nil: return errNoConf case c.UpstreamTimeout.Duration <= 0: return newMustBePositiveError("upstream_timeout", c.UpstreamTimeout) default: return nil } } // httpConfig is the on-disk web API configuration. type httpConfig struct { Pprof *httpPprofConfig `yaml:"pprof"` // TODO(a.garipov): Document the configuration change. Addresses []netip.AddrPort `yaml:"addresses"` SecureAddresses []netip.AddrPort `yaml:"secure_addresses"` Timeout timeutil.Duration `yaml:"timeout"` ForceHTTPS bool `yaml:"force_https"` } // validate returns an error if the HTTP configuration structure is invalid. // // TODO(a.garipov): Add more validations. func (c *httpConfig) validate() (err error) { switch { case c == nil: return errNoConf case c.Timeout.Duration <= 0: return newMustBePositiveError("timeout", c.Timeout) default: return c.Pprof.validate() } } // httpPprofConfig is the on-disk pprof configuration. type httpPprofConfig struct { Port uint16 `yaml:"port"` Enabled bool `yaml:"enabled"` } // validate returns an error if the pprof configuration structure is invalid. func (c *httpPprofConfig) validate() (err error) { if c == nil { return errNoConf } return nil } // logConfig is the on-disk web API configuration. type logConfig struct { // TODO(a.garipov): Use. Verbose bool `yaml:"verbose"` } // validate returns an error if the HTTP configuration structure is invalid. // // TODO(a.garipov): Add more validations. func (c *logConfig) validate() (err error) { if c == nil { return errNoConf } return nil } ```
/content/code_sandbox/internal/next/configmgr/config.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
903
```go package cmd import ( "os" "strconv" "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/configmgr" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/osutil" "github.com/google/renameio/v2/maybe" ) // signalHandler processes incoming signals and shuts services down. type signalHandler struct { // confMgrConf contains the configuration parameters for the configuration // manager. confMgrConf *configmgr.Config // signal is the channel to which OS signals are sent. signal chan os.Signal // pidFile is the path to the file where to store the PID, if any. pidFile string // services are the services that are shut down before application exiting. services []agh.Service } // handle processes OS signals. func (h *signalHandler) handle() { defer log.OnPanic("signalHandler.handle") h.writePID() for sig := range h.signal { log.Info("sighdlr: received signal %q", sig) if aghos.IsReconfigureSignal(sig) { h.reconfigure() } else if osutil.IsShutdownSignal(sig) { status := h.shutdown() h.removePID() log.Info("sighdlr: exiting with status %d", status) os.Exit(status) } } } // reconfigure rereads the configuration file and updates and restarts services. func (h *signalHandler) reconfigure() { log.Info("sighdlr: reconfiguring adguard home") status := h.shutdown() if status != statusSuccess { log.Info("sighdlr: reconfiguring: exiting with status %d", status) os.Exit(status) } // TODO(a.garipov): This is a very rough way to do it. Some services can be // reconfigured without the full shutdown, and the error handling is // currently not the best. confMgr, err := newConfigMgr(h.confMgrConf) check(err) web := confMgr.Web() err = web.Start() check(err) dns := confMgr.DNS() err = dns.Start() check(err) h.services = []agh.Service{ dns, web, } log.Info("sighdlr: successfully reconfigured adguard home") } // Exit status constants. const ( statusSuccess = 0 statusError = 1 statusArgumentError = 2 ) // shutdown gracefully shuts down all services. func (h *signalHandler) shutdown() (status int) { ctx, cancel := ctxWithDefaultTimeout() defer cancel() status = statusSuccess log.Info("sighdlr: shutting down services") for i, service := range h.services { err := service.Shutdown(ctx) if err != nil { log.Error("sighdlr: shutting down service at index %d: %s", i, err) status = statusError } } return status } // newSignalHandler returns a new signalHandler that shuts down svcs. func newSignalHandler( confMgrConf *configmgr.Config, pidFile string, svcs ...agh.Service, ) (h *signalHandler) { h = &signalHandler{ confMgrConf: confMgrConf, signal: make(chan os.Signal, 1), pidFile: pidFile, services: svcs, } notifier := osutil.DefaultSignalNotifier{} osutil.NotifyShutdownSignal(notifier, h.signal) aghos.NotifyReconfigureSignal(h.signal) return h } // writePID writes the PID to the file, if needed. Any errors are reported to // log. func (h *signalHandler) writePID() { if h.pidFile == "" { return } // Use 8, since most PIDs will fit. data := make([]byte, 0, 8) data = strconv.AppendInt(data, int64(os.Getpid()), 10) data = append(data, '\n') err := maybe.WriteFile(h.pidFile, data, 0o644) if err != nil { log.Error("sighdlr: writing pidfile: %s", err) return } log.Debug("sighdlr: wrote pid to %q", h.pidFile) } // removePID removes the PID file, if any. func (h *signalHandler) removePID() { if h.pidFile == "" { return } err := os.Remove(h.pidFile) if err != nil { log.Error("sighdlr: removing pidfile: %s", err) return } log.Debug("sighdlr: removed pid at %q", h.pidFile) } ```
/content/code_sandbox/internal/next/cmd/signal.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,046
```go // Package configmgr defines the AdGuard Home on-disk configuration entities and // configuration manager. // // TODO(a.garipov): Add tests. package configmgr import ( "context" "fmt" "io/fs" "net/netip" "os" "slices" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/agh" "github.com/AdguardTeam/AdGuardHome/internal/next/dnssvc" "github.com/AdguardTeam/AdGuardHome/internal/next/websvc" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/timeutil" "github.com/google/renameio/v2/maybe" "gopkg.in/yaml.v3" ) // Configuration Manager // Manager handles full and partial changes in the configuration, persisting // them to disk if necessary. // // TODO(a.garipov): Support missing configs and default values. type Manager struct { // updMu makes sure that at most one reconfiguration is performed at a time. // updMu protects all fields below. updMu *sync.RWMutex // dns is the DNS service. dns *dnssvc.Service // Web is the Web API service. web *websvc.Service // current is the current configuration. current *config // fileName is the name of the configuration file. fileName string } // Validate returns an error if the configuration file with the given name does // not exist or is invalid. func Validate(fileName string) (err error) { conf, err := read(fileName) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } // Don't wrap the error, because it's informative enough as is. return conf.validate() } // Config contains the configuration parameters for the configuration manager. type Config struct { // Frontend is the filesystem with the frontend files. Frontend fs.FS // WebAddr is the initial or override address for the Web UI. It is not // written to the configuration file. WebAddr netip.AddrPort // Start is the time of start of AdGuard Home. Start time.Time // FileName is the path to the configuration file. FileName string } // New creates a new *Manager that persists changes to the file pointed to by // c.FileName. It reads the configuration file and populates the service // fields. c must not be nil. func New(ctx context.Context, c *Config) (m *Manager, err error) { conf, err := read(c.FileName) if err != nil { // Don't wrap the error, because it's informative enough as is. return nil, err } err = conf.validate() if err != nil { return nil, fmt.Errorf("validating config: %w", err) } m = &Manager{ updMu: &sync.RWMutex{}, current: conf, fileName: c.FileName, } err = m.assemble(ctx, conf, c.Frontend, c.WebAddr, c.Start) if err != nil { return nil, fmt.Errorf("creating config manager: %w", err) } return m, nil } // read reads and decodes configuration from the provided filename. func read(fileName string) (conf *config, err error) { defer func() { err = errors.Annotate(err, "reading config: %w") }() conf = &config{} f, err := os.Open(fileName) if err != nil { // Don't wrap the error, because it's informative enough as is. return nil, err } defer func() { err = errors.WithDeferred(err, f.Close()) }() err = yaml.NewDecoder(f).Decode(conf) if err != nil { // Don't wrap the error, because it's informative enough as is. return nil, err } return conf, nil } // assemble creates all services and puts them into the corresponding fields. // The fields of conf must not be modified after calling assemble. func (m *Manager) assemble( ctx context.Context, conf *config, frontend fs.FS, webAddr netip.AddrPort, start time.Time, ) (err error) { dnsConf := &dnssvc.Config{ Addresses: conf.DNS.Addresses, BootstrapServers: conf.DNS.BootstrapDNS, UpstreamServers: conf.DNS.UpstreamDNS, DNS64Prefixes: conf.DNS.DNS64Prefixes, UpstreamTimeout: conf.DNS.UpstreamTimeout.Duration, BootstrapPreferIPv6: conf.DNS.BootstrapPreferIPv6, UseDNS64: conf.DNS.UseDNS64, } err = m.updateDNS(ctx, dnsConf) if err != nil { return fmt.Errorf("assembling dnssvc: %w", err) } webSvcConf := &websvc.Config{ Pprof: &websvc.PprofConfig{ Port: conf.HTTP.Pprof.Port, Enabled: conf.HTTP.Pprof.Enabled, }, ConfigManager: m, Frontend: frontend, // TODO(a.garipov): Fill from config file. TLS: nil, Start: start, Addresses: conf.HTTP.Addresses, SecureAddresses: conf.HTTP.SecureAddresses, OverrideAddress: webAddr, Timeout: conf.HTTP.Timeout.Duration, ForceHTTPS: conf.HTTP.ForceHTTPS, } err = m.updateWeb(ctx, webSvcConf) if err != nil { return fmt.Errorf("assembling websvc: %w", err) } return nil } // write writes the current configuration to disk. func (m *Manager) write() (err error) { b, err := yaml.Marshal(m.current) if err != nil { return fmt.Errorf("encoding: %w", err) } err = maybe.WriteFile(m.fileName, b, 0o644) if err != nil { return fmt.Errorf("writing: %w", err) } log.Info("configmgr: written to %q", m.fileName) return nil } // DNS returns the current DNS service. It is safe for concurrent use. func (m *Manager) DNS() (dns agh.ServiceWithConfig[*dnssvc.Config]) { m.updMu.RLock() defer m.updMu.RUnlock() return m.dns } // UpdateDNS implements the [websvc.ConfigManager] interface for *Manager. The // fields of c must not be modified after calling UpdateDNS. func (m *Manager) UpdateDNS(ctx context.Context, c *dnssvc.Config) (err error) { m.updMu.Lock() defer m.updMu.Unlock() // TODO(a.garipov): Update and write the configuration file. Return an // error if something went wrong. err = m.updateDNS(ctx, c) if err != nil { return fmt.Errorf("reassembling dnssvc: %w", err) } m.updateCurrentDNS(c) return m.write() } // updateDNS recreates the DNS service. m.updMu is expected to be locked. func (m *Manager) updateDNS(ctx context.Context, c *dnssvc.Config) (err error) { if prev := m.dns; prev != nil { err = prev.Shutdown(ctx) if err != nil { return fmt.Errorf("shutting down dns svc: %w", err) } } svc, err := dnssvc.New(c) if err != nil { return fmt.Errorf("creating dns svc: %w", err) } m.dns = svc return nil } // updateCurrentDNS updates the DNS configuration in the current config. func (m *Manager) updateCurrentDNS(c *dnssvc.Config) { m.current.DNS.Addresses = slices.Clone(c.Addresses) m.current.DNS.BootstrapDNS = slices.Clone(c.BootstrapServers) m.current.DNS.UpstreamDNS = slices.Clone(c.UpstreamServers) m.current.DNS.DNS64Prefixes = slices.Clone(c.DNS64Prefixes) m.current.DNS.UpstreamTimeout = timeutil.Duration{Duration: c.UpstreamTimeout} m.current.DNS.BootstrapPreferIPv6 = c.BootstrapPreferIPv6 m.current.DNS.UseDNS64 = c.UseDNS64 } // Web returns the current web service. It is safe for concurrent use. func (m *Manager) Web() (web agh.ServiceWithConfig[*websvc.Config]) { m.updMu.RLock() defer m.updMu.RUnlock() return m.web } // UpdateWeb implements the [websvc.ConfigManager] interface for *Manager. The // fields of c must not be modified after calling UpdateWeb. func (m *Manager) UpdateWeb(ctx context.Context, c *websvc.Config) (err error) { m.updMu.Lock() defer m.updMu.Unlock() err = m.updateWeb(ctx, c) if err != nil { return fmt.Errorf("reassembling websvc: %w", err) } m.updateCurrentWeb(c) return m.write() } // updateWeb recreates the web service. m.upd is expected to be locked. func (m *Manager) updateWeb(ctx context.Context, c *websvc.Config) (err error) { if prev := m.web; prev != nil { err = prev.Shutdown(ctx) if err != nil { return fmt.Errorf("shutting down web svc: %w", err) } } m.web, err = websvc.New(c) if err != nil { return fmt.Errorf("creating web svc: %w", err) } return nil } // updateCurrentWeb updates the web configuration in the current config. func (m *Manager) updateCurrentWeb(c *websvc.Config) { // TODO(a.garipov): Update pprof from API? m.current.HTTP.Addresses = slices.Clone(c.Addresses) m.current.HTTP.SecureAddresses = slices.Clone(c.SecureAddresses) m.current.HTTP.Timeout = timeutil.Duration{Duration: c.Timeout} m.current.HTTP.ForceHTTPS = c.ForceHTTPS } ```
/content/code_sandbox/internal/next/configmgr/configmgr.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,224
```go package cmd import ( "fmt" "os" "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/golibs/log" ) // syslogServiceName is the name of the AdGuard Home service used for writing // logs to the system log. const syslogServiceName = "AdGuardHome" // setLog sets up the text logging. // // TODO(a.garipov): Add parameters from configuration file. func setLog(opts *options) (err error) { switch opts.confFile { case "stdout": log.SetOutput(os.Stdout) case "stderr": log.SetOutput(os.Stderr) case "syslog": err = aghos.ConfigureSyslog(syslogServiceName) if err != nil { return fmt.Errorf("initializing syslog: %w", err) } default: // TODO(a.garipov): Use the path. } if opts.verbose { log.SetLevel(log.DEBUG) log.Debug("verbose logging enabled") } return nil } ```
/content/code_sandbox/internal/next/cmd/log.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
223
```go // Package cmd is the AdGuard Home entry point. It assembles the configuration // file manager, sets up signal processing logic, and so on. // // TODO(a.garipov): Move to the upper-level internal/. package cmd import ( "context" "io/fs" "os" "time" "github.com/AdguardTeam/AdGuardHome/internal/next/configmgr" "github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/golibs/log" ) // Main is the entry point of AdGuard Home. func Main(embeddedFrontend fs.FS) { start := time.Now() cmdName := os.Args[0] opts, err := parseOptions(cmdName, os.Args[1:]) exitCode, needExit := processOptions(opts, cmdName, err) if needExit { os.Exit(exitCode) } err = setLog(opts) check(err) log.Info("starting adguard home, version %s, pid %d", version.Version(), os.Getpid()) if opts.workDir != "" { log.Info("changing working directory to %q", opts.workDir) err = os.Chdir(opts.workDir) check(err) } frontend, err := frontendFromOpts(opts, embeddedFrontend) check(err) confMgrConf := &configmgr.Config{ Frontend: frontend, WebAddr: opts.webAddr, Start: start, FileName: opts.confFile, } confMgr, err := newConfigMgr(confMgrConf) check(err) web := confMgr.Web() err = web.Start() check(err) dns := confMgr.DNS() err = dns.Start() check(err) sigHdlr := newSignalHandler( confMgrConf, opts.pidFile, web, dns, ) sigHdlr.handle() } // defaultTimeout is the timeout used for some operations where another timeout // hasn't been defined yet. const defaultTimeout = 5 * time.Second // ctxWithDefaultTimeout is a helper function that returns a context with // timeout set to defaultTimeout. func ctxWithDefaultTimeout() (ctx context.Context, cancel context.CancelFunc) { return context.WithTimeout(context.Background(), defaultTimeout) } // newConfigMgr returns a new configuration manager using defaultTimeout as the // context timeout. func newConfigMgr(c *configmgr.Config) (m *configmgr.Manager, err error) { ctx, cancel := ctxWithDefaultTimeout() defer cancel() return configmgr.New(ctx, c) } // check is a simple error-checking helper. It must only be used within Main. func check(err error) { if err != nil { panic(err) } } ```
/content/code_sandbox/internal/next/cmd/cmd.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
576
```go package updater import ( "encoding/json" "fmt" "io" "net/http" "slices" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/ioutil" "github.com/AdguardTeam/golibs/log" "golang.org/x/exp/maps" ) // TODO(a.garipov): Make configurable. const versionCheckPeriod = 8 * time.Hour // VersionInfo contains information about a new version. type VersionInfo struct { NewVersion string `json:"new_version,omitempty"` Announcement string `json:"announcement,omitempty"` AnnouncementURL string `json:"announcement_url,omitempty"` // TODO(a.garipov): See if the frontend actually still cares about // nullability. CanAutoUpdate aghalg.NullBool `json:"can_autoupdate,omitempty"` } // MaxResponseSize is responses on server's requests maximum length in bytes. const MaxResponseSize = 64 * 1024 // VersionInfo downloads the latest version information. If forceRecheck is // false and there are cached results, those results are returned. func (u *Updater) VersionInfo(forceRecheck bool) (vi VersionInfo, err error) { u.mu.Lock() defer u.mu.Unlock() now := time.Now() recheckTime := u.prevCheckTime.Add(versionCheckPeriod) if !forceRecheck && now.Before(recheckTime) { return u.prevCheckResult, u.prevCheckError } var resp *http.Response vcu := u.versionCheckURL resp, err = u.client.Get(vcu) if err != nil { return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %w", vcu, err) } defer func() { err = errors.WithDeferred(err, resp.Body.Close()) }() r := ioutil.LimitReader(resp.Body, MaxResponseSize) // This use of ReadAll is safe, because we just limited the appropriate // ReadCloser. body, err := io.ReadAll(r) if err != nil { return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %w", vcu, err) } u.prevCheckTime = now u.prevCheckResult, u.prevCheckError = u.parseVersionResponse(body) return u.prevCheckResult, u.prevCheckError } func (u *Updater) parseVersionResponse(data []byte) (VersionInfo, error) { info := VersionInfo{ CanAutoUpdate: aghalg.NBFalse, } versionJSON := map[string]string{ "version": "", "announcement": "", "announcement_url": "", } err := json.Unmarshal(data, &versionJSON) if err != nil { return info, fmt.Errorf("version.json: %w", err) } for k, v := range versionJSON { if v == "" { return info, fmt.Errorf("version.json: bad data: value for key %q is empty", k) } } info.NewVersion = versionJSON["version"] info.Announcement = versionJSON["announcement"] info.AnnouncementURL = versionJSON["announcement_url"] packageURL, key, found := u.downloadURL(versionJSON) if !found { return info, fmt.Errorf("version.json: no package URL: key %q not found in object", key) } info.CanAutoUpdate = aghalg.BoolToNullBool(info.NewVersion != u.version) u.newVersion = info.NewVersion u.packageURL = packageURL return info, nil } // downloadURL returns the download URL for current build as well as its key in // versionObj. If the key is not found, it additionally prints an informative // log message. func (u *Updater) downloadURL(versionObj map[string]string) (dlURL, key string, ok bool) { if u.goarch == "arm" && u.goarm != "" { key = fmt.Sprintf("download_%s_%sv%s", u.goos, u.goarch, u.goarm) } else if isMIPS(u.goarch) && u.gomips != "" { key = fmt.Sprintf("download_%s_%s_%s", u.goos, u.goarch, u.gomips) } else { key = fmt.Sprintf("download_%s_%s", u.goos, u.goarch) } dlURL, ok = versionObj[key] if ok { return dlURL, key, true } keys := maps.Keys(versionObj) slices.Sort(keys) log.Error("updater: key %q not found; got keys %q", key, keys) return "", key, false } // isMIPS returns true if arch is any MIPS architecture. func isMIPS(arch string) (ok bool) { switch arch { case "mips", "mips64", "mips64le", "mipsle": return true default: return false } } ```
/content/code_sandbox/internal/updater/check.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,088
```go package updater import ( "os" "path/filepath" "testing" "github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUpdater_internal(t *testing.T) { wd := t.TempDir() exePathUnix := filepath.Join(wd, "AdGuardHome.exe") exePathWindows := filepath.Join(wd, "AdGuardHome") yamlPath := filepath.Join(wd, "AdGuardHome.yaml") readmePath := filepath.Join(wd, "README.md") licensePath := filepath.Join(wd, "LICENSE.txt") require.NoError(t, os.WriteFile(exePathUnix, []byte("AdGuardHome.exe"), 0o755)) require.NoError(t, os.WriteFile(exePathWindows, []byte("AdGuardHome"), 0o755)) require.NoError(t, os.WriteFile(yamlPath, []byte("AdGuardHome.yaml"), 0o644)) require.NoError(t, os.WriteFile(readmePath, []byte("README.md"), 0o644)) require.NoError(t, os.WriteFile(licensePath, []byte("LICENSE.txt"), 0o644)) testCases := []struct { name string exeName string os string archiveName string }{{ name: "unix", os: "linux", exeName: "AdGuardHome", archiveName: "AdGuardHome.tar.gz", }, { name: "windows", os: "windows", exeName: "AdGuardHome.exe", archiveName: "AdGuardHome.zip", }} for _, tc := range testCases { exePath := filepath.Join(wd, tc.exeName) // start server for returning package file pkgData, err := os.ReadFile(filepath.Join("testdata", tc.archiveName)) require.NoError(t, err) fakeClient, fakeURL := aghtest.StartHTTPServer(t, pkgData) fakeURL = fakeURL.JoinPath(tc.archiveName) u := NewUpdater(&Config{ Client: fakeClient, GOOS: tc.os, Version: "v0.103.0", ExecPath: exePath, WorkDir: wd, ConfName: yamlPath, }) u.newVersion = "v0.103.1" u.packageURL = fakeURL.String() require.NoError(t, u.prepare()) require.NoError(t, u.downloadPackageFile()) require.NoError(t, u.unpack()) require.NoError(t, u.backup(false)) require.NoError(t, u.replace()) u.clean() // check backup files d, err := os.ReadFile(filepath.Join(wd, "agh-backup", "AdGuardHome.yaml")) require.NoError(t, err) assert.Equal(t, "AdGuardHome.yaml", string(d)) d, err = os.ReadFile(filepath.Join(wd, "agh-backup", tc.exeName)) require.NoError(t, err) assert.Equal(t, tc.exeName, string(d)) // check updated files d, err = os.ReadFile(exePath) require.NoError(t, err) assert.Equal(t, "1", string(d)) d, err = os.ReadFile(readmePath) require.NoError(t, err) assert.Equal(t, "2", string(d)) d, err = os.ReadFile(licensePath) require.NoError(t, err) assert.Equal(t, "3", string(d)) d, err = os.ReadFile(yamlPath) require.NoError(t, err) assert.Equal(t, "AdGuardHome.yaml", string(d)) } } ```
/content/code_sandbox/internal/updater/updater_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
806
```go package cmd import ( "encoding" "flag" "fmt" "io" "io/fs" "net/netip" "os" "slices" "strings" "github.com/AdguardTeam/AdGuardHome/internal/configmigrate" "github.com/AdguardTeam/AdGuardHome/internal/next/configmgr" "github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/golibs/log" ) // options contains all command-line options for the AdGuardHome(.exe) binary. type options struct { // confFile is the path to the configuration file. confFile string // logFile is the path to the log file. Special values: // // - "stdout": Write to stdout (the default). // - "stderr": Write to stderr. // - "syslog": Write to the system log. logFile string // pidFile is the path to the file where to store the PID. pidFile string // serviceAction is the service control action to perform: // // - "install": Installs AdGuard Home as a system service. // - "uninstall": Uninstalls it. // - "status": Prints the service status. // - "start": Starts the previously installed service. // - "stop": Stops the previously installed service. // - "restart": Restarts the previously installed service. // - "reload": Reloads the configuration. // - "run": This is a special command that is not supposed to be used // directly it is specified when we register a service, and it indicates // to the app that it is being run as a service. // // TODO(a.garipov): Use. serviceAction string // workDir is the path to the working directory. It is applied before all // other configuration is read, so all relative paths are relative to it. workDir string // webAddr contains the address on which to serve the web UI. webAddr netip.AddrPort // checkConfig, if true, instructs AdGuard Home to check the configuration // file, optionally print an error message to stdout, and exit with a // corresponding exit code. checkConfig bool // disableUpdate, if true, prevents AdGuard Home from automatically checking // for updates. // // TODO(a.garipov): Use. disableUpdate bool // glinetMode enables the GL-Inet compatibility mode. // // TODO(a.garipov): Use. glinetMode bool // help, if true, instructs AdGuard Home to print the command-line option // help message and quit with a successful exit-code. help bool // localFrontend, if true, instructs AdGuard Home to use the local frontend // directory instead of the files compiled into the binary. // // TODO(a.garipov): Use. localFrontend bool // performUpdate, if true, instructs AdGuard Home to update the current // binary and restart the service in case it's installed. // // TODO(a.garipov): Use. performUpdate bool // verbose, if true, instructs AdGuard Home to enable verbose logging. verbose bool // version, if true, instructs AdGuard Home to print the version to stdout // and quit with a successful exit-code. If verbose is also true, print a // more detailed version description. version bool } // Indexes to help with the [commandLineOptions] initialization. const ( confFileIdx = iota logFileIdx pidFileIdx serviceActionIdx workDirIdx webAddrIdx checkConfigIdx disableUpdateIdx glinetModeIdx helpIdx localFrontend performUpdateIdx verboseIdx versionIdx ) // commandLineOption contains information about a command-line option: its long // and, if there is one, short forms, the value type, the description, and the // default value. type commandLineOption struct { defaultValue any description string long string short string valueType string } // commandLineOptions are all command-line options currently supported by // AdGuard Home. var commandLineOptions = []*commandLineOption{ confFileIdx: { // TODO(a.garipov): Remove the directory when the new code is ready. defaultValue: "internal/next/AdGuardHome.yaml", description: "Path to the config file.", long: "config", short: "c", valueType: "path", }, logFileIdx: { defaultValue: "stdout", description: `Path to log file. Special values include "stdout", "stderr", and "syslog".`, long: "logfile", short: "l", valueType: "path", }, pidFileIdx: { defaultValue: "", description: "Path to the file where to store the PID.", long: "pidfile", short: "", valueType: "path", }, serviceActionIdx: { defaultValue: "", description: `Service control action: "status", "install" (as a service), ` + `"uninstall" (as a service), "start", "stop", "restart", "reload" (configuration).`, long: "service", short: "s", valueType: "action", }, workDirIdx: { defaultValue: "", description: `Path to the working directory. ` + `It is applied before all other configuration is read, ` + `so all relative paths are relative to it.`, long: "work-dir", short: "w", valueType: "path", }, webAddrIdx: { defaultValue: netip.AddrPort{}, description: `Address to serve the web UI on, in the host:port format.`, long: "web-addr", short: "", valueType: "host:port", }, checkConfigIdx: { defaultValue: false, description: "Check configuration, print errors to stdout, and quit.", long: "check-config", short: "", valueType: "", }, disableUpdateIdx: { defaultValue: false, description: "Disable automatic update checking.", long: "no-check-update", short: "", valueType: "", }, glinetModeIdx: { defaultValue: false, description: "Run in GL-Inet compatibility mode.", long: "glinet", short: "", valueType: "", }, helpIdx: { defaultValue: false, description: "Print this help message and quit.", long: "help", short: "h", valueType: "", }, localFrontend: { defaultValue: false, description: "Use local frontend directories.", long: "local-frontend", short: "", valueType: "", }, performUpdateIdx: { defaultValue: false, description: "Update the current binary and restart the service in case it's installed.", long: "update", short: "", valueType: "", }, verboseIdx: { defaultValue: false, description: "Enable verbose logging.", long: "verbose", short: "v", valueType: "", }, versionIdx: { defaultValue: false, description: `Print the version to stdout and quit. ` + `Print a more detailed version description with -v.`, long: "version", short: "", valueType: "", }, } // parseOptions parses the command-line options for AdGuardHome. func parseOptions(cmdName string, args []string) (opts *options, err error) { flags := flag.NewFlagSet(cmdName, flag.ContinueOnError) opts = &options{} for i, fieldPtr := range []any{ confFileIdx: &opts.confFile, logFileIdx: &opts.logFile, pidFileIdx: &opts.pidFile, serviceActionIdx: &opts.serviceAction, workDirIdx: &opts.workDir, webAddrIdx: &opts.webAddr, checkConfigIdx: &opts.checkConfig, disableUpdateIdx: &opts.disableUpdate, glinetModeIdx: &opts.glinetMode, helpIdx: &opts.help, localFrontend: &opts.localFrontend, performUpdateIdx: &opts.performUpdate, verboseIdx: &opts.verbose, versionIdx: &opts.version, } { addOption(flags, fieldPtr, commandLineOptions[i]) } flags.Usage = func() { usage(cmdName, os.Stderr) } err = flags.Parse(args) if err != nil { // Don't wrap the error, because it's informative enough as is. return nil, err } return opts, nil } // addOption adds the command-line option described by o to flags using fieldPtr // as the pointer to the value. func addOption(flags *flag.FlagSet, fieldPtr any, o *commandLineOption) { switch fieldPtr := fieldPtr.(type) { case *string: flags.StringVar(fieldPtr, o.long, o.defaultValue.(string), o.description) if o.short != "" { flags.StringVar(fieldPtr, o.short, o.defaultValue.(string), o.description) } case *bool: flags.BoolVar(fieldPtr, o.long, o.defaultValue.(bool), o.description) if o.short != "" { flags.BoolVar(fieldPtr, o.short, o.defaultValue.(bool), o.description) } case encoding.TextUnmarshaler: flags.TextVar(fieldPtr, o.long, o.defaultValue.(encoding.TextMarshaler), o.description) if o.short != "" { flags.TextVar(fieldPtr, o.short, o.defaultValue.(encoding.TextMarshaler), o.description) } default: panic(fmt.Errorf("unexpected field pointer type %T", fieldPtr)) } } // usage prints a usage message similar to the one printed by package flag but // taking long vs. short versions into account as well as using more informative // value hints. func usage(cmdName string, output io.Writer) { options := slices.Clone(commandLineOptions) slices.SortStableFunc(options, func(a, b *commandLineOption) (res int) { return strings.Compare(a.long, b.long) }) b := &strings.Builder{} _, _ = fmt.Fprintf(b, "Usage of %s:\n", cmdName) for _, o := range options { writeUsageLine(b, o) // Use four spaces before the tab to trigger good alignment for both 4- // and 8-space tab stops. if shouldIncludeDefault(o.defaultValue) { _, _ = fmt.Fprintf(b, " \t%s (Default value: %q)\n", o.description, o.defaultValue) } else { _, _ = fmt.Fprintf(b, " \t%s\n", o.description) } } _, _ = io.WriteString(output, b.String()) } // shouldIncludeDefault returns true if this default value should be printed. func shouldIncludeDefault(v any) (ok bool) { switch v := v.(type) { case bool: return v case string: return v != "" default: return v == nil } } // writeUsageLine writes the usage line for the provided command-line option. func writeUsageLine(b *strings.Builder, o *commandLineOption) { if o.short == "" { if o.valueType == "" { _, _ = fmt.Fprintf(b, " --%s\n", o.long) } else { _, _ = fmt.Fprintf(b, " --%s=%s\n", o.long, o.valueType) } return } if o.valueType == "" { _, _ = fmt.Fprintf(b, " --%s/-%s\n", o.long, o.short) } else { _, _ = fmt.Fprintf(b, " --%[1]s=%[3]s/-%[2]s %[3]s\n", o.long, o.short, o.valueType) } } // processOptions decides if AdGuard Home should exit depending on the results // of command-line option parsing. func processOptions( opts *options, cmdName string, parseErr error, ) (exitCode int, needExit bool) { if parseErr != nil { // Assume that usage has already been printed. return statusArgumentError, true } if opts.help { usage(cmdName, os.Stdout) return statusSuccess, true } if opts.version { if opts.verbose { fmt.Print(version.Verbose(configmigrate.LastSchemaVersion)) } else { fmt.Printf("AdGuard Home %s\n", version.Version()) } return statusSuccess, true } if opts.checkConfig { err := configmgr.Validate(opts.confFile) if err != nil { _, _ = io.WriteString(os.Stdout, err.Error()+"\n") return statusError, true } return statusSuccess, true } return 0, false } // frontendFromOpts returns the frontend to use based on the options. func frontendFromOpts(opts *options, embeddedFrontend fs.FS) (frontend fs.FS, err error) { const frontendSubdir = "build/static" if opts.localFrontend { log.Info("warning: using local frontend files") return os.DirFS(frontendSubdir), nil } return fs.Sub(embeddedFrontend, frontendSubdir) } ```
/content/code_sandbox/internal/next/cmd/opt.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,044
```go package updater_test import ( "net/http" "net/http/httptest" "net/url" "testing" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/updater" "github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUpdater_VersionInfo(t *testing.T) { const jsonData = `{ "version": "v0.103.0-beta.2", "announcement": "AdGuard Home v0.103.0-beta.2 is now available!", "announcement_url": "path_to_url", "selfupdate_min_version": "v0.0", "download_windows_amd64": "path_to_url", "download_windows_386": "path_to_url", "download_darwin_amd64": "path_to_url", "download_darwin_386": "path_to_url", "download_linux_amd64": "path_to_url", "download_linux_386": "path_to_url", "download_linux_arm": "path_to_url", "download_linux_armv5": "path_to_url", "download_linux_armv6": "path_to_url", "download_linux_armv7": "path_to_url", "download_linux_arm64": "path_to_url", "download_linux_mips": "path_to_url", "download_linux_mipsle": "path_to_url", "download_linux_mips64": "path_to_url", "download_linux_mips64le": "path_to_url", "download_freebsd_386": "path_to_url", "download_freebsd_amd64": "path_to_url", "download_freebsd_arm": "path_to_url", "download_freebsd_armv5": "path_to_url", "download_freebsd_armv6": "path_to_url", "download_freebsd_armv7": "path_to_url", "download_freebsd_arm64": "path_to_url" }` counter := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { counter++ _, _ = w.Write([]byte(jsonData)) })) t.Cleanup(srv.Close) fakeURL, err := url.JoinPath(srv.URL, "adguardhome", version.ChannelBeta, "version.json") require.NoError(t, err) u := updater.NewUpdater(&updater.Config{ Client: srv.Client(), Version: "v0.103.0-beta.1", Channel: version.ChannelBeta, GOARCH: "arm", GOOS: "linux", VersionCheckURL: fakeURL, }) info, err := u.VersionInfo(false) require.NoError(t, err) assert.Equal(t, counter, 1) assert.Equal(t, "v0.103.0-beta.2", info.NewVersion) assert.Equal(t, "AdGuard Home v0.103.0-beta.2 is now available!", info.Announcement) assert.Equal(t, "path_to_url", info.AnnouncementURL) assert.Equal(t, aghalg.NBTrue, info.CanAutoUpdate) t.Run("cache_check", func(t *testing.T) { _, err = u.VersionInfo(false) require.NoError(t, err) assert.Equal(t, counter, 1) }) t.Run("force_check", func(t *testing.T) { _, err = u.VersionInfo(true) require.NoError(t, err) assert.Equal(t, counter, 2) }) t.Run("api_fail", func(t *testing.T) { srv.Close() _, err = u.VersionInfo(true) var urlErr *url.Error assert.ErrorAs(t, err, &urlErr) }) } func TestUpdater_VersionInfo_others(t *testing.T) { const jsonData = `{ "version": "v0.103.0-beta.2", "announcement": "AdGuard Home v0.103.0-beta.2 is now available!", "announcement_url": "path_to_url", "selfupdate_min_version": "v0.0", "download_linux_armv7": "path_to_url", "download_linux_mips_softfloat": "path_to_url" }` fakeClient, fakeURL := aghtest.StartHTTPServer(t, []byte(jsonData)) fakeURL = fakeURL.JoinPath("adguardhome", version.ChannelBeta, "version.json") testCases := []struct { name string arch string arm string mips string }{{ name: "ARM", arch: "arm", arm: "7", mips: "", }, { name: "MIPS", arch: "mips", mips: "softfloat", arm: "", }} for _, tc := range testCases { u := updater.NewUpdater(&updater.Config{ Client: fakeClient, Version: "v0.103.0-beta.1", Channel: version.ChannelBeta, GOOS: "linux", GOARCH: tc.arch, GOARM: tc.arm, GOMIPS: tc.mips, VersionCheckURL: fakeURL.String(), }) info, err := u.VersionInfo(false) require.NoError(t, err) assert.Equal(t, "v0.103.0-beta.2", info.NewVersion) assert.Equal(t, "AdGuard Home v0.103.0-beta.2 is now available!", info.Announcement) assert.Equal(t, "path_to_url", info.AnnouncementURL) assert.Equal(t, aghalg.NBTrue, info.CanAutoUpdate) } } ```
/content/code_sandbox/internal/updater/check_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,286
```go package updater_test import ( "fmt" "net/http" "net/http/httptest" "net/url" "os" "path" "path/filepath" "runtime" "testing" "github.com/AdguardTeam/AdGuardHome/internal/updater" "github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } func TestUpdater_Update(t *testing.T) { const jsonData = `{ "version": "v0.103.0-beta.2", "announcement": "AdGuard Home v0.103.0-beta.2 is now available!", "announcement_url": "path_to_url", "selfupdate_min_version": "v0.0", "download_linux_amd64": "%s" }` const packagePath = "/AdGuardHome.tar.gz" wd := t.TempDir() exePath := filepath.Join(wd, "AdGuardHome") yamlPath := filepath.Join(wd, "AdGuardHome.yaml") readmePath := filepath.Join(wd, "README.md") licensePath := filepath.Join(wd, "LICENSE.txt") require.NoError(t, os.WriteFile(exePath, []byte("AdGuardHome"), 0o755)) require.NoError(t, os.WriteFile(yamlPath, []byte("AdGuardHome.yaml"), 0o644)) require.NoError(t, os.WriteFile(readmePath, []byte("README.md"), 0o644)) require.NoError(t, os.WriteFile(licensePath, []byte("LICENSE.txt"), 0o644)) pkgData, err := os.ReadFile("testdata/AdGuardHome_unix.tar.gz") require.NoError(t, err) mux := http.NewServeMux() mux.HandleFunc(packagePath, func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(pkgData) }) versionPath := path.Join("/adguardhome", version.ChannelBeta, "version.json") mux.HandleFunc(versionPath, func(w http.ResponseWriter, r *http.Request) { var u string u, err = url.JoinPath("http://", r.Host, packagePath) require.NoError(t, err) _, _ = fmt.Fprintf(w, jsonData, u) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) versionCheckURL, err := url.JoinPath(srv.URL, versionPath) require.NoError(t, err) u := updater.NewUpdater(&updater.Config{ Client: srv.Client(), GOARCH: "amd64", GOOS: "linux", Version: "v0.103.0", ConfName: yamlPath, WorkDir: wd, ExecPath: exePath, VersionCheckURL: versionCheckURL, }) _, err = u.VersionInfo(false) require.NoError(t, err) err = u.Update(true) require.NoError(t, err) // check backup files d, err := os.ReadFile(filepath.Join(wd, "agh-backup", "LICENSE.txt")) require.NoError(t, err) assert.Equal(t, "LICENSE.txt", string(d)) d, err = os.ReadFile(filepath.Join(wd, "agh-backup", "README.md")) require.NoError(t, err) assert.Equal(t, "README.md", string(d)) // check updated files _, err = os.Stat(exePath) require.NoError(t, err) d, err = os.ReadFile(readmePath) require.NoError(t, err) assert.Equal(t, "2", string(d)) d, err = os.ReadFile(licensePath) require.NoError(t, err) assert.Equal(t, "3", string(d)) d, err = os.ReadFile(yamlPath) require.NoError(t, err) assert.Equal(t, "AdGuardHome.yaml", string(d)) t.Run("config_check", func(t *testing.T) { // TODO(s.chzhen): Test on Windows also. if runtime.GOOS == "windows" { t.Skip("skipping config check test on windows") } err = u.Update(false) assert.NoError(t, err) }) t.Run("api_fail", func(t *testing.T) { srv.Close() err = u.Update(true) var urlErr *url.Error assert.ErrorAs(t, err, &urlErr) }) } ```
/content/code_sandbox/internal/updater/updater_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
962
```go //go:build tools // Package tools and its main module are a nested internal module containing our // development tool dependencies. // // See path_to_url#how-can-i-track-tool-dependencies-for-a-module. package tools import ( _ "github.com/fzipp/gocyclo/cmd/gocyclo" _ "github.com/golangci/misspell/cmd/misspell" _ "github.com/gordonklaus/ineffassign" _ "github.com/kisielk/errcheck" _ "github.com/kyoh86/looppointer" _ "github.com/securego/gosec/v2/cmd/gosec" _ "github.com/uudashr/gocognit/cmd/gocognit" _ "golang.org/x/tools/go/analysis/passes/nilness/cmd/nilness" _ "golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow" _ "golang.org/x/vuln/cmd/govulncheck" _ "honnef.co/go/tools/cmd/staticcheck" _ "mvdan.cc/gofumpt" _ "mvdan.cc/unparam" ) ```
/content/code_sandbox/internal/tools/tools.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
253
```go //go:build linux package arpdb import ( "bufio" "fmt" "io/fs" "net" "net/netip" "strings" "sync" "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/stringutil" ) func newARPDB() (arp *arpdbs) { // Use the common storage among the implementations. ns := &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), } var parseF parseNeighsFunc if aghos.IsOpenWrt() { parseF = parseArpAWrt } else { parseF = parseArpA } return newARPDBs( // Try /proc/net/arp first. &fsysARPDB{ ns: ns, fsys: rootDirFS, filename: "proc/net/arp", }, // Then, try "arp -a -n". &cmdARPDB{ parse: parseF, ns: ns, cmd: "arp", // Use -n flag to avoid resolving the hostnames of the neighbors. // By default ARP attempts to resolve the hostnames via DNS. See // man 8 arp. // // See also path_to_url args: []string{"-a", "-n"}, }, // Finally, try "ip neigh". &cmdARPDB{ parse: parseIPNeigh, ns: ns, cmd: "ip", args: []string{"neigh"}, }, ) } // fsysARPDB accesses the ARP cache file to update the database. type fsysARPDB struct { ns *neighs fsys fs.FS filename string } // type check var _ Interface = (*fsysARPDB)(nil) // Refresh implements the [Interface] interface for *fsysARPDB. func (arp *fsysARPDB) Refresh() (err error) { var f fs.File f, err = arp.fsys.Open(arp.filename) if err != nil { return fmt.Errorf("opening %q: %w", arp.filename, err) } sc := bufio.NewScanner(f) // Skip the header. if !sc.Scan() { return nil } else if err = sc.Err(); err != nil { return err } ns := make([]Neighbor, 0, arp.ns.len()) for sc.Scan() { n := parseNeighbor(sc.Text()) if n != nil { ns = append(ns, *n) } } arp.ns.reset(ns) return nil } // parseNeighbor parses line into *Neighbor. func parseNeighbor(line string) (n *Neighbor) { fields := stringutil.SplitTrimmed(line, " ") if len(fields) != 6 { return nil } ip, err := netip.ParseAddr(fields[0]) if err != nil || ip.IsUnspecified() { return nil } mac, err := net.ParseMAC(fields[3]) if err != nil { return nil } return &Neighbor{ IP: ip, MAC: mac, } } // Neighbors implements the [Interface] interface for *fsysARPDB. func (arp *fsysARPDB) Neighbors() (ns []Neighbor) { return arp.ns.clone() } // parseArpAWrt parses the output of the "arp -a -n" command on OpenWrt. The // expected input format: // // IP address HW type Flags HW address Mask Device // 192.168.11.98 0x1 0x2 5a:92:df:a9:7e:28 * wan func parseArpAWrt(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { if !sc.Scan() { // Skip the header. return } ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() fields := strings.Fields(ln) if len(fields) < 4 { continue } ip, err := netip.ParseAddr(fields[0]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } hwStr := fields[3] mac, err := net.ParseMAC(hwStr) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } ns = append(ns, Neighbor{ IP: ip, MAC: mac, }) } return ns } // parseArpA parses the output of the "arp -a -n" command on Linux. The // expected input format: // // hostname (192.168.1.1) at ab:cd:ef:ab:cd:ef [ether] on enp0s3 func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() fields := strings.Fields(ln) if len(fields) < 4 { continue } ipStr := fields[1] if len(ipStr) < 2 { continue } ip, err := netip.ParseAddr(ipStr[1 : len(ipStr)-1]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } hwStr := fields[3] mac, err := net.ParseMAC(hwStr) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } ns = append(ns, Neighbor{ IP: ip, MAC: mac, Name: validatedHostname(fields[0]), }) } return ns } // parseIPNeigh parses the output of the "ip neigh" command on Linux. The // expected input format: // // 192.168.1.1 dev enp0s3 lladdr ab:cd:ef:ab:cd:ef REACHABLE func parseIPNeigh(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() fields := strings.Fields(ln) if len(fields) < 5 { continue } n := Neighbor{} ip, err := netip.ParseAddr(fields[0]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } else { n.IP = ip } mac, err := net.ParseMAC(fields[4]) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } else { n.MAC = mac } ns = append(ns, n) } return ns } ```
/content/code_sandbox/internal/arpdb/arpdb_linux.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,621
```go //go:build darwin || freebsd package arpdb import ( "bufio" "net" "net/netip" "strings" "sync" "github.com/AdguardTeam/golibs/log" ) func newARPDB() (arp *cmdARPDB) { return &cmdARPDB{ parse: parseArpA, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, cmd: "arp", // Use -n flag to avoid resolving the hostnames of the neighbors. By // default ARP attempts to resolve the hostnames via DNS. See man 8 // arp. // // See also path_to_url args: []string{"-a", "-n"}, } } // parseArpA parses the output of the "arp -a -n" command on macOS and FreeBSD. // The expected input format: // // host.name (192.168.0.1) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet] func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() fields := strings.Fields(ln) if len(fields) < 4 { continue } ipStr := fields[1] if len(ipStr) < 2 { continue } ip, err := netip.ParseAddr(ipStr[1 : len(ipStr)-1]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } hwStr := fields[3] mac, err := net.ParseMAC(hwStr) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } ns = append(ns, Neighbor{ IP: ip, MAC: mac, Name: validatedHostname(fields[0]), }) } return ns } ```
/content/code_sandbox/internal/arpdb/arpdb_bsd.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
478
```go //go:build darwin || freebsd package arpdb import ( "net" "net/netip" ) const arpAOutput = ` invalid.mac (1.2.3.4) at 12:34:56:78:910 on el0 ifscope [ethernet] invalid.ip (1.2.3.4.5) at ab:cd:ef:ab:cd:12 on ek0 ifscope [ethernet] invalid.fmt 1 at 12:cd:ef:ab:cd:ef on er0 ifscope [ethernet] hostname.one (192.168.1.2) at ab:cd:ef:ab:cd:ef on en0 ifscope [ethernet] hostname.two (::ffff:ffff) at ef:cd:ab:ef:cd:ab on em0 expires in 1198 seconds [ethernet] ? (::1234) at aa:bb:cc:dd:ee:ff on ej0 expires in 1918 seconds [ethernet] ` var wantNeighs = []Neighbor{{ Name: "hostname.one", IP: netip.MustParseAddr("192.168.1.2"), MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF}, }, { Name: "hostname.two", IP: netip.MustParseAddr("::ffff:ffff"), MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB}, }, { Name: "", IP: netip.MustParseAddr("::1234"), MAC: net.HardwareAddr{0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, }} ```
/content/code_sandbox/internal/arpdb/arpdb_bsd_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
393
```go // Package updater provides an updater for AdGuardHome. package updater import ( "archive/tar" "archive/zip" "compress/gzip" "fmt" "io" "net/http" "os" "os/exec" "path/filepath" "strings" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/ioutil" "github.com/AdguardTeam/golibs/log" ) // Updater is the AdGuard Home updater. type Updater struct { client *http.Client version string channel string goarch string goos string goarm string gomips string workDir string confName string execPath string versionCheckURL string // mu protects all fields below. mu *sync.RWMutex // TODO(a.garipov): See if all of these fields actually have to be in // this struct. currentExeName string // current binary executable updateDir string // "workDir/agh-update-v0.103.0" packageName string // "workDir/agh-update-v0.103.0/pkg_name.tar.gz" backupDir string // "workDir/agh-backup" backupExeName string // "workDir/agh-backup/AdGuardHome[.exe]" updateExeName string // "workDir/agh-update-v0.103.0/AdGuardHome[.exe]" unpackedFiles []string newVersion string packageURL string // Cached fields to prevent too many API requests. prevCheckError error prevCheckTime time.Time prevCheckResult VersionInfo } // Config is the AdGuard Home updater configuration. type Config struct { Client *http.Client Version string Channel string GOARCH string GOOS string GOARM string GOMIPS string // ConfName is the name of the current configuration file. Typically, // "AdGuardHome.yaml". ConfName string // WorkDir is the working directory that is used for temporary files. WorkDir string // ExecPath is path to the executable file. ExecPath string // VersionCheckURL is url to the latest version announcement. VersionCheckURL string } // NewUpdater creates a new Updater. func NewUpdater(conf *Config) *Updater { return &Updater{ client: conf.Client, version: conf.Version, channel: conf.Channel, goarch: conf.GOARCH, goos: conf.GOOS, goarm: conf.GOARM, gomips: conf.GOMIPS, confName: conf.ConfName, workDir: conf.WorkDir, execPath: conf.ExecPath, versionCheckURL: conf.VersionCheckURL, mu: &sync.RWMutex{}, } } // Update performs the auto-update. It returns an error if the update failed. // If firstRun is true, it assumes the configuration file doesn't exist. func (u *Updater) Update(firstRun bool) (err error) { u.mu.Lock() defer u.mu.Unlock() log.Info("updater: updating") defer func() { if err != nil { log.Info("updater: failed") } else { log.Info("updater: finished successfully") } }() err = u.prepare() if err != nil { return fmt.Errorf("preparing: %w", err) } defer u.clean() err = u.downloadPackageFile() if err != nil { return fmt.Errorf("downloading package file: %w", err) } err = u.unpack() if err != nil { return fmt.Errorf("unpacking: %w", err) } if !firstRun { err = u.check() if err != nil { return fmt.Errorf("checking config: %w", err) } } err = u.backup(firstRun) if err != nil { return fmt.Errorf("making backup: %w", err) } err = u.replace() if err != nil { return fmt.Errorf("replacing: %w", err) } return nil } // NewVersion returns the available new version. func (u *Updater) NewVersion() (nv string) { u.mu.RLock() defer u.mu.RUnlock() return u.newVersion } // VersionCheckURL returns the version check URL. func (u *Updater) VersionCheckURL() (vcu string) { u.mu.RLock() defer u.mu.RUnlock() return u.versionCheckURL } // prepare fills all necessary fields in Updater object. func (u *Updater) prepare() (err error) { u.updateDir = filepath.Join(u.workDir, fmt.Sprintf("agh-update-%s", u.newVersion)) _, pkgNameOnly := filepath.Split(u.packageURL) if pkgNameOnly == "" { return fmt.Errorf("invalid PackageURL: %q", u.packageURL) } u.packageName = filepath.Join(u.updateDir, pkgNameOnly) u.backupDir = filepath.Join(u.workDir, "agh-backup") updateExeName := "AdGuardHome" if u.goos == "windows" { updateExeName = "AdGuardHome.exe" } u.backupExeName = filepath.Join(u.backupDir, filepath.Base(u.execPath)) u.updateExeName = filepath.Join(u.updateDir, updateExeName) log.Debug( "updater: updating from %s to %s using url: %s", version.Version(), u.newVersion, u.packageURL, ) u.currentExeName = u.execPath _, err = os.Stat(u.currentExeName) if err != nil { return fmt.Errorf("checking %q: %w", u.currentExeName, err) } return nil } // unpack extracts the files from the downloaded archive. func (u *Updater) unpack() error { var err error _, pkgNameOnly := filepath.Split(u.packageURL) log.Debug("updater: unpacking package") if strings.HasSuffix(pkgNameOnly, ".zip") { u.unpackedFiles, err = zipFileUnpack(u.packageName, u.updateDir) if err != nil { return fmt.Errorf(".zip unpack failed: %w", err) } } else if strings.HasSuffix(pkgNameOnly, ".tar.gz") { u.unpackedFiles, err = tarGzFileUnpack(u.packageName, u.updateDir) if err != nil { return fmt.Errorf(".tar.gz unpack failed: %w", err) } } else { return fmt.Errorf("unknown package extension") } return nil } // check returns an error if the configuration file couldn't be used with the // version of AdGuard Home just downloaded. func (u *Updater) check() (err error) { log.Debug("updater: checking configuration") err = copyFile(u.confName, filepath.Join(u.updateDir, "AdGuardHome.yaml")) if err != nil { return fmt.Errorf("copyFile() failed: %w", err) } const format = "executing configuration check command: %w %d:\n" + "below is the output of configuration check:\n" + "%s" + "end of the output" cmd := exec.Command(u.updateExeName, "--check-config") out, err := cmd.CombinedOutput() code := cmd.ProcessState.ExitCode() if err != nil || code != 0 { return fmt.Errorf(format, err, code, out) } return nil } // backup makes a backup of the current configuration and supporting files. It // ignores the configuration file if firstRun is true. func (u *Updater) backup(firstRun bool) (err error) { log.Debug("updater: backing up current configuration") _ = os.Mkdir(u.backupDir, 0o755) if !firstRun { err = copyFile(u.confName, filepath.Join(u.backupDir, "AdGuardHome.yaml")) if err != nil { return fmt.Errorf("copyFile() failed: %w", err) } } wd := u.workDir err = copySupportingFiles(u.unpackedFiles, wd, u.backupDir) if err != nil { return fmt.Errorf("copySupportingFiles(%s, %s) failed: %w", wd, u.backupDir, err) } return nil } // replace moves the current executable with the updated one and also copies the // supporting files. func (u *Updater) replace() error { err := copySupportingFiles(u.unpackedFiles, u.updateDir, u.workDir) if err != nil { return fmt.Errorf("copySupportingFiles(%s, %s) failed: %w", u.updateDir, u.workDir, err) } log.Debug("updater: renaming: %s to %s", u.currentExeName, u.backupExeName) err = os.Rename(u.currentExeName, u.backupExeName) if err != nil { return err } if u.goos == "windows" { // rename fails with "File in use" error err = copyFile(u.updateExeName, u.currentExeName) } else { err = os.Rename(u.updateExeName, u.currentExeName) } if err != nil { return err } log.Debug("updater: renamed: %s to %s", u.updateExeName, u.currentExeName) return nil } // clean removes the temporary directory itself and all it's contents. func (u *Updater) clean() { _ = os.RemoveAll(u.updateDir) } // MaxPackageFileSize is a maximum package file length in bytes. The largest // package whose size is limited by this constant currently has the size of // approximately 9 MiB. const MaxPackageFileSize = 32 * 1024 * 1024 // Download package file and save it to disk func (u *Updater) downloadPackageFile() (err error) { var resp *http.Response resp, err = u.client.Get(u.packageURL) if err != nil { return fmt.Errorf("http request failed: %w", err) } defer func() { err = errors.WithDeferred(err, resp.Body.Close()) }() r := ioutil.LimitReader(resp.Body, MaxPackageFileSize) log.Debug("updater: reading http body") // This use of ReadAll is now safe, because we limited body's Reader. body, err := io.ReadAll(r) if err != nil { return fmt.Errorf("io.ReadAll() failed: %w", err) } _ = os.Mkdir(u.updateDir, 0o755) log.Debug("updater: saving package to file") err = os.WriteFile(u.packageName, body, 0o644) if err != nil { return fmt.Errorf("os.WriteFile() failed: %w", err) } return nil } func tarGzFileUnpackOne(outDir string, tr *tar.Reader, hdr *tar.Header) (name string, err error) { name = filepath.Base(hdr.Name) if name == "" { return "", nil } outputName := filepath.Join(outDir, name) if hdr.Typeflag == tar.TypeDir { if name == "AdGuardHome" { // Top-level AdGuardHome/. Skip it. // // TODO(a.garipov): This whole package needs to be // rewritten and covered in more integration tests. It // has weird assumptions and file mode issues. return "", nil } err = os.Mkdir(outputName, os.FileMode(hdr.Mode&0o755)) if err != nil && !errors.Is(err, os.ErrExist) { return "", fmt.Errorf("os.Mkdir(%q): %w", outputName, err) } log.Debug("updater: created directory %q", outputName) return "", nil } if hdr.Typeflag != tar.TypeReg { log.Info("updater: %s: unknown file type %d, skipping", name, hdr.Typeflag) return "", nil } var wc io.WriteCloser wc, err = os.OpenFile( outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(hdr.Mode&0o755), ) if err != nil { return "", fmt.Errorf("os.OpenFile(%s): %w", outputName, err) } defer func() { err = errors.WithDeferred(err, wc.Close()) }() _, err = io.Copy(wc, tr) if err != nil { return "", fmt.Errorf("io.Copy(): %w", err) } log.Debug("updater: created file %q", outputName) return name, nil } // Unpack all files from .tar.gz file to the specified directory // Existing files are overwritten // All files are created inside outDir, subdirectories are not created // Return the list of files (not directories) written func tarGzFileUnpack(tarfile, outDir string) (files []string, err error) { f, err := os.Open(tarfile) if err != nil { return nil, fmt.Errorf("os.Open(): %w", err) } defer func() { err = errors.WithDeferred(err, f.Close()) }() gzReader, err := gzip.NewReader(f) if err != nil { return nil, fmt.Errorf("gzip.NewReader(): %w", err) } defer func() { err = errors.WithDeferred(err, gzReader.Close()) }() tarReader := tar.NewReader(gzReader) for { var hdr *tar.Header hdr, err = tarReader.Next() if errors.Is(err, io.EOF) { err = nil break } else if err != nil { err = fmt.Errorf("tarReader.Next(): %w", err) break } var name string name, err = tarGzFileUnpackOne(outDir, tarReader, hdr) if name != "" { files = append(files, name) } } return files, err } func zipFileUnpackOne(outDir string, zf *zip.File) (name string, err error) { var rc io.ReadCloser rc, err = zf.Open() if err != nil { return "", fmt.Errorf("zip file Open(): %w", err) } defer func() { err = errors.WithDeferred(err, rc.Close()) }() fi := zf.FileInfo() name = fi.Name() if name == "" { return "", nil } outputName := filepath.Join(outDir, name) if fi.IsDir() { if name == "AdGuardHome" { // Top-level AdGuardHome/. Skip it. // // TODO(a.garipov): See the similar todo in // tarGzFileUnpack. return "", nil } err = os.Mkdir(outputName, fi.Mode()) if err != nil && !errors.Is(err, os.ErrExist) { return "", fmt.Errorf("os.Mkdir(%q): %w", outputName, err) } log.Debug("updater: created directory %q", outputName) return "", nil } var wc io.WriteCloser wc, err = os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode()) if err != nil { return "", fmt.Errorf("os.OpenFile(): %w", err) } defer func() { err = errors.WithDeferred(err, wc.Close()) }() _, err = io.Copy(wc, rc) if err != nil { return "", fmt.Errorf("io.Copy(): %w", err) } log.Debug("updater: created file %q", outputName) return name, nil } // Unpack all files from .zip file to the specified directory // Existing files are overwritten // All files are created inside 'outDir', subdirectories are not created // Return the list of files (not directories) written func zipFileUnpack(zipfile, outDir string) (files []string, err error) { zrc, err := zip.OpenReader(zipfile) if err != nil { return nil, fmt.Errorf("zip.OpenReader(): %w", err) } defer func() { err = errors.WithDeferred(err, zrc.Close()) }() for _, zf := range zrc.File { var name string name, err = zipFileUnpackOne(outDir, zf) if err != nil { break } if name != "" { files = append(files, name) } } return files, err } // Copy file on disk func copyFile(src, dst string) error { d, e := os.ReadFile(src) if e != nil { return e } e = os.WriteFile(dst, d, 0o644) if e != nil { return e } return nil } func copySupportingFiles(files []string, srcdir, dstdir string) error { for _, f := range files { _, name := filepath.Split(f) if name == "AdGuardHome" || name == "AdGuardHome.exe" || name == "AdGuardHome.yaml" { continue } src := filepath.Join(srcdir, name) dst := filepath.Join(dstdir, name) err := copyFile(src, dst) if err != nil && !errors.Is(err, os.ErrNotExist) { return err } log.Debug("updater: copied: %q to %q", src, dst) } return nil } ```
/content/code_sandbox/internal/updater/updater.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,861
```go //go:build windows package arpdb import ( "bufio" "net" "net/netip" "strings" "sync" "github.com/AdguardTeam/golibs/log" ) func newARPDB() (arp *cmdARPDB) { return &cmdARPDB{ parse: parseArpA, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, cmd: "arp", args: []string{"/a"}, } } // parseArpA parses the output of the "arp /a" command on Windows. The expected // input format (the first line is empty): // // Interface: 192.168.56.16 --- 0x7 // Internet Address Physical Address Type // 192.168.56.1 0a-00-27-00-00-00 dynamic // 192.168.56.255 ff-ff-ff-ff-ff-ff static func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() if ln == "" { continue } fields := strings.Fields(ln) if len(fields) != 3 { continue } ip, err := netip.ParseAddr(fields[0]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } mac, err := net.ParseMAC(fields[1]) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } ns = append(ns, Neighbor{ IP: ip, MAC: mac, }) } return ns } ```
/content/code_sandbox/internal/arpdb/arpdb_windows.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
429
```go package arpdb import ( "fmt" "io/fs" "net" "net/netip" "os" "strings" "sync" "testing" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // testdata is the filesystem containing data for testing the package. var testdata fs.FS = os.DirFS("./testdata") // RunCmdFunc is the signature of aghos.RunCommand function. type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error) // substShell replaces the the aghos.RunCommand function used throughout the // package with rc for tests ran under t. func substShell(t testing.TB, rc RunCmdFunc) { t.Helper() prev := aghosRunCommand t.Cleanup(func() { aghosRunCommand = prev }) aghosRunCommand = rc } // mapShell is a substitution of aghos.RunCommand that maps the command to it's // execution result. It's only needed to simplify testing. // // TODO(e.burkov): Perhaps put all the shell interactions behind an interface. type mapShell map[string]struct { err error out string code int } // theOnlyCmd returns mapShell that only handles a single command and arguments // combination from cmd. func theOnlyCmd(cmd string, code int, out string, err error) (s mapShell) { return mapShell{cmd: {code: code, out: out, err: err}} } // RunCmd is a RunCmdFunc handled by s. func (s mapShell) RunCmd(cmd string, args ...string) (code int, out []byte, err error) { key := strings.Join(append([]string{cmd}, args...), " ") ret, ok := s[key] if !ok { return 0, nil, fmt.Errorf("unexpected shell command %q", key) } return ret.code, []byte(ret.out), ret.err } func Test_New(t *testing.T) { var a Interface require.NotPanics(t, func() { a = New() }) assert.NotNil(t, a) } // TODO(s.chzhen): Consider moving mocks into aghtest. // TestARPDB is the mock implementation of [Interface] to use in tests. type TestARPDB struct { OnRefresh func() (err error) OnNeighbors func() (ns []Neighbor) } // type check var _ Interface = (*TestARPDB)(nil) // Refresh implements the [Interface] interface for *TestARPDB. func (arp *TestARPDB) Refresh() (err error) { return arp.OnRefresh() } // Neighbors implements the [Interface] interface for *TestARPDB. func (arp *TestARPDB) Neighbors() (ns []Neighbor) { return arp.OnNeighbors() } func Test_NewARPDBs(t *testing.T) { knownIP := netip.MustParseAddr("1.2.3.4") knownMAC := net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF} succRefrCount, failRefrCount := 0, 0 clnp := func() { succRefrCount, failRefrCount = 0, 0 } succDB := &TestARPDB{ OnRefresh: func() (err error) { succRefrCount++; return nil }, OnNeighbors: func() (ns []Neighbor) { return []Neighbor{{Name: "abc", IP: knownIP, MAC: knownMAC}} }, } failDB := &TestARPDB{ OnRefresh: func() (err error) { failRefrCount++; return errors.Error("refresh failed") }, OnNeighbors: func() (ns []Neighbor) { return nil }, } t.Run("begin_with_success", func(t *testing.T) { t.Cleanup(clnp) a := newARPDBs(succDB, failDB) err := a.Refresh() require.NoError(t, err) assert.Equal(t, 1, succRefrCount) assert.Zero(t, failRefrCount) assert.NotEmpty(t, a.Neighbors()) }) t.Run("begin_with_fail", func(t *testing.T) { t.Cleanup(clnp) a := newARPDBs(failDB, succDB) err := a.Refresh() require.NoError(t, err) assert.Equal(t, 1, succRefrCount) assert.Equal(t, 1, failRefrCount) assert.NotEmpty(t, a.Neighbors()) }) t.Run("fail_only", func(t *testing.T) { t.Cleanup(clnp) wantMsg := "each arpdb failed: refresh failed\nrefresh failed" a := newARPDBs(failDB, failDB) err := a.Refresh() require.Error(t, err) testutil.AssertErrorMsg(t, wantMsg, err) assert.Equal(t, 2, failRefrCount) assert.Empty(t, a.Neighbors()) }) t.Run("fail_after_success", func(t *testing.T) { t.Cleanup(clnp) shouldFail := false unstableDB := &TestARPDB{ OnRefresh: func() (err error) { if shouldFail { err = errors.Error("unstable failed") } shouldFail = !shouldFail return err }, OnNeighbors: func() (ns []Neighbor) { if !shouldFail { return failDB.OnNeighbors() } return succDB.OnNeighbors() }, } a := newARPDBs(unstableDB, succDB) // Unstable ARPDB should refresh successfully. err := a.Refresh() require.NoError(t, err) assert.Zero(t, succRefrCount) assert.NotEmpty(t, a.Neighbors()) // Unstable ARPDB should fail and the succDB should be used. err = a.Refresh() require.NoError(t, err) assert.Equal(t, 1, succRefrCount) assert.NotEmpty(t, a.Neighbors()) // Unstable ARPDB should refresh successfully again. err = a.Refresh() require.NoError(t, err) assert.Equal(t, 1, succRefrCount) assert.NotEmpty(t, a.Neighbors()) }) t.Run("empty", func(t *testing.T) { a := newARPDBs() require.NoError(t, a.Refresh()) assert.Empty(t, a.Neighbors()) }) } func TestCmdARPDB_arpa(t *testing.T) { a := &cmdARPDB{ cmd: "cmd", parse: parseArpA, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, } t.Run("arp_a", func(t *testing.T) { sh := theOnlyCmd("cmd", 0, arpAOutput, nil) substShell(t, sh.RunCmd) err := a.Refresh() require.NoError(t, err) assert.Equal(t, wantNeighs, a.Neighbors()) }) t.Run("runcmd_error", func(t *testing.T) { sh := theOnlyCmd("cmd", 0, "", errors.Error("can't run")) substShell(t, sh.RunCmd) err := a.Refresh() testutil.AssertErrorMsg(t, "cmd arpdb: running command: can't run", err) }) t.Run("bad_code", func(t *testing.T) { sh := theOnlyCmd("cmd", 1, "", nil) substShell(t, sh.RunCmd) err := a.Refresh() testutil.AssertErrorMsg(t, "cmd arpdb: running command: unexpected exit code 1", err) }) t.Run("empty", func(t *testing.T) { sh := theOnlyCmd("cmd", 0, "", nil) substShell(t, sh.RunCmd) err := a.Refresh() require.NoError(t, err) assert.Empty(t, a.Neighbors()) }) } func TestEmptyARPDB(t *testing.T) { a := Empty{} t.Run("refresh", func(t *testing.T) { var err error require.NotPanics(t, func() { err = a.Refresh() }) assert.NoError(t, err) }) t.Run("neighbors", func(t *testing.T) { var ns []Neighbor require.NotPanics(t, func() { ns = a.Neighbors() }) assert.Empty(t, ns) }) } ```
/content/code_sandbox/internal/arpdb/arpdb_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,901
```go //go:build windows package arpdb import ( "net" "net/netip" ) const arpAOutput = ` Interface: 192.168.1.1 --- 0x7 Internet Address Physical Address Type 192.168.1.2 ab-cd-ef-ab-cd-ef dynamic ::ffff:ffff ef-cd-ab-ef-cd-ab static` var wantNeighs = []Neighbor{{ IP: netip.MustParseAddr("192.168.1.2"), MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF}, }, { IP: netip.MustParseAddr("::ffff:ffff"), MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB}, }} ```
/content/code_sandbox/internal/arpdb/arpdb_windows_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
203
```go //go:build openbsd package arpdb import ( "bufio" "net" "net/netip" "strings" "sync" "github.com/AdguardTeam/golibs/log" ) func newARPDB() (arp *cmdARPDB) { return &cmdARPDB{ parse: parseArpA, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, cmd: "arp", // Use -n flag to avoid resolving the hostnames of the neighbors. By // default ARP attempts to resolve the hostnames via DNS. See man 8 // arp. // // See also path_to_url args: []string{"-a", "-n"}, } } // parseArpA parses the output of the "arp -a -n" command on OpenBSD. The // expected input format: // // Host Ethernet Address Netif Expire Flags // 192.168.1.1 ab:cd:ef:ab:cd:ef em0 19m59s func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) { // Skip the header. if !sc.Scan() { return nil } ns = make([]Neighbor, 0, lenHint) for sc.Scan() { ln := sc.Text() fields := strings.Fields(ln) if len(fields) < 2 { continue } n := Neighbor{} ip, err := netip.ParseAddr(fields[0]) if err != nil { log.Debug("arpdb: parsing arp output: ip: %s", err) continue } else { n.IP = ip } mac, err := net.ParseMAC(fields[1]) if err != nil { log.Debug("arpdb: parsing arp output: mac: %s", err) continue } else { n.MAC = mac } ns = append(ns, n) } return ns } ```
/content/code_sandbox/internal/arpdb/arpdb_openbsd.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
467
```go // Package arpdb implements the Network Neighborhood Database. package arpdb import ( "bufio" "bytes" "fmt" "net" "net/netip" "slices" "sync" "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/osutil" ) // Variables and functions to substitute in tests. var ( // aghosRunCommand is the function to run shell commands. aghosRunCommand = aghos.RunCommand // rootDirFS is the filesystem pointing to the root directory. rootDirFS = osutil.RootDirFS() ) // Interface stores and refreshes the network neighborhood reported by ARP // (Address Resolution Protocol). type Interface interface { // Refresh updates the stored data. It must be safe for concurrent use. Refresh() (err error) // Neighbors returnes the last set of data reported by ARP. Both the method // and it's result must be safe for concurrent use. Neighbors() (ns []Neighbor) } // New returns the [Interface] properly initialized for the OS. func New() (arp Interface) { return newARPDB() } // Empty is the [Interface] implementation that does nothing. type Empty struct{} // type check var _ Interface = Empty{} // Refresh implements the [Interface] interface for EmptyARPContainer. It does // nothing and always returns nil error. func (Empty) Refresh() (err error) { return nil } // Neighbors implements the [Interface] interface for EmptyARPContainer. It // always returns nil. func (Empty) Neighbors() (ns []Neighbor) { return nil } // Neighbor is the pair of IP address and MAC address reported by ARP. type Neighbor struct { // Name is the hostname of the neighbor. Empty name is valid since not each // implementation of ARP is able to retrieve that. Name string // IP contains either IPv4 or IPv6. IP netip.Addr // MAC contains the hardware address. MAC net.HardwareAddr } // Clone returns the deep copy of n. func (n Neighbor) Clone() (clone Neighbor) { return Neighbor{ Name: n.Name, IP: n.IP, MAC: slices.Clone(n.MAC), } } // validatedHostname returns h if it's a valid hostname, or an empty string // otherwise, logging the validation error. func validatedHostname(h string) (host string) { err := netutil.ValidateHostname(h) if err != nil { log.Debug("arpdb: parsing arp output: host: %s", err) return "" } return h } // neighs is the helper type that stores neighbors to avoid copying its methods // among all the [Interface] implementations. type neighs struct { mu *sync.RWMutex ns []Neighbor } // len returns the length of the neighbors slice. It's safe for concurrent use. func (ns *neighs) len() (l int) { ns.mu.RLock() defer ns.mu.RUnlock() return len(ns.ns) } // clone returns a deep copy of the underlying neighbors slice. It's safe for // concurrent use. func (ns *neighs) clone() (cloned []Neighbor) { ns.mu.RLock() defer ns.mu.RUnlock() cloned = make([]Neighbor, len(ns.ns)) for i, n := range ns.ns { cloned[i] = n.Clone() } return cloned } // reset replaces the underlying slice with the new one. It's safe for // concurrent use. func (ns *neighs) reset(with []Neighbor) { ns.mu.Lock() defer ns.mu.Unlock() ns.ns = with } // parseNeighsFunc parses the text from sc as if it'd be an output of some // ARP-related command. lenHint is a hint for the size of the allocated slice // of Neighbors. type parseNeighsFunc func(sc *bufio.Scanner, lenHint int) (ns []Neighbor) // cmdARPDB is the implementation of the [Interface] that uses command line to // retrieve data. type cmdARPDB struct { parse parseNeighsFunc ns *neighs cmd string args []string } // type check var _ Interface = (*cmdARPDB)(nil) // Refresh implements the [Interface] interface for *cmdARPDB. func (arp *cmdARPDB) Refresh() (err error) { defer func() { err = errors.Annotate(err, "cmd arpdb: %w") }() code, out, err := aghosRunCommand(arp.cmd, arp.args...) if err != nil { return fmt.Errorf("running command: %w", err) } else if code != 0 { return fmt.Errorf("running command: unexpected exit code %d", code) } sc := bufio.NewScanner(bytes.NewReader(out)) ns := arp.parse(sc, arp.ns.len()) if err = sc.Err(); err != nil { // TODO(e.burkov): This error seems unreachable. Investigate. return fmt.Errorf("scanning the output: %w", err) } arp.ns.reset(ns) return nil } // Neighbors implements the [Interface] interface for *cmdARPDB. func (arp *cmdARPDB) Neighbors() (ns []Neighbor) { return arp.ns.clone() } // arpdbs is the [Interface] that combines several [Interface] implementations // and consequently switches between those. type arpdbs struct { // arps is the set of [Interface] implementations to range through. arps []Interface neighs } // newARPDBs returns a properly initialized *arpdbs. It begins refreshing from // the first of arps. func newARPDBs(arps ...Interface) (arp *arpdbs) { return &arpdbs{ arps: arps, neighs: neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, } } // type check var _ Interface = (*arpdbs)(nil) // Refresh implements the [Interface] interface for *arpdbs. func (arp *arpdbs) Refresh() (err error) { var errs []error for _, a := range arp.arps { err = a.Refresh() if err != nil { errs = append(errs, err) continue } arp.reset(a.Neighbors()) return nil } return errors.Annotate(errors.Join(errs...), "each arpdb failed: %w") } // Neighbors implements the [Interface] interface for *arpdbs. // // TODO(e.burkov): Think of a way to avoid cloning the slice twice. func (arp *arpdbs) Neighbors() (ns []Neighbor) { return arp.clone() } ```
/content/code_sandbox/internal/arpdb/arpdb.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,521
```go //go:build openbsd package arpdb import ( "net" "net/netip" ) const arpAOutput = ` Host Ethernet Address Netif Expire Flags 1.2.3.4.5 aa:bb:cc:dd:ee:ff em0 permanent 1.2.3.4 12:34:56:78:910 em0 permanent 192.168.1.2 ab:cd:ef:ab:cd:ef em0 19m56s ::ffff:ffff ef:cd:ab:ef:cd:ab em0 permanent l ` var wantNeighs = []Neighbor{{ IP: netip.MustParseAddr("192.168.1.2"), MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF}, }, { IP: netip.MustParseAddr("::ffff:ffff"), MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB}, }} ```
/content/code_sandbox/internal/arpdb/arpdb_openbsd_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
247
```go //go:build linux package arpdb import ( "net" "net/netip" "sync" "testing" "testing/fstest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const arpAOutputWrt = ` IP address HW type Flags HW address Mask Device 1.2.3.4.5 0x1 0x2 aa:bb:cc:dd:ee:ff * wan 1.2.3.4 0x1 0x2 12:34:56:78:910 * wan 192.168.1.2 0x1 0x2 ab:cd:ef:ab:cd:ef * wan ::ffff:ffff 0x1 0x2 ef:cd:ab:ef:cd:ab * wan` const arpAOutput = ` invalid.mac (1.2.3.4) at 12:34:56:78:910 on el0 ifscope [ethernet] invalid.ip (1.2.3.4.5) at ab:cd:ef:ab:cd:12 on ek0 ifscope [ethernet] invalid.fmt 1 at 12:cd:ef:ab:cd:ef on er0 ifscope [ethernet] ? (192.168.1.2) at ab:cd:ef:ab:cd:ef on en0 ifscope [ethernet] ? (::ffff:ffff) at ef:cd:ab:ef:cd:ab on em0 expires in 100 seconds [ethernet]` const ipNeighOutput = ` 1.2.3.4.5 dev enp0s3 lladdr aa:bb:cc:dd:ee:ff DELAY 1.2.3.4 dev enp0s3 lladdr 12:34:56:78:910 DELAY 192.168.1.2 dev enp0s3 lladdr ab:cd:ef:ab:cd:ef DELAY ::ffff:ffff dev enp0s3 lladdr ef:cd:ab:ef:cd:ab router STALE` var wantNeighs = []Neighbor{{ IP: netip.MustParseAddr("192.168.1.2"), MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF}, }, { IP: netip.MustParseAddr("::ffff:ffff"), MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB}, }} func TestFSysARPDB(t *testing.T) { require.NoError(t, fstest.TestFS(testdata, "proc_net_arp")) a := &fsysARPDB{ ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, fsys: testdata, filename: "proc_net_arp", } err := a.Refresh() require.NoError(t, err) ns := a.Neighbors() assert.Equal(t, wantNeighs, ns) } func TestCmdARPDB_linux(t *testing.T) { sh := mapShell{ "arp -a": {err: nil, out: arpAOutputWrt, code: 0}, "ip neigh": {err: nil, out: ipNeighOutput, code: 0}, } substShell(t, sh.RunCmd) t.Run("wrt", func(t *testing.T) { a := &cmdARPDB{ parse: parseArpAWrt, cmd: "arp", args: []string{"-a"}, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, } err := a.Refresh() require.NoError(t, err) assert.Equal(t, wantNeighs, a.Neighbors()) }) t.Run("ip_neigh", func(t *testing.T) { a := &cmdARPDB{ parse: parseIPNeigh, cmd: "ip", args: []string{"neigh"}, ns: &neighs{ mu: &sync.RWMutex{}, ns: make([]Neighbor, 0), }, } err := a.Refresh() require.NoError(t, err) assert.Equal(t, wantNeighs, a.Neighbors()) }) } ```
/content/code_sandbox/internal/arpdb/arpdb_linux_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,014
```go package querylog import ( "fmt" "io" "os" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" ) // qLogReader allows reading from multiple query log files in the reverse // order. // // Please note that this is a stateful object. Internally, it contains a // pointer to a particular query log file, and to a specific position in this // file, and it reads lines in reverse order starting from that position. type qLogReader struct { // qFiles is an array with the query log files. The order is from oldest // to newest. qFiles []*qLogFile // currentFile is the index of the current file. currentFile int } // newQLogReader initializes a qLogReader instance with the specified files. func newQLogReader(files []string) (*qLogReader, error) { qFiles := make([]*qLogFile, 0) for _, f := range files { q, err := newQLogFile(f) if err != nil { if errors.Is(err, os.ErrNotExist) { continue } // Close what we've already opened. cErr := closeQFiles(qFiles) if cErr != nil { log.Debug("querylog: closing files: %s", cErr) } return nil, err } qFiles = append(qFiles, q) } return &qLogReader{qFiles: qFiles, currentFile: len(qFiles) - 1}, nil } // seekTS performs binary search of a query log record with the specified // timestamp. If the record is found, it sets qLogReader's position to point // to that line, so that the next ReadNext call returned this line. func (r *qLogReader) seekTS(timestamp int64) (err error) { for i := len(r.qFiles) - 1; i >= 0; i-- { q := r.qFiles[i] _, _, err = q.seekTS(timestamp) if err != nil { if errors.Is(err, errTSTooEarly) { // Look at the next file, since we've reached the end of this // one. If there is no next file, it's not found. err = errTSNotFound continue } else if errors.Is(err, errTSTooLate) { // Just seek to the start then. timestamp is probably between // the end of the previous one and the start of this one. return r.SeekStart() } else if errors.Is(err, errTSNotFound) { return err } else { return fmt.Errorf("seekts: file at index %d: %w", i, err) } } // The search is finished, and the searched element has been found. // Update currentFile only, position is already set properly in // qLogFile. r.currentFile = i return nil } if err != nil { return fmt.Errorf("seekts: %w", err) } return nil } // SeekStart changes the current position to the end of the newest file. // Please note that we're reading query log in the reverse order and that's why // the log starts actually at the end of file. // // Returns nil if we were able to change the current position. Returns error // in any other cases. func (r *qLogReader) SeekStart() error { if len(r.qFiles) == 0 { return nil } r.currentFile = len(r.qFiles) - 1 _, err := r.qFiles[r.currentFile].SeekStart() return err } // ReadNext reads the next line (in the reverse order) from the query log // files. Then shifts the current position left to the next (actually prev) // line (or the next file). // // Returns io.EOF if there is nothing more to read. func (r *qLogReader) ReadNext() (string, error) { if len(r.qFiles) == 0 { return "", io.EOF } for r.currentFile >= 0 { q := r.qFiles[r.currentFile] line, err := q.ReadNext() if err != nil { // Shift to the older file. r.currentFile-- if r.currentFile < 0 { break } q = r.qFiles[r.currentFile] // Set its position to the start right away. _, err = q.SeekStart() // This is unexpected, return an error right away. if err != nil { return "", err } } else { return line, nil } } // Nothing to read anymore. return "", io.EOF } // Close closes the qLogReader. func (r *qLogReader) Close() error { return closeQFiles(r.qFiles) } // closeQFiles is a helper method to close multiple qLogFile instances. func closeQFiles(qFiles []*qLogFile) (err error) { var errs []error for _, q := range qFiles { err = q.Close() if err != nil { errs = append(errs, err) } } return errors.Annotate(errors.Join(errs...), "closing qLogReader: %w") } ```
/content/code_sandbox/internal/querylog/qlogreader.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,182
```go package querylog import ( "fmt" "io" "os" "strings" "sync" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" ) const ( // Timestamp not found errors. errTSNotFound errors.Error = "ts not found" errTSTooLate errors.Error = "ts too late" errTSTooEarly errors.Error = "ts too early" // maxEntrySize is a maximum size of the entry. // // TODO: Find a way to grow buffer instead of relying on this value when // reading strings. maxEntrySize = 16 * 1024 // bufferSize should be enough for at least this number of entries. bufferSize = 100 * maxEntrySize ) // qLogFile represents a single query log file. It allows reading from the // file in the reverse order. // // Please note, that this is a stateful object. Internally, it contains a // pointer to a specific position in the file, and it reads lines in reverse // order starting from that position. type qLogFile struct { // file is the query log file. file *os.File // buffer that we've read from the file. buffer []byte // lock is a mutex to make it thread-safe. lock sync.Mutex // position is the position in the file. position int64 // bufferStart is the start of the buffer (in the file). bufferStart int64 // bufferLen is the length of the buffer. bufferLen int } // newQLogFile initializes a new instance of the qLogFile. func newQLogFile(path string) (qf *qLogFile, err error) { f, err := os.OpenFile(path, os.O_RDONLY, 0o644) if err != nil { return nil, err } return &qLogFile{file: f}, nil } // validateQLogLineIdx returns error if the line index is not valid to continue // search. func (q *qLogFile) validateQLogLineIdx(lineIdx, lastProbeLineIdx, ts, fSize int64) (err error) { if lineIdx == lastProbeLineIdx { if lineIdx == 0 { return errTSTooEarly } // If we're testing the same line twice then most likely the scope is // too narrow and we won't find anything anymore in any other file. return fmt.Errorf("looking up timestamp %d in %q: %w", ts, q.file.Name(), errTSNotFound) } else if lineIdx == fSize { return errTSTooLate } return nil } // seekTS performs binary search in the query log file looking for a record // with the specified timestamp. Once the record is found, it sets "position" // so that the next ReadNext call returned that record. // // The algorithm is rather simple: // 1. It starts with the position in the middle of a file. // 2. Shifts back to the beginning of the line. // 3. Checks the log record timestamp. // 4. If it is lower than the timestamp we are looking for, it shifts seek // position to 3/4 of the file. Otherwise, to 1/4 of the file. // 5. It performs the search again, every time the search scope is narrowed // twice. // // Returns: // - It returns the position of the line with the timestamp we were looking // for so that when we call "ReadNext" this line was returned. // - Depth of the search (how many times we compared timestamps). // - If we could not find it, it returns one of the errors described above. func (q *qLogFile) seekTS(timestamp int64) (pos int64, depth int, err error) { q.lock.Lock() defer q.lock.Unlock() // Empty the buffer. q.buffer = nil // First of all, check the file size. fileInfo, err := q.file.Stat() if err != nil { return 0, 0, err } // Define the search scope. // Start of the search interval (position in the file). start := int64(0) // End of the search interval (position in the file). end := fileInfo.Size() // Probe is the approximate index of the line we'll try to check. probe := (end - start) / 2 var line string // Index of the probe line in the file. var lineIdx int64 var lineEndIdx int64 // Index of the last probe line. var lastProbeLineIdx int64 lastProbeLineIdx = -1 // Count seek depth in order to detect mistakes. If depth is too large, // we should stop the search. for { // Get the line at the specified position. line, lineIdx, lineEndIdx, err = q.readProbeLine(probe) if err != nil { return 0, depth, err } // Check if the line index if invalid. err = q.validateQLogLineIdx(lineIdx, lastProbeLineIdx, timestamp, fileInfo.Size()) if err != nil { return 0, depth, err } // Save the last found idx. lastProbeLineIdx = lineIdx // Get the timestamp from the query log record. ts := readQLogTimestamp(line) if ts == 0 { return 0, depth, fmt.Errorf( "looking up timestamp %d in %q: record %q has empty timestamp", timestamp, q.file.Name(), line, ) } if ts == timestamp { // Hurray, returning the result. break } // Narrow the scope and repeat the search. if ts > timestamp { // If the timestamp we're looking for is OLDER than what we found, // then the line is somewhere on the LEFT side from the current // probe position. end = lineIdx } else { // If the timestamp we're looking for is NEWER than what we found, // then the line is somewhere on the RIGHT side from the current // probe position. start = lineEndIdx } probe = start + (end-start)/2 depth++ if depth >= 100 { return 0, depth, fmt.Errorf( "looking up timestamp %d in %q: depth %d too high: %w", timestamp, q.file.Name(), depth, errTSNotFound, ) } } q.position = lineIdx + int64(len(line)) return q.position, depth, nil } // SeekStart changes the current position to the end of the file. Please note, // that we're reading query log in the reverse order and that's why log start // is actually the end of file. // // Returns nil if we were able to change the current position. Returns error // in any other case. func (q *qLogFile) SeekStart() (int64, error) { q.lock.Lock() defer q.lock.Unlock() // Empty the buffer. q.buffer = nil // First of all, check the file size. fileInfo, err := q.file.Stat() if err != nil { return 0, err } // Place the position to the very end of file. q.position = fileInfo.Size() - 1 if q.position < 0 { q.position = 0 } return q.position, nil } // ReadNext reads the next line (in the reverse order) from the file and shifts // the current position left to the next (actually prev) line. // // Returns io.EOF if there's nothing more to read. func (q *qLogFile) ReadNext() (string, error) { q.lock.Lock() defer q.lock.Unlock() if q.position == 0 { return "", io.EOF } line, lineIdx, err := q.readNextLine(q.position) if err != nil { return "", err } // Shift position. if lineIdx == 0 { q.position = 0 } else { // There's usually a line break before the line, so we should shift one // more char left from the line "\nline". q.position = lineIdx - 1 } return line, err } // Close frees the underlying resources. func (q *qLogFile) Close() error { return q.file.Close() } // readNextLine reads the next line from the specified position. This line // actually have to END on that position. // // The algorithm is: // 1. Check if we have the buffer initialized. // 2. If it is so, scan it and look for the line there. // 3. If we cannot find the line there, read the prev chunk into the buffer. // 4. Read the line from the buffer. func (q *qLogFile) readNextLine(position int64) (string, int64, error) { relativePos := position - q.bufferStart if q.buffer == nil || (relativePos < maxEntrySize && q.bufferStart != 0) { // Time to re-init the buffer. err := q.initBuffer(position) if err != nil { return "", 0, err } relativePos = position - q.bufferStart } // Look for the end of the prev line, this is where we'll read from. startLine := int64(0) for i := relativePos - 1; i >= 0; i-- { if q.buffer[i] == '\n' { startLine = i + 1 break } } line := string(q.buffer[startLine:relativePos]) lineIdx := q.bufferStart + startLine return line, lineIdx, nil } // initBuffer initializes the qLogFile buffer. The goal is to read a chunk of // file that includes the line with the specified position. func (q *qLogFile) initBuffer(position int64) error { q.bufferStart = int64(0) if position > bufferSize { q.bufferStart = position - bufferSize } // Seek to this position. _, err := q.file.Seek(q.bufferStart, io.SeekStart) if err != nil { return err } if q.buffer == nil { q.buffer = make([]byte, bufferSize) } q.bufferLen, err = q.file.Read(q.buffer) return err } // readProbeLine reads a line that includes the specified position. This // method is supposed to be used when we use binary search in the Seek method. // In the case of consecutive reads, use readNext, cause it uses better buffer. func (q *qLogFile) readProbeLine(position int64) (string, int64, int64, error) { // First of all, we should read a buffer that will include the query log // line. In order to do this, we'll define the boundaries. seekPosition := int64(0) // Position relative to the buffer we're going to read. relativePos := position if position > maxEntrySize { seekPosition = position - maxEntrySize relativePos = maxEntrySize } // Seek to this position. _, err := q.file.Seek(seekPosition, io.SeekStart) if err != nil { return "", 0, 0, err } // The buffer size is 2*maxEntrySize. buffer := make([]byte, maxEntrySize*2) bufferLen, err := q.file.Read(buffer) if err != nil { return "", 0, 0, err } // Now start looking for the new line character starting from the // relativePos and going left. startLine := int64(0) for i := relativePos - 1; i >= 0; i-- { if buffer[i] == '\n' { startLine = i + 1 break } } // Looking for the end of line now. endLine := int64(bufferLen) lineEndIdx := endLine + seekPosition for i := relativePos; i < int64(bufferLen); i++ { if buffer[i] == '\n' { endLine = i lineEndIdx = endLine + seekPosition + 1 break } } // Finally we can return the string we were looking for. lineIdx := startLine + seekPosition return string(buffer[startLine:endLine]), lineIdx, lineEndIdx, nil } // readJSONValue reads a JSON string in form of '"key":"value"'. prefix must // be of the form '"key":"' to generate less garbage. func readJSONValue(s, prefix string) string { i := strings.Index(s, prefix) if i == -1 { return "" } start := i + len(prefix) i = strings.IndexByte(s[start:], '"') if i == -1 { return "" } end := start + i return s[start:end] } // readQLogTimestamp reads the timestamp field from the query log line. func readQLogTimestamp(str string) int64 { val := readJSONValue(str, `"T":"`) if len(val) == 0 { val = readJSONValue(str, `"Time":"`) } if len(val) == 0 { log.Error("Couldn't find timestamp: %s", str) return 0 } tm, err := time.Parse(time.RFC3339Nano, val) if err != nil { log.Error("Couldn't parse timestamp: %s", val) return 0 } return tm.UnixNano() } ```
/content/code_sandbox/internal/querylog/qlogfile.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,015
```go package querylog import "time" // searchParams represent the search query sent by the client. type searchParams struct { // olderThen represents a parameter for entries that are older than this // parameter value. If not set, disregard it and return any value. olderThan time.Time // searchCriteria is a list of search criteria that we use to get filter // results. searchCriteria []searchCriterion // offset for the search. offset int // limit the number of records returned. limit int // maxFileScanEntries is a maximum of log entries to scan in query log // files. If not set, then no limit. maxFileScanEntries int } // newSearchParams - creates an empty instance of searchParams func newSearchParams() *searchParams { return &searchParams{ // default max log entries to return limit: 500, // by default, we scan up to 50k entries at once maxFileScanEntries: 50000, } } // quickMatchClientFunc is a simplified client finder for quick matches. type quickMatchClientFunc = func(clientID, ip string) (c *Client) // quickMatch quickly checks if the line matches the given search parameters. // It returns false if the line doesn't match. This method is only here for // optimization purposes. func (s *searchParams) quickMatch(line string, findClient quickMatchClientFunc) (ok bool) { for _, c := range s.searchCriteria { if !c.quickMatch(line, findClient) { return false } } return true } // match - checks if the logEntry matches the searchParams func (s *searchParams) match(entry *logEntry) bool { if !s.olderThan.IsZero() && !entry.Time.Before(s.olderThan) { // Ignore entries newer than what was requested return false } for _, c := range s.searchCriteria { if !c.match(entry) { return false } } return true } ```
/content/code_sandbox/internal/querylog/searchparams.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
446
```go package querylog import ( "bytes" "encoding/base64" "net" "net/netip" "strings" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghtest" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/urlfilter/rules" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDecodeLogEntry(t *testing.T) { logOutput := &bytes.Buffer{} aghtest.ReplaceLogWriter(t, logOutput) aghtest.ReplaceLogLevel(t, log.DEBUG) t.Run("success", func(t *testing.T) { const ansStr = `Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==` const data = `{"IP":"127.0.0.1",` + `"CID":"cli42",` + `"T":"2020-11-25T18:55:56.519796+03:00",` + `"QH":"an.yandex.ru",` + `"QT":"A",` + `"QC":"IN",` + `"CP":"",` + `"ECS":"1.2.3.0/24",` + `"Answer":"` + ansStr + `",` + `"Cached":true,` + `"AD":true,` + `"Result":{` + `"IsFiltered":true,` + `"Reason":3,` + `"IPList":["127.0.0.2"],` + `"Rules":[{"FilterListID":42,"Text":"||an.yandex.ru","IP":"127.0.0.2"},` + `{"FilterListID":43,"Text":"||an2.yandex.ru","IP":"127.0.0.3"}],` + `"CanonName":"example.com",` + `"ServiceName":"example.org",` + `"DNSRewriteResult":{"RCode":0,"Response":{"1":["127.0.0.2"]}}},` + `"Upstream":"path_to_url",` + `"Elapsed":837429}` ans, err := base64.StdEncoding.DecodeString(ansStr) require.NoError(t, err) want := &logEntry{ IP: net.IPv4(127, 0, 0, 1), Time: time.Date(2020, 11, 25, 15, 55, 56, 519796000, time.UTC), QHost: "an.yandex.ru", QType: "A", QClass: "IN", ClientID: "cli42", ClientProto: "", ReqECS: "1.2.3.0/24", Answer: ans, Cached: true, Result: filtering.Result{ DNSRewriteResult: &filtering.DNSRewriteResult{ RCode: dns.RcodeSuccess, Response: filtering.DNSRewriteResultResponse{ dns.TypeA: []rules.RRValue{net.IPv4(127, 0, 0, 2)}, }, }, CanonName: "example.com", ServiceName: "example.org", IPList: []netip.Addr{netip.AddrFrom4([4]byte{127, 0, 0, 2})}, Rules: []*filtering.ResultRule{{ FilterListID: 42, Text: "||an.yandex.ru", IP: netip.AddrFrom4([4]byte{127, 0, 0, 2}), }, { FilterListID: 43, Text: "||an2.yandex.ru", IP: netip.AddrFrom4([4]byte{127, 0, 0, 3}), }}, Reason: filtering.FilteredBlockList, IsFiltered: true, }, Upstream: "path_to_url", Elapsed: 837429, AuthenticatedData: true, } got := &logEntry{} decodeLogEntry(got, data) s := logOutput.String() assert.Empty(t, s) // Correct for time zones. got.Time = got.Time.UTC() assert.Equal(t, want, got) }) testCases := []struct { name string log string want string }{{ name: "all_right_old_rule", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3,"Rule":"||an.yandex.","FilterID":1,"ReverseHosts":["example.com"],"IPList":["127.0.0.1"]},"Elapsed":837429}`, want: "", }, { name: "bad_filter_id_old_rule", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3,"FilterID":1.5},"Elapsed":837429}`, want: "decodeResult handler err: strconv.ParseInt: parsing \"1.5\": invalid syntax\n", }, { name: "bad_is_filtered", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":trooe,"Reason":3},"Elapsed":837429}`, want: "decodeLogEntry err: invalid character 'o' in literal true (expecting 'u')\n", }, { name: "bad_elapsed", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":-1}`, want: "", }, { name: "bad_ip", log: `{"IP":127001,"T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "bad_time", log: `{"IP":"127.0.0.1","T":"12/09/1998T15:00:00.000000+05:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "decodeLogEntry handler err: parsing time \"12/09/1998T15:00:00.000000+05:00\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \"12/09/1998T15:00:00.000000+05:00\" as \"2006\"\n", }, { name: "bad_host", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":6,"QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "bad_type", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":true,"QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "bad_class", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":false,"CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "bad_client_proto", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":8,"Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "very_bad_client_proto", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"dog","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "decodeLogEntry handler err: invalid client proto: \"dog\"\n", }, { name: "bad_answer", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":0.9,"Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "", }, { name: "very_bad_answer", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3},"Elapsed":837429}`, want: "decodeLogEntry handler err: illegal base64 data at input byte 61\n", }, { name: "bad_rule", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3,"Rule":false},"Elapsed":837429}`, want: "", }, { name: "bad_reason", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":true},"Elapsed":837429}`, want: "", }, { name: "bad_reverse_hosts", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3,"ReverseHosts":[{}]},"Elapsed":837429}`, want: "decodeResultReverseHosts: unexpected delim \"{\"\n", }, { name: "bad_ip_list", log: `{"IP":"127.0.0.1","T":"2020-11-25T18:55:56.519796+03:00","QH":"an.yandex.ru","QT":"A","QC":"IN","CP":"","Answer":"Qz+BgAABAAEAAAAAAmFuBnlhbmRleAJydQAAAQABwAwAAQABAAAACgAEAAAAAA==","Result":{"IsFiltered":true,"Reason":3,"ReverseHosts":["example.net"],"IPList":[{}]},"Elapsed":837429}`, want: "decodeResultIPList: unexpected delim \"{\"\n", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { decodeLogEntry(new(logEntry), tc.log) s := logOutput.String() if tc.want == "" { assert.Empty(t, s) } else { assert.True(t, strings.HasSuffix(s, tc.want), "got %q", s) } logOutput.Reset() }) } } func TestDecodeLogEntry_backwardCompatability(t *testing.T) { var ( a1 = netutil.IPv4Localhost() a2 = a1.Next() aaaa1 = netutil.IPv6Localhost() aaaa2 = aaaa1.Next() ) testCases := []struct { want *logEntry entry string name string }{{ entry: `{"Result":{"ReverseHosts":["example.net","example.org"]}`, want: &logEntry{ Result: filtering.Result{DNSRewriteResult: &filtering.DNSRewriteResult{ RCode: dns.RcodeSuccess, Response: filtering.DNSRewriteResultResponse{ dns.TypePTR: []rules.RRValue{"example.net.", "example.org."}, }, }}, }, name: "reverse_hosts", }, { entry: `{"Result":{"IPList":["127.0.0.1","127.0.0.2","::1","::2"],"Reason":10}}`, want: &logEntry{ Result: filtering.Result{ DNSRewriteResult: &filtering.DNSRewriteResult{ RCode: dns.RcodeSuccess, Response: filtering.DNSRewriteResultResponse{ dns.TypeA: []rules.RRValue{a1, a2}, dns.TypeAAAA: []rules.RRValue{aaaa1, aaaa2}, }, }, Reason: filtering.RewrittenAutoHosts, }, }, name: "iplist_autohosts", }, { entry: `{"Result":{"IPList":["127.0.0.1","127.0.0.2","::1","::2"],"Reason":9}}`, want: &logEntry{ Result: filtering.Result{ IPList: []netip.Addr{ a1, a2, aaaa1, aaaa2, }, Reason: filtering.Rewritten, }, }, name: "iplist_rewritten", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := &logEntry{} decodeLogEntry(e, tc.entry) assert.Equal(t, tc.want, e) }) } } // anonymizeIPSlow masks ip to anonymize the client if the ip is a valid one. // It only exists in purposes of benchmark comparison, see BenchmarkAnonymizeIP. func anonymizeIPSlow(ip net.IP) { if ip4 := ip.To4(); ip4 != nil { copy(ip4[net.IPv4len-2:net.IPv4len], []byte{0, 0}) } else if len(ip) == net.IPv6len { copy(ip[net.IPv6len-10:net.IPv6len], []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) } } func BenchmarkAnonymizeIP(b *testing.B) { benchCases := []struct { name string ip net.IP want net.IP }{{ name: "v4", ip: net.IP{1, 2, 3, 4}, want: net.IP{1, 2, 0, 0}, }, { name: "v4_mapped", ip: net.IP{1, 2, 3, 4}.To16(), want: net.IP{1, 2, 0, 0}.To16(), }, { name: "v6", ip: net.IP{ 0xa, 0xb, 0x0, 0x0, 0x0, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, }, want: net.IP{ 0xa, 0xb, 0x0, 0x0, 0x0, 0xb, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }, }, { name: "invalid", ip: net.IP{1, 2, 3}, want: net.IP{1, 2, 3}, }} for _, bc := range benchCases { b.Run(bc.name, func(b *testing.B) { b.ReportAllocs() for range b.N { AnonymizeIP(bc.ip) } assert.Equal(b, bc.want, bc.ip) }) b.Run(bc.name+"_slow", func(b *testing.B) { b.ReportAllocs() for range b.N { anonymizeIPSlow(bc.ip) } assert.Equal(b, bc.want, bc.ip) }) } } ```
/content/code_sandbox/internal/querylog/decode_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
4,654
```go package querylog import ( "slices" "strconv" "strings" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/log" "github.com/miekg/dns" "golang.org/x/net/idna" ) // TODO(a.garipov): Use a proper structured approach here. // jobject is a JSON object alias. type jobject = map[string]any // entriesToJSON converts query log entries to JSON. func entriesToJSON( entries []*logEntry, oldest time.Time, anonFunc aghnet.IPMutFunc, ) (res jobject) { data := make([]jobject, 0, len(entries)) // The elements order is already reversed to be from newer to older. for _, entry := range entries { jsonEntry := entryToJSON(entry, anonFunc) data = append(data, jsonEntry) } res = jobject{ "data": data, "oldest": "", } if !oldest.IsZero() { res["oldest"] = oldest.Format(time.RFC3339Nano) } return res } // entryToJSON converts a log entry's data into an entry for the JSON API. func entryToJSON(entry *logEntry, anonFunc aghnet.IPMutFunc) (jsonEntry jobject) { hostname := entry.QHost question := jobject{ "type": entry.QType, "class": entry.QClass, "name": hostname, } if qhost, err := idna.ToUnicode(hostname); err != nil { log.Debug("querylog: translating %q into unicode: %s", hostname, err) } else if qhost != hostname && qhost != "" { question["unicode_name"] = qhost } entIP := slices.Clone(entry.IP) anonFunc(entIP) jsonEntry = jobject{ "reason": entry.Result.Reason.String(), "elapsedMs": strconv.FormatFloat(entry.Elapsed.Seconds()*1000, 'f', -1, 64), "time": entry.Time.Format(time.RFC3339Nano), "client": entIP, "client_proto": entry.ClientProto, "cached": entry.Cached, "upstream": entry.Upstream, "question": question, "rules": resultRulesToJSONRules(entry.Result.Rules), } if entIP.Equal(entry.IP) { jsonEntry["client_info"] = entry.client } if entry.ClientID != "" { jsonEntry["client_id"] = entry.ClientID } if entry.ReqECS != "" { jsonEntry["ecs"] = entry.ReqECS } if len(entry.Result.Rules) > 0 { if r := entry.Result.Rules[0]; len(r.Text) > 0 { jsonEntry["rule"] = r.Text jsonEntry["filterId"] = r.FilterListID } } if len(entry.Result.ServiceName) != 0 { jsonEntry["service_name"] = entry.Result.ServiceName } setMsgData(entry, jsonEntry) setOrigAns(entry, jsonEntry) return jsonEntry } // setMsgData sets the message data in jsonEntry. func setMsgData(entry *logEntry, jsonEntry jobject) { if len(entry.Answer) == 0 { return } msg := &dns.Msg{} if err := msg.Unpack(entry.Answer); err != nil { log.Debug("querylog: failed to unpack dns msg answer: %v: %s", entry.Answer, err) return } jsonEntry["status"] = dns.RcodeToString[msg.Rcode] // Old query logs may still keep AD flag value in the message. Try to get // it from there as well. jsonEntry["answer_dnssec"] = entry.AuthenticatedData || msg.AuthenticatedData if a := answerToJSON(msg); a != nil { jsonEntry["answer"] = a } } // setOrigAns sets the original answer data in jsonEntry. func setOrigAns(entry *logEntry, jsonEntry jobject) { if len(entry.OrigAnswer) == 0 { return } orig := &dns.Msg{} err := orig.Unpack(entry.OrigAnswer) if err != nil { log.Debug("querylog: orig.Unpack(entry.OrigAnswer): %v: %s", entry.OrigAnswer, err) return } if a := answerToJSON(orig); a != nil { jsonEntry["original_answer"] = a } } func resultRulesToJSONRules(rules []*filtering.ResultRule) (jsonRules []jobject) { jsonRules = make([]jobject, len(rules)) for i, r := range rules { jsonRules[i] = jobject{ "filter_list_id": r.FilterListID, "text": r.Text, } } return jsonRules } type dnsAnswer struct { Type string `json:"type"` Value string `json:"value"` TTL uint32 `json:"ttl"` } // answerToJSON converts the answer records of msg, if any, to their JSON form. func answerToJSON(msg *dns.Msg) (answers []*dnsAnswer) { if msg == nil || len(msg.Answer) == 0 { return nil } answers = make([]*dnsAnswer, 0, len(msg.Answer)) for _, rr := range msg.Answer { header := rr.Header() a := &dnsAnswer{ Type: dns.TypeToString[header.Rrtype], // Remove the header string from the answer value since it's mostly // unnecessary in the log. Value: strings.TrimPrefix(rr.String(), header.String()), TTL: header.Ttl, } answers = append(answers, a) } return answers } ```
/content/code_sandbox/internal/querylog/json.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,296
```go package querylog import ( "encoding/json" "fmt" "math" "net" "net/http" "net/url" "slices" "strconv" "strings" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/timeutil" "golang.org/x/net/idna" ) // configJSON is the JSON structure for the querylog configuration. type configJSON struct { // Interval is the querylog rotation interval. Use float64 here to support // fractional numbers and not mess the API users by changing the units. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an aghalg.NullBool to // be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an [aghalg.NullBool] to be able to tell when it's set without using // pointers. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` } // getConfigResp is the JSON structure for the querylog configuration. type getConfigResp struct { // Ignored is the list of host names, which should not be written to log. Ignored []string `json:"ignored"` // Interval is the querylog rotation interval in milliseconds. Interval float64 `json:"interval"` // Enabled shows if the querylog is enabled. It is an aghalg.NullBool to // be able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` // AnonymizeClientIP shows if the clients' IP addresses must be anonymized. // It is an aghalg.NullBool to be able to tell when it's set without using // pointers. // // TODO(a.garipov): Consider using separate setting for statistics. AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"` } // Register web handlers func (l *queryLog) initWeb() { l.conf.HTTPRegister(http.MethodGet, "/control/querylog", l.handleQueryLog) l.conf.HTTPRegister(http.MethodPost, "/control/querylog_clear", l.handleQueryLogClear) l.conf.HTTPRegister(http.MethodGet, "/control/querylog/config", l.handleGetQueryLogConfig) l.conf.HTTPRegister( http.MethodPut, "/control/querylog/config/update", l.handlePutQueryLogConfig, ) // Deprecated handlers. l.conf.HTTPRegister(http.MethodGet, "/control/querylog_info", l.handleQueryLogInfo) l.conf.HTTPRegister(http.MethodPost, "/control/querylog_config", l.handleQueryLogConfig) } // handleQueryLog is the handler for the GET /control/querylog HTTP API. func (l *queryLog) handleQueryLog(w http.ResponseWriter, r *http.Request) { params, err := parseSearchParams(r) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "parsing params: %s", err) return } var entries []*logEntry var oldest time.Time func() { l.confMu.RLock() defer l.confMu.RUnlock() entries, oldest = l.search(params) }() resp := entriesToJSON(entries, oldest, l.anonymizer.Load()) aghhttp.WriteJSONResponseOK(w, r, resp) } // handleQueryLogClear is the handler for the POST /control/querylog/clear HTTP // API. func (l *queryLog) handleQueryLogClear(_ http.ResponseWriter, _ *http.Request) { l.clear() } // handleQueryLogInfo is the handler for the GET /control/querylog_info HTTP // API. // // Deprecated: Remove it when migration to the new API is over. func (l *queryLog) handleQueryLogInfo(w http.ResponseWriter, r *http.Request) { l.confMu.RLock() defer l.confMu.RUnlock() ivl := l.conf.RotationIvl if !checkInterval(ivl) { // NOTE: If interval is custom we set it to 90 days for compatibility // with old API. ivl = timeutil.Day * 90 } aghhttp.WriteJSONResponseOK(w, r, configJSON{ Enabled: aghalg.BoolToNullBool(l.conf.Enabled), Interval: ivl.Hours() / 24, AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), }) } // handleGetQueryLogConfig is the handler for the GET /control/querylog/config // HTTP API. func (l *queryLog) handleGetQueryLogConfig(w http.ResponseWriter, r *http.Request) { var resp *getConfigResp func() { l.confMu.RLock() defer l.confMu.RUnlock() resp = &getConfigResp{ Interval: float64(l.conf.RotationIvl.Milliseconds()), Enabled: aghalg.BoolToNullBool(l.conf.Enabled), AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP), Ignored: l.conf.Ignored.Values(), } }() aghhttp.WriteJSONResponseOK(w, r, resp) } // AnonymizeIP masks ip to anonymize the client if the ip is a valid one. func AnonymizeIP(ip net.IP) { // zeroes is a slice of zero bytes from which the IP address tail is copied. // Using constant string as source of copying is more efficient than byte // slice, see path_to_url const zeroes = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" if ip4 := ip.To4(); ip4 != nil { copy(ip4[net.IPv4len-2:net.IPv4len], zeroes) } else if len(ip) == net.IPv6len { copy(ip[net.IPv6len-10:net.IPv6len], zeroes) } } // handleQueryLogConfig is the handler for the POST /control/querylog_config // HTTP API. // // Deprecated: Remove it when migration to the new API is over. func (l *queryLog) handleQueryLogConfig(w http.ResponseWriter, r *http.Request) { // Set NaN as initial value to be able to know if it changed later by // comparing it to NaN. newConf := &configJSON{ Interval: math.NaN(), } err := json.NewDecoder(r.Body).Decode(newConf) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } ivl := time.Duration(float64(timeutil.Day) * newConf.Interval) hasIvl := !math.IsNaN(newConf.Interval) if hasIvl && !checkInterval(ivl) { aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval") return } defer l.conf.ConfigModified() l.confMu.Lock() defer l.confMu.Unlock() conf := *l.conf if newConf.Enabled != aghalg.NBNull { conf.Enabled = newConf.Enabled == aghalg.NBTrue } if hasIvl { conf.RotationIvl = ivl } if newConf.AnonymizeClientIP != aghalg.NBNull { conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { l.anonymizer.Store(AnonymizeIP) } else { l.anonymizer.Store(nil) } } l.conf = &conf } // handlePutQueryLogConfig is the handler for the PUT // /control/querylog/config/update HTTP API. func (l *queryLog) handlePutQueryLogConfig(w http.ResponseWriter, r *http.Request) { newConf := &getConfigResp{} err := json.NewDecoder(r.Body).Decode(newConf) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "%s", err) return } engine, err := aghnet.NewIgnoreEngine(newConf.Ignored) if err != nil { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "ignored: %s", err) return } ivl := time.Duration(newConf.Interval) * time.Millisecond err = validateIvl(ivl) if err != nil { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "unsupported interval: %s", err) return } if newConf.Enabled == aghalg.NBNull { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "enabled is null") return } if newConf.AnonymizeClientIP == aghalg.NBNull { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "anonymize_client_ip is null") return } defer l.conf.ConfigModified() l.confMu.Lock() defer l.confMu.Unlock() conf := *l.conf conf.Ignored = engine conf.RotationIvl = ivl conf.Enabled = newConf.Enabled == aghalg.NBTrue conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue if conf.AnonymizeClientIP { l.anonymizer.Store(AnonymizeIP) } else { l.anonymizer.Store(nil) } l.conf = &conf } // "value" -> value, return TRUE func getDoubleQuotesEnclosedValue(s *string) bool { t := *s if len(t) >= 2 && t[0] == '"' && t[len(t)-1] == '"' { *s = t[1 : len(t)-1] return true } return false } // parseSearchCriterion parses a search criterion from the query parameter. func parseSearchCriterion(q url.Values, name string, ct criterionType) ( ok bool, sc searchCriterion, err error, ) { val := q.Get(name) if val == "" { return false, sc, nil } strict := getDoubleQuotesEnclosedValue(&val) var asciiVal string switch ct { case ctTerm: // Decode lowercased value from punycode to make EqualFold and // friends work properly with IDNAs. // // TODO(e.burkov): Make it work with parts of IDNAs somehow. loweredVal := strings.ToLower(val) if asciiVal, err = idna.ToASCII(loweredVal); err != nil { log.Debug("can't convert %q to ascii: %s", val, err) } else if asciiVal == loweredVal { // Purge asciiVal to prevent checking the same value // twice. asciiVal = "" } case ctFilteringStatus: if !slices.Contains(filteringStatusValues, val) { return false, sc, fmt.Errorf("invalid value %s", val) } default: return false, sc, fmt.Errorf( "invalid criterion type %v: should be one of %v", ct, []criterionType{ctTerm, ctFilteringStatus}, ) } sc = searchCriterion{ criterionType: ct, value: val, asciiVal: asciiVal, strict: strict, } return true, sc, nil } // parseSearchParams parses search parameters from the HTTP request's query // string. func parseSearchParams(r *http.Request) (p *searchParams, err error) { p = newSearchParams() q := r.URL.Query() olderThan := q.Get("older_than") if len(olderThan) != 0 { p.olderThan, err = time.Parse(time.RFC3339Nano, olderThan) if err != nil { return nil, err } } var limit64 int64 if limit64, err = strconv.ParseInt(q.Get("limit"), 10, 64); err == nil { p.limit = int(limit64) } var offset64 int64 if offset64, err = strconv.ParseInt(q.Get("offset"), 10, 64); err == nil { p.offset = int(offset64) // If we don't use "olderThan" and use offset/limit instead, we should change the default behavior // and scan all log records until we found enough log entries p.maxFileScanEntries = 0 } for _, v := range []struct { urlField string ct criterionType }{{ urlField: "search", ct: ctTerm, }, { urlField: "response_status", ct: ctFilteringStatus, }} { var ok bool var c searchCriterion ok, c, err = parseSearchCriterion(q, v.urlField, v.ct) if err != nil { return nil, err } if ok { p.searchCriteria = append(p.searchCriteria, c) } } return p, nil } ```
/content/code_sandbox/internal/querylog/http.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,928
```go package querylog import ( "fmt" "net" "testing" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } // TestQueryLog tests adding and loading (with filtering) entries from disk and // memory. func TestQueryLog(t *testing.T) { l, err := newQueryLog(Config{ Enabled: true, FileEnabled: true, RotationIvl: timeutil.Day, MemSize: 100, BaseDir: t.TempDir(), }) require.NoError(t, err) // Add disk entries. addEntry(l, "example.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) // Write to disk (first file). require.NoError(t, l.flushLogBuffer()) // Start writing to the second file. require.NoError(t, l.rotate()) // Add disk entries. addEntry(l, "example.org", net.IPv4(1, 1, 1, 2), net.IPv4(2, 2, 2, 2)) // Write to disk. require.NoError(t, l.flushLogBuffer()) // Add memory entries. addEntry(l, "test.example.org", net.IPv4(1, 1, 1, 3), net.IPv4(2, 2, 2, 3)) addEntry(l, "example.com", net.IPv4(1, 1, 1, 4), net.IPv4(2, 2, 2, 4)) addEntry(l, "", net.IPv4(1, 1, 1, 5), net.IPv4(2, 2, 2, 5)) type tcAssertion struct { host string answer net.IP client net.IP num int } testCases := []struct { name string sCr []searchCriterion want []tcAssertion }{{ name: "all", sCr: []searchCriterion{}, want: []tcAssertion{ {num: 0, host: ".", answer: net.IPv4(1, 1, 1, 5), client: net.IPv4(2, 2, 2, 5)}, {num: 1, host: "example.com", answer: net.IPv4(1, 1, 1, 4), client: net.IPv4(2, 2, 2, 4)}, {num: 2, host: "test.example.org", answer: net.IPv4(1, 1, 1, 3), client: net.IPv4(2, 2, 2, 3)}, {num: 3, host: "example.org", answer: net.IPv4(1, 1, 1, 2), client: net.IPv4(2, 2, 2, 2)}, {num: 4, host: "example.org", answer: net.IPv4(1, 1, 1, 1), client: net.IPv4(2, 2, 2, 1)}, }, }, { name: "by_domain_strict", sCr: []searchCriterion{{ criterionType: ctTerm, strict: true, value: "TEST.example.org", }}, want: []tcAssertion{{ num: 0, host: "test.example.org", answer: net.IPv4(1, 1, 1, 3), client: net.IPv4(2, 2, 2, 3), }}, }, { name: "by_domain_non-strict", sCr: []searchCriterion{{ criterionType: ctTerm, strict: false, value: "example.ORG", }}, want: []tcAssertion{ {num: 0, host: "test.example.org", answer: net.IPv4(1, 1, 1, 3), client: net.IPv4(2, 2, 2, 3)}, {num: 1, host: "example.org", answer: net.IPv4(1, 1, 1, 2), client: net.IPv4(2, 2, 2, 2)}, {num: 2, host: "example.org", answer: net.IPv4(1, 1, 1, 1), client: net.IPv4(2, 2, 2, 1)}, }, }, { name: "by_client_ip_strict", sCr: []searchCriterion{{ criterionType: ctTerm, strict: true, value: "2.2.2.2", }}, want: []tcAssertion{{ num: 0, host: "example.org", answer: net.IPv4(1, 1, 1, 2), client: net.IPv4(2, 2, 2, 2), }}, }, { name: "by_client_ip_non-strict", sCr: []searchCriterion{{ criterionType: ctTerm, strict: false, value: "2.2.2", }}, want: []tcAssertion{ {num: 0, host: ".", answer: net.IPv4(1, 1, 1, 5), client: net.IPv4(2, 2, 2, 5)}, {num: 1, host: "example.com", answer: net.IPv4(1, 1, 1, 4), client: net.IPv4(2, 2, 2, 4)}, {num: 2, host: "test.example.org", answer: net.IPv4(1, 1, 1, 3), client: net.IPv4(2, 2, 2, 3)}, {num: 3, host: "example.org", answer: net.IPv4(1, 1, 1, 2), client: net.IPv4(2, 2, 2, 2)}, {num: 4, host: "example.org", answer: net.IPv4(1, 1, 1, 1), client: net.IPv4(2, 2, 2, 1)}, }, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { params := newSearchParams() params.searchCriteria = tc.sCr entries, _ := l.search(params) require.Len(t, entries, len(tc.want)) for _, want := range tc.want { assertLogEntry(t, entries[want.num], want.host, want.answer, want.client) } }) } } func TestQueryLogOffsetLimit(t *testing.T) { l, err := newQueryLog(Config{ Enabled: true, RotationIvl: timeutil.Day, MemSize: 100, BaseDir: t.TempDir(), }) require.NoError(t, err) const ( entNum = 10 firstPageDomain = "first.example.org" secondPageDomain = "second.example.org" ) // Add entries to the log. for range entNum { addEntry(l, secondPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) } // Write them to the first file. require.NoError(t, l.flushLogBuffer()) // Add more to the in-memory part of log. for range entNum { addEntry(l, firstPageDomain, net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) } params := newSearchParams() testCases := []struct { name string want string wantLen int offset int limit int }{{ name: "page_1", want: firstPageDomain, wantLen: 10, offset: 0, limit: 10, }, { name: "page_2", want: secondPageDomain, wantLen: 10, offset: 10, limit: 10, }, { name: "page_2.5", want: secondPageDomain, wantLen: 5, offset: 15, limit: 10, }, { name: "page_3", want: "", wantLen: 0, offset: 20, limit: 10, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { params.offset = tc.offset params.limit = tc.limit entries, _ := l.search(params) require.Len(t, entries, tc.wantLen) if tc.wantLen > 0 { assert.Equal(t, entries[0].QHost, tc.want) assert.Equal(t, entries[tc.wantLen-1].QHost, tc.want) } }) } } func TestQueryLogMaxFileScanEntries(t *testing.T) { l, err := newQueryLog(Config{ Enabled: true, FileEnabled: true, RotationIvl: timeutil.Day, MemSize: 100, BaseDir: t.TempDir(), }) require.NoError(t, err) const entNum = 10 // Add entries to the log. for range entNum { addEntry(l, "example.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) } // Write them to disk. require.NoError(t, l.flushLogBuffer()) params := newSearchParams() for _, maxFileScanEntries := range []int{5, 0} { t.Run(fmt.Sprintf("limit_%d", maxFileScanEntries), func(t *testing.T) { params.maxFileScanEntries = maxFileScanEntries entries, _ := l.search(params) assert.Len(t, entries, entNum-maxFileScanEntries) }) } } func TestQueryLogFileDisabled(t *testing.T) { l, err := newQueryLog(Config{ Enabled: true, FileEnabled: false, RotationIvl: timeutil.Day, MemSize: 2, BaseDir: t.TempDir(), }) require.NoError(t, err) addEntry(l, "example1.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) addEntry(l, "example2.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) // The oldest entry is going to be removed from memory buffer. addEntry(l, "example3.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1)) params := newSearchParams() ll, _ := l.search(params) require.Len(t, ll, 2) assert.Equal(t, "example3.org", ll[0].QHost) assert.Equal(t, "example2.org", ll[1].QHost) } func TestQueryLogShouldLog(t *testing.T) { const ( ignored1 = "ignor.ed" ignored2 = "ignored.to" ignoredWildcard = "*.ignored.com" ignoredRoot = "|.^" ) ignored := []string{ ignored1, ignored2, ignoredWildcard, ignoredRoot, } engine, err := aghnet.NewIgnoreEngine(ignored) require.NoError(t, err) findClient := func(ids []string) (c *Client, err error) { log := ids[0] == "no_log" return &Client{IgnoreQueryLog: log}, nil } l, err := newQueryLog(Config{ Ignored: engine, Enabled: true, RotationIvl: timeutil.Day, MemSize: 100, BaseDir: t.TempDir(), FindClient: findClient, }) require.NoError(t, err) testCases := []struct { name string host string ids []string wantLog bool }{{ name: "log", host: "example.com", ids: []string{"whatever"}, wantLog: true, }, { name: "no_log_ignored_1", host: ignored1, ids: []string{"whatever"}, wantLog: false, }, { name: "no_log_ignored_2", host: ignored2, ids: []string{"whatever"}, wantLog: false, }, { name: "no_log_ignored_wildcard", host: "www.ignored.com", ids: []string{"whatever"}, wantLog: false, }, { name: "no_log_ignored_root", host: ".", ids: []string{"whatever"}, wantLog: false, }, { name: "no_log_client_ignore", host: "example.com", ids: []string{"no_log"}, wantLog: false, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res := l.ShouldLog(tc.host, dns.TypeA, dns.ClassINET, tc.ids) assert.Equal(t, tc.wantLog, res) }) } } func addEntry(l *queryLog, host string, answerStr, client net.IP) { q := dns.Msg{ Question: []dns.Question{{ Name: host + ".", Qtype: dns.TypeA, Qclass: dns.ClassINET, }}, } a := dns.Msg{ Question: q.Question, Answer: []dns.RR{&dns.A{ Hdr: dns.RR_Header{ Name: q.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, }, A: answerStr, }}, } res := filtering.Result{ ServiceName: "SomeService", Rules: []*filtering.ResultRule{{ FilterListID: 1, Text: "SomeRule", }}, Reason: filtering.Rewritten, IsFiltered: true, } params := &AddParams{ Question: &q, Answer: &a, OrigAnswer: &a, Result: &res, Upstream: "upstream", ClientIP: client, } l.Add(params) } func assertLogEntry(t *testing.T, entry *logEntry, host string, answer, client net.IP) { t.Helper() require.NotNil(t, entry) assert.Equal(t, host, entry.QHost) assert.Equal(t, client, entry.IP) assert.Equal(t, "A", entry.QType) assert.Equal(t, "IN", entry.QClass) msg := &dns.Msg{} require.NoError(t, msg.Unpack(entry.Answer)) require.Len(t, msg.Answer, 1) a := testutil.RequireTypeAssert[*dns.A](t, msg.Answer[0]) assert.Equal(t, answer, a.A.To16()) } ```
/content/code_sandbox/internal/querylog/qlog_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,601
```go package querylog import "github.com/AdguardTeam/AdGuardHome/internal/whois" // Client is the information required by the query log to match against clients // during searches. type Client struct { WHOIS *whois.Info `json:"whois,omitempty"` Name string `json:"name"` DisallowedRule string `json:"disallowed_rule"` Disallowed bool `json:"disallowed"` IgnoreQueryLog bool `json:"-"` } // clientCacheKey is the key by which a cached client information is found. type clientCacheKey struct { clientID string ip string } // clientCache is the cache of client information found throughout a request to // the query log API. It is used both to speed up the lookup, as well as to // make sure that changes in client data between two lookups don't create // discrepancies in our response. type clientCache map[clientCacheKey]*Client ```
/content/code_sandbox/internal/querylog/client.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
205
```go package querylog import ( "fmt" "net" "path/filepath" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/container" "github.com/AdguardTeam/golibs/errors" "github.com/miekg/dns" ) // QueryLog - main interface type QueryLog interface { Start() // Close query log object Close() // Add a log entry Add(params *AddParams) // WriteDiskConfig - write configuration WriteDiskConfig(c *Config) // ShouldLog returns true if request for the host should be logged. ShouldLog(host string, qType, qClass uint16, ids []string) bool } // Config is the query log configuration structure. // // Do not alter any fields of this structure after using it. type Config struct { // Ignored contains the list of host names, which should not be written to // log, and matches them. Ignored *aghnet.IgnoreEngine // Anonymizer processes the IP addresses to anonymize those if needed. Anonymizer *aghnet.IPMut // ConfigModified is called when the configuration is changed, for example // by HTTP requests. ConfigModified func() // HTTPRegister registers an HTTP handler. HTTPRegister aghhttp.RegisterFunc // FindClient returns client information by their IDs. FindClient func(ids []string) (c *Client, err error) // BaseDir is the base directory for log files. BaseDir string // RotationIvl is the interval for log rotation. After that period, the old // log file will be renamed, NOT deleted, so the actual log retention time // is twice the interval. RotationIvl time.Duration // MemSize is the number of entries kept in a memory buffer before they are // flushed to disk. MemSize uint // Enabled tells if the query log is enabled. Enabled bool // FileEnabled tells if the query log writes logs to files. FileEnabled bool // AnonymizeClientIP tells if the query log should anonymize clients' IP // addresses. AnonymizeClientIP bool } // AddParams is the parameters for adding an entry. type AddParams struct { Question *dns.Msg // ReqECS is the IP network extracted from EDNS Client-Subnet option of a // request. ReqECS *net.IPNet // Answer is the response which is sent to the client, if any. Answer *dns.Msg // OrigAnswer is the response from an upstream server. It's only set if the // answer has been modified by filtering. OrigAnswer *dns.Msg // Result is the filtering result (optional). Result *filtering.Result ClientID string // Upstream is the URL of the upstream DNS server. Upstream string ClientProto ClientProto ClientIP net.IP // Elapsed is the time spent for processing the request. Elapsed time.Duration // Cached indicates if the response is served from cache. Cached bool // AuthenticatedData shows if the response had the AD bit set. AuthenticatedData bool } // validate returns an error if the parameters aren't valid. func (p *AddParams) validate() (err error) { switch { case p.Question == nil: return errors.Error("question is nil") case len(p.Question.Question) != 1: return errors.Error("more than one question") case len(p.Question.Question[0].Name) == 0: return errors.Error("no host in question") case p.ClientIP == nil: return errors.Error("no client ip") default: return nil } } // New creates a new instance of the query log. func New(conf Config) (ql QueryLog, err error) { return newQueryLog(conf) } // newQueryLog crates a new queryLog. func newQueryLog(conf Config) (l *queryLog, err error) { findClient := conf.FindClient if findClient == nil { findClient = func(_ []string) (_ *Client, _ error) { return nil, nil } } memSize := conf.MemSize if memSize == 0 { // If query log is enabled, we still need to write entries to a file. // And all writing goes through a buffer. memSize = 1 } l = &queryLog{ findClient: findClient, buffer: container.NewRingBuffer[*logEntry](memSize), conf: &Config{}, confMu: &sync.RWMutex{}, logFile: filepath.Join(conf.BaseDir, queryLogFileName), anonymizer: conf.Anonymizer, } *l.conf = conf err = validateIvl(conf.RotationIvl) if err != nil { return nil, fmt.Errorf("unsupported interval: %w", err) } return l, nil } ```
/content/code_sandbox/internal/querylog/querylog.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,113
```go // Package querylog provides query log functions and interfaces. package querylog import ( "fmt" "os" "sync" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/container" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/timeutil" "github.com/miekg/dns" ) // queryLogFileName is a name of the log file. ".gz" extension is added later // during compression. const queryLogFileName = "querylog.json" // queryLog is a structure that writes and reads the DNS query log. type queryLog struct { // confMu protects conf. confMu *sync.RWMutex conf *Config anonymizer *aghnet.IPMut findClient func(ids []string) (c *Client, err error) // buffer contains recent log entries. The entries in this buffer must not // be modified. buffer *container.RingBuffer[*logEntry] // logFile is the path to the log file. logFile string // bufferLock protects buffer. bufferLock sync.RWMutex // fileFlushLock synchronizes a file-flushing goroutine and main thread. fileFlushLock sync.Mutex fileWriteLock sync.Mutex flushPending bool } // ClientProto values are names of the client protocols. type ClientProto string // Client protocol names. const ( ClientProtoDoH ClientProto = "doh" ClientProtoDoQ ClientProto = "doq" ClientProtoDoT ClientProto = "dot" ClientProtoDNSCrypt ClientProto = "dnscrypt" ClientProtoPlain ClientProto = "" ) // NewClientProto validates that the client protocol name is valid and returns // the name as a ClientProto. func NewClientProto(s string) (cp ClientProto, err error) { switch cp = ClientProto(s); cp { case ClientProtoDoH, ClientProtoDoQ, ClientProtoDoT, ClientProtoDNSCrypt, ClientProtoPlain: return cp, nil default: return "", fmt.Errorf("invalid client proto: %q", s) } } func (l *queryLog) Start() { if l.conf.HTTPRegister != nil { l.initWeb() } go l.periodicRotate() } func (l *queryLog) Close() { l.confMu.RLock() defer l.confMu.RUnlock() if l.conf.FileEnabled { err := l.flushLogBuffer() if err != nil { log.Error("querylog: closing: %s", err) } } } func checkInterval(ivl time.Duration) (ok bool) { // The constants for possible values of query log's rotation interval. const ( quarterDay = timeutil.Day / 4 day = timeutil.Day week = timeutil.Day * 7 month = timeutil.Day * 30 threeMonths = timeutil.Day * 90 ) return ivl == quarterDay || ivl == day || ivl == week || ivl == month || ivl == threeMonths } // validateIvl returns an error if ivl is less than an hour or more than a // year. func validateIvl(ivl time.Duration) (err error) { if ivl < time.Hour { return errors.Error("less than an hour") } if ivl > timeutil.Day*365 { return errors.Error("more than a year") } return nil } func (l *queryLog) WriteDiskConfig(c *Config) { l.confMu.RLock() defer l.confMu.RUnlock() *c = *l.conf } // Clear memory buffer and remove log files func (l *queryLog) clear() { l.fileFlushLock.Lock() defer l.fileFlushLock.Unlock() func() { l.bufferLock.Lock() defer l.bufferLock.Unlock() l.buffer.Clear() l.flushPending = false }() oldLogFile := l.logFile + ".1" err := os.Remove(oldLogFile) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Error("removing old log file %q: %s", oldLogFile, err) } err = os.Remove(l.logFile) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Error("removing log file %q: %s", l.logFile, err) } log.Debug("querylog: cleared") } // newLogEntry creates an instance of logEntry from parameters. func newLogEntry(params *AddParams) (entry *logEntry) { q := params.Question.Question[0] qHost := aghnet.NormalizeDomain(q.Name) entry = &logEntry{ // TODO(d.kolyshev): Export this timestamp to func params. Time: time.Now(), QHost: qHost, QType: dns.Type(q.Qtype).String(), QClass: dns.Class(q.Qclass).String(), ClientID: params.ClientID, ClientProto: params.ClientProto, Result: *params.Result, Upstream: params.Upstream, IP: params.ClientIP, Elapsed: params.Elapsed, Cached: params.Cached, AuthenticatedData: params.AuthenticatedData, } if params.ReqECS != nil { entry.ReqECS = params.ReqECS.String() } entry.addResponse(params.Answer, false) entry.addResponse(params.OrigAnswer, true) return entry } // Add implements the [QueryLog] interface for *queryLog. func (l *queryLog) Add(params *AddParams) { var isEnabled, fileIsEnabled bool var memSize uint func() { l.confMu.RLock() defer l.confMu.RUnlock() isEnabled, fileIsEnabled = l.conf.Enabled, l.conf.FileEnabled memSize = l.conf.MemSize }() if !isEnabled { return } err := params.validate() if err != nil { log.Error("querylog: adding record: %s, skipping", err) return } if params.Result == nil { params.Result = &filtering.Result{} } entry := newLogEntry(params) l.bufferLock.Lock() defer l.bufferLock.Unlock() l.buffer.Push(entry) if !l.flushPending && fileIsEnabled && l.buffer.Len() >= memSize { l.flushPending = true // TODO(s.chzhen): Fix occasional rewrite of entires. go func() { flushErr := l.flushLogBuffer() if flushErr != nil { log.Error("querylog: flushing after adding: %s", flushErr) } }() } } // ShouldLog returns true if request for the host should be logged. func (l *queryLog) ShouldLog(host string, _, _ uint16, ids []string) bool { l.confMu.RLock() defer l.confMu.RUnlock() c, err := l.findClient(ids) if err != nil { log.Error("querylog: finding client: %s", err) } if c != nil && c.IgnoreQueryLog { return false } return !l.isIgnored(host) } // isIgnored returns true if the host is in the ignored domains list. It // assumes that l.confMu is locked for reading. func (l *queryLog) isIgnored(host string) bool { return l.conf.Ignored.Has(host) } ```
/content/code_sandbox/internal/querylog/qlog.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,650
```go package querylog import ( "net" "time" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/miekg/dns" ) // logEntry represents a single entry in the file. type logEntry struct { // client is the found client information, if any. client *Client Time time.Time `json:"T"` QHost string `json:"QH"` QType string `json:"QT"` QClass string `json:"QC"` ReqECS string `json:"ECS,omitempty"` ClientID string `json:"CID,omitempty"` ClientProto ClientProto `json:"CP"` Upstream string `json:",omitempty"` Answer []byte `json:",omitempty"` OrigAnswer []byte `json:",omitempty"` // TODO(s.chzhen): Use netip.Addr. IP net.IP `json:"IP"` Result filtering.Result Elapsed time.Duration Cached bool `json:",omitempty"` AuthenticatedData bool `json:"AD,omitempty"` } // shallowClone returns a shallow clone of e. func (e *logEntry) shallowClone() (clone *logEntry) { cloneVal := *e return &cloneVal } // addResponse adds data from resp to e.Answer if resp is not nil. If isOrig is // true, addResponse sets the e.OrigAnswer field instead of e.Answer. Any // errors are logged. func (e *logEntry) addResponse(resp *dns.Msg, isOrig bool) { if resp == nil { return } var err error if isOrig { e.OrigAnswer, err = resp.Pack() err = errors.Annotate(err, "packing orig answer: %w") } else { e.Answer, err = resp.Pack() err = errors.Annotate(err, "packing answer: %w") } if err != nil { log.Error("querylog: %s", err) } } // parseDNSRewriteResultIPs fills logEntry's DNSRewriteResult response records // with the IP addresses parsed from the raw strings. func (e *logEntry) parseDNSRewriteResultIPs() { for rrType, rrValues := range e.Result.DNSRewriteResult.Response { switch rrType { case dns.TypeA, dns.TypeAAAA: for i, v := range rrValues { s, _ := v.(string) rrValues[i] = net.ParseIP(s) } default: // Go on. } } } ```
/content/code_sandbox/internal/querylog/entry.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
577
```go package querylog import ( "encoding/base64" "encoding/json" "fmt" "io" "net" "net/netip" "strings" "time" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/urlfilter/rules" "github.com/miekg/dns" ) // logEntryHandler represents a handler for decoding json token to the logEntry // struct. type logEntryHandler func(t json.Token, ent *logEntry) error // logEntryHandlers is the map of log entry decode handlers for various keys. var logEntryHandlers = map[string]logEntryHandler{ "CID": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.ClientID = v return nil }, "IP": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } if ent.IP == nil { ent.IP = net.ParseIP(v) } return nil }, "T": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } var err error ent.Time, err = time.Parse(time.RFC3339, v) return err }, "QH": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.QHost = v return nil }, "QT": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.QType = v return nil }, "QC": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.QClass = v return nil }, "CP": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } var err error ent.ClientProto, err = NewClientProto(v) return err }, "Answer": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } var err error ent.Answer, err = base64.StdEncoding.DecodeString(v) return err }, "OrigAnswer": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } var err error ent.OrigAnswer, err = base64.StdEncoding.DecodeString(v) return err }, "ECS": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.ReqECS = v return nil }, "Cached": func(t json.Token, ent *logEntry) error { v, ok := t.(bool) if !ok { return nil } ent.Cached = v return nil }, "AD": func(t json.Token, ent *logEntry) error { v, ok := t.(bool) if !ok { return nil } ent.AuthenticatedData = v return nil }, "Upstream": func(t json.Token, ent *logEntry) error { v, ok := t.(string) if !ok { return nil } ent.Upstream = v return nil }, "Elapsed": func(t json.Token, ent *logEntry) error { v, ok := t.(json.Number) if !ok { return nil } i, err := v.Int64() if err != nil { return err } ent.Elapsed = time.Duration(i) return nil }, } // decodeResultRuleKey decodes the token of "Rules" type to logEntry struct. func decodeResultRuleKey(key string, i int, dec *json.Decoder, ent *logEntry) { var vToken json.Token switch key { case "FilterListID": ent.Result.Rules, vToken = decodeVTokenAndAddRule(key, i, dec, ent.Result.Rules) if n, ok := vToken.(json.Number); ok { id, _ := n.Int64() ent.Result.Rules[i].FilterListID = rulelist.URLFilterID(id) } case "IP": ent.Result.Rules, vToken = decodeVTokenAndAddRule(key, i, dec, ent.Result.Rules) if ipStr, ok := vToken.(string); ok { if ip, err := netip.ParseAddr(ipStr); err == nil { ent.Result.Rules[i].IP = ip } else { log.Debug("querylog: decoding ipStr value: %s", err) } } case "Text": ent.Result.Rules, vToken = decodeVTokenAndAddRule(key, i, dec, ent.Result.Rules) if s, ok := vToken.(string); ok { ent.Result.Rules[i].Text = s } default: // Go on. } } // decodeVTokenAndAddRule decodes the "Rules" toke as [filtering.ResultRule] // and then adds the decoded object to the slice of result rules. func decodeVTokenAndAddRule( key string, i int, dec *json.Decoder, rules []*filtering.ResultRule, ) (newRules []*filtering.ResultRule, vToken json.Token) { newRules = rules vToken, err := dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeResultRuleKey %s err: %s", key, err) } return newRules, nil } if len(rules) < i+1 { newRules = append(newRules, &filtering.ResultRule{}) } return newRules, vToken } // decodeResultRules parses the dec's tokens into logEntry ent interpreting it // as a slice of the result rules. func decodeResultRules(dec *json.Decoder, ent *logEntry) { for { delimToken, err := dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeResultRules err: %s", err) } return } if d, ok := delimToken.(json.Delim); !ok { return } else if d != '[' { log.Debug("decodeResultRules: unexpected delim %q", d) } err = decodeResultRuleToken(dec, ent) if err != nil { if err != io.EOF && !errors.Is(err, ErrEndOfToken) { log.Debug("decodeResultRules err: %s", err) } return } } } // decodeResultRuleToken decodes the tokens of "Rules" type to the logEntry ent. func decodeResultRuleToken(dec *json.Decoder, ent *logEntry) (err error) { i := 0 for { var keyToken json.Token keyToken, err = dec.Token() if err != nil { // Don't wrap the error, because it's informative enough as is. return err } if d, ok := keyToken.(json.Delim); ok { switch d { case '}': i++ case ']': return ErrEndOfToken default: // Go on. } continue } key, ok := keyToken.(string) if !ok { return fmt.Errorf("keyToken is %T (%[1]v) and not string", keyToken) } decodeResultRuleKey(key, i, dec, ent) } } // decodeResultReverseHosts parses the dec's tokens into ent interpreting it as // the result of hosts container's $dnsrewrite rule. It assumes there are no // other occurrences of DNSRewriteResult in the entry since hosts container's // rewrites currently has the highest priority along the entire filtering // pipeline. func decodeResultReverseHosts(dec *json.Decoder, ent *logEntry) { for { itemToken, err := dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeResultReverseHosts err: %s", err) } return } switch v := itemToken.(type) { case json.Delim: if v == '[' { continue } else if v == ']' { return } log.Debug("decodeResultReverseHosts: unexpected delim %q", v) return case string: v = dns.Fqdn(v) if res := &ent.Result; res.DNSRewriteResult == nil { res.DNSRewriteResult = &filtering.DNSRewriteResult{ RCode: dns.RcodeSuccess, Response: filtering.DNSRewriteResultResponse{ dns.TypePTR: []rules.RRValue{v}, }, } continue } else { res.DNSRewriteResult.RCode = dns.RcodeSuccess } if rres := ent.Result.DNSRewriteResult; rres.Response == nil { rres.Response = filtering.DNSRewriteResultResponse{dns.TypePTR: []rules.RRValue{v}} } else { rres.Response[dns.TypePTR] = append(rres.Response[dns.TypePTR], v) } default: continue } } } // decodeResultIPList parses the dec's tokens into logEntry ent interpreting it // as the result IP addresses list. func decodeResultIPList(dec *json.Decoder, ent *logEntry) { for { itemToken, err := dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeResultIPList err: %s", err) } return } switch v := itemToken.(type) { case json.Delim: if v == '[' { continue } else if v == ']' { return } log.Debug("decodeResultIPList: unexpected delim %q", v) return case string: var ip netip.Addr ip, err = netip.ParseAddr(v) if err == nil { ent.Result.IPList = append(ent.Result.IPList, ip) } default: continue } } } // decodeResultDNSRewriteResultKey decodes the token of "DNSRewriteResult" type // to the logEntry struct. func decodeResultDNSRewriteResultKey(key string, dec *json.Decoder, ent *logEntry) { var err error switch key { case "RCode": var vToken json.Token vToken, err = dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeResultDNSRewriteResultKey err: %s", err) } return } if ent.Result.DNSRewriteResult == nil { ent.Result.DNSRewriteResult = &filtering.DNSRewriteResult{} } if n, ok := vToken.(json.Number); ok { rcode64, _ := n.Int64() ent.Result.DNSRewriteResult.RCode = rules.RCode(rcode64) } case "Response": if ent.Result.DNSRewriteResult == nil { ent.Result.DNSRewriteResult = &filtering.DNSRewriteResult{} } if ent.Result.DNSRewriteResult.Response == nil { ent.Result.DNSRewriteResult.Response = filtering.DNSRewriteResultResponse{} } // TODO(a.garipov): I give up. This whole file is a mess. Luckily, we // can assume that this field is relatively rare and just use the normal // decoding and correct the values. err = dec.Decode(&ent.Result.DNSRewriteResult.Response) if err != nil { log.Debug("decodeResultDNSRewriteResultKey response err: %s", err) } ent.parseDNSRewriteResultIPs() default: // Go on. } } // decodeResultDNSRewriteResult parses the dec's tokens into logEntry ent // interpreting it as the result DNSRewriteResult. func decodeResultDNSRewriteResult(dec *json.Decoder, ent *logEntry) { for { key, err := parseKeyToken(dec) if err != nil { if err != io.EOF && !errors.Is(err, ErrEndOfToken) { log.Debug("decodeResultDNSRewriteResult: %s", err) } return } if key == "" { continue } decodeResultDNSRewriteResultKey(key, dec, ent) } } // translateResult converts some fields of the ent.Result to the format // consistent with current implementation. func translateResult(ent *logEntry) { res := &ent.Result if res.Reason != filtering.RewrittenAutoHosts || len(res.IPList) == 0 { return } if res.DNSRewriteResult == nil { res.DNSRewriteResult = &filtering.DNSRewriteResult{ RCode: dns.RcodeSuccess, } } if res.DNSRewriteResult.Response == nil { res.DNSRewriteResult.Response = filtering.DNSRewriteResultResponse{} } resp := res.DNSRewriteResult.Response for _, ip := range res.IPList { qType := dns.TypeAAAA if ip.Is4() { qType = dns.TypeA } resp[qType] = append(resp[qType], ip) } res.IPList = nil } // ErrEndOfToken is an error returned by parse key token when the closing // bracket is found. const ErrEndOfToken errors.Error = "end of token" // parseKeyToken parses the dec's token key. func parseKeyToken(dec *json.Decoder) (key string, err error) { keyToken, err := dec.Token() if err != nil { return "", err } if d, ok := keyToken.(json.Delim); ok { if d == '}' { return "", ErrEndOfToken } return "", nil } key, ok := keyToken.(string) if !ok { return "", fmt.Errorf("keyToken is %T (%[1]v) and not string", keyToken) } return key, nil } // decodeResult decodes a token of "Result" type to logEntry struct. func decodeResult(dec *json.Decoder, ent *logEntry) { defer translateResult(ent) for { key, err := parseKeyToken(dec) if err != nil { if err != io.EOF && !errors.Is(err, ErrEndOfToken) { log.Debug("decodeResult: %s", err) } return } if key == "" { continue } decHandler, ok := resultDecHandlers[key] if ok { decHandler(dec, ent) continue } handler, ok := resultHandlers[key] if !ok { continue } val, err := dec.Token() if err != nil { return } if err = handler(val, ent); err != nil { log.Debug("decodeResult handler err: %s", err) return } } } // resultHandlers is the map of log entry decode handlers for various keys. var resultHandlers = map[string]logEntryHandler{ "IsFiltered": func(t json.Token, ent *logEntry) error { v, ok := t.(bool) if !ok { return nil } ent.Result.IsFiltered = v return nil }, "Rule": func(t json.Token, ent *logEntry) error { s, ok := t.(string) if !ok { return nil } l := len(ent.Result.Rules) if l == 0 { ent.Result.Rules = []*filtering.ResultRule{{}} l++ } ent.Result.Rules[l-1].Text = s return nil }, "FilterID": func(t json.Token, ent *logEntry) error { n, ok := t.(json.Number) if !ok { return nil } id, err := n.Int64() if err != nil { return err } l := len(ent.Result.Rules) if l == 0 { ent.Result.Rules = []*filtering.ResultRule{{}} l++ } ent.Result.Rules[l-1].FilterListID = rulelist.URLFilterID(id) return nil }, "Reason": func(t json.Token, ent *logEntry) error { v, ok := t.(json.Number) if !ok { return nil } i, err := v.Int64() if err != nil { return err } ent.Result.Reason = filtering.Reason(i) return nil }, "ServiceName": func(t json.Token, ent *logEntry) error { s, ok := t.(string) if !ok { return nil } ent.Result.ServiceName = s return nil }, "CanonName": func(t json.Token, ent *logEntry) error { s, ok := t.(string) if !ok { return nil } ent.Result.CanonName = s return nil }, } // resultDecHandlers is the map of decode handlers for various keys. var resultDecHandlers = map[string]func(dec *json.Decoder, ent *logEntry){ "ReverseHosts": decodeResultReverseHosts, "IPList": decodeResultIPList, "Rules": decodeResultRules, "DNSRewriteResult": decodeResultDNSRewriteResult, } // decodeLogEntry decodes string str to logEntry ent. func decodeLogEntry(ent *logEntry, str string) { dec := json.NewDecoder(strings.NewReader(str)) dec.UseNumber() for { keyToken, err := dec.Token() if err != nil { if err != io.EOF { log.Debug("decodeLogEntry err: %s", err) } return } if _, ok := keyToken.(json.Delim); ok { continue } key, ok := keyToken.(string) if !ok { log.Debug("decodeLogEntry: keyToken is %T (%[1]v) and not string", keyToken) return } if key == "Result" { decodeResult(dec, ent) continue } handler, ok := logEntryHandlers[key] if !ok { continue } val, err := dec.Token() if err != nil { return } if err = handler(val, ent); err != nil { log.Debug("decodeLogEntry handler err: %s", err) return } } } ```
/content/code_sandbox/internal/querylog/decode.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
4,354
```go package querylog import ( "net" "testing" "time" "github.com/AdguardTeam/golibs/timeutil" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestQueryLog_Search_findClient(t *testing.T) { const knownClientID = "client-1" const knownClientName = "Known Client 1" const unknownClientID = "client-2" knownClient := &Client{ Name: knownClientName, } findClientCalls := 0 findClient := func(ids []string) (c *Client, _ error) { defer func() { findClientCalls++ }() if len(ids) == 0 { return nil, nil } if ids[0] == knownClientID { return knownClient, nil } return nil, nil } l, err := newQueryLog(Config{ FindClient: findClient, BaseDir: t.TempDir(), RotationIvl: timeutil.Day, MemSize: 100, Enabled: true, FileEnabled: true, AnonymizeClientIP: false, }) require.NoError(t, err) t.Cleanup(l.Close) q := &dns.Msg{ Question: []dns.Question{{ Name: "example.com", }}, } l.Add(&AddParams{ Question: q, ClientID: knownClientID, ClientIP: net.IP{1, 2, 3, 4}, }) // Add the same thing again to test the cache. l.Add(&AddParams{ Question: q, ClientID: knownClientID, ClientIP: net.IP{1, 2, 3, 4}, }) l.Add(&AddParams{ Question: q, ClientID: unknownClientID, ClientIP: net.IP{1, 2, 3, 5}, }) sp := &searchParams{ // Add some time to the "current" one to protect against // low-resolution timers on some Windows machines. // // TODO(a.garipov): Use some kind of timeSource interface // instead of relying on time.Now() in tests. olderThan: time.Now().Add(10 * time.Second), limit: 3, } entries, _ := l.search(sp) assert.Equal(t, 2, findClientCalls) require.Len(t, entries, 3) assert.Nil(t, entries[0].client) gotClient := entries[2].client require.NotNil(t, gotClient) assert.Equal(t, knownClientName, gotClient.Name) } ```
/content/code_sandbox/internal/querylog/search_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
601
```go package querylog import ( "encoding/binary" "fmt" "io" "math" "net" "os" "strings" "testing" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // prepareTestFile prepares one test query log file with the specified lines // count. func prepareTestFile(t *testing.T, dir string, linesNum int) (name string) { t.Helper() f, err := os.CreateTemp(dir, "*.txt") require.NoError(t, err) // Use defer and not t.Cleanup to make sure that the file is closed // after this function is done. defer func() { derr := f.Close() require.NoError(t, derr) }() const ans = `your_sha256_hashAAAABAECAwQ="` const format = `{"IP":%q,"T":%q,"QH":"example.org","QT":"A","QC":"IN",` + `"Answer":` + ans + `,"Result":{},"Elapsed":0,"Upstream":"upstream"}` + "\n" var lineIP uint32 lineTime := time.Date(2020, 2, 18, 19, 36, 35, 920973000, time.UTC) for range linesNum { lineIP++ lineTime = lineTime.Add(time.Second) ip := make(net.IP, 4) binary.BigEndian.PutUint32(ip, lineIP) line := fmt.Sprintf(format, ip, lineTime.Format(time.RFC3339Nano)) _, err = f.WriteString(line) require.NoError(t, err) } return f.Name() } // prepareTestFiles prepares several test query log files, each with the // specified lines count. func prepareTestFiles(t *testing.T, filesNum, linesNum int) []string { t.Helper() if filesNum == 0 { return []string{} } dir := t.TempDir() files := make([]string, filesNum) for i := range files { files[filesNum-i-1] = prepareTestFile(t, dir, linesNum) } return files } // newTestQLogFile creates new *qLogFile for tests and registers the required // cleanup functions. func newTestQLogFile(t *testing.T, linesNum int) (file *qLogFile) { t.Helper() testFile := prepareTestFiles(t, 1, linesNum)[0] // Create the new qLogFile instance. file, err := newQLogFile(testFile) require.NoError(t, err) assert.NotNil(t, file) testutil.CleanupAndRequireSuccess(t, file.Close) return file } func TestQLogFile_ReadNext(t *testing.T) { testCases := []struct { name string linesNum int }{{ name: "empty", linesNum: 0, }, { name: "large", linesNum: 50000, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { q := newTestQLogFile(t, tc.linesNum) // Calculate the expected position. fileInfo, err := q.file.Stat() require.NoError(t, err) var expPos int64 if expPos = fileInfo.Size(); expPos > 0 { expPos-- } // Seek to the start. pos, err := q.SeekStart() require.NoError(t, err) require.EqualValues(t, expPos, pos) var read int var line string for err == nil { line, err = q.ReadNext() if err == nil { assert.NotEmpty(t, line) read++ } } require.Equal(t, io.EOF, err) assert.Equal(t, tc.linesNum, read) }) } } func TestQLogFile_SeekTS_good(t *testing.T) { linesCases := []struct { name string num int }{{ name: "large", num: 10000, }, { name: "small", num: 10, }} for _, l := range linesCases { testCases := []struct { name string linesNum int line int }{{ name: "not_too_old", line: 2, }, { name: "old", line: l.num - 2, }, { name: "first", line: 0, }, { name: "last", line: l.num, }} q := newTestQLogFile(t, l.num) for _, tc := range testCases { t.Run(l.name+"_"+tc.name, func(t *testing.T) { line, err := getQLogFileLine(q, tc.line) require.NoError(t, err) ts := readQLogTimestamp(line) assert.NotEqualValues(t, 0, ts) // Try seeking to that line now. pos, _, err := q.seekTS(ts) require.NoError(t, err) assert.NotEqualValues(t, 0, pos) testLine, err := q.ReadNext() require.NoError(t, err) assert.Equal(t, line, testLine) }) } } } func TestQLogFile_SeekTS_bad(t *testing.T) { linesCases := []struct { name string num int }{{ name: "large", num: 10000, }, { name: "small", num: 10, }} for _, l := range linesCases { testCases := []struct { name string ts int64 leq bool }{{ name: "non-existent_long_ago", }, { name: "non-existent_far_ahead", }, { name: "almost", leq: true, }} q := newTestQLogFile(t, l.num) testCases[0].ts = 123 lateTS, _ := time.Parse(time.RFC3339, "2100-01-02T15:04:05Z07:00") testCases[1].ts = lateTS.UnixNano() line, err := getQLogFileLine(q, l.num/2) require.NoError(t, err) testCases[2].ts = readQLogTimestamp(line) - 1 for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { assert.NotEqualValues(t, 0, tc.ts) var depth int _, depth, err = q.seekTS(tc.ts) assert.NotEmpty(t, l.num) require.Error(t, err) if tc.leq { assert.LessOrEqual(t, depth, int(math.Log2(float64(l.num))+3)) } }) } } } func getQLogFileLine(q *qLogFile, lineNumber int) (line string, err error) { if _, err = q.SeekStart(); err != nil { return line, err } for i := 1; i < lineNumber; i++ { if _, err = q.ReadNext(); err != nil { return line, err } } return q.ReadNext() } // Check adding and loading (with filtering) entries from disk and memory. func TestQLogFile(t *testing.T) { // Create the new qLogFile instance. q := newTestQLogFile(t, 2) // Seek to the start. pos, err := q.SeekStart() require.NoError(t, err) assert.Greater(t, pos, int64(0)) // Read first line. line, err := q.ReadNext() require.NoError(t, err) assert.Contains(t, line, "0.0.0.2") assert.True(t, strings.HasPrefix(line, "{"), line) assert.True(t, strings.HasSuffix(line, "}"), line) // Read second line. line, err = q.ReadNext() require.NoError(t, err) assert.EqualValues(t, 0, q.position) assert.Contains(t, line, "0.0.0.1") assert.True(t, strings.HasPrefix(line, "{"), line) assert.True(t, strings.HasSuffix(line, "}"), line) // Try reading again (there's nothing to read anymore). line, err = q.ReadNext() require.Equal(t, io.EOF, err) assert.Empty(t, line) } func newTestQLogFileData(t *testing.T, data string) (file *qLogFile) { f, err := os.CreateTemp(t.TempDir(), "*.txt") require.NoError(t, err) testutil.CleanupAndRequireSuccess(t, f.Close) _, err = f.WriteString(data) require.NoError(t, err) file, err = newQLogFile(f.Name()) require.NoError(t, err) testutil.CleanupAndRequireSuccess(t, file.Close) return file } func TestQLog_Seek(t *testing.T) { const nl = "\n" const strV = "%s" const recs = `{"T":"` + strV + `","QH":"wfqvjymurpwegyv","QT":"A","QC":"IN","CP":"","Answer":"","Result":{},"Elapsed":66286385,"Upstream":"tls://unfiltered.adguard-dns.com:853"}` + nl + `{"T":"` + strV + `"}` + nl + `{"T":"` + strV + `"}` + nl timestamp, _ := time.Parse(time.RFC3339Nano, "2020-08-31T18:44:25.376690873+03:00") testCases := []struct { wantErr error name string delta int wantDepth int }{{ name: "ok", delta: 0, wantErr: nil, wantDepth: 2, }, { name: "too_late", delta: 2, wantErr: errTSTooLate, wantDepth: 2, }, { name: "too_early", delta: -2, wantErr: errTSTooEarly, wantDepth: 1, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { data := fmt.Sprintf(recs, timestamp.Add(-time.Second).Format(time.RFC3339Nano), timestamp.Format(time.RFC3339Nano), timestamp.Add(time.Second).Format(time.RFC3339Nano), ) q := newTestQLogFileData(t, data) _, depth, err := q.seekTS(timestamp.Add(time.Second * time.Duration(tc.delta)).UnixNano()) require.Truef(t, errors.Is(err, tc.wantErr), "%v", err) assert.Equal(t, tc.wantDepth, depth) }) } } ```
/content/code_sandbox/internal/querylog/qlogfile_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,414
```go package querylog import ( "fmt" "io" "slices" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" ) // client finds the client info, if any, by its ClientID and IP address, // optionally checking the provided cache. It will use the IP address // regardless of if the IP anonymization is enabled now, because the // anonymization could have been disabled in the past, and client will try to // find those records as well. func (l *queryLog) client(clientID, ip string, cache clientCache) (c *Client, err error) { cck := clientCacheKey{clientID: clientID, ip: ip} var ok bool if c, ok = cache[cck]; ok { return c, nil } var ids []string if clientID != "" { ids = append(ids, clientID) } if ip != "" { ids = append(ids, ip) } c, err = l.findClient(ids) if err != nil { return nil, err } // Cache all results, including negative ones, to prevent excessive and // expensive client searching. cache[cck] = c return c, nil } // searchMemory looks up log records which are currently in the in-memory // buffer. It optionally uses the client cache, if provided. It also returns // the total amount of records in the buffer at the moment of searching. // l.confMu is expected to be locked. func (l *queryLog) searchMemory(params *searchParams, cache clientCache) (entries []*logEntry, total int) { // Check memory size, as the buffer can contain a single log record. See // [newQueryLog]. if l.conf.MemSize == 0 { return nil, 0 } l.bufferLock.Lock() defer l.bufferLock.Unlock() l.buffer.ReverseRange(func(entry *logEntry) (cont bool) { // A shallow clone is enough, since the only thing that this loop // modifies is the client field. e := entry.shallowClone() var err error e.client, err = l.client(e.ClientID, e.IP.String(), cache) if err != nil { msg := "querylog: enriching memory record at time %s" + " for client %q (clientid %q): %s" log.Error(msg, e.Time, e.IP, e.ClientID, err) // Go on and try to match anyway. } if params.match(e) { entries = append(entries, e) } return true }) return entries, int(l.buffer.Len()) } // search searches log entries in memory buffer and log file using specified // parameters and returns the list of entries found and the time of the oldest // entry. l.confMu is expected to be locked. func (l *queryLog) search(params *searchParams) (entries []*logEntry, oldest time.Time) { start := time.Now() if params.limit == 0 { return []*logEntry{}, time.Time{} } cache := clientCache{} memoryEntries, bufLen := l.searchMemory(params, cache) log.Debug("querylog: got %d entries from memory", len(memoryEntries)) fileEntries, oldest, total := l.searchFiles(params, cache) log.Debug("querylog: got %d entries from files", len(fileEntries)) total += bufLen totalLimit := params.offset + params.limit // now let's get a unified collection entries = append(memoryEntries, fileEntries...) if len(entries) > totalLimit { // remove extra records entries = entries[:totalLimit] } // Resort entries on start time to partially mitigate query log looking // weird on the frontend. // // See path_to_url slices.SortStableFunc(entries, func(a, b *logEntry) (res int) { return -a.Time.Compare(b.Time) }) if params.offset > 0 { if len(entries) > params.offset { entries = entries[params.offset:] } else { entries = make([]*logEntry, 0) oldest = time.Time{} } } if len(entries) > 0 { // Update oldest after merging in the memory buffer. oldest = entries[len(entries)-1].Time } log.Debug( "querylog: prepared data (%d/%d) older than %s in %s", len(entries), total, params.olderThan, time.Since(start), ) return entries, oldest } // seekRecord changes the current position to the next record older than the // provided parameter. func (r *qLogReader) seekRecord(olderThan time.Time) (err error) { if olderThan.IsZero() { return r.SeekStart() } err = r.seekTS(olderThan.UnixNano()) if err == nil { // Read to the next record, because we only need the one that goes // after it. _, err = r.ReadNext() } return err } // setQLogReader creates a reader with the specified files and sets the // position to the next record older than the provided parameter. func (l *queryLog) setQLogReader(olderThan time.Time) (qr *qLogReader, err error) { files := []string{ l.logFile + ".1", l.logFile, } r, err := newQLogReader(files) if err != nil { return nil, fmt.Errorf("opening qlog reader: %s", err) } err = r.seekRecord(olderThan) if err != nil { defer func() { err = errors.WithDeferred(err, r.Close()) }() log.Debug("querylog: cannot seek to %s: %s", olderThan, err) return nil, nil } return r, nil } // readEntries reads entries from the reader to totalLimit. By default, we do // not scan more than maxFileScanEntries at once. The idea is to make search // calls faster so that the UI could handle it and show something quicker. // This behavior can be overridden if maxFileScanEntries is set to 0. func (l *queryLog) readEntries( r *qLogReader, params *searchParams, cache clientCache, totalLimit int, ) (entries []*logEntry, oldestNano int64, total int) { for total < params.maxFileScanEntries || params.maxFileScanEntries <= 0 { ent, ts, rErr := l.readNextEntry(r, params, cache) if rErr != nil { if rErr == io.EOF { oldestNano = 0 break } log.Error("querylog: reading next entry: %s", rErr) } oldestNano = ts total++ if ent == nil { continue } entries = append(entries, ent) if len(entries) == totalLimit { break } } return entries, oldestNano, total } // searchFiles looks up log records from all log files. It optionally uses the // client cache, if provided. searchFiles does not scan more than // maxFileScanEntries so callers may need to call it several times to get all // the results. oldest and total are the time of the oldest processed entry // and the total number of processed entries, including discarded ones, // correspondingly. func (l *queryLog) searchFiles( params *searchParams, cache clientCache, ) (entries []*logEntry, oldest time.Time, total int) { r, err := l.setQLogReader(params.olderThan) if err != nil { log.Error("querylog: %s", err) } if r == nil { return entries, oldest, 0 } defer func() { if closeErr := r.Close(); closeErr != nil { log.Error("querylog: closing file: %s", closeErr) } }() totalLimit := params.offset + params.limit entries, oldestNano, total := l.readEntries(r, params, cache, totalLimit) if oldestNano != 0 { oldest = time.Unix(0, oldestNano) } return entries, oldest, total } // quickMatchClientFinder is a wrapper around the usual client finding function // to make it easier to use with quick matches. type quickMatchClientFinder struct { client func(clientID, ip string, cache clientCache) (c *Client, err error) cache clientCache } // findClient is a method that can be used as a quickMatchClientFinder. func (f quickMatchClientFinder) findClient(clientID, ip string) (c *Client) { var err error c, err = f.client(clientID, ip, f.cache) if err != nil { log.Error( "querylog: enriching file record for quick search: for client %q (clientid %q): %s", ip, clientID, err, ) } return c } // readNextEntry reads the next log entry and checks if it matches the search // criteria. It optionally uses the client cache, if provided. e is nil if // the entry doesn't match the search criteria. ts is the timestamp of the // processed entry. func (l *queryLog) readNextEntry( r *qLogReader, params *searchParams, cache clientCache, ) (e *logEntry, ts int64, err error) { var line string line, err = r.ReadNext() if err != nil { return nil, 0, err } clientFinder := quickMatchClientFinder{ client: l.client, cache: cache, } if !params.quickMatch(line, clientFinder.findClient) { ts = readQLogTimestamp(line) return nil, ts, nil } e = &logEntry{} decodeLogEntry(e, line) if l.isIgnored(e.QHost) { return nil, ts, nil } e.client, err = l.client(e.ClientID, e.IP.String(), cache) if err != nil { log.Error( "querylog: enriching file record at time %s for client %q (clientid %q): %s", e.Time, e.IP, e.ClientID, err, ) // Go on and try to match anyway. } if e.client != nil && e.client.IgnoreQueryLog { return nil, ts, nil } ts = e.Time.UnixNano() if !params.match(e) { return nil, ts, nil } return e, ts, nil } ```
/content/code_sandbox/internal/querylog/search.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,357
```go package querylog import ( "io" "testing" "time" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // newTestQLogReader creates new *qLogReader for tests and registers the // required cleanup functions. func newTestQLogReader(t *testing.T, filesNum, linesNum int) (reader *qLogReader) { t.Helper() testFiles := prepareTestFiles(t, filesNum, linesNum) // Create the new qLogReader instance. reader, err := newQLogReader(testFiles) require.NoError(t, err) assert.NotNil(t, reader) testutil.CleanupAndRequireSuccess(t, reader.Close) return reader } func TestQLogReader(t *testing.T) { testCases := []struct { name string filesNum int linesNum int }{{ name: "empty", filesNum: 0, linesNum: 0, }, { name: "one_file", filesNum: 1, linesNum: 10, }, { name: "multiple_files", filesNum: 5, linesNum: 10000, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { r := newTestQLogReader(t, tc.filesNum, tc.linesNum) // Seek to the start. err := r.SeekStart() require.NoError(t, err) // Read everything. var read int var line string for err == nil { line, err = r.ReadNext() if err == nil { assert.NotEmpty(t, line) read++ } } require.Equal(t, io.EOF, err) assert.Equal(t, tc.filesNum*tc.linesNum, read) }) } } func TestQLogReader_Seek(t *testing.T) { r := newTestQLogReader(t, 2, 10000) testCases := []struct { want error name string time string }{{ name: "not_too_old", time: "2020-02-18T22:39:35.920973+03:00", want: nil, }, { name: "old", time: "2020-02-19T01:28:16.920973+03:00", want: nil, }, { name: "first", time: "2020-02-18T22:36:36.920973+03:00", want: nil, }, { name: "last", time: "2020-02-19T01:23:16.920973+03:00", want: nil, }, { name: "non-existent_long_ago", time: "2000-02-19T01:23:16.920973+03:00", want: errTSNotFound, }, { name: "non-existent_far_ahead", time: "2100-02-19T01:23:16.920973+03:00", want: nil, }, { name: "non-existent_but_could", time: "2020-02-18T22:36:37.000000+03:00", want: errTSNotFound, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { ts, err := time.Parse(time.RFC3339Nano, tc.time) require.NoError(t, err) err = r.seekTS(ts.UnixNano()) assert.ErrorIs(t, err, tc.want) }) } } func TestQLogReader_ReadNext(t *testing.T) { const linesNum = 10 const filesNum = 1 r := newTestQLogReader(t, filesNum, linesNum) testCases := []struct { want error name string start int }{{ name: "ok", start: 0, want: nil, }, { name: "too_big", start: linesNum + 1, want: io.EOF, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { err := r.SeekStart() require.NoError(t, err) for i := 1; i < tc.start; i++ { _, err = r.ReadNext() require.NoError(t, err) } _, err = r.ReadNext() assert.Equal(t, tc.want, err) }) } } ```
/content/code_sandbox/internal/querylog/qlogreader_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,029
```go package querylog import ( "fmt" "strings" "github.com/AdguardTeam/AdGuardHome/internal/filtering" "github.com/AdguardTeam/golibs/stringutil" ) type criterionType int const ( // ctTerm is for searching by the domain name, the client's IP address, // the client's ID or the client's name. The domain name search // supports IDNAs. ctTerm criterionType = iota // ctFilteringStatus is for searching by the filtering status. // // See (*searchCriterion).ctFilteringStatusCase for details. ctFilteringStatus ) const ( filteringStatusAll = "all" filteringStatusFiltered = "filtered" // all kinds of filtering filteringStatusBlocked = "blocked" // blocked or blocked services filteringStatusBlockedService = "blocked_services" // blocked filteringStatusBlockedSafebrowsing = "blocked_safebrowsing" // blocked by safebrowsing filteringStatusBlockedParental = "blocked_parental" // blocked by parental control filteringStatusWhitelisted = "whitelisted" // whitelisted filteringStatusRewritten = "rewritten" // all kinds of rewrites filteringStatusSafeSearch = "safe_search" // enforced safe search filteringStatusProcessed = "processed" // not blocked, not white-listed entries ) // filteringStatusValues -- array with all possible filteringStatus values var filteringStatusValues = []string{ filteringStatusAll, filteringStatusFiltered, filteringStatusBlocked, filteringStatusBlockedService, filteringStatusBlockedSafebrowsing, filteringStatusBlockedParental, filteringStatusWhitelisted, filteringStatusRewritten, filteringStatusSafeSearch, filteringStatusProcessed, } // searchCriterion is a search criterion that is used to match a record. type searchCriterion struct { value string asciiVal string criterionType criterionType // strict, if true, means that the criterion must be applied to the // whole value rather than the part of it. That is, equality and not // containment. strict bool } func ctDomainOrClientCaseStrict( term string, asciiTerm string, clientID string, name string, host string, ip string, ) (ok bool) { return strings.EqualFold(host, term) || (asciiTerm != "" && strings.EqualFold(host, asciiTerm)) || strings.EqualFold(clientID, term) || strings.EqualFold(ip, term) || strings.EqualFold(name, term) } func ctDomainOrClientCaseNonStrict( term string, asciiTerm string, clientID string, name string, host string, ip string, ) (ok bool) { return stringutil.ContainsFold(clientID, term) || stringutil.ContainsFold(host, term) || (asciiTerm != "" && stringutil.ContainsFold(host, asciiTerm)) || stringutil.ContainsFold(ip, term) || stringutil.ContainsFold(name, term) } // quickMatch quickly checks if the line matches the given search criterion. // It returns false if the like doesn't match. This method is only here for // optimization purposes. func (c *searchCriterion) quickMatch(line string, findClient quickMatchClientFunc) (ok bool) { switch c.criterionType { case ctTerm: host := readJSONValue(line, `"QH":"`) ip := readJSONValue(line, `"IP":"`) clientID := readJSONValue(line, `"CID":"`) var name string if cli := findClient(clientID, ip); cli != nil { name = cli.Name } if c.strict { return ctDomainOrClientCaseStrict(c.value, c.asciiVal, clientID, name, host, ip) } return ctDomainOrClientCaseNonStrict(c.value, c.asciiVal, clientID, name, host, ip) case ctFilteringStatus: // Go on, as we currently don't do quick matches against // filtering statuses. return true default: return true } } // match checks if the log entry matches this search criterion. func (c *searchCriterion) match(entry *logEntry) bool { switch c.criterionType { case ctTerm: return c.ctDomainOrClientCase(entry) case ctFilteringStatus: return c.ctFilteringStatusCase(entry.Result.Reason, entry.Result.IsFiltered) } return false } func (c *searchCriterion) ctDomainOrClientCase(e *logEntry) bool { clientID := e.ClientID host := e.QHost var name string if e.client != nil { name = e.client.Name } ip := e.IP.String() if c.strict { return ctDomainOrClientCaseStrict(c.value, c.asciiVal, clientID, name, host, ip) } return ctDomainOrClientCaseNonStrict(c.value, c.asciiVal, clientID, name, host, ip) } // ctFilteringStatusCase returns true if the result matches the value. func (c *searchCriterion) ctFilteringStatusCase( reason filtering.Reason, isFiltered bool, ) (matched bool) { switch c.value { case filteringStatusAll: return true case filteringStatusFiltered: return isFiltered || reason.In( filtering.NotFilteredAllowList, filtering.Rewritten, filtering.RewrittenAutoHosts, filtering.RewrittenRule, ) case filteringStatusBlocked, filteringStatusBlockedParental, filteringStatusBlockedSafebrowsing, filteringStatusBlockedService, filteringStatusSafeSearch: return isFiltered && c.isFilteredWithReason(reason) case filteringStatusWhitelisted: return reason == filtering.NotFilteredAllowList case filteringStatusRewritten: return reason.In( filtering.Rewritten, filtering.RewrittenAutoHosts, filtering.RewrittenRule, ) case filteringStatusProcessed: return !reason.In( filtering.FilteredBlockList, filtering.FilteredBlockedService, filtering.NotFilteredAllowList, ) default: return false } } // isFilteredWithReason returns true if reason matches the criterion value. // c.value must be one of: // // - filteringStatusBlocked // - filteringStatusBlockedParental // - filteringStatusBlockedSafebrowsing // - filteringStatusBlockedService // - filteringStatusSafeSearch func (c *searchCriterion) isFilteredWithReason(reason filtering.Reason) (matched bool) { switch c.value { case filteringStatusBlocked: return reason.In(filtering.FilteredBlockList, filtering.FilteredBlockedService) case filteringStatusBlockedParental: return reason == filtering.FilteredParental case filteringStatusBlockedSafebrowsing: return reason == filtering.FilteredSafeBrowsing case filteringStatusBlockedService: return reason == filtering.FilteredBlockedService case filteringStatusSafeSearch: return reason == filtering.FilteredSafeSearch default: panic(fmt.Errorf("unexpected value %q", c.value)) } } ```
/content/code_sandbox/internal/querylog/searchcriterion.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,539
```go package querylog import ( "bytes" "encoding/json" "fmt" "os" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" ) // flushLogBuffer flushes the current buffer to file and resets the current // buffer. func (l *queryLog) flushLogBuffer() (err error) { defer func() { err = errors.Annotate(err, "flushing log buffer: %w") }() l.fileFlushLock.Lock() defer l.fileFlushLock.Unlock() b, err := l.encodeEntries() if err != nil { // Don't wrap the error since it's informative enough as is. return err } return l.flushToFile(b) } // encodeEntries returns JSON encoded log entries, logs estimated time, clears // the log buffer. func (l *queryLog) encodeEntries() (b *bytes.Buffer, err error) { l.bufferLock.Lock() defer l.bufferLock.Unlock() bufLen := l.buffer.Len() if bufLen == 0 { return nil, errors.Error("nothing to write to a file") } start := time.Now() b = &bytes.Buffer{} e := json.NewEncoder(b) l.buffer.Range(func(entry *logEntry) (cont bool) { err = e.Encode(entry) return err == nil }) if err != nil { // Don't wrap the error since it's informative enough as is. return nil, err } elapsed := time.Since(start) log.Debug("%d elements serialized via json in %v: %d kB, %v/entry, %v/entry", bufLen, elapsed, b.Len()/1024, float64(b.Len())/float64(bufLen), elapsed/time.Duration(bufLen)) l.buffer.Clear() l.flushPending = false return b, nil } // flushToFile saves the encoded log entries to the query log file. func (l *queryLog) flushToFile(b *bytes.Buffer) (err error) { l.fileWriteLock.Lock() defer l.fileWriteLock.Unlock() filename := l.logFile f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("creating file %q: %w", filename, err) } defer func() { err = errors.WithDeferred(err, f.Close()) }() n, err := f.Write(b.Bytes()) if err != nil { return fmt.Errorf("writing to file %q: %w", filename, err) } log.Debug("querylog: ok %q: %v bytes written", filename, n) return nil } func (l *queryLog) rotate() error { from := l.logFile to := l.logFile + ".1" err := os.Rename(from, to) if err != nil { if errors.Is(err, os.ErrNotExist) { log.Debug("querylog: no log to rotate") return nil } return fmt.Errorf("failed to rename old file: %w", err) } log.Debug("querylog: renamed %s into %s", from, to) return nil } func (l *queryLog) readFileFirstTimeValue() (first time.Time, err error) { var f *os.File f, err = os.Open(l.logFile) if err != nil { return time.Time{}, err } defer func() { err = errors.WithDeferred(err, f.Close()) }() buf := make([]byte, 512) var r int r, err = f.Read(buf) if err != nil { return time.Time{}, err } val := readJSONValue(string(buf[:r]), `"T":"`) t, err := time.Parse(time.RFC3339Nano, val) if err != nil { return time.Time{}, err } log.Debug("querylog: the oldest log entry: %s", val) return t, nil } func (l *queryLog) periodicRotate() { defer log.OnPanic("querylog: rotating") l.checkAndRotate() // rotationCheckIvl is the period of time between checking the need for // rotating log files. It's smaller of any available rotation interval to // increase time accuracy. // // See path_to_url const rotationCheckIvl = 1 * time.Hour rotations := time.NewTicker(rotationCheckIvl) defer rotations.Stop() for range rotations.C { l.checkAndRotate() } } // checkAndRotate rotates log files if those are older than the specified // rotation interval. func (l *queryLog) checkAndRotate() { var rotationIvl time.Duration func() { l.confMu.RLock() defer l.confMu.RUnlock() rotationIvl = l.conf.RotationIvl }() oldest, err := l.readFileFirstTimeValue() if err != nil && !errors.Is(err, os.ErrNotExist) { log.Error("querylog: reading oldest record for rotation: %s", err) return } if rotTime, now := oldest.Add(rotationIvl), time.Now(); rotTime.After(now) { log.Debug( "querylog: %s <= %s, not rotating", now.Format(time.RFC3339), rotTime.Format(time.RFC3339), ) return } err = l.rotate() if err != nil { log.Error("querylog: rotating: %s", err) return } log.Debug("querylog: rotated successfully") } ```
/content/code_sandbox/internal/querylog/querylogfile.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,190
```go package stats import ( "bytes" "encoding/binary" "encoding/gob" "fmt" "slices" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "go.etcd.io/bbolt" "golang.org/x/exp/maps" ) const ( // maxDomains is the max number of top domains to return. maxDomains = 100 // maxClients is the max number of top clients to return. maxClients = 100 // maxUpstreams is the max number of top upstreams to return. maxUpstreams = 100 ) // UnitIDGenFunc is the signature of a function that generates a unique ID for // the statistics unit. type UnitIDGenFunc func() (id uint32) // Supported values of [StatsResp.TimeUnits]. const ( timeUnitsHours = "hours" timeUnitsDays = "days" ) // Result is the resulting code of processing the DNS request. type Result int // Supported Result values. // // TODO(e.burkov): Think about better naming. const ( RNotFiltered Result = iota + 1 RFiltered RSafeBrowsing RSafeSearch RParental resultLast = RParental + 1 ) // Entry is a statistics data entry. type Entry struct { // Clients is the client's primary ID. // // TODO(a.garipov): Make this a {net.IP, string} enum? Client string // Domain is the domain name requested. Domain string // Upstream is the upstream DNS server. Upstream string // Result is the result of processing the request. Result Result // ProcessingTime is the duration of the request processing from the start // of the request including timeouts. ProcessingTime time.Duration // UpstreamTime is the duration of the successful request to the upstream. UpstreamTime time.Duration } // validate returns an error if entry is not valid. func (e *Entry) validate() (err error) { switch { case e.Result == 0: return errors.Error("result code is not set") case e.Result >= resultLast: return fmt.Errorf("unknown result code %d", e.Result) case e.Domain == "": return errors.Error("domain is empty") case e.Client == "": return errors.Error("client is empty") default: return nil } } // unit collects the statistics data for a specific period of time. type unit struct { // domains stores the number of requests for each domain. domains map[string]uint64 // blockedDomains stores the number of requests for each domain that has // been blocked. blockedDomains map[string]uint64 // clients stores the number of requests from each client. clients map[string]uint64 // upstreamsResponses stores the number of responses from each upstream. upstreamsResponses map[string]uint64 // upstreamsTimeSum stores the sum of durations of successful queries in // microseconds to each upstream. upstreamsTimeSum map[string]uint64 // nResult stores the number of requests grouped by it's result. nResult []uint64 // id is the unique unit's identifier. It's set to an absolute hour number // since the beginning of UNIX time by the default ID generating function. // // Must not be rewritten after creating to be accessed concurrently without // using mu. id uint32 // nTotal stores the total number of requests. nTotal uint64 // timeSum stores the sum of processing time in microseconds of each request // written by the unit. timeSum uint64 } // newUnit allocates the new *unit. func newUnit(id uint32) (u *unit) { return &unit{ domains: map[string]uint64{}, blockedDomains: map[string]uint64{}, clients: map[string]uint64{}, upstreamsResponses: map[string]uint64{}, upstreamsTimeSum: map[string]uint64{}, nResult: make([]uint64, resultLast), id: id, } } // countPair is a single name-number pair for deserializing statistics data into // the database. type countPair struct { Name string Count uint64 } // unitDB is the structure for serializing statistics data into the database. // // NOTE: Do not change the names or types of fields, as this structure is used // for GOB encoding. type unitDB struct { // NResult is the number of requests by the result's kind. NResult []uint64 // Domains is the number of requests for each domain name. Domains []countPair // BlockedDomains is the number of requests blocked for each domain name. BlockedDomains []countPair // Clients is the number of requests from each client. Clients []countPair // UpstreamsResponses is the number of responses from each upstream. UpstreamsResponses []countPair // UpstreamsTimeSum is the sum of processing time in microseconds of // responses from each upstream. UpstreamsTimeSum []countPair // NTotal is the total number of requests. NTotal uint64 // TimeAvg is the average of processing times in microseconds of all the // requests in the unit. TimeAvg uint32 } // newUnitID is the default UnitIDGenFunc that generates the unique id hourly. func newUnitID() (id uint32) { const secsInHour = int64(time.Hour / time.Second) return uint32(time.Now().Unix() / secsInHour) } func finishTxn(tx *bbolt.Tx, commit bool) (err error) { if commit { err = errors.Annotate(tx.Commit(), "committing: %w") } else { err = errors.Annotate(tx.Rollback(), "rolling back: %w") } return err } // bucketNameLen is the length of a bucket, a 64-bit unsigned integer. // // TODO(a.garipov): Find out why a 64-bit integer is used when IDs seem to // always be 32 bits. const bucketNameLen = 8 // idToUnitName converts a numerical ID into a database unit name. func idToUnitName(id uint32) (name []byte) { n := [bucketNameLen]byte{} binary.BigEndian.PutUint64(n[:], uint64(id)) return n[:] } // unitNameToID converts a database unit name into a numerical ID. ok is false // if name is not a valid database unit name. func unitNameToID(name []byte) (id uint32, ok bool) { if len(name) < bucketNameLen { return 0, false } return uint32(binary.BigEndian.Uint64(name)), true } // compareCount used to sort countPair by Count in descending order. func (a countPair) compareCount(b countPair) (res int) { switch x, y := a.Count, b.Count; { case x > y: return -1 case x < y: return +1 default: return 0 } } func convertMapToSlice(m map[string]uint64, max int) (s []countPair) { s = make([]countPair, 0, len(m)) for k, v := range m { s = append(s, countPair{Name: k, Count: v}) } slices.SortFunc(s, countPair.compareCount) if max > len(s) { max = len(s) } return s[:max] } func convertSliceToMap(a []countPair) (m map[string]uint64) { m = map[string]uint64{} for _, it := range a { m[it.Name] = it.Count } return m } // serialize converts u to the *unitDB. It's safe for concurrent use. u must // not be nil. func (u *unit) serialize() (udb *unitDB) { var timeAvg uint32 = 0 if u.nTotal != 0 { timeAvg = uint32(u.timeSum / u.nTotal) } return &unitDB{ NTotal: u.nTotal, NResult: append([]uint64{}, u.nResult...), Domains: convertMapToSlice(u.domains, maxDomains), BlockedDomains: convertMapToSlice(u.blockedDomains, maxDomains), Clients: convertMapToSlice(u.clients, maxClients), UpstreamsResponses: convertMapToSlice(u.upstreamsResponses, maxUpstreams), UpstreamsTimeSum: convertMapToSlice(u.upstreamsTimeSum, maxUpstreams), TimeAvg: timeAvg, } } func loadUnitFromDB(tx *bbolt.Tx, id uint32) (udb *unitDB) { bkt := tx.Bucket(idToUnitName(id)) if bkt == nil { return nil } log.Tracef("Loading unit %d", id) var buf bytes.Buffer buf.Write(bkt.Get([]byte{0})) udb = &unitDB{} err := gob.NewDecoder(&buf).Decode(udb) if err != nil { log.Error("gob Decode: %s", err) return nil } return udb } // deserialize assigns the appropriate values from udb to u. u must not be nil. // It's safe for concurrent use. func (u *unit) deserialize(udb *unitDB) { if udb == nil { return } u.nTotal = udb.NTotal u.nResult = make([]uint64, resultLast) copy(u.nResult, udb.NResult) u.domains = convertSliceToMap(udb.Domains) u.blockedDomains = convertSliceToMap(udb.BlockedDomains) u.clients = convertSliceToMap(udb.Clients) u.upstreamsResponses = convertSliceToMap(udb.UpstreamsResponses) u.upstreamsTimeSum = convertSliceToMap(udb.UpstreamsTimeSum) u.timeSum = uint64(udb.TimeAvg) * udb.NTotal } // add adds new data to u. It's safe for concurrent use. func (u *unit) add(e *Entry) { u.nResult[e.Result]++ if e.Result == RNotFiltered { u.domains[e.Domain]++ } else { u.blockedDomains[e.Domain]++ } u.clients[e.Client]++ pt := uint64(e.ProcessingTime.Microseconds()) u.timeSum += pt u.nTotal++ if e.Upstream != "" { u.upstreamsResponses[e.Upstream]++ ut := uint64(e.UpstreamTime.Microseconds()) u.upstreamsTimeSum[e.Upstream] += ut } } // flushUnitToDB puts udb to the database at id. func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) { log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) bkt, err := tx.CreateBucketIfNotExists(idToUnitName(id)) if err != nil { return fmt.Errorf("creating bucket: %w", err) } buf := &bytes.Buffer{} err = gob.NewEncoder(buf).Encode(udb) if err != nil { return fmt.Errorf("encoding unit: %w", err) } err = bkt.Put([]byte{0}, buf.Bytes()) if err != nil { return fmt.Errorf("putting unit to database: %w", err) } return nil } func convertTopSlice(a []countPair) (m []map[string]uint64) { m = make([]map[string]uint64, 0, len(a)) for _, it := range a { m = append(m, map[string]uint64{it.Name: it.Count}) } return m } // pairsGetter is a signature for topsCollector argument. type pairsGetter func(u *unitDB) (pairs []countPair) // topsCollector collects statistics about highest values from the given *unitDB // slice using pg to retrieve data. func topsCollector(units []*unitDB, max int, ignored *aghnet.IgnoreEngine, pg pairsGetter) []map[string]uint64 { m := map[string]uint64{} for _, u := range units { for _, cp := range pg(u) { if !ignored.Has(cp.Name) { m[cp.Name] += cp.Count } } } a2 := convertMapToSlice(m, max) return convertTopSlice(a2) } // getData returns the statistics data using the following algorithm: // // 1. Prepare a slice of N units, where N is the value of "limit" configuration // setting. Load data for the most recent units from the file. If a unit // with required ID doesn't exist, just add an empty unit. Get data for the // current unit. // // 2. Process data from the units and prepare an output map object, including // per time unit counters (DNS queries per time-unit, blocked queries per // time unit, etc.). If the time unit is hour, just add values from each // unit to the slice; otherwise, the time unit is day, so aggregate per-hour // data into days. // // To get the top counters (queries per domain, queries per blocked domain, // etc.), first sum up data for all units into a single map. Then, get the // pairs with the highest numbers. // // The total counters (DNS queries, blocked, etc.) are just the sum of data // for all units. func (s *StatsCtx) getData(limit uint32) (resp *StatsResp, ok bool) { if limit == 0 { return &StatsResp{ TimeUnits: "days", TopBlocked: []topAddrs{}, TopClients: []topAddrs{}, TopQueried: []topAddrs{}, TopUpstreamsResponses: []topAddrs{}, TopUpstreamsAvgTime: []topAddrsFloat{}, BlockedFiltering: []uint64{}, DNSQueries: []uint64{}, ReplacedParental: []uint64{}, ReplacedSafebrowsing: []uint64{}, }, true } units, curID := s.loadUnits(limit) if units == nil { return &StatsResp{}, false } return s.dataFromUnits(units, curID), true } // dataFromUnits collects and returns the statistics data. func (s *StatsCtx) dataFromUnits(units []*unitDB, curID uint32) (resp *StatsResp) { topUpstreamsResponses, topUpstreamsAvgTime := topUpstreamsPairs(units) resp = &StatsResp{ TopQueried: topsCollector(units, maxDomains, s.ignored, func(u *unitDB) (pairs []countPair) { return u.Domains }), TopBlocked: topsCollector(units, maxDomains, s.ignored, func(u *unitDB) (pairs []countPair) { return u.BlockedDomains }), TopUpstreamsResponses: topUpstreamsResponses, TopUpstreamsAvgTime: topUpstreamsAvgTime, TopClients: topsCollector(units, maxClients, nil, topClientPairs(s)), } s.fillCollectedStats(resp, units, curID) // Total counters: sum := unitDB{ NResult: make([]uint64, resultLast), } var timeN uint32 for _, u := range units { sum.NTotal += u.NTotal sum.TimeAvg += u.TimeAvg if u.TimeAvg != 0 { timeN++ } sum.NResult[RFiltered] += u.NResult[RFiltered] sum.NResult[RSafeBrowsing] += u.NResult[RSafeBrowsing] sum.NResult[RSafeSearch] += u.NResult[RSafeSearch] sum.NResult[RParental] += u.NResult[RParental] } resp.NumDNSQueries = sum.NTotal resp.NumBlockedFiltering = sum.NResult[RFiltered] resp.NumReplacedSafebrowsing = sum.NResult[RSafeBrowsing] resp.NumReplacedSafesearch = sum.NResult[RSafeSearch] resp.NumReplacedParental = sum.NResult[RParental] if timeN != 0 { resp.AvgProcessingTime = microsecondsToSeconds(float64(sum.TimeAvg / timeN)) } return resp } // fillCollectedStats fills data with collected statistics. func (s *StatsCtx) fillCollectedStats(data *StatsResp, units []*unitDB, curID uint32) { size := len(units) data.TimeUnits = timeUnitsHours daysCount := size / 24 if daysCount > 7 { size = daysCount data.TimeUnits = timeUnitsDays } data.DNSQueries = make([]uint64, size) data.BlockedFiltering = make([]uint64, size) data.ReplacedSafebrowsing = make([]uint64, size) data.ReplacedParental = make([]uint64, size) if data.TimeUnits == timeUnitsDays { s.fillCollectedStatsDaily(data, units, curID, size) return } for i, u := range units { data.DNSQueries[i] += u.NTotal data.BlockedFiltering[i] += u.NResult[RFiltered] data.ReplacedSafebrowsing[i] += u.NResult[RSafeBrowsing] data.ReplacedParental[i] += u.NResult[RParental] } } // fillCollectedStatsDaily fills data with collected daily statistics. units // must contain data for the count of days. // // TODO(s.chzhen): Improve collection of statistics for frontend. Dashboard // cards should contain statistics for the whole interval without rounding to // days. func (s *StatsCtx) fillCollectedStatsDaily( data *StatsResp, units []*unitDB, curHour uint32, days int, ) { // Per time unit counters: 720 hours may span 31 days, so we skip data for // the first hours in this case. align_ceil(24) hours := countHours(curHour, days) units = units[len(units)-hours:] for i, u := range units { day := i / 24 data.DNSQueries[day] += u.NTotal data.BlockedFiltering[day] += u.NResult[RFiltered] data.ReplacedSafebrowsing[day] += u.NResult[RSafeBrowsing] data.ReplacedParental[day] += u.NResult[RParental] } } // countHours returns the number of hours in the last days. func countHours(curHour uint32, days int) (n int) { hoursInCurDay := int(curHour % 24) if hoursInCurDay == 0 { hoursInCurDay = 24 } hoursInRestDays := (days - 1) * 24 return hoursInRestDays + hoursInCurDay } func topClientPairs(s *StatsCtx) (pg pairsGetter) { return func(u *unitDB) (clients []countPair) { for _, c := range u.Clients { if c.Name != "" && !s.shouldCountClient([]string{c.Name}) { continue } clients = append(clients, c) } return clients } } // topUpstreamsPairs returns sorted lists of number of total responses and the // average of processing time for each upstream. func topUpstreamsPairs( units []*unitDB, ) (topUpstreamsResponses []topAddrs, topUpstreamsAvgTime []topAddrsFloat) { upstreamsResponses := topAddrs{} upstreamsTimeSum := topAddrsFloat{} for _, u := range units { for _, cp := range u.UpstreamsResponses { upstreamsResponses[cp.Name] += cp.Count } for _, cp := range u.UpstreamsTimeSum { upstreamsTimeSum[cp.Name] += float64(cp.Count) } } upstreamsAvgTime := topAddrsFloat{} for u, n := range upstreamsResponses { total := upstreamsTimeSum[u] if total != 0 { upstreamsAvgTime[u] = microsecondsToSeconds(total / float64(n)) } } upstreamsPairs := convertMapToSlice(upstreamsResponses, maxUpstreams) topUpstreamsResponses = convertTopSlice(upstreamsPairs) return topUpstreamsResponses, prepareTopUpstreamsAvgTime(upstreamsAvgTime) } // microsecondsToSeconds converts microseconds to seconds. // // NOTE: Frontend expects time duration in seconds as floating-point number // with double precision. func microsecondsToSeconds(n float64) (r float64) { const micro = 1e-6 return n * micro } // prepareTopUpstreamsAvgTime returns sorted list of average processing times // of the DNS requests from each upstream. func prepareTopUpstreamsAvgTime( upstreamsAvgTime topAddrsFloat, ) (topUpstreamsAvgTime []topAddrsFloat) { keys := maps.Keys(upstreamsAvgTime) slices.SortFunc(keys, func(a, b string) (res int) { switch x, y := upstreamsAvgTime[a], upstreamsAvgTime[b]; { case x > y: return -1 case x < y: return +1 default: return 0 } }) topUpstreamsAvgTime = make([]topAddrsFloat, 0, len(upstreamsAvgTime)) for _, k := range keys { topUpstreamsAvgTime = append(topUpstreamsAvgTime, topAddrsFloat{k: upstreamsAvgTime[k]}) } return topUpstreamsAvgTime } ```
/content/code_sandbox/internal/stats/unit.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
4,783
```go // HTTP request handlers for accessing statistics data and configuration settings package stats import ( "encoding/json" "net/http" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/timeutil" ) // topAddrs is an alias for the types of the TopFoo fields of statsResponse. // The key is either a client's address or a requested address. type topAddrs = map[string]uint64 // topAddrsFloat is like [topAddrs] but the value is float64 number. type topAddrsFloat = map[string]float64 // StatsResp is a response to the GET /control/stats. type StatsResp struct { TimeUnits string `json:"time_units"` TopQueried []topAddrs `json:"top_queried_domains"` TopClients []topAddrs `json:"top_clients"` TopBlocked []topAddrs `json:"top_blocked_domains"` TopUpstreamsResponses []topAddrs `json:"top_upstreams_responses"` TopUpstreamsAvgTime []topAddrsFloat `json:"top_upstreams_avg_time"` DNSQueries []uint64 `json:"dns_queries"` BlockedFiltering []uint64 `json:"blocked_filtering"` ReplacedSafebrowsing []uint64 `json:"replaced_safebrowsing"` ReplacedParental []uint64 `json:"replaced_parental"` NumDNSQueries uint64 `json:"num_dns_queries"` NumBlockedFiltering uint64 `json:"num_blocked_filtering"` NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"` NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"` NumReplacedParental uint64 `json:"num_replaced_parental"` AvgProcessingTime float64 `json:"avg_processing_time"` } // handleStats is the handler for the GET /control/stats HTTP API. func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) { start := time.Now() var ( resp *StatsResp ok bool ) func() { s.confMu.RLock() defer s.confMu.RUnlock() resp, ok = s.getData(uint32(s.limit.Hours())) }() log.Debug("stats: prepared data in %v", time.Since(start)) if !ok { // Don't bring the message to the lower case since it's a part of UI // text for the moment. aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't get statistics data") return } aghhttp.WriteJSONResponseOK(w, r, resp) } // configResp is the response to the GET /control/stats_info. type configResp struct { IntervalDays uint32 `json:"interval"` } // getConfigResp is the response to the GET /control/stats_info. type getConfigResp struct { // Ignored is the list of host names, which should not be counted. Ignored []string `json:"ignored"` // Interval is the statistics rotation interval in milliseconds. Interval float64 `json:"interval"` // Enabled shows if statistics are enabled. It is an aghalg.NullBool to be // able to tell when it's set without using pointers. Enabled aghalg.NullBool `json:"enabled"` } // handleStatsInfo is the handler for the GET /control/stats_info HTTP API. // // Deprecated: Remove it when migration to the new API is over. func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) { var ( enabled bool limit time.Duration ) func() { s.confMu.RLock() defer s.confMu.RUnlock() enabled, limit = s.enabled, s.limit }() days := uint32(limit / timeutil.Day) ok := checkInterval(days) if !ok || (enabled && days == 0) { // NOTE: If interval is custom we set it to 90 days for compatibility // with old API. days = 90 } resp := configResp{IntervalDays: days} if !enabled { resp.IntervalDays = 0 } aghhttp.WriteJSONResponseOK(w, r, resp) } // handleGetStatsConfig is the handler for the GET /control/stats/config HTTP // API. func (s *StatsCtx) handleGetStatsConfig(w http.ResponseWriter, r *http.Request) { var resp *getConfigResp func() { s.confMu.RLock() defer s.confMu.RUnlock() resp = &getConfigResp{ Ignored: s.ignored.Values(), Interval: float64(s.limit.Milliseconds()), Enabled: aghalg.BoolToNullBool(s.enabled), } }() aghhttp.WriteJSONResponseOK(w, r, resp) } // handleStatsConfig is the handler for the POST /control/stats_config HTTP API. // // Deprecated: Remove it when migration to the new API is over. func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) { reqData := configResp{} err := json.NewDecoder(r.Body).Decode(&reqData) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err) return } if !checkInterval(reqData.IntervalDays) { aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval") return } limit := time.Duration(reqData.IntervalDays) * timeutil.Day defer s.configModified() s.confMu.Lock() defer s.confMu.Unlock() s.setLimit(limit) } // handlePutStatsConfig is the handler for the PUT /control/stats/config/update // HTTP API. func (s *StatsCtx) handlePutStatsConfig(w http.ResponseWriter, r *http.Request) { reqData := getConfigResp{} err := json.NewDecoder(r.Body).Decode(&reqData) if err != nil { aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err) return } engine, err := aghnet.NewIgnoreEngine(reqData.Ignored) if err != nil { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "ignored: %s", err) return } ivl := time.Duration(reqData.Interval) * time.Millisecond err = validateIvl(ivl) if err != nil { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "unsupported interval: %s", err) return } if reqData.Enabled == aghalg.NBNull { aghhttp.Error(r, w, http.StatusUnprocessableEntity, "enabled is null") return } defer s.configModified() s.confMu.Lock() defer s.confMu.Unlock() s.ignored = engine s.limit = ivl s.enabled = reqData.Enabled == aghalg.NBTrue } // handleStatsReset is the handler for the POST /control/stats_reset HTTP API. func (s *StatsCtx) handleStatsReset(w http.ResponseWriter, r *http.Request) { err := s.clear() if err != nil { aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err) } } // initWeb registers the handlers for web endpoints of statistics module. func (s *StatsCtx) initWeb() { if s.httpRegister == nil { return } s.httpRegister(http.MethodGet, "/control/stats", s.handleStats) s.httpRegister(http.MethodPost, "/control/stats_reset", s.handleStatsReset) s.httpRegister(http.MethodGet, "/control/stats/config", s.handleGetStatsConfig) s.httpRegister(http.MethodPut, "/control/stats/config/update", s.handlePutStatsConfig) // Deprecated handlers. s.httpRegister(http.MethodGet, "/control/stats_info", s.handleStatsInfo) s.httpRegister(http.MethodPost, "/control/stats_config", s.handleStatsConfig) } ```
/content/code_sandbox/internal/stats/http.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,766
```go package stats import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUnit_Deserialize(t *testing.T) { testCases := []struct { db *unitDB name string want unit }{{ name: "empty", want: unit{ domains: map[string]uint64{}, blockedDomains: map[string]uint64{}, clients: map[string]uint64{}, nResult: []uint64{0, 0, 0, 0, 0, 0}, id: 0, nTotal: 0, timeSum: 0, upstreamsResponses: map[string]uint64{}, upstreamsTimeSum: map[string]uint64{}, }, db: &unitDB{ NResult: []uint64{0, 0, 0, 0, 0, 0}, Domains: []countPair{}, BlockedDomains: []countPair{}, Clients: []countPair{}, NTotal: 0, TimeAvg: 0, UpstreamsResponses: []countPair{}, UpstreamsTimeSum: []countPair{}, }, }, { name: "basic", want: unit{ domains: map[string]uint64{ "example.com": 1, }, blockedDomains: map[string]uint64{ "example.net": 1, }, clients: map[string]uint64{ "127.0.0.1": 2, }, nResult: []uint64{0, 1, 1, 0, 0, 0}, id: 0, nTotal: 2, timeSum: 246912, upstreamsResponses: map[string]uint64{ "1.2.3.4": 2, }, upstreamsTimeSum: map[string]uint64{ "1.2.3.4": 246912, }, }, db: &unitDB{ NResult: []uint64{0, 1, 1, 0, 0, 0}, Domains: []countPair{{ "example.com", 1, }}, BlockedDomains: []countPair{{ "example.net", 1, }}, Clients: []countPair{{ "127.0.0.1", 2, }}, NTotal: 2, TimeAvg: 123456, UpstreamsResponses: []countPair{{ "1.2.3.4", 2, }}, UpstreamsTimeSum: []countPair{{ "1.2.3.4", 246912, }}, }, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got := unit{} got.deserialize(tc.db) require.Equal(t, tc.want, got) }) } } func TestTopUpstreamsPairs(t *testing.T) { testCases := []struct { db *unitDB name string wantResponses []topAddrs wantAvgTime []topAddrsFloat }{{ name: "empty", db: &unitDB{ NResult: []uint64{0, 0, 0, 0, 0, 0}, Domains: []countPair{}, BlockedDomains: []countPair{}, Clients: []countPair{}, NTotal: 0, TimeAvg: 0, UpstreamsResponses: []countPair{}, UpstreamsTimeSum: []countPair{}, }, wantResponses: []topAddrs{}, wantAvgTime: []topAddrsFloat{}, }, { name: "basic", db: &unitDB{ NResult: []uint64{0, 0, 0, 0, 0, 0}, Domains: []countPair{}, BlockedDomains: []countPair{}, Clients: []countPair{}, NTotal: 0, TimeAvg: 0, UpstreamsResponses: []countPair{{ "1.2.3.4", 2, }}, UpstreamsTimeSum: []countPair{{ "1.2.3.4", 246912, }}, }, wantResponses: []topAddrs{{ "1.2.3.4": 2, }}, wantAvgTime: []topAddrsFloat{{ "1.2.3.4": 0.123456, }}, }, { name: "sorted", db: &unitDB{ NResult: []uint64{0, 0, 0, 0, 0, 0}, Domains: []countPair{}, BlockedDomains: []countPair{}, Clients: []countPair{}, NTotal: 0, TimeAvg: 0, UpstreamsResponses: []countPair{ {"3.3.3.3", 8}, {"2.2.2.2", 4}, {"4.4.4.4", 16}, {"1.1.1.1", 2}, }, UpstreamsTimeSum: []countPair{ {"3.3.3.3", 800_000_000}, {"2.2.2.2", 40_000_000}, {"4.4.4.4", 16_000_000_000}, {"1.1.1.1", 2_000_000}, }, }, wantResponses: []topAddrs{ {"4.4.4.4": 16}, {"3.3.3.3": 8}, {"2.2.2.2": 4}, {"1.1.1.1": 2}, }, wantAvgTime: []topAddrsFloat{ {"4.4.4.4": 1000}, {"3.3.3.3": 100}, {"2.2.2.2": 10}, {"1.1.1.1": 1}, }, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { gotResponses, gotAvgTime := topUpstreamsPairs([]*unitDB{tc.db}) assert.Equal(t, tc.wantResponses, gotResponses) assert.Equal(t, tc.wantAvgTime, gotAvgTime) }) } } ```
/content/code_sandbox/internal/stats/unit_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,565
```go package stats_test import ( "encoding/json" "fmt" "net" "net/http" "net/http/httptest" "path/filepath" "sync/atomic" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/stats" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/miekg/dns" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { testutil.DiscardLogOutput(m) } // constUnitID is the UnitIDGenFunc which always return 0. func constUnitID() (id uint32) { return 0 } func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) { t.Helper() require.NotNil(t, handler) rw := httptest.NewRecorder() handler.ServeHTTP(rw, req) require.Equal(t, http.StatusOK, rw.Code) data := rw.Body.Bytes() if to == nil { assert.Empty(t, data) return } err := json.Unmarshal(data, to) require.NoError(t, err) } func TestStats(t *testing.T) { cliIP := netutil.IPv4Localhost() cliIPStr := cliIP.String() handlers := map[string]http.Handler{} conf := stats.Config{ ShouldCountClient: func([]string) bool { return true }, Filename: filepath.Join(t.TempDir(), "stats.db"), Limit: timeutil.Day, Enabled: true, UnitID: constUnitID, HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, } s, err := stats.New(conf) require.NoError(t, err) s.Start() testutil.CleanupAndRequireSuccess(t, s.Close) t.Run("data", func(t *testing.T) { const reqDomain = "domain" const respUpstream = "upstream" entries := []*stats.Entry{{ Domain: reqDomain, Client: cliIPStr, Result: stats.RFiltered, ProcessingTime: time.Microsecond * 123456, Upstream: respUpstream, UpstreamTime: time.Microsecond * 222222, }, { Domain: reqDomain, Client: cliIPStr, Result: stats.RNotFiltered, ProcessingTime: time.Microsecond * 123456, Upstream: respUpstream, UpstreamTime: time.Microsecond * 222222, }} wantData := &stats.StatsResp{ TimeUnits: "hours", TopQueried: []map[string]uint64{0: {reqDomain: 1}}, TopClients: []map[string]uint64{0: {cliIPStr: 2}}, TopBlocked: []map[string]uint64{0: {reqDomain: 1}}, TopUpstreamsResponses: []map[string]uint64{0: {respUpstream: 2}}, TopUpstreamsAvgTime: []map[string]float64{0: {respUpstream: 0.222222}}, DNSQueries: []uint64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, }, BlockedFiltering: []uint64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, }, ReplacedSafebrowsing: []uint64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, ReplacedParental: []uint64{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, NumDNSQueries: 2, NumBlockedFiltering: 1, NumReplacedSafebrowsing: 0, NumReplacedSafesearch: 0, NumReplacedParental: 0, AvgProcessingTime: 0.123456, } for _, e := range entries { s.Update(e) } data := &stats.StatsResp{} req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) assert.Equal(t, wantData, data) }) t.Run("tops", func(t *testing.T) { topClients := s.TopClientsIP(2) require.NotEmpty(t, topClients) assert.Equal(t, cliIP, topClients[0]) }) t.Run("reset", func(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil) assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req) _24zeroes := [24]uint64{} emptyData := &stats.StatsResp{ TimeUnits: "hours", TopQueried: []map[string]uint64{}, TopClients: []map[string]uint64{}, TopBlocked: []map[string]uint64{}, TopUpstreamsResponses: []map[string]uint64{}, TopUpstreamsAvgTime: []map[string]float64{}, DNSQueries: _24zeroes[:], BlockedFiltering: _24zeroes[:], ReplacedSafebrowsing: _24zeroes[:], ReplacedParental: _24zeroes[:], } req = httptest.NewRequest(http.MethodGet, "/control/stats", nil) data := &stats.StatsResp{} assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) assert.Equal(t, emptyData, data) }) } func TestLargeNumbers(t *testing.T) { var curHour uint32 = 1 handlers := map[string]http.Handler{} conf := stats.Config{ ShouldCountClient: func([]string) bool { return true }, Filename: filepath.Join(t.TempDir(), "stats.db"), Limit: timeutil.Day, Enabled: true, UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) }, HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, } s, err := stats.New(conf) require.NoError(t, err) s.Start() testutil.CleanupAndRequireSuccess(t, s.Close) const ( hoursNum = 12 cliNumPerHour = 1000 ) req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) for h := 0; h < hoursNum; h++ { atomic.AddUint32(&curHour, 1) for i := range cliNumPerHour { ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)} e := &stats.Entry{ Domain: fmt.Sprintf("domain%d.hour%d", i, h), Client: ip.String(), Result: stats.RNotFiltered, ProcessingTime: 123456, } s.Update(e) } } data := &stats.StatsResp{} assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) assert.Equal(t, hoursNum*cliNumPerHour, int(data.NumDNSQueries)) } func TestShouldCount(t *testing.T) { const ( ignored1 = "ignor.ed" ignored2 = "ignored.to" ) ignored := []string{ignored1, ignored2} engine, err := aghnet.NewIgnoreEngine(ignored) require.NoError(t, err) s, err := stats.New(stats.Config{ Enabled: true, Filename: filepath.Join(t.TempDir(), "stats.db"), Limit: timeutil.Day, Ignored: engine, ShouldCountClient: func(ids []string) (a bool) { return ids[0] != "no_count" }, }) require.NoError(t, err) s.Start() testutil.CleanupAndRequireSuccess(t, s.Close) testCases := []struct { wantCount assert.BoolAssertionFunc name string host string ids []string }{{ name: "count", host: "example.com", ids: []string{"whatever"}, wantCount: assert.True, }, { name: "no_count_ignored_1", host: ignored1, ids: []string{"whatever"}, wantCount: assert.False, }, { name: "no_count_ignored_2", host: ignored2, ids: []string{"whatever"}, wantCount: assert.False, }, { name: "no_count_client_ignore", host: "example.com", ids: []string{"no_count"}, wantCount: assert.False, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res := s.ShouldCount(tc.host, dns.TypeA, dns.ClassINET, tc.ids) tc.wantCount(t, res) }) } } ```
/content/code_sandbox/internal/stats/stats_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
2,335
```go // Package stats provides units for managing statistics of the filtering DNS // server. package stats import ( "fmt" "io" "net/netip" "os" "sync" "sync/atomic" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/timeutil" "go.etcd.io/bbolt" ) // checkInterval returns true if days is valid to be used as statistics // retention interval. The valid values are 0, 1, 7, 30 and 90. func checkInterval(days uint32) (ok bool) { return days == 0 || days == 1 || days == 7 || days == 30 || days == 90 } // validateIvl returns an error if ivl is less than an hour or more than a // year. func validateIvl(ivl time.Duration) (err error) { if ivl < time.Hour { return errors.Error("less than an hour") } if ivl > timeutil.Day*365 { return errors.Error("more than a year") } return nil } // Config is the configuration structure for the statistics collecting. // // Do not alter any fields of this structure after using it. type Config struct { // UnitID is the function to generate the identifier for current unit. If // nil, the default function is used, see newUnitID. UnitID UnitIDGenFunc // ConfigModified will be called each time the configuration changed via web // interface. ConfigModified func() // ShouldCountClient returns client's ignore setting. ShouldCountClient func([]string) bool // HTTPRegister is the function that registers handlers for the stats // endpoints. HTTPRegister aghhttp.RegisterFunc // Ignored contains the list of host names, which should not be counted, // and matches them. Ignored *aghnet.IgnoreEngine // Filename is the name of the database file. Filename string // Limit is an upper limit for collecting statistics. Limit time.Duration // Enabled tells if the statistics are enabled. Enabled bool } // Interface is the statistics interface to be used by other packages. type Interface interface { // Start begins the statistics collecting. Start() io.Closer // Update collects the incoming statistics data. Update(e *Entry) // GetTopClientIP returns at most limit IP addresses corresponding to the // clients with the most number of requests. TopClientsIP(limit uint) []netip.Addr // WriteDiskConfig puts the Interface's configuration to the dc. WriteDiskConfig(dc *Config) // ShouldCount returns true if request for the host should be counted. ShouldCount(host string, qType, qClass uint16, ids []string) bool } // StatsCtx collects the statistics and flushes it to the database. Its default // flushing interval is one hour. type StatsCtx struct { // currMu protects curr. currMu *sync.RWMutex // curr is the actual statistics collection result. curr *unit // db is the opened statistics database, if any. db atomic.Pointer[bbolt.DB] // unitIDGen is the function that generates an identifier for the current // unit. It's here for only testing purposes. unitIDGen UnitIDGenFunc // httpRegister is used to set HTTP handlers. httpRegister aghhttp.RegisterFunc // configModified is called whenever the configuration is modified via web // interface. configModified func() // confMu protects ignored, limit, and enabled. confMu *sync.RWMutex // ignored contains the list of host names, which should not be counted, // and matches them. ignored *aghnet.IgnoreEngine // shouldCountClient returns client's ignore setting. shouldCountClient func([]string) bool // filename is the name of database file. filename string // limit is an upper limit for collecting statistics. limit time.Duration // enabled tells if the statistics are enabled. enabled bool } // New creates s from conf and properly initializes it. Don't use s before // calling it's Start method. func New(conf Config) (s *StatsCtx, err error) { defer withRecovered(&err) err = validateIvl(conf.Limit) if err != nil { return nil, fmt.Errorf("unsupported interval: %w", err) } if conf.ShouldCountClient == nil { return nil, errors.Error("should count client is unspecified") } s = &StatsCtx{ currMu: &sync.RWMutex{}, httpRegister: conf.HTTPRegister, configModified: conf.ConfigModified, filename: conf.Filename, confMu: &sync.RWMutex{}, ignored: conf.Ignored, shouldCountClient: conf.ShouldCountClient, limit: conf.Limit, enabled: conf.Enabled, } if s.unitIDGen = newUnitID; conf.UnitID != nil { s.unitIDGen = conf.UnitID } // TODO(e.burkov): Move the code below to the Start method. err = s.openDB() if err != nil { return nil, fmt.Errorf("opening database: %w", err) } var udb *unitDB id := s.unitIDGen() tx, err := s.db.Load().Begin(true) if err != nil { return nil, fmt.Errorf("stats: opening a transaction: %w", err) } deleted := deleteOldUnits(tx, id-uint32(s.limit.Hours())-1) udb = loadUnitFromDB(tx, id) err = finishTxn(tx, deleted > 0) if err != nil { log.Error("stats: %s", err) } s.curr = newUnit(id) s.curr.deserialize(udb) log.Debug("stats: initialized") return s, nil } // withRecovered turns the value recovered from panic if any into an error and // combines it with the one pointed by orig. orig must be non-nil. func withRecovered(orig *error) { p := recover() if p == nil { return } var err error switch p := p.(type) { case error: err = fmt.Errorf("panic: %w", p) default: err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p) } *orig = errors.WithDeferred(*orig, err) } // type check var _ Interface = (*StatsCtx)(nil) // Start implements the [Interface] interface for *StatsCtx. func (s *StatsCtx) Start() { s.initWeb() go s.periodicFlush() } // Close implements the [io.Closer] interface for *StatsCtx. func (s *StatsCtx) Close() (err error) { defer func() { err = errors.Annotate(err, "stats: closing: %w") }() db := s.db.Swap(nil) if db == nil { return nil } defer func() { cerr := db.Close() if cerr == nil { log.Debug("stats: database closed") } err = errors.WithDeferred(err, cerr) }() tx, err := db.Begin(true) if err != nil { return fmt.Errorf("opening transaction: %w", err) } defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }() s.currMu.RLock() defer s.currMu.RUnlock() udb := s.curr.serialize() return udb.flushUnitToDB(tx, s.curr.id) } // Update implements the [Interface] interface for *StatsCtx. e must not be // nil. func (s *StatsCtx) Update(e *Entry) { s.confMu.Lock() defer s.confMu.Unlock() if !s.enabled || s.limit == 0 { return } err := e.validate() if err != nil { log.Debug("stats: updating: validating entry: %s", err) return } s.currMu.Lock() defer s.currMu.Unlock() if s.curr == nil { log.Error("stats: current unit is nil") return } s.curr.add(e) } // WriteDiskConfig implements the [Interface] interface for *StatsCtx. func (s *StatsCtx) WriteDiskConfig(dc *Config) { s.confMu.RLock() defer s.confMu.RUnlock() dc.Ignored = s.ignored dc.Limit = s.limit dc.Enabled = s.enabled } // TopClientsIP implements the [Interface] interface for *StatsCtx. func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []netip.Addr) { s.confMu.RLock() defer s.confMu.RUnlock() limit := uint32(s.limit.Hours()) if !s.enabled || limit == 0 { return nil } units, _ := s.loadUnits(limit) if units == nil { return nil } // Collect data for all the clients to sort and crop it afterwards. m := map[string]uint64{} for _, u := range units { for _, it := range u.Clients { m[it.Name] += it.Count } } a := convertMapToSlice(m, int(maxCount)) ips = []netip.Addr{} for _, it := range a { ip, err := netip.ParseAddr(it.Name) if err == nil { ips = append(ips, ip) } } return ips } // deleteOldUnits walks the buckets available to tx and deletes old units. It // returns the number of deletions performed. func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) { log.Debug("stats: deleting old units until id %d", firstID) // TODO(a.garipov): See if this is actually necessary. Looks like a rather // bizarre solution. const errStop errors.Error = "stop iteration" walk := func(name []byte, _ *bbolt.Bucket) (err error) { nameID, ok := unitNameToID(name) if ok && nameID >= firstID { return errStop } err = tx.DeleteBucket(name) if err != nil { log.Debug("stats: deleting bucket: %s", err) return nil } log.Debug("stats: deleted unit %d (name %x)", nameID, name) deleted++ return nil } err := tx.ForEach(walk) if err != nil && !errors.Is(err, errStop) { log.Debug("stats: deleting units: %s", err) } return deleted } // openDB returns an error if the database can't be opened from the specified // file. It's safe for concurrent use. func (s *StatsCtx) openDB() (err error) { log.Debug("stats: opening database") var db *bbolt.DB db, err = bbolt.Open(s.filename, 0o644, nil) if err != nil { if err.Error() == "invalid argument" { log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: path_to_url#limitations") } return err } // Use defer to unlock the mutex as soon as possible. defer log.Debug("stats: database opened") s.db.Store(db) return nil } func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) { id := s.unitIDGen() s.confMu.Lock() defer s.confMu.Unlock() s.currMu.Lock() defer s.currMu.Unlock() ptr := s.curr if ptr == nil { return false, 0 } limit := uint32(s.limit.Hours()) if limit == 0 || ptr.id == id { return true, time.Second } return s.flushDB(id, limit, ptr) } // flushDB flushes the unit to the database. confMu and currMu are expected to // be locked. func (s *StatsCtx) flushDB(id, limit uint32, ptr *unit) (cont bool, sleepFor time.Duration) { db := s.db.Load() if db == nil { return true, 0 } isCommitable := true tx, err := db.Begin(true) if err != nil { log.Error("stats: opening transaction: %s", err) return true, 0 } defer func() { if err = finishTxn(tx, isCommitable); err != nil { log.Error("stats: %s", err) } }() s.curr = newUnit(id) flushErr := ptr.serialize().flushUnitToDB(tx, ptr.id) if flushErr != nil { log.Error("stats: flushing unit: %s", flushErr) isCommitable = false } delErr := tx.DeleteBucket(idToUnitName(id - limit)) if delErr != nil { // TODO(e.burkov): Improve the algorithm of deleting the oldest bucket // to avoid the error. if errors.Is(delErr, bbolt.ErrBucketNotFound) { log.Debug("stats: warning: deleting unit: %s", delErr) } else { isCommitable = false log.Error("stats: deleting unit: %s", delErr) } } return true, 0 } // periodicFlush checks and flushes the unit to the database if the freshly // generated unit ID differs from the current's ID. Flushing process includes: // - swapping the current unit with the new empty one; // - writing the current unit to the database; // - removing the stale unit from the database. func (s *StatsCtx) periodicFlush() { for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) { cont, sleepFor = s.flush() } log.Debug("periodic flushing finished") } // setLimit sets the limit. s.lock is expected to be locked. // // TODO(s.chzhen): Remove it when migration to the new API is over. func (s *StatsCtx) setLimit(limit time.Duration) { if limit != 0 { s.enabled = true s.limit = limit log.Debug("stats: set limit: %d days", limit/timeutil.Day) return } s.enabled = false log.Debug("stats: disabled") if err := s.clear(); err != nil { log.Error("stats: %s", err) } } // Reset counters and clear database func (s *StatsCtx) clear() (err error) { defer func() { err = errors.Annotate(err, "clearing: %w") }() db := s.db.Swap(nil) if db != nil { var tx *bbolt.Tx tx, err = db.Begin(true) if err != nil { log.Error("stats: opening a transaction: %s", err) } else if err = finishTxn(tx, false); err != nil { // Don't wrap the error since it's informative enough as is. return err } // Active transactions will continue using database, but new ones won't // be created. err = db.Close() if err != nil { return fmt.Errorf("closing database: %w", err) } // All active transactions are now closed. log.Debug("stats: database closed") } err = os.Remove(s.filename) if err != nil { log.Error("stats: %s", err) } err = s.openDB() if err != nil { log.Error("stats: opening database: %s", err) } // Use defer to unlock the mutex as soon as possible. defer log.Debug("stats: cleared") s.currMu.Lock() defer s.currMu.Unlock() s.curr = newUnit(s.unitIDGen()) return nil } // loadUnits returns stored units from the database and current unit ID. func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, curID uint32) { db := s.db.Load() if db == nil { return nil, 0 } // Use writable transaction to ensure any ongoing writable transaction is // taken into account. tx, err := db.Begin(true) if err != nil { log.Error("stats: opening transaction: %s", err) return nil, 0 } s.currMu.RLock() defer s.currMu.RUnlock() cur := s.curr if cur != nil { curID = cur.id } else { curID = s.unitIDGen() } // Per-hour units. units = make([]*unitDB, 0, limit) firstID := curID - limit + 1 for i := firstID; i != curID; i++ { u := loadUnitFromDB(tx, i) if u == nil { u = &unitDB{NResult: make([]uint64, resultLast)} } units = append(units, u) } err = finishTxn(tx, false) if err != nil { log.Error("stats: %s", err) } if cur != nil { units = append(units, cur.serialize()) } if unitsLen := len(units); unitsLen != int(limit) { log.Fatalf("loaded %d units whilst the desired number is %d", unitsLen, limit) } return units, curID } // ShouldCount returns true if request for the host should be counted. func (s *StatsCtx) ShouldCount(host string, _, _ uint16, ids []string) bool { s.confMu.RLock() defer s.confMu.RUnlock() if !s.shouldCountClient(ids) { return false } return !s.isIgnored(host) } // isIgnored returns true if the host is in the ignored domains list. It // assumes that s.confMu is locked for reading. func (s *StatsCtx) isIgnored(host string) bool { return s.ignored.Has(host) } ```
/content/code_sandbox/internal/stats/stats.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,968
```go package stats import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "path/filepath" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHandleStatsConfig(t *testing.T) { const ( smallIvl = 1 * time.Minute minIvl = 1 * time.Hour maxIvl = 365 * timeutil.Day ) conf := Config{ UnitID: func() (id uint32) { return 0 }, ConfigModified: func() {}, ShouldCountClient: func([]string) bool { return true }, Filename: filepath.Join(t.TempDir(), "stats.db"), Limit: time.Hour * 24, Enabled: true, } testCases := []struct { name string wantErr string body getConfigResp wantCode int }{{ name: "set_ivl_1_minIvl", body: getConfigResp{ Enabled: aghalg.NBTrue, Interval: float64(minIvl.Milliseconds()), Ignored: []string{}, }, wantCode: http.StatusOK, wantErr: "", }, { name: "small_interval", body: getConfigResp{ Enabled: aghalg.NBTrue, Interval: float64(smallIvl.Milliseconds()), Ignored: []string{}, }, wantCode: http.StatusUnprocessableEntity, wantErr: "unsupported interval: less than an hour\n", }, { name: "big_interval", body: getConfigResp{ Enabled: aghalg.NBTrue, Interval: float64(maxIvl.Milliseconds() + minIvl.Milliseconds()), Ignored: []string{}, }, wantCode: http.StatusUnprocessableEntity, wantErr: "unsupported interval: more than a year\n", }, { name: "set_ignored_ivl_1_maxIvl", body: getConfigResp{ Enabled: aghalg.NBTrue, Interval: float64(maxIvl.Milliseconds()), Ignored: []string{ "ignor.ed", }, }, wantCode: http.StatusOK, wantErr: "", }, { name: "enabled_is_null", body: getConfigResp{ Enabled: aghalg.NBNull, Interval: float64(minIvl.Milliseconds()), Ignored: []string{}, }, wantCode: http.StatusUnprocessableEntity, wantErr: "enabled is null\n", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { s, err := New(conf) require.NoError(t, err) s.Start() testutil.CleanupAndRequireSuccess(t, s.Close) buf, err := json.Marshal(tc.body) require.NoError(t, err) const ( configGet = "/control/stats/config" configPut = "/control/stats/config/update" ) req := httptest.NewRequest(http.MethodPut, configPut, bytes.NewReader(buf)) rw := httptest.NewRecorder() s.handlePutStatsConfig(rw, req) require.Equal(t, tc.wantCode, rw.Code) if tc.wantCode != http.StatusOK { assert.Equal(t, tc.wantErr, rw.Body.String()) return } resp := httptest.NewRequest(http.MethodGet, configGet, nil) rw = httptest.NewRecorder() s.handleGetStatsConfig(rw, resp) require.Equal(t, http.StatusOK, rw.Code) ans := getConfigResp{} err = json.Unmarshal(rw.Body.Bytes(), &ans) require.NoError(t, err) assert.Equal(t, tc.body, ans) }) } } ```
/content/code_sandbox/internal/stats/http_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
903
```go package aghalg import ( "slices" ) // SortedMap is a map that keeps elements in order with internal sorting // function. Must be initialised by the [NewSortedMap]. type SortedMap[K comparable, V any] struct { vals map[K]V cmp func(a, b K) (res int) keys []K } // NewSortedMap initializes the new instance of sorted map. cmp is a sort // function to keep elements in order. // // TODO(s.chzhen): Use cmp.Compare in Go 1.21. func NewSortedMap[K comparable, V any](cmp func(a, b K) (res int)) SortedMap[K, V] { return SortedMap[K, V]{ vals: map[K]V{}, cmp: cmp, } } // Set adds val with key to the sorted map. It panics if the m is nil. func (m *SortedMap[K, V]) Set(key K, val V) { m.vals[key] = val i, has := slices.BinarySearchFunc(m.keys, key, m.cmp) if has { m.keys[i] = key } else { m.keys = slices.Insert(m.keys, i, key) } } // Get returns val by key from the sorted map. func (m *SortedMap[K, V]) Get(key K) (val V, ok bool) { if m == nil { return } val, ok = m.vals[key] return val, ok } // Del removes the value by key from the sorted map. func (m *SortedMap[K, V]) Del(key K) { if m == nil { return } if _, has := m.vals[key]; !has { return } delete(m.vals, key) i, _ := slices.BinarySearchFunc(m.keys, key, m.cmp) m.keys = slices.Delete(m.keys, i, i+1) } // Clear removes all elements from the sorted map. func (m *SortedMap[K, V]) Clear() { if m == nil { return } m.keys = nil clear(m.vals) } // Range calls cb for each element of the map, sorted by m.cmp. If cb returns // false it stops. func (m *SortedMap[K, V]) Range(cb func(K, V) (cont bool)) { if m == nil { return } for _, k := range m.keys { if !cb(k, m.vals[k]) { return } } } ```
/content/code_sandbox/internal/aghalg/sortedmap.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
556
```go package stats import ( "fmt" "path/filepath" "sync" "sync/atomic" "testing" "time" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/timeutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestStats_races(t *testing.T) { var r uint32 idGen := func() (id uint32) { return atomic.LoadUint32(&r) } conf := Config{ ShouldCountClient: func([]string) bool { return true }, UnitID: idGen, Filename: filepath.Join(t.TempDir(), "./stats.db"), Limit: timeutil.Day, } s, err := New(conf) require.NoError(t, err) s.Start() startTime := time.Now() testutil.CleanupAndRequireSuccess(t, s.Close) writeFunc := func(start, fin *sync.WaitGroup, waitCh <-chan unit, i int) { e := &Entry{ Domain: fmt.Sprintf("example-%d.org", i), Client: fmt.Sprintf("client_%d", i), Result: Result(i)%(resultLast-1) + 1, ProcessingTime: time.Since(startTime), } start.Done() defer fin.Done() <-waitCh s.Update(e) } readFunc := func(start, fin *sync.WaitGroup, waitCh <-chan unit) { start.Done() defer fin.Done() <-waitCh _, _ = s.getData(24) } const ( roundsNum = 3 writersNum = 10 readersNum = 5 ) for round := 0; round < roundsNum; round++ { atomic.StoreUint32(&r, uint32(round)) startWG, finWG := &sync.WaitGroup{}, &sync.WaitGroup{} waitCh := make(chan unit) for i := range writersNum { startWG.Add(1) finWG.Add(1) go writeFunc(startWG, finWG, waitCh, i) } for range readersNum { startWG.Add(1) finWG.Add(1) go readFunc(startWG, finWG, waitCh) } startWG.Wait() close(waitCh) finWG.Wait() } } func TestStatsCtx_FillCollectedStats_daily(t *testing.T) { const ( daysCount = 10 timeUnits = "days" ) s, err := New(Config{ ShouldCountClient: func([]string) bool { return true }, Filename: filepath.Join(t.TempDir(), "./stats.db"), Limit: time.Hour, }) require.NoError(t, err) testutil.CleanupAndRequireSuccess(t, s.Close) sum := make([][]uint64, resultLast) sum[RFiltered] = make([]uint64, daysCount) sum[RSafeBrowsing] = make([]uint64, daysCount) sum[RParental] = make([]uint64, daysCount) total := make([]uint64, daysCount) dailyData := []*unitDB{} for i := range daysCount * 24 { n := uint64(i) nResult := make([]uint64, resultLast) nResult[RFiltered] = n nResult[RSafeBrowsing] = n nResult[RParental] = n day := i / 24 sum[RFiltered][day] += n sum[RSafeBrowsing][day] += n sum[RParental][day] += n t := n * 3 total[day] += t dailyData = append(dailyData, &unitDB{ NTotal: t, NResult: nResult, }) } data := &StatsResp{} // In this way we will not skip first hours. curID := uint32(daysCount * 24) s.fillCollectedStats(data, dailyData, curID) assert.Equal(t, timeUnits, data.TimeUnits) assert.Equal(t, sum[RFiltered], data.BlockedFiltering) assert.Equal(t, sum[RSafeBrowsing], data.ReplacedSafebrowsing) assert.Equal(t, sum[RParental], data.ReplacedParental) assert.Equal(t, total, data.DNSQueries) } func TestStatsCtx_DataFromUnits_month(t *testing.T) { const hoursInMonth = 720 s, err := New(Config{ ShouldCountClient: func([]string) bool { return true }, Filename: filepath.Join(t.TempDir(), "./stats.db"), Limit: time.Hour, }) require.NoError(t, err) testutil.CleanupAndRequireSuccess(t, s.Close) units, curID := s.loadUnits(hoursInMonth) require.Len(t, units, hoursInMonth) var h uint32 for h = 1; h <= hoursInMonth; h++ { data := s.dataFromUnits(units[:h], curID) require.NotNil(t, data) } } ```
/content/code_sandbox/internal/stats/stats_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,113
```go package aghalg import ( "bytes" "encoding/json" "fmt" "github.com/AdguardTeam/golibs/mathutil" ) // NullBool is a nullable boolean. Use these in JSON requests and responses // instead of pointers to bool. type NullBool uint8 // NullBool values const ( NBNull NullBool = iota NBTrue NBFalse ) // String implements the fmt.Stringer interface for NullBool. func (nb NullBool) String() (s string) { switch nb { case NBNull: return "null" case NBTrue: return "true" case NBFalse: return "false" } return fmt.Sprintf("!invalid NullBool %d", uint8(nb)) } // BoolToNullBool converts a bool into a NullBool. func BoolToNullBool(cond bool) (nb NullBool) { return NBFalse - mathutil.BoolToNumber[NullBool](cond) } // type check var _ json.Marshaler = NBNull // MarshalJSON implements the json.Marshaler interface for NullBool. func (nb NullBool) MarshalJSON() (b []byte, err error) { return []byte(nb.String()), nil } // type check var _ json.Unmarshaler = (*NullBool)(nil) // UnmarshalJSON implements the json.Unmarshaler interface for *NullBool. func (nb *NullBool) UnmarshalJSON(b []byte) (err error) { if len(b) == 0 || bytes.Equal(b, []byte("null")) { *nb = NBNull } else if bytes.Equal(b, []byte("true")) { *nb = NBTrue } else if bytes.Equal(b, []byte("false")) { *nb = NBFalse } else { return fmt.Errorf("unmarshalling json data into aghalg.NullBool: bad value %q", b) } return nil } ```
/content/code_sandbox/internal/aghalg/nullbool.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
408
```go // Package aghalg contains common generic algorithms and data structures. // // TODO(a.garipov): Move parts of this into golibs. package aghalg import ( "fmt" "slices" "golang.org/x/exp/constraints" ) // CoalesceSlice returns the first non-zero value. It is named after function // COALESCE in SQL. If values or all its elements are empty, it returns nil. func CoalesceSlice[E any, S []E](values ...S) (res S) { for _, v := range values { if v != nil { return v } } return nil } // UniqChecker allows validating uniqueness of comparable items. // // TODO(a.garipov): The Ordered constraint is only really necessary in Validate. // Consider ways of making this constraint comparable instead. type UniqChecker[T constraints.Ordered] map[T]int64 // Add adds a value to the validator. v must not be nil. func (uc UniqChecker[T]) Add(elems ...T) { for _, e := range elems { uc[e]++ } } // Merge returns a checker containing data from both uc and other. func (uc UniqChecker[T]) Merge(other UniqChecker[T]) (merged UniqChecker[T]) { merged = make(UniqChecker[T], len(uc)+len(other)) for elem, num := range uc { merged[elem] += num } for elem, num := range other { merged[elem] += num } return merged } // Validate returns an error enumerating all elements that aren't unique. func (uc UniqChecker[T]) Validate() (err error) { var dup []T for elem, num := range uc { if num > 1 { dup = append(dup, elem) } } if len(dup) == 0 { return nil } slices.Sort(dup) return fmt.Errorf("duplicated values: %v", dup) } ```
/content/code_sandbox/internal/aghalg/aghalg.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
434
```go package aghalg_test import ( "encoding/json" "testing" "github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNullBool_MarshalJSON(t *testing.T) { testCases := []struct { name string wantErrMsg string want []byte in aghalg.NullBool }{{ name: "null", wantErrMsg: "", want: []byte("null"), in: aghalg.NBNull, }, { name: "true", wantErrMsg: "", want: []byte("true"), in: aghalg.NBTrue, }, { name: "false", wantErrMsg: "", want: []byte("false"), in: aghalg.NBFalse, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got, err := tc.in.MarshalJSON() testutil.AssertErrorMsg(t, tc.wantErrMsg, err) assert.Equal(t, tc.want, got) }) } t.Run("json", func(t *testing.T) { in := &struct { A aghalg.NullBool }{ A: aghalg.NBTrue, } got, err := json.Marshal(in) require.NoError(t, err) assert.Equal(t, []byte(`{"A":true}`), got) }) } func TestNullBool_UnmarshalJSON(t *testing.T) { testCases := []struct { name string wantErrMsg string data []byte want aghalg.NullBool }{{ name: "empty", wantErrMsg: "", data: []byte{}, want: aghalg.NBNull, }, { name: "null", wantErrMsg: "", data: []byte("null"), want: aghalg.NBNull, }, { name: "true", wantErrMsg: "", data: []byte("true"), want: aghalg.NBTrue, }, { name: "false", wantErrMsg: "", data: []byte("false"), want: aghalg.NBFalse, }, { name: "invalid", wantErrMsg: `unmarshalling json data into aghalg.NullBool: bad value "invalid"`, data: []byte("invalid"), want: aghalg.NBNull, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { var got aghalg.NullBool err := got.UnmarshalJSON(tc.data) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) assert.Equal(t, tc.want, got) }) } t.Run("json", func(t *testing.T) { want := aghalg.NBTrue var got struct { A aghalg.NullBool } err := json.Unmarshal([]byte(`{"A":true}`), &got) require.NoError(t, err) assert.Equal(t, want, got.A) }) } ```
/content/code_sandbox/internal/aghalg/nullbool_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
729
```go package aghalg import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestNewSortedMap(t *testing.T) { var m SortedMap[string, int] letters := []string{} for i := range 10 { r := string('a' + rune(i)) letters = append(letters, r) } t.Run("create_and_fill", func(t *testing.T) { m = NewSortedMap[string, int](strings.Compare) nums := []int{} for i, r := range letters { m.Set(r, i) nums = append(nums, i) } gotLetters := []string{} gotNums := []int{} m.Range(func(k string, v int) bool { gotLetters = append(gotLetters, k) gotNums = append(gotNums, v) return true }) assert.Equal(t, letters, gotLetters) assert.Equal(t, nums, gotNums) n, ok := m.Get(letters[0]) assert.True(t, ok) assert.Equal(t, nums[0], n) }) t.Run("clear", func(t *testing.T) { lastLetter := letters[len(letters)-1] m.Del(lastLetter) _, ok := m.Get(lastLetter) assert.False(t, ok) m.Clear() gotLetters := []string{} m.Range(func(k string, _ int) bool { gotLetters = append(gotLetters, k) return true }) assert.Len(t, gotLetters, 0) }) } func TestNewSortedMap_nil(t *testing.T) { const ( key = "key" val = "val" ) var m SortedMap[string, string] assert.Panics(t, func() { m.Set(key, val) }) assert.NotPanics(t, func() { _, ok := m.Get(key) assert.False(t, ok) }) assert.NotPanics(t, func() { m.Range(func(_, _ string) (cont bool) { return true }) }) assert.NotPanics(t, func() { m.Del(key) }) assert.NotPanics(t, func() { m.Clear() }) } ```
/content/code_sandbox/internal/aghalg/sortedmap_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
503
```go package dhcpsvc import ( "net/netip" "strconv" "testing" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewIPRange(t *testing.T) { start4 := netip.MustParseAddr("0.0.0.1") end4 := netip.MustParseAddr("0.0.0.3") start6 := netip.MustParseAddr("1::1") end6 := netip.MustParseAddr("1::3") end6Large := netip.MustParseAddr("2::3") testCases := []struct { start netip.Addr end netip.Addr name string wantErrMsg string }{{ start: start4, end: end4, name: "success_ipv4", wantErrMsg: "", }, { start: start6, end: end6, name: "success_ipv6", wantErrMsg: "", }, { start: end4, end: start4, name: "start_gt_end", wantErrMsg: "invalid ip range: start 0.0.0.3 is greater than or equal to end 0.0.0.1", }, { start: start4, end: start4, name: "start_eq_end", wantErrMsg: "invalid ip range: start 0.0.0.1 is greater than or equal to end 0.0.0.1", }, { start: start6, end: end6Large, name: "too_large", wantErrMsg: "invalid ip range: range length must be within " + strconv.FormatUint(maxRangeLen, 10), }, { start: start4, end: end6, name: "different_family", wantErrMsg: "invalid ip range: 0.0.0.1 and 1::3 must be within the same address family", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { _, err := newIPRange(tc.start, tc.end) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) }) } } func TestIPRange_Contains(t *testing.T) { start, end := netip.MustParseAddr("0.0.0.1"), netip.MustParseAddr("0.0.0.3") r, err := newIPRange(start, end) require.NoError(t, err) testCases := []struct { in netip.Addr want assert.BoolAssertionFunc name string }{{ in: start, want: assert.True, name: "start", }, { in: end, want: assert.True, name: "end", }, { in: start.Next(), want: assert.True, name: "within", }, { in: netip.MustParseAddr("0.0.0.0"), want: assert.False, name: "before", }, { in: netip.MustParseAddr("0.0.0.4"), want: assert.False, name: "after", }, { in: netip.MustParseAddr("::"), want: assert.False, name: "another_family", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { tc.want(t, r.contains(tc.in)) }) } } func TestIPRange_Find(t *testing.T) { start, end := netip.MustParseAddr("0.0.0.1"), netip.MustParseAddr("0.0.0.5") r, err := newIPRange(start, end) require.NoError(t, err) num, ok := r.offset(end) require.True(t, ok) testCases := []struct { predicate ipPredicate want netip.Addr name string }{{ predicate: func(ip netip.Addr) (ok bool) { ipData := ip.AsSlice() return ipData[len(ipData)-1]%2 == 0 }, want: netip.MustParseAddr("0.0.0.2"), name: "even", }, { predicate: func(ip netip.Addr) (ok bool) { ipData := ip.AsSlice() return ipData[len(ipData)-1]%10 == 0 }, want: netip.Addr{}, name: "none", }, { predicate: func(ip netip.Addr) (ok bool) { return true }, want: start, name: "first", }, { predicate: func(ip netip.Addr) (ok bool) { off, _ := r.offset(ip) return off == num }, want: end, name: "last", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got := r.find(tc.predicate) assert.Equal(t, tc.want, got) }) } } func TestIPRange_Offset(t *testing.T) { start, end := netip.MustParseAddr("0.0.0.1"), netip.MustParseAddr("0.0.0.5") r, err := newIPRange(start, end) require.NoError(t, err) testCases := []struct { in netip.Addr name string wantOffset uint64 wantOK bool }{{ in: netip.MustParseAddr("0.0.0.2"), name: "in", wantOffset: 1, wantOK: true, }, { in: start, name: "in_start", wantOffset: 0, wantOK: true, }, { in: end, name: "in_end", wantOffset: 4, wantOK: true, }, { in: netip.MustParseAddr("0.0.0.6"), name: "out_after", wantOffset: 0, wantOK: false, }, { in: netip.MustParseAddr("0.0.0.0"), name: "out_before", wantOffset: 0, wantOK: false, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { offset, ok := r.offset(tc.in) assert.Equal(t, tc.wantOffset, offset) assert.Equal(t, tc.wantOK, ok) }) } } ```
/content/code_sandbox/internal/dhcpsvc/iprange_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,486
```go package dhcpsvc import ( "context" "encoding/json" "fmt" "io/fs" "net" "net/netip" "os" "slices" "strings" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/google/renameio/v2/maybe" ) // dataVersion is the current version of the stored DHCP leases structure. const dataVersion = 1 // databasePerm is the permissions for the database file. const databasePerm fs.FileMode = 0o640 // dataLeases is the structure of the stored DHCP leases. type dataLeases struct { // Leases is the list containing stored DHCP leases. Leases []*dbLease `json:"leases"` // Version is the current version of the structure. Version int `json:"version"` } // dbLease is the structure of stored lease. type dbLease struct { Expiry string `json:"expires"` IP netip.Addr `json:"ip"` Hostname string `json:"hostname"` HWAddr string `json:"mac"` IsStatic bool `json:"static"` } // compareNames returns the result of comparing the hostnames of dl and other // lexicographically. func (dl *dbLease) compareNames(other *dbLease) (res int) { return strings.Compare(dl.Hostname, other.Hostname) } // toDBLease converts *Lease to *dbLease. func toDBLease(l *Lease) (dl *dbLease) { var expiryStr string if !l.IsStatic { // The front-end is waiting for RFC 3999 format of the time value. It // also shouldn't got an Expiry field for static leases. // // See path_to_url expiryStr = l.Expiry.Format(time.RFC3339) } return &dbLease{ Expiry: expiryStr, Hostname: l.Hostname, HWAddr: l.HWAddr.String(), IP: l.IP, IsStatic: l.IsStatic, } } // toInternal converts dl to *Lease. func (dl *dbLease) toInternal() (l *Lease, err error) { mac, err := net.ParseMAC(dl.HWAddr) if err != nil { return nil, fmt.Errorf("parsing hardware address: %w", err) } expiry := time.Time{} if !dl.IsStatic { expiry, err = time.Parse(time.RFC3339, dl.Expiry) if err != nil { return nil, fmt.Errorf("parsing expiry time: %w", err) } } return &Lease{ Expiry: expiry, IP: dl.IP, Hostname: dl.Hostname, HWAddr: mac, IsStatic: dl.IsStatic, }, nil } // dbLoad loads stored leases. It must only be called before the service has // been started. func (srv *DHCPServer) dbLoad(ctx context.Context) (err error) { defer func() { err = errors.Annotate(err, "loading db: %w") }() file, err := os.Open(srv.dbFilePath) if err != nil { if !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("reading db: %w", err) } srv.logger.DebugContext(ctx, "no db file found") return nil } defer func() { err = errors.WithDeferred(err, file.Close()) }() dl := &dataLeases{} err = json.NewDecoder(file).Decode(dl) if err != nil { return fmt.Errorf("decoding db: %w", err) } srv.resetLeases() srv.addDBLeases(ctx, dl.Leases) return nil } // addDBLeases adds leases to the server. func (srv *DHCPServer) addDBLeases(ctx context.Context, leases []*dbLease) { var v4, v6 uint for i, l := range leases { lease, err := l.toInternal() if err != nil { srv.logger.WarnContext(ctx, "converting lease", "idx", i, slogutil.KeyError, err) continue } iface, err := srv.ifaceForAddr(l.IP) if err != nil { srv.logger.WarnContext(ctx, "searching lease iface", "idx", i, slogutil.KeyError, err) continue } err = srv.leases.add(lease, iface) if err != nil { srv.logger.WarnContext(ctx, "adding lease", "idx", i, slogutil.KeyError, err) continue } if l.IP.Is4() { v4++ } else { v6++ } } // TODO(e.burkov): Group by interface. srv.logger.InfoContext(ctx, "loaded leases", "v4", v4, "v6", v6, "total", len(leases)) } // writeDB writes leases to the database file. It expects the // [DHCPServer.leasesMu] to be locked. func (srv *DHCPServer) dbStore(ctx context.Context) (err error) { defer func() { err = errors.Annotate(err, "writing db: %w") }() dl := &dataLeases{ // Avoid writing null into the database file if there are no leases. Leases: make([]*dbLease, 0, srv.leases.len()), Version: dataVersion, } srv.leases.rangeLeases(func(l *Lease) (cont bool) { lease := toDBLease(l) i, _ := slices.BinarySearchFunc(dl.Leases, lease, (*dbLease).compareNames) dl.Leases = slices.Insert(dl.Leases, i, lease) return true }) buf, err := json.Marshal(dl) if err != nil { // Don't wrap the error since it's informative enough as is. return err } err = maybe.WriteFile(srv.dbFilePath, buf, databasePerm) if err != nil { // Don't wrap the error since it's informative enough as is. return err } srv.logger.InfoContext(ctx, "stored leases", "num", len(dl.Leases), "file", srv.dbFilePath) return nil } ```
/content/code_sandbox/internal/dhcpsvc/db.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,432
```go package dhcpsvc import ( "net" "net/netip" "slices" "time" ) // Lease is a DHCP lease. // // TODO(e.burkov): Consider moving it to [agh], since it also may be needed in // [websvc]. // // TODO(e.burkov): Add validation method. type Lease struct { // IP is the IP address leased to the client. IP netip.Addr // Expiry is the expiration time of the lease. Expiry time.Time // Hostname of the client. Hostname string // HWAddr is the physical hardware address (MAC address). HWAddr net.HardwareAddr // IsStatic defines if the lease is static. IsStatic bool } // Clone returns a deep copy of l. func (l *Lease) Clone() (clone *Lease) { if l == nil { return nil } return &Lease{ Expiry: l.Expiry, Hostname: l.Hostname, HWAddr: slices.Clone(l.HWAddr), IP: l.IP, IsStatic: l.IsStatic, } } ```
/content/code_sandbox/internal/dhcpsvc/lease.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
255
```go package dhcpsvc // DatabasePerm is the permissions for the test database file. const DatabasePerm = databasePerm ```
/content/code_sandbox/internal/dhcpsvc/db_internal_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
25
```go package dhcpsvc import ( "encoding/binary" "fmt" "math" "math/big" "net/netip" "github.com/AdguardTeam/golibs/errors" ) // ipRange is an inclusive range of IP addresses. A zero range doesn't contain // any IP addresses. // // It is safe for concurrent use. type ipRange struct { start netip.Addr end netip.Addr } // maxRangeLen is the maximum IP range length. The bitsets used in servers only // accept uints, which can have the size of 32 bit. // // TODO(a.garipov, e.burkov): Reconsider the value for IPv6. const maxRangeLen = math.MaxUint32 // newIPRange creates a new IP address range. start must be less than end. The // resulting range must not be greater than maxRangeLen. func newIPRange(start, end netip.Addr) (r ipRange, err error) { defer func() { err = errors.Annotate(err, "invalid ip range: %w") }() switch false { case start.Is4() == end.Is4(): return ipRange{}, fmt.Errorf("%s and %s must be within the same address family", start, end) case start.Less(end): return ipRange{}, fmt.Errorf("start %s is greater than or equal to end %s", start, end) default: diff := (&big.Int{}).Sub( (&big.Int{}).SetBytes(end.AsSlice()), (&big.Int{}).SetBytes(start.AsSlice()), ) if !diff.IsUint64() || diff.Uint64() > maxRangeLen { return ipRange{}, fmt.Errorf("range length must be within %d", uint32(maxRangeLen)) } } return ipRange{ start: start, end: end, }, nil } // contains returns true if r contains ip. func (r ipRange) contains(ip netip.Addr) (ok bool) { // Assume that the end was checked to be within the same address family as // the start during construction. return r.start.Is4() == ip.Is4() && !ip.Less(r.start) && !r.end.Less(ip) } // ipPredicate is a function that is called on every IP address in // [ipRange.find]. type ipPredicate func(ip netip.Addr) (ok bool) // find finds the first IP address in r for which p returns true. It returns an // empty [netip.Addr] if there are no addresses that satisfy p. // // TODO(e.burkov): Use. func (r ipRange) find(p ipPredicate) (ip netip.Addr) { for ip = r.start; !r.end.Less(ip); ip = ip.Next() { if p(ip) { return ip } } return netip.Addr{} } // offset returns the offset of ip from the beginning of r. It returns 0 and // false if ip is not in r. func (r ipRange) offset(ip netip.Addr) (offset uint64, ok bool) { if !r.contains(ip) { return 0, false } startData, ipData := r.start.As16(), ip.As16() be := binary.BigEndian // Assume that the range length was checked against maxRangeLen during // construction. return be.Uint64(ipData[8:]) - be.Uint64(startData[8:]), true } // String implements the fmt.Stringer interface for *ipRange. func (r ipRange) String() (s string) { return fmt.Sprintf("%s-%s", r.start, r.end) } ```
/content/code_sandbox/internal/dhcpsvc/iprange.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
795
```go package dhcpsvc import ( "fmt" "github.com/AdguardTeam/golibs/errors" ) const ( // errNilConfig is returned when a nil config met. errNilConfig errors.Error = "config is nil" // errNoInterfaces is returned when no interfaces found in configuration. errNoInterfaces errors.Error = "no interfaces specified" ) // newMustErr returns an error that indicates that valName must be as must // describes. func newMustErr(valName, must string, val fmt.Stringer) (err error) { return fmt.Errorf("%s %s must %s", valName, val, must) } ```
/content/code_sandbox/internal/dhcpsvc/errors.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
135
```go package dhcpsvc import ( "context" "fmt" "log/slog" "net/netip" "slices" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/netutil" "github.com/google/gopacket/layers" ) // IPv6Config is the interface-specific configuration for DHCPv6. type IPv6Config struct { // RangeStart is the first address in the range to assign to DHCP clients. RangeStart netip.Addr // Options is the list of DHCP options to send to DHCP clients. The options // with zero length are treated as deletions of the corresponding options, // either implicit or explicit. Options layers.DHCPv6Options // LeaseDuration is the TTL of a DHCP lease. LeaseDuration time.Duration // RASlaacOnly defines whether the DHCP clients should only use SLAAC for // address assignment. RASLAACOnly bool // RAAllowSlaac defines whether the DHCP clients may use SLAAC for address // assignment. RAAllowSLAAC bool // Enabled is the state of the DHCPv6 service, whether it is enabled or not // on the specific interface. Enabled bool } // validate returns an error in conf if any. func (c *IPv6Config) validate() (err error) { if c == nil { return errNilConfig } else if !c.Enabled { return nil } var errs []error if !c.RangeStart.Is6() { err = fmt.Errorf("range start %s should be a valid ipv6", c.RangeStart) errs = append(errs, err) } if c.LeaseDuration <= 0 { err = fmt.Errorf("lease duration %s must be positive", c.LeaseDuration) errs = append(errs, err) } return errors.Join(errs...) } // dhcpInterfaceV6 is a DHCP interface for IPv6 address family. type dhcpInterfaceV6 struct { // common is the common part of any network interface within the DHCP // server. common *netInterface // rangeStart is the first IP address in the range. rangeStart netip.Addr // implicitOpts are the DHCPv6 options listed in RFC 8415 (and others) and // initialized with default values. It must not have intersections with // explicitOpts. implicitOpts layers.DHCPv6Options // explicitOpts are the user-configured options. It must not have // intersections with implicitOpts. explicitOpts layers.DHCPv6Options // raSLAACOnly defines if DHCP should send ICMPv6.RA packets without MO // flags. raSLAACOnly bool // raAllowSLAAC defines if DHCP should send ICMPv6.RA packets with MO flags. raAllowSLAAC bool } // newDHCPInterfaceV6 creates a new DHCP interface for IPv6 address family with // the given configuration. // // TODO(e.burkov): Validate properly. func newDHCPInterfaceV6( ctx context.Context, l *slog.Logger, name string, conf *IPv6Config, ) (i *dhcpInterfaceV6) { l = l.With(keyInterface, name, keyFamily, netutil.AddrFamilyIPv6) if !conf.Enabled { l.DebugContext(ctx, "disabled") return nil } i = &dhcpInterfaceV6{ rangeStart: conf.RangeStart, common: newNetInterface(name, l, conf.LeaseDuration), raSLAACOnly: conf.RASLAACOnly, raAllowSLAAC: conf.RAAllowSLAAC, } i.implicitOpts, i.explicitOpts = conf.options(ctx, l) return i } // dhcpInterfacesV6 is a slice of network interfaces of IPv6 address family. type dhcpInterfacesV6 []*dhcpInterfaceV6 // find returns the first network interface within ifaces containing ip. It // returns false if there is no such interface. func (ifaces dhcpInterfacesV6) find(ip netip.Addr) (iface6 *netInterface, ok bool) { // prefLen is the length of prefix to match ip against. // // TODO(e.burkov): DHCPv6 inherits the weird behavior of legacy // implementation where the allocated range constrained by the first address // and the first address with last byte set to 0xff. Proper prefixes should // be used instead. const prefLen = netutil.IPv6BitLen - 8 i := slices.IndexFunc(ifaces, func(iface *dhcpInterfaceV6) (contains bool) { return !ip.Less(iface.rangeStart) && netip.PrefixFrom(iface.rangeStart, prefLen).Contains(ip) }) if i < 0 { return nil, false } return ifaces[i].common, true } // options returns the implicit and explicit options for the interface. The two // lists are disjoint and the implicit options are initialized with default // values. // // TODO(e.burkov): Add implicit options according to RFC. func (c *IPv6Config) options(ctx context.Context, l *slog.Logger) (imp, exp layers.DHCPv6Options) { // Set default values of host configuration parameters listed in RFC 8415. imp = layers.DHCPv6Options{} slices.SortFunc(imp, compareV6OptionCodes) // Set values for explicitly configured options. for _, e := range c.Options { i, found := slices.BinarySearchFunc(imp, e, compareV6OptionCodes) if found { imp = slices.Delete(imp, i, i+1) } exp = append(exp, e) } l.DebugContext(ctx, "options", "implicit", imp, "explicit", exp) return imp, exp } // compareV6OptionCodes compares option codes of a and b. func compareV6OptionCodes(a, b layers.DHCPv6Option) (res int) { return int(a.Code) - int(b.Code) } ```
/content/code_sandbox/internal/dhcpsvc/v6.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,332
```go package dhcpsvc_test import ( "io/fs" "net/netip" "os" "path" "path/filepath" "strings" "testing" "time" "github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc" "github.com/AdguardTeam/golibs/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // testdata is a filesystem containing data for tests. var testdata = os.DirFS("testdata") // newTempDB copies the leases database file located in the testdata FS, under // tb.Name()/leases.json, to a temporary directory and returns the path to the // copied file. func newTempDB(tb testing.TB) (dst string) { tb.Helper() const filename = "leases.json" data, err := fs.ReadFile(testdata, path.Join(tb.Name(), filename)) require.NoError(tb, err) dst = filepath.Join(tb.TempDir(), filename) err = os.WriteFile(dst, data, dhcpsvc.DatabasePerm) require.NoError(tb, err) return dst } func TestNew(t *testing.T) { validIPv4Conf := &dhcpsvc.IPv4Config{ Enabled: true, GatewayIP: netip.MustParseAddr("192.168.0.1"), SubnetMask: netip.MustParseAddr("255.255.255.0"), RangeStart: netip.MustParseAddr("192.168.0.2"), RangeEnd: netip.MustParseAddr("192.168.0.254"), LeaseDuration: 1 * time.Hour, } gwInRangeConf := &dhcpsvc.IPv4Config{ Enabled: true, GatewayIP: netip.MustParseAddr("192.168.0.100"), SubnetMask: netip.MustParseAddr("255.255.255.0"), RangeStart: netip.MustParseAddr("192.168.0.1"), RangeEnd: netip.MustParseAddr("192.168.0.254"), LeaseDuration: 1 * time.Hour, } badStartConf := &dhcpsvc.IPv4Config{ Enabled: true, GatewayIP: netip.MustParseAddr("192.168.0.1"), SubnetMask: netip.MustParseAddr("255.255.255.0"), RangeStart: netip.MustParseAddr("127.0.0.1"), RangeEnd: netip.MustParseAddr("192.168.0.254"), LeaseDuration: 1 * time.Hour, } validIPv6Conf := &dhcpsvc.IPv6Config{ Enabled: true, RangeStart: netip.MustParseAddr("2001:db8::1"), LeaseDuration: 1 * time.Hour, RAAllowSLAAC: true, RASLAACOnly: true, } leasesPath := filepath.Join(t.TempDir(), "leases.json") testCases := []struct { conf *dhcpsvc.Config name string wantErrMsg string }{{ conf: &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: map[string]*dhcpsvc.InterfaceConfig{ "eth0": { IPv4: validIPv4Conf, IPv6: validIPv6Conf, }, }, DBFilePath: leasesPath, }, name: "valid", wantErrMsg: "", }, { conf: &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: map[string]*dhcpsvc.InterfaceConfig{ "eth0": { IPv4: &dhcpsvc.IPv4Config{Enabled: false}, IPv6: &dhcpsvc.IPv6Config{Enabled: false}, }, }, DBFilePath: leasesPath, }, name: "disabled_interfaces", wantErrMsg: "", }, { conf: &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: map[string]*dhcpsvc.InterfaceConfig{ "eth0": { IPv4: gwInRangeConf, IPv6: validIPv6Conf, }, }, DBFilePath: leasesPath, }, name: "gateway_within_range", wantErrMsg: `creating interfaces: interface "eth0": ipv4: ` + `gateway ip 192.168.0.100 in the ip range 192.168.0.1-192.168.0.254`, }, { conf: &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: map[string]*dhcpsvc.InterfaceConfig{ "eth0": { IPv4: badStartConf, IPv6: validIPv6Conf, }, }, DBFilePath: leasesPath, }, name: "bad_start", wantErrMsg: `creating interfaces: interface "eth0": ipv4: ` + `range start 127.0.0.1 is not within 192.168.0.1/24`, }} ctx := testutil.ContextWithTimeout(t, testTimeout) for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { _, err := dhcpsvc.New(ctx, tc.conf) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) }) } } func TestDHCPServer_AddLease(t *testing.T) { ctx := testutil.ContextWithTimeout(t, testTimeout) leasesPath := filepath.Join(t.TempDir(), "leases.json") srv, err := dhcpsvc.New(ctx, &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, }) require.NoError(t, err) const ( existHost = "host1" newHost = "host2" ipv6Host = "host3" ) var ( existIP = netip.MustParseAddr("192.168.0.2") newIP = netip.MustParseAddr("192.168.0.3") newIPv6 = netip.MustParseAddr("2001:db8::2") existMAC = mustParseMAC(t, "01:02:03:04:05:06") newMAC = mustParseMAC(t, "06:05:04:03:02:01") ipv6MAC = mustParseMAC(t, "02:03:04:05:06:07") ) require.NoError(t, srv.AddLease(ctx, &dhcpsvc.Lease{ Hostname: existHost, IP: existIP, HWAddr: existMAC, IsStatic: true, })) testCases := []struct { name string lease *dhcpsvc.Lease wantErrMsg string }{{ name: "outside_range", lease: &dhcpsvc.Lease{ Hostname: newHost, IP: netip.MustParseAddr("1.2.3.4"), HWAddr: newMAC, }, wantErrMsg: "adding lease: no interface for ip 1.2.3.4", }, { name: "duplicate_ip", lease: &dhcpsvc.Lease{ Hostname: newHost, IP: existIP, HWAddr: newMAC, }, wantErrMsg: "adding lease: lease for ip " + existIP.String() + " already exists", }, { name: "duplicate_hostname", lease: &dhcpsvc.Lease{ Hostname: existHost, IP: newIP, HWAddr: newMAC, }, wantErrMsg: "adding lease: lease for hostname " + existHost + " already exists", }, { name: "duplicate_hostname_case", lease: &dhcpsvc.Lease{ Hostname: strings.ToUpper(existHost), IP: newIP, HWAddr: newMAC, }, wantErrMsg: "adding lease: lease for hostname " + strings.ToUpper(existHost) + " already exists", }, { name: "duplicate_mac", lease: &dhcpsvc.Lease{ Hostname: newHost, IP: newIP, HWAddr: existMAC, }, wantErrMsg: "adding lease: lease for mac " + existMAC.String() + " already exists", }, { name: "valid", lease: &dhcpsvc.Lease{ Hostname: newHost, IP: newIP, HWAddr: newMAC, }, wantErrMsg: "", }, { name: "valid_v6", lease: &dhcpsvc.Lease{ Hostname: ipv6Host, IP: newIPv6, HWAddr: ipv6MAC, }, wantErrMsg: "", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { testutil.AssertErrorMsg(t, tc.wantErrMsg, srv.AddLease(ctx, tc.lease)) }) } assert.NotEmpty(t, srv.Leases()) assert.FileExists(t, leasesPath) } func TestDHCPServer_index(t *testing.T) { ctx := testutil.ContextWithTimeout(t, testTimeout) leasesPath := newTempDB(t) srv, err := dhcpsvc.New(ctx, &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, }) require.NoError(t, err) const ( host1 = "host1" host2 = "host2" host3 = "host3" host4 = "host4" host5 = "host5" ) var ( ip1 = netip.MustParseAddr("192.168.0.2") ip2 = netip.MustParseAddr("192.168.0.3") ip3 = netip.MustParseAddr("172.16.0.3") ip4 = netip.MustParseAddr("172.16.0.4") mac1 = mustParseMAC(t, "01:02:03:04:05:06") mac2 = mustParseMAC(t, "06:05:04:03:02:01") mac3 = mustParseMAC(t, "02:03:04:05:06:07") ) t.Run("ip_idx", func(t *testing.T) { assert.Equal(t, ip1, srv.IPByHost(host1)) assert.Equal(t, ip2, srv.IPByHost(host2)) assert.Equal(t, ip3, srv.IPByHost(host3)) assert.Equal(t, ip4, srv.IPByHost(host4)) assert.Zero(t, srv.IPByHost(host5)) }) t.Run("name_idx", func(t *testing.T) { assert.Equal(t, host1, srv.HostByIP(ip1)) assert.Equal(t, host2, srv.HostByIP(ip2)) assert.Equal(t, host3, srv.HostByIP(ip3)) assert.Equal(t, host4, srv.HostByIP(ip4)) assert.Zero(t, srv.HostByIP(netip.Addr{})) }) t.Run("mac_idx", func(t *testing.T) { assert.Equal(t, mac1, srv.MACByIP(ip1)) assert.Equal(t, mac2, srv.MACByIP(ip2)) assert.Equal(t, mac3, srv.MACByIP(ip3)) assert.Equal(t, mac1, srv.MACByIP(ip4)) assert.Zero(t, srv.MACByIP(netip.Addr{})) }) } func TestDHCPServer_UpdateStaticLease(t *testing.T) { ctx := testutil.ContextWithTimeout(t, testTimeout) leasesPath := newTempDB(t) srv, err := dhcpsvc.New(ctx, &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, }) require.NoError(t, err) const ( host1 = "host1" host2 = "host2" host3 = "host3" host4 = "host4" host5 = "host5" host6 = "host6" ) var ( ip1 = netip.MustParseAddr("192.168.0.2") ip2 = netip.MustParseAddr("192.168.0.3") ip3 = netip.MustParseAddr("192.168.0.4") ip4 = netip.MustParseAddr("2001:db8::3") mac1 = mustParseMAC(t, "01:02:03:04:05:06") mac2 = mustParseMAC(t, "06:05:04:03:02:01") mac3 = mustParseMAC(t, "06:05:04:03:02:02") ) testCases := []struct { name string lease *dhcpsvc.Lease wantErrMsg string }{{ name: "outside_range", lease: &dhcpsvc.Lease{ Hostname: host1, IP: netip.MustParseAddr("1.2.3.4"), HWAddr: mac1, }, wantErrMsg: "updating static lease: no interface for ip 1.2.3.4", }, { name: "not_found", lease: &dhcpsvc.Lease{ Hostname: host3, IP: ip3, HWAddr: mac2, }, wantErrMsg: "updating static lease: no lease for mac " + mac2.String(), }, { name: "duplicate_ip", lease: &dhcpsvc.Lease{ Hostname: host1, IP: ip2, HWAddr: mac1, }, wantErrMsg: "updating static lease: lease for ip " + ip2.String() + " already exists", }, { name: "duplicate_hostname", lease: &dhcpsvc.Lease{ Hostname: host2, IP: ip1, HWAddr: mac1, }, wantErrMsg: "updating static lease: lease for hostname " + host2 + " already exists", }, { name: "duplicate_hostname_case", lease: &dhcpsvc.Lease{ Hostname: strings.ToUpper(host2), IP: ip1, HWAddr: mac1, }, wantErrMsg: "updating static lease: lease for hostname " + strings.ToUpper(host2) + " already exists", }, { name: "valid", lease: &dhcpsvc.Lease{ Hostname: host3, IP: ip3, HWAddr: mac1, }, wantErrMsg: "", }, { name: "valid_v6", lease: &dhcpsvc.Lease{ Hostname: host6, IP: ip4, HWAddr: mac3, }, wantErrMsg: "", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { testutil.AssertErrorMsg(t, tc.wantErrMsg, srv.UpdateStaticLease(ctx, tc.lease)) }) } assert.FileExists(t, leasesPath) } func TestDHCPServer_RemoveLease(t *testing.T) { ctx := testutil.ContextWithTimeout(t, testTimeout) leasesPath := newTempDB(t) srv, err := dhcpsvc.New(ctx, &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, }) require.NoError(t, err) const ( host1 = "host1" host2 = "host2" host3 = "host3" ) var ( existIP = netip.MustParseAddr("192.168.0.2") newIP = netip.MustParseAddr("192.168.0.3") newIPv6 = netip.MustParseAddr("2001:db8::2") existMAC = mustParseMAC(t, "01:02:03:04:05:06") newMAC = mustParseMAC(t, "02:03:04:05:06:07") ipv6MAC = mustParseMAC(t, "06:05:04:03:02:01") ) testCases := []struct { name string lease *dhcpsvc.Lease wantErrMsg string }{{ name: "not_found_mac", lease: &dhcpsvc.Lease{ Hostname: host1, IP: existIP, HWAddr: newMAC, }, wantErrMsg: "removing lease: no lease for mac " + newMAC.String(), }, { name: "not_found_ip", lease: &dhcpsvc.Lease{ Hostname: host1, IP: newIP, HWAddr: existMAC, }, wantErrMsg: "removing lease: no lease for ip " + newIP.String(), }, { name: "not_found_host", lease: &dhcpsvc.Lease{ Hostname: host2, IP: existIP, HWAddr: existMAC, }, wantErrMsg: "removing lease: no lease for hostname " + host2, }, { name: "valid", lease: &dhcpsvc.Lease{ Hostname: host1, IP: existIP, HWAddr: existMAC, }, wantErrMsg: "", }, { name: "valid_v6", lease: &dhcpsvc.Lease{ Hostname: host3, IP: newIPv6, HWAddr: ipv6MAC, }, wantErrMsg: "", }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { testutil.AssertErrorMsg(t, tc.wantErrMsg, srv.RemoveLease(ctx, tc.lease)) }) } assert.FileExists(t, leasesPath) assert.Empty(t, srv.Leases()) } func TestDHCPServer_Reset(t *testing.T) { leasesPath := newTempDB(t) conf := &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, } ctx := testutil.ContextWithTimeout(t, testTimeout) srv, err := dhcpsvc.New(ctx, conf) require.NoError(t, err) const leasesNum = 4 require.Len(t, srv.Leases(), leasesNum) require.NoError(t, srv.Reset(ctx)) assert.FileExists(t, leasesPath) assert.Empty(t, srv.Leases()) } func TestServer_Leases(t *testing.T) { leasesPath := newTempDB(t) conf := &dhcpsvc.Config{ Enabled: true, Logger: discardLog, LocalDomainName: testLocalTLD, Interfaces: testInterfaceConf, DBFilePath: leasesPath, } ctx := testutil.ContextWithTimeout(t, testTimeout) srv, err := dhcpsvc.New(ctx, conf) require.NoError(t, err) expiry, err := time.Parse(time.RFC3339, "2042-01-02T03:04:05Z") require.NoError(t, err) wantLeases := []*dhcpsvc.Lease{{ Expiry: expiry, IP: netip.MustParseAddr("192.168.0.3"), Hostname: "example.host", HWAddr: mustParseMAC(t, "AA:AA:AA:AA:AA:AA"), IsStatic: false, }, { Expiry: time.Time{}, IP: netip.MustParseAddr("192.168.0.4"), Hostname: "example.static.host", HWAddr: mustParseMAC(t, "BB:BB:BB:BB:BB:BB"), IsStatic: true, }} assert.ElementsMatch(t, wantLeases, srv.Leases()) } ```
/content/code_sandbox/internal/dhcpsvc/server_test.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
4,716
```go package dhcpsvc import ( "fmt" "net/netip" "slices" "strings" ) // leaseIndex is the set of leases indexed by their identifiers for quick // lookup. type leaseIndex struct { // byAddr is a lookup shortcut for leases by their IP addresses. byAddr map[netip.Addr]*Lease // byName is a lookup shortcut for leases by their hostnames. // // TODO(e.burkov): Use a slice of leases with the same hostname? byName map[string]*Lease } // newLeaseIndex returns a new index for [Lease]s. func newLeaseIndex() *leaseIndex { return &leaseIndex{ byAddr: map[netip.Addr]*Lease{}, byName: map[string]*Lease{}, } } // leaseByAddr returns a lease by its IP address. func (idx *leaseIndex) leaseByAddr(addr netip.Addr) (l *Lease, ok bool) { l, ok = idx.byAddr[addr] return l, ok } // leaseByName returns a lease by its hostname. func (idx *leaseIndex) leaseByName(name string) (l *Lease, ok bool) { // TODO(e.burkov): Probably, use a case-insensitive comparison and store in // slice. This would require a benchmark. l, ok = idx.byName[strings.ToLower(name)] return l, ok } // clear removes all leases from idx. func (idx *leaseIndex) clear() { clear(idx.byAddr) clear(idx.byName) } // add adds l into idx and into iface. l must be valid, iface should be // responsible for l's IP. It returns an error if l duplicates at least a // single value of another lease. func (idx *leaseIndex) add(l *Lease, iface *netInterface) (err error) { loweredName := strings.ToLower(l.Hostname) if _, ok := idx.byAddr[l.IP]; ok { return fmt.Errorf("lease for ip %s already exists", l.IP) } else if _, ok = idx.byName[loweredName]; ok { return fmt.Errorf("lease for hostname %s already exists", l.Hostname) } err = iface.addLease(l) if err != nil { return err } idx.byAddr[l.IP] = l idx.byName[loweredName] = l return nil } // remove removes l from idx and from iface. l must be valid, iface should // contain the same lease or the lease itself. It returns an error if the lease // not found. func (idx *leaseIndex) remove(l *Lease, iface *netInterface) (err error) { loweredName := strings.ToLower(l.Hostname) if _, ok := idx.byAddr[l.IP]; !ok { return fmt.Errorf("no lease for ip %s", l.IP) } else if _, ok = idx.byName[loweredName]; !ok { return fmt.Errorf("no lease for hostname %s", l.Hostname) } err = iface.removeLease(l) if err != nil { return err } delete(idx.byAddr, l.IP) delete(idx.byName, loweredName) return nil } // update updates l in idx and in iface. l must be valid, iface should be // responsible for l's IP. It returns an error if l duplicates at least a // single value of another lease, except for the updated lease itself. func (idx *leaseIndex) update(l *Lease, iface *netInterface) (err error) { loweredName := strings.ToLower(l.Hostname) existing, ok := idx.byAddr[l.IP] if ok && !slices.Equal(l.HWAddr, existing.HWAddr) { return fmt.Errorf("lease for ip %s already exists", l.IP) } existing, ok = idx.byName[loweredName] if ok && !slices.Equal(l.HWAddr, existing.HWAddr) { return fmt.Errorf("lease for hostname %s already exists", l.Hostname) } prev, err := iface.updateLease(l) if err != nil { return err } delete(idx.byAddr, prev.IP) delete(idx.byName, strings.ToLower(prev.Hostname)) idx.byAddr[l.IP] = l idx.byName[loweredName] = l return nil } // rangeLeases calls f for each lease in idx in an unspecified order until f // returns false. func (idx *leaseIndex) rangeLeases(f func(l *Lease) (cont bool)) { for _, l := range idx.byName { if !f(l) { break } } } // len returns the number of leases in idx. func (idx *leaseIndex) len() (l uint) { return uint(len(idx.byAddr)) } ```
/content/code_sandbox/internal/dhcpsvc/leaseindex.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
1,055
```go package dhcpsvc import ( "context" "fmt" "log/slog" "net" "net/netip" "slices" "time" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/netutil" "github.com/google/gopacket/layers" ) // IPv4Config is the interface-specific configuration for DHCPv4. type IPv4Config struct { // GatewayIP is the IPv4 address of the network's gateway. It is used as // the default gateway for DHCP clients and also used in calculating the // network-specific broadcast address. GatewayIP netip.Addr // SubnetMask is the IPv4 subnet mask of the network. It should be a valid // IPv4 CIDR (i.e. all 1s followed by all 0s). SubnetMask netip.Addr // RangeStart is the first address in the range to assign to DHCP clients. RangeStart netip.Addr // RangeEnd is the last address in the range to assign to DHCP clients. RangeEnd netip.Addr // Options is the list of DHCP options to send to DHCP clients. The options // having a zero value within the Length field are treated as deletions of // the corresponding options, either implicit or explicit. Options layers.DHCPOptions // LeaseDuration is the TTL of a DHCP lease. LeaseDuration time.Duration // Enabled is the state of the DHCPv4 service, whether it is enabled or not // on the specific interface. Enabled bool } // validate returns an error in conf if any. func (c *IPv4Config) validate() (err error) { if c == nil { return errNilConfig } else if !c.Enabled { return nil } var errs []error if !c.GatewayIP.Is4() { err = newMustErr("gateway ip", "be a valid ipv4", c.GatewayIP) errs = append(errs, err) } if !c.SubnetMask.Is4() { err = newMustErr("subnet mask", "be a valid ipv4 cidr mask", c.SubnetMask) errs = append(errs, err) } if !c.RangeStart.Is4() { err = newMustErr("range start", "be a valid ipv4", c.RangeStart) errs = append(errs, err) } if !c.RangeEnd.Is4() { err = newMustErr("range end", "be a valid ipv4", c.RangeEnd) errs = append(errs, err) } if c.LeaseDuration <= 0 { err = newMustErr("icmp timeout", "be positive", c.LeaseDuration) errs = append(errs, err) } return errors.Join(errs...) } // dhcpInterfaceV4 is a DHCP interface for IPv4 address family. type dhcpInterfaceV4 struct { // common is the common part of any network interface within the DHCP // server. common *netInterface // gateway is the IP address of the network gateway. gateway netip.Addr // subnet is the network subnet. subnet netip.Prefix // addrSpace is the IPv4 address space allocated for leasing. addrSpace ipRange // implicitOpts are the options listed in Appendix A of RFC 2131 and // initialized with default values. It must not have intersections with // explicitOpts. implicitOpts layers.DHCPOptions // explicitOpts are the user-configured options. It must not have // intersections with implicitOpts. explicitOpts layers.DHCPOptions } // newDHCPInterfaceV4 creates a new DHCP interface for IPv4 address family with // the given configuration. It returns an error if the given configuration // can't be used. func newDHCPInterfaceV4( ctx context.Context, l *slog.Logger, name string, conf *IPv4Config, ) (i *dhcpInterfaceV4, err error) { l = l.With( keyInterface, name, keyFamily, netutil.AddrFamilyIPv4, ) if !conf.Enabled { l.DebugContext(ctx, "disabled") return nil, nil } maskLen, _ := net.IPMask(conf.SubnetMask.AsSlice()).Size() subnet := netip.PrefixFrom(conf.GatewayIP, maskLen) switch { case !subnet.Contains(conf.RangeStart): return nil, fmt.Errorf("range start %s is not within %s", conf.RangeStart, subnet) case !subnet.Contains(conf.RangeEnd): return nil, fmt.Errorf("range end %s is not within %s", conf.RangeEnd, subnet) } addrSpace, err := newIPRange(conf.RangeStart, conf.RangeEnd) if err != nil { return nil, err } else if addrSpace.contains(conf.GatewayIP) { return nil, fmt.Errorf("gateway ip %s in the ip range %s", conf.GatewayIP, addrSpace) } i = &dhcpInterfaceV4{ gateway: conf.GatewayIP, subnet: subnet, addrSpace: addrSpace, common: newNetInterface(name, l, conf.LeaseDuration), } i.implicitOpts, i.explicitOpts = conf.options(ctx, l) return i, nil } // dhcpInterfacesV4 is a slice of network interfaces of IPv4 address family. type dhcpInterfacesV4 []*dhcpInterfaceV4 // find returns the first network interface within ifaces containing ip. It // returns false if there is no such interface. func (ifaces dhcpInterfacesV4) find(ip netip.Addr) (iface4 *netInterface, ok bool) { i := slices.IndexFunc(ifaces, func(iface *dhcpInterfaceV4) (contains bool) { return iface.subnet.Contains(ip) }) if i < 0 { return nil, false } return ifaces[i].common, true } // options returns the implicit and explicit options for the interface. The two // lists are disjoint and the implicit options are initialized with default // values. // // TODO(e.burkov): DRY with the IPv6 version. func (c *IPv4Config) options(ctx context.Context, l *slog.Logger) (imp, exp layers.DHCPOptions) { // Set default values of host configuration parameters listed in Appendix A // of RFC-2131. imp = layers.DHCPOptions{ // Values From Configuration layers.NewDHCPOption(layers.DHCPOptSubnetMask, c.SubnetMask.AsSlice()), layers.NewDHCPOption(layers.DHCPOptRouter, c.GatewayIP.AsSlice()), // IP-Layer Per Host // An Internet host that includes embedded gateway code MUST have a // configuration switch to disable the gateway function, and this switch // MUST default to the non-gateway mode. // // See path_to_url#section-3.3.5. layers.NewDHCPOption(layers.DHCPOptIPForwarding, []byte{0x0}), // A host that supports non-local source-routing MUST have a // configurable switch to disable forwarding, and this switch MUST // default to disabled. // // See path_to_url#section-3.3.5. layers.NewDHCPOption(layers.DHCPOptSourceRouting, []byte{0x0}), // Do not set the Policy Filter Option since it only makes sense when // the non-local source routing is enabled. // The minimum legal value is 576. // // See path_to_url#section-4.4. layers.NewDHCPOption(layers.DHCPOptDatagramMTU, []byte{0x2, 0x40}), // Set the current recommended default time to live for the Internet // Protocol which is 64. // // See path_to_url#ip-parameters-2. layers.NewDHCPOption(layers.DHCPOptDefaultTTL, []byte{0x40}), // For example, after the PTMU estimate is decreased, the timeout should // be set to 10 minutes; once this timer expires and a larger MTU is // attempted, the timeout can be set to a much smaller value. // // See path_to_url#section-6.6. layers.NewDHCPOption(layers.DHCPOptPathMTUAgingTimeout, []byte{0x0, 0x0, 0x2, 0x58}), // There is a table describing the MTU values representing all major // data-link technologies in use in the Internet so that each set of // similar MTUs is associated with a plateau value equal to the lowest // MTU in the group. // // See path_to_url#section-7. layers.NewDHCPOption(layers.DHCPOptPathPlateuTableOption, []byte{ 0x0, 0x44, 0x1, 0x28, 0x1, 0xFC, 0x3, 0xEE, 0x5, 0xD4, 0x7, 0xD2, 0x11, 0x0, 0x1F, 0xE6, 0x45, 0xFA, }), // IP-Layer Per Interface // Don't set the Interface MTU because client may choose the value on // their own since it's listed in the [Host Requirements RFC]. It also // seems the values listed there sometimes appear obsolete, see // path_to_url // // [Host Requirements RFC]: path_to_url#section-3.3.3. // Set the All Subnets Are Local Option to false since commonly the // connected hosts aren't expected to be multihomed. // // See path_to_url#section-3.3.3. layers.NewDHCPOption(layers.DHCPOptAllSubsLocal, []byte{0x0}), // Set the Perform Mask Discovery Option to false to provide the subnet // mask by options only. // // See path_to_url#section-3.2.2.9. layers.NewDHCPOption(layers.DHCPOptMaskDiscovery, []byte{0x0}), // A system MUST NOT send an Address Mask Reply unless it is an // authoritative agent for address masks. An authoritative agent may be // a host or a gateway, but it MUST be explicitly configured as a // address mask agent. // // See path_to_url#section-3.2.2.9. layers.NewDHCPOption(layers.DHCPOptMaskSupplier, []byte{0x0}), // Set the Perform Router Discovery Option to true as per Router // Discovery Document. // // See path_to_url#section-5.1. layers.NewDHCPOption(layers.DHCPOptRouterDiscovery, []byte{0x1}), // The all-routers address is preferred wherever possible. // // See path_to_url#section-5.1. layers.NewDHCPOption(layers.DHCPOptSolicitAddr, netutil.IPv4allrouter()), // Don't set the Static Routes Option since it should be set up by // system administrator. // // See path_to_url#section-3.3.1.2. // A datagram with the destination address of limited broadcast will be // received by every host on the connected physical network but will not // be forwarded outside that network. // // See path_to_url#section-3.2.1.3. layers.NewDHCPOption(layers.DHCPOptBroadcastAddr, netutil.IPv4bcast()), // Link-Layer Per Interface // If the system does not dynamically negotiate use of the trailer // protocol on a per-destination basis, the default configuration MUST // disable the protocol. // // See path_to_url#section-2.3.1. layers.NewDHCPOption(layers.DHCPOptARPTrailers, []byte{0x0}), // For proxy ARP situations, the timeout needs to be on the order of a // minute. // // See path_to_url#section-2.3.2.1. layers.NewDHCPOption(layers.DHCPOptARPTimeout, []byte{0x0, 0x0, 0x0, 0x3C}), // An Internet host that implements sending both the RFC-894 and the // RFC-1042 encapsulations MUST provide a configuration switch to select // which is sent, and this switch MUST default to RFC-894. // // See path_to_url#section-2.3.3. layers.NewDHCPOption(layers.DHCPOptEthernetEncap, []byte{0x0}), // TCP Per Host // A fixed value must be at least big enough for the Internet diameter, // i.e., the longest possible path. A reasonable value is about twice // the diameter, to allow for continued Internet growth. // // See path_to_url#section-3.2.1.7. layers.NewDHCPOption(layers.DHCPOptTCPTTL, []byte{0x0, 0x0, 0x0, 0x3C}), // The interval MUST be configurable and MUST default to no less than // two hours. // // See path_to_url#section-4.2.3.6. layers.NewDHCPOption(layers.DHCPOptTCPKeepAliveInt, []byte{0x0, 0x0, 0x1C, 0x20}), // Unfortunately, some misbehaved TCP implementations fail to respond to // a probe segment unless it contains data. // // See path_to_url#section-4.2.3.6. layers.NewDHCPOption(layers.DHCPOptTCPKeepAliveGarbage, []byte{0x1}), } slices.SortFunc(imp, compareV4OptionCodes) // Set values for explicitly configured options. for _, o := range c.Options { i, found := slices.BinarySearchFunc(imp, o, compareV4OptionCodes) if found { imp = slices.Delete(imp, i, i+1) } i, found = slices.BinarySearchFunc(exp, o, compareV4OptionCodes) if o.Length > 0 { exp = slices.Insert(exp, i, o) } else if found { exp = slices.Delete(exp, i, i+1) } } l.DebugContext(ctx, "options", "implicit", imp, "explicit", exp) return imp, exp } // compareV4OptionCodes compares option codes of a and b. func compareV4OptionCodes(a, b layers.DHCPOption) (res int) { return int(a.Type) - int(b.Type) } ```
/content/code_sandbox/internal/dhcpsvc/v4.go
go
2016-07-06T10:31:47
2024-08-16T18:17:06
AdGuardHome
AdguardTeam/AdGuardHome
24,082
3,447