xenu_nntp/lib/nntp/tiny/server.py

92 lines
2.6 KiB
Python
Raw Normal View History

2024-11-20 21:17:03 -05:00
import enum
import threading
2024-11-26 16:55:44 -05:00
import socket
import selectors
2024-12-03 12:14:45 -05:00
import ssl
2024-11-20 21:17:03 -05:00
from configparser import ConfigParser
2024-11-26 16:24:32 -05:00
from nntp.tiny.config import ConfigException
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 listen(self, host: str, port: int, af: int):
listener = socket.socket(af, 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:
return self.sslctx.wrap_socket(listener, server_side=True)
2024-12-03 12:14:45 -05:00
return listener
def accept(self, listener):
sock, addr = listener.accept()
def spawn():
session = Session(self, sock)
try:
session.handle()
except (ssl.SSLError, ssl.SSLEOFError) as e:
pass
thread = threading.Thread(target=spawn)
thread.start()
2024-11-26 16:55:44 -05:00
def run(self):
port = int(self.config['listen']['port'])
listeners = list()
if self.config.has_option('listen', 'host_inet'):
host = self.config.get('listen', 'host_inet')
listeners.append(self.listen(host, port, socket.AF_INET))
if self.config.has_option('listen', 'host_inet6'):
host = self.config.get('listen', 'host_inet6')
listeners.append(self.listen(host, port, socket.AF_INET6))
2024-11-26 17:01:49 -05:00
if len(listeners) == 0:
raise ConfigException("No listener hosts specified")
sel = selectors.DefaultSelector()
for listener in listeners:
sel.register(listener, selectors.EVENT_READ)
while True:
events = sel.select()
2024-11-26 16:55:44 -05:00
for key, ev in events:
self.accept(key.fileobj)