clean up the code, enforce 63 character limit

This commit is contained in:
randomuser 2021-07-20 12:50:52 -05:00
parent 4eda8f6d2c
commit ffbbb6f93b
1 changed files with 37 additions and 19 deletions

56
esgd.py
View File

@ -1,4 +1,5 @@
import socketserver from socketserver import TCPServer
from socketserver import BaseRequestHandler
import subprocess import subprocess
import argparse import argparse
import os import os
@ -18,6 +19,7 @@ class GopherLine:
self.port = "0" self.port = "0"
self.line = line self.line = line
self.parse() self.parse()
def parse(self): def parse(self):
split = self.line.rstrip().split('\t') split = self.line.rstrip().split('\t')
location = False location = False
@ -57,24 +59,30 @@ class Logger:
def __init__(self, file=None): def __init__(self, file=None):
if file != None: self.fd = open(file, "a+") if file != None: self.fd = open(file, "a+")
else: self.fd = False else: self.fd = False
def time(self): def time(self):
return int(time.time()) return int(time.time())
def write(self, msg): def write(self, msg):
if self.fd: self.fd.write("{}\n") if self.fd: self.fd.write("{}\n")
def log(self, msg): def log(self, msg):
ct = self.time() ct = self.time()
self.write("[{}] {}".format(str(ct), msg)) self.write("[{}] {}".format(str(ct), msg))
print("[{}] {}".format(str(ct), msg)) print("[{}] {}".format(str(ct), msg))
def warn(self, msg): def warn(self, msg):
ct = self.time() ct = self.time()
self.write("! [{}] {}".format(str(ct), msg)) self.write("! [{}] {}".format(str(ct), msg))
print("! [{}] {}".format(str(ct), msg)) print("! [{}] {}".format(str(ct), msg))
def error(self, msg): def error(self, msg):
ct = self.time() ct = self.time()
self.write("!! [{}] {}".format(str(ct), msg)) self.write("!! [{}] {}".format(str(ct), msg))
print("!! [{}] {}".format(str(ct), msg)) print("!! [{}] {}".format(str(ct), msg))
self.close() self.close()
raise SystemExit raise SystemExit
def close(self): def close(self):
if self.fd: self.fd.close() if self.fd: self.fd.close()
@ -107,16 +115,19 @@ class GopherServerLogic:
else: raise RequestError("unreachable state") else: raise RequestError("unreachable state")
return (ret, gph) return (ret, gph)
def fileSendable(self, file): return os.access(file, os.F_OK|os.R_OK) def fileSendable(self, file):
return os.access(file, os.F_OK|os.R_OK)
def fileCGI(self, file): def fileCGI(self, file):
return os.access(file, os.F_OK|os.R_OK|os.X_OK) return os.access(file, os.F_OK|os.R_OK|os.X_OK)
def notFound(self): def notFound(self):
self.request.sendall(b"3error: file not found!\r\n.\r\n") self.request.sendall(
b"3error: file not found!\r\n.\r\n")
def invalid(self): def invalid(self):
self.request.sendall(b"3error: selector contains '..'!\r\n.\r\n") self.request.sendall(
b"3error: selector contains '..'!\r\n.\r\n")
def fileToFileArray(self, file): def fileToFileArray(self, file):
fd = open(file, "r") fd = open(file, "r")
@ -147,7 +158,9 @@ class GopherServerLogic:
proc.kill() proc.kill()
out, err = proc.communicate() out, err = proc.communicate()
return out.decode("utf-8").replace("\r", "").split("\n") return out.decode("utf-8")\
.replace("\r", "")\
.split("\n")
def gopherRenderer(self, fileArray): def gopherRenderer(self, fileArray):
gopherlines = [] gopherlines = []
@ -160,7 +173,8 @@ class GopherServerLogic:
def serveFile(self, file, query, gph): def serveFile(self, file, query, gph):
if self.fileCGI(file): fa = self.cgi(file, query) if self.fileCGI(file): fa = self.cgi(file, query)
elif self.fileSendable(file): fa = self.fileToFileArray(file) elif self.fileSendable(file):
fa = self.fileToFileArray(file)
else: else:
log.log("selector not found") log.log("selector not found")
self.notFound() self.notFound()
@ -168,9 +182,11 @@ class GopherServerLogic:
if gph: fa = self.gopherRenderer(fa) if gph: fa = self.gopherRenderer(fa)
self.sendFileArray(fa) self.sendFileArray(fa)
class GopherHandler(socketserver.BaseRequestHandler, GopherServerLogic): class GopherHandler(BaseRequestHandler,
GopherServerLogic):
def handle(self): def handle(self):
log.log("request from {}".format(self.client_address[0])) log.log("request from {}".format(
self.client_address[0]))
decoded = self.recieveRequest() decoded = self.recieveRequest()
try: parsed = self.requestParser(decoded) try: parsed = self.requestParser(decoded)
except RequestError: except RequestError:
@ -190,14 +206,18 @@ log = Logger()
def parseArgs(): def parseArgs():
parse = argparse.ArgumentParser() parse = argparse.ArgumentParser()
parse.add_argument("-u", "--user", default="nobody", help="user to change to on startup") parse.add_argument("-u", "--user", default="nobody",
parse.add_argument("-g", "--group", default="nobody", help="group to change to on startup") help="user to change to on startup")
parse.add_argument("-s", "--host", default="localhost", help="host to host on") parse.add_argument("-g", "--group", default="nobody",
parse.add_argument("-p", "--port", default=70, type=int, help="port to host on") help="group to change to on startup")
parse.add_argument("-d", "--dir", default="/var/gopher", help="directory to host from") parse.add_argument("-s", "--host", default="localhost",
help="host to host on")
parse.add_argument("-p", "--port", default=70, type=int,
help="port to host on")
parse.add_argument("-d", "--dir", default="/var/gopher",
help="directory to host from")
return parse.parse_args() return parse.parse_args()
if __name__ == "__main__": if __name__ == "__main__":
args = parseArgs() args = parseArgs()
log.log("arguments parsed") log.log("arguments parsed")
@ -209,14 +229,12 @@ if __name__ == "__main__":
location = args.dir location = args.dir
log.log("arguments good") log.log("arguments good")
try: try:
with socketserver.TCPServer((host, port), GopherHandler) as server: with TCPServer((host, port), GopherHandler) as server:
os.setgid(switchgrp) os.setgid(switchgrp)
os.seteuid(switchusr) os.seteuid(switchusr)
log.log("switch user successful") log.log("switch user successful")
os.chdir(location) os.chdir(location)
log.log("change directory successful") log.log("change directory successful")
server.serve_forever() server.serve_forever()
except PermissionError: except PermissionError: log.error("invalid permissions")
log.error("invalid permissions") except OSError: log.error("address already in use")
except OSError:
log.error("address already in use")