weblog-model.lua 48.8 KB
Newer Older
Ted Trask's avatar
Ted Trask committed
1 2 3 4
module(..., package.seeall)

-- Load libraries
require("modelfunctions")
5 6 7
fs = require("acf.fs")
format = require("acf.format")
validator = require("acf.validator")
Ted Trask's avatar
Ted Trask committed
8 9
require("luasql.postgres")

10
local DatabaseName = "webproxylog"
Ted Trask's avatar
Ted Trask committed
11 12 13 14 15 16
local DatabaseOwner = "weblogowner"
local DatabaseUser = "webloguser"

local path = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin "
local env
local con
17
local configfile = "/etc/weblog/weblog.conf"
Ted Trask's avatar
Ted Trask committed
18 19
local configcontent = fs.read_file(configfile) or ""
local config = format.parse_ini_file(configcontent, "") or {}
20
local goodwordslist = "/etc/weblog/goodwords"
21
local goodwords
22
local badwordslist = "/etc/weblog/badwords"
23
local badwords
Ted Trask's avatar
Ted Trask committed
24
local ignorewordslist = "/etc/weblog/ignorewords"
25
local ignorewords
Ted Trask's avatar
Ted Trask committed
26
local files = {badwordslist, goodwordslist, ignorewordslist, configfile}
Ted Trask's avatar
Ted Trask committed
27 28

local database_creation_script = {
29
	"CREATE TABLE dbhistlog (logdatetime timestamp(3) without time zone NOT NULL, msgtext text)",
30 31
	"CREATE TABLE pubweblog(sourcename character varying(40), clientip inet NOT NULL, clientuserid character varying(64) NOT NULL, logdatetime timestamp(3) without time zone NOT NULL, uri text NOT NULL, bytes bigint NOT NULL, reason text, score integer, shortreason text, badyesno int, deniedyesno int, bypassyesno int, wordloc text, goodwordloc text, selected boolean, id serial)",
	"CREATE TABLE pubweblog_history(sourcename character varying(40), clientip inet NOT NULL, clientuserid character varying(64) NOT NULL, logdatetime timestamp(3) without time zone NOT NULL, uri text NOT NULL, bytes bigint NOT NULL, reason text, score integer, shortreason text, badyesno int, deniedyesno int, bypassyesno int, wordloc text, goodwordloc text, selected boolean, id int)",
32
	"CREATE TABLE weblog(sourcename character varying(40), clientip inet NOT NULL, clientuserid character varying(64) NOT NULL, logdatetime timestamp(3) without time zone NOT NULL, uri text NOT NULL, bytes bigint NOT NULL, reason text, score integer, shortreason text, badyesno int, deniedyesno int, bypassyesno int, wordloc text, goodwordloc text)",
Ted Trask's avatar
Ted Trask committed
33
	"CREATE TABLE source (sourcename character varying(40) NOT NULL, method character varying(100) NOT NULL, userid character varying(32), passwd character varying(255), source character varying(255) NOT NULL, tzislocal boolean, enabled boolean)",
34
	"CREATE TABLE usagestat (sourcename character varying(40) NOT NULL, date timestamp(0) without time zone NOT NULL, numrequest integer, numblock integer)",
Ted Trask's avatar
Ted Trask committed
35 36 37 38 39
	"ALTER TABLE ONLY source ADD CONSTRAINT source_pkey PRIMARY KEY (sourcename)",
	"CREATE INDEX dbhistlogdatetimeidx ON dbhistlog USING btree (logdatetime)",
	"CREATE INDEX pubweblogclientdateidx ON pubweblog USING btree (logdatetime, clientuserid)",
	"CREATE INDEX pubweblogclientuserididx ON pubweblog USING btree (clientuserid)",
	"CREATE INDEX pubwebloglogdatetimeidx ON pubweblog USING btree (logdatetime)",
40 41 42
	"CREATE INDEX pubweblog_historyclientdateidx ON pubweblog_history USING btree (logdatetime, clientuserid)",
	"CREATE INDEX pubweblog_historyclientuserididx ON pubweblog_history USING btree (clientuserid)",
	"CREATE INDEX pubweblog_historylogdatetimeidx ON pubweblog_history USING btree (logdatetime)",
43 44
	"GRANT SELECT ON dbhistlog TO "..DatabaseUser,
	"GRANT SELECT ON pubweblog TO "..DatabaseUser,
45
	"GRANT SELECT ON pubweblog_history TO "..DatabaseUser,
46 47
	"GRANT SELECT, UPDATE, INSERT, DELETE ON source TO "..DatabaseUser,
	"GRANT SELECT ON usagestat TO "..DatabaseUser,
Ted Trask's avatar
Ted Trask committed
48 49 50 51 52 53 54 55 56 57 58 59 60
}

-- ################################################################################
-- DATABASE FUNCTIONS

local function assert (v, m)
	if not v then
		m = m or "Assertion failed!"
		error(m, 0)
	end
	return v, m
end

61 62
-- Escape special characters in sql statements and truncate to length
local escape = function(sql, length)
Ted Trask's avatar
Ted Trask committed
63
	sql = sql or ""
64
	if length then sql = string.sub(sql, 1, length) end
65
	return string.gsub(sql, "'", "''")
Ted Trask's avatar
Ted Trask committed
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
end

