1
0
Fork 0
mirror of https://github.com/sileht/bird-lg.git synced 2024-11-22 06:54:43 +01:00

Rewrite the way that user input is handled

This commit is contained in:
Mehdi Abaakouk 2012-10-17 16:17:52 +02:00
parent 5bb5d42d0f
commit 6311df95e8
3 changed files with 41 additions and 47 deletions

71
lg.py
View file

@ -30,11 +30,11 @@ import json
import random import random
from toolbox import mask_is_valid, ipv6_is_valid, ipv4_is_valid, resolve, save_cache_pickle, load_cache_pickle, get_asn_from_as, unescape from toolbox import mask_is_valid, ipv6_is_valid, ipv4_is_valid, resolve, save_cache_pickle, load_cache_pickle, get_asn_from_as, unescape
from xml.sax.saxutils import escape #from xml.sax.saxutils import escape
import pydot import pydot
from flask import Flask, render_template, jsonify, redirect, session, request, abort, Response from flask import Flask, render_template, jsonify, redirect, session, request, abort, Response, Markup
app = Flask(__name__) app = Flask(__name__)
app.config.from_pyfile('lg.cfg') app.config.from_pyfile('lg.cfg')
@ -58,17 +58,17 @@ def add_links(text):
# Some heuristic to create link # Some heuristic to create link
if line.strip().startswith("BGP.as_path:") or \ if line.strip().startswith("BGP.as_path:") or \
line.strip().startswith("Neighbor AS:"): line.strip().startswith("Neighbor AS:"):
ret_text.append(re.sub(r'(\d+)', r'<a href="/whois/\1" class="whois">\1</a>', line)) ret_text.append(re.sub(r'(\d+)', r'<a href="/whois?q=\1" class="whois">\1</a>', line))
else: else:
line = re.sub(r'([a-zA-Z0-9\-]*\.([a-zA-Z]{2,3}){1,2})(\s|$)', r'<a href="/whois/\1" class="whois">\1</a>\3', line) line = re.sub(r'([a-zA-Z0-9\-]*\.([a-zA-Z]{2,3}){1,2})(\s|$)', r'<a href="/whois?q=\1" class="whois">\1</a>\3', line)
line = re.sub(r'AS(\d+)', r'<a href="/whois/\1" class="whois">AS\1</a>', line) line = re.sub(r'AS(\d+)', r'<a href="/whois?q=\1" class="whois">AS\1</a>', line)
line = re.sub(r'(\d+\.\d+\.\d+\.\d+)', r'<a href="/whois/\1" class="whois">\1</a>', line) line = re.sub(r'(\d+\.\d+\.\d+\.\d+)', r'<a href="/whois?q=\1" class="whois">\1</a>', line)
if len(request.path) >= 2: if len(request.path) >= 2:
hosts = "/".join(request.path.split("/")[2:]) hosts = "/".join(request.path.split("/")[2:])
else: else:
hosts = "/" hosts = "/"
line = re.sub(r'\[(\w+)\s+((|\d\d\d\d-\d\d-\d\d\s)(|\d\d:)\d\d:\d\d|\w\w\w\d\d)', r'[<a href="/detail/%s?q=\1">\1</a> \2' % hosts, line) line = re.sub(r'\[(\w+)\s+((|\d\d\d\d-\d\d-\d\d\s)(|\d\d:)\d\d:\d\d|\w\w\w\d\d)', r'[<a href="/detail/%s?q=\1">\1</a> \2' % hosts, line)
line = re.sub(r'(^|\s+)(([a-f\d]{0,4}:){3,10}[a-f\d]{0,4})', r'\1<a href="/whois/\2" class="whois">\2</a>', line, re.I) line = re.sub(r'(^|\s+)(([a-f\d]{0,4}:){3,10}[a-f\d]{0,4})', r'\1<a href="/whois?q=\2" class="whois">\2</a>', line, re.I)
ret_text.append(line) ret_text.append(line)
return "\n".join(ret_text) return "\n".join(ret_text)
@ -168,29 +168,26 @@ def hello():
def error_page(text): def error_page(text):
return render_template('error.html', error=text), 500 return render_template('error.html', errors=[text]), 500
@app.errorhandler(400) @app.errorhandler(400)
def incorrect_request(e): def incorrect_request(e):
return render_template('error.html', warning="The server could not understand the request"), 400 return render_template('error.html', warnings=["The server could not understand the request"]), 400
@app.errorhandler(404) @app.errorhandler(404)
def page_not_found(e): def page_not_found(e):
return render_template('error.html', warning="The requested URL was not found on the server."), 404 return render_template('error.html', warnings=["The requested URL was not found on the server."]), 404
def sanitized(*args): def get_query():
res = tuple( unescape(s) for s in args) q = unquote(request.args.get('q', '').strip())
if len(args) == 1: return q
return res[0]
else:
return res
@app.route("/whois/<query>") @app.route("/whois")
def whois(query): def whois():
query = sanitized(query) query = get_query()
if not query.strip(): if not query:
abort(400) abort(400)
try: try:
@ -212,13 +209,12 @@ SUMMARY_RE_MATCH = r"(?P<name>[\w_]+)\s+(?P<proto>\w+)\s+(?P<table>\w+)\s+(?P<st
@app.route("/summary/<hosts>") @app.route("/summary/<hosts>")
@app.route("/summary/<hosts>/<proto>") @app.route("/summary/<hosts>/<proto>")
def summary(hosts, proto="ipv4"): def summary(hosts, proto="ipv4"):
hosts, proto = sanitized(hosts, proto)
set_session("summary", hosts, proto, "") set_session("summary", hosts, proto, "")
command = "show protocols" command = "show protocols"
summary = {} summary = {}
error = [] errors = []
for host in hosts.split("+"): for host in hosts.split("+"):
ret, res = bird_command(host, proto, command) ret, res = bird_command(host, proto, command)
res = res.split("\n") res = res.split("\n")
@ -235,16 +231,14 @@ def summary(hosts, proto="ipv4"):
summary[host] = data summary[host] = data
else: else:
error.append("%s: bird command failed with error, %s" % (host, "\n".join(res))) errors.append("%s: bird command failed with error, %s" % (host, "\n".join(res)))
return render_template('summary.html', summary=summary, command=command, error="<br>".join(error)) return render_template('summary.html', summary=summary, command=command, errors=errors)
@app.route("/detail/<hosts>/<proto>") @app.route("/detail/<hosts>/<proto>")
def detail(hosts, proto): def detail(hosts, proto):
name = request.args.get('q', '').strip() name = get_query()
hosts, proto, name= sanitized(hosts, proto, name)
if not name: if not name:
abort(400) abort(400)
@ -253,22 +247,21 @@ def detail(hosts, proto):
command = "show protocols all %s" % name command = "show protocols all %s" % name
detail = {} detail = {}
error = [] errors = []
for host in hosts.split("+"): for host in hosts.split("+"):
ret, res = bird_command(host, proto, command) ret, res = bird_command(host, proto, command)
res = res.split("\n") res = res.split("\n")
if len(res) > 1: if len(res) > 1:
detail[host] = {"status": res[1], "description": add_links(res[2:])} detail[host] = {"status": res[1], "description": add_links(res[2:])}
else: else:
error.append("%s: bird command failed with error, %s" % (host, "\n".join(res))) errors.append("%s: bird command failed with error, %s" % (host, "\n".join(res)))
return render_template('detail.html', detail=detail, command=command, error="<br>".join(error)) return render_template('detail.html', detail=detail, command=command, errors=errors)
@app.route("/traceroute/<hosts>/<proto>") @app.route("/traceroute/<hosts>/<proto>")
def traceroute(hosts, proto): def traceroute(hosts, proto):
q = request.args.get('q', '').strip() q = get_query()
hosts, proto, q = sanitized(hosts, proto, q)
if not q: if not q:
abort(400) abort(400)
@ -362,12 +355,11 @@ def get_as_number_from_protocol_name(host, proto, protocol):
def show_bgpmap(): def show_bgpmap():
"""return a bgp map in a png file, from the json tree in q argument""" """return a bgp map in a png file, from the json tree in q argument"""
data = request.args.get('q', '').strip() data = get_query()
#data = sanitized(data)
if not data: if not data:
abort(400) abort(400)
data = json.loads(unquote(data)) data = json.loads(data)
graph = pydot.Dot('BGPMAP', graph_type='digraph') graph = pydot.Dot('BGPMAP', graph_type='digraph')
@ -521,8 +513,7 @@ def build_as_tree_from_raw_bird_ouput(host, proto, text):
def show_route(request_type, hosts, proto): def show_route(request_type, hosts, proto):
expression = request.args.get('q', '').strip() expression = get_query()
request_type, hosts, proto, expression = sanitized(request_type, hosts, proto, expression)
if not expression: if not expression:
abort(400) abort(400)
@ -569,7 +560,7 @@ def show_route(request_type, hosts, proto):
command = "show route for " + expression + all command = "show route for " + expression + all
detail = {} detail = {}
error = [] errors = []
for host in hosts.split("+"): for host in hosts.split("+"):
ret, res = bird_command(host, proto, command) ret, res = bird_command(host, proto, command)
@ -580,12 +571,12 @@ def show_route(request_type, hosts, proto):
else: else:
detail[host] = add_links(res) detail[host] = add_links(res)
else: else:
error.append("%s: bird command failed with error, %s" % (host, "\n".join(res))) errors.append("%s: bird command failed with error, %s" % (host, "\n".join(res)))
if bgpmap: if bgpmap:
detail = json.dumps(detail) detail = json.dumps(detail)
return render_template((bgpmap and 'bgpmap.html' or 'route.html'), detail=detail, command=command, expression=expression, error="<br />".join(error)) return render_template((bgpmap and 'bgpmap.html' or 'route.html'), detail=detail, command=command, expression=expression, errors=errors)
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -14,7 +14,7 @@ function reload(){
loc = "/" + request_type + "/" + hosts + "/" + proto; loc = "/" + request_type + "/" + hosts + "/" + proto;
if (request_type != "summary" ){ if (request_type != "summary" ){
if( request_args != undefined && request_args != ""){ if( request_args != undefined && request_args != ""){
loc = loc + "?q=" + request_args; loc = loc + "?q=" + escape(request_args);
change_url(loc) change_url(loc)
} }
} else { } else {

View file

@ -64,11 +64,15 @@
<div class="container-fluid"> <div class="container-fluid">
<div class="row-fluid"> <div class="row-fluid">
<div class="span8"> <div class="span8">
{% if warning %} {% if warnings %}
<div class="alert alert-warning">{{warning|safe}}</div> <div class="alert alert-warning">
{% for warning in warnings %}{{warning}}<br />{% endfor %}
</div>
{% endif %} {% endif %}
{% if error %} {% if errors %}
<div class="alert alert-error">{{error|safe}}</div> <div class="alert alert-error">
{% for error in errors %}{{error}}<br />{% endfor %}
</div>
{% endif %} {% endif %}
{% block body %}{% endblock %} {% block body %}{% endblock %}
@ -112,12 +116,11 @@
</div> </div>
<script type="text/javascript" src="{{url_for('static', filename='js/jquery.js') }}"></script> <script type="text/javascript" src="{{url_for('static', filename='js/jquery.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename='js/bootstrap.min.js') }}"></script> <script type="text/javascript" src="{{url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename='js/jquery-impromptu.3.2.min.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename='js/jquery.dataTables.js') }}"></script> <script type="text/javascript" src="{{url_for('static', filename='js/jquery.dataTables.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename='js/DT_bootstrap.js') }}"></script> <script type="text/javascript" src="{{url_for('static', filename='js/DT_bootstrap.js') }}"></script>
<script type="text/javascript"> <script type="text/javascript">
request_type = "{{session.request_type}}"; request_type = "{{session.request_type}}";
request_args = "{{session.request_args}}"; request_args = "{{session.request_args|safe}}";
hosts = "{{session.hosts}}"; hosts = "{{session.hosts}}";
proto = "{{session.proto}}"; proto = "{{session.proto}}";
history_query = {{session.history|tojson|safe}}; history_query = {{session.history|tojson|safe}};