|
| 1 | +package hostsapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +const hostspath = "C:/Windows/System32/drivers/etc/hosts" |
| 13 | + |
| 14 | +// HostEntry data structure for IP and hostnames |
| 15 | +type HostEntry struct { |
| 16 | + Idx int |
| 17 | + IP string |
| 18 | + Hostname string |
| 19 | +} |
| 20 | + |
| 21 | +// HostsAPI data structure |
| 22 | +type HostsAPI struct { |
| 23 | + filter string |
| 24 | + hostsfile *os.File |
| 25 | + entries map[string]*HostEntry |
| 26 | + remidxs map[int]interface{} |
| 27 | +} |
| 28 | + |
| 29 | +func parseHostfileLine(idx int, line string) ([]*HostEntry, error) { |
| 30 | + if len(line) <= 0 { |
| 31 | + return nil, errors.New("invalid line") |
| 32 | + } |
| 33 | + line = strings.TrimSpace(line) |
| 34 | + if line[0] == '#' { |
| 35 | + return nil, errors.New("comment line") |
| 36 | + } |
| 37 | + fields := strings.Fields(line) |
| 38 | + var validfields []string |
| 39 | + for _, f := range fields { |
| 40 | + if len(f) <= 0 { |
| 41 | + continue |
| 42 | + } |
| 43 | + if f[0] == '#' { // inline comment |
| 44 | + break // don't process any more |
| 45 | + } |
| 46 | + validfields = append(validfields, f) |
| 47 | + } |
| 48 | + if len(validfields) <= 1 { |
| 49 | + return nil, fmt.Errorf("invalid fields for line: %q", line) |
| 50 | + } |
| 51 | + var entries []*HostEntry |
| 52 | + for _, hostname := range validfields[1:] { |
| 53 | + entries = append(entries, &HostEntry{ |
| 54 | + Idx: idx, |
| 55 | + IP: validfields[0], |
| 56 | + Hostname: hostname, |
| 57 | + }) |
| 58 | + } |
| 59 | + |
| 60 | + return entries, nil |
| 61 | +} |
| 62 | + |
| 63 | +func (h *HostsAPI) loadAndParse() error { |
| 64 | + scanner := bufio.NewScanner(h.hostsfile) |
| 65 | + idx := 0 |
| 66 | + for scanner.Scan() { |
| 67 | + line := scanner.Text() |
| 68 | + entries, err := parseHostfileLine(idx, line) |
| 69 | + idx++ |
| 70 | + if err != nil { |
| 71 | + // log.Println(err) // debug |
| 72 | + continue |
| 73 | + } |
| 74 | + for _, e := range entries { |
| 75 | + if h.filter == "" || strings.Contains(e.Hostname, h.filter) { |
| 76 | + h.entries[e.Hostname] = e |
| 77 | + h.remidxs[e.Idx] = nil |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + h.hostsfile.Seek(0, 0) |
| 82 | + return nil |
| 83 | +} |
| 84 | + |
| 85 | +// CreateAPI creates a new instance of the hosts file API |
| 86 | +// Call Close() when finished |
| 87 | +// `filter` proves ability to filter by string contains |
| 88 | +func CreateAPI(filter string) (*HostsAPI, error) { |
| 89 | + f, err := os.Open(hostspath) |
| 90 | + if err != nil { |
| 91 | + return nil, fmt.Errorf("failed to open hosts file: %w", err) |
| 92 | + } |
| 93 | + h := &HostsAPI{ |
| 94 | + filter: filter, |
| 95 | + remidxs: make(map[int]interface{}), |
| 96 | + entries: make(map[string]*HostEntry), |
| 97 | + hostsfile: f, |
| 98 | + } |
| 99 | + err = h.loadAndParse() |
| 100 | + if err != nil { |
| 101 | + return nil, fmt.Errorf("failed to parse hosts file: %w", err) |
| 102 | + } |
| 103 | + return h, nil |
| 104 | +} |
| 105 | + |
| 106 | +// Close closes the hosts file |
| 107 | +func (h *HostsAPI) Close() error { |
| 108 | + err := h.hostsfile.Close() |
| 109 | + if err != nil { |
| 110 | + return fmt.Errorf("failed to close hosts file: %w", err) |
| 111 | + } |
| 112 | + |
| 113 | + return nil |
| 114 | +} |
| 115 | + |
| 116 | +// Entries returns parsed entries of host file |
| 117 | +func (h *HostsAPI) Entries() map[string]*HostEntry { |
| 118 | + return h.entries |
| 119 | +} |
| 120 | + |
| 121 | +// RemoveEntry removes existing entry from hosts file |
| 122 | +func (h *HostsAPI) RemoveEntry(hostname string) error { |
| 123 | + if _, exists := h.entries[hostname]; exists { |
| 124 | + delete(h.entries, hostname) |
| 125 | + } else { |
| 126 | + return fmt.Errorf("failed to remove, hostname does not exist: %s", hostname) |
| 127 | + } |
| 128 | + return nil |
| 129 | +} |
| 130 | + |
| 131 | +// AddEntry adds a new HostEntry |
| 132 | +func (h *HostsAPI) AddEntry(entry *HostEntry) error { |
| 133 | + if _, exists := h.entries[entry.Hostname]; exists { |
| 134 | + return fmt.Errorf("failed to add entry, hostname already exists: %s", entry.Hostname) |
| 135 | + } |
| 136 | + |
| 137 | + h.entries[entry.Hostname] = entry |
| 138 | + |
| 139 | + return nil |
| 140 | +} |
| 141 | + |
| 142 | +// Write |
| 143 | +func (h *HostsAPI) Write() error { |
| 144 | + var outbuf bytes.Buffer |
| 145 | + |
| 146 | + // first remove all current entries |
| 147 | + scanner := bufio.NewScanner(h.hostsfile) |
| 148 | + for idx := 0; scanner.Scan() == true; idx++ { |
| 149 | + line := scanner.Text() |
| 150 | + if _, exists := h.remidxs[idx]; !exists { |
| 151 | + outbuf.WriteString(line) |
| 152 | + outbuf.WriteString("\r\n") |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // append entries to file |
| 157 | + for _, e := range h.entries { |
| 158 | + outbuf.WriteString(fmt.Sprintf("%s %s # managed by wsl2-host\r\n", e.IP, e.Hostname)) |
| 159 | + } |
| 160 | + |
| 161 | + fmt.Println(string(outbuf.Bytes())) |
| 162 | + f, err := os.OpenFile(hostspath, os.O_WRONLY|os.O_TRUNC, 0600) |
| 163 | + if err != nil { |
| 164 | + return fmt.Errorf("failed to open hosts file for writing: %w", err) |
| 165 | + } |
| 166 | + defer f.Close() |
| 167 | + |
| 168 | + f.Write(outbuf.Bytes()) |
| 169 | + |
| 170 | + return nil |
| 171 | +} |
0 commit comments