initial commit
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/benjaminbear/docker-ddns-server/dyndns/model"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/tg123/go-htpasswd"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
DB *gorm.DB
|
||||
AuthHost *model.Host
|
||||
AuthAdmin bool
|
||||
Config Envs
|
||||
}
|
||||
|
||||
type Envs struct {
|
||||
AdminLogin string
|
||||
Domain string
|
||||
}
|
||||
|
||||
type CustomValidator struct {
|
||||
Validator *validator.Validate
|
||||
}
|
||||
|
||||
func (cv *CustomValidator) Validate(i interface{}) error {
|
||||
return cv.Validator.Struct(i)
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (h *Handler) Authenticate(username, password string, c echo.Context) (bool, error) {
|
||||
h.AuthHost = nil
|
||||
h.AuthAdmin = false
|
||||
|
||||
ok, err := h.authByEnv(username, password)
|
||||
if err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if ok {
|
||||
h.AuthAdmin = true
|
||||
return true, nil
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err := h.DB.Where(&model.Host{UserName: username, Password: password}).First(host).Error; err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
h.AuthHost = host
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (h *Handler) authByEnv(username, password string) (bool, error) {
|
||||
hashReader := strings.NewReader(h.Config.AdminLogin)
|
||||
|
||||
pw, err := htpasswd.NewFromReader(hashReader, htpasswd.DefaultSystems, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if ok := pw.Match(username, password); ok {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (h *Handler) ParseEnvs() error {
|
||||
h.Config = Envs{}
|
||||
h.Config.AdminLogin = os.Getenv("DDNS_ADMIN_LOGIN")
|
||||
if h.Config.AdminLogin == "" {
|
||||
return fmt.Errorf("environment variable DDNS_ADMIN_LOGIN has to be set")
|
||||
}
|
||||
|
||||
h.Config.Domain = os.Getenv("DDNS_DOMAIN")
|
||||
if h.Config.Domain == "" {
|
||||
return fmt.Errorf("environment variable DDNS_DOMAIN has to be set")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) InitDB() (err error) {
|
||||
if _, err := os.Stat("database"); os.IsNotExist(err) {
|
||||
err = os.MkdirAll("database", os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
h.DB, err = gorm.Open("sqlite3", "database/ddns.db")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !h.DB.HasTable(&model.Host{}) {
|
||||
h.DB.CreateTable(&model.Host{})
|
||||
}
|
||||
|
||||
if !h.DB.HasTable(&model.Log{}) {
|
||||
h.DB.CreateTable(&model.Log{})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/benjaminbear/docker-ddns-server/dyndns/model"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (h *Handler) GetHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err = h.DB.First(host, id).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
// Display site
|
||||
return c.JSON(http.StatusOK, id)
|
||||
}
|
||||
|
||||
func (h *Handler) ListHosts(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
hosts := new([]model.Host)
|
||||
if err = h.DB.Find(hosts).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return c.Render(http.StatusOK, "listhosts", echo.Map{
|
||||
"hosts": hosts,
|
||||
"config": h.Config,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) AddHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
return c.Render(http.StatusOK, "edithost", echo.Map{
|
||||
"addEdit": "add",
|
||||
"config": h.Config,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) EditHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err = h.DB.First(host, id).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return c.Render(http.StatusOK, "edithost", echo.Map{
|
||||
"host": host,
|
||||
"addEdit": "edit",
|
||||
"config": h.Config,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) CreateHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err = c.Bind(host); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
if err = c.Validate(host); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
if err = h.DB.Create(host).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
// If a ip is set create dns entry
|
||||
if host.Ip != "" {
|
||||
ipType := getIPType(host.Ip)
|
||||
if ipType == "" {
|
||||
return c.JSON(http.StatusBadRequest, &Error{fmt.Sprintf("ip %s is not a valid ip", host.Ip)})
|
||||
}
|
||||
|
||||
if err = h.updateRecord(host.Hostname, host.Ip, ipType, host.Ttl); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, host)
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
hostUpdate := &model.Host{}
|
||||
if err = c.Bind(hostUpdate); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err = h.DB.First(host, id).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
forceRecordUpdate := host.UpdateHost(hostUpdate)
|
||||
if err = c.Validate(host); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
if err = h.DB.Save(host).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
// If ip or ttl changed update dns entry
|
||||
if forceRecordUpdate {
|
||||
ipType := getIPType(host.Ip)
|
||||
if ipType == "" {
|
||||
return c.JSON(http.StatusBadRequest, &Error{fmt.Sprintf("ip %s is not a valid ip", host.Ip)})
|
||||
}
|
||||
|
||||
if err = h.updateRecord(host.Hostname, host.Ip, ipType, host.Ttl); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, host)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteHost(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
host := &model.Host{}
|
||||
if err = h.DB.First(host, id).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
err = h.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err = tx.Unscoped().Delete(host).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
if err = tx.Where(&model.Log{HostID: uint(id)}).Delete(&model.Log{}).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
if err = h.deleteRecord(host.Hostname); err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, id)
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateIP(c echo.Context) (err error) {
|
||||
if h.AuthHost == nil {
|
||||
return c.String(http.StatusBadRequest, "badauth\n")
|
||||
}
|
||||
|
||||
log := &model.Log{Status: false, Host: *h.AuthHost, TimeStamp: time.Now(), UserAgent: shrinkUserAgent(c.Request().UserAgent())}
|
||||
log.SentIP = c.QueryParam(("myip"))
|
||||
|
||||
// Get caller IP
|
||||
log.CallerIP, err = getCallerIP(c.Request())
|
||||
if log.CallerIP == "" {
|
||||
log.CallerIP, _, err = net.SplitHostPort(c.Request().RemoteAddr)
|
||||
if err != nil {
|
||||
if err = h.CreateLogEntry(log); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
return c.String(http.StatusBadRequest, "badrequest\n")
|
||||
}
|
||||
}
|
||||
|
||||
// Validate hostname
|
||||
hostname := c.QueryParam("hostname")
|
||||
if hostname == "" || hostname != h.AuthHost.Hostname+"."+h.Config.Domain {
|
||||
if err = h.CreateLogEntry(log); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
return c.String(http.StatusBadRequest, "notfqdn\n")
|
||||
}
|
||||
|
||||
// Get IP type
|
||||
ipType := getIPType(log.SentIP)
|
||||
if ipType == "" {
|
||||
log.SentIP = log.CallerIP
|
||||
ipType = getIPType(log.SentIP)
|
||||
if ipType == "" {
|
||||
if err = h.CreateLogEntry(log); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
return c.String(http.StatusBadRequest, "badrequest\n")
|
||||
}
|
||||
}
|
||||
|
||||
// add/update DNS record
|
||||
if err = h.updateRecord(log.Host.Hostname, log.SentIP, ipType, log.Host.Ttl); err != nil {
|
||||
if err = h.CreateLogEntry(log); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
return c.String(http.StatusBadRequest, "dnserr\n")
|
||||
}
|
||||
|
||||
log.Host.Ip = log.SentIP
|
||||
log.Host.LastUpdate = log.TimeStamp
|
||||
log.Status = true
|
||||
if err = h.CreateLogEntry(log); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
return c.String(http.StatusOK, "good\n")
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/benjaminbear/docker-ddns-server/dyndns/model"
|
||||
"github.com/labstack/echo/v4"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateLogEntry(log *model.Log) (err error) {
|
||||
if err = h.DB.Create(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) ShowLogs(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
logs := new([]model.Log)
|
||||
if err = h.DB.Preload("Host").Limit(30).Find(logs).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return c.Render(http.StatusOK, "listlogs", echo.Map{
|
||||
"logs": logs,
|
||||
"config": h.Config,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) ShowHostLogs(c echo.Context) (err error) {
|
||||
if !h.AuthAdmin {
|
||||
return c.JSON(http.StatusUnauthorized, &Error{"You are not allow to view that content"})
|
||||
}
|
||||
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
logs := new([]model.Log)
|
||||
if err = h.DB.Preload("Host").Where(&model.Log{HostID: uint(id)}).Limit(30).Find(logs).Error; err != nil {
|
||||
return c.JSON(http.StatusBadRequest, &Error{err.Error()})
|
||||
}
|
||||
|
||||
return c.Render(http.StatusOK, "listlogs", echo.Map{
|
||||
"logs": logs,
|
||||
"config": h.Config,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/benjaminbear/docker-ddns-server/dyndns/ipparser"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (h *Handler) updateRecord(hostname string, ipAddr string, addrType string, ttl int) error {
|
||||
fmt.Printf("%s record update request: %s -> %s\n", addrType, hostname, ipAddr)
|
||||
|
||||
f, err := ioutil.TempFile(os.TempDir(), "dyndns")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer os.Remove(f.Name())
|
||||
w := bufio.NewWriter(f)
|
||||
|
||||
w.WriteString(fmt.Sprintf("server %s\n", "localhost"))
|
||||
w.WriteString(fmt.Sprintf("zone %s\n", h.Config.Domain))
|
||||
w.WriteString(fmt.Sprintf("update delete %s.%s %s\n", hostname, h.Config.Domain, addrType))
|
||||
w.WriteString(fmt.Sprintf("update add %s.%s %v %s %s\n", hostname, h.Config.Domain, ttl, addrType, ipAddr))
|
||||
w.WriteString("send\n")
|
||||
|
||||
w.Flush()
|
||||
f.Close()
|
||||
|
||||
cmd := exec.Command("/usr/bin/nsupdate", f.Name())
|
||||
var out bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &stderr
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%v: %v", err, stderr.String())
|
||||
}
|
||||
|
||||
if out.String() != "" {
|
||||
return fmt.Errorf(out.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) deleteRecord(hostname string) error {
|
||||
fmt.Printf("record delete request: %s\n", hostname)
|
||||
|
||||
f, err := ioutil.TempFile(os.TempDir(), "dyndns")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer os.Remove(f.Name())
|
||||
w := bufio.NewWriter(f)
|
||||
|
||||
w.WriteString(fmt.Sprintf("server %s\n", "localhost"))
|
||||
w.WriteString(fmt.Sprintf("zone %s\n", h.Config.Domain))
|
||||
w.WriteString(fmt.Sprintf("update delete %s.%s\n", hostname, h.Config.Domain))
|
||||
w.WriteString("send\n")
|
||||
|
||||
w.Flush()
|
||||
f.Close()
|
||||
|
||||
cmd := exec.Command("/usr/bin/nsupdate", f.Name())
|
||||
var out bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &stderr
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%v: %v", err, stderr.String())
|
||||
}
|
||||
|
||||
if out.String() != "" {
|
||||
return fmt.Errorf(out.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getIPType(ipAddr string) string {
|
||||
if ipparser.ValidIP4(ipAddr) {
|
||||
return "A"
|
||||
} else if ipparser.ValidIP6(ipAddr) {
|
||||
return "AAAA"
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func getCallerIP(r *http.Request) (string, error) {
|
||||
fmt.Println("request", r.Header)
|
||||
for _, h := range []string{"X-Real-Ip", "X-Forwarded-For"} {
|
||||
addresses := strings.Split(r.Header.Get(h), ",")
|
||||
// march from right to left until we get a public address
|
||||
// that will be the address right before our proxy.
|
||||
for i := len(addresses) - 1; i >= 0; i-- {
|
||||
ip := strings.TrimSpace(addresses[i])
|
||||
// header can contain spaces too, strip those out.
|
||||
realIP := net.ParseIP(ip)
|
||||
if !realIP.IsGlobalUnicast() || isPrivateSubnet(realIP) {
|
||||
// bad address, go to next
|
||||
continue
|
||||
}
|
||||
return ip, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("no match")
|
||||
}
|
||||
|
||||
//ipRange - a structure that holds the start and end of a range of ip addresses
|
||||
type ipRange struct {
|
||||
start net.IP
|
||||
end net.IP
|
||||
}
|
||||
|
||||
// inRange - check to see if a given ip address is within a range given
|
||||
func inRange(r ipRange, ipAddress net.IP) bool {
|
||||
// strcmp type byte comparison
|
||||
if bytes.Compare(ipAddress, r.start) >= 0 && bytes.Compare(ipAddress, r.end) < 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var privateRanges = []ipRange{
|
||||
ipRange{
|
||||
start: net.ParseIP("10.0.0.0"),
|
||||
end: net.ParseIP("10.255.255.255"),
|
||||
},
|
||||
ipRange{
|
||||
start: net.ParseIP("100.64.0.0"),
|
||||
end: net.ParseIP("100.127.255.255"),
|
||||
},
|
||||
ipRange{
|
||||
start: net.ParseIP("172.16.0.0"),
|
||||
end: net.ParseIP("172.31.255.255"),
|
||||
},
|
||||
ipRange{
|
||||
start: net.ParseIP("192.0.0.0"),
|
||||
end: net.ParseIP("192.0.0.255"),
|
||||
},
|
||||
ipRange{
|
||||
start: net.ParseIP("192.168.0.0"),
|
||||
end: net.ParseIP("192.168.255.255"),
|
||||
},
|
||||
ipRange{
|
||||
start: net.ParseIP("198.18.0.0"),
|
||||
end: net.ParseIP("198.19.255.255"),
|
||||
},
|
||||
}
|
||||
|
||||
// isPrivateSubnet - check to see if this ip is in a private subnet
|
||||
func isPrivateSubnet(ipAddress net.IP) bool {
|
||||
// my use case is only concerned with ipv4 atm
|
||||
if ipCheck := ipAddress.To4(); ipCheck != nil {
|
||||
// iterate over all our ranges
|
||||
for _, r := range privateRanges {
|
||||
// check if this ip is in a private range
|
||||
if inRange(r, ipAddress) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func shrinkUserAgent(agent string) string {
|
||||
agentParts := strings.Split(agent, " ")
|
||||
|
||||
return agentParts[0]
|
||||
}
|
||||
Reference in New Issue
Block a user