weblog-model.lua 52.5 KB
Newer Older
1
local mymodule = {}
Ted Trask's avatar
Ted Trask committed
2 3

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

12
local DatabaseName = "webproxylog"
Ted Trask's avatar
Ted Trask committed
13 14 15 16 17 18
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
19
local configfile = "/etc/weblog/weblog.conf"
Ted Trask's avatar
Ted Trask committed
20 21
local configcontent = fs.read_file(configfile) or ""
local config = format.parse_ini_file(configcontent, "") or {}
22
local goodwordslist = "/etc/weblog/goodwords"
23
local goodwords
24
local badwordslist = "/etc/weblog/badwords"
25
local badwords
Ted Trask's avatar
Ted Trask committed
26
local ignorewordslist = "/etc/weblog/ignorewords"
27
local ignorewords
Ted Trask's avatar
Ted Trask committed
28
local files = {badwordslist, goodwordslist, ignorewordslist, configfile}
Ted Trask's avatar
Ted Trask committed
29 30

local database_creation_script = {
31
	"CREATE TABLE dbhistlog (logdatetime timestamp(3) without time zone NOT NULL, msgtext text)",
32 33
	"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)",
34
	"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
35
	"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)",
36
	"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
37 38 39 40 41
	"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)",
42 43 44
	"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)",
45 46
	"GRANT SELECT ON dbhistlog TO "..DatabaseUser,
	"GRANT SELECT ON pubweblog TO "..DatabaseUser,
47
	"GRANT SELECT ON pubweblog_history TO "..DatabaseUser,
48 49
	"GRANT SELECT, UPDATE, INSERT, DELETE ON source TO "..DatabaseUser,
	"GRANT SELECT ON usagestat TO "..DatabaseUser,
Ted Trask's avatar
Ted Trask committed
50 51 52 53 54 55 56 57 58 59 60 61 62
}

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

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

63 64
-- Escape special characters in sql statements and truncate to length
local escape = function(sql, length)
Ted Trask's avatar
Ted Trask committed
65
	sql = sql or ""
66
	if length then sql = string.sub(sql, 1, length) end
67
	return con:escape(sql)
Ted Trask's avatar
Ted Trask committed
68 69 70 71 72
end

-- List the postgres databases on this system
local listdatabases = function()
	local dbs = {}
73
	local result = modelfunctions.run_executable({"psql", "-U", "postgres", "-tl"})
Ted Trask's avatar
Ted Trask committed
74 75 76 77 78 79 80 81 82 83 84
	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
85 86 87 88 89 90 91 92 93
	local cmd = "CREATE USER "..DatabaseOwner.." WITH PASSWORD '"..password.."'"
	local cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)

	cmd = "CREATE USER "..DatabaseUser
	cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)
Timo Teräs's avatar
Timo Teräs committed
94

Ted Trask's avatar
Ted Trask committed
95
	-- Create the database
96 97 98 99
	cmd = "CREATE DATABASE "..DatabaseName.." WITH OWNER "..DatabaseOwner
	cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)
Timo Teräs's avatar
Timo Teräs committed
100

Ted Trask's avatar
Ted Trask committed
101 102 103 104 105 106 107
	return table.concat(result, "\n")
end

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

108 109 110 111
	local cmd = "DROP DATABASE "..DatabaseName
	local cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)
Ted Trask's avatar
Ted Trask committed
112

113 114 115 116
	cmd = "DROP ROLE "..DatabaseUser
	cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)
Ted Trask's avatar
Ted Trask committed
117

118 119 120 121
	cmd = "DROP ROLE "..DatabaseOwner
	cmdresult, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-c", cmd}, true)
	table.insert(result, errtxt)
	table.insert(result, cmdresult)
Timo Teräs's avatar
Timo Teräs committed
122

Ted Trask's avatar
Ted Trask committed
123 124 125 126 127
	return table.concat(result, "\n")
end

-- Run an SQL script
local runSQLscript = function(filename)
128 129
	local result, errtxt = modelfunctions.run_executable({"psql", "-U", "postgres", "-f", filename, DatabaseName}, true)
	return errtxt or result
Ted Trask's avatar
Ted Trask committed
130 131 132
end

-- Create the database and tables
133
-- pg_dump -U postgres -c webproxylog > makeweblog.postgres
Ted Trask's avatar
Ted Trask committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
--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)
157
	local sql = string.format("INSERT INTO dbhistlog VALUES ('now', '%s')", escape(message))
Ted Trask's avatar
Ted Trask committed
158 159 160 161 162 163
	local res = assert (con:execute(sql))
