aboutsummaryrefslogtreecommitdiff
path: root/nccli.go
blob: 4059bd185be96ccd405e85fbf691c9830f9098bf (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package main

import (
	"bufio"
	"encoding/xml"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

var (
	verbose = false
	url     string
)

// Based on: https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/
type SetResponseObj struct {
	XMLName xml.Name `xml:"ApiResponse"`
	// Based on: https://www.namecheap.com/support/api/intro/
	Status       string       `xml:"Status,attr"`
	Type         string       `xml:"RequestedCommand"`
	DNSResultObj DNSResultObj `xml:"CommandResponse>DomainDNSSetHostsResult"`
}

type DNSResultObj struct {
	XMLName   xml.Name `xml:"DomainDNSSetHostsResult"`
	Domain    string   `xml:"Domain,attr"`
	IsSuccess bool     `xml:"IsSuccess,attr"`
}

//Based on: https://www.namecheap.com/support/api/methods/domains-dns/get-hosts/
type GetResponseObj struct {
	XMLName xml.Name `xml:"ApiResponse"`
	// Based on: https://www.namecheap.com/support/api/intro/
	Status string `xml:"Status,attr"`
	Type   string `xml:"RequestedCommand"`
	Hosts  []Host `xml:"CommandResponse>DomainDNSGetHostsResult>host"`
}

type Host struct {
	XMLName xml.Name `xml:"host"`
	Type    string   `xml:"Type,attr"`
	Name    string   `xml:"Name,attr"`
	Address string   `xml:"Address,attr"`
	MXPref  int      `xml:"MXPref,attr"`
	TTL     int      `xml:"TTL,attr"`
}

// Helper functions //

// A helper to check if a env var is defined. If not defined, show error.
// Args: key - the env var to check for
// Returns if exists, the value of the var
func getEnv(key string) string {
	value := os.Getenv(key)
	if len(value) == 0 {
		log.Fatalf("Env var %s is required and missing.", key)
	}
	if verbose {
		fmt.Println(key, value)
	}
	return value
}

func loadConfig() {
	url = "https://api.namecheap.com/xml.response?ApiUser=" + getEnv("API_USER") +
		"&ApiKey=" + getEnv("API_KEY") +
		"&UserName=" + getEnv("API_USER") +
		"&ClientIp=" + getEnv("ACCESS_IP") +
		"&SLD=" + getEnv("DOMAIN_MAIN") +
		"&TLD=" + getEnv("DOMAIN_END")
}

func logRecords(hosts []Host) {
	fmt.Println("================================")
	fmt.Println("Number of DNS records:", len(hosts))
	for i, host := range hosts {
		fmt.Println(
			"[", i, "]",
			host.Type,
			host.Name,
			host.Address,
			host.MXPref,
			host.TTL,
		)
	}
	fmt.Println("================================")
}

func makeReq(endPoint string, extraParams ...string) []byte {

	apiUrl := url + "&Command=namecheap.domains.dns." + endPoint
	for _, param := range extraParams {
		apiUrl += param
	}

	if verbose {
		fmt.Println("Using api url:", apiUrl)
	}

	var (
		response *http.Response
		err      error
	)
	switch endPoint {
	case "gethosts":
		response, err = http.Get(apiUrl)
	case "sethosts":
		response, err = http.Post(apiUrl, "application/xml", nil)
	default:
		log.Fatalln("Error: Invalid request type specified.")
	}

	if err != nil {
		log.Fatalln(err)
	}

	responseData, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatalln(err)
	}
	return responseData
}

func normalizeUserChoices(userChoicesStrs []string, maxVal int) []int {
	var chosenInts []int
	for _, choice := range userChoicesStrs {
		if len(strings.TrimSpace(choice)) == 0 {
			continue
		}
		val, err := strconv.Atoi(choice)
		if err != nil {
			log.Fatalln("Error: Bad user input detected. Please only enter numbers.")
		}
		// validate
		if (val >= 0) && (val < maxVal) {
			chosenInts = append(chosenInts, val)
		} else {
			log.Fatalln("Error: Bad user input detected. One of the numbers is not correct.")
		}
	}
	return chosenInts
}

// If an existing (Name, Type) exists => update the first match...
func updateHostRecordSet(hostRecords []Host, newHost Host) {
	for i, host := range hostRecords {
		if (host.Name == newHost.Name) && (host.Type == newHost.Type) {
			hostRecords[i].Address = newHost.Address
			hostRecords[i].MXPref = newHost.MXPref
			hostRecords[i].TTL = newHost.TTL
		}
	}
}

func updateNamecheapRecords(urlEncodedHosts string) {
	// make the api request to namecheap
	responseData := makeReq("sethosts", urlEncodedHosts)
	var responseObj SetResponseObj
	xml.Unmarshal(responseData, &responseObj)

	// validate
	if responseObj.Status != "OK" {
		log.Fatalln(string(responseData))
		log.Fatalln("Error: Api request failed. Exiting.")
	}
	if !responseObj.DNSResultObj.IsSuccess {
		log.Fatalln(string(responseData))
		log.Fatalln("Error: Something went wrong updating DNS records for:", responseObj.DNSResultObj.Domain)
	}
	if verbose {
		fmt.Println("Success updating DNS records for:", responseObj.DNSResultObj.Domain)
	}
}

func urlEncodeHosts(hosts []Host) string {
	var res string
	for i, host := range hosts {
		res += fmt.Sprintf("&HostName%d=%s&RecordType%d=%s&Address%d=%s&MXPref%d=%d&TTL%d=%d",
			i+1, host.Name,
			i+1, host.Type,
			i+1, host.Address,
			i+1, host.MXPref,
			i+1, host.TTL,
		)
	}
	return res
}

func userInputHandler() []string {
	var chosen []string
	for {
		fmt.Println("Please enter the number next to the DNS record you want to remove: ")
		fmt.Println("Each number should be seperated by a space:")
		scanner := bufio.NewScanner(os.Stdin)
		scanner.Scan()
		err := scanner.Err()
		if err != nil {
			log.Fatal(err)
		}
		text := strings.TrimSpace(scanner.Text())
		if len(text) == 0 {
			fmt.Println("Nothing chosen. Exiting.")
			os.Exit(0)
		}
		// split by ","
		chosen = strings.Split(text, " ")

		fmt.Println("You chose", chosen, ". Are you sure you want to remove these? Y/n:")
		scanner2 := bufio.NewScanner(os.Stdin)
		scanner2.Scan()
		err2 := scanner2.Err()
		if err2 != nil {
			log.Fatal(err2)
		}
		confirm := scanner2.Text()
		if confirm == "Y" {
			break
		}
	}
	return chosen
}

// Main functions //

func getAllRecords() []Host {
	responseData := makeReq("gethosts")
	var responseObj GetResponseObj
	xml.Unmarshal(responseData, &responseObj)

	// validate
	if responseObj.Status != "OK" {
		log.Fatalln(string(responseData))
		log.Fatalln("Error: Api request failed. Exiting.")
	}
	return responseObj.Hosts
}

func addRecord(rName string, rType string, rAddress string, rMXPref int, rTTL int) {
	// we need to get the records before we can add to it.
	var hostRecords = getAllRecords()
	if verbose {
		logRecords(hostRecords)
	}

	hostRecords = append(hostRecords, Host{
		Name:    rName,
		Type:    rType,
		Address: rAddress,
		MXPref:  rMXPref,
		TTL:     rTTL,
	})

	// encode all hosts into a url
	urlEncodedHosts := urlEncodeHosts(hostRecords)
	updateNamecheapRecords(urlEncodedHosts)
}

func removeRecord() {
	// we need to get the records before we can remove one
	var hostRecords = getAllRecords()
	logRecords(hostRecords)

	// get user input for which ones to delete
	userChoicesStrs := userInputHandler()
	userChoicesInts := normalizeUserChoices(userChoicesStrs, len(hostRecords))

	// contains the desired set of host records.
	var newHostRecords []Host
	for i, host := range hostRecords {
		found := false
		for _, rmIdx := range userChoicesInts {
			if i == rmIdx {
				found = true
				break
			}
		}
		if !found {
			newHostRecords = append(newHostRecords, host)
		}
	}

	// encode all hosts into a url
	urlEncodedHosts := urlEncodeHosts(newHostRecords)
	updateNamecheapRecords(urlEncodedHosts)
}

func updateRecord(rName string, rType string, rAddress string, rMXPref int, rTTL int) {
	// we need to get the records before we can update it.
	var hostRecords = getAllRecords()
	if verbose {
		logRecords(hostRecords)
	}

	updateHostRecordSet(
		hostRecords,
		Host{
			Name:    rName,
			Type:    rType,
			Address: rAddress,
			MXPref:  rMXPref,
			TTL:     rTTL,
		},
	)

	// encode all hosts into a url
	urlEncodedHosts := urlEncodeHosts(hostRecords)
	updateNamecheapRecords(urlEncodedHosts)
}

func main() {
	// Subcommads: list, add, remove, update
	// define cli args for the "list" subcommand:
	listCmd := flag.NewFlagSet("list", flag.ExitOnError)
	listCmd.BoolVar(&verbose, "v", false, "Verbosity. More output. Default=false.")
	// define cli args for the "add" subcommand:
	addCmd := flag.NewFlagSet("add", flag.ExitOnError)
	addName := addCmd.String("name", "", "Name of DNS record.")
	addType := addCmd.String("type", "", "Type of DNS record.")
	addAddress := addCmd.String("value", "", "Value of the DNS record.")
	addMXPref := addCmd.Int("priority", 0, "Value of the DNS record.")
	addTTL := addCmd.Int("ttl", 1800, "TTL of the DNS record.")
	addCmd.BoolVar(&verbose, "v", false, "Verbosity. More output. Default=false.")
	// define cli args for the "list" subcommand:
	removeCmd := flag.NewFlagSet("remove", flag.ExitOnError)
	removeCmd.BoolVar(&verbose, "v", false, "Verbosity. More output. Default=false.")
	// define cli args for the "update" subcommand:
	updateCmd := flag.NewFlagSet("update", flag.ExitOnError)
	updateName := updateCmd.String("name", "", "Name of DNS record.")
	updateType := updateCmd.String("type", "", "Type of DNS record.")
	updateAddress := updateCmd.String("value", "", "Value of the DNS record.")
	updateMXPref := updateCmd.Int("priority", 0, "Value of the DNS record.")
	updateTTL := updateCmd.Int("ttl", 1800, "TTL of the DNS record.")
	updateCmd.BoolVar(&verbose, "v", false, "Verbosity. More output. Default=false.")

	subCmdErrorMsg := "Error: Expected one of: list, add, remove, or update subcommands."
	addUpdateErrorMsg := "Error: Missing options. Please use -h to see the list of options."
	if len(os.Args) < 2 {
		log.Fatalln(subCmdErrorMsg)
	}
	switch os.Args[1] {
	case "list":
		listCmd.Parse(os.Args[2:])
		loadConfig()
		logRecords(getAllRecords())
	case "add":
		addCmd.Parse(os.Args[2:])
		if *addName == "" || *addType == "" || *addAddress == "" {
			log.Fatalln(addUpdateErrorMsg)
		}
		loadConfig()
		addRecord(*addName, *addType, *addAddress, *addMXPref, *addTTL)
	case "remove":
		removeCmd.Parse(os.Args[2:])
		loadConfig()
		removeRecord()
	case "update":
		updateCmd.Parse(os.Args[2:])
		if *updateName == "" || *updateType == "" || *updateAddress == "" {
			log.Fatalln(addUpdateErrorMsg)
		}
		loadConfig()
		updateRecord(*updateName, *updateType, *updateAddress, *updateMXPref, *updateTTL)
	default:
		log.Fatalln(subCmdErrorMsg)
	}
}