hostsconfig.go 7.75 KB
Newer Older
Michael Bryant's avatar
Michael Bryant committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"regexp"
	"sort"
	"strings"
)

// HostsConfig holds the configuration used to generate the hosts file
type HostsConfig struct {
	AllowRedirect bool
	Sources       map[string]bool
	Blacklist     map[string]struct{}
	Whitelist     map[string]struct{}
	Redirect      map[string]string
}

// NewHostsConfig returns a new instance of a HostsConfig struct
// with maps already initialized.
func NewHostsConfig() HostsConfig {
	var conf HostsConfig
	conf.Sources = make(map[string]bool)
	conf.Blacklist = make(map[string]struct{})
	conf.Whitelist = make(map[string]struct{})
	conf.Redirect = make(map[string]string)
	return conf
}

var domainRegexp = regexp.MustCompile(`^([0-9A-Za-z]([0-9A-Za-z]|\-|\_)*\.)*([0-9A-Za-z]([0-9A-Za-z]|\-|\_)*)$`)
var ipRegexp = regexp.MustCompile(`(2([0-4][0-9]|5[1-5])|(1)?[0-9]{1,2})\.(2([0-4][0-9]|5[1-5])|(1)?[0-9]{1,2}){3}`)
var multiSpaceRegexp = regexp.MustCompile(`(\s){2,}`)
var commentRegexp = regexp.MustCompile(`#.*`)

const fileHeader = `###########################################################################################
## This file was automatically generated by shadowhosts by Shadow53. Do not make changes ##
## to this file directly. Instead, modify the shadowhosts configuration file and re-run  ##
## shadowhosts.                                                                          ##
###########################################################################################

127.0.0.1 localhost localhost.localdomain
`

func invalidDomain(domain string) bool {
	return !domainRegexp.MatchString(domain) || domain == "localhost" ||
		domain == "localhost.localdomain"
}

// AddBlacklist adds a domain to the blacklist.
// Returns an error if it is not a valid domain
func (h *HostsConfig) AddBlacklist(domain string) error {
	if invalidDomain(domain) {
		return fmt.Errorf("%s is not a valid domain name", domain)
	}

	if _, ok := h.Whitelist[domain]; ok {
		// TODO: What to return here?
		return nil
	}

	// Add to set
	h.Blacklist[domain] = struct{}{}

	return nil
}

// AddWhitelist removes a domain from the blacklist, if found.
func (h *HostsConfig) AddWhitelist(domain string) error {
	// No need to validate here, as it must be a valid domain
	// to be blacklisted. Whitelisting something not blacklisted
	// does nothing
	h.Whitelist[domain] = struct{}{}

	// Only remove from the set if it exists
	if _, ok := h.Blacklist[domain]; ok {
		delete(h.Blacklist, domain)
	}

	return nil
}

// AddSource adds a URL source to download a hosts list from
func (h *HostsConfig) AddSource(src string) error {
	_, err := url.ParseRequestURI(src)
	if err != nil {
		return err
	}

	// Set to false to add to the set and mark unparsed
	h.Sources[src] = false
	return nil
}

// AddRedirect adds a redirection rule from `domain` to `ip`
func (h *HostsConfig) AddRedirect(domain, ip string) error {
	if invalidDomain(domain) {
		return fmt.Errorf("%s is not a valid domain name", domain)
	}
	if ip != "127.0.0.1" && !ipRegexp.MatchString(ip) {
		return fmt.Errorf("%s is not a valid ip address", ip)
	}

	// Add to whitelist so redirection takes precedence
	h.AddWhitelist(domain)
	h.Redirect[domain] = ip
	return nil
}

