xenu_nntp/lib/nntp/tiny/server.py

86 lines
2.4 KiB
Python
Raw Normal View History

import re
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
2024-12-06 11:14:38 -05:00
from nntp.tiny.config import Config, ConfigException
from nntp.tiny.db import Database
from nntp.tiny.host import Host
from nntp.tiny.session import Session
2024-11-22 23:57:14 -05:00
2024-11-20 21:17:03 -05:00
class Server():
def __init__(self, config: Config):
2024-12-07 15:48:56 -05:00
self.config = config
self.sslctx = None
2024-12-03 12:14:45 -05:00
if config.section('listen').get('tls', 'no') == 'yes':
2024-12-03 12:14:45 -05:00
self.sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.sslctx.load_cert_chain(config.get('tls', 'cert'),
config.get('tls', 'key'))
2024-11-22 23:57:14 -05:00
def connect_to_db(self):
return Database.connect(self.config.get('database', 'path'))
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 = None, None
try:
sock, addr = listener.accept()
except ssl.SSLError as e:
return
def spawn():
session = Session(self, sock)
try:
session.handle()
2024-12-04 23:28:25 -05:00
except (ssl.SSLEOFError, ssl.SSLError):
pass
thread = threading.Thread(target=spawn)
thread.start()
2024-11-26 16:55:44 -05:00
def run(self):
hosts = re.split(r'\s*,\s*', self.config.get('listen', 'host'))
port = int(self.config.get('listen', 'port'))
listeners = list()
for host in hosts:
if Host.is_ipv6(host):
listeners.append(self.listen(host, port, socket.AF_INET6))
elif Host.is_ipv4(host):
listeners.append(self.listen(host, port, socket.AF_INET))
else:
for af in (socket.AF_INET, socket.AF_INET6):
listeners.append(self.listen(host, port, af))
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)
2024-12-07 06:39:05 -05:00
def stop(self):
...