Sync poc to spec

Co-authored-by: Roberto Abdelkader Martínez Pérez <robertomartinezp@gmail.com>
This commit is contained in:
pancho horrillo
2019-05-27 11:56:25 +02:00
parent e4cbb96cf4
commit dc253f7485
9 changed files with 35 additions and 32 deletions
+1 -1
View File
@@ -16,4 +16,4 @@
# limitations under the License. # limitations under the License.
# #
curl -sf ${KAPOW_URL}/connections/${KAPOW_CONNECTION}/request$1 curl -sf "${KAPOW_URL}/handlers/${KAPOW_HANDLER_ID}/request$1"
+3 -3
View File
@@ -24,17 +24,17 @@ import requests
@click.command() @click.command()
@click.option("--url", envvar='KAPOW_URL') @click.option("--url", envvar='KAPOW_URL')
@click.option("--connection", envvar='KAPOW_CONNECTION') @click.option("--handler-id", envvar='KAPOW_HANDLER_ID')
@click.argument("path", nargs=1) @click.argument("path", nargs=1)
@click.argument("value", required=False) @click.argument("value", required=False)
def response(url, connection, path, value): def response(url, handler_id, path, value):
if value is None: if value is None:
data = sys.stdin.buffer data = sys.stdin.buffer
else: else:
data = value.encode('utf-8') data = value.encode('utf-8')
try: try:
response = requests.put(f"{url}/connections/{connection}/response{path}", response = requests.put(f"{url}/handlers/{handler_id}/response{path}",
data=data) data=data)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
return False return False
+1 -1
View File
@@ -16,4 +16,4 @@
# limitations under the License. # limitations under the License.
# #
kroute add -X GET '/list/{ip}' -c 'nmap -sL $(request /match/ip) | response /body' kroute add -X GET '/list/{ip}' -c 'nmap -sL $(request /matches/ip) | response /body'
+3 -3
View File
@@ -16,7 +16,7 @@
# limitations under the License. # limitations under the License.
# #
kroute add /list/files -c 'ls -la $(request /param/path) | response /body' kroute add /list/files -c 'ls -la $(request /params/path) | response /body'
kroute add /list/processes -c 'ps -aux | response /body' kroute add /list/processes -c 'ps -aux | response /body'
@@ -31,11 +31,11 @@ kroute add /show/connections -c 'ss -pluton | response /body'
kroute add /show/mounts -c 'mount | response /body' kroute add /show/mounts -c 'mount | response /body'
kroute add /tail/dmesg - <<-'EOF' kroute add /tail/dmesg - <<-'EOF'
response /header/Content-Type text/plain response /headers/Content-Type text/plain
dmesg -w | response /stream dmesg -w | response /stream
EOF EOF
kroute add /tail/journal - <<-'EOF' kroute add /tail/journal - <<-'EOF'
response /header/Content-Type text/plain response /headers/Content-Type text/plain
journalctl -f | response /stream journalctl -f | response /stream
EOF EOF
+2 -2
View File
@@ -17,8 +17,8 @@
# #
kroute add -X POST --entrypoint '/bin/zsh -c' '/convert/{from}/{to}' - <<-'EOF' kroute add -X POST --entrypoint '/bin/zsh -c' '/convert/{from}/{to}' - <<-'EOF'
pandoc --from=$(request /match/from) \ pandoc --from=$(request /matches/from) \
--to=$(request /match/to) \ --to=$(request /matches/to) \
--output=>(response /body) \ --output=>(response /body) \
=(request /body) =(request /body)
EOF EOF
+1 -1
View File
@@ -17,4 +17,4 @@
# #
kroute add -X POST --entrypoint ./topdf '/editor/pdf' kroute add -X POST --entrypoint ./topdf '/editor/pdf'
kroute add / -c 'response /header/Content-Type text/html && response /body < pdfeditor.html' kroute add / -c 'response /headers/Content-Type text/html && response /body < pdfeditor.html'
+1 -1
View File
@@ -19,7 +19,7 @@
tmpfile=$(mktemp --suffix=.pdf) tmpfile=$(mktemp --suffix=.pdf)
pandoc --from=$(request /form/from) --to=pdf --output=${tmpfile} -t latex =(request /form/content) pandoc --from=$(request /form/from) --to=pdf --output=${tmpfile} -t latex =(request /form/content)
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
response /header/Content-Type application/pdf response /headers/Content-Type application/pdf
response /body < ${tmpfile} response /body < ${tmpfile}
response /status 200 response /status 200
else else
+3 -3
View File
@@ -17,7 +17,7 @@
# #
kroute add / - <<-'EOF' kroute add / - <<-'EOF'
response /header/Content-Type text/html response /headers/Content-Type text/html
response /body <<-HTML response /body <<-HTML
<html> <html>
<body> <body>
@@ -28,7 +28,7 @@ kroute add / - <<-'EOF'
EOF EOF
kroute add /save/magnet -e '/bin/bash -c' - <<-'EOF' kroute add /save/magnet -e '/bin/bash -c' - <<-'EOF'
link=$(request /param/link) link=$(request /params/link)
[ -z $link ] && response /status 400 && exit 0 [ -z $link ] && response /status 400 && exit 0
watch_folder=/tmp watch_folder=/tmp
@@ -37,7 +37,7 @@ kroute add /save/magnet -e '/bin/bash -c' - <<-'EOF'
echo "d10:magnet-uri${#link}:${link}e" > "meta-${BASH_REMATCH[1]}.torrent" echo "d10:magnet-uri${#link}:${link}e" > "meta-${BASH_REMATCH[1]}.torrent"
response /status 302 response /status 302
response /header/Location /torrent/list response /headers/Location /torrent/list
EOF EOF
kroute add /torrent/list -c 'response /body "Not Implemented Yet"' kroute add /torrent/list -c 'response /body "Not Implemented Yet"'
+20 -17
View File
@@ -69,17 +69,17 @@ class Connection:
return self.request.content return self.request.content
elif res.path == 'request/path': elif res.path == 'request/path':
return self.request.path.encode('utf-8') return self.request.path.encode('utf-8')
elif res.path.startswith('request/match/'): elif res.path.startswith('request/matches/'):
return self.request.match_info[nth(2)].encode('utf-8') return self.request.match_info[nth(2)].encode('utf-8')
elif res.path.startswith('request/param/'): elif res.path.startswith('request/params/'):
return self.request.rel_url.query[nth(2)].encode('utf-8') return self.request.rel_url.query[nth(2)].encode('utf-8')
elif res.path.startswith('request/header/'): elif res.path.startswith('request/headers/'):
return self.request.headers[nth(2)].encode('utf-8') return self.request.headers[nth(2)].encode('utf-8')
elif res.path.startswith('request/cookie/'): elif res.path.startswith('request/cookies/'):
return self.request.cookies[nth(2)].encode('utf-8') return self.request.cookies[nth(2)].encode('utf-8')
elif res.path.startswith('request/form/'): elif res.path.startswith('request/form/'):
return (await self.request.post())[nth(2)].encode('utf-8') return (await self.request.post())[nth(2)].encode('utf-8')
elif res.path.startswith('request/file/'): elif res.path.startswith('request/files/'):
name = nth(2) name = nth(2)
content = nth(3) # filename / content content = nth(3) # filename / content
field = (await self.request.post())[name] field = (await self.request.post())[name]
@@ -109,10 +109,10 @@ class Connection:
self._status = int((await content.read()).decode('utf-8')) self._status = int((await content.read()).decode('utf-8'))
elif res.path == 'response/body': elif res.path == 'response/body':
self._body.write(await content.read()) self._body.write(await content.read())
elif res.path.startswith('response/header/'): elif res.path.startswith('response/headers/'):
clean = (await content.read()).rstrip(b'\n').decode('utf-8') clean = (await content.read()).rstrip(b'\n').decode('utf-8')
self._headers[nth(2)] = clean self._headers[nth(2)] = clean
elif res.path.startswith('response/cookie/'): elif res.path.startswith('response/cookies/'):
clean = (await content.read()).rstrip(b'\n').decode('utf-8') clean = (await content.read()).rstrip(b'\n').decode('utf-8')
self._cookies[nth(2)] = clean self._cookies[nth(2)] = clean
elif res.path == 'response/stream': elif res.path == 'response/stream':
@@ -227,8 +227,8 @@ def handle_route(entrypoint, command):
shell_task = await asyncio.create_subprocess_shell( shell_task = await asyncio.create_subprocess_shell(
args, args,
env={**os.environ, env={**os.environ,
"KAPOW_URL": "http://localhost:8080/kapow", "KAPOW_URL": "http://localhost:8080",
"KAPOW_CONNECTION": id "KAPOW_HANDLER_ID": id
}, },
stdin=asyncio.subprocess.DEVNULL) stdin=asyncio.subprocess.DEVNULL)
@@ -253,7 +253,7 @@ async def get_routes(request):
return web.json_response(list(request.app.router)) return web.json_response(list(request.app.router))
async def create_route(request): async def append_route(request):
"""Create a new Kapow! route.""" """Create a new Kapow! route."""
request.app.router._frozen = False request.app.router._frozen = False
content = await request.json() content = await request.json()
@@ -298,7 +298,7 @@ async def run_init_script(app):
shell_task = await asyncio.create_subprocess_shell( shell_task = await asyncio.create_subprocess_shell(
cmd, cmd,
env={**os.environ, env={**os.environ,
"KAPOW_URL": "http://localhost:8080/kapow" "KAPOW_URL": "http://localhost:8080"
}) })
await shell_task.wait() await shell_task.wait()
@@ -315,12 +315,15 @@ def kapow():
"""Start aiohttp app.""" """Start aiohttp app."""
app = web.Application(client_max_size=1024**3) app = web.Application(client_max_size=1024**3)
app.add_routes([ app.add_routes([
web.get('/kapow/routes', get_routes), # Control API
web.post('/kapow/routes', create_route), web.get('/routes', get_routes),
web.delete('/kapow/routes/{id}', delete_route), web.post('/routes', append_route), # TODO: return route index
web.get('/kapow/connections/{id}/{field:.*}', get_field), # web.put('/routes', insert_route), # TODO: return route index
# web.post('/kapow/connections/{id}/{field:.*}', append_field), web.delete('/routes/{id}', delete_route),
web.put('/kapow/connections/{id}/{field:.*}', set_field),
# Data API
web.get('/handlers/{id}/{field:.*}', get_field),
web.put('/handlers/{id}/{field:.*}', set_field),
]) ])
app.on_startup.append(start_background_tasks) app.on_startup.append(start_background_tasks)
web.run_app(app) web.run_app(app)