ddns/backend.go

100 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
type responder func()
func respondWithFAIL() {
fmt.Printf("FAIL\n")
}
func respondWithEND() {
fmt.Printf("END\n")
}
2014-07-15 23:26:50 +02:00
// This function implements the PowerDNS-Pipe-Backend protocol and generates
// the response data it possible
func RunBackend(conn *RedisConnection) {
bio := bufio.NewReader(os.Stdin)
2014-07-15 23:41:54 +02:00
// handshake with PowerDNS
_, _, _ = bio.ReadLine()
fmt.Printf("OK\tDDNS Go Backend\n")
for {
line, _, err := bio.ReadLine()
if err != nil {
respondWithFAIL()
continue
}
HandleRequest(string(line), conn)()
}
}
2014-07-15 23:26:50 +02:00
func HandleRequest(line string, conn *RedisConnection) responder {
if Verbose {
fmt.Printf("LOG\t'%s'\n", line)
}
2014-07-15 23:41:54 +02:00
parts := strings.Split(line, "\t")
if len(parts) != 6 {
return respondWithFAIL
2014-07-15 23:41:54 +02:00
}
2014-07-15 23:26:50 +02:00
2014-07-15 23:41:54 +02:00
query_name := parts[1]
query_class := parts[2]
query_type := parts[3]
2014-07-15 23:41:54 +02:00
query_id := parts[4]
2014-07-15 23:26:50 +02:00
var response, record string
record = query_type
2014-07-15 23:26:50 +02:00
switch query_type {
case "SOA":
response = fmt.Sprintf("%s. hostmaster.example.com. %d 1800 3600 7200 5",
DdnsSoaFqdn, getSoaSerial())
case "NS":
2014-09-21 18:17:50 +02:00
response = fmt.Sprintf("%s.", DdnsSoaFqdn)
case "A":
case "ANY":
// get the host part of the fqdn: pi.d.example.org -> pi
hostname := ""
if strings.HasSuffix(query_name, DdnsDomain) {
hostname = query_name[:len(query_name)-len(DdnsDomain)]
}
2014-07-15 23:26:50 +02:00
if hostname == "" || !conn.HostExist(hostname) {
return respondWithFAIL
}
2014-07-15 23:26:50 +02:00
host := conn.GetHost(hostname)
response = host.Ip
record = "A"
if !host.IsIPv4() {
record = "AAAA"
}
default:
return respondWithFAIL
2014-07-15 23:41:54 +02:00
}
2014-07-15 23:26:50 +02:00
2014-07-15 23:41:54 +02:00
fmt.Printf("DATA\t%s\t%s\t%s\t10\t%s\t%s\n",
query_name, query_class, record, query_id, response)
return respondWithEND
}
func getSoaSerial() int64 {
// return current time in milliseconds
return time.Now().UnixNano()
2014-07-15 23:26:50 +02:00
}