// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package net

import (
	
	
	
)

const cacheMaxAge = 5 * time.Second

func parseLiteralIP( string) string {
	var  IP
	var  string
	 = parseIPv4()
	if  == nil {
		,  = parseIPv6Zone()
	}
	if  == nil {
		return ""
	}
	if  == "" {
		return .String()
	}
	return .String() + "%" + 
}

// hosts contains known host entries.
var hosts struct {
	sync.Mutex

	// Key for the list of literal IP addresses must be a host
	// name. It would be part of DNS labels, a FQDN or an absolute
	// FQDN.
	// For now the key is converted to lower case for convenience.
	byName map[string][]string

	// Key for the list of host names must be a literal IP address
	// including IPv6 address with zone identifier.
	// We don't support old-classful IP address notation.
	byAddr map[string][]string

	expire time.Time
	path   string
	mtime  time.Time
	size   int64
}

func readHosts() {
	 := time.Now()
	 := testHookHostsPath

	if .Before(hosts.expire) && hosts.path ==  && len(hosts.byName) > 0 {
		return
	}
	, ,  := stat()
	if  == nil && hosts.path ==  && hosts.mtime.Equal() && hosts.size ==  {
		hosts.expire = .Add(cacheMaxAge)
		return
	}

	 := make(map[string][]string)
	 := make(map[string][]string)
	var  *file
	if , _ = open();  == nil {
		return
	}
	for ,  := .readLine(); ; ,  = .readLine() {
		if  := bytealg.IndexByteString(, '#');  >= 0 {
			// Discard comments.
			 = [0:]
		}
		 := getFields()
		if len() < 2 {
			continue
		}
		 := parseLiteralIP([0])
		if  == "" {
			continue
		}
		for  := 1;  < len(); ++ {
			 := absDomainName([]byte([]))
			 := []byte([])
			lowerASCIIBytes()
			 := absDomainName()
			[] = append([], )
			[] = append([], )
		}
	}
	// Update the data cache.
	hosts.expire = .Add(cacheMaxAge)
	hosts.path = 
	hosts.byName = 
	hosts.byAddr = 
	hosts.mtime = 
	hosts.size = 
	.close()
}

// lookupStaticHost looks up the addresses for the given host from /etc/hosts.
func lookupStaticHost( string) []string {
	hosts.Lock()
	defer hosts.Unlock()
	readHosts()
	if len(hosts.byName) != 0 {
		// TODO(jbd,bradfitz): avoid this alloc if host is already all lowercase?
		// or linear scan the byName map if it's small enough?
		 := []byte()
		lowerASCIIBytes()
		if ,  := hosts.byName[absDomainName()];  {
			 := make([]string, len())
			copy(, )
			return 
		}
	}
	return nil
}

// lookupStaticAddr looks up the hosts for the given address from /etc/hosts.
func lookupStaticAddr( string) []string {
	hosts.Lock()
	defer hosts.Unlock()
	readHosts()
	 = parseLiteralIP()
	if  == "" {
		return nil
	}
	if len(hosts.byAddr) != 0 {
		if ,  := hosts.byAddr[];  {
			 := make([]string, len())
			copy(, )
			return 
		}
	}
	return nil
}