~poptart/x

x/cmd/unad/main.go -rw-r--r-- 2.3 KiB
90787cd0 — poptart Added nvim config 5 months ago
                                                                                
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
package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
)

const RegexZone = `^\d\.\d\.\d\.\d\s(.\S*)(?:\s.*|$)`

func main() {
	urlFlag := flag.String("url", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts", "URL to check and pull content from")
	matchFlag := flag.String("match", "Etag", "HEAD HTTP header to match on")
	outFlag := flag.String("output", "/var/unbound/etc/unad.conf", "File to output parsed output file")
	cacheFlag := flag.String("outcache", "/var/unbound/etc/unad.cache", "Where to put the cache content to match")
	forceFlag := flag.Bool("force", false, "Force update and ignore cache")
	flag.Parse()
	r, err := http.Head(*urlFlag)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error downloading header: %s\n", err.Error())
		os.Exit(1)
	}
	defer r.Body.Close()
	_, ok := r.Header[*matchFlag]
	if !ok {
		fmt.Fprintf(os.Stderr, "Error header '%s' not found: %s\n", *matchFlag, err.Error())
		os.Exit(2)
	}

	m := r.Header[*matchFlag][0]
	cc, err := ioutil.ReadFile(*cacheFlag)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error opening cache: %s\n", err.Error())
	}

	err = ioutil.WriteFile(*cacheFlag, []byte(m), 0644)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error creating cache: %s\n", err.Error())
		os.Exit(3)
	}

	//Cache hit, silently exit
	if bytes.Equal(cc, []byte(m)) {
		if !(*forceFlag) {
			os.Exit(0)
		}
	}
	r2, err := http.Get(*urlFlag)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error downloading file: %s\n", err.Error())
		os.Exit(1)
	}
	defer r2.Body.Close()
	body, err := ioutil.ReadAll(r2.Body)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Content error: %s\n", err.Error())
		os.Exit(1)
	}
	f, err := os.OpenFile(*outFlag, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error opening config generated file: %s\n", err.Error())
		os.Exit(2)
	}
	fmt.Fprintf(f, "server:\n")
	regex := *regexp.MustCompile(RegexZone)
	scanner := bufio.NewScanner(strings.NewReader(string(body)))
	for scanner.Scan() {
		res := regex.FindStringSubmatch(scanner.Text())
		if len(res) == 2 {
			fmt.Fprintf(f, "\tlocal-zone: \"%s\" always_nxdomain\n", res[1])
		}
	}
	if err := f.Close(); err != nil {
		fmt.Fprintf(os.Stderr, "Could not close config file: %s\n", err.Error())
		os.Exit(4)
	}
}