etchosts.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package etchosts
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. )
  12. // Record Structure for a single host record
  13. type Record struct {
  14. Hosts string
  15. IP string
  16. }
  17. // WriteTo writes record to file and returns bytes written or error
  18. func (r Record) WriteTo(w io.Writer) (int64, error) {
  19. n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts)
  20. return int64(n), err
  21. }
  22. var (
  23. // Default hosts config records slice
  24. defaultContent = []Record{
  25. {Hosts: "localhost", IP: "127.0.0.1"},
  26. {Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"},
  27. {Hosts: "ip6-localnet", IP: "fe00::0"},
  28. {Hosts: "ip6-mcastprefix", IP: "ff00::0"},
  29. {Hosts: "ip6-allnodes", IP: "ff02::1"},
  30. {Hosts: "ip6-allrouters", IP: "ff02::2"},
  31. }
  32. // A cache of path level locks for synchronizing /etc/hosts
  33. // updates on a file level
  34. pathMap = make(map[string]*sync.Mutex)
  35. // A package level mutex to synchronize the cache itself
  36. pathMutex sync.Mutex
  37. )
  38. func pathLock(path string) func() {
  39. pathMutex.Lock()
  40. defer pathMutex.Unlock()
  41. pl, ok := pathMap[path]
  42. if !ok {
  43. pl = &sync.Mutex{}
  44. pathMap[path] = pl
  45. }
  46. pl.Lock()
  47. return func() {
  48. pl.Unlock()
  49. }
  50. }
  51. // Drop drops the path string from the path cache
  52. func Drop(path string) {
  53. pathMutex.Lock()
  54. defer pathMutex.Unlock()
  55. delete(pathMap, path)
  56. }
  57. // Build function
  58. // path is path to host file string required
  59. // IP, hostname, and domainname set main record leave empty for no master record
  60. // extraContent is an array of extra host records.
  61. func Build(path, IP, hostname, domainname string, extraContent []Record) error {
  62. defer pathLock(path)()
  63. content := bytes.NewBuffer(nil)
  64. if IP != "" {
  65. //set main record
  66. var mainRec Record
  67. mainRec.IP = IP
  68. // User might have provided a FQDN in hostname or split it across hostname
  69. // and domainname. We want the FQDN and the bare hostname.
  70. fqdn := hostname
  71. if domainname != "" {
  72. fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
  73. }
  74. parts := strings.SplitN(fqdn, ".", 2)
  75. if len(parts) == 2 {
  76. mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
  77. } else {
  78. mainRec.Hosts = fqdn
  79. }
  80. if _, err := mainRec.WriteTo(content); err != nil {
  81. return err
  82. }
  83. }
  84. // Write defaultContent slice to buffer
  85. for _, r := range defaultContent {
  86. if _, err := r.WriteTo(content); err != nil {
  87. return err
  88. }
  89. }
  90. // Write extra content from function arguments
  91. for _, r := range extraContent {
  92. if _, err := r.WriteTo(content); err != nil {
  93. return err
  94. }
  95. }
  96. return os.WriteFile(path, content.Bytes(), 0644)
  97. }
  98. // Add adds an arbitrary number of Records to an already existing /etc/hosts file
  99. func Add(path string, recs []Record) error {
  100. defer pathLock(path)()
  101. if len(recs) == 0 {
  102. return nil
  103. }
  104. b, err := mergeRecords(path, recs)
  105. if err != nil {
  106. return err
  107. }
  108. return os.WriteFile(path, b, 0644)
  109. }
  110. func mergeRecords(path string, recs []Record) ([]byte, error) {
  111. f, err := os.Open(path)
  112. if err != nil {
  113. return nil, err
  114. }
  115. defer f.Close()
  116. content := bytes.NewBuffer(nil)
  117. if _, err := content.ReadFrom(f); err != nil {
  118. return nil, err
  119. }
  120. for _, r := range recs {
  121. if _, err := r.WriteTo(content); err != nil {
  122. return nil, err
  123. }
  124. }
  125. return content.Bytes(), nil
  126. }
  127. // Delete deletes an arbitrary number of Records already existing in /etc/hosts file
  128. func Delete(path string, recs []Record) error {
  129. defer pathLock(path)()
  130. if len(recs) == 0 {
  131. return nil
  132. }
  133. old, err := os.Open(path)
  134. if err != nil {
  135. return err
  136. }
  137. var buf bytes.Buffer
  138. s := bufio.NewScanner(old)
  139. eol := []byte{'\n'}
  140. loop:
  141. for s.Scan() {
  142. b := s.Bytes()
  143. if len(b) == 0 {
  144. continue
  145. }
  146. if b[0] == '#' {
  147. buf.Write(b)
  148. buf.Write(eol)
  149. continue
  150. }
  151. for _, r := range recs {
  152. if bytes.HasSuffix(b, []byte("\t"+r.Hosts)) {
  153. continue loop
  154. }
  155. }
  156. buf.Write(b)
  157. buf.Write(eol)
  158. }
  159. old.Close()
  160. if err := s.Err(); err != nil {
  161. return err
  162. }
  163. return os.WriteFile(path, buf.Bytes(), 0644)
  164. }
  165. // Update all IP addresses where hostname matches.
  166. // path is path to host file
  167. // IP is new IP address
  168. // hostname is hostname to search for to replace IP
  169. func Update(path, IP, hostname string) error {
  170. defer pathLock(path)()
  171. old, err := os.ReadFile(path)
  172. if err != nil {
  173. return err
  174. }
  175. var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname)))
  176. return os.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644)
  177. }