xenu_nntp/lib/nntp/tiny/server.py

65 lines
1.8 KiB
Python
Raw Normal View History

2024-11-20 21:17:03 -05:00
import enum
2024-11-26 16:55:44 -05:00
import socket
2024-12-03 12:14:45 -05:00
import ssl
2024-11-26 16:55:44 -05:00
import threading
2024-11-20 21:17:03 -05:00
from configparser import ConfigParser
2024-11-26 16:24:32 -05:00
from nntp.tiny.db import Database
2024-11-22 23:57:14 -05:00
from nntp.tiny.newsgroup import Newsgroup
2024-11-26 16:55:44 -05:00
from nntp.tiny.session import Session
2024-11-22 23:57:14 -05:00
2024-11-20 21:17:03 -05:00
class ServerCapability(enum.Flag):
NONE = 0
AUTH = enum.auto()
POST = enum.auto()
class Server():
def __init__(self, config: ConfigParser):
self.config = config
self.capabilities = ServerCapability.NONE
self.newsgroups = dict()
2024-12-03 12:14:45 -05:00
self.sslctx = None
if config['listen'].get('tls', 'no') == 'yes':
self.sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.sslctx.load_cert_chain(config['tls']['cert'],
config['tls']['key'])
2024-11-22 23:57:14 -05:00
2024-11-25 00:16:15 -05:00
self._init_newsgroups()
2024-11-22 23:57:14 -05:00
def connect_to_db(self):
return Database.connect(self.config['database']['path'])
2024-11-22 23:57:14 -05:00
def _init_newsgroups(self):
2024-11-26 16:24:32 -05:00
db = self.connect_to_db()
for newsgroup in db.query(Newsgroup).each():
2024-11-22 23:57:14 -05:00
self.newsgroups[newsgroup.name.casefold()] = newsgroup
2024-11-26 16:55:44 -05:00
def run(self):
host = self.config['listen']['host']
port = int(self.config['listen']['port'])
2024-11-26 16:55:44 -05:00
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind((host, port))
2024-11-26 16:55:44 -05:00
listener.listen()
2024-12-03 12:14:45 -05:00
if self.sslctx:
listener = self.sslctx.wrap_socket(listener, server_side=True)
2024-11-26 16:55:44 -05:00
while True:
2024-12-03 12:14:45 -05:00
try:
sock, addr = listener.accept()
2024-11-26 16:55:44 -05:00
2024-12-03 12:14:45 -05:00
def spawn():
session = Session(self, sock)
session.handle()
2024-11-26 17:01:49 -05:00
2024-12-03 12:14:45 -05:00
thread = threading.Thread(target=spawn)
thread.start()
except ssl.SSLEOFError as e:
2024-12-03 12:14:45 -05:00
pass
2024-11-26 16:55:44 -05:00
listener.close()