github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/etchosts/etchosts.go (about)

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