summaryrefslogtreecommitdiffstats
path: root/interfaces-model.lua
blob: 8b7e878778ddeeef45bf3dfb7f2a5f782ab057b8 (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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
-- acf model for /etc/network/interfaces 
-- Copyright(c) 2007 N. Angelacos - Licensed under terms of GPL2
module (..., package.seeall)

require("modelfunctions")
fs = require("acf.fs")
format = require("acf.format")

local servicename = "networking"
local filename = "/etc/network/interfaces" 
local path = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin "

local array

-- iface is a local table with cfes for the various parts of interface definitions
local iface = {	tags = { comment = {type="longtext", label="Comments", seq=2},
			auto = {type="boolean", value=false, label="Auto bring-up", seq=3},
			name = {label="Interface Name", seq=1},
			family = {type="select", label="Address Family", option={"inet", "ipx", "inet6"}, seq=4}, 
			['pre-up'] = {type="longtext", label="'pre-up' actions", seq=6},
			up = {type="longtext", label="'up' actions", seq=7},
			down = {type="longtext", label="'down' actions", seq=8}, 
			['post-down'] = {type="longtext", label="'post-down' actions", seq=9} },
		method_tag = {type="select", label="Method", seq=5}, 
		family_methods = { inet = {"loopback", "static", "manual", 
				"dhcp", "bootp", "ppp", "wvdial"},
			ipx = {"static", "dynamic"},
			inet6 = {"loopback", "static", "manual", "v4tunnel"} },
		method_options = {inet = {loopback = {},
					static = {address = {label="Address"},
						netmask = {label="Netmask"},
						broadcast = {label="Broadcast address"},
						network = {label="Network address"},
						metric = {label="Routing metric"},
						gateway = {label="Default gateway"},
						pointopoint = {label="Point-to-point address"},
						media = {label="Medium type"},
						hwaddress = {label="Hardware address"},
						mtu = {label="MTU size"} },
					manual = {},
					dhcp = {hostname = {label="Hostname"},
						leasehours = {label="Preferred lease time (hours)"},
						leasetime = {label="Preferred lease time (seconds)"},
						vendor = {label="Vendor class identifier"},
						client = {label="Client identifier"},
						hwaddress = {label="Hardware address"} },
					bootp = {bootfile = {label="Boot file"},
						server = {label="Server address"},
						hwaddr = {label="Hardware address"} },
					ppp = {provider = {label="Provider name"} },
					wvdial = {provider = {label="Provider name"} },
					},
				ipx = {	static = {frame = {label="Ethernet frame type"},
						netnum = {label="Network number"} },
					dynamic = {frame = {label="Ethernet frame type"} },
					},
				inet6 ={loopback = {},
					static = {address = {label="Address"},
						netmask = {label="Netmask"},
						gateway = {label="Default gateway"},
						media = {label="Medium type"},
						hwaddress = {label="Hardware address"},
						mtu = {label="MTU size"} },
					manual = {},
					v4tunnel = {address = {label="Address"},
						netmask = {label="Netmask"},
						endpoint = {label="Endpoint address"},
						['local'] = {label="Local address"},
						gateway = {label="Default gateway"},
						ttl = {label="TTL setting"} },
					},
				},
		}


local get_iface_type = function (family, method)
	local f =  {}
	for name,table in pairs(iface.tags) do
		f[name] = cfe(table)
	end

	f.family.value = family or ""
	if family and iface.family_methods[family] then
		f.method = cfe(iface.method_tag)
		f.method.option = iface.family_methods[family]
		f.method.value = method or ""

		if method and iface.method_options[family][method] then
			for name,table in pairs(iface.method_options[family][method]) do
				f[name] = cfe(table)
			end
		elseif method then
			f.method.errtxt = "Invalid method"
		end
	elseif family then
		f.family.errtxt = "Invalid family"
	end
	
	return cfe({ type="group", value=f, label="Interface description" })
end

-- return true or false + the index of array entry matching "name"
local arrayindex = function (name)
	if name and #name > 0  then
		if array == nil then
			unpack_interfaces ()
		end

		for k,v in ipairs(array) do
			if name == v.value.name.value then
				return true, k
			end
		end
	end

	return false, 0
end

local appendentry  = function (self, value, prefix)
	self = self or ""
	-- if we already have some values, then append a newline
	if #self > 0  then self = self .. "\n" end
	-- strip the prefix
	local str = string.gsub(value, "^" .. ( prefix or "" ), "")
	-- and append
	return self .. str 
end

local expandentry = function (self, prefix)
	if #self == 0 then
		return ""
	end
	-- force the string to end in a single linefeed
	self = string.gsub (self, "\r", "")
	self = string.gsub (self, "[\n]*$", "\n")
	local strings = {}
	for line in string.gmatch(self, "(.-)\n") do
		if #line > 0 then
			strings[#strings+1] = prefix .. " " .. line
		end
	end
	return table.concat(strings, "\n")
end

-- This function parses the interfaces file and creates array
local unpack_interfaces = function ()
	if array == nil then
		local filecontent = fs.read_file(filename)
		-- make sure it has a terminating \n
		filecontent  = string.gsub (filecontent, "([^\n])$", "%1\n")
		
		array = {}
		local comment = ""
		local auto = {}

		for line in string.gmatch ( filecontent, "%s*([^\n]*%S)%s*\n?") do
			-- it can be #, auto, iface, or a parameter
			if string.match(line, "^#") then
				comment = appendentry(comment, line , "#%s*" )
			elseif string.match(line, "^auto") then
				local name = string.match(line, "auto%s+(%S+)")
				auto[name] = true
			elseif string.match(line, "^iface") then
				local name, family, method = string.match(line, "%S+%s+(%S+)%s+(%S+)%s+(%S+)")
				array[#array + 1] = get_iface_type(family, method)
				local interface = array[#array].value
				interface.comment.value = comment
				comment = ""
				interface.name.value = name or ""
			elseif #array then
				-- it must be some kind of parameter
				local param, val = 
					string.match(line, "(%S+)%s*(.*)$")
				if (param) then
					local interface = array[#array].value
					if comment ~= "" then
						interface.comment.value = appendentry(interface.comment.value, comment)
						comment = ""
					end
					if not (interface[param]) then
						interface[param] = cfe({label=param, errtxt = "Unknown parameter"})
					end
					interface[param].value = 
						appendentry(interface[param].value, val)
				end
			end
		end
		for i,int in ipairs(array) do
			if auto[int.value.name.value] then
				int.value.auto.value = true
			end
		end
	end

	return array
end

-- This function takes array and writes the interfaces file
local commit_interfaces = function()
	local str = ""
	local strings = {}
	for n,int in ipairs(array) do
		local me = int.value
		if me.comment.value ~= "" then
			strings[#strings+1] = expandentry(me.comment.value, "#")
		end
		if me.auto.value then
			strings[#strings+1] = "auto " .. me.name.value
		end
		strings[#strings+1] = string.format("iface %s %s %s", me.name.value,
						me.family.value, me.method.value)
		for name,entry in pairs(me) do
			if name~="comment" and name~="name" and name~="family" and name~="method" and name~="auto"
				and entry.value ~= "" then
				strings[#strings+1] = expandentry(entry.value, "\t"..name)
			end
		end
		strings[#strings+1] = ""
	end

	local filecontent = table.concat(strings, "\n")
	fs.write_file(filename, filecontent)
end

local validate_interface = function (def)
	local success = true
	-- since the structure is different depending on the family and method ...
	local method = ""
	if def.value.method then method = def.value.method.value end
	local newdef = get_iface_type(def.value.family.value, method)
	for name,option in pairs(newdef.value) do
		if option.errtxt then
			success = false
		end
		if def.value[name] then
			option.value = def.value[name].value
		end
	end

	-- Now, start to validate (family and method already validated)
	if #newdef.value.name.value == 0 then
		newdef.value.name.errtxt = "The interface must have a name"
		success = false
	elseif string.find(newdef.value.name.value, "%s") then
		newdef.value.name.errtxt = "Cannot contain spaces"
		success = false
	end
	-- More validation tests go here ---
	--

	if not success then
		newdef.errtxt = "Failed validation"
	end

	return success, newdef
end

local list_interfaces = function()
	local output = {}
	unpack_interfaces()
	for i,int in ipairs(array) do
		output[#output+1] = int.value.name.value
	end
	table.sort(output)
	return output
end

-------------------------------------------------------------------------------
-- Public Methods 
-------------------------------------------------------------------------------

get_all_interfaces = function(self, clientdata)
	unpack_interfaces()
	return cfe({ type="group", value=array, label="Interfaces" })
end

get_iface_by_name = function(self, clientdata)
	-- if the name is blank, then return a blank iface with error
	unpack_interfaces()
	local rc, idx = arrayindex(clientdata.name or "")
	if rc == false then
		local ret = get_iface_type()
		ret.value.name.value = name
		ret.value.name.errtxt = "Interface does not exist"
		return ret
	end
	return array[idx]
end

get_iface = function(self, clientdata) 
	unpack_interfaces()
	return get_iface_type(clientdata.family, clientdata.method)
end

create_iface = function(self, def)
	unpack_interfaces()
	local rc
	rc, def = validate_interface( def )

	if rc then
		idx = #array
		table.insert( array, idx+1, def )
		commit_interfaces()
	else
		def.errtxt = "Failed to create interface"
	end

	return def
end

update_iface = function(self, def)
	unpack_interfaces()
	-- if the def by that name doesn't exist, fail
	local rc, idx = arrayindex(def.value.name.value or "" )
	if rc == false then
		def.value.name.errtxt = "This is an invalid interface name"
	else
		rc, def = validate_interface( def )
	end

	if rc then
		array[idx] = def
		commit_interfaces()
	else
		def.errtxt = "Failed to update interface"
	end

	return def
end

get_delete_iface_by_name = function(self, clientdata)
	local result = {}
	result.name = cfe({ type="select", value=clientdata.name or "", label="Interface Name", option=list_interfaces() })

	return cfe({ type="group", value=result, label="Interface Name" })
end

delete_iface_by_name = function(self, deleterequest)
	local success = modelfunctions.validateselect(deleterequest.value.name)

	if success then
		unpack_interfaces()
		local rc, idx = arrayindex(deleterequest.value.name.value)
		if rc then
			table.remove (array, idx ) 
			commit_interfaces()
			deleterequest.descr = "Interface deleted"
		else
			deleterequest.errtxt = "Interface not found"
		end
	else
		deleterequest.errtxt = "Failed to delete interface"
	end

	return deleterequest
end

get_status = function ()
	local status = {}
	status.filename = cfe({ value=filename, label="Interfaces file" })
	status.iproute = cfe({ type="longtext", label="ip route" })
	status.ipaddr = cfe({ type="longtext", label="ip addr" })
	status.iptunnel = cfe({ type="longtext", label="ip tunnel" })

	if not fs.is_file(filename) then
		status.filename.errtxt = "File not found"
	end
	local cmd = path.."ip route"
	local f = io.popen(cmd)
	status.iproute.value = f:read("*a")
	f:close()
	cmd = path.."ip addr"
	f = io.popen(cmd)
	status.ipaddr.value = f:read("*a")
	f:close()
	cmd = path.."ip tunnel"
	f = io.popen(cmd)
	status.iptunnel.value = f:read("*a")
	f:close()

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

get_file = function ()
	return modelfunctions.getfiledetails(filename)
end

write_file = function (self, newfile)
	array = nil
	return modelfunctions.setfiledetails(self, newfile, {filename})
end

get_interfaces = function()
	local cmd = path.."ip addr"
	local f = io.popen(cmd)
	local ipaddr = f:read("*a")
	f:close()
	-- now parse the result to find the interfaces
	local retval = {}
	for line in string.gmatch(ipaddr, "[^\n]*\n?") do
		if string.find(line, "^%d+:%s+") then
			local interface=string.match(line, "^%d+:%s+([^:@]+)")
			retval[#retval+1] = interface
		end
	end
	return cfe({ type="list", value=retval, label="IP Interfaces" })
end

get_addresses = function()
	local cmd = path.."ip addr"
	local f = io.popen(cmd)
	local ipaddr = f:read("*a")
	f:close()
	-- now parse the result to find the interfaces and IP addresses
	local retval = {}
	local interface
	for line in string.gmatch(ipaddr, "[^\n]*\n?") do
		if string.find(line, "^%d+:%s+") then
			interface=string.match(line, "^%d+:%s+([^:@]+)")
		elseif string.find(line, "^%s*inet%s") then
			table.insert(retval, {interface=interface, ipaddr=string.match(line, "^%s*inet%s+([%d%.]+)")})
		end
	end
	return cfe({ type="structure", value=retval, label="Interface IP Addresses" })
end

get_ifup_by_name = function(self, clientdata)
	local result = {}
	result.name = cfe({ type="select", value=clientdata.name or "", label="Interface Name", option=list_interfaces() })

	return cfe({ type="group", value=result, label="Interface Name" })
end

ifup_by_name = function (self, ifuprequest)
	local success = modelfunctions.validateselect(ifuprequest.value.name)
	if success then
		name = ifuprequest.value.name.value or ""
		local cmd = path.."ifup "..format.escapespecialcharacters(name).." 2>&1"
		local f = io.popen(cmd)
		ifuprequest.descr = f:read("*a")
		f:close()

		if ifuprequest.descr == "" then
			ifuprequest.descr = "Interface up"
		end
	else
		ifuprequest.errtxt = "Failed ifup"
	end

	return ifuprequest
end

get_ifdown_by_name = function(self, clientdata)
	local result = {}
	result.name = cfe({ type="select", value=clientdata.name or "", label="Interface Name", option=list_interfaces() })

	return cfe({ type="group", value=result, label="Interface Name" })
end

ifdown_by_name = function (self, ifdownrequest)
	local success = modelfunctions.validateselect(ifdownrequest.value.name)
	if success then
		name = ifdownrequest.value.name.value or ""
		local cmd = path.."ifdown "..format.escapespecialcharacters(name).." 2>&1"
		local f = io.popen(cmd)
		ifdownrequest.descr = f:read("*a")
		f:close()

		if ifdownrequest.descr == "" then
			ifdownrequest.descr = "Interface down"
		end
	else
		ifdownrequest.errtxt = "Failed ifup"
	end

	return ifdownrequest
end

get_restartnetworking = function(self, clientdata)
	local actions = {}
	actions[1] = "restart"
	local service = cfe({ type="hidden", value=servicename, label="Service Name" })
	local startstop = cfe({ type="group", label="Restart Networking", value={servicename=service}, option=actions })

	return startstop
end

restartnetworking = function(self, startstop)
	return modelfunctions.startstop_service(startstop, "restart")
end