// DownloadSources downloads non-downloaded sources and
// adds the entries to the HostsConfig
func (h *HostsConfig) DownloadSources() error {
	for url := range h.Sources {
		if !h.Sources[url] {
			// Download file
			resp, err := http.Get(url)
			if err != nil {
				return err
			}
			defer resp.Body.Close()

			// Error if not success
			if resp.StatusCode < 200 || resp.StatusCode >= 300 {
				return fmt.Errorf("Error while connecting to %v:\n  Received non-ok status code %v", url, resp.StatusCode)
			}

			// Read contents of Body
			content, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return err
			}

			// Parse Body contents as string and split into lines
			entries := strings.Split(string(content[:]), "\n")
			for _, entry := range entries {
				//fmt.Println("Original entry: " + entry)
				// Remove comments
				entry = commentRegexp.ReplaceAllString(entry, "")
				//fmt.Println("Without comments: " + entry)
				// Trim leading and trailing spaces
				entry = strings.TrimSpace(entry)
				//fmt.Println("Trimmed spaces: " + entry)
				// Ignore now-empty lines
				if entry != "" {
					// Collapse all whitespace into a single space character
					entry = multiSpaceRegexp.ReplaceAllString(entry, " ")
					strs := strings.Split(entry, " ")
					ip := strs[0]
					for _, domain := range strs[1:] {
						if domain != "localhost" && domain != "localhost.localdomain" {
							if ip == "0.0.0.0" || ip == "127.0.0.1" {
								err = h.AddBlacklist(domain)
								if err != nil {
									return err
								}
							} else if h.AllowRedirect {
								err = h.AddRedirect(domain, ip)
								if err != nil {
									return nil
								}
							}
						}
					}
				}
			}
			h.Sources[url] = true
		}
	}
	return nil
}

// GenerateHosts generates an alphabetically sorted list of host entries as a string
func (h HostsConfig) GenerateHosts() []byte {
	// Create sorted list of all domains
	var domains sort.StringSlice = make([]string, len(h.Blacklist)+len(h.Redirect))
	for domain := range h.Blacklist {
		domains = append(domains, domain)
	}
	for domain := range h.Redirect {
		domains = append(domains, domain)
	}
	domains.Sort()

	var buf bytes.Buffer
	buf.WriteString(fileHeader)
	for _, domain := range domains {
		if _, ok := h.Blacklist[domain]; ok {
			buf.WriteString("0.0.0.0 " + domain + "\n")
		} else if ip, ok := h.Redirect[domain]; ok {
			buf.WriteString(ip + " " + domain + "\n")
		}
	}

	return buf.Bytes()
}

// UnmarshalTOML is used by the toml package to parse and set values in the HostsConfig
func (h *HostsConfig) UnmarshalTOML(data interface{}) error {
	if data == nil {
		return nil
	}

	var err error

	d := data.(map[string]interface{})

	if d["sources"] != nil {
		srcs, ok := d["sources"].([]interface{})
		if !ok {
			return fmt.Errorf("Could not parse sources as an array. Received %v", d["sources"])
		}

		for _, src := range srcs {
			srcStr, ok := src.(string)
			if !ok {
				return fmt.Errorf("Could not parse source URL as a string. Received %s", src)
			}

			err = h.AddSource(srcStr)
			if err != nil {
				return nil
			}
		}
	}

	if d["whitelist"] != nil {
		wlist, ok := d["whitelist"].([]interface{})
		if !ok {
			return fmt.Errorf("Could not parse whitelist as an array. Received %v", d["whitelist"])
		}

		for _, domain := range wlist {
			domainStr, ok := domain.(string)
			if !ok {
				return fmt.Errorf("Could not parse domain as a string. Received %s", domain)
			}
			err = h.AddWhitelist(domainStr)
			if err != nil {
				return err
			}
		}
	}

	if d["blacklist"] != nil {
		blist, ok := d["blacklist"].([]interface{})
		if !ok {
			return fmt.Errorf("Could not parse blacklist as an array. Received %v", d["blacklist"])
		}

		for _, domain := range blist {
			domainStr, ok := domain.(string)
			if !ok {
				return fmt.Errorf("Could not parse domain as a string. Received %s", domain)
			}
			err = h.AddBlacklist(domainStr)
			if err != nil {
				return err
			}
		}
	}

	if d["redirect"] != nil {
		redirects, ok := d["redirect"].(map[string]interface{})
		if !ok {
			return fmt.Errorf("Could not parse redirect as a domain-ip mapping. Received %v", d["redirect"])
		}

		for domain, ip := range redirects {
			ipString, ok := ip.(string)
			if !ok {
				return fmt.Errorf("Could not parse redirect IP address as a string. Received %v", ip)
			}

			err = h.AddRedirect(domain, ipString)
			if err != nil {
				return err
			}
		}
	}

	if d["allow_redirect"] != nil {
		allowRedir, ok := d["allow_redirect"].(bool)
		if !ok {
			return fmt.Errorf("Could not parse \"allow_redirect\" as a boolean. Received %v", d["allow_redirect"])
		}
		h.AllowRedirect = allowRedir
	}

	return nil
}