| 1 |
#!/usr/bin/env python3 |
| 2 |
# Licensed under GPLv3 |
| 3 |
# |
| 4 |
# Simple http server to allow user control of n2n edge nodes |
| 5 |
# |
| 6 |
# Currently only for demonstration |
| 7 |
# - needs nicer looking html written |
| 8 |
# - needs more json interfaces in edge |
| 9 |
# |
| 10 |
# Try it out with |
| 11 |
# http://localhost:8080/ |
| 12 |
# http://localhost:8080/edge/edges |
| 13 |
# http://localhost:8080/edge/supernodes |
| 14 |
|
| 15 |
import argparse |
| 16 |
import socket |
| 17 |
import json |
| 18 |
import socketserver |
| 19 |
import http.server |
| 20 |
import signal |
| 21 |
import functools |
| 22 |
import base64 |
| 23 |
|
| 24 |
from http import HTTPStatus |
| 25 |
|
| 26 |
import os |
| 27 |
import sys |
| 28 |
import importlib.machinery |
| 29 |
import importlib.util |
| 30 |
|
| 31 |
|
| 32 |
def import_filename(modulename, filename): |
| 33 |
# look in the same dir as this script |
| 34 |
pathname = os.path.join(os.path.dirname(os.path.abspath(__file__)), |
| 35 |
filename) |
| 36 |
loader = importlib.machinery.SourceFileLoader(modulename, pathname) |
| 37 |
spec = importlib.util.spec_from_loader(modulename, loader) |
| 38 |
module = importlib.util.module_from_spec(spec) |
| 39 |
|
| 40 |
try: |
| 41 |
loader.exec_module(module) |
| 42 |
except FileNotFoundError: |
| 43 |
print("Script {} not found".format(pathname), file=sys.stderr) |
| 44 |
sys.exit(1) |
| 45 |
return module |
| 46 |
|
| 47 |
|
| 48 |
# We share the implementation of the RPC class with the n2n-ctl script. We |
| 49 |
# cannot just import the module as 'n2n-ctl' has a dash in its name :-( |
| 50 |
JsonUDP = import_filename('n2nctl', 'n2n-ctl').JsonUDP |
| 51 |
|
| 52 |
|
| 53 |
pages = { |
| 54 |
"/script.js": { |
| 55 |
"content_type": "text/javascript", |
| 56 |
"content": """ |
| 57 |
var verbose=-1; |
| 58 |
|
| 59 |
function rows2verbose(id, unused, data) { |
| 60 |
row0 = data[0] |
| 61 |
verbose = row0['traceLevel'] |
| 62 |
|
| 63 |
let div = document.getElementById(id); |
| 64 |
div.innerHTML=verbose |
| 65 |
} |
| 66 |
|
| 67 |
function rows2keyvalue(id, keys, data) { |
| 68 |
let s = "<table border=1 cellspacing=0>" |
| 69 |
data.forEach((row) => { |
| 70 |
keys.forEach((key) => { |
| 71 |
if (key in row) { |
| 72 |
s += "<tr><th>" + key + "<td>" + row[key]; |
| 73 |
} |
| 74 |
}); |
| 75 |
}); |
| 76 |
|
| 77 |
s += "</table>" |
| 78 |
let div = document.getElementById(id); |
| 79 |
div.innerHTML=s |
| 80 |
} |
| 81 |
|
| 82 |
function rows2keyvalueall(id, unused, data) { |
| 83 |
let s = "<table border=1 cellspacing=0>" |
| 84 |
data.forEach((row) => { |
| 85 |
Object.keys(row).forEach((key) => { |
| 86 |
s += "<tr><th>" + key + "<td>" + row[key]; |
| 87 |
}); |
| 88 |
}); |
| 89 |
|
| 90 |
s += "</table>" |
| 91 |
let div = document.getElementById(id); |
| 92 |
div.innerHTML=s |
| 93 |
} |
| 94 |
|
| 95 |
function rows2table(id, columns, data) { |
| 96 |
let s = "<table border=1 cellspacing=0>" |
| 97 |
s += "<tr>" |
| 98 |
columns.forEach((col) => { |
| 99 |
s += "<th>" + col |
| 100 |
}); |
| 101 |
data.forEach((row) => { |
| 102 |
s += "<tr>" |
| 103 |
columns.forEach((col) => { |
| 104 |
val = row[col] |
| 105 |
if (typeof val === "undefined") { |
| 106 |
val = '' |
| 107 |
} |
| 108 |
s += "<td>" + val |
| 109 |
}); |
| 110 |
}); |
| 111 |
|
| 112 |
s += "</table>" |
| 113 |
let div = document.getElementById(id); |
| 114 |
div.innerHTML=s |
| 115 |
} |
| 116 |
|
| 117 |
function do_get(url, id, handler, handler_param) { |
| 118 |
fetch(url) |
| 119 |
.then(function (response) { |
| 120 |
if (!response.ok) { |
| 121 |
throw new Error('Fetch got ' + response.status) |
| 122 |
} |
| 123 |
return response.json(); |
| 124 |
}) |
| 125 |
.then(function (data) { |
| 126 |
handler(id,handler_param,data); |
| 127 |
|
| 128 |
// update the timestamp on success |
| 129 |
let now = Math.round(new Date().getTime() / 1000); |
| 130 |
let time = document.getElementById('time'); |
| 131 |
time.innerHTML=now; |
| 132 |
}) |
| 133 |
.catch(function (err) { |
| 134 |
console.log('error: ' + err); |
| 135 |
}); |
| 136 |
} |
| 137 |
|
| 138 |
function do_post(url, body, id, handler, handler_param) { |
| 139 |
fetch(url, {method:'POST', body: body}) |
| 140 |
.then(function (response) { |
| 141 |
if (!response.ok) { |
| 142 |
throw new Error('Fetch got ' + response.status) |
| 143 |
} |
| 144 |
return response.json(); |
| 145 |
}) |
| 146 |
.then(function (data) { |
| 147 |
handler(id,handler_param,data); |
| 148 |
}) |
| 149 |
.catch(function (err) { |
| 150 |
console.log('error: ' + err); |
| 151 |
}); |
| 152 |
} |
| 153 |
|
| 154 |
function do_stop(tracelevel) { |
| 155 |
// FIXME: uses global in script library |
| 156 |
fetch(nodetype + '/stop', {method:'POST'}) |
| 157 |
} |
| 158 |
|
| 159 |
function setverbose(tracelevel) { |
| 160 |
if (tracelevel < 0) { |
| 161 |
tracelevel = 0; |
| 162 |
} |
| 163 |
// FIXME: uses global in script library |
| 164 |
do_post( |
| 165 |
nodetype + '/verbose', tracelevel, 'verbose', |
| 166 |
rows2verbose, null |
| 167 |
); |
| 168 |
} |
| 169 |
|
| 170 |
function refresh_setup(interval) { |
| 171 |
var timer = setInterval(refresh_job, interval); |
| 172 |
} |
| 173 |
""", |
| 174 |
}, |
| 175 |
"/": { |
| 176 |
"content_type": "text/html; charset=utf-8", |
| 177 |
"content": """ |
| 178 |
<html> |
| 179 |
<head> |
| 180 |
<title>n2n edge management</title> |
| 181 |
</head> |
| 182 |
<body> |
| 183 |
<table> |
| 184 |
<tr> |
| 185 |
<td>Last Updated: |
| 186 |
<td><div id="time"></div> |
| 187 |
<td><button onclick=refresh_job()>update</button> |
| 188 |
<td><button onclick=do_stop()>stop edge</button> |
| 189 |
<tr> |
| 190 |
<td>Logging Verbosity: |
| 191 |
<td> |
| 192 |
<div id="verbose"></div> |
| 193 |
<td> |
| 194 |
<button onclick=setverbose(verbose+1)>+</button> |
| 195 |
<button onclick=setverbose(verbose-1)>-</button> |
| 196 |
</table> |
| 197 |
<br> |
| 198 |
<div id="communities"></div> |
| 199 |
<br> |
| 200 |
Edges/Peers: |
| 201 |
<div id="edges"></div> |
| 202 |
<br> |
| 203 |
Supernodes: |
| 204 |
<div id="supernodes"></div> |
| 205 |
<br> |
| 206 |
<div id="timestamps"></div> |
| 207 |
<br> |
| 208 |
<div id="packetstats"></div> |
| 209 |
|
| 210 |
<script src="script.js"></script> |
| 211 |
<script> |
| 212 |
// FIXME: hacky global |
| 213 |
var nodetype="edge"; |
| 214 |
|
| 215 |
function refresh_job() { |
| 216 |
do_get( |
| 217 |
nodetype + '/verbose', 'verbose', |
| 218 |
rows2verbose, null |
| 219 |
); |
| 220 |
do_get( |
| 221 |
nodetype + '/communities', 'communities', |
| 222 |
rows2keyvalue, ['community'] |
| 223 |
); |
| 224 |
do_get( |
| 225 |
nodetype + '/supernodes', 'supernodes', |
| 226 |
rows2table, ['version','current','macaddr','sockaddr','uptime'] |
| 227 |
); |
| 228 |
do_get( |
| 229 |
nodetype + '/edges', 'edges', |
| 230 |
rows2table, ['mode','ip4addr','macaddr','sockaddr','desc'] |
| 231 |
); |
| 232 |
do_get( |
| 233 |
nodetype + '/timestamps', 'timestamps', |
| 234 |
rows2keyvalueall, null |
| 235 |
); |
| 236 |
do_get( |
| 237 |
nodetype + '/packetstats', 'packetstats', |
| 238 |
rows2table, ['type','tx_pkt','rx_pkt'] |
| 239 |
); |
| 240 |
} |
| 241 |
|
| 242 |
refresh_setup(10000); |
| 243 |
refresh_job(); |
| 244 |
</script> |
| 245 |
</body> |
| 246 |
</html> |
| 247 |
""", |
| 248 |
}, |
| 249 |
"/supernode.html": { |
| 250 |
"content_type": "text/html; charset=utf-8", |
| 251 |
"content": """ |
| 252 |
<html> |
| 253 |
<head> |
| 254 |
<title>n2n supernode management</title> |
| 255 |
</head> |
| 256 |
<body> |
| 257 |
<table> |
| 258 |
<tr> |
| 259 |
<td>Last Updated: |
| 260 |
<td><div id="time"></div> |
| 261 |
<td><button onclick=refresh_job()>update</button> |
| 262 |
<td><button onclick=do_stop()>stop supernode</button> |
| 263 |
<tr> |
| 264 |
<td>Logging Verbosity: |
| 265 |
<td> |
| 266 |
<div id="verbose"></div> |
| 267 |
<td> |
| 268 |
<button onclick=setverbose(verbose+1)>+</button> |
| 269 |
<button onclick=setverbose(verbose-1)>-</button> |
| 270 |
<td><button onclick=do_reload()>reload communities</button> |
| 271 |
</table> |
| 272 |
<br> |
| 273 |
Communities: |
| 274 |
<div id="communities"></div> |
| 275 |
<br> |
| 276 |
Edges/Peers: |
| 277 |
<div id="edges"></div> |
| 278 |
<br> |
| 279 |
<div id="timestamps"></div> |
| 280 |
<br> |
| 281 |
<div id="packetstats"></div> |
| 282 |
|
| 283 |
<script src="script.js"></script> |
| 284 |
<script> |
| 285 |
// FIXME: hacky global |
| 286 |
var nodetype="supernode"; |
| 287 |
|
| 288 |
function do_reload() { |
| 289 |
fetch(nodetype + '/reload_communities', {method:'POST'}) |
| 290 |
} |
| 291 |
|
| 292 |
function refresh_job() { |
| 293 |
do_get( |
| 294 |
nodetype + '/verbose', 'verbose', |
| 295 |
rows2verbose, null |
| 296 |
); |
| 297 |
do_get( |
| 298 |
nodetype + '/communities', 'communities', |
| 299 |
rows2table, ['community','ip4addr','is_federation','purgeable'] |
| 300 |
); |
| 301 |
do_get( |
| 302 |
nodetype + '/edges', 'edges', |
| 303 |
rows2table, |
| 304 |
['community','ip4addr','macaddr','sockaddr','proto','desc'] |
| 305 |
); |
| 306 |
do_get( |
| 307 |
nodetype + '/timestamps', 'timestamps', |
| 308 |
rows2keyvalueall, null |
| 309 |
); |
| 310 |
do_get( |
| 311 |
nodetype + '/packetstats', 'packetstats', |
| 312 |
rows2table, ['type','tx_pkt','rx_pkt'] |
| 313 |
); |
| 314 |
} |
| 315 |
|
| 316 |
refresh_setup(10000); |
| 317 |
refresh_job(); |
| 318 |
</script> |
| 319 |
</body> |
| 320 |
</html> |
| 321 |
""", |
| 322 |
}, |
| 323 |
} |
| 324 |
|
| 325 |
|
| 326 |
class SimpleHandler(http.server.BaseHTTPRequestHandler): |
| 327 |
|
| 328 |
def __init__(self, rpc, snrpc, *args, **kwargs): |
| 329 |
self.rpc = rpc |
| 330 |
self.snrpc = snrpc |
| 331 |
super().__init__(*args, **kwargs) |
| 332 |
|
| 333 |
def log_request(self, code='-', size='-'): |
| 334 |
# Dont spam the output |
| 335 |
pass |
| 336 |
|
| 337 |
def _simplereply(self, number, message): |
| 338 |
self.send_response(number) |
| 339 |
self.end_headers() |
| 340 |
self.wfile.write(message.encode('utf8')) |
| 341 |
|
| 342 |
def _replyjson(self, data): |
| 343 |
self.send_response(HTTPStatus.OK) |
| 344 |
self.send_header('Content-type', 'application/json') |
| 345 |
self.end_headers() |
| 346 |
self.wfile.write(json.dumps(data).encode('utf8')) |
| 347 |
|
| 348 |
def _replyunauth(self): |
| 349 |
self.send_response(HTTPStatus.UNAUTHORIZED) |
| 350 |
self.send_header('WWW-Authenticate', 'Basic realm="n2n"') |
| 351 |
self.end_headers() |
| 352 |
|
| 353 |
def _extractauth(self, rpc): |
| 354 |
# Avoid caching the key inside the object for all clients |
| 355 |
rpc.key = None |
| 356 |
|
| 357 |
header = self.headers.get('Authorization') |
| 358 |
if header is not None: |
| 359 |
authtype, encoded = header.split(' ') |
| 360 |
if authtype == 'Basic': |
| 361 |
user, key = base64.b64decode(encoded).decode('utf8').split(':') |
| 362 |
rpc.key = key |
| 363 |
|
| 364 |
if rpc.key is None: |
| 365 |
rpc.key = rpc.defaultkey |
| 366 |
|
| 367 |
def _rpc(self, method, cmdline): |
| 368 |
try: |
| 369 |
data = method(cmdline) |
| 370 |
except ValueError as e: |
| 371 |
if str(e) == "Error: badauth": |
| 372 |
self._replyunauth() |
| 373 |
return |
| 374 |
|
| 375 |
self._simplereply(HTTPStatus.BAD_REQUEST, 'Bad Command') |
| 376 |
return |
| 377 |
except socket.timeout as e: |
| 378 |
self._simplereply(HTTPStatus.REQUEST_TIMEOUT, str(e)) |
| 379 |
return |
| 380 |
|
| 381 |
self._replyjson(data) |
| 382 |
return |
| 383 |
|
| 384 |
def _rpc_read(self, rpc): |
| 385 |
self._extractauth(rpc) |
| 386 |
tail = self.path.split('/') |
| 387 |
cmd = tail[2] |
| 388 |
# if reads ever need args, could use more of the tail |
| 389 |
|
| 390 |
self._rpc(rpc.read, cmd) |
| 391 |
|
| 392 |
def _rpc_write(self, rpc): |
| 393 |
self._extractauth(rpc) |
| 394 |
content_length = int(self.headers['Content-Length']) |
| 395 |
post_data = self.rfile.read(content_length).decode('utf8') |
| 396 |
|
| 397 |
tail = self.path.split('/') |
| 398 |
cmd = tail[2] |
| 399 |
cmdline = cmd + ' ' + post_data |
| 400 |
|
| 401 |
self._rpc(rpc.write, cmdline) |
| 402 |
|
| 403 |
def do_GET(self): |
| 404 |
if self.path.startswith("/edge/"): |
| 405 |
self._rpc_read(self.rpc) |
| 406 |
return |
| 407 |
|
| 408 |
if self.path.startswith("/supernode/"): |
| 409 |
self._rpc_read(self.snrpc) |
| 410 |
return |
| 411 |
|
| 412 |
if self.path in pages: |
| 413 |
page = pages[self.path] |
| 414 |
|
| 415 |
self.send_response(HTTPStatus.OK) |
| 416 |
self.send_header('Content-type', page['content_type']) |
| 417 |
self.end_headers() |
| 418 |
self.wfile.write(page['content'].encode('utf8')) |
| 419 |
return |
| 420 |
|
| 421 |
self._simplereply(HTTPStatus.NOT_FOUND, 'Not Found') |
| 422 |
return |
| 423 |
|
| 424 |
def do_POST(self): |
| 425 |
if self.path.startswith("/edge/"): |
| 426 |
self._rpc_write(self.rpc) |
| 427 |
return |
| 428 |
|
| 429 |
if self.path.startswith("/supernode/"): |
| 430 |
self._rpc_write(self.snrpc) |
| 431 |
return |
| 432 |
|
| 433 |
|
| 434 |
def main(): |
| 435 |
ap = argparse.ArgumentParser( |
| 436 |
description='Control the running local n2n edge via http') |
| 437 |
ap.add_argument('-t', '--mgmtport', action='store', default=5644, |
| 438 |
help='Management Port (default=5644)', type=int) |
| 439 |
ap.add_argument('--snmgmtport', action='store', default=5645, |
| 440 |
help='Supernode Management Port (default=5645)', type=int) |
| 441 |
ap.add_argument('-k', '--key', action='store', |
| 442 |
help='Password for mgmt commands') |
| 443 |
ap.add_argument('-d', '--debug', action='store_true', |
| 444 |
help='Also show raw internal data') |
| 445 |
ap.add_argument('port', action='store', |
| 446 |
default=8080, type=int, nargs='?', |
| 447 |
help='Serve requests on TCP port (default 8080)') |
| 448 |
|
| 449 |
args = ap.parse_args() |
| 450 |
|
| 451 |
rpc = JsonUDP(args.mgmtport) |
| 452 |
rpc.debug = args.debug |
| 453 |
rpc.defaultkey = args.key |
| 454 |
|
| 455 |
snrpc = JsonUDP(args.snmgmtport) |
| 456 |
snrpc.debug = args.debug |
| 457 |
snrpc.defaultkey = args.key |
| 458 |
|
| 459 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) |
| 460 |
|
| 461 |
socketserver.TCPServer.allow_reuse_address = True |
| 462 |
handler = functools.partial(SimpleHandler, rpc, snrpc) |
| 463 |
|
| 464 |
httpd = socketserver.TCPServer(("", args.port), handler) |
| 465 |
try: |
| 466 |
httpd.serve_forever() |
| 467 |
except KeyboardInterrupt: |
| 468 |
return |
| 469 |
|
| 470 |
|
| 471 |
if __name__ == '__main__': |
| 472 |
main() |