diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ce4b03 --- /dev/null +++ b/.gitignore @@ -0,0 +1,224 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +*.lcov +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi/* +!.pixi/config.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule* +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +# .idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ +# Temporary file for partial code execution +tempCodeRunnerFile.py + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml + + +# StingNET +server/users.db diff --git a/server/db.py b/server/db.py new file mode 100644 index 0000000..0954ba6 --- /dev/null +++ b/server/db.py @@ -0,0 +1,118 @@ +import os +import sqlite3 + +class Database(): + def __init__(self,name): + print(f"init db {name}") + self.name = name + self.con = sqlite3.connect(f"{name}.db") + self.cur = self.con.cursor() + + def execute(self,cmd: str,*args): + print("execute",[cmd,*args]) + return self.cur.execute(cmd,*args) + + def executemany(self,cmd: str,*args): + print("executemany",[cmd,*args]) + return self.cur.executemany(cmd,*args) + + def select(self,cmd: str,*args) -> list[tuple]: + return self.execute(cmd,*args).fetchall() + + def sameType(self,typeA: str,typeB: str) -> bool: + return typeA.lower() == typeB.lower() + + + # tables + def tableExists(self,table: str) -> bool: + res = self.select("SELECT name FROM sqlite_master WHERE type='table' AND name=?",(table,)) + return type(res)!=type(None) and len(res)>0 + + def createTable(self,table: str,cols: dict[str,str]) -> None: + if self.tableExists(table): return self.checkColumns(table,cols) + # i know i shouldn't be inserting these directly but using placeholders returns a syntax error for some reason + self.execute(f"CREATE TABLE {table}({", ".join([f"{n} {cols[n]}" for n in cols])})") + + def dropTable(self,table: str) -> None: + self.execute(f"DROP TABLE {table}") + + + # columns + def getColumns(self,table: str) -> tuple[str]: + if not self.tableExists(table): return () + res = self.select(f"PRAGMA table_info('{table}')") + return dict([e[1:3] for e in res]) + + def hasColumn(self,table: str,colname: str) -> bool: + return colname in self.getColumns(table) + + def insertColumn(self,table: str,colname: str,coltype: str) -> None: + self.execute(f"ALTER TABLE {table} ADD COLUMN {colname} {coltype}") + + def checkColumns(self,table: str,cols: dict[str,str]) -> None: + tcols = self.getColumns(table) + for colname in cols: + if not colname in tcols: + self.insertColumn(table,colname,cols[colname]) + continue + if not self.sameType(cols[colname],tcols[colname]): + raise Exception(f"Invalid table '{table}' in database '{self.name}': column '{colname}' has type '{tcols[colname]}' instead of '{cols[colname]}'") + + + # rows + def insertRows(self,table: str,values: list[list|tuple|dict]) -> None: + if len(values)==0: return + amount=len(values[0]) + if type(values[0])==dict: + cols = self.getColumns(table) + for e in values: + for c in cols: + if not c in e: + e[c] = None + self.executemany(f"INSERT INTO {table} VALUES({", ".join([f":{e}" for e in cols])})",values) + else: + self.executemany(f"INSERT INTO {table} VALUES({", ".join(["?"]*amount)})",values) + self.con.commit() + + def insertRow(self,table: str,values: list|tuple|dict) -> None: + self.insertRows(table,[values]) + + def rowAmount(self,table: str) -> int: + return self.select(f"SELECT COUNT(*) FROM {table}")[0][0] + + # find + def findRowList(self,table: str,pattern: str,*args) -> list | None: + res = self.select(f"SELECT * FROM {table} WHERE {pattern}",*args) + if len(res)==0: return None + return res[0] + + def findRow(self,table: str,pattern: str,*args) -> dict | None: + res = self.findRowList(table,pattern,*args) + if res==None: return None + cols = list(self.getColumns(table)) + return dict([[cols[i],res[i]] for i in range(len(cols))]) + + # PK = primary key + def rowListFromPK(self,table: str,pkname: str,pk) -> tuple | None: + res = self.select(f"SELECT * FROM {table} WHERE {pkname} = ?",(pk,)) + if len(res)==0: return None + return res[0] + + def rowFromPK(self,table: str,pkname: str,pk) -> dict | None: + res = self.rowListFromPK(table,pkname,pk) + if res==None: return None + cols = list(self.getColumns(table)) + return dict([[cols[i],res[i]] for i in range(len(cols))]) + + def hasPK(self,table: str,pkname: str,pk) -> bool: + return type(self.rowListFromPK(table,pkname,pk))!=type(None) + + def removePK(self,table: str,pkname: str,pk) -> None: + self.execute(f"DELETE FROM {table} WHERE {pkname} = ?",(pk,)) + self.con.commit() + + def updateFromPK(self,table: str,pkname: str,pk,row:dict): + keys = list(row) + vals = [row[i] for i in keys] + self.execute(f"UPDATE {table} SET {", ".join([f"{e} = ?" for e in keys])} WHERE {pkname} = ?",(*vals,pk)) + self.con.commit() diff --git a/server/main.py b/server/main.py new file mode 100644 index 0000000..9fb632d --- /dev/null +++ b/server/main.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python + +import asyncio +import json, random, re, math, time, traceback +from websockets.asyncio.server import serve + +from db import Database + + +userdb = Database("users") +userdb.createTable("NAMES",{"id":"int","name":"string","creation_date":"int","last_login":"int"}) +userdb.createTable("PASSWORDS",{"id":"int","sum":"string"}) + +def makeUserID() -> int: + count = userdb.rowAmount("NAMES") + digits = max(4,1+int(math.log10(10+count))) + + uid=0 + while uid==0 or userdb.hasPK("NAMES","id",uid) or userdb.hasPK("PASSWORDS","id",uid): + uid = random.randint(0,(10**digits)-1) & 0x7FFFFFFFFFFFFFFF + return uid + +def isValidUsername(name) -> bool: + pattern = re.compile("^[a-z][a-z0-9-_]*") + match = pattern.match(name) + if match==None: return False + return match.start()==0 and match.end()==len(name) + +def isValidChecksum(cs) -> bool: + if len(cs)!=32: return False + pattern = re.compile("^[0-9a-f]*") + match = pattern.match(cs) + if match==None: return False + return match.start()==0 and match.end()==len(cs) + + +def response(msg,**kwargs) -> str: + return json.dumps({"type":"response","response":msg,**kwargs}) + +def clientError(msg,**kwargs) -> str: + return json.dumps({"type":"error","error":msg,"server":False,**kwargs}) + +def serverError(msg,**kwargs) -> str: + print(f"Server error: {msg}") + return json.dumps({"type":"error","error":msg,"server":True,**kwargs}) + +sessionUsers = {} + +async def handleCommand(ws,cmd): + global sessionUsers + print(f"recieved command: {cmd} (from {id(ws)})") + if not "type" in cmd: + return await ws.send(clientError("Malformed command")) + if id(ws) in sessionUsers: + uid = sessionUsers[id(ws)] + match cmd["type"]: + case "ping": + return await ws.send(response("Pong!")) + case "createuser": + uid = makeUserID() + name = cmd["name"] + name = name.lower() + if not isValidUsername(name): + return await ws.send(clientError("Username is not valid.")) + if len(userdb.select("SELECT * FROM NAMES WHERE name = ?",(name,)))>0: + return await ws.send(clientError(f"The username '{name}' is already taken.")) + psum = cmd["pass"] + psum = psum.lower() + if not isValidChecksum(psum): + return await ws.send(clientError("Recieved password has not been correctly checksummed.")) + create = time.time() + userdb.insertRow("NAMES",{"id":uid,"name":cmd["name"],"creation_date":create,"last_login":create}) + userdb.insertRow("PASSWORDS",{"id":uid,"sum":psum}) + return await ws.send(response({"uid":uid})) + + case "login": + if id(ws) in sessionUsers: + return await ws.send(clientError("You are already logged in.")) + name = cmd["name"] + psum = cmd["pass"] + if not isValidUsername(name): + return await ws.send(clientError("Username is not valid.")) + res = userdb.findRow("NAMES","name = ?",(name,)) + if res==None: + return await ws.send(clientError("Invalid username or password.")) + uid = res["id"] + if not isValidChecksum(psum): + return await ws.send(clientError("Recieved password has not been correctly checksummed.")) + dbsum = userdb.rowFromPK("PASSWORDS","id",uid)["sum"] + if psum.lower() != dbsum.lower(): + return await ws.send(clientError("Invalid username or password.")) + print(f"session {id(ws)} has logged in as {name} ({uid})") + sessionUsers[id(ws)] = uid + userdb.updateFromPK("NAMES","id",uid,{"last_login":time.time()}) + return await ws.send(response("success")) + + case "logout": + if not id(ws) in sessionUsers: + return await ws.send(clientError("You are already logged out.")) + del sessionUsers[id(ws)] + return await ws.send(response("success")) + + case "status": + if not id(ws) in sessionUsers: + return await ws.send(response({"login":False})) + name = userdb.rowFromPK("NAMES","id",uid)["name"] + return await ws.send(response({"login":True,"uid":uid,"name":name})) + + case _: + return await ws.send(clientError(f"Command '{cmd["type"]}' does not exist.")) + + +async def serveClient(ws): + print("serve client",id(ws)) + await ws.send(json.dumps({"type":"connected"})) + while True: + try: + cmdtxt = await ws.recv() + if type(cmdtxt)==bytes: cmdtxt=cmdtxt.decode("utf8") + if type(cmdtxt)!=str: continue + cmd = json.loads(cmdtxt) + try: + await handleCommand(ws,cmd) + except Exception as e: + traceback.print_exception(e) + await ws.send(serverError(f"Cannot process command ({cmd["type"]})")) + except Exception as e: + traceback.print_exception(e) + await ws.send(serverError("Cannot process JSON.")) + +async def main(): + async with serve(serveClient, "", 30341) as server: + await server.serve_forever() + +if __name__ == "__main__": + print("now serving") + asyncio.run(main()) diff --git a/websocket-test.py b/websocket-test.py new file mode 100644 index 0000000..36d3ba8 --- /dev/null +++ b/websocket-test.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python + +from websockets.sync.client import connect + +def hello(): + uri = "ws://localhost:30341" + with connect(uri) as ws: + while True: + greeting = ws.recv() + print(f"<<< {greeting}") + + cmd = input(">>> ") + + ws.send(cmd) + # print(f">>> {name}") + +if __name__ == "__main__": + hello()