ncddns/main.go

118 lines
2.1 KiB
Go
Raw Normal View History

2022-07-31 12:57:34 +01:00
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
const (
baseURL = "https://dynamicdns.park-your-domain.com/update?"
)
2022-08-01 00:19:30 +01:00
var (
byName = map[string]IPSetter{
"namecheap": NameCheap{},
"gandi": Gandi{},
}
)
type IPSetRequest struct {
IP string
Domain string
Password string
Host string
}
type IPSetter interface {
IPSet([]IPSetRequest) error
}
2022-07-31 12:57:34 +01:00
type DomainTuple struct {
Domain string
Password string
2022-08-01 00:19:30 +01:00
Setter IPSetter
2022-07-31 12:57:34 +01:00
}
func Config(path string) ([]DomainTuple, error) {
conf, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read conf: %w", err)
}
tuples := []DomainTuple{}
for _, line := range strings.Split(string(conf), "\n") {
line := strings.TrimSpace(line)
2022-08-01 00:19:30 +01:00
if !strings.Contains(line, ",") {
2022-07-31 12:57:34 +01:00
continue
}
2022-08-01 00:19:30 +01:00
parts := strings.SplitN(line, ",", 3)
if len(parts) != 3 {
2022-07-31 12:57:34 +01:00
continue
}
2022-08-01 00:19:30 +01:00
setter, ok := byName[parts[0]]
if !ok {
return nil, fmt.Errorf("line [%s] has unsupported provider [%s]", line, parts[0])
}
2022-07-31 12:57:34 +01:00
tuples = append(tuples, DomainTuple{
2022-08-01 00:19:30 +01:00
Domain: parts[1],
Password: parts[2],
Setter: setter,
2022-07-31 12:57:34 +01:00
})
}
return tuples, nil
}
func fatal(name string, err error) {
if err != nil {
fmt.Fprintln(os.Stderr, name, err.Error())
os.Exit(1)
}
}
func main() {
cfgPath := flag.String("config", "nc.conf", "config file path")
flag.Parse()
ip, err := IP()
fatal("ip", err)
cfg, err := Config(*cfgPath)
fatal("config", err)
for _, cfgEntry := range cfg {
fmt.Println(cfgEntry.Domain)
2022-08-01 00:19:30 +01:00
err = cfgEntry.Setter.IPSet([]IPSetRequest{
{
IP: ip,
Domain: cfgEntry.Domain,
Password: cfgEntry.Password,
Host: "*",
},
{
IP: ip,
Domain: cfgEntry.Domain,
Password: cfgEntry.Password,
Host: "@",
},
})
2022-07-31 12:57:34 +01:00
fatal(cfgEntry.Domain, err)
}
}
func IP() (string, error) {
resp, err := http.Get("https://ipv4.icanhazip.com")
if err != nil {
return "", fmt.Errorf("get ip: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read body: %w", err)
}
return string(body), nil
}