-
Notifications
You must be signed in to change notification settings - Fork 45
/
update.go
95 lines (78 loc) · 2.37 KB
/
update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package nswrapper
import (
"bufio"
"bytes"
"fmt"
"github.com/labstack/gommon/log"
"io/ioutil"
"os"
"os/exec"
)
// UpdateRecord builds a nsupdate file and updates a record by executing it with nsupdate.
func UpdateRecord(hostname string, target string, addrType string, zone string, ttl int, enableWildcard bool) error {
log.Info(fmt.Sprintf("%s record update request: %s -> %s", addrType, hostname, target))
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", zone))
w.WriteString(fmt.Sprintf("update delete %s.%s %s\n", hostname, zone, addrType))
if enableWildcard {
w.WriteString(fmt.Sprintf("update delete %s.%s %s\n", "*."+hostname, zone, addrType))
}
w.WriteString(fmt.Sprintf("update add %s.%s %v %s %s\n", hostname, zone, ttl, addrType, target))
if enableWildcard {
w.WriteString(fmt.Sprintf("update add %s.%s %v %s %s\n", "*."+hostname, zone, ttl, addrType, target))
}
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
}
// DeleteRecord builds a nsupdate file and deletes a record by executing it with nsupdate.
func DeleteRecord(hostname string, zone string, enableWildcard bool) 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", zone))
w.WriteString(fmt.Sprintf("update delete %s.%s\n", hostname, zone))
if enableWildcard {
w.WriteString(fmt.Sprintf("update delete %s.%s\n", "*."+hostname, zone))
}
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
}