api.pyfabapi/fabapi/connect.py

55 lines
1.6 KiB
Python
Raw Permalink Normal View History

2021-12-09 21:54:22 +01:00
import asyncio
import socket
import ssl
2021-09-19 20:35:34 +02:00
2022-04-28 20:57:40 +02:00
import capnp
from .schema import connection_capnp
from .schema import authenticationsystem_capnp
2021-09-19 20:35:34 +02:00
2021-12-09 21:54:22 +01:00
async def myreader(client, reader):
while True:
data = await reader.read(4096)
client.write(data)
async def mywriter(client, writer):
while True:
data = await client.read(4096)
writer.write(data.tobytes())
await writer.drain()
async def connect(host, port, user, pw):
# Setup SSL context
ctx = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH
)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Handle both IPv4 and IPv6 cases
try:
reader, writer = await asyncio.open_connection(
host, port, ssl=ctx, family=socket.AF_INET6
)
except Exception:
reader, writer = await asyncio.open_connection(
host, port, ssl=ctx, family=socket.AF_INET
)
# Start TwoPartyClient using TwoWayPipe (takes no arguments in this mode)
client = capnp.TwoPartyClient()
# Assemble reader and writer tasks, run in the background
coroutines = [myreader(client, reader), mywriter(client, writer)]
asyncio.gather(*coroutines, return_exceptions=True)
2021-09-19 20:35:34 +02:00
2022-03-14 00:04:28 +01:00
boot = client.bootstrap().cast_as(connection_capnp.Bootstrap)
2022-04-24 23:07:25 +02:00
auth = boot.createSession("PLAIN")
2022-03-14 00:04:28 +01:00
p = "\0" + user + "\0" + pw
response = await auth.authentication.step(p).a_wait()
if response.which() == 'successful':
return response.successful.session
2021-09-19 20:35:34 +02:00
else:
2022-03-14 00:04:28 +01:00
print("Authentication failed!")
2021-09-19 20:35:34 +02:00
return None