fetchmail-model.lua 13.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
module(..., package.seeall)

require("fs")
require("procps")
require("getopts")
require("format")
require("daemoncontrol")
require("validator")

local processname = "fetchmail"
local configfile = "/root/.fetchmailrc"
local config = {}

local function get_version()
Mika Havela's avatar
Mika Havela committed
15 16
	local cmd_output_result, cmd_output_error
	local cmd = "/sbin/apk_version -vs " .. processname .." 2>/dev/null"
17
	local f = io.popen( cmd )
Mika Havela's avatar
Mika Havela committed
18 19 20 21 22 23
	local cmdresult = f:read("*l")
	if (cmdresult) and (#cmdresult > 0) then
		cmd_output_result = string.match(cmdresult,"^%S*") or "Unknown"
	else
		cmd_output_error = "Program not installed"
	end	
24
	f:close()
Mika Havela's avatar
Mika Havela committed
25
	return cmd_output_result,cmd_output_error
26 27 28 29 30 31 32 33 34 35 36 37 38 39
end

local function getloglevels()
	local loglevels = {}
	for i=1,8 do
		table.insert(loglevels,i)
	end
	return loglevels
end
local function getmethods()
	local methods = {"pop3","imap","pop3domain", }
	return methods
end

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
local function getmailboxes(t)
	local objects = cfe({})
	objects.label = "Mailbox " .. tostring(t["RBOX"])
	objects.method = cfe({ 
		name="method",
		label = "Method",
		type = "select",
		value = t["METHOD"],
		option = getmethods(),
		})
	objects.disabled = cfe({ 
		name="disabled",
		type="checkbox",
		label = "Disabled",
		checked = t["DISABLED"],
		})
	objects.remotehost = cfe({ 
		name="remotehost",
		label = "RemoteHost",
		value = t["RHOST"],
		})
	objects.remotemailbox = cfe({ 
		name="remotemailbox",
		label = "Mailbox",
		value = t["RBOX"],
		})
	objects.remotepassword = cfe({ 
		name="remotepassword",
		label = "Password",
		type = "passwd",
		value = t["PASSWD"],
		})
	objects.localhost = cfe({ 
		name="localhost",
		label = "LocalHost",
		value = t["LHOST"],
		})
	objects.localmailbox = cfe({ 
		name="localmailbox",
		label = "LocalMailbox",
		value = t["LBOX"],
		})
	objects.localdomain = cfe({ 
		name="localdomain",
		label = "LocalDomain",
		value = t["DOMAIN"],
		})
	return objects
88 89
end

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
local function read_config()
--[[
imap/pop3 lines are:
1    2      3        4       5  6   7        8       9        10
poll <host> protocol <proto> no dns username <uname> password <passwd>
11 12             13       14         15 16      17
is <localmailbox> smtphost <desthost> no rewrite fetchall

pop3domain lines are:
1    2      3             4        5        6    7  8   9        10      11       12
poll <host> localdomainst <domain> protocol pop3 no dns username <uname> password <passwd>
13 14 15   16       17         18          19       20 21      22
to *  here smtphost <desthost> smtpaddress <domain> no rewrite fetchall

etrn is:
1    2      3        4    5          6
pool <host> protocol etrn smtpdomain <mydomain>
--]]
108
	local mailboxes = {}
109 110 111 112 113 114
	local configcontent_postmaster = {}
	local configcontent_etrn = {}
	local path = configfile
	local valid = nil
	configcontenttable = fs.read_file_as_array(path) or {}
	for k,v in pairs(configcontenttable) do
115
		if (string.match(v, "^%s*#Begin Fetchmail")) then valid=1 end
116
		if (valid) then
117
			-- 
118 119 120 121 122 123
			local DISABLED = string.match(v, "^%s*(#)")

			-- Set parameters for POP3 or IMAP
			local val = {RHOST=2, CHECK=9 ,METHOD=4, RBOX=8, PASSWD=10, LBOX=12, LHOST=14}
			local configcontent = {}
			configcontent[k] = {}
124
			configcontent[k]["DISABLED"] = DISABLED
125 126 127 128 129 130 131 132 133
			for kk,vv in pairs(val) do
				configcontent[k][kk] = tostring(string.match(v,"^%s*" .. string.rep("%S*%s*",vv-1) .. "(%S*)%s*"))
			end
			-- Remove quotes from passwords
			if (configcontent[k]["PASSWD"]) then
				configcontent[k]["PASSWD"] = string.match(configcontent[k]["PASSWD"], "^\"(.-)\"")
			end
			-- Check if row is valid config
			if (configcontent[k]["CHECK"]) and (string.lower(configcontent[k]["CHECK"]) == "password") then 
134
				table.insert(mailboxes,getmailboxes(configcontent[k])) 
135 136 137 138 139 140
			end

			-- Set parameters for POP3domain
			local val = {RHOST=2, METHOD=6, RBOX=10, CHECK=11, PASSWD=12, LHOST=17, DOMAIN=19,}
			local configcontent = {}
			configcontent[k] = {}
141
			configcontent[k]["DISABLED"] = DISABLED
142 143 144
			for kk,vv in pairs(val) do
				configcontent[k][kk] = tostring(string.match(v,"^%s*" .. string.rep("%S*%s*",vv-1) .. "(%S*)%s*"))
			end
145 146
			-- Display this config as Method=pop3domain (as the current options in the view)
			configcontent[k]["METHOD"] = "pop3domain"
147 148 149 150 151 152
			-- Remove quotes from passwords
			if (configcontent[k]["PASSWD"]) then
				configcontent[k]["PASSWD"] = string.match(configcontent[k]["PASSWD"], "^\"(.-)\"")
			end
			-- Check if row is valid config
			if (configcontent[k]["CHECK"]) and (string.lower(configcontent[k]["CHECK"]) == "password") then 
153
				table.insert(mailboxes,getmailboxes(configcontent[k])) 
154 155 156 157 158 159
			end

			-- Set parameters for etrn
			local val = {ETRNSMTPHOST=2, CHECK=4, ETRNDOMAIN=6}
			local configcontent = {}
			configcontent[k] = {}
160
			configcontent[k]["DISABLED"] = DISABLED
161 162 163 164 165 166 167 168 169 170 171 172
			for kk,vv in pairs(val) do
				configcontent[k][kk] = tostring(string.match(v,"^%s*" .. string.rep("%S*%s*",vv-1) .. "(%S*)%s*"))
			end
			-- Check if row is valid config
			if (configcontent[k]["CHECK"]) and (string.lower(configcontent[k]["CHECK"]) == "etrn") then 
				configcontent_etrn=configcontent[k]
			end

			-- Set parameters for postmaster
			local val = {CHECK=2, POSTMASTER=3}
			local configcontent = {}
			configcontent[k] = {}
173
			configcontent[k]["DISABLED"] = DISABLED
174 175 176 177 178 179 180 181 182
			for kk,vv in pairs(val) do
				configcontent[k][kk] = tostring(string.match(v,"^%s*" .. string.rep("%S*%s*",vv-1) .. "(%S*)%s*"))
			end
			-- Check if row is valid config
			if (configcontent[k]["CHECK"]) and (string.lower(configcontent[k]["CHECK"]) == "postmaster") then 
				configcontent_postmaster=configcontent[k]
			end

		end
183
		if (string.match(v, "^%s*#End Fetchmail")) then valid=nil end
184
	end
185 186
	-- Create one empty record so that user can add settings
	table.insert(mailboxes,getmailboxes({})) 
187
	return mailboxes,configcontent_postmaster,configcontent_etrn
188 189

end
Mika Havela's avatar
Mika Havela committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

local function autostarts()
	local cmd_output_result, cmd_output_error
	local cmd = "/sbin/rc_status | egrep '^S' | egrep '" .. processname .."' 2>/dev/null"
	local f = io.popen( cmd )
	local cmdresult = f:read("*a")
	if (cmdresult) and (#cmdresult > 0) then
		cmd_output_result = "Process will autostart at next boot (at sequence '" .. string.match(cmdresult,"^%a+(%d%d)") .. "')"
	else
		cmd_output_error = "Not programmed to autostart"
	end	
	f:close()
	return cmd_output_result,cmd_output_error
end

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
-- ################################################################################
-- PUBLIC FUNCTIONS

function startstop_service ( self, action )
	local cmd = action.value
	local cmdresult,cmdmessage,cmderror,cmdaction = daemoncontrol.daemoncontrol(processname, cmd)
	action.descr=cmdmessage
	action.errtxt=cmderror
	-- Reporting back (true|false, the original acition)
	return cmdresult,action
end

function getstatus()
	local opts = getconfig()
	local status = {}
Mika Havela's avatar
Mika Havela committed
220 221

	local value, errtxt = get_version()
222 223
	status.version = cfe({ name = "version",
		label="Program version",
Mika Havela's avatar
Mika Havela committed
224 225
		value=value,
		errtxt=errtxt,
226
		 })
Mika Havela's avatar
Mika Havela committed
227

228 229 230 231
	status.status = cfe({ name="status",
		label="Program status",
		value=procps.pidof(processname),
		})
Mika Havela's avatar
Mika Havela committed
232

233 234 235 236 237
	status.configfile = cfe({ name="configfile",
		label="Config file",
		value=configfile,
		})

Mika Havela's avatar
Mika Havela committed
238 239 240 241 242 243 244
	local autostart_sequense, autostart_errtxt = autostarts()
	status.autostart = cfe({ name="autostart",
		label="Autostart sequence",
		value=autostart_sequense,
		errtxt=autostart_errtxt,
		})

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
--[[
	if (opts["remotelogging"]) and not ((opts["remotelogging"]["value"] ~= "") and not (opts["localandnetworklog"]["value"])) then
		status.logfile = cfe({ name="logfile",
			label="Locally logging to",
			value=opts["logfile"]["value"],
			})
	end
	if (opts["SYSLOGD_OPTS"]) and (opts["SYSLOGD_OPTS"]["-R"]) and (opts["SYSLOGD_OPTS"]["-R"] ~= "") then
		status.remote = cfe({ name="remotelogging",
			label="Remote logging to",
			value=opts["SYSLOGD_OPTS"]["-R"],
			})
	end
--]]
	return status
end

function get_filedetails()
	local path = configfile
	local file = {}
	local filedetails = {}
	local config = {}
	local filenameerrtxt
	if (fs.is_file(path)) then
		filedetails = fs.stat(path)
		config = getconfig(path)
	else
		config = {}
		config.filename = {}
		config["filename"]["errtxt"]="Config file '".. path .. "' is missing!"
	end

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

	-- Sum all errors into one cfe
	local sumerrors = ""
	for k,v in pairs(config) do
Mika Havela's avatar
Mika Havela committed
303
		if (config[k]) and (config[k]["errtxt"]) and (config[k]["errtxt"] ~= "") then	
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
			sumerrors = sumerrors .. config[k]["errtxt"] .. "\n"
		end
	end
	if (sumerrors ~= "") then
		file["sumerrors"] = cfe ({ 
			name="sumerrors",
			label = "Configuration errors",
			errtxt = string.match(sumerrors, "(.-)\n$"),
			})
	end

	return file
end
function getconfig()
	local config = {}
319
	local mailboxes,configcontent_postmaster,configcontent_etrn = read_config()
320
	if not (fs.is_file(configfile)) then
321 322 323
		config["configfile"] = "Config file '".. configfile .. "' is missing!"
	end
	
324 325 326 327 328 329 330
	config["debug"] = cfe({ 
		name="debug",
		label = "Debug info",
		type = "longtext",
		value = configcontent,
		})

331 332 333 334 335 336 337 338 339 340 341 342 343


	-- Next section selects which configurations we should show to the user
	config["freq"] = cfe({ 
		name="freq",
		label = "Check mail once every",
		type = "select",
		value = "123",
		option = {"15min", "hour","day",},
		})
	config["mailboxes"] = cfe({ 
		name="mailboxes",
		label = "Mailboxes",
344
		value = mailboxes,
345 346 347 348
		})
	config["postmaster"] = cfe({ 
		name="postmaster",
		label = "Postmaster",
349
		value = configcontent_postmaster["POSTMASTER"],
350 351 352 353
		})
	config["etrnremote"] = cfe({ 
		name="etrnremote",
		label = "Remote server",
354
		value = configcontent_etrn["ETRNSMTPHOST"],
355 356 357 358
		})
	config["etrnquedomain"] = cfe({ 
		name="etrnquedomain",
		label = "Queued domain",
359
		value = configcontent_etrn["ETRNDOMAIN"],
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
		})

--[[

	-- Next section is to print errormessages when configs are wrong
	if (configcontent["SYSLOGD_OPTS"]["-l"]) and 
	  ((tonumber(configcontent["SYSLOGD_OPTS"]["-l"]) == nil) or (tonumber(configcontent["SYSLOGD_OPTS"]["-l"]) > 8))  then
		config["loglevel"]["errtxt"] = "Log value is out of range!\nCurrent value in config is '" ..  
			configcontent["SYSLOGD_OPTS"]["-l"] .. 
			"' - This is invalid!\nPlease select one of the above and save your changes."
		table.insert(config["loglevel"]["option"], tonumber(configcontent["SYSLOGD_OPTS"]["-l"]))
	end

	if (configcontent["SYSLOGD_OPTS"]["-L"] ~= nil) and ((configcontent["SYSLOGD_OPTS"]["-R"] == nil) or (configcontent["SYSLOGD_OPTS"]["-R"] == "")) then
		config["localandnetworklog"]["errtxt"] = "Logging to local and network (-L) is not possible unless you define a host (-R) for remote logging or remove this option."
	end

	-- Sum all errors into one cfe
	local sumerrors = ""
	for k,v in pairs(config) do
		if (config[k]["errtxt"] ~= "") then	
			sumerrors = sumerrors .. config[k]["errtxt"] .. "\n"
		end
	end
	if (sumerrors ~= "") then
		config["sumerrors"] = cfe ({ 
			name="sumerrors",
			label = "Configuration errors",
			errtxt = sumerrors,
			})
	end

--]]

	return config
end

-- IMPORTANT! This function is a exception! It's not fed with CFE's
-- Parameter should be one of the ones defined in the variable 'variabletranslator'.
-- value should be whatever the new value should be.
function setconfigs(self,parameter,value)
	-- Set variables
--[[
	local variable = "SYSLOGD_OPTS"
	local variabletranslator = ({ 
		logfile = "-O", 
		loglevel = "-l",
		smallerlogs = "-S",
		maxsize = "-s",
		numrotate = "-b",
		localandnetworklog = "-L",
		remotelogging = "-R",
		})
	cmdparameter = variabletranslator[parameter]

	-- Report a error if someone tryes to use a invalid parameter
	if not (cmdparameter) then 
		local availablevariables = ""
		for k,v in pairs(variabletranslator) do
			availablevariables = k .. ", " .. availablevariables
		end
		parameter = parameter or ""
		return false, cfe({ 
			name="syslog.model.setconfigs()", 
			errtxt="'" .. parameter .. "' is not a valid parameter!\nValid options are: " .. availablevariables,
			})
	end

	--TODO: Validate so that user cant add values with '-' (could cause major breakage next time you do getopts)

	-- This config-file only accepts one type of parameters (report error if someone uses wrong parameter)
	if not (string.find(cmdparameter, "-%a$")) then 
		return false, cfe({ 
			name="syslog.model.setconfigs()", 
			errtxt="Parameter must be formated '-a' (where a is one upper/lowercase letter [a-z])",
			})
	end

	-- Validate userinput (if valid path/filename)
	if (value) and (cmdparameter == "-O") then 
		local cmdresult, cmdmessage = validator.is_valid_filename(value, "/var/log" )
		if not (cmdresult) then
			return false, cfe({ 
				name="syslog.model.setconfigs()", 
				errtxt=cmdmessage,
				})
		end
	end

	-- Validate userinput (Has the user entered a valid hostname and/or port)
	if (value) and (cmdparameter == "-R") then 
		local hostport = format.string_to_table(value, ":")
		local host = hostport[1]
		local port = hostport[2]
		if (port) and not (validator.is_port(port)) then
			return false, cfe({ 
				name="syslog.model.setconfigs.getopts.setoptsinfile()", 
				errtxt="You entered '" .. tostring(port) .. "' as port - This is not valid!",
				})			
		end
	end

	-- Set/Unset checkbox variables
	if (value) and ((cmdparameter == "-S") or (cmdparameter == "-L")) then value = "" end

	local cmdresult, cmdmessage, cmderror = getopts.setoptsinfile(configfile,variable,cmdparameter,value)
	if (cmderror) then
		return false, cfe({ 
			name="syslog.model.setconfigs.getopts.setoptsinfile()", 
			errtxt=cmderror,
			})
	end
	return true, cfe({ 
			name="syslog.model.setconfigs()", 
			value=cmdmessage,
			})
--]]
end

-- modifications should be a CFE
function update_filecontent (self, modifications)
	local path = configfile
	local file_result,err = fs.write_file(path, format.dostounix(modifications))
	return file_result, err
end