This commit is contained in:
NHerby 2026-03-03 21:43:01 +07:00 committed by GitHub
commit 8cea9c61b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 44 additions and 43 deletions

View file

@ -125,7 +125,7 @@ else:
translog.addHandler(logging.StreamHandler(sys.stdout)) translog.addHandler(logging.StreamHandler(sys.stdout))
translog.setLevel(logging.CRITICAL + 1) # Ignore this logger translog.setLevel(logging.CRITICAL + 1) # Ignore this logger
logging.getLogger("passlib").setLevel(logging.CRITICAL + 1) # Ignore this logger logging.getLogger("passlib").setLevel(logging.CRITICAL + 1) # Ignore this logger
brokerlog = logging.getLogger("hbmqtt.broker") brokerlog = logging.getLogger("amqtt.broker")
#brokerlog.setLevel( #brokerlog.setLevel(
# logging.CRITICAL + 1 # logging.CRITICAL + 1
#) # Ignore this logger #There are some sublogs that could be set if needed (.plugins) #) # Ignore this logger #There are some sublogs that could be set if needed (.plugins)
@ -133,7 +133,7 @@ if not log_to_stdout:
brokerlog.addHandler(mqtt_rotate) brokerlog.addHandler(mqtt_rotate)
else: else:
brokerlog.addHandler(logging.StreamHandler(sys.stdout)) brokerlog.addHandler(logging.StreamHandler(sys.stdout))
protolog = logging.getLogger("hbmqtt.mqtt.protocol") protolog = logging.getLogger("amqtt.mqtt.protocol")
#protolog.setLevel( #protolog.setLevel(
# logging.CRITICAL + 1 # logging.CRITICAL + 1
#) # Ignore this logger #) # Ignore this logger
@ -141,7 +141,7 @@ if not log_to_stdout:
protolog.addHandler(mqtt_rotate) protolog.addHandler(mqtt_rotate)
else: else:
protolog.addHandler(logging.StreamHandler(sys.stdout)) protolog.addHandler(logging.StreamHandler(sys.stdout))
clientlog = logging.getLogger("hbmqtt.client") clientlog = logging.getLogger("amqtt.client")
#clientlog.setLevel(logging.CRITICAL + 1) # Ignore this logger #clientlog.setLevel(logging.CRITICAL + 1) # Ignore this logger
if not log_to_stdout: if not log_to_stdout:
clientlog.addHandler(mqtt_rotate) clientlog.addHandler(mqtt_rotate)

View file

