Compare commits
4 Commits
2c34850415
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
f86e78f01d
|
|||
|
abb97cce56
|
|||
|
aac894ae6f
|
|||
|
f585fb393b
|
@@ -102,7 +102,7 @@ func persistFiles(certificates *certificate.Resource, certType string) {
|
|||||||
utils.Logger.Fatal().Err(err).Msgf("Failed to save ./.lego/certs/%s/server.pem", certType)
|
utils.Logger.Fatal().Err(err).Msgf("Failed to save ./.lego/certs/%s/server.pem", certType)
|
||||||
}
|
}
|
||||||
|
|
||||||
os.WriteFile(fmt.Sprintf("./.lego/certs/%s/server.key", certType), certificates.PrivateKey, 0o644)
|
err = os.WriteFile(fmt.Sprintf("./.lego/certs/%s/server.key", certType), certificates.PrivateKey, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.Logger.Fatal().Err(err).Msgf("Failed to save ./.lego/certs/%s/server.key", certType)
|
utils.Logger.Fatal().Err(err).Msgf("Failed to save ./.lego/certs/%s/server.key", certType)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ var command = &cobra.Command{
|
|||||||
viper.SetEnvPrefix("XIP")
|
viper.SetEnvPrefix("XIP")
|
||||||
viper.AutomaticEnv()
|
viper.AutomaticEnv()
|
||||||
|
|
||||||
|
utils.InitLogger(viper.GetString("log-file"))
|
||||||
|
|
||||||
email := viper.GetString("Email")
|
email := viper.GetString("Email")
|
||||||
_, err := mail.ParseAddress(email)
|
_, err := mail.ParseAddress(email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -84,6 +86,9 @@ var command = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Execute() {
|
func Execute() {
|
||||||
|
command.Flags().String("log-file", utils.DefaultLogFile, "Path to log file")
|
||||||
|
viper.BindPFlag("log-file", command.Flags().Lookup("log-file"))
|
||||||
|
|
||||||
command.Flags().Uint("dns-port", 53, "Port for the DNS server")
|
command.Flags().Uint("dns-port", 53, "Port for the DNS server")
|
||||||
viper.BindPFlag("dns-port", command.Flags().Lookup("dns-port"))
|
viper.BindPFlag("dns-port", command.Flags().Lookup("dns-port"))
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/urfave/negroni"
|
"github.com/urfave/negroni"
|
||||||
@@ -145,6 +146,7 @@ func redirectHttpToHttps() {
|
|||||||
type CertificateReloader struct {
|
type CertificateReloader struct {
|
||||||
CertificateFilePath string
|
CertificateFilePath string
|
||||||
KeyFilePath string
|
KeyFilePath string
|
||||||
|
mu sync.RWMutex
|
||||||
certificate *tls.Certificate
|
certificate *tls.Certificate
|
||||||
lastUpdatedAt time.Time
|
lastUpdatedAt time.Time
|
||||||
}
|
}
|
||||||
@@ -155,16 +157,27 @@ func (cr *CertificateReloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certif
|
|||||||
return nil, fmt.Errorf("failed checking key file modification time: %w", err)
|
return nil, fmt.Errorf("failed checking key file modification time: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if cr.certificate == nil || stat.ModTime().After(cr.lastUpdatedAt) {
|
cr.mu.RLock()
|
||||||
pair, err := tls.LoadX509KeyPair(cr.CertificateFilePath, cr.KeyFilePath)
|
if cr.certificate != nil && !stat.ModTime().After(cr.lastUpdatedAt) {
|
||||||
if err != nil {
|
defer cr.mu.RUnlock()
|
||||||
return nil, fmt.Errorf("failed loading tls key pair: %w", err)
|
return cr.certificate, nil
|
||||||
}
|
}
|
||||||
|
cr.mu.RUnlock()
|
||||||
|
|
||||||
cr.certificate = &pair
|
cr.mu.Lock()
|
||||||
cr.lastUpdatedAt = stat.ModTime()
|
defer cr.mu.Unlock()
|
||||||
|
|
||||||
|
if cr.certificate != nil && !stat.ModTime().After(cr.lastUpdatedAt) {
|
||||||
|
return cr.certificate, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pair, err := tls.LoadX509KeyPair(cr.CertificateFilePath, cr.KeyFilePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed loading tls key pair: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cr.certificate = &pair
|
||||||
|
cr.lastUpdatedAt = stat.ModTime()
|
||||||
return cr.certificate, nil
|
return cr.certificate, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,14 +8,25 @@ import (
|
|||||||
"gopkg.in/natefinch/lumberjack.v2"
|
"gopkg.in/natefinch/lumberjack.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var consoleWriter = zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
|
const DefaultLogFile = "/var/log/local-ip.sh.log"
|
||||||
var fileWriter = &lumberjack.Logger{
|
|
||||||
Filename: "/var/log/local-ip.sh.log",
|
|
||||||
MaxBackups: 3,
|
|
||||||
MaxSize: 1, // megabytes
|
|
||||||
MaxAge: 1, // days
|
|
||||||
Compress: true, // disabled by default
|
|
||||||
}
|
|
||||||
var multi = zerolog.MultiLevelWriter(consoleWriter, fileWriter)
|
|
||||||
|
|
||||||
var Logger = zerolog.New(multi).With().Timestamp().Logger()
|
var consoleWriter = zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
|
||||||
|
|
||||||
|
var Logger = zerolog.New(consoleWriter).With().Timestamp().Logger()
|
||||||
|
|
||||||
|
func InitLogger(logFile string) {
|
||||||
|
if logFile == "" {
|
||||||
|
logFile = DefaultLogFile
|
||||||
|
}
|
||||||
|
|
||||||
|
fileWriter := &lumberjack.Logger{
|
||||||
|
Filename: logFile,
|
||||||
|
MaxBackups: 3,
|
||||||
|
MaxSize: 1,
|
||||||
|
MaxAge: 1,
|
||||||
|
Compress: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
multi := zerolog.MultiLevelWriter(consoleWriter, fileWriter)
|
||||||
|
Logger = zerolog.New(multi).With().Timestamp().Logger()
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,38 +15,39 @@ type hardcodedRecord struct {
|
|||||||
SRV *dns.SRV
|
SRV *dns.SRV
|
||||||
}
|
}
|
||||||
|
|
||||||
var hardcodedRecords = map[string]hardcodedRecord{
|
func initialRecords() map[string]hardcodedRecord {
|
||||||
// additional records I set up to host emails, feel free to change or remove them for your own needs
|
return map[string]hardcodedRecord{
|
||||||
"local-ip.sh.": {
|
"local-ip.sh.": {
|
||||||
TXT: []string{"v=spf1 include:capsulecorp.dev ~all"},
|
TXT: []string{"v=spf1 include:capsulecorp.dev ~all"},
|
||||||
MX: []*dns.MX{
|
MX: []*dns.MX{
|
||||||
{Preference: 10, Mx: "email.capsulecorp.dev."},
|
{Preference: 10, Mx: "email.capsulecorp.dev."},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
"autodiscover.local-ip.sh.": {
|
||||||
"autodiscover.local-ip.sh.": {
|
CNAME: []string{
|
||||||
CNAME: []string{
|
"email.capsulecorp.dev.",
|
||||||
"email.capsulecorp.dev.",
|
},
|
||||||
},
|
},
|
||||||
},
|
"_autodiscover._tcp.local-ip.sh.": {
|
||||||
"_autodiscover._tcp.local-ip.sh.": {
|
SRV: &dns.SRV{
|
||||||
SRV: &dns.SRV{
|
Priority: 0,
|
||||||
Priority: 0,
|
Weight: 0,
|
||||||
Weight: 0,
|
Port: 443,
|
||||||
Port: 443,
|
Target: "email.capsulecorp.dev.",
|
||||||
Target: "email.capsulecorp.dev.",
|
},
|
||||||
},
|
},
|
||||||
},
|
"autoconfig.local-ip.sh.": {
|
||||||
"autoconfig.local-ip.sh.": {
|
CNAME: []string{
|
||||||
CNAME: []string{
|
"email.capsulecorp.dev.",
|
||||||
"email.capsulecorp.dev.",
|
},
|
||||||
},
|
},
|
||||||
},
|
"_dmarc.local-ip.sh.": {
|
||||||
"_dmarc.local-ip.sh.": {
|
TXT: []string{"v=DMARC1; p=none; rua=mailto:postmaster@local-ip.sh; ruf=mailto:admin@local-ip.sh"},
|
||||||
TXT: []string{"v=DMARC1; p=none; rua=mailto:postmaster@local-ip.sh; ruf=mailto:admin@local-ip.sh"},
|
|
||||||
},
|
|
||||||
"dkim._domainkey.local-ip.sh.": {
|
|
||||||
TXT: []string{
|
|
||||||
"v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMW6NFo34qzKRPbzK41GwbWncB8IDg1i2eA2VWznIVDmTzzsqILaBOGv2xokVpzZm0QRF9wSbeVUmvwEeQ7Z6wkfMjawenDEc3XxsNSvQUVBP6LU/xcm1zsR8wtD8r5J+Jm45pNFaateiM/kb/Eypp2ntdtd8CPsEgCEDpNb62LWdy0yzRdZ/M/fNn51UMN8hVFp4YfZngAt3bQwa6kPtgvTeqEbpNf5xanpDysNJt2S8zfqJMVGvnr8JaJiTv7ZlKMMp94aC5Ndcir1WbMyfmgSnGgemuCTVMWDGPJnXDi+8BQMH1b1hmTpWDiVdVlehyyWx5AfPrsWG9cEuDIfXwIDAQAB",
|
|
||||||
},
|
},
|
||||||
},
|
"dkim._domainkey.local-ip.sh.": {
|
||||||
|
TXT: []string{
|
||||||
|
"v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMW6NFo34qzKRPbzK41GwbWncB8IDg1i2eA2VWznIVDmTzzsqILaBOGv2xokVpzZm0QRF9wSbeVUmvwEeQ7Z6wkfMjawenDEc3XxsNSvQUVBP6LU/xcm1zsR8wtD8r5J+Jm45pNFaateiM/kb/Eypp2ntdtd8CPsEgCEDpNb62LWdy0yzRdZ/M/fNn51UMN8hVFp4YfZngAt3bQwa6kPtgvTeqEbpNf5xanpDysNJt2S8zfqJMVGvnr8JaJiTv7ZlKMMp94aC5Ndcir1WbMyfmgSnGgemuCTVMWDGPJnXDi+8BQMH1b1hmTpWDiVdVlehyyWx5AfPrsWG9cEuDIfXwIDAQAB",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
156
xip/xip.go
156
xip/xip.go
@@ -6,6 +6,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/miekg/dns"
|
"github.com/miekg/dns"
|
||||||
@@ -15,6 +16,48 @@ import (
|
|||||||
type Xip struct {
|
type Xip struct {
|
||||||
server dns.Server
|
server dns.Server
|
||||||
nameServers []string
|
nameServers []string
|
||||||
|
domain string
|
||||||
|
email string
|
||||||
|
dnsPort uint
|
||||||
|
recordsMu sync.RWMutex
|
||||||
|
records map[string]hardcodedRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(*Xip)
|
||||||
|
|
||||||
|
func WithDomain(domain string) Option {
|
||||||
|
return func(x *Xip) {
|
||||||
|
x.domain = domain
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithEmail(email string) Option {
|
||||||
|
return func(x *Xip) {
|
||||||
|
x.email = email
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithDnsPort(port uint) Option {
|
||||||
|
return func(x *Xip) {
|
||||||
|
x.dnsPort = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithNameServers(nameServers []string) Option {
|
||||||
|
return func(x *Xip) {
|
||||||
|
x.recordsMu.Lock()
|
||||||
|
defer x.recordsMu.Unlock()
|
||||||
|
for i, ns := range nameServers {
|
||||||
|
name := fmt.Sprintf("ns%d.%s.", i+1, x.domain)
|
||||||
|
ip := net.ParseIP(ns)
|
||||||
|
|
||||||
|
entry := x.records[name]
|
||||||
|
entry.A = append(entry.A, ip)
|
||||||
|
x.records[name] = entry
|
||||||
|
|
||||||
|
x.nameServers = append(x.nameServers, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -26,38 +69,43 @@ var (
|
|||||||
|
|
||||||
func (xip *Xip) SetTXTRecord(fqdn string, value string) {
|
func (xip *Xip) SetTXTRecord(fqdn string, value string) {
|
||||||
utils.Logger.Trace().Str("fqdn", fqdn).Str("value", value).Msg("Trying to set TXT record")
|
utils.Logger.Trace().Str("fqdn", fqdn).Str("value", value).Msg("Trying to set TXT record")
|
||||||
config := utils.GetConfig()
|
if fqdn != fmt.Sprintf("_acme-challenge.%s.", xip.domain) {
|
||||||
if fqdn != fmt.Sprintf("_acme-challenge.%s.", config.Domain) {
|
|
||||||
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Not allowed, abort setting TXT record")
|
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Not allowed, abort setting TXT record")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if rootRecords, ok := hardcodedRecords[fqdn]; ok {
|
xip.recordsMu.Lock()
|
||||||
|
defer xip.recordsMu.Unlock()
|
||||||
|
if rootRecords, ok := xip.records[fqdn]; ok {
|
||||||
rootRecords.TXT = []string{value}
|
rootRecords.TXT = []string{value}
|
||||||
hardcodedRecords[fmt.Sprintf("_acme-challenge.%s.", config.Domain)] = rootRecords
|
xip.records[fmt.Sprintf("_acme-challenge.%s.", xip.domain)] = rootRecords
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (xip *Xip) UnsetTXTRecord(fqdn string) {
|
func (xip *Xip) UnsetTXTRecord(fqdn string) {
|
||||||
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Trying to unset TXT record")
|
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Trying to unset TXT record")
|
||||||
config := utils.GetConfig()
|
if fqdn != fmt.Sprintf("_acme-challenge.%s.", xip.domain) {
|
||||||
if fqdn != fmt.Sprintf("_acme-challenge.%s.", config.Domain) {
|
|
||||||
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Not allowed, abort unsetting TXT record")
|
utils.Logger.Trace().Str("fqdn", fqdn).Msg("Not allowed, abort unsetting TXT record")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if rootRecords, ok := hardcodedRecords[fqdn]; ok {
|
xip.recordsMu.Lock()
|
||||||
|
defer xip.recordsMu.Unlock()
|
||||||
|
if rootRecords, ok := xip.records[fqdn]; ok {
|
||||||
rootRecords.TXT = []string{}
|
rootRecords.TXT = []string{}
|
||||||
hardcodedRecords[fmt.Sprintf("_acme-challenge.%s.", config.Domain)] = rootRecords
|
xip.records[fmt.Sprintf("_acme-challenge.%s.", xip.domain)] = rootRecords
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (xip *Xip) fqdnToA(fqdn string) []*dns.A {
|
func (xip *Xip) fqdnToA(fqdn string) []*dns.A {
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].A != nil {
|
xip.recordsMu.RLock()
|
||||||
|
records := xip.records[normalizedFqdn].A
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if records != nil {
|
||||||
var aRecords []*dns.A
|
var aRecords []*dns.A
|
||||||
|
|
||||||
for _, record := range hardcodedRecords[normalizedFqdn].A {
|
for _, record := range records {
|
||||||
aRecords = append(aRecords, &dns.A{
|
aRecords = append(aRecords, &dns.A{
|
||||||
Hdr: dns.RR_Header{
|
Hdr: dns.RR_Header{
|
||||||
Ttl: uint32((time.Minute * 5).Seconds()),
|
Ttl: uint32((time.Minute * 5).Seconds()),
|
||||||
@@ -118,12 +166,15 @@ func (xip *Xip) handleA(question dns.Question, message *dns.Msg) {
|
|||||||
func (xip *Xip) handleAAAA(question dns.Question, message *dns.Msg) {
|
func (xip *Xip) handleAAAA(question dns.Question, message *dns.Msg) {
|
||||||
fqdn := question.Name
|
fqdn := question.Name
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].AAAA == nil {
|
xip.recordsMu.RLock()
|
||||||
|
records := xip.records[normalizedFqdn].AAAA
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if records == nil {
|
||||||
xip.answerWithAuthority(question, message)
|
xip.answerWithAuthority(question, message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, record := range hardcodedRecords[normalizedFqdn].AAAA {
|
for _, record := range records {
|
||||||
message.Answer = append(message.Answer, &dns.AAAA{
|
message.Answer = append(message.Answer, &dns.AAAA{
|
||||||
Hdr: dns.RR_Header{
|
Hdr: dns.RR_Header{
|
||||||
Ttl: uint32((time.Minute * 5).Seconds()),
|
Ttl: uint32((time.Minute * 5).Seconds()),
|
||||||
@@ -173,12 +224,15 @@ func chunkBy(str string, chunkSize int) (chunks []string) {
|
|||||||
func (xip *Xip) handleTXT(question dns.Question, message *dns.Msg) {
|
func (xip *Xip) handleTXT(question dns.Question, message *dns.Msg) {
|
||||||
fqdn := question.Name
|
fqdn := question.Name
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].TXT == nil {
|
xip.recordsMu.RLock()
|
||||||
|
records := xip.records[normalizedFqdn].TXT
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if records == nil {
|
||||||
xip.answerWithAuthority(question, message)
|
xip.answerWithAuthority(question, message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, record := range hardcodedRecords[normalizedFqdn].TXT {
|
for _, record := range records {
|
||||||
message.Answer = append(message.Answer, &dns.TXT{
|
message.Answer = append(message.Answer, &dns.TXT{
|
||||||
Hdr: dns.RR_Header{
|
Hdr: dns.RR_Header{
|
||||||
Ttl: uint32((time.Minute * 5).Seconds()),
|
Ttl: uint32((time.Minute * 5).Seconds()),
|
||||||
@@ -194,12 +248,15 @@ func (xip *Xip) handleTXT(question dns.Question, message *dns.Msg) {
|
|||||||
func (xip *Xip) handleMX(question dns.Question, message *dns.Msg) {
|
func (xip *Xip) handleMX(question dns.Question, message *dns.Msg) {
|
||||||
fqdn := question.Name
|
fqdn := question.Name
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].MX == nil {
|
xip.recordsMu.RLock()
|
||||||
|
records := xip.records[normalizedFqdn].MX
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if records == nil {
|
||||||
xip.answerWithAuthority(question, message)
|
xip.answerWithAuthority(question, message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, record := range hardcodedRecords[normalizedFqdn].MX {
|
for _, record := range records {
|
||||||
message.Answer = append(message.Answer, &dns.MX{
|
message.Answer = append(message.Answer, &dns.MX{
|
||||||
Hdr: dns.RR_Header{
|
Hdr: dns.RR_Header{
|
||||||
Ttl: uint32((time.Minute * 5).Seconds()),
|
Ttl: uint32((time.Minute * 5).Seconds()),
|
||||||
@@ -216,12 +273,15 @@ func (xip *Xip) handleMX(question dns.Question, message *dns.Msg) {
|
|||||||
func (xip *Xip) handleCNAME(question dns.Question, message *dns.Msg) {
|
func (xip *Xip) handleCNAME(question dns.Question, message *dns.Msg) {
|
||||||
fqdn := question.Name
|
fqdn := question.Name
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].CNAME == nil {
|
xip.recordsMu.RLock()
|
||||||
|
records := xip.records[normalizedFqdn].CNAME
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if records == nil {
|
||||||
xip.answerWithAuthority(question, message)
|
xip.answerWithAuthority(question, message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, record := range hardcodedRecords[normalizedFqdn].CNAME {
|
for _, record := range records {
|
||||||
message.Answer = append(message.Answer, &dns.CNAME{
|
message.Answer = append(message.Answer, &dns.CNAME{
|
||||||
Hdr: dns.RR_Header{
|
Hdr: dns.RR_Header{
|
||||||
Ttl: uint32((time.Minute * 5).Seconds()),
|
Ttl: uint32((time.Minute * 5).Seconds()),
|
||||||
@@ -237,7 +297,10 @@ func (xip *Xip) handleCNAME(question dns.Question, message *dns.Msg) {
|
|||||||
func (xip *Xip) handleSRV(question dns.Question, message *dns.Msg) {
|
func (xip *Xip) handleSRV(question dns.Question, message *dns.Msg) {
|
||||||
fqdn := question.Name
|
fqdn := question.Name
|
||||||
normalizedFqdn := strings.ToLower(fqdn)
|
normalizedFqdn := strings.ToLower(fqdn)
|
||||||
if hardcodedRecords[normalizedFqdn].SRV == nil {
|
xip.recordsMu.RLock()
|
||||||
|
record := xip.records[normalizedFqdn].SRV
|
||||||
|
xip.recordsMu.RUnlock()
|
||||||
|
if record == nil {
|
||||||
xip.answerWithAuthority(question, message)
|
xip.answerWithAuthority(question, message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -249,10 +312,10 @@ func (xip *Xip) handleSRV(question dns.Question, message *dns.Msg) {
|
|||||||
Rrtype: dns.TypeSRV,
|
Rrtype: dns.TypeSRV,
|
||||||
Class: dns.ClassINET,
|
Class: dns.ClassINET,
|
||||||
},
|
},
|
||||||
Priority: hardcodedRecords[normalizedFqdn].SRV.Priority,
|
Priority: record.Priority,
|
||||||
Weight: hardcodedRecords[normalizedFqdn].SRV.Weight,
|
Weight: record.Weight,
|
||||||
Port: hardcodedRecords[normalizedFqdn].SRV.Port,
|
Port: record.Port,
|
||||||
Target: hardcodedRecords[normalizedFqdn].SRV.Target,
|
Target: record.Target,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +331,6 @@ func emailToRname(email string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (xip *Xip) soaRecord(question dns.Question) *dns.SOA {
|
func (xip *Xip) soaRecord(question dns.Question) *dns.SOA {
|
||||||
config := utils.GetConfig()
|
|
||||||
soa := new(dns.SOA)
|
soa := new(dns.SOA)
|
||||||
soa.Hdr = dns.RR_Header{
|
soa.Hdr = dns.RR_Header{
|
||||||
Name: question.Name,
|
Name: question.Name,
|
||||||
@@ -278,7 +340,7 @@ func (xip *Xip) soaRecord(question dns.Question) *dns.SOA {
|
|||||||
Rdlength: 0,
|
Rdlength: 0,
|
||||||
}
|
}
|
||||||
soa.Ns = xip.nameServers[0]
|
soa.Ns = xip.nameServers[0]
|
||||||
soa.Mbox = emailToRname(config.Email)
|
soa.Mbox = emailToRname(xip.email)
|
||||||
soa.Serial = 2024072600
|
soa.Serial = 2024072600
|
||||||
soa.Refresh = uint32((time.Minute * 15).Seconds())
|
soa.Refresh = uint32((time.Minute * 15).Seconds())
|
||||||
soa.Retry = uint32((time.Minute * 15).Seconds())
|
soa.Retry = uint32((time.Minute * 15).Seconds())
|
||||||
@@ -363,7 +425,7 @@ func (xip *Xip) StartServer() {
|
|||||||
err := xip.server.ListenAndServe()
|
err := xip.server.ListenAndServe()
|
||||||
defer xip.server.Shutdown()
|
defer xip.server.Shutdown()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.Logger.Fatal().Err(err).Msg("Failed to start DNS server")
|
utils.Logger.Error().Err(err).Msg("Failed to start DNS server")
|
||||||
if strings.Contains(err.Error(), "fly-global-services: no such host") {
|
if strings.Contains(err.Error(), "fly-global-services: no such host") {
|
||||||
// we're not running on fly, bind to 0.0.0.0 instead
|
// we're not running on fly, bind to 0.0.0.0 instead
|
||||||
port := strings.Split(xip.server.Addr, ":")[1]
|
port := strings.Split(xip.server.Addr, ":")[1]
|
||||||
@@ -381,40 +443,52 @@ func (xip *Xip) StartServer() {
|
|||||||
utils.Logger.Info().Str("dns_address", xip.server.Addr).Msg("Starting up DNS server")
|
utils.Logger.Info().Str("dns_address", xip.server.Addr).Msg("Starting up DNS server")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (xip *Xip) initHardcodedRecords() {
|
func (xip *Xip) initNameServers(nameServers []string) {
|
||||||
config := utils.GetConfig()
|
|
||||||
rootDomainARecords := []net.IP{}
|
rootDomainARecords := []net.IP{}
|
||||||
|
|
||||||
for i, ns := range config.NameServers {
|
xip.recordsMu.Lock()
|
||||||
name := fmt.Sprintf("ns%d.%s.", i+1, config.Domain)
|
defer xip.recordsMu.Unlock()
|
||||||
|
|
||||||
|
for i, ns := range nameServers {
|
||||||
|
name := fmt.Sprintf("ns%d.%s.", i+1, xip.domain)
|
||||||
ip := net.ParseIP(ns)
|
ip := net.ParseIP(ns)
|
||||||
|
|
||||||
rootDomainARecords = append(rootDomainARecords, ip)
|
rootDomainARecords = append(rootDomainARecords, ip)
|
||||||
entry := hardcodedRecords[name]
|
entry := xip.records[name]
|
||||||
entry.A = append(hardcodedRecords[name].A, ip)
|
entry.A = append(xip.records[name].A, ip)
|
||||||
hardcodedRecords[name] = entry
|
xip.records[name] = entry
|
||||||
|
|
||||||
xip.nameServers = append(xip.nameServers, name)
|
xip.nameServers = append(xip.nameServers, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
hardcodedRecords[fmt.Sprintf("%s.", config.Domain)] = hardcodedRecord{A: rootDomainARecords}
|
xip.records[fmt.Sprintf("%s.", xip.domain)] = hardcodedRecord{A: rootDomainARecords}
|
||||||
|
|
||||||
// will be filled in later when requesting certificates
|
xip.records[fmt.Sprintf("_acme-challenge.%s.", xip.domain)] = hardcodedRecord{TXT: []string{}}
|
||||||
hardcodedRecords[fmt.Sprintf("_acme-challenge.%s.", config.Domain)] = hardcodedRecord{TXT: []string{}}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewXip() (xip *Xip) {
|
func NewXip(opts ...Option) (xip *Xip) {
|
||||||
config := utils.GetConfig()
|
config := utils.GetConfig()
|
||||||
xip = &Xip{}
|
xip = &Xip{
|
||||||
|
domain: config.Domain,
|
||||||
|
email: config.Email,
|
||||||
|
dnsPort: config.DnsPort,
|
||||||
|
records: initialRecords(),
|
||||||
|
}
|
||||||
|
|
||||||
xip.initHardcodedRecords()
|
for _, opt := range opts {
|
||||||
|
opt(xip)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(xip.nameServers) == 0 {
|
||||||
|
xip.initNameServers(config.NameServers)
|
||||||
|
}
|
||||||
|
|
||||||
xip.server = dns.Server{
|
xip.server = dns.Server{
|
||||||
Addr: fmt.Sprintf(":%d", config.DnsPort),
|
Addr: fmt.Sprintf(":%d", xip.dnsPort),
|
||||||
Net: "udp",
|
Net: "udp",
|
||||||
}
|
}
|
||||||
|
|
||||||
zone := fmt.Sprintf("%s.", config.Domain)
|
zone := fmt.Sprintf("%s.", xip.domain)
|
||||||
dns.HandleFunc(zone, xip.handleDnsRequest)
|
dns.HandleFunc(zone, xip.handleDnsRequest)
|
||||||
|
|
||||||
return xip
|
return xip
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestResolveDashUnit(t *testing.T) {
|
func TestResolveDashUnit(t *testing.T) {
|
||||||
// viper.Set("dns-port", 9053)
|
xip := NewXip(
|
||||||
xip := NewXip()
|
WithDomain("local-ip.sh"),
|
||||||
|
WithDnsPort(9053),
|
||||||
|
WithNameServers([]string{"1.2.3.4", "5.6.7.8"}),
|
||||||
|
)
|
||||||
|
|
||||||
A := xip.fqdnToA("192-168-1-29.local-ip.sh")
|
A := xip.fqdnToA("192-168-1-29.local-ip.sh")
|
||||||
expected := "192.168.1.29"
|
expected := "192.168.1.29"
|
||||||
@@ -41,20 +42,26 @@ func TestResolveDashUnit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestConstructor(t *testing.T) {
|
func TestConstructor(t *testing.T) {
|
||||||
viper.Set("dns-port", 9053)
|
xip := NewXip(
|
||||||
xip := NewXip()
|
WithDomain("local-ip.sh"),
|
||||||
|
WithDnsPort(9053),
|
||||||
|
WithNameServers([]string{"1.2.3.4", "5.6.7.8"}),
|
||||||
|
)
|
||||||
|
|
||||||
if xip.nameServers[0] != "ns1.local-ip.sh" {
|
if xip.nameServers[0] != "ns1.local-ip.sh." {
|
||||||
t.Error("")
|
t.Errorf("expected ns1.local-ip.sh., got %s", xip.nameServers[0])
|
||||||
}
|
}
|
||||||
if xip.nameServers[1] != "ns2.local-ip.sh" {
|
if xip.nameServers[1] != "ns2.local-ip.sh." {
|
||||||
t.Error("")
|
t.Errorf("expected ns2.local-ip.sh., got %s", xip.nameServers[1])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestResolveDashE2E(t *testing.T) {
|
func TestResolveDashE2E(t *testing.T) {
|
||||||
viper.Set("dns-port", 9053)
|
xip := NewXip(
|
||||||
xip := NewXip()
|
WithDomain("local-ip.sh"),
|
||||||
|
WithDnsPort(9053),
|
||||||
|
WithNameServers([]string{"1.2.3.4", "5.6.7.8"}),
|
||||||
|
)
|
||||||
go xip.StartServer()
|
go xip.StartServer()
|
||||||
|
|
||||||
cmd := exec.Command("dig", "@localhost", "-p", "9053", "192-168-1-29.local-ip.sh", "+short")
|
cmd := exec.Command("dig", "@localhost", "-p", "9053", "192-168-1-29.local-ip.sh", "+short")
|
||||||
@@ -70,25 +77,55 @@ func TestResolveDashE2E(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkResolveDashBasic(b *testing.B) {
|
func BenchmarkResolveDashBasic(b *testing.B) {
|
||||||
b.Skip()
|
b.Skip()
|
||||||
// var semaphore = make(chan int, 40)
|
|
||||||
// var done = make(chan bool, 1)
|
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
port := 9053 + i
|
port := 9053 + i
|
||||||
viper.Set("dns-port", port)
|
xip := NewXip(
|
||||||
xip := NewXip()
|
WithDomain("local-ip.sh"),
|
||||||
|
WithDnsPort(uint(port)),
|
||||||
|
WithNameServers([]string{"1.2.3.4", "5.6.7.8"}),
|
||||||
|
)
|
||||||
go xip.StartServer()
|
go xip.StartServer()
|
||||||
|
|
||||||
// semaphore <- 1
|
|
||||||
// go func() {
|
|
||||||
cmd := exec.Command("dig", "@localhost", "-p", fmt.Sprint(port), "192-168-1-29.local-ip.sh", "+short")
|
cmd := exec.Command("dig", "@localhost", "-p", fmt.Sprint(port), "192-168-1-29.local-ip.sh", "+short")
|
||||||
cmd.Run()
|
cmd.Run()
|
||||||
|
|
||||||
// <-semaphore
|
|
||||||
// if i == b.N {
|
|
||||||
// done <- true
|
|
||||||
// }
|
|
||||||
// }()
|
|
||||||
}
|
}
|
||||||
// <-done
|
}
|
||||||
|
|
||||||
|
func TestInstanceIsolation(t *testing.T) {
|
||||||
|
xip1 := NewXip(
|
||||||
|
WithDomain("one.test"),
|
||||||
|
WithDnsPort(0),
|
||||||
|
WithNameServers([]string{"1.1.1.1"}),
|
||||||
|
)
|
||||||
|
xip2 := NewXip(
|
||||||
|
WithDomain("two.test"),
|
||||||
|
WithDnsPort(0),
|
||||||
|
WithNameServers([]string{"2.2.2.2"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
if xip1.records == nil || xip2.records == nil {
|
||||||
|
t.Fatal("records not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(xip1.nameServers) != 1 || xip1.nameServers[0] != "ns1.one.test." {
|
||||||
|
t.Errorf("xip1 nameservers incorrect: %v", xip1.nameServers)
|
||||||
|
}
|
||||||
|
if len(xip2.nameServers) != 1 || xip2.nameServers[0] != "ns1.two.test." {
|
||||||
|
t.Errorf("xip2 nameservers incorrect: %v", xip2.nameServers)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := xip1.records["ns1.one.test."]; !ok {
|
||||||
|
t.Error("xip1 missing ns1.one.test. record")
|
||||||
|
}
|
||||||
|
if _, ok := xip2.records["ns1.two.test."]; !ok {
|
||||||
|
t.Error("xip2 missing ns1.two.test. record")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := xip1.records["ns1.two.test."]; ok {
|
||||||
|
t.Error("xip1 should not have xip2's records")
|
||||||
|
}
|
||||||
|
if _, ok := xip2.records["ns1.one.test."]; ok {
|
||||||
|
t.Error("xip2 should not have xip1's records")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user