summaryrefslogtreecommitdiff
path: root/api/dns.go
blob: f8d345c9e8c86e488e4d195996245a6453339b2d (plain) (blame)
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
package api

import (
	"encoding/json"
	"log"
	"net"

	"sinanmohd.com/redq/dns"
)

type DnsResp map[string]string

func handleDnsBlock(conn net.Conn, d *dns.Dns, domains []string) {
	resp := make(DnsResp)

	for _, domain := range domains {
		err := d.Block(domain)
		if err != nil {
			resp[domain] = err.Error()
		} else {
			resp[domain] = "blocked"
		}
	}

	buf, err := json.Marshal(resp)
	if err != nil {
		log.Printf("marshaling json: %s", err)
		return
	}

	conn.Write(buf)
}

func handleDnsUnblock(conn net.Conn, d *dns.Dns, domains []string) {
	resp := make(DnsResp)

	for _, domain := range domains {
		err := d.Unblock(domain)
		if err != nil {
			resp[domain] = err.Error()
		} else {
			resp[domain] = "unblocked"
		}
	}

	buf, err := json.Marshal(resp)
	if err != nil {
		log.Printf("marshaling json: %s", err)
		return
	}

	conn.Write(buf)
}

func handleDns(conn net.Conn, d *dns.Dns, domains []string, action string) {
	switch action {
	case "block":
		handleDnsBlock(conn, d, domains)
	case "unblock":
		handleDnsUnblock(conn, d, domains)
	default:
		log.Printf("handling dns: invalid action '%s'", action)
	}
}