commit 2e219d553aabac4cfe1918b2e82830152c42824b Author: Fierelier Date: Thu Feb 15 08:26:03 2024 +0100 First commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed8ebf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..67fe97b --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023 + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/config/servers/basic.toml b/config/servers/basic.toml new file mode 100644 index 0000000..f1cda81 --- /dev/null +++ b/config/servers/basic.toml @@ -0,0 +1,3 @@ +_script = "./scripts/http_example/main.py" +# Script-specific configuration: +max_header_length = 16384 \ No newline at end of file diff --git a/config/sockets/basic/http.toml b/config/sockets/basic/http.toml new file mode 100644 index 0000000..0ba1279 --- /dev/null +++ b/config/sockets/basic/http.toml @@ -0,0 +1,9 @@ +_addr = "127.0.0.1" +_port = 8080 +_timeout = 30 +_ssl = false +_options = [ + ["SOL_SOCKET","SO_REUSEADDR","1"], # Immediately free address when server is shut down + ["IPPROTO_TCP","TCP_NODELAY","1"], # Disable nagle's algorithm (decreases delay) + ["IPPROTO_TCP","IP_TOS", "16"] # 16 = IPTOS_LOWDELAY. Prioritizes this socket's traffic over other ones. +] diff --git a/module/http/_main.py b/module/http/_main.py new file mode 100644 index 0000000..5df4c0f --- /dev/null +++ b/module/http/_main.py @@ -0,0 +1,3 @@ +connection = mfp.require("http.connection") +header = mfp.require("http.header") +url = mfp.require("http.url") diff --git a/module/http/connection.py b/module/http/connection.py new file mode 100644 index 0000000..9b3b3c8 --- /dev/null +++ b/module/http/connection.py @@ -0,0 +1,21 @@ +import time + +def recv(conn,l): + start = time.process_time() + timeo = conn.gettimeout() + bytes = b"" + + if timeo != None: + while l > 0: + b = conn.recv(l) + if b == b"": raise ConnectionResetError + if time.process_time() - start > timeo: raise TimeoutError + bytes += b + l -= len(b) + else: + while l > 0: + b = conn.recv(l) + if b == b"": raise ConnectionResetError + bytes += b + l -= len(b) + return bytes diff --git a/module/http/exception.py b/module/http/exception.py new file mode 100644 index 0000000..7fb581b --- /dev/null +++ b/module/http/exception.py @@ -0,0 +1,7 @@ +class parse(Exception): + def __init__(self, message="Failed parsing header", **kwargs): + super().__init__(message) + +class length(Exception): + def __init__(self, message="Length invalid", **kwargs): + super().__init__(message) diff --git a/module/http/header.py b/module/http/header.py new file mode 100644 index 0000000..bd93324 --- /dev/null +++ b/module/http/header.py @@ -0,0 +1,51 @@ +import urllib.parse +http = mfp.require("http") + +def receive(connection,limit = 0): + count = 0 + nl = False + data = b"" + while True: + if limit > 0: + count += 1 + if count >= limit: + raise http.exception.length("Header exceeding given limit") + + b = http.connection.recv(connection,1) + data = data + b + if b[0] == 0x0A: + if nl == False: + nl = True + continue + + if nl == True: + return data + else: + if b[0] != 0x0D: + nl = False + +def parse(text): + text = text.split("\n") + text[0] = text[0].rstrip("\r").split(" ",2) + + i = 1 + length = len(text) + while i < length: + text[i] = text[i].rstrip(" \t\r") + text[i] = text[i].lstrip(" \t") + if text[i] == "": + del text[i] + length -= 1 + continue + text[i] = text[i].split(":",1) + if len(text[i]) != 2: raise http.exception.parse("No separator (:) in header.") + text[i][0] = text[i][0].rstrip(" \t").lower() + text[i][1] = text[i][1].lstrip(" \t") + i += 1 + return text + +def create(headers): + text = "" + for i in range(len(headers)): + text = text + headers[i][0] + ": " +headers[i][1]+ "\r\n" + return text diff --git a/module/http/url.py b/module/http/url.py new file mode 100644 index 0000000..9c82db4 --- /dev/null +++ b/module/http/url.py @@ -0,0 +1,32 @@ +import urllib.parse +import os + +def parse(url): + url = url.split("?",1) + url[0] = urllib.parse.unquote(url[0],encoding="utf-8") + if len(url) < 2: url.append("") + url[1] = url[1].split("&") + for i in range(len(url[1])): + url[1][i] = url[1][i].split("=",1) + if len(url[1][i] < 2): url[1][i].append("") + url[1][i][0] = urllib.parse.unquote(url[1][i][0],encoding="utf-8") + url[1][i][1] = urllib.parse.unquote(url[1][i][1],encoding="utf-8") + +def standardize(path): + path = path.replace("/",os.path.sep) + path = path.replace("\\",os.path.sep) + path = path.lstrip(os.path.sep) + while os.path.sep + os.path.sep in path: + path = path.replace(os.path.sep + os.path.sep,os.path.sep) + path = path.split(os.path.sep) + + i = 0 + length = len(path) + while i < length: + if path[i] in [".",".."]: + del path[i] + length -= 1 + continue + i += 1 + + return path diff --git a/module/py/me/fier/python/__init__.py b/module/py/me/fier/python/__init__.py new file mode 100644 index 0000000..c4c1b19 --- /dev/null +++ b/module/py/me/fier/python/__init__.py @@ -0,0 +1,90 @@ +import sys +import os + +# BUNCH +try: + import munch + Bunch = munch.Munch + bunchify = munch.munchify + unbunchify = munch.unmunchify +except ModuleNotFoundError: + try: + import bunch + Bunch = munch.Bunch + bunchify = munch.bunchify + unbunchify = munch.unbunchify + except ModuleNotFoundError: + print("Error: Could not find munch/bunch module. Install munch on Python 3, bunch on Python 2.",file=sys.stderr) + sys.exit(1) + +# GLOBALS +g = Bunch() + +# SCRIPTS +paths = [] +loaded = Bunch() + +def docode(st,name = "Unknown",glb = False): + code = compile(st,name,"exec") + if glb == False: glb = Bunch() + glb[distro] = me + glb[distro + "l"] = Bunch() + glb[distro + "l"].s = name + try: + glb[distro + "l"].sd = pUp(name) + except Exception: + pass + glb[distro + "l"].g = glb + exec(code,glb) + return glb + +def dofile(path,*args,**kwargs): + return docode(open(path,"rb").read(),path,*args,**kwargs) + +def dorequire(name,*args,**kwargs): + name = name.replace("/",".").replace("\\",".") + for path in paths: + path = path.replace("?",name.replace(".",os.path.sep)) + if os.path.isfile(path): + return dofile(path,*args,**kwargs) + raise Exception("dorequire: Library '" +name+ "' not found.") + +def require(name,env=False,*args,**kwargs): + if env == False: env = loaded + if type(env) != Bunch: raise Exception("require: env is not of type " +distro+ ".Bunch") + if not name in env: + env[name] = Bunch() + env[name] = dorequire(name,*args,glb=env[name],**kwargs) + return env[name] + +# PROGRAM +programName = None +programNameSet = False +def setProgramName(name): + global programName,programNameSet + if programNameSet: return + programNameSet = True + programName = name + +# INIT +inited = False +def init(mod,modl,sp,d): + global inited + if inited: return + global distro,me,p,pUp,programName,programNameSet,s,sd + import sys + inited = True + distro = d + me = mod + + p = os.path.join + pUp = os.path.dirname + s = sp + sd = pUp(sp) + modl.s = s + modl.sd = sd + programName = distro + "." + s.replace(modl.sd + os.path.sep,"",1).rsplit(".",1)[0] + programNameSet = False + + paths.append(p(modl.sd,"module","?.py")) + paths.append(p(modl.sd,"module","?","_main.py")) diff --git a/module/server/_main.py b/module/server/_main.py new file mode 100644 index 0000000..acda925 --- /dev/null +++ b/module/server/_main.py @@ -0,0 +1,235 @@ +import sys +import os +import toml +import threading +import queue +import traceback +import socket +import ssl + +servers = {} +lockServers = threading.Lock() + +debug = True +debugLock = threading.Lock() +def debugOutput(*args,**kwargs): + try: + if not debug: return + with debugLock: print(*args,**kwargs) + except: + pass + +def printException(): + debugOutput(traceback.format_exc() + "\n---") + +def kickClient(client): + debugOutput("Kicking client:",client.cClient.address) + try: + client.cClient.connection.close() + except Exception: + printException() + + try: + del(client.cServer.cClients[client.cServer.cClients.index(client)]) + except Exception: + printException() + +class clientThread(threading.Thread): + def __init__(self,server,client,*args,**kwargs): + super().__init__(*args,**kwargs) + self.cServer = server + self.cClient = client + + def run(self): + try: + self.cServer.cGlb._client(self.cServer,self) + except Exception: + printException() + + with self.cServer.cLockClients: + kickClient(self) + + if debug: + serverCount = 0 + socketCount = 0 + clientCount = 0 + with lockServers: + serverCount = len(servers) + for serverName in servers: + with servers[serverName].cLockSockets: + socketCount = len(servers[serverName].cSockets) + + with servers[serverName].cLockClients: + clientCount = len(servers[serverName].cClients) + + debugOutput("* serverCount:",serverCount) + debugOutput("* socketCount:",socketCount) + debugOutput("* clientCount:",clientCount) + debugOutput("* realThreads:",threading.active_count()) + +def closeServer(server): + debugOutput("Closing server:",server.cServerName) + if "_shutdown" in server.cGlb: + try: + if server.cGlb._shutdown() == True: + return + except Exception: + printException() + + for client in server.cClients: + try: + client.connection.close() + except Exception: + printException() + del servers[server.cServerName] + +class serverThread(threading.Thread): + def __init__(self,serverName,config,glb,*args,**kwargs): + super().__init__(*args,**kwargs) + self.cConfig = config + self.cGlb = glb + self.cLockSockets = threading.Lock() + self.cSockets = [] + self.cLockClients = threading.Lock() + self.cClients = [] + self.cQueueClients = queue.Queue() + self.cServerName = serverName + self.cSockets = [] + + def run(self): + while True: + client = self.cQueueClients.get() + if client == None: + with lockServers: + with self.cLockClients: + closeServer(self) + return + + with self.cLockClients: + clientThr = clientThread(self,client) + self.cClients.append(clientThr) + clientThr.start() + +class socketThread(threading.Thread): + def __init__(self,server,config,socket,*args,**kwargs): + super().__init__(*args,**kwargs) + self.cServer = server + self.cSocket = socket + self.cConfig = config + + def run(self): + while True: + try: + conn,addr = self.cSocket.accept() + client = mfp.Bunch() + client.connection = conn + client.address = addr + client.connection.settimeout(self.cConfig._timeout) + + try: + if "_filter" in self.cServer.cGlb and self.cServer.cGlb._filter(client) == True: + try: + client.connection.close() + except Exception: + printException() + continue + + if self.cConfig._ssl: + client.connection.do_handshake() + except Exception: + printException() + try: + client.connection.close() + except Exception: + printException() + continue + + self.cServer.cQueueClients.put(client) + except Exception: + printException() + try: + self.cSocket.close() + except Exception: + printException() + + with self.cServer.cLockSockets: + del self.cServer.cSockets[self.cServer.cSockets.index(self)] + return + +def main(): + dirConfig = mfp.p(mfp.sd,"config") + dirServers = mfp.p(dirConfig,"servers") + dirSockets = mfp.p(dirConfig,"sockets") + + print("Starting servers ...") + for root,dirs,files in os.walk(dirServers): + for file in sorted(files): + ffile = mfp.p(root,file) + lfile = ffile.replace(dirServers + os.path.sep,"",1) + serverName = lfile.rsplit(".",1)[0] + print("> " +serverName) + glb = mfp.Bunch() + config = toml.load(ffile) + config = mfp.bunchify(config) + thr = serverThread(serverName,config,glb) + servers[serverName] = thr + mfp.dofile(config["_script"],glb) + thr.start() + break + + print("\nStarting sockets ...") + for root,dirs,files in os.walk(dirSockets): + for file in sorted(dirs): + ffile = mfp.p(root,file) + lfile = ffile.replace(dirSockets + os.path.sep,"",1) + serverName = lfile + print("> " +serverName) + for root2,dirs2,files2 in os.walk(ffile): + for file2 in sorted(files2): + ffile2 = mfp.p(root2,file2) + lfile2 = ffile2.replace(ffile + os.path.sep,"",1) + socketName = lfile2.rsplit(".",1)[0] + print(">> " +socketName) + config = toml.load(ffile2) + config = mfp.bunchify(config) + serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + print(">>> Socket options:") + for opt in config._options: + print(">>>>",", ".join(opt)) + for i in range(len(opt)): + try: + opt[i] = int(opt[i]) + except Exception: + opt[i] = getattr(socket,opt[i]) + #print(">>>>>","(" +(", ".join(str(i) for i in opt))+ ")") + serverSocket.setsockopt(*opt) + print(">>> Address: ---",config._addr) + print(">>> Port: ------",config._port) + serverSocket.bind((config._addr,config._port)) + print(">>> SSL: -------",not (config._ssl == False)) + if config._ssl: + proto = False + if sys.version_info >= (3,10): + proto = ssl.PROTOCOL_TLS_SERVER + else: + proto = ssl.PROTOCOL_TLS + + ctx = ssl.SSLContext(proto) + ctx.check_hostname = False + ctx.load_cert_chain(config._ssl) + serverSocket = ctx.wrap_socket( + serverSocket, + server_side = True, + do_handshake_on_connect = False + ) + serverSocket.listen(65535) + + with lockServers: + for serverName in servers: + with servers[serverName].cLockSockets: + socketThr = socketThread(servers[serverName],config,serverSocket) + servers[serverName].cSockets.append(socketThr) + socketThr.start() + break + break + print("\nReady!") diff --git a/module/test.py b/module/test.py new file mode 100644 index 0000000..ac58484 --- /dev/null +++ b/module/test.py @@ -0,0 +1,4 @@ +print("Running new instance of " +mfpl.s) +st = None +def echo(): + print(st) diff --git a/scripts/http_example/main.py b/scripts/http_example/main.py new file mode 100644 index 0000000..1cd46de --- /dev/null +++ b/scripts/http_example/main.py @@ -0,0 +1,10 @@ +print("hello world") +http = mfp.require("http") +def _client(server,client): + client.cClient.connection.sendall("HTTP/1.1 200 OK\n".encode("ascii")) + client.cClient.connection.sendall(http.header.create([ + ["Content-Type","text/html; charset=ascii"], + ["Content-Length","47"] + ]).encode("ascii")) + client.cClient.connection.sendall("\n

Hello, world

".encode("ascii")) + diff --git a/tcpserver.py b/tcpserver.py new file mode 100755 index 0000000..01c927a --- /dev/null +++ b/tcpserver.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +def init(): pass +def main(): + mfp.setProgramName("me.fier.tcpserver") # Your domain/username and the name of your program + server = mfp.require("server") + server.main() + +def bootstrap(name,modName): + if name in globals(): return + import sys, os, importlib + if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): + s = os.path.realpath(sys.executable) + else: + s = os.path.realpath(__file__) + + if not os.path.join(os.path.dirname(s),"module","py") in sys.path: + sys.path = [os.path.join(os.path.dirname(s),"module","py")] + sys.path + + mod = importlib.import_module(modName); modl = mod.Bunch() + mod.init(mod,modl,s,name) + globals()[name] = mod; globals()[name + "l"] = modl + +bootstrap("mfp","me.fier.python") +init() +if __name__ == '__main__': + main()