mirror of https://github.com/ntop/n2n.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
533 lines
14 KiB
533 lines
14 KiB
3 years ago
|
#!/usr/bin/env python3
|
||
|
# Licensed under GPLv3
|
||
|
#
|
||
|
# Simple http server to allow user control of n2n edge nodes
|
||
|
#
|
||
3 years ago
|
# Currently only for demonstration
|
||
|
# - needs nicer looking html written
|
||
|
# - needs more json interfaces in edge
|
||
3 years ago
|
#
|
||
|
# Try it out with
|
||
3 years ago
|
# http://localhost:8080/
|
||
3 years ago
|
# http://localhost:8080/edge/edges
|
||
|
# http://localhost:8080/edge/supernodes
|
||
3 years ago
|
|
||
|
import argparse
|
||
|
import socket
|
||
|
import json
|
||
|
import socketserver
|
||
|
import http.server
|
||
3 years ago
|
import signal
|
||
|
import functools
|
||
3 years ago
|
import base64
|
||
3 years ago
|
|
||
|
from http import HTTPStatus
|
||
|
|
||
|
|
||
3 years ago
|
class JsonUDP():
|
||
|
"""encapsulate communication with the edge"""
|
||
3 years ago
|
|
||
3 years ago
|
def __init__(self, port):
|
||
|
self.address = "127.0.0.1"
|
||
|
self.port = port
|
||
|
self.tag = 0
|
||
|
self.key = None
|
||
|
self.debug = False
|
||
|
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
3 years ago
|
|
||
3 years ago
|
def _next_tag(self):
|
||
|
tagstr = str(self.tag)
|
||
|
self.tag = (self.tag + 1) % 1000
|
||
|
return tagstr
|
||
3 years ago
|
|
||
3 years ago
|
def _cmdstr(self, msgtype, cmdline):
|
||
|
"""Create the full command string to send"""
|
||
|
tagstr = self._next_tag()
|
||
3 years ago
|
|
||
3 years ago
|
options = [tagstr]
|
||
|
if self.key is not None:
|
||
|
options += ['1'] # Flags set for auth key field
|
||
|
options += [self.key]
|
||
|
optionsstr = ':'.join(options)
|
||
3 years ago
|
|
||
3 years ago
|
return tagstr, ' '.join((msgtype, optionsstr, cmdline))
|
||
3 years ago
|
|
||
3 years ago
|
def _rx(self, tagstr):
|
||
|
"""Wait for rx packets"""
|
||
3 years ago
|
|
||
3 years ago
|
# TODO: there are no timeouts with any of the recv calls
|
||
|
data, _ = self.sock.recvfrom(1024)
|
||
3 years ago
|
data = json.loads(data.decode('utf8'))
|
||
3 years ago
|
|
||
|
# TODO: We assume the first packet we get will be tagged for us
|
||
|
# and be either an "error" or a "begin"
|
||
3 years ago
|
assert(data['_tag'] == tagstr)
|
||
|
|
||
3 years ago
|
if data['_type'] == 'error':
|
||
|
raise ValueError('Error: {}'.format(data['error']))
|
||
|
|
||
|
assert(data['_type'] == 'begin')
|
||
|
|
||
|
# Ideally, we would confirm that this is our "begin", but that
|
||
|
# would need the cmd passed into this method, and that would
|
||
|
# probably require parsing the cmdline passed to us :-(
|
||
|
# assert(data['cmd'] == cmd)
|
||
|
|
||
|
result = list()
|
||
3 years ago
|
error = None
|
||
3 years ago
|
|
||
|
while True:
|
||
|
data, _ = self.sock.recvfrom(1024)
|
||
|
data = json.loads(data.decode('utf8'))
|
||
|
|
||
|
if data['_tag'] != tagstr:
|
||
|
# this packet is not for us, ignore it
|
||
|
continue
|
||
|
|
||
|
if data['_type'] == 'error':
|
||
3 years ago
|
# we still expect an end packet, so save the error
|
||
|
error = ValueError('Error: {}'.format(data['error']))
|
||
|
continue
|
||
3 years ago
|
|
||
|
if data['_type'] == 'end':
|
||
3 years ago
|
if error:
|
||
|
raise error
|
||
3 years ago
|
return result
|
||
3 years ago
|
|
||
3 years ago
|
if data['_type'] != 'row':
|
||
|
raise ValueError('Unknown data type {} from '
|
||
|
'edge'.format(data['_type']))
|
||
3 years ago
|
|
||
3 years ago
|
# remove our boring metadata
|
||
|
del data['_tag']
|
||
|
del data['_type']
|
||
3 years ago
|
|
||
3 years ago
|
if self.debug:
|
||
|
print(data)
|
||
3 years ago
|
|
||
3 years ago
|
result.append(data)
|
||
3 years ago
|
|
||
3 years ago
|
def _call(self, msgtype, cmdline):
|
||
|
"""Perform a rpc call"""
|
||
|
tagstr, msgstr = self._cmdstr(msgtype, cmdline)
|
||
|
self.sock.sendto(msgstr.encode('utf8'), (self.address, self.port))
|
||
|
return self._rx(tagstr)
|
||
|
|
||
|
def read(self, cmdline):
|
||
|
return self._call('r', cmdline)
|
||
|
|
||
|
def write(self, cmdline):
|
||
|
return self._call('w', cmdline)
|
||
3 years ago
|
|
||
|
|
||
3 years ago
|
pages = {
|
||
|
"/script.js": {
|
||
|
"content_type": "text/javascript",
|
||
|
"content": """
|
||
|
var verbose=-1;
|
||
3 years ago
|
|
||
3 years ago
|
function rows2verbose(id, unused, data) {
|
||
|
row0 = data[0]
|
||
|
verbose = row0['traceLevel']
|
||
|
|
||
|
let div = document.getElementById(id);
|
||
|
div.innerHTML=verbose
|
||
|
}
|
||
|
|
||
|
function rows2keyvalue(id, keys, data) {
|
||
|
let s = "<table border=1 cellspacing=0>"
|
||
|
data.forEach((row) => {
|
||
|
keys.forEach((key) => {
|
||
|
if (key in row) {
|
||
|
s += "<tr><th>" + key + "<td>" + row[key];
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
|
||
|
s += "</table>"
|
||
|
let div = document.getElementById(id);
|
||
|
div.innerHTML=s
|
||
|
}
|
||
|
|
||
|
function rows2keyvalueall(id, unused, data) {
|
||
|
let s = "<table border=1 cellspacing=0>"
|
||
|
data.forEach((row) => {
|
||
|
Object.keys(row).forEach((key) => {
|
||
|
s += "<tr><th>" + key + "<td>" + row[key];
|
||
|
});
|
||
|
});
|
||
|
|
||
|
s += "</table>"
|
||
|
let div = document.getElementById(id);
|
||
|
div.innerHTML=s
|
||
|
}
|
||
|
|
||
|
function rows2table(id, columns, data) {
|
||
3 years ago
|
let s = "<table border=1 cellspacing=0>"
|
||
|
s += "<tr>"
|
||
|
columns.forEach((col) => {
|
||
|
s += "<th>" + col
|
||
|
});
|
||
|
data.forEach((row) => {
|
||
|
s += "<tr>"
|
||
|
columns.forEach((col) => {
|
||
3 years ago
|
val = row[col]
|
||
|
if (typeof val === "undefined") {
|
||
|
val = ''
|
||
|
}
|
||
|
s += "<td>" + val
|
||
3 years ago
|
});
|
||
|
});
|
||
|
|
||
|
s += "</table>"
|
||
|
let div = document.getElementById(id);
|
||
|
div.innerHTML=s
|
||
3 years ago
|
}
|
||
3 years ago
|
|
||
3 years ago
|
function do_get(url, id, handler, handler_param) {
|
||
3 years ago
|
fetch(url)
|
||
|
.then(function (response) {
|
||
|
return response.json();
|
||
|
})
|
||
|
.then(function (data) {
|
||
3 years ago
|
handler(id,handler_param,data);
|
||
|
|
||
|
// update the timestamp on success
|
||
|
let now = Math.round(new Date().getTime() / 1000);
|
||
|
let time = document.getElementById('time');
|
||
|
time.innerHTML=now;
|
||
3 years ago
|
})
|
||
|
.catch(function (err) {
|
||
|
console.log('error: ' + err);
|
||
|
});
|
||
3 years ago
|
}
|
||
3 years ago
|
|
||
3 years ago
|
function do_post(url, body, id, handler, handler_param) {
|
||
|
fetch(url, {method:'POST', body: body})
|
||
|
.then(function (response) {
|
||
|
return response.json();
|
||
|
})
|
||
|
.then(function (data) {
|
||
|
handler(id,handler_param,data);
|
||
|
})
|
||
|
.catch(function (err) {
|
||
|
console.log('error: ' + err);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
function do_stop(tracelevel) {
|
||
|
// FIXME: uses global in script library
|
||
|
fetch(nodetype + '/stop', {method:'POST'})
|
||
|
}
|
||
|
|
||
|
function setverbose(tracelevel) {
|
||
|
if (tracelevel < 0) {
|
||
|
tracelevel = 0;
|
||
|
}
|
||
|
// FIXME: uses global in script library
|
||
|
do_post(
|
||
|
nodetype + '/verbose', tracelevel, 'verbose',
|
||
|
rows2verbose, null
|
||
|
);
|
||
|
}
|
||
3 years ago
|
|
||
3 years ago
|
function refresh_setup(interval) {
|
||
|
var timer = setInterval(refresh_job, interval);
|
||
|
}
|
||
|
""",
|
||
|
},
|
||
|
"/": {
|
||
|
"content_type": "text/html; charset=utf-8",
|
||
|
"content": """
|
||
|
<html>
|
||
|
<head>
|
||
|
<title>n2n edge management</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<table>
|
||
|
<tr>
|
||
|
<td>Last Updated:
|
||
|
<td><div id="time"></div>
|
||
|
<td><button onclick=refresh_job()>update</button>
|
||
|
<td><button onclick=do_stop()>stop edge</button>
|
||
|
<tr>
|
||
|
<td>Logging Verbosity:
|
||
|
<td>
|
||
|
<div id="verbose"></div>
|
||
|
<td>
|
||
|
<button onclick=setverbose(verbose+1)>+</button>
|
||
|
<button onclick=setverbose(verbose-1)>-</button>
|
||
|
</table>
|
||
|
<br>
|
||
|
<div id="communities"></div>
|
||
|
<br>
|
||
|
Edges/Peers:
|
||
|
<div id="edges"></div>
|
||
|
<br>
|
||
|
Supernodes:
|
||
|
<div id="supernodes"></div>
|
||
|
<br>
|
||
|
<div id="timestamps"></div>
|
||
|
<br>
|
||
|
<div id="packetstats"></div>
|
||
3 years ago
|
|
||
3 years ago
|
<script src="script.js"></script>
|
||
|
<script>
|
||
|
// FIXME: hacky global
|
||
|
var nodetype="edge";
|
||
|
|
||
|
function refresh_job() {
|
||
|
do_get(
|
||
|
nodetype + '/verbose', 'verbose',
|
||
|
rows2verbose, null
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/communities', 'communities',
|
||
|
rows2keyvalue, ['community']
|
||
3 years ago
|
);
|
||
3 years ago
|
do_get(
|
||
|
nodetype + '/supernodes', 'supernodes',
|
||
|
rows2table, ['version','current','macaddr','sockaddr','uptime']
|
||
3 years ago
|
);
|
||
3 years ago
|
do_get(
|
||
|
nodetype + '/edges', 'edges',
|
||
|
rows2table, ['mode','ip4addr','macaddr','sockaddr','desc']
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/timestamps', 'timestamps',
|
||
|
rows2keyvalueall, null
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/packetstats', 'packetstats',
|
||
|
rows2table, ['type','tx_pkt','rx_pkt']
|
||
|
);
|
||
|
}
|
||
3 years ago
|
|
||
3 years ago
|
refresh_setup(10000);
|
||
|
refresh_job();
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|
||
|
""",
|
||
|
},
|
||
|
"/supernode.html": {
|
||
|
"content_type": "text/html; charset=utf-8",
|
||
|
"content": """
|
||
|
<html>
|
||
|
<head>
|
||
|
<title>n2n supernode management</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<table>
|
||
|
<tr>
|
||
|
<td>Last Updated:
|
||
|
<td><div id="time"></div>
|
||
|
<td><button onclick=refresh_job()>update</button>
|
||
|
<td><button onclick=do_stop()>stop supernode</button>
|
||
|
<tr>
|
||
|
<td>Logging Verbosity:
|
||
|
<td>
|
||
|
<div id="verbose"></div>
|
||
|
<td>
|
||
|
<button onclick=setverbose(verbose+1)>+</button>
|
||
|
<button onclick=setverbose(verbose-1)>-</button>
|
||
|
<td><button onclick=do_reload()>reload communities</button>
|
||
|
</table>
|
||
|
<br>
|
||
|
Communities:
|
||
|
<div id="communities"></div>
|
||
|
<br>
|
||
|
Edges/Peers:
|
||
|
<div id="edges"></div>
|
||
|
<br>
|
||
|
<div id="timestamps"></div>
|
||
|
<br>
|
||
|
<div id="packetstats"></div>
|
||
|
|
||
|
<script src="script.js"></script>
|
||
|
<script>
|
||
|
// FIXME: hacky global
|
||
|
var nodetype="supernode";
|
||
3 years ago
|
|
||
3 years ago
|
function do_reload() {
|
||
|
fetch(nodetype + '/reload_communities', {method:'POST'})
|
||
|
}
|
||
|
|
||
|
function refresh_job() {
|
||
|
do_get(
|
||
|
nodetype + '/verbose', 'verbose',
|
||
|
rows2verbose, null
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/communities', 'communities',
|
||
|
rows2table, ['community','ip4addr','is_federation','purgeable']
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/edges', 'edges',
|
||
|
rows2table,
|
||
|
['community','ip4addr','macaddr','sockaddr','proto','desc']
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/timestamps', 'timestamps',
|
||
|
rows2keyvalueall, null
|
||
|
);
|
||
|
do_get(
|
||
|
nodetype + '/packetstats', 'packetstats',
|
||
|
rows2table, ['type','tx_pkt','rx_pkt']
|
||
|
);
|
||
|
}
|
||
|
|
||
|
refresh_setup(10000);
|
||
3 years ago
|
refresh_job();
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|
||
3 years ago
|
""",
|
||
|
},
|
||
|
}
|
||
3 years ago
|
|
||
|
|
||
3 years ago
|
class SimpleHandler(http.server.BaseHTTPRequestHandler):
|
||
|
|
||
3 years ago
|
def __init__(self, rpc, snrpc, *args, **kwargs):
|
||
3 years ago
|
self.rpc = rpc
|
||
3 years ago
|
self.snrpc = snrpc
|
||
3 years ago
|
super().__init__(*args, **kwargs)
|
||
|
|
||
3 years ago
|
def log_request(self, code='-', size='-'):
|
||
|
# Dont spam the output
|
||
|
pass
|
||
|
|
||
3 years ago
|
def _simplereply(self, number, message):
|
||
|
self.send_response(number)
|
||
|
self.end_headers()
|
||
|
self.wfile.write(message.encode('utf8'))
|
||
|
|
||
3 years ago
|
def _replyjson(self, data):
|
||
|
self.send_response(HTTPStatus.OK)
|
||
|
self.send_header('Content-type', 'application/json')
|
||
|
self.end_headers()
|
||
|
self.wfile.write(json.dumps(data).encode('utf8'))
|
||
3 years ago
|
|
||
3 years ago
|
def _replyunauth(self):
|
||
|
self.send_response(HTTPStatus.UNAUTHORIZED)
|
||
|
self.send_header('WWW-Authenticate', 'Basic realm="n2n"')
|
||
|
self.end_headers()
|
||
3 years ago
|
|
||
3 years ago
|
def _extractauth(self, rpc):
|
||
|
# Avoid caching the key inside the object for all clients
|
||
|
rpc.key = None
|
||
3 years ago
|
|
||
3 years ago
|
header = self.headers.get('Authorization')
|
||
|
if header is not None:
|
||
|
authtype, encoded = header.split(' ')
|
||
|
if authtype == 'Basic':
|
||
|
user, key = base64.b64decode(encoded).decode('utf8').split(':')
|
||
|
rpc.key = key
|
||
|
|
||
|
if rpc.key is None:
|
||
|
rpc.key = rpc.defaultkey
|
||
|
|
||
|
def _rpc(self, method, cmdline):
|
||
|
try:
|
||
|
data = method(cmdline)
|
||
|
except ValueError as e:
|
||
|
if str(e) == "Error: badauth":
|
||
|
self._replyunauth()
|
||
3 years ago
|
return
|
||
|
|
||
3 years ago
|
self._simplereply(HTTPStatus.BAD_REQUEST, 'Bad Command')
|
||
|
return
|
||
|
|
||
|
self._replyjson(data)
|
||
|
return
|
||
|
|
||
|
def _rpc_read(self, rpc):
|
||
|
self._extractauth(rpc)
|
||
|
tail = self.path.split('/')
|
||
|
cmd = tail[2]
|
||
|
# if reads ever need args, could use more of the tail
|
||
|
|
||
|
self._rpc(rpc.read, cmd)
|
||
|
|
||
|
def _rpc_write(self, rpc):
|
||
|
self._extractauth(rpc)
|
||
|
content_length = int(self.headers['Content-Length'])
|
||
|
post_data = self.rfile.read(content_length).decode('utf8')
|
||
|
|
||
|
tail = self.path.split('/')
|
||
|
cmd = tail[2]
|
||
|
cmdline = cmd + ' ' + post_data
|
||
|
|
||
|
self._rpc(rpc.write, cmdline)
|
||
|
|
||
|
def do_GET(self):
|
||
|
if self.path.startswith("/edge/"):
|
||
|
self._rpc_read(self.rpc)
|
||
|
return
|
||
|
|
||
|
if self.path.startswith("/supernode/"):
|
||
|
self._rpc_read(self.snrpc)
|
||
|
return
|
||
|
|
||
|
if self.path in pages:
|
||
|
page = pages[self.path]
|
||
|
|
||
3 years ago
|
self.send_response(HTTPStatus.OK)
|
||
3 years ago
|
self.send_header('Content-type', page['content_type'])
|
||
3 years ago
|
self.end_headers()
|
||
3 years ago
|
self.wfile.write(page['content'].encode('utf8'))
|
||
3 years ago
|
return
|
||
|
|
||
3 years ago
|
self._simplereply(HTTPStatus.NOT_FOUND, 'Not Found')
|
||
3 years ago
|
return
|
||
3 years ago
|
|
||
3 years ago
|
def do_POST(self):
|
||
|
if self.path.startswith("/edge/"):
|
||
|
self._rpc_write(self.rpc)
|
||
|
return
|
||
|
|
||
|
if self.path.startswith("/supernode/"):
|
||
|
self._rpc_write(self.snrpc)
|
||
|
return
|
||
|
|
||
3 years ago
|
|
||
|
def main():
|
||
|
ap = argparse.ArgumentParser(
|
||
|
description='Control the running local n2n edge via http')
|
||
3 years ago
|
ap.add_argument('-t', '--mgmtport', action='store', default=5644,
|
||
3 years ago
|
help='Management Port (default=5644)', type=int)
|
||
|
ap.add_argument('--snmgmtport', action='store', default=5645,
|
||
|
help='Supernode Management Port (default=5645)', type=int)
|
||
3 years ago
|
ap.add_argument('-k', '--key', action='store',
|
||
|
help='Password for mgmt commands')
|
||
|
ap.add_argument('-d', '--debug', action='store_true',
|
||
|
help='Also show raw internal data')
|
||
3 years ago
|
ap.add_argument('port', action='store',
|
||
|
default=8080, type=int, nargs='?',
|
||
|
help='Serve requests on TCP port (default 8080)')
|
||
|
|
||
|
args = ap.parse_args()
|
||
|
|
||
3 years ago
|
rpc = JsonUDP(args.mgmtport)
|
||
|
rpc.debug = args.debug
|
||
3 years ago
|
rpc.defaultkey = args.key
|
||
|
|
||
|
snrpc = JsonUDP(args.snmgmtport)
|
||
|
snrpc.debug = args.debug
|
||
|
snrpc.defaultkey = args.key
|
||
3 years ago
|
|
||
|
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
||
|
|
||
|
socketserver.TCPServer.allow_reuse_address = True
|
||
3 years ago
|
handler = functools.partial(SimpleHandler, rpc, snrpc)
|
||
3 years ago
|
with socketserver.TCPServer(("", args.port), handler) as httpd:
|
||
|
try:
|
||
|
httpd.serve_forever()
|
||
|
except KeyboardInterrupt:
|
||
|
return
|
||
3 years ago
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
main()
|