-- List the postgres databases on this system
local listdatabases = function()
	local dbs = {}
	local cmd = path.."psql -U postgres -tl 2>&1"
	local f = io.popen(cmd)
	local result = f:read("*a") or ""
	f:close()
	for line in string.gmatch(result, "[^\n]+") do
		dbs[#dbs+1] = string.match(line, "^ (%S+)")
	end
	return dbs
end

-- Create the necessary database
local createdatabase = function(password)
	local result = {}

	-- First, create the users
	local cmd = path..'psql -U postgres -c "CREATE USER '..DatabaseOwner..' WITH PASSWORD \''..password..'\'" 2>&1'
	local f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
	cmd = path..'psql -U postgres -c "CREATE USER '..DatabaseUser..'" 2>&1'
	f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
Timo Teräs's avatar
Timo Teräs committed
94

Ted Trask's avatar
Ted Trask committed
95 96 97 98 99
	-- Create the database
	cmd = path..'psql -U postgres -c "CREATE DATABASE '..DatabaseName..' WITH OWNER '..DatabaseOwner..'" 2>&1'
	f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
Timo Teräs's avatar
Timo Teräs committed
100

Ted Trask's avatar
Ted Trask committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	return table.concat(result, "\n")
end

-- Delete the database and roles
local deletedatabase = function()
	local result = {}

	local cmd = path..'psql -U postgres -c "DROP DATABASE '..DatabaseName..'" 2>&1'
	local f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
	cmd = path..'psql -U postgres -c "DROP ROLE '..DatabaseUser..'" 2>&1'
	f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
	cmd = path..'psql -U postgres -c "DROP ROLE '..DatabaseOwner..'" 2>&1'
	f = io.popen(cmd)
	table.insert(result, f:read("*a"))
	f:close()
Timo Teräs's avatar
Timo Teräs committed
120

Ted Trask's avatar
Ted Trask committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	return table.concat(result, "\n")
end

-- Run an SQL script
local runSQLscript = function(filename)
	-- Create the database
	local cmd = path..'psql -U postgres -f "'..filename..'" '..DatabaseName..' 2>&1'
	local f = io.popen(cmd)
	local result = f:read("*a") or ""
	f:close()
	-- Create the tables
	print (result)
	return result
end

-- Create the database and tables
137
-- pg_dump -U postgres -c webproxylog > makeweblog.postgres
Ted Trask's avatar
Ted Trask committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
--runSQLscript("/root/work/weblog/makeweblog.postgres")

local databaseconnect = function(username, password)
	if not con then
		-- create environment object
		env = assert (luasql.postgres())
		-- connect to data source
		con = assert (env:connect(DatabaseName, username, password))
	end
end

local databasedisconnect = function()
	if env then
		env:close()
		env = nil
	end
	if con then
		con:close()
		con = nil
	end
end

local logme = function(message)
161
	local sql = string.format("INSERT INTO dbhistlog VALUES ('now', '%s')", escape(message))
Ted Trask's avatar
Ted Trask committed
162 163 164 165 166 167
	local res = assert (con:execute(sql))
end

local listhistorylogentries = function()
	local entries = {}
	-- retrieve a cursor
Timo Teräs's avatar
Timo Teräs committed
168
	cur = assert (con:execute"SELECT logdatetime, msgtext from dbhistlog ORDER BY logdatetime")
Ted Trask's avatar
Ted Trask committed
169 170 171 172 173 174 175 176 177 178
	row = cur:fetch ({}, "a")
	while row do
		entries[#entries+1] = {logdatetime = row.logdatetime, msgtext = row.msgtext}
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
	return entries
end

179
local importlogentry = function(entry, sourcename)
180
	if entry then
181
		local sql = string.format("INSERT INTO weblog VALUES ('%s', '%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')",
182
			escape(sourcename), escape(entry.clientip), escape(entry.clientuserid, 64):lower(),
183
			escape(entry.logdatetime), escape(entry.URL), escape(entry.bytes), escape(entry.reason), escape(entry.score or "0"), escape(entry.shortreason), escape(entry.badyesno or "0"), escape(entry.deniedyesno or "0"), escape(entry.bypassyesno or "0"), escape(entry.wordloc), escape(entry.goodwordloc))
Ted Trask's avatar
Ted Trask committed
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
		local res = assert (con:execute(sql))
	end
end

local listsourceentries = function(sourcename)
	local sources = {}
	-- retrieve a cursor
	local sql = "SELECT sourcename, method, userid, passwd, source, tzislocal, enabled FROM source"
	if sourcename then
		sql = sql .. " WHERE sourcename='" .. escape(sourcename) .. "'"
	end
	sql = sql .. " ORDER BY sourcename"
	cur = assert (con:execute(sql))
	row = cur:fetch ({}, "a")
	while row do
		row.tzislocal = (row.tzislocal == "t")
		row.enabled = (row.enabled == "t")
		sources[#sources+1] = row
		row = cur:fetch ({}, "a")
	end
	cur:close()
	return sources
end

local importsourceentry = function(source)
	local sql = string.format("INSERT INTO source VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
		escape(source.sourcename), escape(source.method), escape(source.userid), escape(source.passwd),
		escape(source.source), escape(tostring(source.tzislocal):upper()), escape(tostring(source.enabled):upper()))
	local res = assert (con:execute(sql))
	return res
end

local updatesourceentry = function(source)
	local sql = string.format("UPDATE source SET method='%s', userid='%s', passwd='%s', source='%s', tzislocal='%s', enabled='%s' WHERE sourcename='%s'",
		escape(source.method), escape(source.userid), escape(source.passwd), escape(source.source),
		escape(tostring(source.tzislocal):upper()), escape(tostring(source.enabled):upper()),
		escape(source.sourcename))
	local res = assert (con:execute(sql))
	return res
end

local deletesourceentry = function(sourcename)
	local sql = string.format("DELETE FROM source WHERE sourcename='%s'", escape(sourcename))
	local res = assert (con:execute(sql))
	return res
end

-- Generate usage statistics from weblog and blocklog
local updateusagestats = function()
	-- update the usagestat table from weblog
	-- (will result in multiple rows where logs rotated on partial hours)
235 236 237
	local sql = "insert into usagestat select weblog.sourcename, " ..
		"date_trunc('hour', weblog.logdatetime) as date, " ..
		"count(*), SUM(deniedyesno) from weblog group by sourcename,date"
Ted Trask's avatar
Ted Trask committed
238 239 240
	local res = assert (con:execute(sql))
end

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
-- Move weblog into pubweblog, and truncate weblog
local importpubweblog = function()
	local sql = "ANALYZE"
	res = assert (con:execute(sql))

	-- Move weblog to pubweblog
	sql= "insert into pubweblog select * from weblog"
	res = assert (con:execute(sql))
	logme("importpubweblog imported " .. res .. " new rows into database.")

	-- Truncate the staging table
	assert (con:execute("truncate weblog"))
	logme("truncated staging table")
end

Ted Trask's avatar
Ted Trask committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
-- Delete useage stats from more than a year ago
local groomusagestat = function()
	local res = assert (con:execute("delete from usagestat where " ..
		"date < (now() - INTERVAL '1 year')"))
	logme("removed " .. res .. " old usage status lines")
end

-- Delete history log information from more than a month ago
local groomdbhistlog = function()
	local res = assert (con:execute("delete from dbhistlog where " ..
		"logdatetime < (now() - INTERVAL '1 month')"))
	logme("removed " .. res .. " old dbhistlog lines")
end

-- Delete old junk from pub tables
local groompublogs = function()
	local purgedays = config.purgedays or 30
Ted Trask's avatar
Ted Trask committed
273

Ted Trask's avatar
Ted Trask committed
274 275 276
	local now = os.time()

	local temp = os.date("%Y-%m-%d %H:%M:%S", now - purgedays*86400)
277
	logme("Purgedate is " .. temp .. ". Nothing will exist in pubweblog from before purgedate.")
Ted Trask's avatar
Ted Trask committed
278

279 280
	-- Move flagged records to histoy and then purge anything older than purgedate
	sql = "Insert into pubweblog_history select * from pubweblog where logdatetime < '" .. temp .."' and (badyesno > 0 or deniedyesno > 0 or bypassyesno > 0 or selected = 'true')"
Ted Trask's avatar
Ted Trask committed
281
	res = assert (con:execute(sql))
282
	logme("Moved " .. res .. " old records to history")
Ted Trask's avatar
Ted Trask committed
283

284
	sql = "Delete from pubweblog where logdatetime < '" .. temp .."'"
Ted Trask's avatar
Ted Trask committed
285
	res = assert (con:execute(sql))
286 287 288 289 290
	logme("Deleted " .. res .. " old records from pubweblog")
	
	sql = "delete from pubweblog_history where logdatetime < (now() - INTERVAL '1 year')"
	res = assert (con:execute(sql))
	logme("Deleted " .. res .. " old records from pubweblog_history")
Ted Trask's avatar
Ted Trask committed
291 292
end

293
local generatewhereclause = function(clientuserid, starttime, endtime, clientip, badyesno, deniedyesno, bypassyesno, score, urisearch, selected)
Ted Trask's avatar
Ted Trask committed
294 295 296
	local sql = ""
	local where = {}
	if clientuserid and clientuserid ~= "" then
297
		where[#where+1] = "clientuserid LIKE '%"..escape(clientuserid).."%'"
Ted Trask's avatar
Ted Trask committed
298 299 300 301 302 303 304 305 306 307
	end
	if starttime and starttime ~= "" then
		where[#where+1] = "logdatetime >= '"..escape(starttime).."'"
	end
	if endtime and endtime ~= "" then
		where[#where+1] = "logdatetime <= '"..escape(endtime).."'"
	end
	if clientip and clientip ~= "" then
		where[#where+1] = "clientip = '"..escape(clientip).."'"
	end
308 309
	if badyesno then
		where[#where+1] = "badyesno = '1'"
310
	end
311 312
	if deniedyesno then
		where[#where+1] = "deniedyesno = '1'"
313
	end
314 315
	if bypassyesno then
		where[#where+1] = "bypassyesno = '1'"
316 317 318 319
	end
	if score and score ~= "" then
		where[#where+1] = "score >= '"..escape(score).."'"
	end
Ted Trask's avatar
Ted Trask committed
320
	if urisearch and urisearch ~= "" then
321 322
	    	where[#where+1] = "lower(uri) LIKE '%"..escape(urisearch).."%'"
	end
323
	if selected then
324 325
		where[#where+1] = "selected = 'true'"
	end
Ted Trask's avatar
Ted Trask committed
326

Ted Trask's avatar
Ted Trask committed
327 328 329
	if #where > 0 then
		sql = " WHERE " .. table.concat(where, " AND ")
	end
Ted Trask's avatar
Ted Trask committed
330

Ted Trask's avatar
Ted Trask committed
331 332 333
	return sql
end

334
local listlogentries = function(activelog, clientuserid, starttime, endtime, clientip, badyesno, deniedyesno, bypassyesno, score, urisearch, sortby, selected)
Ted Trask's avatar
Ted Trask committed
335 336
	local entries = {}
	-- retrieve a cursor
337 338 339
	local sql = "SELECT * FROM "..activelog
	sql = sql .. generatewhereclause(clientuserid, starttime, endtime, clientip, badyesno, deniedyesno, bypassyesno, score, urisearch, selected)
	sql = sql .. " ORDER BY "..sortby
Ted Trask's avatar
Ted Trask committed
340 341 342
	cur = assert (con:execute(sql))
	row = cur:fetch ({}, "a")
	while row do
Ted Trask's avatar
Ted Trask committed
343 344
		if config.shorturi == "true" then
			shorturi=string.gsub(row.uri, "[;?].*", "...")
345
		end
346
		entries[#entries+1] = {sourcename=row.sourcename, clientip=row.clientip, clientuserid=row.clientuserid, logdatetime=row.logdatetime, uri=row.uri, shorturi=shorturi, bytes=row.bytes, reason=row.reason, score=row.score, shortreason=row.shortreason, badyesno=row.badyesno, deniedyesno=row.deniedyesno, bypassyesno=row.bypassyesno, wordloc=row.wordloc, id=row.id, selected=row.selected }
347 348 349
		if (config.shortreason ~= "true") then
			entries[#entries].shortreason = nil
		end
Ted Trask's avatar
Ted Trask committed
350 351 352 353 354 355 356
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
	return entries
end

357
local groupflaggedlogentries = function(starttime, endtime, groupby)
358 359 360
	groupby = groupby or "clientuserid"
	local entries = {}
	-- retrieve a cursor
361 362 363 364 365 366
	--local sql = "SELECT "..groupby..", count(*) AS numblock, max(score) AS maxscore FROM pubweblog"
	local sql = "SELECT "..groupby..", COUNT(*) as numrecords, SUM(CASE WHEN (bypassyesno > '0' OR deniedyesno > '0' OR badyesno > '0') THEN 1 ELSE 0 END) as numflagged, sum(score) AS numhits, sum(CASE WHEN deniedyesno > '0' THEN 1 ELSE 0 END) AS numdenied, sum(CASE WHEN bypassyesno > '0' THEN 1 ELSE 0 END) AS numbypassed, max(score) as maxscore from pubweblog"
	--sql = sql .. generatewhereclause(nil, starttime, endtime) .. " AND deniedyesno > '0'"
	sql = sql .. generatewhereclause(nil, starttime, endtime)
	--sql = sql .. " GROUP BY "..groupby.. " ORDER BY numblock DESC"
	sql = sql .. " GROUP BY " ..groupby.. " ORDER BY numflagged DESC"
367 368 369
	cur = assert (con:execute(sql))
	row = cur:fetch ({}, "a")
	while row do
370 371
		--entries[#entries+1] = {numblock=row.numblock, maxscore=row.maxscore}
		entries[#entries+1] = {numrecords=row.numrecords, numflagged=row.numflagged, numhits=row.numhits, numdenied=row.numdenied, numbypassed=row.numbypassed, maxscore=row.maxscore}
372 373 374 375 376 377 378 379
		entries[#entries][groupby] = row[groupby]
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
	return entries
end

Ted Trask's avatar
Ted Trask committed
380 381 382 383
local listusagestats = function()
	local entries = {}
	-- retrieve a cursor
	local sql = "SELECT sourcename, date, sum(numrequest) AS numrequest, sum(numblock) AS numblock " ..
384
		"FROM usagestat GROUP BY sourcename, date ORDER BY date, sourcename"
Ted Trask's avatar
Ted Trask committed
385 386 387 388 389 390 391 392 393 394 395
	cur = assert (con:execute(sql))
	row = cur:fetch ({}, "a")
	while row do
		entries[#entries+1] = {sourcename=row.sourcename, date=row.date, numrequest=row.numrequest, numblock=row.numblock}
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
	return entries
end

396 397 398
local testdatabaseentry = function(datatype, value)
	local success = true
	local errtxt
399
	local sql = "CREATE TEMP TABLE testing ( test "..datatype.." DEFAULT '"..escape(value).."' ) ON COMMIT DROP"
400 401 402 403 404 405 406 407 408 409
	local res, err = pcall(function()
		assert (con:execute(sql))
	end)
	if not res then
		success = false
		errtxt = string.gsub(err or "", "\n.*", "")
	end
	return success, errtxt
end

410 411 412 413 414
local convertdatabaseentry = function(datatype, value)
	local success = true
	local errtxt
	local result = value
	local res, err = pcall(function()
415
		local sql = "CREATE TEMP TABLE testing ( test "..datatype.." )"
416
		assert (con:execute(sql))
417
		sql = "INSERT INTO testing VALUES ('"..escape(value).."')"
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
		assert (con:execute(sql))
		sql = "SELECT * FROM testing"
		local cur = assert (con:execute(sql))
		local row = cur:fetch ({}, "a")
		if row then
			result = row.test
		end
	end)
	if not res then
		success = false
		errtxt = string.gsub(err or "", "\n.*", "")
	end
	local res, err = pcall(function()
		local sql = "DROP TABLE testing"
		assert (con:execute(sql))
	end)
	return success, errtxt, result
end

Ted Trask's avatar
Ted Trask committed
437 438 439 440 441 442 443 444 445
local printtableentries = function(tablename)
	-- retrieve a cursor
	local count = 0
	cur = assert (con:execute("SELECT * from "..tablename))
	-- print all rows, the rows will be indexed by field names
	row = cur:fetch ({}, "a")
	while row do
		count = count + 1
		for name,val in pairs(row) do
Ted Trask's avatar
Ted Trask committed
446
			logevent(name.." = "..val..", ")
Ted Trask's avatar
Ted Trask committed
447 448 449 450 451
		end
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
Ted Trask's avatar
Ted Trask committed
452
	logevent("Table "..tablename.." contains "..count.." rows")
Ted Trask's avatar
Ted Trask committed
453 454 455 456 457
end

-- ################################################################################
-- LOG FILE FUNCTIONS

458
local function checkwords(logentry)
459 460
	local goodwordloc={}
	local badwordloc={}
461 462
	local wrdcnt=0
	local isbad=0
463

464
	--check for ignored records first
465
	for i,thisline in ipairs(ignorewords) do
466 467 468
		if not thisline then
			break
		end
469
		_,instcnt = string.lower(logentry.URL):gsub(thisline, " ")
470
		if instcnt ~= 0 then
471
			logentry.ignoreme = true
472
			--logme("ignoring...")
473
			break
474 475 476
		end
	end

477
	if not logentry.ignoreme then
478 479 480 481 482
		--proceed with record analysis
		for i,thisline in ipairs(badwords) do
			if not thisline then
				break
			end
Ted Trask's avatar
Ted Trask committed
483

484 485 486 487 488
			_,instcnt = string.lower(logentry.URL):gsub(thisline, " ")
			if instcnt ~= 0 then
				-- logme("instcnt =  "..instcnt)
				isbad=1
				wrdcnt= wrdcnt + instcnt
489
				badwordloc[#badwordloc+1] = thisline
490
			end
491
		end
Ted Trask's avatar
Ted Trask committed
492

493
		--check for DansGuardian actions
494
		if (logentry.reason and logentry.reason ~= "") then
Ted Trask's avatar
Ted Trask committed
495 496 497 498 499 500 501 502 503 504
			if string.find(logentry.reason,"DENIED") then
				-- logme("*Denied*")
				logentry.deniedyesno=1
			elseif string.find(logentry.URL,"GBYPASS") then
				-- logme("GBYPASS")
				logentry.bypassyesno=1
			elseif string.find(logentry.reason,"OVERRIDE") then
				-- logme("*OVERRIDE*")
				logentry.bypassyesno=1
			end
505
		end
506 507 508

		--check for Squark actions
		if (logentry.squarkaction and logentry.squarkaction ~= "") then
Ted Trask's avatar
Ted Trask committed
509 510 511 512 513 514
			--logme("squarkaction="..logentry.squarkaction)
			if string.find(logentry.squarkaction, "blocked") then
				logentry.deniedyesno=1
			elseif string.find(logentry.squarkaction,"overridden") then
				logentry.bypassyesno=1
			end
515 516
		end

517 518 519 520 521 522
		--check for Squark category
		if (logentry.squarkcategory and logentry.squarkcategory ~= "") then
			logentry.reason = logentry.squarkcategory
			logentry.shortreason = logentry.squarkcategory
		end

523 524 525 526 527 528 529
		for i,goodline in ipairs(goodwords) do
			if not goodline then
				break
			end
			_,instcnt = string.lower(logentry.URL):gsub(goodline, " ")
			--if string.find(logentry.URL,goodline) then
			if instcnt ~= 0 then
530
				if wrdcnt >= instcnt then
531
					wrdcnt = wrdcnt - instcnt
532 533
				else
					wrdcnt = 0
534
				end
535
				goodwordloc[#goodwordloc+1] = goodline
536
			end
537 538
		end
	end
Ted Trask's avatar
Ted Trask committed
539 540 541 542
	-- Reset bad to reduce number of bad hits if score is zero
	-- if wrdcnt == 0 then
	-- isbad=0
	-- end
543 544 545

	logentry.score=wrdcnt
	logentry.badyesno=isbad
546 547
	logentry.wordloc=table.concat(badwordloc,"|")
	logentry.gwordloc=table.concat(goodwordloc,"|")
548 549 550 551
end

local function parsesquidlog(line)
	-- Format of squid log (space separated):
552
	-- time elapsed remotehost code/status bytes method URL rfc931 peerstatus/peerhost ? squarkcategory/squarkaction
553 554 555 556 557 558
	local words = {}

	for word in string.gmatch(line, "%S+") do
		words[#words+1] = word
	end

559 560 561
	local logentry = {logdatetime=words[1],
		elapsed=words[2],
		clientip=words[3],
Ted Trask's avatar
Ted Trask committed
562 563
		code=string.match(words[4] or "", "^[^/]*"),
		status=string.match(words[4] or "", "[^/]*$"),
564
		bytes=words[5],
Ted Trask's avatar
Ted Trask committed
565
		method=words[6],
566
		URL=words[7],
567
		clientuserid=words[8],
Ted Trask's avatar
Ted Trask committed
568
		peerstatus=string.match(words[9] or "", "^[^/]*"),
569 570 571
		peerhost=string.match(words[9] or "", "[^/]*$"),
		squarkcategory=string.match(words[11] or "", "^[^,]*"),
		squarkaction=string.match(words[11] or "", "[^,]*$")}
Ted Trask's avatar
Ted Trask committed
572

573
	checkwords(logentry)
574

Natanael Copa's avatar
Natanael Copa committed
575 576 577 578 579 580
	-- Don't care about TCP_DENIED so apps like dropbox, nokia connection
	-- suite does not flood our logs.
	if logentry.code == nil or logentry.code == "TCP_DENIED" then
		return nil
	end

Ted Trask's avatar
Ted Trask committed
581 582
	-- Don't care about local requests (from DG) (this check also removes blank lines)
	if logentry.clientip and logentry.clientip ~= "127.0.0.1" then
583 584
		logentry.logdatetime = os.date("%Y-%m-%d %H:%M:%S", logentry.logdatetime)..string.match(logentry.logdatetime, "%..*")
		return logentry
Ted Trask's avatar
Ted Trask committed
585 586 587 588
	end
	return nil
end

589
local function parsedglog(line)
590
	local words = format.string_to_table(line, "\t")
591 592 593 594 595 596 597
	local logentry = {logdatetime=words[1],
			clientuserid=words[2],
			clientip=words[3],
			URL=words[4],
			reason=words[5],
			method=words[6],
			bytes=words[7],
598 599
			shortreason=words[9],
			deniedyesno=1}
Ted Trask's avatar
Ted Trask committed
600

601
	checkwords(logentry)
Ted Trask's avatar
Ted Trask committed
602 603 604 605 606

	if logentry.reason and logentry.reason ~= "" then
           	if logentry.shortreason == "" then
           		logentry.shortreason = logentry.reason
           	end
607
		--logentry.score = string.match(logentry.reason, "^.*: ([0-9]+) ")
608
		logentry.logdatetime = string.gsub(logentry.logdatetime, "%.", "-")
Ted Trask's avatar
Ted Trask committed
609 610 611 612 613
	   	return logentry
	end
	return nil
end

Ted Trask's avatar
Ted Trask committed
614 615 616 617 618 619 620 621 622
-- ################################################################################
-- DOWNLOAD FILE FUNCTIONS

-- must do apk_add wget first

local connecttosource = function(source, cookiesfile)
	local success = false
	logme("Connecting to source "..source.sourcename)
	if source.method == "http" or source.method == "https" then
623 624
		fs.write_file(cookiesfile, "password="..source.passwd.."&userid="..source.userid.."&Logon=Logon")
		local cmd = "wget -O - --no-check-certificate --save-cookies "..cookiesfile.." --keep-session-cookies --post-file '"..cookiesfile.."' '"..source.method.."://"..format.escapespecialcharacters(source.source).."/cgi-bin/acf/acf-util/logon/logon' 2>/dev/null"
Ted Trask's avatar
Ted Trask committed
625 626 627 628 629 630 631 632 633 634
		local f = io.popen(cmd)
		local resultpage = f:read("*a")
		f:close()
		if resultpage == "" then
			logme("Failed to connect to "..source.sourcename)
		elseif string.find(resultpage, "Log in") then
			logme("Failed to log in to "..source.sourcename)
		else
			success = true
		end
635 636
	elseif source.method == "local" then
		success = true
Ted Trask's avatar
Ted Trask committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650
	end
	return success
end

local getlogcandidates = function(source, cookiesfile)
	local candidates = {}
	if source.method == "http" or source.method == "https" then
		local cmd = "wget -O - --no-check-certificate --load-cookies "..cookiesfile.." '"..source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/status' 2>/dev/null"
		local f = io.popen(cmd)
		local resultpage = f:read("*a")
		f:close()
		for file in string.gmatch(resultpage, "download%?name=([^\"]+)") do
			candidates[#candidates+1] = file
		end
651 652
	elseif source.method == "local" then
		candidates = fs.find_files_as_array(nil, source.source)
Ted Trask's avatar
Ted Trask committed
653 654 655 656
	end
	return candidates
end

657 658
local openlogfile = function(source, cookiesfile, logfile)
	local handle
Ted Trask's avatar
Ted Trask committed
659 660
	if source.method == "http" or source.method == "https" then
		local cmd = "wget -O - --no-check-certificate --load-cookies "..cookiesfile.." --post-data 'name="..logfile.."' '"..source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/download' 2>/dev/null"
661 662 663
		if string.find(logfile, "%.gz$") then
			cmd = cmd.." | gunzip -c"
		end
664
		handle = io.popen(cmd)
665
	elseif source.method == "local" then
666 667
		if string.find(logfile, "%.gz$") then
			local cmd = "gunzip -c "..logfile
668
			handle = io.popen(cmd)
669
		else
670
			handle = io.open(logfile)
671
		end
Ted Trask's avatar
Ted Trask committed
672
	end
673
	return handle
Ted Trask's avatar
Ted Trask committed
674 675 676 677 678 679 680
end

local deletelogfile = function(source, cookiesfile, logfile)
	if source.method == "http" or source.method == "https" then
		local cmd = "wget -O - --no-check-certificate --load-cookies "..cookiesfile.." --post-data 'name="..logfile.."' '"..source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/delete' 2>/dev/null"
		local f = io.popen(cmd)
		f:close()
681 682
	elseif source.method == "local" then
		os.remove(logfile)
Ted Trask's avatar
Ted Trask committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
	end
end

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

function getsourcelist()
	local retval = cfe({ type="list", value={}, label="Weblog Source List" })
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listsourceentries()
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

function getsource(sourcename)
	local sourcedata = getnewsource()
	sourcedata.value.sourcename.value = sourcename
	sourcedata.value.sourcename.errtxt = "Source name does not exist"
707
	sourcedata.value.sourcename.readonly = true
Ted Trask's avatar
Ted Trask committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733

	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		local sourcelist = listsourceentries()
		databasedisconnect()
		for i,source in ipairs(sourcelist) do
			if source.sourcename == sourcename then
				sourcedata.value.sourcename.errtxt = nil
				for name,val in pairs(source) do
					if sourcedata.value[name] then
						sourcedata.value[name].value = val
					end
				end
				break
			end
		end
	end)
	if not res then
		sourcedata.errtxt = err
	end

	return sourcedata
end

local validatesource = function(sourcedata)
	local success = modelfunctions.validateselect(sourcedata.value.method)
734 735 736 737 738 739
	local test = {"sourcename", "source"}
	if sourcedata.value.method.value ~= "local" then
		test[#test+1] = "userid"
		test[#test+1] = "passwd"
	end
	for i,name in ipairs(test) do
Ted Trask's avatar
Ted Trask committed
740 741 742 743 744 745 746 747 748
		if sourcedata.value[name].value == "" then
			sourcedata.value[name].errtxt = "Cannot be empty"
			success = false
		end
	end

	return success
end

749
function updatesource(self, sourcedata)
Ted Trask's avatar
Ted Trask committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
	local success = validatesource(sourcedata)
	sourcedata.errtxt = "Failed to update source"
	if success then
		local source = {}
		for name,val in pairs(sourcedata.value) do
			source[name] = val.value
		end

		local res, err = pcall(function()
			databaseconnect(DatabaseUser)
			sourcedata.descr = updatesourceentry(source)
			databasedisconnect()
			sourcedata.errtxt = nil
		end)
		if not res and err then
			sourcedata.errtxt = sourcedata.errtxt .. "\n" .. err
		end
	end

	return sourcedata
end

function getnewsource()
	local source = {}
774 775 776 777 778 779 780
	source.sourcename = cfe({ label="Source Name", seq=0 })
	source.method = cfe({ type="select", value="local", label="Method", option={"http", "https", "local"}, seq=3 })
	source.userid = cfe({ label="UserID", seq=4 })
	source.passwd = cfe({ type="password", label="Password", seq=5 })
	source.source = cfe({ value="/var/log", label="Source Location / Address", seq=2 })
	source.tzislocal = cfe({ type="boolean", value=false, label="Using local timezone", seq=6 })
	source.enabled = cfe({ type="boolean", value=false, label="Enabled", seq=1 })
Ted Trask's avatar
Ted Trask committed
781 782 783
	return cfe({ type="group", value=source, label="Source" })
end

784
function createsource(self, sourcedata)
Ted Trask's avatar
Ted Trask committed
785 786 787 788 789 790 791
	local success = validatesource(sourcedata)
	sourcedata.errtxt = "Failed to create source"
	if success then
		local source = {}
		for name,val in pairs(sourcedata.value) do
			source[name] = val.value
		end
792 793
		-- remove spaces from sourcename
		source.sourcename = string.gsub(source.sourcename, "%s+$", "")
Ted Trask's avatar
Ted Trask committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

		local res, err = pcall(function()
			databaseconnect(DatabaseUser)
			sourcedata.descr = importsourceentry(source)
			databasedisconnect()
			sourcedata.errtxt = nil
		end)
		if not res and err then
			sourcedata.errtxt = sourcedata.errtxt .. "\n" .. err
		end
	end

	return sourcedata
end

809 810 811 812 813 814 815 816
function getdeletesource(self, clientdata)
	local retval = {}
	retval.sourcename = cfe({ value=clientdata.sourcename or "", label="Source Name" })
	return cfe({ type="group", value=retval, label="Delete Source" })
end

function deletesource(self, delsource)
	delsource.errtxt="Failed to delete source"
Ted Trask's avatar
Ted Trask committed
817 818
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
819
		local number = deletesourceentry(delsource.value.sourcename.value)
Ted Trask's avatar
Ted Trask committed
820 821
		databasedisconnect()
		if number > 0 then
822 823 824
			delsource.errtxt = nil
		else
			delsource.value.sourcename.errtxt = "Failed to find source"
Ted Trask's avatar
Ted Trask committed
825 826 827
		end
	end)
	if not res and err then
828
		delsource.errtxt = delsource.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
829
	end
830
	return delsource
Ted Trask's avatar
Ted Trask committed
831 832
end

833 834 835 836 837
function gettestsource(self, clientdata)
	local retval = {}
	retval.sourcename = cfe({ value=clientdata.sourcename or "", label="Source Name" })
	return cfe({ type="group", value=retval, label="Test Source" })
end
Ted Trask's avatar
Ted Trask committed
838

839
function testsource(self, test)
Ted Trask's avatar
Ted Trask committed
840
	-- temporary override of logme function to capture messages to result.value
841
	test.descr = {}
Ted Trask's avatar
Ted Trask committed
842
	local temp = logme
Ted Trask's avatar
Ted Trask committed
843
	logme = function(message) table.insert(test.descr, message) end
844 845

	test.errtxt = "Test Failed"
Ted Trask's avatar
Ted Trask committed
846 847 848 849

	local cookiesfile = "/tmp/cookies-"..tostring(os.time())
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
850
		local sources = listsourceentries(test.value.sourcename.value)
Ted Trask's avatar
Ted Trask committed
851 852
		databasedisconnect()
		if #sources < 1 then
853
			test.value.sourcename.errtxt = "Failed to find source"
Ted Trask's avatar
Ted Trask committed
854 855 856 857 858
		else
			local source = sources[1]
			-- run the test
			if connecttosource(source, cookiesfile) then
				local files = getlogcandidates(source, cookiesfile)
859
				test.errtxt = nil
Ted Trask's avatar
Ted Trask committed
860 861 862 863 864 865 866 867 868 869
				if #files == 0 then
					logme("No log files found")
				else
					for i,file in ipairs(files) do
						logme("Found log file "..file)
					end
				end
			end
		end
	end)
870 871
	if err and not res then
		test.errtxt = test.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
872 873 874 875
	end
	os.remove(cookiesfile)

	-- fix the result
876 877 878 879 880
	if test.errtxt then
		test.descr = nil
	else
		test.descr = table.concat(test.descr, "\n") or ""
	end
Ted Trask's avatar
Ted Trask committed
881 882
	logme = temp

883
	return test
Ted Trask's avatar
Ted Trask committed
884 885
end

886 887
-- import a logfile and delete logfile after
local function importlogfile(source, cookiesfile, file, parselog_func)
Ted Trask's avatar
Ted Trask committed
888
	logme("Getting " .. file )
889
	local loghandle = openlogfile(source, cookiesfile, file)
Ted Trask's avatar
Ted Trask committed
890
	logme("Processing " .. file )
891 892 893
	local res, err = pcall(function()
		con:execute("START TRANSACTION")
		for line in loghandle:lines() do
894 895 896
			assert(con:execute("SAVEPOINT before_line"))
			local res2, err2 = pcall(function()
				local logentry = parselog_func(line)
897
				importlogentry(logentry, source.sourcename)
898 899 900 901 902 903
			end)
			if not res2 then
				if (config.stoponerror == "true") then
					pcall(function() con:execute("ROLLBACK") end)
				else
					assert(con:execute("ROLLBACK TO before_line"))
904
					con:execute("COMMIT")
905 906 907
				end
				pcall(function() logme("Exception on line:"..line) end)
				if err2 then
Ted Trask's avatar
Ted Trask committed
908
					pcall(function() logme(err2) end)
909 910 911
				end
				if (config.stoponerror == "true") then
					assert(res2, "Import halted on exception")
912 913
				else
					con:execute("START TRANSACTION")
914
				end
915 916
			else
				assert(con:execute("RELEASE SAVEPOINT before_line"))
917
			end
918 919 920 921 922 923 924 925
		end
		con:execute("COMMIT")
	end)
	if not res then
		pcall(function() con:execute("ROLLBACK") end)
		if err then
			pcall(function() logme(err) end)
		end
926
	end
927
	loghandle:close()
928 929 930 931 932
	if res then
		logme("Deleting " .. file )
		deletelogfile(source, cookiesfile, file)
	end
	return res
933 934
end

935 936 937 938 939 940
function getimportlogs(self, clientdata)
	local retval = {}
	return cfe({ type="group", value=retval, label="Import Logs" })
end

function importlogs(self, import)
Ted Trask's avatar
Ted Trask committed
941
	local count = 0
942
	local success = true
Ted Trask's avatar
Ted Trask committed
943 944 945 946 947

	local res, err = pcall(function()
		databaseconnect(DatabaseOwner, config.password)

		-- Download, parse, and import the logs
948 949 950 951
		logme("Executing importlogs")
		logme("Analyzing...")
		local sql = "ANALYZE"
		res = assert (con:execute(sql))
952 953 954 955 956 957

		-- Get the word lists
		goodwords = fs.read_file_as_array(goodwordslist) or {}
		badwords = fs.read_file_as_array(badwordslist) or {}
		ignorewords = fs.read_file_as_array(ignorewordslist) or {}

958 959
		-- Determine sources
		local sources = listsourceentries(sourcename)
Ted Trask's avatar
Ted Trask committed
960

Ted Trask's avatar
Ted Trask committed
961 962 963 964 965 966 967
		for i,source in ipairs(sources) do
			if source.enabled then
				logme("Getting logs from source " .. source.sourcename)
				local cookiesfile = "/tmp/cookies-"..tostring(os.time())
				if connecttosource(source, cookiesfile) then
					local files = getlogcandidates(source, cookiesfile)
					for j,file in ipairs(files) do
968
						if string.match(file, "dansguardian/access%.log[%.%-]") then
Ted Trask's avatar
Ted Trask committed
969
							count = count + 1
970
							success = importlogfile(source, cookiesfile, file, parsedglog) and success
Ted Trask's avatar
Ted Trask committed
971
						elseif string.match(file, "squid/access%.log[%.%-]") then
Ted Trask's avatar
Ted Trask committed
972
							count = count + 1
973
							success = importlogfile(source, cookiesfile, file, parsesquidlog) and success
Ted Trask's avatar
Ted Trask committed
974 975 976 977 978 979 980 981
						end
					end
				end
				os.remove(cookiesfile)
			end
		end

		-- Process the logs
982 983
		if success then
			updateusagestats()
984
			importpubweblog()
985
		end
Ted Trask's avatar
Ted Trask committed
986 987 988 989 990 991 992
		-- Purge old database entries
		groomusagestat()
		groomdbhistlog()
		groompublogs()

		databasedisconnect()
	end)
993
	if not res or not success then
994
		import.errtxt = "Import Logs Failure"
Ted Trask's avatar
Ted Trask committed
995 996
		if err then
			pcall(function() logme(err) end)
997
			import.errtxt = import.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
998
		end
999
		pcall(function() databasedisconnect() end)
1000 1001
	else
		import.descr = "Imported "..tostring(count).." logs"
Ted Trask's avatar
Ted Trask committed
1002 1003
	end

1004
	return import
Ted Trask's avatar
Ted Trask committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
end

function getactivitylog()
	local retval = cfe({ type="list", value={}, label="Weblog Activity Log" })
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listhistorylogentries() or {}
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

Ted Trask's avatar
Ted Trask committed
1021 1022 1023 1024 1025 1026 1027
function geteditselected()
	local result = {}
	result.select = cfe({ type="list", value={}, label="Entries to mark as selected" })
	result.deselect = cfe({ type="list", value={}, label="Entries to mark as selected" })
	return cfe({ type="group", value=result, label="Select / Deselect log entries" })
end

1028
function editselected(self, data)
Ted Trask's avatar
Ted Trask committed
1029 1030 1031 1032
	local res, err = pcall(function()
		databaseconnect(DatabaseOwner)
		con:execute("START TRANSACTION")
		for i,sel in ipairs(data.value.select.value) do
1033
			assert (con:execute("UPDATE pubweblog SET selected = true WHERE id = '"..escape(sel).."'"))
Ted Trask's avatar
Ted Trask committed
1034
		end
Ted Trask's avatar
Ted Trask committed
1035
		for i,sel in ipairs(data.value.deselect.value) do
1036
			assert (con:execute("UPDATE pubweblog SET selected = false WHERE id = '"..escape(sel).."'"))
Ted Trask's avatar
Ted Trask committed
1037 1038 1039 1040 1041 1042
		end
		con:execute("COMMIT")
		databasedisconnect()
	end)
	if not res then
		data.errtxt = err
Ted Trask's avatar
Ted Trask committed
1043
	end
Ted Trask's avatar
Ted Trask committed
1044
	return data
1045 1046
end

1047 1048 1049 1050 1051 1052 1053
function getclearselected(self, clientdata)
	local retval = {}
	return cfe({ type="group", value=retval, label="Clear select fields" })
end

function clearselected(self, clear)
	clear.errtxt = "Failed to clear select fields"
1054 1055 1056 1057 1058
	local res, err = pcall(function()
		sql = "UPDATE pubweblog SET selected = false WHERE selected = true"
		databaseconnect(DatabaseOwner)
		assert (con:execute(sql))
		databasedisconnect()
1059
		clear.errtxt = nil
1060 1061
	end)
	if not res then
1062
		clear.errtxt = clear.errtxt.."\n"..err
1063
	end
1064
	return clear
1065 1066
end

1067 1068 1069 1070 1071 1072
local validateweblogparameters = function(params)
	local success = modelfunctions.validateselect(params.value.activelog)
	success = modelfunctions.validateselect(params.value.sortby) and success
	if params.value.clientip.value ~= "" and string.find(params.value.clientip.value, "[^%d%.]") then
		params.value.clientip.errtxt = "Invalid IP Address"
		success = false
Ted Trask's avatar
Ted Trask committed
1073
	end
1074 1075 1076 1077
	if not validator.is_integer(params.value.score.value) then
		params.value.score.errtxt = "Must be a number"
		success = false
	end
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		local s
		if params.value.starttime.value ~= "" then
			s,params.value.starttime.errtxt,params.value.starttime.value = convertdatabaseentry("TIMESTAMP", params.value.starttime.value)
			success = success and s
		end
		if params.value.endtime.value ~= "" then
			s,params.value.endtime.errtxt,params.value.endtime.value = convertdatabaseentry("TIMESTAMP", params.value.endtime.value)
			success = success and s
		end
		if params.value.focus.value ~= "" then
			s,params.value.focus.errtxt,params.value.focus.value = convertdatabaseentry("TIMESTAMP", params.value.focus.value)
			success = success and s
		end
		databasedisconnect()
	end)
	if not res and err then
		params.value.starttime.errtxt = err
		params.value.endtime.errtxt = err
		params.value.focus.errtxt = err
		success = false
1100
	end
1101 1102
	return success
end
Ted Trask's avatar
Ted Trask committed
1103

1104 1105 1106 1107 1108 1109 1110 1111 1112
function getweblogparameters()
	local c = getconfig()
	local result = {}
	result.activelog = cfe({ type="select", value="pubweblog", option={"pubweblog", "pubweblog_history"}, label="Active Weblog", seq=1 })
	result.starttime = cfe({ value=c.value.auditstart.value, label="Start Time", seq=2 })
	result.endtime = cfe({ value=c.value.auditend.value, label="End Time", seq=3 })
	result.clientuserid = cfe({ value="", label="User ID", seq=4 })
	result.clientip = cfe({ value="", label="Client IP", seq=5 })
	result.urisearch = cfe({ value="", label="URI Contains", descr="Retrieve records where the URI contains this word", seq=6 })
1113
	result.score = cfe({ value=c.value.score.value, label="Minimum Score", descr="Minimum score to search on", seq=7 })
1114 1115 1116 1117 1118 1119 1120 1121
	result.sortby = cfe({ type="select", value=c.value.sortby.value, option=c.value.sortby.option, label="Sort By field", descr="Sort by this field when displaying records", seq=8 })
	result.badyesno = cfe({ type="boolean", value=c.value.badyesno.value, label="Show Suspect Records", descr="Limit search to records marked as suspect", seq=9 })
	result.deniedyesno = cfe({ type="boolean", value=c.value.deniedyesno.value, label="Show Denied Records", descr="Limit search to Denied URIs", seq=10 })
	result.bypassyesno = cfe({ type="boolean", value=c.value.bypassyesno.value, label="Show Bypass Records", descr="Limit search to Bypass attempts", seq=11 })
	result.selected = cfe({ type="boolean", value=false, label="Show Selected Records", descr="Limit search to records that have been selected", seq=12 })
	result.focus = cfe({ value="", label="Focus Time", seq=13 })
	return cfe({ type="group", value=result, label="Weblog Access Log" })
end
Ted Trask's avatar
Ted Trask committed
1122

1123
function getweblog(self, result)
1124 1125 1126 1127
	local success = validateweblogparameters(result)
	result.value.log = cfe({ type="list", value={}, label="Weblog Access Log" })
	result.value.window = cfe({ value=config.window or "5", label="Time Window" })
	local err
1128 1129 1130
	if success then
		local res, err = pcall(function()
			databaseconnect(DatabaseUser)
1131
			result.value.log.value = listlogentries(result.value.activelog.value, result.value.clientuserid.value, result.value.starttime.value, result.value.endtime.value, result.value.clientip.value, result.value.badyesno.value, result.value.deniedyesno.value, result.value.bypassyesno.value, result.value.score.value, result.value.urisearch.value, result.value.sortby.value, result.value.selected.value ) or {}
1132 1133
			databasedisconnect()
		end)
1134 1135 1136
		if not res then
			result.errtxt = err
		end
1137
	else
1138
		result.errtxt = "Invalid search parameters"
1139
	end
1140
	return result
Ted Trask's avatar
Ted Trask committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
end

function getusagestats()
	local retval = cfe({ type="list", value={}, label="Weblog Usage Stats" })
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listusagestats() or {}
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

1157 1158 1159 1160 1161 1162 1163 1164 1165
function getauditstats()
	local result = {}
	result.auditstart = cfe({ value=config.auditstart or "", label="Audit Start Time" })
	result.auditend = cfe({ value=config.auditend or "", label="Audit End Time" })
	result.groupby = cfe({ value=config.groupby or "clientuserid", label="Group By" })
	result.stats = cfe({ type="list", value={}, label="Audit Block Statistics" })
	local res, err = pcall(function()
		if config.auditstart ~= "" and config.auditend ~= "" then
			databaseconnect(DatabaseUser)
1166
			result.stats.value = groupflaggedlogentries(config.auditstart, config.auditend, result.groupby.value) or {}
1167 1168 1169 1170 1171 1172
			databasedisconnect()
		end
	end)
	return cfe({ type="group", value=result, errtxt=err, label="Weblog Audit Statistics" })
end

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
function getcompleteaudit(self, clientdata)
	local retval = {}
	retval.timestamp = cfe({ value=clientdata.timestamp or "", label="New Audit End Time" })
	return cfe({ type="group", value=retval, label="Complete Audit" })
end

function completeaudit(self, complete)
	if "" == complete.value.timestamp.value then
		local now = os.time()
		complete.value.timestamp.value = os.date("%Y-%m-%d %H:%M:%S", now - now%86400 - 86400)
	end
1184 1185
	local conf = getconfig()
	conf.value.auditstart.value = conf.value.auditend.value
1186
	conf.value.auditend.value = complete.value.timestamp.value
1187
	conf = updateconfig(self, conf)
1188
	if conf.errtxt then
1189
		complete.errtxt = "Failed to complete audit\n"..conf.errtxt.."\n"..conf.value.auditend.errtxt
1190
	end
1191
	return complete
1192
end
Ted Trask's avatar
Ted Trask committed
1193 1194 1195

function getconfig()
	local result = {}
Ted Trask's avatar
Ted Trask committed
1196 1197
	result.auditstart = cfe({ value=config.auditstart or "", label="Audit Start Time", seq=1 })
	result.auditend = cfe({ value=config.auditend or "", label="Audit End Time", seq=2 })
1198
	result.groupby = cfe({ type="select", value=config.groupby or "clientuserid", label="Group results by", option={"clientuserid", "clientip"}, descr="Display audit results based on user ID or IP", seq=3 })
1199
	result.score = cfe({ value=config.score or "0", label="Minimum Score", descr="Default minimum Score to search for", seq=4 })
1200 1201 1202 1203 1204 1205 1206 1207 1208
	result.sortby = cfe({ type="select", value=config.sortby or "logdatetime", label="Sort By field", option={"logdatetime", "logdatetime DESC", "clientuserid", "clientuserid DESC", "clientip", "clientip DESC", "bytes", "bytes DESC", "score", "score DESC", "reason"}, descr="Default sort order", seq=5 })
	result.badyesno = cfe({ type="boolean", value=(config.badyesno == "true"), label="Display Suspect Records", descr="By default, only show records flagged as suspect", seq=6 })
	result.deniedyesno = cfe({ type="boolean", value=(config.deniedyesno == "true"), label="Display Denied Records", descr="By default, only show records with denied URI", seq=7 })
	result.bypassyesno = cfe({ type="boolean", value=(config.bypassyesno == "true"), label="Display Bypass Records", descr="By default, only show records with bypass attempts", seq=8 })
	result.shorturi = cfe({ type="boolean", value=(config.shorturi == "true"), label="Truncate URLs", descr="You can limit the length of displayed URLs by enabling this option", seq=9 })
	result.shortreason = cfe({ type="boolean", value=(config.shortreason == "true"), label="Short Reason", descr="Display a short reason (dansguardian only)", seq=10 })
	result.window = cfe({ value=config.window or "5", label="Time Window", descr="Minutes of activity to display before and after selected block", seq=11 })
	result.purgedays = cfe({ value=config.purgedays or "30", label="Days before Purge", descr="Days to keep full history, regardless of audit", seq=12 })
	result.stoponerror = cfe({ type="boolean", value=(config.stoponerror == "true"), label="Stop on Error", descr="Stop import of logs if an error is encountered", seq=13})
Ted Trask's avatar
Ted Trask committed
1209 1210 1211
	return cfe({ type="group", value=result, label="Weblog Config" })
end

1212
local function validateconfig(newconfig)
Ted Trask's avatar
Ted Trask committed
1213 1214
	local success = modelfunctions.validateselect(newconfig.value.groupby)
	success = modelfunctions.validateselect(newconfig.value.sortby) and success
1215 1216 1217 1218
	if not validator.is_integer(newconfig.value.score.value) then
		newconfig.value.score.errtxt = "Must be a number"
		success = false
	end
Ted Trask's avatar
Ted Trask committed
1219 1220 1221 1222 1223 1224
	if newconfig.value.window.value == "" then
		newconfig.value.window.errtxt = "Cannot be blank"
		success = false
	elseif not validator.is_integer(newconfig.value.window.value) then
		newconfig.value.window.errtxt = "Must be a number"
		success = false
Timo Teräs's avatar
Timo Teräs committed
1225
	end
Ted Trask's avatar
Ted Trask committed
1226 1227 1228
	if not validator.is_integer(newconfig.value.purgedays.value) then
		newconfig.value.purgedays.errtxt = "Must be a number"
		success = false
Timo Teräs's avatar
Timo Teräs committed
1229
	end
1230 1231 1232 1233
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		local s
		if newconfig.value.auditstart.value ~= "" then
1234
			s,newconfig.value.auditstart.errtxt,newconfig.value.auditstart.value = convertdatabaseentry("TIMESTAMP", newconfig.value.auditstart.value)
1235 1236 1237
			success = success and s
		end
		if newconfig.value.auditend.value ~= "" then
1238
			s,newconfig.value.auditend.errtxt,newconfig.value.auditend.value = convertdatabaseentry("TIMESTAMP", newconfig.value.auditend.value)
1239 1240 1241 1242 1243 1244 1245 1246 1247
			success = success and s
		end
		databasedisconnect()
	end)
	if not res and err then
		newconfig.value.auditstart.errtxt = err
		newconfig.value.auditend.errtxt = err
		success = false
	end
1248
	return success, newconfig
1249 1250
end

1251
function updateconfig(self, newconfig)
1252
	local success = validateconfig(newconfig)
Ted Trask's avatar
Ted Trask committed
1253 1254 1255 1256 1257
	if success then
		configcontent = format.update_ini_file(configcontent, "", "auditstart", newconfig.value.auditstart.value)
		configcontent = format.update_ini_file(configcontent, "", "auditend", newconfig.value.auditend.value)
		configcontent = format.update_ini_file(configcontent, "", "window", newconfig.value.window.value)
		configcontent = format.update_ini_file(configcontent, "", "purgedays", newconfig.value.purgedays.value)
Ted Trask's avatar
Ted Trask committed
1258
		configcontent = format.update_ini_file(configcontent, "", "groupby", newconfig.value.groupby.value)
Ted Trask's avatar
Ted Trask committed
1259
		configcontent = format.update_ini_file(configcontent, "", "shorturi", tostring(newconfig.value.shorturi.value))
1260
		configcontent = format.update_ini_file(configcontent, "", "shortreason", tostring(newconfig.value.shortreason.value))
1261
		configcontent = format.update_ini_file(configcontent, "", "stoponerror", tostring(newconfig.value.stoponerror.value))
1262
		configcontent = format.update_ini_file(configcontent, "", "badyesno", tostring(newconfig.value.badyesno.value))
1263 1264
		configcontent = format.update_ini_file(configcontent, "", "deniedyesno", tostring(newconfig.value.deniedyesno.value))
		configcontent = format.update_ini_file(configcontent, "", "bypassyesno", tostring(newconfig.value.bypassyesno.value))
1265
		configcontent = format.update_ini_file(configcontent, "", "score", tostring(newconfig.value.score.value))
1266
		configcontent = format.update_ini_file(configcontent, "", "sortby", tostring(newconfig.value.sortby.value))
Ted Trask's avatar
Ted Trask committed
1267

Ted Trask's avatar
Ted Trask committed
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
		fs.write_file(configfile, configcontent)
		config = format.parse_ini_file(configcontent, "") or {}
	else
		newconfig.errtxt = "Failed to update config"
	end

	return newconfig
end

function getnewadhocquery()
	local query = {}
	query.query = cfe({ label="Query select statement" })
	return cfe({ type="group", value=query, label="Ad-hoc Query" })
end

1283
function adhocquery(self, query)
Ted Trask's avatar
Ted Trask committed
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	local success = true
	query.value.query.value = query.value.query.value:lower()
	if query.value.query.value == "" then
		query.value.query.errtxt = "Empty select statement"
		success = false
	elseif not string.find(query.value.query.value, "^%s*select%s") then
		query.value.query.errtxt = "Must be a select statement"
		success = false
	end

	if success then
		local cur
		local res, err = pcall(function()
			databaseconnect(DatabaseUser)
			cur = assert (con:execute(query.value.query.value))
			databasedisconnect()
		end)
		if not res or not cur then
			query.value.query.errtxt = err or "Select failed"
			query.errtxt = "Query failed"
		else
			query.value.result = cfe({ type="list", value={}, label="Select result" })
			local result = query.value.result.value
			local row = cur:fetch ({}, "a")
			while row do
				result[#result+1] = {}
				for name,val in pairs(row) do
					result[#result][name] = val
				end
1313
				row = cur:fetch (row, "a")
Ted Trask's avatar
Ted Trask committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
			end
			-- close everything
			cur:close()
		end
	else
		query.errtxt = "Query failed"
	end

	return query
end

function testdatabase()
	local retval = cfe({ type="boolean", value=false, label="Database present" })
	local dbs = listdatabases()
	for i,db in ipairs(dbs) do