fixed some identations and added browser automatic launcher

This commit is contained in:
psy 2013-09-05 08:45:09 -07:00
parent 7b83722aaa
commit f1548d52eb
2 changed files with 113 additions and 132 deletions

66
main.py
View File

@ -26,12 +26,12 @@ DEBUG = 1
class bc(object): class bc(object):
""" """
BC main Class BC main Class
""" """
def __init__(self): def __init__(self):
""" """
Init defaults Init defaults
""" """
self.browser = "" # "F" Firefox / "C" Chrome self.browser = "" # "F" Firefox / "C" Chrome
self.browser_path = "" self.browser_path = ""
self.url = "" self.url = ""
@ -39,14 +39,14 @@ Init defaults
def set_options(self, options): def set_options(self, options):
""" """
Set program options Set program options
""" """
self.options = options self.options = options
def create_options(self, args=None): def create_options(self, args=None):
""" """
Create options for OptionParser Create options for OptionParser
""" """
self.optionParser = BCOptions() self.optionParser = BCOptions()
self.options = self.optionParser.get_options(args) self.options = self.optionParser.get_options(args)
if not self.options: if not self.options:
@ -55,8 +55,8 @@ Create options for OptionParser
def try_running(self, func, error, args=None): def try_running(self, func, error, args=None):
""" """
Try running a function and print some error if it fails and exists with a fatal error. Try running a function and print some error if it fails and exists with a fatal error.
""" """
options = self.options options = self.options
args = args or [] args = args or []
try: try:
@ -72,8 +72,8 @@ Try running a function and print some error if it fails and exists with a fatal
def check_browser(self): def check_browser(self):
""" """
Check for browser used by system Check browsers used by system
""" """
if sys.platform == 'darwin': if sys.platform == 'darwin':
f_osx = os.path.join(os.path.expanduser('~'), 'Library/Application Support/Firefox/Profiles') f_osx = os.path.join(os.path.expanduser('~'), 'Library/Application Support/Firefox/Profiles')
c_osx = os.path.join(os.path.expanduser('~'), 'Library/Application Support/Google/Chrome/Default/History') c_osx = os.path.join(os.path.expanduser('~'), 'Library/Application Support/Google/Chrome/Default/History')
@ -81,7 +81,7 @@ Check for browser used by system
try: try:
if os.path.exists(f_osx): if os.path.exists(f_osx):
if len(os.listdir(f_osx)) > 2: if len(os.listdir(f_osx)) > 2:
print 'you have multiple profiles, choosing the last one used' print 'You have multiple profiles, choosing the last one used'
#filtering the directory that was last modified #filtering the directory that was last modified
all_subdirs = [os.path.join(f_osx,d)for d in os.listdir(f_osx)] all_subdirs = [os.path.join(f_osx,d)for d in os.listdir(f_osx)]
try: try:
@ -89,37 +89,30 @@ Check for browser used by system
except: except:
pass pass
latest_subdir = max(all_subdirs, key=os.path.getmtime) latest_subdir = max(all_subdirs, key=os.path.getmtime)
osx_profile = os.path.join(f_osx, latest_subdir) osx_profile = os.path.join(f_osx, latest_subdir)
osx_history_path = os.path.join(osx_profile, 'places.sqlite') osx_history_path = os.path.join(osx_profile, 'places.sqlite')
self.browser_path = osx_history_path self.browser_path = osx_history_path
else: else:
for folder in os.listdir(f_osx): for folder in os.listdir(f_osx):
if folder.endswith('.default'): if folder.endswith('.default'):
osx_default = os.path.join(f_osx, folder) osx_default = os.path.join(f_osx, folder)
osx_history_path = os.path.join(osx_default, 'places.sqlite') osx_history_path = os.path.join(osx_default, 'places.sqlite')
print "setting:", osx_history_path, "as history file" print "Setting:", osx_history_path, "as history file"
self.browser_path = osx_history_path self.browser_path = osx_history_path
self.browser = "F" self.browser = "F"
elif os.path.exists(c_osx): elif os.path.exists(c_osx):
self.browser = "C" self.browser = "C"
self.browser_path = c_osx self.browser_path = c_osx
elif os.path.exists(chromium_osx): elif os.path.exists(chromium_osx):
self.browser = "CHROMIUM" self.browser = "CHROMIUM"
self.browser_path = chromium_osx self.browser_path = chromium_osx
except: except:
print "no firefox or chrome installed" print "Warning: No firefox or chrome installed."
elif sys.platform.startswith('linux'): elif sys.platform.startswith('linux'):
f_lin = os.path.join(os.path.expanduser('~'), '.mozilla/firefox/') #add the next folder f_lin = os.path.join(os.path.expanduser('~'), '.mozilla/firefox/') #add the next folder
c_lin = os.path.join(os.path.expanduser('~'), '.config/google-chrome/History') c_lin = os.path.join(os.path.expanduser('~'), '.config/google-chrome/History')
chromium_lin = os.path.join(os.path.expanduser('~'), '.config/chromium/Default/History') chromium_lin = os.path.join(os.path.expanduser('~'), '.config/chromium/Default/History')
if os.path.exists(f_lin): if os.path.exists(f_lin):
#missing multiple profile support #missing multiple profile support
for folder in os.listdir(f_lin): for folder in os.listdir(f_lin):
@ -128,20 +121,17 @@ Check for browser used by system
lin_history_path = os.path.join(lin_default, 'places.sqlite') lin_history_path = os.path.join(lin_default, 'places.sqlite')
self.browser = "F" self.browser = "F"
self.browser_path = lin_history_path self.browser_path = lin_history_path
elif os.path.exists(c_lin): elif os.path.exists(c_lin):
self.browser = "C" self.browser = "C"
self.browser_path = c_lin self.browser_path = c_lin
elif os.path.exists(chromium_lin): elif os.path.exists(chromium_lin):
self.browser = "CHROMIUM" self.browser = "CHROMIUM"
self.browser_path = chromium_lin self.browser_path = chromium_lin
def getURL(self): def getURL(self):
""" """
Set urls to visit Set urls to visit
""" """
print "Browser database:", self.browser_path, "\n" print "Browser database:", self.browser_path, "\n"
conn = sqlite3.connect(self.browser_path) conn = sqlite3.connect(self.browser_path)
c = conn.cursor() c = conn.cursor()
@ -149,10 +139,6 @@ Set urls to visit
if self.browser == "F": #Firefox history database if self.browser == "F": #Firefox history database
c.execute('select url, last_visit_date from moz_places ORDER BY last_visit_date DESC') c.execute('select url, last_visit_date from moz_places ORDER BY last_visit_date DESC')
elif self.browser == "C": #Chrome history database elif self.browser == "C": #Chrome history database
# Linux: /home/$USER/.config/google-chrome/
# Linux: /home/$USER/.config/chromium/
# Windows Vista (and Win 7): C:\Users\[USERNAME]\AppData\Local\Google\Chrome\
# Windows XP: C:\Documents and Settings\[USERNAME]\Local Settings\Application Data\Google\Chrome\
c.execute('select urls.url, urls.title, urls.visit_count, urls.typed_count, urls.last_visit_time, urls.hidden, visits.visit_time, visits.from_visit, visits.transition from urls, visits where urls.id = visits.url') c.execute('select urls.url, urls.title, urls.visit_count, urls.typed_count, urls.last_visit_time, urls.hidden, visits.visit_time, visits.from_visit, visits.transition from urls, visits where urls.id = visits.url')
else: # Browser not allowed else: # Browser not allowed
print "\nSorry, you haven't a compatible browser\n\n" print "\nSorry, you haven't a compatible browser\n\n"
@ -164,8 +150,8 @@ Set urls to visit
def getGEO(self): def getGEO(self):
""" """
Get Geolocation database (http://dev.maxmind.com/geoip/legacy/geolite/) Get Geolocation database (http://dev.maxmind.com/geoip/legacy/geolite/)
""" """
# Download and extract database # Download and extract database
try: try:
urllib.urlretrieve('http://xsser.sf.net/map/GeoLiteCity.dat.gz', urllib.urlretrieve('http://xsser.sf.net/map/GeoLiteCity.dat.gz',
@ -183,9 +169,8 @@ Get Geolocation database (http://dev.maxmind.com/geoip/legacy/geolite/)
def run(self, opts=None): def run(self, opts=None):
""" """
Run BorderCheck Run BorderCheck
""" """
#eprint = sys.stderr.write
# set options # set options
if opts: if opts:
options = self.create_options(opts) options = self.create_options(opts)
@ -203,17 +188,16 @@ Run BorderCheck
print "url:", self.url print "url:", self.url
# start web mode # start web mode
print("Running webserver\n") print("Running webserver\n")
BorderCheckWebserver(self) BorderCheckWebserver(self) #child process or another thread
while True: while True:
url = urlparse(self.url[0]).netloc url = urlparse(self.url[0]).netloc
url = url.replace('www.','') #--> doing a tracert to for example.com and www.example.com yields different results most of the times. url = url.replace('www.','') #--> doing a tracert to example.com and www.example.com yields different results.
url_ip = socket.gethostbyname(url) url_ip = socket.gethostbyname(url)
print url_ip print url_ip
if url != self.old_url: if url != self.old_url:
count = 0 count = 0
print url print url
a = subprocess.Popen(['lft', '-S', '-n', '-E', url_ip], stdout=subprocess.PIPE) # -> using tcp a = subprocess.Popen(['lft', '-S', '-n', '-E', url_ip], stdout=subprocess.PIPE) # -> using tcp
#a = subprocess.Popen(['lft', '-S', '-n', '-u', url_ip], stdout=subprocess.PIPE) # -> using udp #a = subprocess.Popen(['lft', '-S', '-n', '-u', url_ip], stdout=subprocess.PIPE) # -> using udp
logfile = open('logfile', 'a') logfile = open('logfile', 'a')
@ -240,7 +224,7 @@ Run BorderCheck
exit() exit()
self.old_url = url self.old_url = url
print"old url =", self.old_url print "old url = ", self.old_url
logfile.close() logfile.close()
time.sleep(5) time.sleep(5)
@ -249,4 +233,4 @@ if __name__ == "__main__":
options = app.create_options() options = app.create_options()
if options: if options:
app.set_options(options) app.set_options(options)
app.run() app.run()

View File

@ -12,6 +12,7 @@ from runpy import run_module
from urlparse import urlparse from urlparse import urlparse
from cgi import parse_qs #, parse_header, parse_multipart from cgi import parse_qs #, parse_header, parse_multipart
import cgi import cgi
import webbrowser
port = 8080 port = 8080
wwwroot = "web/" wwwroot = "web/"
@ -21,106 +22,103 @@ class ForkingTCPServer(ForkingMixIn, HTTPServer): pass
class ThreadingTCPServer(ThreadingMixIn, HTTPServer): pass class ThreadingTCPServer(ThreadingMixIn, HTTPServer): pass
def print_exception(type=None, value=None, tb=None, limit=None): def print_exception(type=None, value=None, tb=None, limit=None):
if type is None: if type is None:
type, value, tb = sys.exc_info() type, value, tb = sys.exc_info()
import traceback import traceback
ret = "<html><body><h2>Traceback (most recent call last):<h2 />" ret = "<html><body><h2>Traceback (most recent call last):<h2 />"
ret += "<pre>" ret += "<pre>"
list = traceback.format_tb(tb, limit) + \ list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(type, value) traceback.format_exception_only(type, value)
ret += "exception error" ret += "exception error"
ret += "%s: %s<br/>\n" % ( ("\n".join(list[:-1])), (list[-1])) ret += "%s: %s<br/>\n" % ( ("\n".join(list[:-1])), (list[-1]))
ret +="</body></html>" ret +="</body></html>"
del tb del tb
return ret return ret
class HttpHandler(BaseHTTPRequestHandler): class HttpHandler(BaseHTTPRequestHandler):
def client_not_allowed(self, addr):
# TODO: whitelist out there return False
def client_not_allowed(self, addr): if addr == "127.0.0.1":
return False return False
if addr == "127.0.0.1": print ("Client not allowed ",addr)
return False return True
print ("Client not allowed ",addr)
return True
def serve(self): def serve(self):
output = "" output = ""
uri = self.path uri = self.path
tmp = uri.find ('?') tmp = uri.find ('?')
args = parse_qs(urlparse(uri)[4]) args = parse_qs(urlparse(uri)[4])
#from ipdb import set_trace;set_trace() if tmp != -1:
if tmp != -1: uri = uri[0:tmp]
uri = uri[0:tmp] for a in uri[tmp:-1].split("&"):
for a in uri[tmp:-1].split("&"): sep = a.find ("=")
sep = a.find ("=") if sep != -1:
if sep != -1: print "%s)(%s"%(a[0:sep],a[sep:-1])
print "%s)(%s"%(a[0:sep],a[sep:-1]) args[a[0:sep]]=a[sep:-1]
args[a[0:sep]]=a[sep:-1]
file = wwwroot + "/" + uri file = wwwroot + "/" + uri
if self.client_not_allowed (self.client_address[0]): if self.client_not_allowed (self.client_address[0]):
self.wfile.write ("HTTP/1.0 503 Not allowed\r\n\r\nYou are not whitelisted") self.wfile.write ("HTTP/1.0 503 Not allowed\r\n\r\nYou are not whitelisted")
return return
content = "" content = ""
try: try:
ctype,pdict = cgi.parse_header(self.headers.getheader('content-type')) ctype,pdict = cgi.parse_header(self.headers.getheader('content-type'))
print "CTYPE IS ",ctype print "CTYPE IS ",ctype
if ctype == 'multipart/form-data': if ctype == 'multipart/form-data':
query = cgi.parse_multipart(self.rfile, pdict) query = cgi.parse_multipart(self.rfile, pdict)
content = query.get('upfile') content = query.get('upfile')
except: except:
pass pass
print "Request from %s:%d"%self.client_address+" "+uri print "Request from %s:%d"%self.client_address + " " + uri
if uri[-1] == '/' or os.path.isdir(file): if uri[-1] == '/' or os.path.isdir(file):
file = file + "/index.py" file = file + "/index.py"
if os.path.isfile(file+".py"): if os.path.isfile(file + ".py"):
file = file + ".py" file = file + ".py"
if file.find("py") != -1: if file.find("py") != -1:
modname = file.replace(".py", "") modname = file.replace(".py", "")
cwd = modname[0:modname.rfind('/')]+"/" cwd = modname[0:modname.rfind('/')] + "/"
modname = modname.replace("/", ".") modname = modname.replace("/", ".")
while modname.find("..") != -1: while modname.find("..") != -1:
modname = modname.replace("..",".") modname = modname.replace("..",".")
globals = { globals = {
"output": output, "output": output,
"http": http, "http": http,
"uri": uri, "uri": uri,
"args": args, "args": args,
"cwd": cwd, "cwd": cwd,
"headers": self.headers, "content": content
"content": content }
} try:
try: a = run_module(modname, init_globals=globals)
a = run_module(modname, init_globals=globals) output = a["output"]
output = a["output"] except:
except: output = print_exception()
output = print_exception() else:
else: try:
try: f = open (file, "r")
f = open (file, "r") output = f.read ()
output = f.read () f.close ()
f.close () except:
except: output = "404"
output = "404" if output == "404":
if output == "404": self.wfile.write ("HTTP/1.0 404 Not found\r\n\r\n")
self.wfile.write ("HTTP/1.0 404 Not found\r\n\r\n") else:
else: self.wfile.write ("HTTP/1.0 200 OK\r\n\r\n")
self.wfile.write ("HTTP/1.0 200 OK\r\n\r\n") self.wfile.write (output)
self.wfile.write (output)
def do_POST (self): def do_POST (self):
self.serve () self.serve ()
def do_GET (self): def do_GET (self):
self.serve () self.serve ()
class BorderCheckWebserver(): class BorderCheckWebserver():
def __init__(self, ref, *args): def __init__(self, ref, *args):
HttpHandler.ref = ref HttpHandler.ref = ref
httpd = HTTPServer(('', port), HttpHandler) httpd = HTTPServer(('', port), HttpHandler)
print "http://127.0.0.1:%d/ : Serving directory '%s/www'" % (port, os.getcwd()) print "http://127.0.0.1:%d/ : Serving directory '%s/www'" % (port, os.getcwd())
webbrowser.open('http://127.0.0.1:8080', new=1)
try: try:
httpd.serve_forever() httpd.serve_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
@ -130,8 +128,7 @@ if __name__=="__main__":
wwwroot = "www" wwwroot = "www"
httpd = HTTPServer(('', port), HttpHandler) httpd = HTTPServer(('', port), HttpHandler)
print "http://127.0.0.1:%d/ : Serving directory '%s/www'" % (port, os.getcwd()) print "http://127.0.0.1:%d/ : Serving directory '%s/www'" % (port, os.getcwd())
try: try:
httpd.serve_forever() httpd.serve_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
print 'Server killed on user request (keyboard interrupt).' print 'Server killed on user request (keyboard interrupt).'