@ -3,11 +3,14 @@
import logging import logging
import asyncio import asyncio
import os import os
import hbmqtt import amqtt as hbmqtt
from hbmqtt.broker import Broker import amqtt.broker
from hbmqtt.client import MQTTClient from amqtt.broker import Broker
from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2 from amqtt.client import MQTTClient
import pkg_resources from amqtt.mqtt.constants import QOS_0, QOS_1, QOS_2
from amqtt.plugins.base import BaseAuthPlugin
from dataclasses import dataclass, field
amqtt.broker.BrokerException = Exception # amqtt removed this; map to generic Exception
import time import time
import bumper import bumper
import json import json
@ -183,60 +186,60 @@ class MQTTServer:
elif key == "allow_anonymous": elif key == "allow_anonymous":
allow_anon = kwargs["allow_anonymous"] # Set to True to allow anonymous authentication allow_anon = kwargs["allow_anonymous"] # Set to True to allow anonymous authentication
# The below adds a plugin to the hbmqtt.broker.plugins without having to futz with setup.py # Initialize bot server using amqtt's config-based plugin format
distribution = pkg_resources.Distribution("hbmqtt.broker.plugins")
bumper_plugin = pkg_resources.EntryPoint.parse(
"bumper = bumper.mqttserver:BumperMQTTServer_Plugin", dist=distribution
)
distribution._ep_map = {"hbmqtt.broker.plugins": {"bumper": bumper_plugin}}
pkg_resources.working_set.add(distribution)
# Initialize bot server
self.default_config = { self.default_config = {
"listeners": { "listeners": {
"default": {"type": "tcp"}, "default": {"type": "tcp"},
"tls1": { "tls1": {
"bind": "{}:{}".format(address[0], address[1]), "bind": "{}:{}".format(address[0], address[1]),
"ssl": "on", "ssl": True,
"certfile": bumper.server_cert,
"keyfile": bumper.server_key,
},
"wss1": {
"type": "ws",
"bind": "0.0.0.0:8884",
"ssl": True,
"certfile": bumper.server_cert, "certfile": bumper.server_cert,
"keyfile": bumper.server_key, "keyfile": bumper.server_key,
}, },
}, },
"sys_interval": 0, "plugins": {
"auth": { "bumper.mqttserver.BumperMQTTServer_Plugin": {
"allow-anonymous": allow_anon, "allow_anonymous": allow_anon,
"password-file": passwd_file, "password_file": passwd_file,
"plugins": ["bumper"], # Bumper plugin provides auth and handling of bots/clients connecting }
}, },
"topic-check": {"enabled": False},
} }
self.broker = hbmqtt.broker.Broker(config=self.default_config) self.broker = amqtt.broker.Broker(config=self.default_config)
except Exception as e: except Exception as e:
mqttserverlog.exception("{}".format(e)) mqttserverlog.exception("{}".format(e))
class BumperMQTTServer_Plugin: class BumperMQTTServer_Plugin(BaseAuthPlugin):
@dataclass
class Config:
allow_anonymous: bool = False
password_file: str = ""
def __init__(self, context): def __init__(self, context):
self.context = context super().__init__(context)
try: try:
self.auth_config = self.context.config["auth"]
self._users = dict() self._users = dict()
cfg = context.config
self._allow_anonymous = getattr(cfg, "allow_anonymous", False)
self._password_file = getattr(cfg, "password_file", None)
self._read_password_file() self._read_password_file()
except KeyError:
self.context.logger.warning(
"'bumper' section not found in context configuration"
)
except Exception as e: except Exception as e:
mqttserverlog.exception("{}".format(e)) mqttserverlog.exception("{}".format(e))
async def authenticate(self, *args, **kwargs): async def authenticate(self, *, session=None, **kwargs):
authenticated = False authenticated = False
try: try:
session = kwargs.get("session", None)
username = session.username username = session.username
password = session.password password = session.password
client_id = session.client_id client_id = session.client_id
@ -295,14 +298,12 @@ class BumperMQTTServer_Plugin:
except Exception as e: except Exception as e:
mqttserverlog.exception( mqttserverlog.exception(
"Session: {} - {}".format((kwargs.get("session", None)), e) "Session: {} - {}".format(session, e)
) )
authenticated = False authenticated = False
# Check for allow anonymous # Check for allow anonymous
allow_anonymous = self.auth_config.get( allow_anonymous = self._allow_anonymous
"allow-anonymous", True
)
if allow_anonymous and not authenticated: # If anonymous auth is allowed and it isn't already authenticated if allow_anonymous and not authenticated: # If anonymous auth is allowed and it isn't already authenticated
authenticated = True authenticated = True
self.context.logger.debug(f"Anonymous Authentication Success: config allows anonymous - Username: {username}") self.context.logger.debug(f"Anonymous Authentication Success: config allows anonymous - Username: {username}")
@ -311,7 +312,7 @@ class BumperMQTTServer_Plugin:
return authenticated return authenticated
def _read_password_file(self): def _read_password_file(self):
password_file = self.auth_config.get('password-file', None) password_file = self._password_file
if password_file: if password_file:
try: try:
with open(password_file) as f: with open(password_file) as f:
@ -327,7 +328,7 @@ class BumperMQTTServer_Plugin:
except FileNotFoundError: except FileNotFoundError:
self.context.logger.warning(f"Password file {password_file} not found") self.context.logger.warning(f"Password file {password_file} not found")
async def on_broker_client_connected(self, client_id): async def on_broker_client_connected(self, client_id, **kwargs):
didsplit = str(client_id).split("@") didsplit = str(client_id).split("@")
@ -405,7 +406,7 @@ class BumperMQTTServer_Plugin:
bumper.mqtt_helperbot.command_responses.remove(msg) bumper.mqtt_helperbot.command_responses.remove(msg)
async def on_broker_client_disconnected(self, client_id): async def on_broker_client_disconnected(self, client_id, **kwargs):
didsplit = str(client_id).split("@") didsplit = str(client_id).split("@")