OSDN Git Service

Add Go frontend, libgo library, and Go testsuite.
[pf3gnuchains/gcc-fork.git] / libgo / go / net / hosts.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Read static host/IP entries from /etc/hosts.
6
7 package net
8
9 import (
10         "os"
11         "sync"
12 )
13
14 const cacheMaxAge = int64(300) // 5 minutes.
15
16 // hostsPath points to the file with static IP/address entries.
17 var hostsPath = "/etc/hosts"
18
19 // Simple cache.
20 var hosts struct {
21         sync.Mutex
22         data map[string][]string
23         time int64
24         path string
25 }
26
27 func readHosts() {
28         now, _, _ := os.Time()
29         hp := hostsPath
30         if len(hosts.data) == 0 || hosts.time+cacheMaxAge <= now || hosts.path != hp {
31                 hs := make(map[string][]string)
32                 var file *file
33                 if file, _ = open(hp); file == nil {
34                         return
35                 }
36                 for line, ok := file.readLine(); ok; line, ok = file.readLine() {
37                         if i := byteIndex(line, '#'); i >= 0 {
38                                 // Discard comments.
39                                 line = line[0:i]
40                         }
41                         f := getFields(line)
42                         if len(f) < 2 || ParseIP(f[0]) == nil {
43                                 continue
44                         }
45                         for i := 1; i < len(f); i++ {
46                                 h := f[i]
47                                 hs[h] = append(hs[h], f[0])
48                         }
49                 }
50                 // Update the data cache.
51                 hosts.time, _, _ = os.Time()
52                 hosts.path = hp
53                 hosts.data = hs
54                 file.close()
55         }
56 }
57
58 // lookupStaticHosts looks up the addresses for the given host from /etc/hosts.
59 func lookupStaticHost(host string) []string {
60         hosts.Lock()
61         defer hosts.Unlock()
62         readHosts()
63         if len(hosts.data) != 0 {
64                 if ips, ok := hosts.data[host]; ok {
65                         return ips
66                 }
67         }
68         return nil
69 }