end

local listhistorylogentries = function()
	local entries = {}
	-- retrieve a cursor
Timo Teräs's avatar
Timo Teräs committed
164
	cur = assert (con:execute"SELECT logdatetime, msgtext from dbhistlog ORDER BY logdatetime")
Ted Trask's avatar
Ted Trask committed
165 166 167 168 169 170 171 172 173 174
	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

175
local importlogentry = function(entry, sourcename)
176
	if entry then
177
		local sql = string.format("INSERT INTO weblog VALUES ('%s', '%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')",
178
			escape(sourcename), escape(entry.clientip), escape(entry.clientuserid, 64):lower(),
179
			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
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
		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)
231 232 233
	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
234 235 236
	local res = assert (con:execute(sql))
end

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
-- 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
252 253
-- Delete useage stats from more than a year ago
local groomusagestat = function()
254 255 256
	local res = assert (con:execute("delete from usagestat where " ..
		"date < (now() - INTERVAL '1 year')"))
	logme("removed " .. res .. " old usage status lines")
Ted Trask's avatar
Ted Trask committed
257 258 259 260
end

-- Delete history log information from more than a month ago
local groomdbhistlog = function()
261 262 263
	local res = assert (con:execute("delete from dbhistlog where " ..
		"logdatetime < (now() - INTERVAL '1 month')"))
	logme("removed " .. res .. " old dbhistlog lines")
Ted Trask's avatar
Ted Trask committed
264 265 266 267 268
end

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

Ted Trask's avatar
Ted Trask committed
270 271 272
	local now = os.time()

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

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

280
	sql = "Delete from pubweblog where logdatetime < '" .. escape(temp) .."'"
Ted Trask's avatar
Ted Trask committed
281
	res = assert (con:execute(sql))
282
	logme("Deleted " .. res .. " old records from pubweblog")
Ted Trask's avatar
Ted Trask committed
283

284 285 286
	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
287 288
end

289
local generatewhereclause = function(clientuserid, starttime, endtime, clientip, badyesno, deniedyesno, bypassyesno, score, urisearch, selected, sourcename)
Ted Trask's avatar
Ted Trask committed
290 291 292
	local sql = ""
	local where = {}
	if clientuserid and clientuserid ~= "" then
