summaryrefslogtreecommitdiffstats
path: root/tinydns-model.lua
blob: e75f937723450c02a4d2e7ba7842c42785c9df7f (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
module(..., package.seeall)

-- Load libraries
require("procps")
require("getopts")
require("fs")
require("format")
require("processinfo")
require("daemoncontrol")
require("validator")

-- Set variables
local configfiles = {}
local packagename = "tinydns"
local processname = "tinydns"
local configfile = "/etc/conf.d/" .. processname
local configdir = "/etc/"..processname
local descr = {
	prefix={
		['.']="Name server for your domain (NS + A + SOA)", 
		['&']="Delegate subdomain (NS + A)", 
		['=']="Host (A + PTR)", 
		['+']="Alias (A, no PTR)", 
		['@']="Mail exchanger (MX)",
		["'"]="Text record (TXT)",
		['^']="Reverse record (PTR)", 
		['C']="Canonical name (CNAME)", 
		['Z']="SOA record (SOA)", 
		[':']="Generic record", 
		['%']="Client location", 
	},
	fieldlabels={
		['.']={"Domain", "IP address", "Name server", "Time to live", "Timestamp", "Location", }, 
		['&']={"Domain", "IP address", "Name server", "Time to live", "Timestamp", "Location", }, 
		['=']={"Host", "IP address", "Time to live", "Timestamp", "Location", }, 
		['+']={"Alias", "IP address", "Time to live", "Timestamp", "Location", }, 
		['@']={"Domain", "IP address", "Mail exchanger", "Distance", "Time to live", "Timestamp", "Location", }, 
		['\'']={"Domain", "Text Record", "Time to live", "Timestamp", "Location", }, 
		['^']={"PTR", "Domain name", "Time to live", "Timestamp", "Location", }, 
		['C']={"Domain", "Canonical name", "Time to live", "Timestamp", "Location", }, 
		['Z']={"Domain", "Primary name server", "Contact address", "Serial number", "Refresh time", "Retry time", "Expire time", "Minimum time", "Time to live", "Timestamp", "Location",}, 
		[':']={"Domain", "Record type", "Record data", "Time to live", "Timestamp", "Location", }, 
		['%']={"Location", "IP prefix", }, 
	},
}

-- ################################################################################
-- LOCAL FUNCTIONS

-- Return a table with the config-content of a file
-- Commented/Blank lines are ignored
local function get_value_from_file(file)
	local output = {}
	local filecontent = fs.read_file_as_array(file)
	for i=1,table.maxn(filecontent) do
		local l = filecontent[i]
		if not (string.find ( l, "^[;#].*" )) and not (string.find (l, "^%s*$")) then
			table.insert(output, string.match(l,"(.-)%s*$"))
		end
	end
	if (#output > 0) then
		return true, output
	else
		return false, output
	end

end

-- Function to recursively inserts all filenames in a dir into an array
local function recursedir(path, filearray)
	local k,v
	for k,v in pairs(posix.dir(path) or {}) do
		-- Ignore files that begins with a '.'
		if not string.match(v, "^%.") then
			local f = path .. "/" .. v
			-- If subfolder exists, list files in this subfolder
			if (posix.stat(f).type == "directory") then
				recursedir(f, filearray)
			else
				table.insert(filearray, f)
			end
		end
	end
end

-- Functin to split items into a table
local function split_config_items(orgitem)
	local delimiter = ":"
	local output = {}
	output = format.string_to_table(string.sub(orgitem,2),delimiter)
	output.type = string.sub(orgitem,1,1)
	output.label = descr['prefix'][output.type] or "unknown"
	return output
end

-- Feed the configfiles table with list of all availage configfiles
local function searchforconfigfiles()
	local cnffile = {}
	recursedir(configdir, cnffile)
	for k,v in pairs(cnffile) do
		local configcontent = get_value_from_file(v)
		if (configcontent) then
			table.insert(configfiles, v)
		end
	end
end
searchforconfigfiles()

local function validfilename(path)
	for k,v in pairs(getfilelist().value) do
		if (v == path) then
			return true
		end
	end
	return false, "Not a valid filename!"
end

-- ################################################################################
-- PUBLIC FUNCTIONS

function startstop_service ( self, action )
	-- action is validated in daemoncontrol
	local cmdresult,cmdmessage,cmderror,cmdaction = daemoncontrol.daemoncontrol(processname, action)
	return cfe({ type="boolean", value=cmdresult, descr=cmdmessage, errtxt=cmderror, label="Start/Stop result" })
end

-- Present some general status
function getstatus()
	local status = {}

	local value, errtxt = processinfo.package_version(packagename)
	status.version = cfe({
		label="Program version",
		value=value,
		errtxt=errtxt,
		 })

	status.status = cfe({
		label="Program status",
		value=procps.pidof(processname),
		})
	if (#status.status.value > 0) then
		status.status.value = "Enabled"
	else
		status.status.value = "Disabled"
	end

	status.configdir = cfe({
		label="Config directory",
		value=configdir,
		})

	status.configfiles = cfe({
		type="list",
		label="Config files",
		value=configfiles,
		})

	local autostart_sequense, autostart_errtxt = processinfo.process_botsequence(processname)
	status.autostart = cfe({
		label="Autostart sequence",
		value=autostart_sequense,
		errtxt=autostart_errtxt,
		})

	local config = getconfig()
	status.listen = config.value.listen

	return cfe({ type="group", value=status, label="DNS Status" })
end

function getconfig()
	local config = {}

	local listenaddr = getopts.getoptsfromfile(configfile,"","IP") or ""
	config.listen = cfe({
		label="IP address to listen on",
		value=listenaddr,
		 })
	local test, errtxt = validator.is_ipv4(config.listen.value)
	if not test then
		config.listen.errtxt = errtxt
	end

	return cfe({ type="group", value=config, label="TinyDNS Configuration" })
end

function setconfig(conf)
	local test, errtxt = validator.is_ipv4(conf.value.listen.value)
	if not test then
		conf.value.listen.errtxt = errtxt
		conf.errtxt = "Failed to set configuration"
	else
		getopts.setoptsinfile(configfile,"","IP",conf.value.listen.value)
	end

	return conf
end

-- If you enter 'filter_type' (this should be one of the options found in local function check_signs() ) then
-- the output will be filtered to only contain this type of data.
function getconfigobjects(self, filter_type)
	local configobjects = {}
	--Loop through all available configfiles
	for i,filename in pairs(configfiles) do
		local filecontent, fileresult
		fileresult, filecontent = get_value_from_file(filename)
		for j,configline in pairs(filecontent) do
			local domaindetails = {}
			local filecontent_table = split_config_items(configline)
			filecontent_table.configline = configline

			-- Use only configs that has a valid prefix
			-- If function is called with some filter options... then show only the filtered values
			if ( not (filter_type) or ((filter_type) and (filter_type == filecontent_table.type)) )
				and (filecontent_table.label) 
			then
				local entry = {}
				for i,value in ipairs(filecontent_table) do
					entry[i] = value
				end
				-- we're gonna add a reverse domain name to make it easier to sort
				local domain = {}
				for mt in string.gmatch(entry[1], "([^.]+)") do
					table.insert(domain, mt)
				end
				local reversedomain = {}
				for i=#domain,1,-1 do
					table.insert(reversedomain, domain[i])
				end
				entry.sort = table.concat(reversedomain, ".")

				-- add it to the table
				if not configobjects[filecontent_table.type] then
					configobjects[filecontent_table.type] = {label=filecontent_table.label, fieldlabels=descr.fieldlabels[filecontent_table.type]}
				end
				table.insert(configobjects[filecontent_table.type], entry)
			end
		end
	end

	-- Sort each of the tables by domain name (entry 1)
	for type,entries in pairs(configobjects) do
		table.sort(entries, function(a,b)
			if a == b then
				return false;
			elseif a.sort ~= b.sort then
				return a.sort < b.sort
			end
			for i in ipairs(a) do
				if a[i] ~= b[i] then
					return a[i] < b[i]
				end
			end
			a.errtxt = "Duplicate entry"
			b.errtxt = "Duplicate entry"
			return false
		end)
		for i,entry in ipairs(entries) do
			entry.sort = nil
		end
	end

	return configobjects
end

function getfilelist ()
	local listed_files = {}
	recursedir(configdir, listed_files)

	return cfe({ type="list", value=listed_files, label="List of config files" })
end

function get_filedetails(path)
	local file = {}
	local filedetails = {}
	local filenameerrtxt
	if (path) and (fs.is_file(path)) then
		filedetails = fs.stat(path)
	else
		filenameerrtxt="Config file '".. tostring(path) .. "' is missing!"
	end

	file["filename"] = cfe({ 
		label="File name",
		value=path,
		errtxt=filenameerrtxt
		})
	file["filesize"] = cfe({ 
		label="File size",
		value=filedetails.size or "0",
		})
	file["mtime"] = cfe({ 
		label="File date",
		value=filedetails.mtime or "---",
		})
	file["filecontent"] = cfe({ 
		type="longtext",
		label="File content",
		value=fs.read_file(path),
		})

	return cfe({ type="group", value=file, label="Config file details" })
end

function updatefilecontent (path, modifications)
	local success = false
	local errtxt
	if not (fs.is_file(path)) then
		errtxt = "Not a filename"
	elseif (validfilename(path)) then
		modifications = string.gsub(format.dostounix(modifications), "\n*$", "")
		fs.write_file(path, modifications)
		success = true
	else
		errtxt = "Not a valid filename!"
	end

	return cfe({ type="boolean", value=success, label="Update file result", errtxt=errtxt })
end

function getnewconfigfile()
	local options = {}
	options.filename = cfe({ value=configdir.."/", label="File Name" })
	return cfe({ type="group", value=options, label="New config file" })
end

function createconfigfile(configfile)
	configfile.errtxt = "Failed to create file"
	local path = configfile.value.filename.value
	local validfilepath, filepatherror = validator.is_valid_filename(path,configdir)
	if (validfilepath) then
		if (fs.is_file(path)) then
			configfile.value.filename.errtxt = "File already exists"
		else
			local file = io.open(path, "w")
			file:close()
			configfile.errtxt = nil
		end
	else
		configfile.value.filename.errtxt = filepatherror
	end

	return configfile
end

function remove_file(path)
	local success = false
	local errtxt
	if not (fs.is_file(path)) then
		errtxt = "File doesn't exist!"
	elseif (validfilename(path)) then
		local cmd, errors = io.popen( "/bin/rm " .. path, r )
		local cmdoutput = cmd:read("*a")
		cmd:close()
		success = true
	else
		errtxt = "Not a valid filename!"
	end
	return cfe({ type="boolean", value=success, label="Delete config file result", errtxt=errtxt })
end