mirror of
https://github.com/iio612/DEFENDER.git
synced 2026-02-13 19:24:23 +00:00
New Version
This commit is contained in:
113
core/base.py
113
core/base.py
@@ -1,8 +1,9 @@
|
||||
import time, threading, os, random, socket, hashlib, ipaddress
|
||||
import time, threading, os, random, socket, hashlib, ipaddress, logging, requests, json, sys
|
||||
from datetime import datetime
|
||||
from sqlalchemy import create_engine, Engine, Connection, CursorResult
|
||||
from sqlalchemy.sql import text
|
||||
from core.configuration import Config
|
||||
from core.sys_configuration import SysConfig
|
||||
|
||||
class Base:
|
||||
|
||||
@@ -19,6 +20,10 @@ class Base:
|
||||
def __init__(self, Config: Config) -> None:
|
||||
|
||||
self.Config = Config # Assigner l'objet de configuration
|
||||
self.SysConfig = SysConfig() # Importer les information pour le systeme
|
||||
self.init_log_system() # Demarrer le systeme de log
|
||||
|
||||
self.get_latest_defender_version()
|
||||
|
||||
self.running_timers:list[threading.Timer] = [] # Liste des timers en cours
|
||||
self.running_threads:list[threading.Thread] = [] # Liste des threads en cours
|
||||
@@ -32,6 +37,26 @@ class Base:
|
||||
|
||||
self.db_create_first_admin() # Créer un nouvel admin si la base de données est vide
|
||||
|
||||
def get_latest_defender_version(self) -> None:
|
||||
try:
|
||||
#token = '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'
|
||||
token = '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'
|
||||
json_url = f'https://github.com/adator85/IRC_DEFENDER_MODULES/blob/e27a027ae99a6c11171635b2a120803e8682aac6/version.json'
|
||||
headers = {
|
||||
'Authorization': f'token {token}',
|
||||
'Accept': 'application/vnd.github.v3.raw' # Indique à GitHub que nous voulons le contenu brut du fichier
|
||||
}
|
||||
response = requests.get(json_url)
|
||||
response.raise_for_status() # Vérifie si la requête a réussi
|
||||
json_response:dict = response.json()
|
||||
self.SysConfig.LATEST_DEFENDER_VERSION = json_response["version"]
|
||||
|
||||
return None
|
||||
except requests.HTTPError as err:
|
||||
self.logs.error(f'Github not available to fetch latest version: {err}')
|
||||
except:
|
||||
self.logs.warning(f'Github not available to fetch latest version')
|
||||
|
||||
def get_unixtime(self) -> int:
|
||||
"""
|
||||
Cette fonction retourne un UNIXTIME de type 12365456
|
||||
@@ -62,12 +87,36 @@ class Base:
|
||||
|
||||
return None
|
||||
|
||||
def init_log_system(self) -> None:
|
||||
# Create folder if not available
|
||||
logs_directory = f'logs{os.sep}'
|
||||
if not os.path.exists(f'{logs_directory}'):
|
||||
os.makedirs(logs_directory)
|
||||
|
||||
# Init logs object
|
||||
self.logs = logging
|
||||
self.logs.basicConfig(level=self.Config.DEBUG_LEVEL,
|
||||
filename='logs/defender.log',
|
||||
encoding='UTF-8',
|
||||
format='%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(funcName)s - %(message)s')
|
||||
|
||||
self.logs.info('#################### STARTING INTERCEPTOR HQ ####################')
|
||||
|
||||
return None
|
||||
|
||||
def log_cmd(self, user_cmd:str, cmd:str) -> None:
|
||||
"""Enregistre les commandes envoyées par les utilisateurs
|
||||
|
||||
Args:
|
||||
cmd (str): la commande a enregistrer
|
||||
"""
|
||||
cmd_list = cmd.split()
|
||||
if len(cmd_list) == 3:
|
||||
if cmd_list[0].replace('.', '') == 'auth':
|
||||
cmd_list[1] = '*******'
|
||||
cmd_list[2] = '*******'
|
||||
cmd = ' '.join(cmd_list)
|
||||
|
||||
insert_cmd_query = f"INSERT INTO {self.DB_SCHEMA['commandes']} (datetime, user, commande) VALUES (:datetime, :user, :commande)"
|
||||
mes_donnees = {'datetime': self.get_datetime(), 'user': user_cmd, 'commande': cmd}
|
||||
self.db_execute_query(insert_cmd_query, mes_donnees)
|
||||
@@ -100,13 +149,13 @@ class Base:
|
||||
"""
|
||||
|
||||
if not self.db_isModuleExist(module_name):
|
||||
self.__debug(f"Le module {module_name} n'existe pas alors ont le créer")
|
||||
self.logs.debug(f"Le module {module_name} n'existe pas alors ont le créer")
|
||||
insert_cmd_query = f"INSERT INTO {self.DB_SCHEMA['modules']} (datetime, user, module) VALUES (:datetime, :user, :module)"
|
||||
mes_donnees = {'datetime': self.get_datetime(), 'user': user_cmd, 'module': module_name}
|
||||
self.db_execute_query(insert_cmd_query, mes_donnees)
|
||||
# self.db_close_session(self.session)
|
||||
else:
|
||||
self.__debug(f"Le module {module_name} existe déja dans la base de données")
|
||||
self.logs.debug(f"Le module {module_name} existe déja dans la base de données")
|
||||
|
||||
return False
|
||||
|
||||
@@ -148,10 +197,10 @@ class Base:
|
||||
|
||||
self.running_timers.append(t)
|
||||
|
||||
self.__debug(f"Timer ID : {str(t.ident)} | Running Threads : {len(threading.enumerate())}")
|
||||
self.logs.debug(f"Timer ID : {str(t.ident)} | Running Threads : {len(threading.enumerate())}")
|
||||
|
||||
except AssertionError as ae:
|
||||
self.__debug(f'Assertion Error -> {ae}')
|
||||
self.logs.error(f'Assertion Error -> {ae}')
|
||||
|
||||
def create_thread(self, func:object, func_args: tuple = (), run_once:bool = False) -> None:
|
||||
try:
|
||||
@@ -170,98 +219,95 @@ class Base:
|
||||
th.start()
|
||||
|
||||
self.running_threads.append(th)
|
||||
self.__debug(f"Thread ID : {str(th.ident)} | Thread name : {th.getName()} | Running Threads : {len(threading.enumerate())}")
|
||||
self.logs.debug(f"Thread ID : {str(th.ident)} | Thread name : {th.getName()} | Running Threads : {len(threading.enumerate())}")
|
||||
|
||||
except AssertionError as ae:
|
||||
self.__debug(f'Assertion Error -> {ae}')
|
||||
self.logs.error(f'{ae}')
|
||||
|
||||
def garbage_collector_timer(self) -> None:
|
||||
"""Methode qui supprime les timers qui ont finis leurs job
|
||||
"""
|
||||
try:
|
||||
# self.__debug(f"=======> Checking for Timers to stop")
|
||||
# print(f"{self.running_timers}")
|
||||
|
||||
for timer in self.running_timers:
|
||||
if not timer.is_alive():
|
||||
timer.cancel()
|
||||
self.running_timers.remove(timer)
|
||||
self.__debug(f"Timer {str(timer)} removed")
|
||||
self.logs.info(f"Timer {str(timer)} removed")
|
||||
else:
|
||||
self.__debug(f"===> Timer {str(timer)} Still running ...")
|
||||
self.logs.debug(f"===> Timer {str(timer)} Still running ...")
|
||||
|
||||
except AssertionError as ae:
|
||||
print(f'Assertion Error -> {ae}')
|
||||
self.logs.error(f'Assertion Error -> {ae}')
|
||||
|
||||
def garbage_collector_thread(self) -> None:
|
||||
"""Methode qui supprime les threads qui ont finis leurs job
|
||||
"""
|
||||
try:
|
||||
# self.__debug(f"=======> Checking for Threads to stop")
|
||||
for thread in self.running_threads:
|
||||
if thread.getName() != 'heartbeat':
|
||||
if not thread.is_alive():
|
||||
self.running_threads.remove(thread)
|
||||
self.__debug(f"Thread {str(thread.getName())} {str(thread.native_id)} removed")
|
||||
self.logs.debug(f"Thread {str(thread.getName())} {str(thread.native_id)} removed")
|
||||
|
||||
# print(threading.enumerate())
|
||||
except AssertionError as ae:
|
||||
self.__debug(f'Assertion Error -> {ae}')
|
||||
self.logs.error(f'Assertion Error -> {ae}')
|
||||
|
||||
def garbage_collector_sockets(self) -> None:
|
||||
|
||||
# self.__debug(f"=======> Checking for Sockets to stop")
|
||||
for soc in self.running_sockets:
|
||||
while soc.fileno() != -1:
|
||||
self.__debug(soc.fileno())
|
||||
self.logs.debug(soc.fileno())
|
||||
soc.close()
|
||||
|
||||
soc.close()
|
||||
self.running_sockets.remove(soc)
|
||||
self.__debug(f"Socket ==> closed {str(soc.fileno())}")
|
||||
self.logs.debug(f"Socket ==> closed {str(soc.fileno())}")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Methode qui va préparer l'arrêt complêt du service
|
||||
"""
|
||||
# Nettoyage des timers
|
||||
print(f"=======> Checking for Timers to stop")
|
||||
self.logs.debug(f"=======> Checking for Timers to stop")
|
||||
for timer in self.running_timers:
|
||||
while timer.is_alive():
|
||||
print(f"> waiting for {timer.getName()} to close")
|
||||
self.logs.debug(f"> waiting for {timer.getName()} to close")
|
||||
timer.cancel()
|
||||
time.sleep(0.2)
|
||||
self.running_timers.remove(timer)
|
||||
print(f"> Cancelling {timer.getName()} {timer.native_id}")
|
||||
self.logs.debug(f"> Cancelling {timer.getName()} {timer.native_id}")
|
||||
|
||||
print(f"=======> Checking for Threads to stop")
|
||||
self.logs.debug(f"=======> Checking for Threads to stop")
|
||||
for thread in self.running_threads:
|
||||
if thread.getName() == 'heartbeat' and thread.is_alive():
|
||||
self.execute_periodic_action()
|
||||
print(f"> Running the last periodic action")
|
||||
self.logs.debug(f"> Running the last periodic action")
|
||||
self.running_threads.remove(thread)
|
||||
print(f"> Cancelling {thread.getName()} {thread.native_id}")
|
||||
self.logs.debug(f"> Cancelling {thread.getName()} {thread.native_id}")
|
||||
|
||||
print(f"=======> Checking for Sockets to stop")
|
||||
self.logs.debug(f"=======> Checking for Sockets to stop")
|
||||
for soc in self.running_sockets:
|
||||
soc.close()
|
||||
while soc.fileno() != -1:
|
||||
soc.close()
|
||||
|
||||
self.running_sockets.remove(soc)
|
||||
print(f"> Socket ==> closed {str(soc.fileno())}")
|
||||
self.logs.debug(f"> Socket ==> closed {str(soc.fileno())}")
|
||||
|
||||
return None
|
||||
|
||||
def db_init(self) -> tuple[Engine, Connection]:
|
||||
|
||||
db_directory = self.Config.DEFENDER_DB_PATH
|
||||
full_path_db = self.Config.DEFENDER_DB_PATH + self.Config.DEFENDER_DB_NAME
|
||||
db_directory = self.SysConfig.DEFENDER_DB_PATH
|
||||
full_path_db = self.SysConfig.DEFENDER_DB_PATH + self.SysConfig.DEFENDER_DB_NAME
|
||||
|
||||
if not os.path.exists(db_directory):
|
||||
os.makedirs(db_directory)
|
||||
|
||||
engine = create_engine(f'sqlite:///{full_path_db}.db', echo=False)
|
||||
cursor = engine.connect()
|
||||
|
||||
self.logs.info("database connexion has been initiated")
|
||||
return engine, cursor
|
||||
|
||||
def __create_db(self) -> None:
|
||||
@@ -325,7 +371,7 @@ class Base:
|
||||
try:
|
||||
self.cursor.close()
|
||||
except AttributeError as ae:
|
||||
self.__debug(f"Attribute Error : {ae}")
|
||||
self.logs.error(f"Attribute Error : {ae}")
|
||||
|
||||
def crypt_password(self, password:str) -> str:
|
||||
"""Retourne un mot de passe chiffré en MD5
|
||||
@@ -396,10 +442,3 @@ class Base:
|
||||
|
||||
# Vider le dictionnaire de fonction
|
||||
self.periodic_func.clear()
|
||||
|
||||
def __debug(self, debug_msg:str) -> None:
|
||||
|
||||
if self.Config.DEBUG == 1:
|
||||
print(f"[{self.get_datetime()}] - {debug_msg}")
|
||||
|
||||
return None
|
||||
@@ -1,5 +1,3 @@
|
||||
import os
|
||||
from typing import Literal, Dict, List
|
||||
##########################################
|
||||
# CONFIGURATION FILE : #
|
||||
# Rename file to : configuration.py #
|
||||
@@ -7,19 +5,15 @@ from typing import Literal, Dict, List
|
||||
|
||||
class Config:
|
||||
|
||||
DEFENDER_VERSION = '3.3.2' # MAJOR.MINOR.BATCH
|
||||
DEFENDER_DB_PATH = 'db' + os.sep # Séparateur en fonction de l'OS
|
||||
DEFENDER_DB_NAME = 'defender' # Le nom de la base de données principale
|
||||
SERVICE_NAME = 'defender' # Le nom du service
|
||||
|
||||
SERVEUR_IP = '8.8.8.8' # IP ou host du serveur à rejoindre
|
||||
SERVEUR_IP = '0.0.0.0' # IP ou host du serveur à rejoindre
|
||||
SERVEUR_HOSTNAME = 'your hostname' # Le hostname du serveur IRC
|
||||
SERVEUR_LINK = 'your link' # Host attendu par votre IRCd (ex. dans votre link block pour Unrealircd)
|
||||
SERVEUR_PORT = 6666 # Port du link
|
||||
SERVEUR_PASSWORD = 'your link password' # Mot de passe du link (Privilégiez argon2 sur Unrealircd)
|
||||
SERVEUR_ID = '002' # SID (identification) du bot en tant que Services
|
||||
SERVEUR_SSL = False # Activer / Desactiver la connexion SSL
|
||||
SERVEUR_SSL = True # Activer / Desactiver la connexion SSL
|
||||
|
||||
SERVICE_NAME = 'defender' # Le nom du service
|
||||
SERVICE_NICKNAME = 'BotName' # Nick du bot sur IRC
|
||||
SERVICE_REALNAME = 'BotRealname' # Realname du bot
|
||||
SERVICE_USERNAME = 'BotIdent' # Ident du bot
|
||||
@@ -45,7 +39,7 @@ class Config:
|
||||
WHITELISTED_IP = ['127.0.0.1'] # IP a ne pas scanner
|
||||
GLINE_DURATION = '1d' # La durée du gline
|
||||
|
||||
DEBUG = 0 # Afficher l'ensemble des messages du serveurs dans la console
|
||||
DEBUG_LEVEL = 10 # Le niveau des logs DEBUG 10 | INFO 20 | WARNING 30 | ERROR 40 | CRITICAL 50
|
||||
|
||||
CONFIG_COLOR = {
|
||||
'blanche': '\x0300', # Couleur blanche
|
||||
|
||||
255
core/irc.py
255
core/irc.py
@@ -1,7 +1,9 @@
|
||||
import ssl, re, importlib, sys, time, threading, socket
|
||||
from ssl import SSLSocket
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Union
|
||||
from core.configuration import Config
|
||||
from core.sys_configuration import SysConfig
|
||||
from core.base import Base
|
||||
|
||||
class Irc:
|
||||
@@ -16,6 +18,7 @@ class Irc:
|
||||
self.beat = 30 # Lancer toutes les 30 secondes des actions de nettoyages
|
||||
self.hb_active = True # Heartbeat active
|
||||
self.HSID = '' # ID du serveur qui accueil le service ( Host Serveur Id )
|
||||
self.IrcSocket:Union[socket.socket, SSLSocket] = None
|
||||
|
||||
self.INIT = 1 # Variable d'intialisation | 1 -> indique si le programme est en cours d'initialisation
|
||||
self.RESTART = 0 # Variable pour le redemarrage du bot | 0 -> indique que le programme n'es pas en cours de redemarrage
|
||||
@@ -23,6 +26,7 @@ class Irc:
|
||||
self.SSL_VERSION = None # Version SSL
|
||||
|
||||
self.Config = Config()
|
||||
self.SysConfig = SysConfig()
|
||||
|
||||
# Liste des commandes internes du bot
|
||||
self.commands_level = {
|
||||
@@ -49,7 +53,7 @@ class Irc:
|
||||
self.__create_socket()
|
||||
self.__connect_to_irc(ircInstance)
|
||||
except AssertionError as ae:
|
||||
self.debug(f'Assertion error : {ae}')
|
||||
self.Base.logs.critical(f'Assertion error: {ae}')
|
||||
|
||||
def __create_socket(self) -> None:
|
||||
|
||||
@@ -59,32 +63,36 @@ class Irc:
|
||||
|
||||
if self.Config.SERVEUR_SSL:
|
||||
# Créer un object ssl
|
||||
|
||||
ssl_context = self.__ssl_context()
|
||||
ssl_connexion = ssl_context.wrap_socket(soc, server_hostname=self.Config.SERVEUR_HOSTNAME)
|
||||
ssl_connexion.connect(connexion_information)
|
||||
self.IrcSocket:ssl.SSLSocket = ssl_connexion
|
||||
self.debug(f"Connexion en mode SSL : Version = {self.IrcSocket.version()}")
|
||||
self.IrcSocket:SSLSocket = ssl_connexion
|
||||
|
||||
self.Base.logs.info(f"Connexion en mode SSL : Version = {self.IrcSocket.version()}")
|
||||
self.SSL_VERSION = self.IrcSocket.version()
|
||||
else:
|
||||
soc.connect(connexion_information)
|
||||
self.IrcSocket:socket = soc
|
||||
self.debug("Connexion en mode normal")
|
||||
self.IrcSocket:socket.socket = soc
|
||||
self.Base.logs.info("Connexion en mode normal")
|
||||
|
||||
return None
|
||||
|
||||
except ssl.SSLEOFError as soe:
|
||||
self.debug(f"SSLEOFError __create_socket: {soe} - {self.IrcSocket.fileno()}")
|
||||
self.Base.logs.critical(f"SSLEOFError __create_socket: {soe} - {soc.fileno()}")
|
||||
except ssl.SSLError as se:
|
||||
self.debug(f"SSLError __create_socket: {se} - {self.IrcSocket.fileno()}")
|
||||
self.Base.logs.critical(f"SSLError __create_socket: {se} - {soc.fileno()}")
|
||||
except OSError as oe:
|
||||
self.debug(f"OSError __create_socket: {oe} - {self.IrcSocket.fileno()}")
|
||||
self.Base.logs.critical(f"OSError __create_socket: {oe} - {soc.fileno()}")
|
||||
except AttributeError as ae:
|
||||
self.Base.logs.critical(f"OSError __create_socket: {oe} - {soc.fileno()}")
|
||||
|
||||
def __ssl_context(self) -> ssl.SSLContext:
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
|
||||
self.Base.logs.debug(f'SSLContext initiated with verified mode {ctx.verify_mode}')
|
||||
|
||||
return ctx
|
||||
|
||||
def __connect_to_irc(self, ircInstance: 'Irc') -> None:
|
||||
@@ -97,23 +105,23 @@ class Irc:
|
||||
while self.signal:
|
||||
try:
|
||||
if self.RESTART == 1:
|
||||
self.Base.logs.debug('Restarting Defender ...')
|
||||
self.IrcSocket.shutdown(socket.SHUT_RDWR)
|
||||
self.IrcSocket.close()
|
||||
|
||||
while self.IrcSocket.fileno() != -1:
|
||||
time.sleep(0.5)
|
||||
self.debug("--> En attente de la fermeture du socket ...")
|
||||
self.Base.logs.warning('--> Waiting for socket to close ...')
|
||||
|
||||
self.__create_socket()
|
||||
self.__link(self.IrcSocket)
|
||||
self.load_existing_modules()
|
||||
self.RESTART = 0
|
||||
|
||||
# 4072 max what the socket can grab
|
||||
buffer_size = self.IrcSocket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
|
||||
# data = self.IrcSocket.recv(buffer_size).splitlines(True)
|
||||
|
||||
data_in_bytes = self.IrcSocket.recv(buffer_size)
|
||||
|
||||
data = data_in_bytes.splitlines(True)
|
||||
count_bytes = len(data_in_bytes)
|
||||
|
||||
while count_bytes > 4070:
|
||||
@@ -121,10 +129,8 @@ class Irc:
|
||||
new_data = self.IrcSocket.recv(buffer_size)
|
||||
data_in_bytes += new_data
|
||||
count_bytes = len(new_data)
|
||||
# print("========================================================")
|
||||
|
||||
data = data_in_bytes.splitlines()
|
||||
# print(f"{str(buffer_size)} - {str(len(data_in_bytes))}")
|
||||
data = data_in_bytes.splitlines(True)
|
||||
|
||||
if not data:
|
||||
break
|
||||
@@ -132,24 +138,24 @@ class Irc:
|
||||
self.send_response(data)
|
||||
|
||||
except ssl.SSLEOFError as soe:
|
||||
self.debug(f"SSLEOFError __connect_to_irc: {soe} - {data}")
|
||||
self.Base.logs.error(f"SSLEOFError __connect_to_irc: {soe} - {data}")
|
||||
except ssl.SSLError as se:
|
||||
self.debug(f"SSLError __connect_to_irc: {se} - {data}")
|
||||
self.Base.logs.error(f"SSLError __connect_to_irc: {se} - {data}")
|
||||
except OSError as oe:
|
||||
self.debug(f"SSLError __connect_to_irc: {oe} - {data}")
|
||||
# except Exception as e:
|
||||
# self.debug(f"Exception __connect_to_irc: {e} - {data}")
|
||||
self.Base.logs.error(f"SSLError __connect_to_irc: {oe} - {data}")
|
||||
|
||||
self.IrcSocket.shutdown(socket.SHUT_RDWR)
|
||||
self.IrcSocket.close()
|
||||
self.debug("--> Fermeture de Defender ...")
|
||||
self.Base.logs.info("--> Fermeture de Defender ...")
|
||||
|
||||
except AssertionError as ae:
|
||||
self.debug(f'Assertion error : {ae}')
|
||||
self.Base.logs.error(f'Assertion error : {ae}')
|
||||
except ValueError as ve:
|
||||
self.debug(f'Value Error : {ve}')
|
||||
self.Base.logs.error(f'Value Error : {ve}')
|
||||
except ssl.SSLEOFError as soe:
|
||||
self.debug(f"OS Error __connect_to_irc: {soe}")
|
||||
self.Base.logs.error(f"OS Error __connect_to_irc: {soe}")
|
||||
except AttributeError as atte:
|
||||
self.Base.logs.critical(f"{atte}")
|
||||
# except Exception as e:
|
||||
# self.debug(f"Exception: {e}")
|
||||
|
||||
@@ -160,38 +166,43 @@ class Irc:
|
||||
Args:
|
||||
writer (StreamWriter): permet l'envoi des informations au serveur.
|
||||
"""
|
||||
nickname = self.Config.SERVICE_NICKNAME
|
||||
username = self.Config.SERVICE_USERNAME
|
||||
realname = self.Config.SERVICE_REALNAME
|
||||
chan = self.Config.SERVICE_CHANLOG
|
||||
info = self.Config.SERVICE_INFO
|
||||
smodes = self.Config.SERVICE_SMODES
|
||||
cmodes = self.Config.SERVICE_CMODES
|
||||
umodes = self.Config.SERVICE_UMODES
|
||||
host = self.Config.SERVICE_HOST
|
||||
service_name = self.Config.SERVICE_NAME
|
||||
try:
|
||||
nickname = self.Config.SERVICE_NICKNAME
|
||||
username = self.Config.SERVICE_USERNAME
|
||||
realname = self.Config.SERVICE_REALNAME
|
||||
chan = self.Config.SERVICE_CHANLOG
|
||||
info = self.Config.SERVICE_INFO
|
||||
smodes = self.Config.SERVICE_SMODES
|
||||
cmodes = self.Config.SERVICE_CMODES
|
||||
umodes = self.Config.SERVICE_UMODES
|
||||
host = self.Config.SERVICE_HOST
|
||||
service_name = self.Config.SERVICE_NAME
|
||||
|
||||
password = self.Config.SERVEUR_PASSWORD
|
||||
link = self.Config.SERVEUR_LINK
|
||||
sid = self.Config.SERVEUR_ID
|
||||
service_id = self.Config.SERVICE_ID
|
||||
password = self.Config.SERVEUR_PASSWORD
|
||||
link = self.Config.SERVEUR_LINK
|
||||
sid = self.Config.SERVEUR_ID
|
||||
service_id = self.Config.SERVICE_ID
|
||||
|
||||
version = self.Config.DEFENDER_VERSION
|
||||
unixtime = self.Base.get_unixtime()
|
||||
version = self.SysConfig.DEFENDER_VERSION
|
||||
unixtime = self.Base.get_unixtime()
|
||||
|
||||
# Envoyer un message d'identification
|
||||
writer.send(f":{sid} PASS :{password}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL NICKv2 VHP UMODE2 NICKIP SJOIN SJOIN2 SJ3 NOQUIT TKLEXT MLOCK SID MTAGS\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL EAUTH={link},,,{service_name}-v{version}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL SID={sid}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} SERVER {link} 1 :{info}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} {nickname} :Reserved for services\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} UID {nickname} 1 {unixtime} {username} {host} {service_id} * {smodes} * * * :{realname}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} SJOIN {unixtime} {chan} + :{service_id}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} MODE {chan} +{cmodes}\r\n".encode('utf-8'))
|
||||
writer.send(f":{service_id} SAMODE {chan} +{umodes} {nickname}\r\n".encode('utf-8'))
|
||||
# Envoyer un message d'identification
|
||||
writer.send(f":{sid} PASS :{password}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL NICKv2 VHP UMODE2 NICKIP SJOIN SJOIN2 SJ3 NOQUIT TKLEXT MLOCK SID MTAGS\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL EAUTH={link},,,{service_name}-v{version}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} PROTOCTL SID={sid}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} SERVER {link} 1 :{info}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} {nickname} :Reserved for services\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} UID {nickname} 1 {unixtime} {username} {host} {service_id} * {smodes} * * * :{realname}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} SJOIN {unixtime} {chan} + :{service_id}\r\n".encode('utf-8'))
|
||||
writer.send(f":{sid} MODE {chan} +{cmodes}\r\n".encode('utf-8'))
|
||||
writer.send(f":{service_id} SAMODE {chan} +{umodes} {nickname}\r\n".encode('utf-8'))
|
||||
|
||||
return None
|
||||
self.Base.logs.debug('Link information sent to the server')
|
||||
|
||||
return None
|
||||
except AttributeError as ae:
|
||||
self.Base.logs.critical(f'{ae}')
|
||||
|
||||
def send2socket(self, send_message:str) -> None:
|
||||
"""Envoit les commandes à envoyer au serveur.
|
||||
@@ -203,21 +214,22 @@ class Irc:
|
||||
with self.Base.lock:
|
||||
# print(f">{str(send_message)}")
|
||||
self.IrcSocket.send(f"{send_message}\r\n".encode(self.CHARSET[0]))
|
||||
self.Base.logs.debug(f'{send_message}')
|
||||
|
||||
except UnicodeDecodeError:
|
||||
self.debug('Write Decode impossible try iso-8859-1')
|
||||
self.Base.logs.error(f'Decode Error try iso-8859-1 - message: {send_message}')
|
||||
self.IrcSocket.send(f"{send_message}\r\n".encode(self.CHARSET[0],'replace'))
|
||||
except UnicodeEncodeError:
|
||||
self.debug('Write Encode impossible ... try iso-8859-1')
|
||||
self.Base.logs.error(f'Encode Error try iso-8859-1 - message: {send_message}')
|
||||
self.IrcSocket.send(f"{send_message}\r\n".encode(self.CHARSET[0],'replace'))
|
||||
except AssertionError as ae:
|
||||
self.debug(f"Assertion error : {ae}")
|
||||
self.Base.logs.warning(f'Assertion Error {ae} - message: {send_message}')
|
||||
except ssl.SSLEOFError as soe:
|
||||
self.debug(f"SSLEOFError send2socket: {soe} - {send_message}")
|
||||
self.Base.logs.error(f"SSLEOFError: {soe} - {send_message}")
|
||||
except ssl.SSLError as se:
|
||||
self.debug(f"SSLError send2socket: {se} - {send_message}")
|
||||
self.Base.logs.error(f"SSLError: {se} - {send_message}")
|
||||
except OSError as oe:
|
||||
self.debug(f"OSError send2socket: {oe} - {send_message}")
|
||||
self.Base.logs.error(f"OSError: {oe} - {send_message}")
|
||||
|
||||
def send_response(self, responses:list[bytes]) -> None:
|
||||
try:
|
||||
@@ -225,6 +237,7 @@ class Irc:
|
||||
for data in responses:
|
||||
response = data.decode(self.CHARSET[0]).split()
|
||||
self.cmd(response)
|
||||
|
||||
except UnicodeEncodeError:
|
||||
for data in responses:
|
||||
response = data.decode(self.CHARSET[1],'replace').split()
|
||||
@@ -234,7 +247,8 @@ class Irc:
|
||||
response = data.decode(self.CHARSET[1],'replace').split()
|
||||
self.cmd(response)
|
||||
except AssertionError as ae:
|
||||
self.debug(f"Assertion error : {ae}")
|
||||
self.Base.logs.error(f"Assertion error : {ae}")
|
||||
|
||||
##############################################
|
||||
# FIN CONNEXION IRC #
|
||||
##############################################
|
||||
@@ -284,7 +298,7 @@ class Irc:
|
||||
# 2. Executer la fonction
|
||||
try:
|
||||
if not class_name in self.loaded_classes:
|
||||
self.debug(f"La class [{class_name} n'existe pas !!]")
|
||||
self.Base.logs.error(f"La class [{class_name} n'existe pas !!]")
|
||||
return False
|
||||
|
||||
class_instance = self.loaded_classes[class_name]
|
||||
@@ -294,12 +308,12 @@ class Irc:
|
||||
|
||||
self.Base.running_timers.append(t)
|
||||
|
||||
self.debug(f"Timer ID : {str(t.ident)} | Running Threads : {len(threading.enumerate())}")
|
||||
self.Base.logs.debug(f"Timer ID : {str(t.ident)} | Running Threads : {len(threading.enumerate())}")
|
||||
|
||||
except AssertionError as ae:
|
||||
self.debug(f'Assertion Error -> {ae}')
|
||||
self.Base.logs.error(f'Assertion Error -> {ae}')
|
||||
except TypeError as te:
|
||||
self.debug(f"Type error -> {te}")
|
||||
self.Base.logs.error(f"Type error -> {te}")
|
||||
|
||||
def __create_tasks(self, obj: object, method_name: str, param:list) -> None:
|
||||
"""#### Ajouter les méthodes a éxecuter dans un dictionnaire
|
||||
@@ -318,7 +332,7 @@ class Irc:
|
||||
'param': param
|
||||
}
|
||||
|
||||
self.debug(f'Function to execute : {str(self.Base.periodic_func)}')
|
||||
self.Base.logs.debug(f'Function to execute : {str(self.Base.periodic_func)}')
|
||||
self.send_ping_to_sereur()
|
||||
return None
|
||||
|
||||
@@ -332,7 +346,6 @@ class Irc:
|
||||
return None
|
||||
|
||||
def load_module(self, fromuser:str, module_name:str, init:bool = False) -> bool:
|
||||
|
||||
try:
|
||||
# module_name : mod_voice
|
||||
module_name = module_name.lower()
|
||||
@@ -342,8 +355,8 @@ class Irc:
|
||||
|
||||
# Si le module est déja chargé
|
||||
if 'mods.' + module_name in sys.modules:
|
||||
self.debug("Module déja chargé ...")
|
||||
self.debug('module name = ' + module_name)
|
||||
self.Base.logs.info("Module déja chargé ...")
|
||||
self.Base.logs.info('module name = ' + module_name)
|
||||
if class_name in self.loaded_classes:
|
||||
# Si le module existe dans la variable globale retourne False
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Le module {module_name} est déja chargé ! si vous souhaiter le recharge tapez {self.Config.SERVICE_PREFIX}reload {module_name}")
|
||||
@@ -374,14 +387,14 @@ class Irc:
|
||||
self.Base.db_record_module(fromuser, module_name)
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} chargé")
|
||||
|
||||
self.debug(self.loaded_classes)
|
||||
self.Base.logs.info(self.loaded_classes)
|
||||
return True
|
||||
|
||||
except ModuleNotFoundError as moduleNotFound:
|
||||
self.debug(f"MODULE_NOT_FOUND: {moduleNotFound}")
|
||||
self.Base.logs.error(f"MODULE_NOT_FOUND: {moduleNotFound}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :[ {self.Config.CONFIG_COLOR['rouge']}MODULE_NOT_FOUND{self.Config.CONFIG_COLOR['noire']} ]: {moduleNotFound}")
|
||||
except Exception as e:
|
||||
self.debug(f"Something went wrong with a module you want to load : {e}")
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to load : {e}")
|
||||
|
||||
def insert_db_uid(self, uid:str, nickname:str, username:str, hostname:str, umodes:str, vhost:str, isWebirc: bool) -> None:
|
||||
|
||||
@@ -431,10 +444,10 @@ class Irc:
|
||||
if oldnickname in self.db_uid:
|
||||
del self.db_uid[oldnickname]
|
||||
else:
|
||||
self.debug(f"L'ancien nickname {oldnickname} n'existe pas dans UID_DB")
|
||||
self.Base.logs.debug(f"L'ancien nickname {oldnickname} n'existe pas dans UID_DB")
|
||||
response = False
|
||||
|
||||
self.debug(f"{oldnickname} changed to {newnickname}")
|
||||
self.Base.logs.debug(f"{oldnickname} changed to {newnickname}")
|
||||
|
||||
return None
|
||||
|
||||
@@ -519,7 +532,7 @@ class Irc:
|
||||
# Supprimer les doublons de la liste
|
||||
self.db_chan = list(set(self.db_chan))
|
||||
|
||||
self.debug(f"Le salon {channel} a été ajouté à la liste CHAN_DB")
|
||||
self.Base.logs.debug(f"Le salon {channel} a été ajouté à la liste CHAN_DB")
|
||||
|
||||
return response
|
||||
|
||||
@@ -530,13 +543,13 @@ class Irc:
|
||||
|
||||
if level > 4:
|
||||
response = "Impossible d'ajouter un niveau > 4"
|
||||
self.debug(response)
|
||||
self.Base.logs.warning(response)
|
||||
return response
|
||||
|
||||
# Verification si le user existe dans notre UID_DB
|
||||
if not nickname in self.db_uid:
|
||||
response = f"{nickname} n'est pas connecté, impossible de l'enregistrer pour le moment"
|
||||
self.debug(response)
|
||||
self.Base.logs.warning(response)
|
||||
return response
|
||||
|
||||
hostname = self.db_uid[nickname]['hostname']
|
||||
@@ -557,12 +570,12 @@ class Irc:
|
||||
''', mes_donnees)
|
||||
response = f"{nickname} ajouté en tant qu'administrateur de niveau {level}"
|
||||
self.send2socket(f':{self.Config.SERVICE_NICKNAME} NOTICE {nickname} : {response}')
|
||||
self.debug(response)
|
||||
self.Base.logs.info(response)
|
||||
return response
|
||||
else:
|
||||
response = f'{nickname} Existe déjà dans les users enregistrés'
|
||||
self.send2socket(f':{self.Config.SERVICE_NICKNAME} NOTICE {nickname} : {response}')
|
||||
self.debug(response)
|
||||
self.Base.logs.info(response)
|
||||
return response
|
||||
|
||||
def get_uid(self, uidornickname:str) -> Union[str, None]:
|
||||
@@ -636,6 +649,7 @@ class Irc:
|
||||
|
||||
def cmd(self, data:list) -> None:
|
||||
try:
|
||||
|
||||
cmd_to_send:list[str] = data.copy()
|
||||
cmd = data.copy()
|
||||
|
||||
@@ -643,9 +657,19 @@ class Irc:
|
||||
cmd_to_debug.pop(0)
|
||||
|
||||
if len(cmd) == 0 or len(cmd) == 1:
|
||||
self.Base.logs.warning(f'Size ({str(len(cmd))}) - {cmd}')
|
||||
return False
|
||||
|
||||
self.debug(cmd_to_debug)
|
||||
# self.debug(cmd_to_debug)
|
||||
if len(data) == 7:
|
||||
if data[2] == 'PRIVMSG' and data[4] == ':auth':
|
||||
data_copy = data.copy()
|
||||
data_copy[6] = '**********'
|
||||
self.Base.logs.debug(data_copy)
|
||||
else:
|
||||
self.Base.logs.debug(data)
|
||||
else:
|
||||
self.Base.logs.debug(data)
|
||||
|
||||
match cmd[0]:
|
||||
|
||||
@@ -687,8 +711,8 @@ class Irc:
|
||||
# self.Base.create_thread(self.abuseipdb_scan, (cmd[2], ))
|
||||
pass
|
||||
# Possibilité de déclancher les bans a ce niveau.
|
||||
except IndexError:
|
||||
self.debug(f'cmd reputation: index error')
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f'{ie}')
|
||||
|
||||
case '320':
|
||||
#:irc.deb.biz.st 320 PyDefender IRCParis07 :is in security-groups: known-users,webirc-users,tls-and-known-users,tls-users
|
||||
@@ -717,9 +741,20 @@ class Irc:
|
||||
print(f"# SSL VER : {self.SSL_VERSION} ")
|
||||
print(f"# NICKNAME : {self.Config.SERVICE_NICKNAME} ")
|
||||
print(f"# CHANNEL : {self.Config.SERVICE_CHANLOG} ")
|
||||
print(f"# VERSION : {self.Config.DEFENDER_VERSION} ")
|
||||
print(f"# VERSION : {self.SysConfig.DEFENDER_VERSION} ")
|
||||
print(f"################################################")
|
||||
|
||||
self.Base.logs.info(f"################### DEFENDER ###################")
|
||||
self.Base.logs.info(f"# SERVICE CONNECTE ")
|
||||
self.Base.logs.info(f"# SERVEUR : {self.Config.SERVEUR_IP} ")
|
||||
self.Base.logs.info(f"# PORT : {self.Config.SERVEUR_PORT} ")
|
||||
self.Base.logs.info(f"# SSL : {self.Config.SERVEUR_SSL} ")
|
||||
self.Base.logs.info(f"# SSL VER : {self.SSL_VERSION} ")
|
||||
self.Base.logs.info(f"# NICKNAME : {self.Config.SERVICE_NICKNAME} ")
|
||||
self.Base.logs.info(f"# CHANNEL : {self.Config.SERVICE_CHANLOG} ")
|
||||
self.Base.logs.info(f"# VERSION : {self.SysConfig.DEFENDER_VERSION} ")
|
||||
self.Base.logs.info(f"################################################")
|
||||
|
||||
# Initialisation terminé aprés le premier PING
|
||||
self.INIT = 0
|
||||
# self.send2socket(f':{self.Config.SERVICE_ID} PING :{hsid}')
|
||||
@@ -785,6 +820,15 @@ class Irc:
|
||||
cmd.pop(0)
|
||||
|
||||
get_uid_or_nickname = str(cmd[0].replace(':',''))
|
||||
if len(cmd) == 6:
|
||||
if cmd[1] == 'PRIVMSG' and cmd[3] == ':auth':
|
||||
cmd_copy = cmd.copy()
|
||||
cmd_copy[5] = '**********'
|
||||
self.Base.logs.debug(cmd_copy)
|
||||
else:
|
||||
self.Base.logs.info(cmd)
|
||||
else:
|
||||
self.Base.logs.info(f'{cmd}')
|
||||
# user_trigger = get_user.split('!')[0]
|
||||
user_trigger = self.get_nickname(get_uid_or_nickname)
|
||||
dnickname = self.Config.SERVICE_NICKNAME
|
||||
@@ -818,7 +862,7 @@ class Irc:
|
||||
|
||||
# Réponse a un CTCP VERSION
|
||||
if arg[0] == '\x01VERSION\x01':
|
||||
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01VERSION Service {self.Config.SERVICE_NICKNAME} V{self.Config.DEFENDER_VERSION}\x01')
|
||||
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01VERSION Service {self.Config.SERVICE_NICKNAME} V{self.SysConfig.DEFENDER_VERSION}\x01')
|
||||
return False
|
||||
|
||||
# Réponse a un TIME
|
||||
@@ -844,8 +888,8 @@ class Irc:
|
||||
|
||||
self._hcmds(user_trigger, arg)
|
||||
|
||||
except IndexError:
|
||||
self.debug(f'cmd --> PRIVMSG --> List index out of range')
|
||||
except IndexError as io:
|
||||
self.Base.logs.error(f'{io}')
|
||||
|
||||
case _:
|
||||
pass
|
||||
@@ -856,7 +900,7 @@ class Irc:
|
||||
classe_object.cmd(cmd_to_send)
|
||||
|
||||
except IndexError as ie:
|
||||
self.debug(f"IRC CMD -> IndexError : {ie} - {cmd} - length {str(len(cmd))}")
|
||||
self.Base.logs.error(f"{ie} / {cmd} / length {str(len(cmd))}")
|
||||
|
||||
def _hcmds(self, user: str, cmd:list) -> None:
|
||||
|
||||
@@ -888,8 +932,8 @@ class Irc:
|
||||
current_command = cmd[0]
|
||||
self.send2socket(f':{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR["rouge"]}{current_command}{self.Config.CONFIG_COLOR["noire"]} ] - Accès Refusé à {self.get_nickname(fromuser)}')
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Accès Refusé')
|
||||
except IndexError:
|
||||
self.debug(f'_hcmd notallowed : Index Error')
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f'{ie}')
|
||||
|
||||
case 'deauth':
|
||||
|
||||
@@ -914,6 +958,7 @@ class Irc:
|
||||
uid_user = self.get_uid(user_to_log)
|
||||
self.insert_db_admin(uid_user, user_from_db[1])
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR['verte']}{current_command}{self.Config.CONFIG_COLOR['noire']} ] - {self.get_nickname(fromuser)} est désormais connecté a {dnickname}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} NOTICE {fromuser} :Connexion a {dnickname} réussie!")
|
||||
else:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR['rouge']}{current_command}{self.Config.CONFIG_COLOR['noire']} ] - {self.get_nickname(fromuser)} a tapé un mauvais mot de pass")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} NOTICE {fromuser} :Mot de passe incorrecte")
|
||||
@@ -930,13 +975,13 @@ class Irc:
|
||||
|
||||
response = self.create_defender_user(newnickname, newlevel, password)
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : {response}')
|
||||
self.debug(response)
|
||||
self.Base.logs.info(response)
|
||||
|
||||
except IndexError as ie:
|
||||
self.debug(f'_hcmd addaccess: {ie}')
|
||||
self.Base.logs.error(f'_hcmd addaccess: {ie}')
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} addaccess [nickname] [level] [password]')
|
||||
except TypeError as te:
|
||||
self.debug(f'_hcmd addaccess: out of index : {te}')
|
||||
self.Base.logs.error(f'_hcmd addaccess: out of index : {te}')
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} addaccess [nickname] [level] [password]')
|
||||
|
||||
case 'editaccess':
|
||||
@@ -984,9 +1029,9 @@ class Irc:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} : Impossible de modifier l'utilisateur {str(user_new_level)}")
|
||||
|
||||
except TypeError as te:
|
||||
self.debug(f"Type error : {te}")
|
||||
self.Base.logs.error(f"Type error : {te}")
|
||||
except ValueError as ve:
|
||||
self.debug(f"Value Error : {ve}")
|
||||
self.Base.logs.error(f"Value Error : {ve}")
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : .editaccess [USER] [NEWPASSWORD] [NEWLEVEL]')
|
||||
|
||||
case 'delaccess':
|
||||
@@ -996,9 +1041,9 @@ class Irc:
|
||||
|
||||
if user_to_del != user_confirmation:
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Les user ne sont pas les mêmes, tu dois confirmer le user que tu veux supprimer')
|
||||
self.Base.logs.warning(f':{dnickname} NOTICE {fromuser} : Les user ne sont pas les mêmes, tu dois confirmer le user que tu veux supprimer')
|
||||
return None
|
||||
|
||||
print(len(cmd))
|
||||
if len(cmd) < 3:
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : .delaccess [USER] [CONFIRMUSER]')
|
||||
return None
|
||||
@@ -1017,6 +1062,7 @@ class Irc:
|
||||
level_user_to_del = info_user[1]
|
||||
if current_user_level <= level_user_to_del:
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : You are not allowed to delete this access')
|
||||
self.Base.logs.warning(f':{dnickname} NOTICE {fromuser} : You are not allowed to delete this access')
|
||||
return None
|
||||
|
||||
data_to_delete = {'user': user_to_del}
|
||||
@@ -1026,6 +1072,7 @@ class Irc:
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : User {user_to_del} has been deleted !')
|
||||
else:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} : Impossible de supprimer l'utilisateur.")
|
||||
self.Base.logs.warning(f":{dnickname} NOTICE {fromuser} : Impossible de supprimer l'utilisateur.")
|
||||
|
||||
case 'help':
|
||||
|
||||
@@ -1083,7 +1130,7 @@ class Irc:
|
||||
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} supprimé")
|
||||
except:
|
||||
self.debug(f"Something went wrong with a module you want to load")
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to load")
|
||||
|
||||
case 'reload':
|
||||
# reload mod_dktmb
|
||||
@@ -1093,7 +1140,7 @@ class Irc:
|
||||
|
||||
if 'mods.' + module_name in sys.modules:
|
||||
self.loaded_classes[class_name].unload()
|
||||
self.debug('Module Already Loaded ... reload the module ...')
|
||||
self.Base.logs.info('Module Already Loaded ... reload the module ...')
|
||||
the_module = sys.modules['mods.' + module_name]
|
||||
importlib.reload(the_module)
|
||||
|
||||
@@ -1117,7 +1164,7 @@ class Irc:
|
||||
else:
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} n'est pas chargé !")
|
||||
except:
|
||||
self.debug(f"Something went wrong with a module you want to reload")
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to reload")
|
||||
|
||||
case 'quit':
|
||||
try:
|
||||
@@ -1132,12 +1179,12 @@ class Irc:
|
||||
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Arrêt du service {dnickname}')
|
||||
self.send2socket(f':{self.Config.SERVEUR_LINK} SQUIT {self.Config.SERVEUR_LINK} :{final_reason}')
|
||||
self.debug(f'Arrêt du server {dnickname}')
|
||||
self.Base.logs.info(f'Arrêt du server {dnickname}')
|
||||
self.RESTART = 0
|
||||
self.signal = False
|
||||
|
||||
except IndexError:
|
||||
self.debug('_hcmd die: out of index')
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f'{ie}')
|
||||
|
||||
self.send2socket(f"QUIT Good bye")
|
||||
|
||||
@@ -1155,14 +1202,14 @@ class Irc:
|
||||
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : Redémarrage du service {dnickname}')
|
||||
self.send2socket(f':{self.Config.SERVEUR_LINK} SQUIT {self.Config.SERVEUR_LINK} :{final_reason}')
|
||||
self.debug(f'Redémarrage du server {dnickname}')
|
||||
self.Base.logs.info(f'Redémarrage du server {dnickname}')
|
||||
self.loaded_classes.clear()
|
||||
self.RESTART = 1 # Set restart status to 1 saying that the service will restart
|
||||
self.INIT = 1 # set init to 1 saying that the service will be re initiated
|
||||
|
||||
case 'show_modules':
|
||||
|
||||
self.debug(self.loaded_classes)
|
||||
self.Base.logs.debug(self.loaded_classes)
|
||||
|
||||
results = self.Base.db_execute_query(f'SELECT module FROM {self.Base.DB_SCHEMA["modules"]}')
|
||||
results = results.fetchall()
|
||||
@@ -1173,13 +1220,11 @@ class Irc:
|
||||
|
||||
for r in results:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :Le module {r[0]} chargé")
|
||||
self.debug(r[0])
|
||||
|
||||
case 'show_timers':
|
||||
|
||||
if self.Base.running_timers:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :{self.Base.running_timers}")
|
||||
self.debug(self.Base.running_timers)
|
||||
else:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :Aucun timers en cours d'execution")
|
||||
|
||||
@@ -1196,7 +1241,7 @@ class Irc:
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : {uptime}')
|
||||
|
||||
case 'copyright':
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : # Defender V.{self.Config.DEFENDER_VERSION} Developped by adator® and dktmb® #')
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : # Defender V.{self.SysConfig.DEFENDER_VERSION} Developped by adator® and dktmb® #')
|
||||
|
||||
case 'sentinel':
|
||||
# .sentinel on
|
||||
|
||||
22
core/sys_configuration.py
Normal file
22
core/sys_configuration.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import os, json
|
||||
|
||||
####################################################################################################
|
||||
# DO NOT TOUCH THIS FILE #
|
||||
####################################################################################################
|
||||
|
||||
class SysConfig:
|
||||
|
||||
DEFENDER_VERSION = '4.0.0' # MAJOR.MINOR.BATCH
|
||||
LATEST_DEFENDER_VERSION = '0.0.0' # Latest Version of Defender in git
|
||||
DEFENDER_DB_PATH = 'db' + os.sep # Séparateur en fonction de l'OS
|
||||
DEFENDER_DB_NAME = 'defender' # Le nom de la base de données principale
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
version_filename = f'.{os.sep}version.json'
|
||||
with open(version_filename, 'r') as version_data:
|
||||
self.global_configuration:dict[str, str] = json.load(version_data)
|
||||
|
||||
self.DEFENDER_VERSION = self.global_configuration["version"]
|
||||
|
||||
return None
|
||||
Reference in New Issue
Block a user