293
		where[#where+1] = "clientuserid LIKE '%"..escape(clientuserid).."%'"
Ted Trask's avatar
Ted Trask committed
294 295 296 297 298 299 300 301 302 303
	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
304 305
	if badyesno then
		where[#where+1] = "badyesno = '1'"
306
	end
307 308
	if deniedyesno then
		where[#where+1] = "deniedyesno = '1'"
309
	end
310 311
	if bypassyesno then
		where[#where+1] = "bypassyesno = '1'"
312 313 314 315
	end
	if score and score ~= "" then
		where[#where+1] = "score >= '"..escape(score).."'"
	end
Ted Trask's avatar
Ted Trask committed
316
	if urisearch and urisearch ~= "" then
317 318
	    	where[#where+1] = "lower(uri) LIKE '%"..escape(urisearch).."%'"
	end
319
	if selected then
320 321
		where[#where+1] = "selected = 'true'"
	end
322 323 324 325 326 327 328
	if sourcename and #sourcename > 0 then
		tmp = {}
		for i,s in pairs(sourcename) do
			tmp[#tmp+1] = "sourcename = '"..escape(s).."'"
		end
		where[#where+1] = "("..table.concat(tmp, " OR ")..")"
	end
Ted Trask's avatar
Ted Trask committed
329

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

Ted Trask's avatar
Ted Trask committed
334 335 336
	return sql
end

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

360
local groupflaggedlogentries = function(starttime, endtime, groupby)
361 362 363
	groupby = groupby or "clientuserid"
	local entries = {}
	-- retrieve a cursor
364
	local sql = "SELECT "..escape(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"
365
	sql = sql .. generatewhereclause(nil, starttime, endtime)
366
	sql = sql .. " GROUP BY " ..escape(groupby).. " ORDER BY numflagged DESC"
367 368 369
	cur = assert (con:execute(sql))
	row = cur:fetch ({}, "a")
	while row do
370
		entries[#entries+1] = {numrecords=row.numrecords, numflagged=row.numflagged, numhits=row.numhits, numdenied=row.numdenied, numbypassed=row.numbypassed, maxscore=row.maxscore}
371 372 373 374 375 376 377 378
		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
379 380 381 382
local listusagestats = function()
	local entries = {}
	-- retrieve a cursor
	local sql = "SELECT sourcename, date, sum(numrequest) AS numrequest, sum(numblock) AS numblock " ..
383
		"FROM usagestat GROUP BY sourcename, date ORDER BY date, sourcename"
Ted Trask's avatar
Ted Trask committed
384 385 386 387 388 389 390 391 392 393 394
	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

395 396 397
local testdatabaseentry = function(datatype, value)
	local success = true
	local errtxt
398
	local sql = "CREATE TEMP TABLE testing ( test "..escape(datatype).." DEFAULT '"..escape(value).."' ) ON COMMIT DROP"
399 400 401 402 403 404 405 406 407 408
	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

409 410 411 412 413
local convertdatabaseentry = function(datatype, value)
	local success = true
	local errtxt
	local result = value
	local res, err = pcall(function()
414
		local sql = "CREATE TEMP TABLE testing ( test "..escape(datatype).." )"
415
		assert (con:execute(sql))
416
		sql = "INSERT INTO testing VALUES ('"..escape(value).."')"
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
		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
436 437 438
local printtableentries = function(tablename)
	-- retrieve a cursor
	local count = 0
439
	cur = assert (con:execute("SELECT * from "..escape(tablename)))
Ted Trask's avatar
Ted Trask committed
440 441 442 443 444
	-- 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
445
			mymodule.logevent(name.." = "..val..", ")
Ted Trask's avatar
Ted Trask committed
446 447 448 449 450
		end
		row = cur:fetch (row, "a")
	end
	-- close everything
	cur:close()
451
	mymodule.logevent("Table "..tablename.." contains "..count.." rows")
Ted Trask's avatar
Ted Trask committed
452 453 454 455 456
end

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

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

463
	--check for ignored records first
464
	for i,thisline in ipairs(ignorewords) do
465 466 467
		if not thisline then
			break
		end
468 469 470 471 472 473 474 475 476

		-- ignore blank lines
		if string.find(thisline, "%S") then
			_,instcnt = string.lower(logentry.URL):gsub(format.escapemagiccharacters(thisline), " ")
			if instcnt ~= 0 then
				logentry.ignoreme = true
				--logme("ignoring...")
				break
			end
477 478 479
		end
	end

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

487 488 489 490 491 492 493 494 495
			-- ignore blank lines
			if string.find(thisline, "%S") then
				_,instcnt = string.lower(logentry.URL):gsub(format.escapemagiccharacters(thisline), " ")
				if instcnt ~= 0 then
					-- logme("instcnt =  "..instcnt)
					isbad=1
					wrdcnt= wrdcnt + instcnt
					badwordloc[#badwordloc+1] = thisline
				end
496
			end
497
		end
Ted Trask's avatar
Ted Trask committed
498

499
		--check for DansGuardian actions
500
		if (logentry.reason and logentry.reason ~= "") then
Ted Trask's avatar
Ted Trask committed
501 502 503 504 505 506 507 508 509 510
			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
511
		end
512 513 514

		--check for Squark actions
		if (logentry.squarkaction and logentry.squarkaction ~= "") then
Ted Trask's avatar
Ted Trask committed
515 516 517 518 519 520
			--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
521 522
		end

523 524 525 526 527 528
		--check for Squark category
		if (logentry.squarkcategory and logentry.squarkcategory ~= "") then
			logentry.reason = logentry.squarkcategory
			logentry.shortreason = logentry.squarkcategory
		end

529 530 531 532
		for i,goodline in ipairs(goodwords) do
			if not goodline then
				break
			end
Ted Trask's avatar
Ted Trask committed
533

534
			-- ignore blank lines
535
			if string.find(goodline, "%S") then
536 537 538 539 540 541 542 543 544
				_,instcnt = string.lower(logentry.URL):gsub(format.escapemagiccharacters(goodline), " ")
				--if string.find(logentry.URL,goodline) then
				if instcnt ~= 0 then
					if wrdcnt >= instcnt then
						wrdcnt = wrdcnt - instcnt
					else
						wrdcnt = 0
					end
					goodwordloc[#goodwordloc+1] = goodline
545 546
				end
			end
547 548
		end
	end
Ted Trask's avatar
Ted Trask committed
549 550 551 552
	-- Reset bad to reduce number of bad hits if score is zero
	-- if wrdcnt == 0 then
	-- isbad=0
	-- end
553 554 555

	logentry.score=wrdcnt
	logentry.badyesno=isbad
556 557
	logentry.wordloc=table.concat(badwordloc,"|")
	logentry.gwordloc=table.concat(goodwordloc,"|")
558 559 560 561
end

local function parsesquidlog(line)
	-- Format of squid log (space separated):
562
	-- time elapsed remotehost code/status bytes method URL rfc931 peerstatus/peerhost ? squarkcategory/squarkaction
563 564 565 566 567 568
	local words = {}

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

569 570 571
	local logentry = {logdatetime=words[1],
		elapsed=words[2],
		clientip=words[3],
Ted Trask's avatar
Ted Trask committed
572 573
		code=string.match(words[4] or "", "^[^/]*"),
		status=string.match(words[4] or "", "[^/]*$"),
574
		bytes=words[5],
Ted Trask's avatar
Ted Trask committed
575
		method=words[6],
576
		URL=words[7],
577
		clientuserid=words[8],
Ted Trask's avatar
Ted Trask committed
578
		peerstatus=string.match(words[9] or "", "^[^/]*"),
579 580 581
		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
582

583
	checkwords(logentry)
584

Natanael Copa's avatar
Natanael Copa committed
585 586 587 588 589 590
	-- 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
591 592
	-- 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
593 594
		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
595 596 597 598
	end
	return nil
end

599
local function parsedglog(line)
600
	local words = format.string_to_table(line, "\t")
601 602 603 604 605 606 607
	local logentry = {logdatetime=words[1],
			clientuserid=words[2],
			clientip=words[3],
			URL=words[4],
			reason=words[5],
			method=words[6],
			bytes=words[7],
608 609
			shortreason=words[9],
			deniedyesno=1}
Ted Trask's avatar
Ted Trask committed
610

611
	checkwords(logentry)
Ted Trask's avatar
Ted Trask committed
612 613 614 615 616

	if logentry.reason and logentry.reason ~= "" then
           	if logentry.shortreason == "" then
           		logentry.shortreason = logentry.reason
           	end
617
		--logentry.score = string.match(logentry.reason, "^.*: ([0-9]+) ")
618
		logentry.logdatetime = string.gsub(logentry.logdatetime, "%.", "-")
Ted Trask's avatar
Ted Trask committed
619 620 621 622 623
	   	return logentry
	end
	return nil
end

Ted Trask's avatar
Ted Trask committed
624 625 626 627 628 629 630 631 632
-- ################################################################################
-- 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
633 634
		fs.write_file(cookiesfile, "password="..source.passwd.."&userid="..source.userid.."&Logon=Logon&submit=true")
		local resultpage, errtxt = modelfunctions.run_executable({"wget", "-O", "-", "--no-check-certificate", "--save-cookies", cookiesfile, "--keep-session-cookies", "--post-file", cookiesfile, source.method.."://"..source.source.."/cgi-bin/acf/acf-util/logon/logon"})
Ted Trask's avatar
Ted Trask committed
635 636
		if resultpage == "" then
			logme("Failed to connect to "..source.sourcename)
637
		elseif string.find(resultpage, "/acf%-util/logon/logon") then
638
			logme("Failed to log on to "..source.sourcename)
Ted Trask's avatar
Ted Trask committed
639 640 641
		else
			success = true
		end
642 643
	elseif source.method == "local" then
		success = true
Ted Trask's avatar
Ted Trask committed
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
651
		local resultpage = modelfunctions.run_executable({"wget", "-O", "-", "--no-check-certificate", "--load-cookies", cookiesfile, source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/status"})
652
		-- This method works for view prior to acf-alpine-baselayout-0.12.0
653
		for file in string.gmatch(resultpage, "download%?[^\"]*name=([^\"]+)") do
Ted Trask's avatar
Ted Trask committed
654 655
			candidates[#candidates+1] = file
		end
656 657 658 659 660 661 662 663
		-- This method works for view from acf-alpine-baselayout-0.12.0
		local reversetable = {}
		for file in string.gmatch(resultpage, 'name="filename"  value="([^\"]+)"') do
			if not reversetable[file] then
				candidates[#candidates+1] = file
				reversetable[file] = true
			end
		end
664 665
	elseif source.method == "local" then
		candidates = fs.find_files_as_array(nil, source.source)
Ted Trask's avatar
Ted Trask committed
666 667 668 669
	end
	return candidates
end

670
local openlogfile = function(source, cookiesfile, logfile)
671
	local handle, handle2, errtxt
Ted Trask's avatar
Ted Trask committed
672
	if source.method == "http" or source.method == "https" then
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
		local cmd = {"wget", "-O", "-", "--no-check-certificate", "--load-cookies", cookiesfile, "--post-data", "submit=true&viewtype=stream&name="..logfile.."&filename="..logfile, source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/download"}
		cmd.stdin = "/dev/null"
		cmd.stdout = subprocess.PIPE
		cmd.stderr = "/dev/null"
		local res, err = pcall(function()
	                -- For security, set the path
	                posix.setenv("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin")
	                local proc, errmsg, errno = subprocess.popen(cmd)
			if proc then
				if string.find(logfile, "%.gz$") then
					local cmd2 = {"gunzip", "-c"}
					-- Pipe the output of wget into gunzip
					cmd2.stdin = proc.stdout
					cmd2.stdout = subprocess.PIPE
					cmd2.stderr = "/dev/null"
	                		local proc2, errmsg2, errno2 = subprocess.popen(cmd2)
					if proc2 then
						handle = proc2.stdout
						handle2 = proc.stdout
					else
						proc.stdout:close()
						errtxt = errmsg2 or "Unknown failure"
					end
				else
					handle = proc.stdout
				end
Ted Trask's avatar
Ted Trask committed
699

700 701 702 703 704 705
			else
				errtxt = errmsg or "Unknown failure"
			end
		end)
		if not res or err then
			errtxt = err or "Unknown failure"
706
		end
707
	elseif source.method == "local" then
708
		if string.find(logfile, "%.gz$") then
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
			local res, err = pcall(function()
	                	-- For security, set the path
		                posix.setenv("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin")
				local cmd = {"gunzip", "-c", logfile}
				cmd.stdin = "/dev/null"
				cmd.stdout = subprocess.PIPE
				cmd.stderr = "/dev/null"
	               		local proc, errmsg, errno = subprocess.popen(cmd)
				if proc then
					handle = proc.stdout
				else
					errtxt = errmsg or "Unknown failure"
				end
			end)
			if not res or err then
				errtxt = err or "Unknown failure"
			end
726
		else
727
			handle = io.open(logfile)
728
		end
Ted Trask's avatar
Ted Trask committed
729
	end
730
	return handle, handle2
Ted Trask's avatar
Ted Trask committed
731 732 733 734
end

local deletelogfile = function(source, cookiesfile, logfile)
	if source.method == "http" or source.method == "https" then
735
		modelfunctions.run_executable({"wget", "-O", "-", "--no-check-certificate", "--load-cookies", cookiesfile, "--post-data", "submit=true&name="..logfile.."&filename="..logfile, source.method.."://"..source.source.."/cgi-bin/acf/alpine-baselayout/logfiles/delete"})
736 737
	elseif source.method == "local" then
		os.remove(logfile)
Ted Trask's avatar
Ted Trask committed
738 739 740 741 742 743
	end
end

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

744
function mymodule.getsourcelist()
745
	local retval = cfe({ type="structure", value={}, label="Weblog Source List" })
Ted Trask's avatar
Ted Trask committed
746 747 748 749 750 751 752 753 754 755 756 757
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listsourceentries()
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

758 759
function mymodule.getsource(sourcename)
	local sourcedata = mymodule.getnewsource()
Ted Trask's avatar
Ted Trask committed
760 761
	sourcedata.value.sourcename.value = sourcename
	sourcedata.value.sourcename.errtxt = "Source name does not exist"
762
	sourcedata.value.sourcename.readonly = true
Ted Trask's avatar
Ted Trask committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

	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)
789 790 791 792 793 794
	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
795 796 797 798 799 800 801 802 803
		if sourcedata.value[name].value == "" then
			sourcedata.value[name].errtxt = "Cannot be empty"
			success = false
		end
	end

	return success
end

804
function mymodule.updatesource(self, sourcedata)
Ted Trask's avatar
Ted Trask committed
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
	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

827
function mymodule.getnewsource()
Ted Trask's avatar
Ted Trask committed
828
	local source = {}
829 830 831 832 833 834 835
	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
836 837 838
	return cfe({ type="group", value=source, label="Source" })
end

839
function mymodule.createsource(self, sourcedata)
Ted Trask's avatar
Ted Trask committed
840 841 842 843 844 845 846
	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
847 848
		-- remove spaces from sourcename
		source.sourcename = string.gsub(source.sourcename, "%s+$", "")
Ted Trask's avatar
Ted Trask committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863

		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

864
function mymodule.getdeletesource(self, clientdata)
865 866 867 868 869
	local retval = {}
	retval.sourcename = cfe({ value=clientdata.sourcename or "", label="Source Name" })
	return cfe({ type="group", value=retval, label="Delete Source" })
end

870
function mymodule.deletesource(self, delsource)
871
	delsource.errtxt="Failed to delete source"
Ted Trask's avatar
Ted Trask committed
872 873
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
874
		local number = deletesourceentry(delsource.value.sourcename.value)
Ted Trask's avatar
Ted Trask committed
875 876
		databasedisconnect()
		if number > 0 then
877 878 879
			delsource.errtxt = nil
		else
			delsource.value.sourcename.errtxt = "Failed to find source"
Ted Trask's avatar
Ted Trask committed
880 881 882
		end
	end)
	if not res and err then
883
		delsource.errtxt = delsource.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
884
	end
885
	return delsource
Ted Trask's avatar
Ted Trask committed
886 887
end

888
function mymodule.gettestsource(self, clientdata)
889 890 891 892
	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
893

894
function mymodule.testsource(self, test)
Ted Trask's avatar
Ted Trask committed
895
	-- temporary override of logme function to capture messages to result.value
896
	test.descr = {}
Ted Trask's avatar
Ted Trask committed
897
	local temp = logme
Ted Trask's avatar
Ted Trask committed
898
	logme = function(message) table.insert(test.descr, message) end
899 900

	test.errtxt = "Test Failed"
Ted Trask's avatar
Ted Trask committed
901 902 903 904

	local cookiesfile = "/tmp/cookies-"..tostring(os.time())
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
905
		local sources = listsourceentries(test.value.sourcename.value)
Ted Trask's avatar
Ted Trask committed
906 907
		databasedisconnect()
		if #sources < 1 then
908
			test.value.sourcename.errtxt = "Failed to find source"
Ted Trask's avatar
Ted Trask committed
909 910 911 912 913
		else
			local source = sources[1]
			-- run the test
			if connecttosource(source, cookiesfile) then
				local files = getlogcandidates(source, cookiesfile)
914
				test.errtxt = nil
Ted Trask's avatar
Ted Trask committed
915 916 917 918 919 920 921 922 923 924
				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)
925 926
	if err and not res then
		test.errtxt = test.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
927 928 929 930
	end
	os.remove(cookiesfile)

	-- fix the result
931
	test.descr = table.concat(test.descr, "\n") or ""
Ted Trask's avatar
Ted Trask committed
932 933
	logme = temp

934
	return test
Ted Trask's avatar
Ted Trask committed
935 936
end

937 938
-- import a logfile and delete logfile after
local function importlogfile(source, cookiesfile, file, parselog_func)
Ted Trask's avatar
Ted Trask committed
939
	logme("Getting " .. file )
940 941 942 943 944
	local loghandle, loghandle2 = openlogfile(source, cookiesfile, file)
	if not loghandle then
		logme("Failed to get " .. file )
		return
	end
Ted Trask's avatar
Ted Trask committed
945
	logme("Processing " .. file )
946 947 948
	local res, err = pcall(function()
		con:execute("START TRANSACTION")
		for line in loghandle:lines() do
949 950 951
			assert(con:execute("SAVEPOINT before_line"))
			local res2, err2 = pcall(function()
				local logentry = parselog_func(line)
952
				importlogentry(logentry, source.sourcename)
953 954 955 956 957 958
			end)
			if not res2 then
				if (config.stoponerror == "true") then
					pcall(function() con:execute("ROLLBACK") end)
				else
					assert(con:execute("ROLLBACK TO before_line"))
959
					con:execute("COMMIT")
960 961 962
				end
				pcall(function() logme("Exception on line:"..line) end)
				if err2 then
Ted Trask's avatar
Ted Trask committed
963
					pcall(function() logme(err2) end)
964 965 966
				end
				if (config.stoponerror == "true") then
					assert(res2, "Import halted on exception")
967 968
				else
					con:execute("START TRANSACTION")
969
				end
970 971
			else
				assert(con:execute("RELEASE SAVEPOINT before_line"))
972
			end
973 974 975 976 977 978 979 980
		end
		con:execute("COMMIT")
	end)
	if not res then
		pcall(function() con:execute("ROLLBACK") end)
		if err then
			pcall(function() logme(err) end)
		end
981
	end
982
	loghandle:close()
983 984 985
	if loghandle2 then
		loghandle2:close()
	end
986 987 988 989 990
	if res then
		logme("Deleting " .. file )
		deletelogfile(source, cookiesfile, file)
	end
	return res
991 992
end

993
function mymodule.getimportlogs(self, clientdata)
994 995 996 997
	local retval = {}
	return cfe({ type="group", value=retval, label="Import Logs" })
end

998
function mymodule.importlogs(self, import)
Ted Trask's avatar
Ted Trask committed
999
	local count = 0
1000
	local success = true
Ted Trask's avatar
Ted Trask committed
1001 1002 1003 1004 1005

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

		-- Download, parse, and import the logs
1006 1007 1008 1009
		logme("Executing importlogs")
		logme("Analyzing...")
		local sql = "ANALYZE"
		res = assert (con:execute(sql))
1010 1011 1012 1013 1014 1015

		-- 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 {}

1016 1017
		-- Determine sources
		local sources = listsourceentries(sourcename)
Ted Trask's avatar
Ted Trask committed
1018

Ted Trask's avatar
Ted Trask committed
1019 1020 1021 1022 1023 1024 1025
		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
1026
						if string.match(file, "dansguardian/access%.log[%.%-]") then
Ted Trask's avatar
Ted Trask committed
1027
							count = count + 1
1028
							success = importlogfile(source, cookiesfile, file, parsedglog) and success
Ted Trask's avatar
Ted Trask committed
1029
						elseif string.match(file, "squid/access%.log[%.%-]") then
Ted Trask's avatar
Ted Trask committed
1030
							count = count + 1
1031
							success = importlogfile(source, cookiesfile, file, parsesquidlog) and success
Ted Trask's avatar
Ted Trask committed
1032 1033 1034 1035 1036 1037 1038 1039
						end
					end
				end
				os.remove(cookiesfile)
			end
		end

		-- Process the logs
1040 1041
		if success then
			updateusagestats()
1042
			importpubweblog()
1043
		end
Ted Trask's avatar
Ted Trask committed
1044 1045 1046 1047 1048 1049 1050
		-- Purge old database entries
		groomusagestat()
		groomdbhistlog()
		groompublogs()

		databasedisconnect()
	end)
1051
	if not res or not success then
1052
		import.errtxt = "Import Logs Failure"
Ted Trask's avatar
Ted Trask committed
1053 1054
		if err then
			pcall(function() logme(err) end)
1055
			import.errtxt = import.errtxt .. "\n" .. err
Ted Trask's avatar
Ted Trask committed
1056
		end
1057
		pcall(function() databasedisconnect() end)
1058 1059
	else
		import.descr = "Imported "..tostring(count).." logs"
Ted Trask's avatar
Ted Trask committed
1060 1061
	end

1062
	return import
Ted Trask's avatar
Ted Trask committed
1063 1064
end

1065
function mymodule.getactivitylog()
1066
	local retval = cfe({ type="structure", value={}, label="Weblog Activity Log" })
Ted Trask's avatar
Ted Trask committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listhistorylogentries() or {}
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

1079
function mymodule.geteditselected()
Ted Trask's avatar
Ted Trask committed
1080 1081 1082 1083 1084 1085
	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

1086
function mymodule.editselected(self, data)
Ted Trask's avatar
Ted Trask committed
1087 1088 1089 1090
	local res, err = pcall(function()
		databaseconnect(DatabaseOwner)
		con:execute("START TRANSACTION")
		for i,sel in ipairs(data.value.select.value) do
1091
			assert (con:execute("UPDATE pubweblog SET selected = true WHERE id = '"..escape(sel).."'"))
Ted Trask's avatar
Ted Trask committed
1092
		end
Ted Trask's avatar
Ted Trask committed
1093
		for i,sel in ipairs(data.value.deselect.value) do
1094
			assert (con:execute("UPDATE pubweblog SET selected = false WHERE id = '"..escape(sel).."'"))
Ted Trask's avatar
Ted Trask committed
1095 1096 1097 1098 1099 1100
		end
		con:execute("COMMIT")
		databasedisconnect()
	end)
	if not res then
		data.errtxt = err
Ted Trask's avatar
Ted Trask committed
1101
	end
Ted Trask's avatar
Ted Trask committed
1102
	return data
1103 1104
end

1105
function mymodule.getclearselected(self, clientdata)
1106 1107 1108 1109
	local retval = {}
	return cfe({ type="group", value=retval, label="Clear select fields" })
end

1110
function mymodule.clearselected(self, clear)
1111
	clear.errtxt = "Failed to clear select fields"
1112 1113 1114 1115 1116
	local res, err = pcall(function()
		sql = "UPDATE pubweblog SET selected = false WHERE selected = true"
		databaseconnect(DatabaseOwner)
		assert (con:execute(sql))
		databasedisconnect()
1117
		clear.errtxt = nil
1118 1119
	end)
	if not res then
1120
		clear.errtxt = clear.errtxt.."\n"..err
1121
	end
1122
	return clear
1123 1124
end

1125 1126 1127
local validateweblogparameters = function(params)
	local success = modelfunctions.validateselect(params.value.activelog)
	success = modelfunctions.validateselect(params.value.sortby) and success
1128
	success = modelfunctions.validatemulti(params.value.sourcename) and success
1129 1130 1131
	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
1132
	end
1133 1134 1135 1136
	if not validator.is_integer(params.value.score.value) then
		params.value.score.errtxt = "Must be a number"
		success = false
	end
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	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
1159
	end
1160 1161
	return success
end
Ted Trask's avatar
Ted Trask committed
1162

1163
function mymodule.getweblogparameters(self, clientdata)
1164
	local c = mymodule.getconfig()
1165 1166 1167 1168
	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 })
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
	result.sourcename = cfe({ type="multi", value={}, label="Source", option={}, seq=4 })
	result.clientuserid = cfe({ value=clientdata.clientuserid or "", label="User ID", seq=5 })
	result.clientip = cfe({ value=clientdata.clientip or "", label="Client IP", seq=6 })
	result.urisearch = cfe({ value="", label="URI Contains", descr="Retrieve records where the URI contains this word", seq=7 })
	result.score = cfe({ value=c.value.score.value, label="Minimum Score", descr="Minimum score to search on", seq=8 })
	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=9 })
	result.badyesno = cfe({ type="boolean", value=c.value.badyesno.value, label="Show Suspect Records", descr="Limit search to records marked as suspect", seq=10 })
	result.deniedyesno = cfe({ type="boolean", value=c.value.deniedyesno.value, label="Show Denied Records", descr="Limit search to Denied URIs", seq=11 })
	result.bypassyesno = cfe({ type="boolean", value=c.value.bypassyesno.value, label="Show Bypass Records", descr="Limit search to Bypass attempts", seq=12 })
	result.selected = cfe({ type="boolean", value=false, label="Show Selected Records", descr="Limit search to records that have been selected", seq=13 })
	result.focus = cfe({ value="", label="Focus Time", seq=14 })

	-- Get the source options
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		local sources = listsourceentries()
		for i,s in ipairs(sources) do
			result.sourcename.value[#result.sourcename.value + 1] = s.sourcename
			result.sourcename.option[#result.sourcename.option + 1] = s.sourcename
		end
		databasedisconnect()
	end)
	if err and not res then
1192
		result.sourcename.errtxt = err
1193 1194
	end

1195 1196
	return cfe({ type="group", value=result, label="Weblog Access Log" })
end
Ted Trask's avatar
Ted Trask committed
1197

1198
function mymodule.getweblog(self, result)
1199
	local success = validateweblogparameters(result)
1200
	result.value.log = cfe({ type="structure", value={}, label="Weblog Access Log" })
1201 1202
	result.value.window = cfe({ value=config.window or "5", label="Time Window" })
	local err
1203 1204 1205
	if success then
		local res, err = pcall(function()
			databaseconnect(DatabaseUser)
1206
			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, result.value.sourcename.value ) or {}
1207 1208
			databasedisconnect()
		end)
1209 1210 1211
		if not res then
			result.errtxt = err
		end
1212
	else
1213
		result.errtxt = "Invalid search parameters"
1214
	end
1215
	return result
Ted Trask's avatar
Ted Trask committed
1216 1217
end

1218
function mymodule.getusagestats()
1219
	local retval = cfe({ type="structure", value={}, label="Weblog Usage Stats" })
Ted Trask's avatar
Ted Trask committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
	local res, err = pcall(function()
		databaseconnect(DatabaseUser)
		retval.value = listusagestats() or {}
		databasedisconnect()
	end)
	if not res then
		retval.errtxt = err
	end

	return retval
end

1232
function mymodule.getauditstats()
1233 1234 1235 1236
	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" })
1237
	result.stats = cfe({ type="structure", value={}, label="Audit Block Statistics" })
1238 1239 1240
	local res, err = pcall(function()
		if config.auditstart ~= "" and config.auditend ~= "" then
			databaseconnect(DatabaseUser)
1241
			result.stats.value = groupflaggedlogentries(config.auditstart, config.auditend, result.groupby.value) or {}
1242 1243 1244 1245 1246 1247
			databasedisconnect()
		end
	end)
	return cfe({ type="group", value=result, errtxt=err, label="Weblog Audit Statistics" })
end

1248
function mymodule.getcompleteaudit(self, clientdata)
1249 1250 1251 1252 1253
	local retval = {}
	retval.timestamp = cfe({ value=clientdata.timestamp or "", label="New Audit End Time" })
	return cfe({ type="group", value=retval, label="Complete Audit" })
end

1254
function mymodule.completeaudit(self, complete)
1255 1256