#!/usr/bin/env python
"""
This program parse the output from pcap_compile() to visualize the CFG after
each optimize phase.
Usage guide:
1. Enable optimizier debugging code when configure libpcap,
and build libpcap & the test programs
./configure --enable-optimizer-dbg
make
make testprogs
2. Run filtertest to compile BPF expression and produce the CFG as a
DOT graph, save to output a.txt
testprogs/filtertest -g EN10MB host 192.168.1.1 > a.txt
3. Send a.txt to this program's standard input
cat a.txt | testprogs/visopts.py
4. Step 2&3 can be merged:
testprogs/filtertest -g EN10MB host 192.168.1.1 | testprogs/visopts.py
5. The standard output is something like this:
generated files under directory: /tmp/visopts-W9ekBw
the directory will be removed when this programs finished.
open this link: http://localhost:39062/expr1.html
6. Using open link at the 3rd line `http://localhost:39062/expr1.html'
Note:
1. The CFG is translated to SVG an document, expr1.html embeded them as external
document. If you open expr1.html as local file using file:// protocol, some
browsers will deny such requests so the web pages will not shown properly.
For chrome, you can run it using following command to avoid this:
chromium --disable-web-security
That's why this program start a localhost http server.
2. expr1.html use jquery from http://ajax.googleapis.com, so you need internet
access to show the web page.
"""
import sys, os
import string
import subprocess
import json
html_template = string.Template("""
BPF compiler optimization phases for $expr
""")
def write_html(expr, gcount, logs):
logs = map(lambda s: s.strip().replace("\n", "
"), logs)
global html_template
html = html_template.safe_substitute(expr=expr.encode("string-escape"), gcount=gcount, logs=json.dumps(logs).encode("string-escape"))
with file("expr1.html", "wt") as f:
f.write(html)
def render_on_html(infile):
expr = None
gid = 1
log = ""
dot = ""
indot = 0
logs = []
for line in infile:
if line.startswith("machine codes for filter:"):
expr = line[len("machine codes for filter:"):].strip()
break
elif line.startswith("digraph BPF {"):
indot = 1
dot = line
elif indot:
dot += line
if line.startswith("}"):
indot = 2
else:
log += line
if indot == 2:
p = subprocess.Popen(['dot', '-Tsvg'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
svg = p.communicate(dot)[0]
with file("expr1_g%03d.svg" % (gid), "wt") as f:
f.write(svg)
logs.append(log)
gid += 1
log = ""
dot = ""
indot = 0
if indot != 0:
#unterminated dot graph for expression
return False
if expr is None:
# BPF parser encounter error(s)
return False
write_html(expr, gid - 1, logs)
return True
def run_httpd():
import SimpleHTTPServer
import SocketServer
class MySocketServer(SocketServer.TCPServer):
allow_reuse_address = True
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = MySocketServer(("localhost", 0), Handler)
print "open this link: http://localhost:%d/expr1.html" % (httpd.server_address[1])
try:
httpd.serve_forever()
except KeyboardInterrupt as e:
pass
def main():
import tempfile
import atexit
import shutil
os.chdir(tempfile.mkdtemp(prefix="visopts-"))
atexit.register(shutil.rmtree, os.getcwd())
print "generated files under directory: %s" % os.getcwd()
print " the directory will be removed when this programs finished."
if not render_on_html(sys.stdin):
return 1
run_httpd()
return 0
if __name__ == "__main__":
if '-h' in sys.argv or '--help' in sys.argv:
print __doc__
exit(0)
exit(main())