#!C:\Python26\python.exe
import cgi, cgitb, pickle, re
from buzhug import TS_Base
cgitb.enable()
print "Content-type: text/html"

#directory where the syslog server is installed
installDir = "D:\Syslog\\"

#loads the configuration parameters from the pickled file and opens the database
configs = pickle.load(open(installDir+"syslog.conf", 'r'))
dbName = installDir+configs["dbName"]
db = TS_Base(dbName).create(('srcIP', str), ('hostName', str), ('time', str), ('priority', int), ('facility', str), ('message', str), mode="open")
form = cgi.FieldStorage()

#default regex matching for blank fields
matchAll = re.compile('')
pattern = {"pri":7}
for i in ['ipAddr', 'hostName', 'facility', 'message', 'time']:
	pattern[i] = matchAll

#Any non-blank fields on the form (except priority) will have their value compiled to a regex and saved in the pattern dictionary.
if form.value != []:
	for i in form:
		if i == "priority":
			pattern["pri"] = int(form["priority"].value)
		else:
			pattern[i] = re.compile(form[i].value, re.I)
			
#database selection. Priority is stored as an integer, so we can't regex it.
dbSet = db.select(["time", "srcIP", "hostName", "priority", "facility", "message"], 't.search(time) and s.search(srcIP) and priority<=p and h.search(hostName) and f.search(facility) and m.search(message)', t=pattern["time"],s=pattern["ipAddr"],p=pattern["pri"],h=pattern["hostName"],f=pattern["facility"],m=pattern["message"])

#javascript for validating the IP Address and Priority field
print """
<html><head>
<script language="JavaScript" type="text/javascript">
function checkform(form)
{
	if (form.ipAddr.value != "" && !form.ipAddr.value.match(/^([0-9]{1,3}\.?){1,3}([0-9]{1,3})?$/)) {
		alert("Not a valid IP address.")
		return false
	}
	if (form.priority.value != "" && !form.priority.value.match(/^[0-7]$/)) {
		alert("Priority must be between 0 and 7.")
		return false
	}
	return true
}
</script>
<script src="js/sorttable.js"></script>
</head><body>

<form name="filter" method="post" onSubmit="return checkform(this)" action="/">
<table><tr>
<td>Time:</td>		<td><input type="text" name="time"/></td>
<td>IP Address:</td>	<td><input type="text" name="ipAddr"/></td>
<td>Hostname:</td>	<td><input type="text" name="hostName"/></td>
<td><a href="http://docs.python.org/library/re.html">Regex Reference</a></td>
</tr><tr>
<td>Priority:</td>	<td><input type="text" name="priority"/></td>
<td>Facility:</td>	<td><input type="text" name="facility"/></td>
<td>Message:</td>	<td><input type="text" name="message"/></td>
<td><input type="submit" value="Filter"/></td>
</form>
"""

#print the beginning of the table and column headers
print """
<table class="sortable" border="1">
<tr bgcolor=#666666><font color=color=#FFFFFF>
   <td>Time</td><td>IP Address</td><td>Hostname</td><td>Priority</td><td>Facility</td><td>Message</td>
</tr></font>
"""

#prints the selected records from oldest to newest in a table, with different colors based on priority
for record in reversed(dbSet):
	if record.priority <= configs["minPriHigh"]:
		bgcolor = "#FF0000"
	elif record.priority <= configs["minPriMed"]:
		bgcolor = "#FFCC00"
	else:
		bgcolor = "#CCCCCC"
	print "<tr bgcolor=" + bgcolor + ">"
	print "<td>" + record.time + "</td><td>" + record.srcIP + "</td><td>" + record.hostName + "</td><td>" + str(record.priority) + "</td><td>" + record.facility + "</td><td>" + record.message + "</td></tr>" 
		
print "</table>"

print """
</body></html>
"""

db.close()

"""
Goes into httpd.conf:

Alias /js "E:\htdocs\js"
ScriptAlias / "C:/Program Files/Apache Group/Apache2/cgi-bin/index.py"
"""