Path: blob/master/pkg/networks/usernet/dnshosts/dnshosts.go
2662 views
// SPDX-FileCopyrightText: Copyright The Lima Authors1// SPDX-License-Identifier: Apache-2.023// From https://raw.githubusercontent.com/abiosoft/colima/v0.5.5/daemon/process/gvproxy/dnshosts_test.go4/*5MIT License67Copyright (c) 2021 Abiola Ibrahim89Permission is hereby granted, free of charge, to any person obtaining a copy10of this software and associated documentation files (the "Software"), to deal11in the Software without restriction, including without limitation the rights12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell13copies of the Software, and to permit persons to whom the Software is14furnished to do so, subject to the following conditions:1516The above copyright notice and this permission notice shall be included in all17copies or substantial portions of the Software.1819THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE25SOFTWARE.26*/2728package dnshosts2930import (31"net"32"strings"3334"github.com/containers/gvisor-tap-vsock/pkg/types"35)3637func ExtractZones(hosts hostMap) []types.Zone {38list := make(map[string]types.Zone)3940for host := range hosts {41h := zoneHost(host)4243zone := types.Zone{Name: h.name()}44if existingZone, ok := list[h.name()]; ok {45zone = existingZone46}4748if h.recordName() == "" {49if zone.DefaultIP == nil {50zone.DefaultIP = hosts.hostIP(host)51}52} else {53zone.Records = append(zone.Records, types.Record{54Name: h.recordName(),55IP: hosts.hostIP(host),56})57}5859list[h.name()] = zone60}6162zones := make([]types.Zone, 0, len(list))63for _, zone := range list {64zones = append(zones, zone)65}66return zones67}6869type hostMap map[string]string7071func (z hostMap) hostIP(host string) net.IP {72for {73// check if host entry exists74h, ok := z[host]75if !ok || h == "" {76return nil77}7879// if it's a valid ip, return80if ip := net.ParseIP(h); ip != nil {81return ip82}8384// otherwise, a string i.e. another host85// loop through the process again.86host = h87}88}8990type zoneHost string9192func (z zoneHost) name() string {93i := z.dotIndex()94if i < 0 {95return string(z)96}97return string(z)[i+1:] + "."98}99100func (z zoneHost) recordName() string {101i := z.dotIndex()102if i < 0 {103return ""104}105return string(z)[:i]106}107108func (z zoneHost) dotIndex() int {109return strings.LastIndex(string(z), ".")110}111112113