joker/main.go

247 lines
5.2 KiB
Go
Raw Permalink Normal View History

2018-08-01 01:22:38 +00:00
package main
import (
"encoding/json"
"flag"
2019-09-29 09:28:54 +00:00
"github.com/asaskevich/govalidator"
"github.com/hoisie/redis"
"github.com/julienschmidt/httprouter"
"github.com/weppos/publicsuffix-go/publicsuffix"
"log"
2019-09-29 09:28:54 +00:00
"net/http"
"os"
"strings"
2018-08-01 01:22:38 +00:00
)
var c *redis.Client
type infoResponse struct {
RedisServer string `json:"redis"`
}
var (
flagKey = flag.String("key", "godns:hosts", "Redis key for hash set")
flagListen = flag.String("listen", ":8080", "listen address")
flagServer = flag.String("server", "localhost:6379", "redis host")
2018-08-01 01:22:38 +00:00
filePath = flag.String("filepath", "/var/lib/joker/dist", "file path")
)
var (
key string
server string
)
func main() {
flag.Parse()
if key = os.Getenv("REDIS_KEY"); key == "" {
key = *flagKey
}
2018-08-03 00:11:49 +00:00
if server = os.Getenv("REDIS_ADDR"); server == "" {
2018-08-01 01:22:38 +00:00
server = *flagServer
}
c = &redis.Client{
Addr: server,
}
router := httprouter.New()
fs := http.FileServer(http.Dir(*filePath))
serveFiles := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fs.ServeHTTP(w, r)
}
router.GET("/", serveFiles)
router.GET("/js/*filepath", serveFiles)
router.GET("/css/*filepath", serveFiles)
router.GET("/info", getInfo)
router.GET("/records", getRecords)
router.GET("/records/:zone", getRecords)
router.POST("/update", updateRecord)
router.POST("/remove", removeRecord)
log.Println("Starting server on " + *flagListen)
http.ListenAndServe(*flagListen, router)
2018-08-01 01:22:38 +00:00
}
func getInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
json.NewEncoder(w).Encode(&infoResponse{
RedisServer: server,
})
}
type tableRow struct {
2019-09-29 09:28:54 +00:00
Name string `json:"name"`
IP string `json:"ip"`
ItemCount int `json:"itemCount"`
}
2018-08-03 00:03:32 +00:00
type response struct {
Success bool `json:"success"`
Message string `json:"message"`
}
2018-08-01 01:22:38 +00:00
func getRecords(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
zone := p.ByName("zone")
hosts := make(map[string]string)
if err := c.Hgetall(key, hosts); err != nil {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusInternalServerError, "Unable to retrieve records: " + err.Error())
2018-08-01 01:22:38 +00:00
return
}
groups := make(map[string]map[string]string)
for host, addr := range hosts {
domain, err := publicsuffix.Domain(host)
if err != nil {
domain = host
}
if zone != "" && !strings.HasSuffix(host, zone) {
continue
}
if group, ok := groups[domain]; ok {
group[host] = addr
} else {
groups[domain] = map[string]string{host:addr}
}
}
out := make([]*tableRow, 0)
if zone == "" {
for domain, children := range groups {
ip := children[domain]
if len(children) > 1 {
ip = "-"
} else {
domain = mapFirst(children)
ip = children[domain]
}
out = append(out, &tableRow{
2019-09-29 09:28:54 +00:00
Name: domain,
IP: ip,
ItemCount: len(children),
})
}
} else {
for domain, ip := range groups[zone] {
out = append(out, &tableRow{
2019-09-29 09:28:54 +00:00
Name: domain,
IP: ip,
ItemCount: 1,
})
}
}
json.NewEncoder(w).Encode(out)
}
func mapFirst(m map[string]string) string {
for k := range m {
return k
}
return ""
2018-08-01 01:22:38 +00:00
}
type domainRequest struct {
2019-09-29 09:28:54 +00:00
Name string `json:"name"`
2018-08-01 01:22:38 +00:00
IP string `json:"ip"`
Group bool `json:"group"`
}
func updateRecord(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusBadRequest, "Invalid body type.")
return
}
2018-08-01 01:22:38 +00:00
var req domainRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusBadRequest, "Unable to decode body: " + err.Error())
2018-08-01 01:22:38 +00:00
return
}
2019-09-29 09:28:54 +00:00
req.Name = strings.ToLower(req.Name)
2018-08-01 01:22:38 +00:00
2018-08-21 03:38:39 +00:00
// Replace wildcards with an 'a' to test the domain
2019-09-29 09:28:54 +00:00
testDomain := req.Name
2018-08-21 03:38:39 +00:00
testDomain = strings.Replace(testDomain, "*", "a", -1)
if !govalidator.IsDNSName(testDomain) || !govalidator.IsIP(req.IP) {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusBadRequest, "Invalid domain or IP")
2018-08-01 01:22:38 +00:00
return
}
2019-09-29 09:28:54 +00:00
if _, err := c.Hset(key, req.Name, []byte(req.IP)); err != nil {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusInternalServerError, "Unable to save record: " + err.Error())
2018-08-01 01:22:38 +00:00
return
}
2019-09-29 09:33:06 +00:00
c.Publish("godns:update_record", []byte(req.Name))
json.NewEncoder(w).Encode(&response{Success: true})
2018-08-01 01:22:38 +00:00
}
func removeRecord(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var req domainRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return
}
2019-09-29 09:28:54 +00:00
req.Name = strings.ToLower(req.Name)
2018-08-01 01:22:38 +00:00
2019-09-29 09:28:54 +00:00
if !govalidator.IsDNSName(strings.Replace(req.Name, "*", "a", -1)) {
2018-08-01 01:22:38 +00:00
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Group {
hosts := make(map[string]string)
if err := c.Hgetall(key, hosts); err != nil {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusInternalServerError, "Unable to fetch records: " + err.Error())
2018-08-01 01:22:38 +00:00
return
}
for host, _ := range hosts {
host = strings.ToLower(host)
2019-09-29 09:28:54 +00:00
if !strings.HasSuffix(host, req.Name) {
2018-08-01 01:22:38 +00:00
continue
}
c.Hdel(key, host)
c.Publish("godns:remove_record", []byte(host))
}
} else {
2019-09-29 09:28:54 +00:00
if _, err := c.Hdel(key, req.Name); err != nil {
2018-08-05 08:52:49 +00:00
errorResponse(w, http.StatusInternalServerError, "Unable to delete record: " + err.Error())
2018-08-01 01:22:38 +00:00
return
}
2019-09-29 09:33:06 +00:00
c.Publish("godns:remove_record", []byte(req.Name))
2018-08-01 01:22:38 +00:00
}
2018-08-05 08:52:49 +00:00
}
func errorResponse(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(&response{Success: false, Message: message})
2018-08-01 01:22:38 +00:00
}