-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinternets.py
More file actions
1698 lines (1465 loc) · 69.9 KB
/
internets.py
File metadata and controls
1698 lines (1465 loc) · 69.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Internets — async modular IRC bot.
Architecture: asyncio event loop for connection, dispatch, and background
tasks. Module command handlers are coroutines. Blocking I/O (HTTP via
requests, disk, CPU-heavy work like password hashing) runs via
asyncio.to_thread() inside the handler.
Core commands: .help .modules .auth .deauth
.load .unload .reload .reloadall .restart .rehash
.version
Modules live in modules/. Each exposes setup(bot) -> BotModule.
See modules/base.py for the interface.
"""
from __future__ import annotations
__version__ = "1.4.0"
import asyncio
import ssl
import re
import sys
import os
import time
import base64
import signal
import threading
import logging
import logging.handlers
import configparser
import importlib
import importlib.util
from pathlib import Path
from typing import Any, Optional
from store import Store, RateLimiter
from sender import Sender
from hashpw import verify_password
from protocol import (
strip_tags,
parse_isupport_chanmodes,
parse_isupport_prefix,
parse_mode_changes,
parse_names_entry,
sasl_plain_payload,
)
cfg = configparser.ConfigParser(inline_comment_prefixes=(";", "#"))
_CONFIG_PATH = str(Path("config.ini").resolve())
cfg.read(_CONFIG_PATH)
SERVER = cfg["irc"]["server"]
PORT = int(cfg["irc"]["port"])
NICKNAME = cfg["irc"]["nickname"]
REALNAME = cfg["irc"]["realname"]
NS_PW = cfg["irc"].get("nickserv_password", "").strip()
SERVER_PW = cfg["irc"].get("server_password", "").strip()
OPER_N = cfg["irc"].get("oper_name", "").strip()
OPER_PW = cfg["irc"].get("oper_password", "").strip()
USER_MODES = cfg["irc"].get("user_modes", "").strip()
OPER_MODES = cfg["irc"].get("oper_modes", "").strip()
OPER_SNOMASK = cfg["irc"].get("oper_snomask", "").strip()
CMD_PREFIX = cfg["bot"]["command_prefix"]
API_CD = int(cfg["bot"]["api_cooldown"])
FLOOD_CD = int(cfg["bot"].get("flood_cooldown", "3"))
MODULES_DIR = Path(cfg["bot"].get("modules_dir", "modules"))
AUTO_LOAD = [m.strip() for m in cfg["bot"].get("autoload", "").split(",") if m.strip()]
# All optional — the bot works fine if the server supports none of these.
DESIRED_CAPS: set[str] = {
"multi-prefix", "away-notify", "account-notify", "chghost",
"extended-join", "server-time", "message-tags", "sasl",
}
class ChannelSet:
"""Thread-safe set of active channel names (lowercased).
Thread safety is required because module command handlers run in
asyncio.to_thread (thread pool), but state mutations happen in
the event loop thread.
"""
def __init__(self) -> None:
self._channels: set[str] = set()
self._lock = threading.Lock()
def add(self, ch: str) -> None:
"""Add a channel (case-folded) to the set."""
with self._lock:
self._channels.add(ch.lower())
def discard(self, ch: str) -> None:
"""Remove a channel from the set. No-op if absent."""
with self._lock:
self._channels.discard(ch.lower())
def snapshot(self) -> set[str]:
"""Return a copy of the channel set (safe for iteration)."""
with self._lock:
return set(self._channels)
def __contains__(self, ch: str) -> bool:
with self._lock:
return ch.lower() in self._channels
def __iter__(self):
return iter(self.snapshot())
def __bool__(self) -> bool:
with self._lock:
return bool(self._channels)
def __len__(self) -> int:
with self._lock:
return len(self._channels)
def _backoff(attempt: int, base: float = 15.0, cap: float = 300.0) -> float:
"""Exponential backoff: 15, 30, 60, 120, 240, 300 (capped at 5 min)."""
return min(base * (2 ** attempt), cap)
# ── CLI ──────────────────────────────────────────────────────────────
import argparse
_cli = argparse.ArgumentParser(
description="Internets — async modular IRC bot",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""\
debug examples:
%(prog)s --debug global debug (all subsystems)
%(prog)s --debug weather store debug only weather + store
%(prog)s --loglevel WARNING suppress INFO from console + main log
%(prog)s --debug-file debug.log capture all DEBUG to separate file
%(prog)s --no-console disable stdin command loop (for daemons)
interactive console (type 'help' at the > prompt while running):
debug, loglevel, status, shutdown""")
_cli.add_argument("--version", action="version", version=f"Internets {__version__}")
_cli.add_argument("--debug", nargs="*", metavar="SUBSYSTEM", default=None,
help="enable debug output. No args = global debug. "
"With args = per-subsystem (e.g. --debug weather store)")
_cli.add_argument("--loglevel", metavar="LEVEL", default=None,
help="base log level: DEBUG, INFO, WARNING, ERROR")
_cli.add_argument("--debug-file", metavar="PATH", default=None,
help="write all DEBUG output to this file (overrides config)")
_cli.add_argument("--no-console", action="store_true", default=False,
help="disable interactive stdin console (for daemonized use)")
_args = _cli.parse_args()
# CLI overrides applied before logging setup.
LOG_LEVEL = (_args.loglevel or cfg["logging"]["level"]).upper()
LOG_FILE = cfg["logging"]["log_file"]
LOG_MAX = int(cfg["logging"].get("max_bytes", "5242880")) # 5 MB default
LOG_BACKUPS = int(cfg["logging"].get("backup_count", "3"))
LOG_DEBUG = _args.debug_file or cfg["logging"].get("debug_file", "").strip()
LOG_FMT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
class _SafeFormatter(logging.Formatter):
"""Formatter that strips CR/LF/NUL from user-controlled log data.
Sanitizes record.msg and record.args to prevent log injection via
format-string interpolation (e.g. ``log.info("cmd: %s", attacker_input)``).
Works on a *copy* of the record so other handlers see the original.
Exception tracebacks (which naturally contain newlines) are preserved.
"""
_CONTROL_RE = re.compile(r"[\r\n\x00]")
def _clean(self, val: Any) -> Any:
return self._CONTROL_RE.sub("", val) if isinstance(val, str) else val
def format(self, record: logging.LogRecord) -> str:
safe = logging.makeLogRecord(record.__dict__)
safe.msg = self._clean(str(safe.msg))
if safe.args:
if isinstance(safe.args, dict):
safe.args = {k: self._clean(v) for k, v in safe.args.items()}
elif isinstance(safe.args, tuple):
safe.args = tuple(self._clean(a) for a in safe.args)
return super().format(safe)
class _DebugFilter(logging.Filter):
"""
Attached to main-log and console handlers. Passes a record if:
- record level >= self.base_level (normal output), OR
- global_debug is True (.debug on), OR
- record's logger name is in the subsystem debug set (.debug weather)
"""
def __init__(self, base_level: int = logging.INFO) -> None:
super().__init__()
self.base_level: int = base_level
self.global_debug: bool = False
self._subsystems: set[str] = set()
self._lock = threading.Lock()
def filter(self, record: logging.LogRecord) -> bool:
"""Allow record if it meets the base level, global debug, or subsystem debug."""
if record.levelno >= self.base_level:
return True
if self.global_debug:
return True
with self._lock:
name = record.name
for sub in self._subsystems:
if name == sub or name.startswith(sub + "."):
return True
return False
def set_base_level(self, level: int) -> None:
"""Set the minimum log level for non-debug output."""
self.base_level = level
def add_subsystem(self, name: str) -> None:
"""Enable debug logging for a specific subsystem (e.g. ``weather``)."""
with self._lock:
self._subsystems.add(name)
def remove_subsystem(self, name: str) -> None:
"""Disable debug logging for a specific subsystem."""
with self._lock:
self._subsystems.discard(name)
def clear_subsystems(self) -> None:
"""Disable all per-subsystem debug logging."""
with self._lock:
self._subsystems.clear()
def active_subsystems(self) -> set[str]:
"""Return the set of subsystems with debug enabled."""
with self._lock:
return set(self._subsystems)
def _setup_logging() -> _DebugFilter:
"""Configure the internets logger with rotating file + console + optional debug file."""
root = logging.getLogger("internets")
root.setLevel(logging.DEBUG)
root.handlers.clear()
fmt = _SafeFormatter(LOG_FMT)
filt = _DebugFilter(getattr(logging, LOG_LEVEL, logging.INFO))
fh = logging.handlers.RotatingFileHandler(
LOG_FILE, maxBytes=LOG_MAX, backupCount=LOG_BACKUPS, encoding="utf-8")
fh.setLevel(logging.DEBUG)
fh.setFormatter(fmt)
fh.addFilter(filt)
root.addHandler(fh)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(fmt)
ch.addFilter(filt)
root.addHandler(ch)
if LOG_DEBUG:
dh = logging.handlers.RotatingFileHandler(
LOG_DEBUG, maxBytes=LOG_MAX, backupCount=LOG_BACKUPS, encoding="utf-8")
dh.setLevel(logging.DEBUG)
dh.setFormatter(fmt)
dh._debug_file = True
root.addHandler(dh)
return filt
_log_filter = _setup_logging()
log = logging.getLogger("internets")
log.info(f"Internets v{__version__} starting")
if _args.debug is not None:
if len(_args.debug) == 0:
_log_filter.global_debug = True
log.info("CLI: global debug enabled")
else:
for sub in _args.debug:
full = f"internets.{sub}" if not sub.startswith("internets") else sub
logging.getLogger(full).setLevel(logging.DEBUG)
_log_filter.add_subsystem(full)
log.info(f"CLI: debug enabled for {full}")
def _get_hash() -> str:
cfg.read(_CONFIG_PATH)
return cfg["admin"].get("password_hash", "").strip()
def _validate_hash() -> None:
h = _get_hash()
if not h:
log.warning("No password_hash in config.ini — auth disabled. Run hashpw.py.")
return
prefix = h.split("$")[0] if "$" in h else ""
if prefix not in ("scrypt", "bcrypt", "argon2"):
log.critical(f"Invalid password_hash prefix '{prefix}' — run hashpw.py and restart.")
sys.exit(1)
log.info(f"Admin password hash loaded ({prefix}).")
_validate_hash()
# BUG-029: Warn if config file is world-readable (contains credentials).
# Only meaningful on POSIX — NTFS does not use Unix permission bits.
if os.name == "posix":
try:
_cfg_stat = os.stat(_CONFIG_PATH)
if _cfg_stat.st_mode & 0o004:
log.warning("config.ini is world-readable — consider: chmod 640 config.ini")
except OSError:
pass
_MODE_VALID = re.compile(r"^[a-zA-Z+\- ]*$")
for _name, _val in [("user_modes", USER_MODES), ("oper_modes", OPER_MODES),
("oper_snomask", OPER_SNOMASK)]:
if _val and not _MODE_VALID.match(_val):
log.critical(f"Invalid {_name} = {_val!r} in config.ini — "
f"only letters, +, -, and spaces allowed.")
sys.exit(1)
if _val:
log.info(f"Config {_name} = {_val}")
# ═════════════════════════════════════════════════════════════════════
# IRCBot
# ═════════════════════════════════════════════════════════════════════
class IRCBot:
"""Async IRC bot core — event loop, state machine, command dispatch.
Owns the asyncio event loop, IRC connection, module registry, and
admin authentication. Module command handlers run as async tasks.
Blocking I/O is offloaded via ``asyncio.to_thread()``.
Public API for modules: ``privmsg``, ``notice``, ``reply``, ``preply``,
``send``, ``is_admin``, ``is_chanop``, ``flood_limited``, ``rate_limited``,
``loc_get``, ``loc_set``, ``loc_del``, ``channel_users``, ``active_channels``,
``cfg``.
"""
_MAX_BODY = 400
_MAX_TASKS = 50 # BUG-030: cap concurrent command tasks
_MAX_ARG_LEN = 400 # BUG-031: cap command argument length
_MAX_LINE_LEN = 450 # BUG-026: max outgoing line body (sender enforces)
_CORE: dict[str, str] = {
"help": "cmd_help",
"modules": "cmd_modules",
"version": "cmd_version",
"auth": "cmd_auth",
"deauth": "cmd_deauth",
"load": "cmd_load",
"unload": "cmd_unload",
"reload": "cmd_reload",
"reloadall": "cmd_reloadall",
"restart": "cmd_restart",
"rehash": "cmd_rehash",
"mode": "cmd_mode",
"snomask": "cmd_snomask",
"shutdown": "cmd_shutdown",
"die": "cmd_shutdown",
"loglevel": "cmd_loglevel",
"debug": "cmd_debug",
}
def __init__(self) -> None:
self.cfg = cfg
self.active_channels: ChannelSet = ChannelSet()
self._modules: dict[str, Any] = {}
self._commands: dict[str, tuple[str, str]] = {}
self._mod_lock = threading.Lock()
self._authed: set[str] = set()
self._auth_fails: dict[str, tuple[int, float]] = {}
self._AUTH_MAX_FAILS: int = 5
self._AUTH_LOCKOUT: int = 300
self._nick: str = NICKNAME
self._chanops: dict[str, set[str]] = {}
self._ns_identified = False
self._sasl_in_progress = False
self._cap_busy = False
self._caps: set[str] = set()
self._services_nick = cfg["bot"].get("services_nick", "ChanServ").strip()
self._chanmode_types: dict[str, str] = {
"b": "A", "e": "A", "I": "A",
"k": "B",
"l": "C",
"i": "D", "m": "D", "n": "D", "p": "D", "s": "D", "t": "D",
}
self._prefix_modes: set[str] = set("qaohv")
self._store = Store(
cfg["bot"].get("locations_file", "locations.json"),
cfg["bot"].get("channels_file", "channels.json"),
cfg["bot"].get("users_file", "users.json"),
user_max_age_days=int(cfg["bot"].get("user_max_age_days", "90")),
)
self._rate = RateLimiter(FLOOD_CD, API_CD)
# Set once run() starts.
self._loop: asyncio.AbstractEventLoop | None = None
self._sender: Sender | None = None
self._reader: asyncio.StreamReader | None = None
self._writer: asyncio.StreamWriter | None = None
self._stop: asyncio.Event | None = None
self._quit_msg = "QUIT :Shutting down"
self._restart_flag = False
self._tasks: list[asyncio.Task] = []
self._last_invite_time: float = 0.0
# ── Outbound messaging (sync, thread-safe via Sender) ────────────
def send(self, msg: str, priority: int = 1) -> None:
"""Enqueue a raw IRC line for sending. Priority 0 bypasses rate limit."""
if self._sender:
self._sender.enqueue(msg, priority)
def privmsg(self, target: str, msg: str) -> None:
"""Send a PRIVMSG to *target* (channel or nick). Long messages are split."""
if " " in target or not target:
log.warning(f"privmsg: invalid target {target!r}")
return
for chunk in self._split_msg(msg):
self.send(f"PRIVMSG {target} :{chunk}")
def notice(self, target: str, msg: str) -> None:
"""Send a NOTICE to *target* (channel or nick). Long messages are split."""
if " " in target or not target:
log.warning(f"notice: invalid target {target!r}")
return
for chunk in self._split_msg(msg):
self.send(f"NOTICE {target} :{chunk}")
def reply(self, nick: str, reply_to: str, msg: str,
privileged: bool = False) -> None:
"""Route a response: PRIVMSG to channel, NOTICE to nick if privileged."""
if not reply_to.startswith(("#", "&", "+", "!")):
self.privmsg(nick, msg)
elif privileged:
self.notice(nick, msg)
else:
self.privmsg(reply_to, msg)
def preply(self, nick: str, reply_to: str, msg: str) -> None:
"""Privileged reply — always NOTICE to nick, never to channel."""
self.reply(nick, reply_to, msg, privileged=True)
def _split_msg(self, msg: str) -> list[str]:
chunks: list[str] = []
enc = msg.encode("utf-8", errors="replace")
while enc:
chunk = enc[:self._MAX_BODY]
if len(enc) > self._MAX_BODY:
while chunk and (chunk[-1] & 0xC0) == 0x80:
chunk = chunk[:-1]
if not chunk:
chunk = enc[:self._MAX_BODY]
chunks.append(chunk.decode("utf-8", errors="replace"))
enc = enc[len(chunk):]
return chunks
# ── Accessors (sync, called from module threads) ─────────────────
def is_admin(self, nick: str) -> bool:
"""Return True if *nick* has an active admin session."""
return nick.lower() in self._authed
def is_chanop(self, channel: str, nick: str) -> bool:
"""Return True if *nick* holds +o/+a/+q in *channel*."""
return nick.lower() in self._chanops.get(channel.lower(), set())
def flood_limited(self, nick: str) -> bool:
"""Return True if *nick* is sending commands too fast. Admins bypass."""
return self._rate.flood_check(nick, self.is_admin(nick))
def rate_limited(self, nick: str) -> bool:
"""Return True if *nick* has hit the API cooldown."""
return self._rate.api_check(nick)
def loc_get(self, nick: str) -> str | None:
"""Return saved location string for *nick*, or None."""
return self._store.loc_get(nick)
def loc_set(self, nick: str, raw: str) -> None:
"""Save a location string for *nick*."""
self._store.loc_set(nick, raw)
def loc_del(self, nick: str) -> bool:
"""Delete saved location for *nick*. Returns False if none existed."""
return self._store.loc_del(nick)
def channel_users(self, ch: str) -> dict[str, Any]:
"""Return tracked user data for *ch* as ``{nick_lower: {nick, hostmask, ...}}``."""
return self._store.channel_users(ch)
# ── Module management ────────────────────────────────────────────
def load_module(self, name: str) -> tuple[bool, str]:
"""Load a module by name from the modules directory.
Returns ``(success, message)`` suitable for display to the user.
Validates the module name, checks for path traversal, prevents
command conflicts, and runs ``on_load()``.
"""
with self._mod_lock:
if not re.match(r"^[a-z][a-z0-9_]*$", name):
return False, f"Invalid module name '{name}' — lowercase alphanumeric and _ only."
if name in self._modules:
return False, f"'{name}' already loaded."
path = MODULES_DIR / f"{name}.py"
if not path.exists():
return False, f"'{path}' not found."
real = path.resolve()
mod_root = MODULES_DIR.resolve()
try:
real.relative_to(mod_root)
except ValueError:
log.warning(f"Module {name!r} resolves outside modules dir: {real}")
return False, f"'{name}' blocked — path escapes modules directory."
try:
spec = importlib.util.spec_from_file_location(f"modules.{name}", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if not hasattr(mod, "setup"):
return False, f"'{name}' has no setup()."
inst = mod.setup(self)
dupes = [c for c in inst.COMMANDS if c in self._commands and self._commands[c][0] != name]
if dupes:
return False, f"'{name}' conflicts on: {', '.join(dupes)}"
inst.on_load()
self._modules[name] = inst
for cmd, method in inst.COMMANDS.items():
self._commands[cmd] = (name, method)
log.info(f"Loaded {name} ({list(inst.COMMANDS)})")
return True, f"'{name}' loaded ({len(inst.COMMANDS)} commands)."
except Exception as e:
log.error(f"Load '{name}': {e}")
return False, f"Error loading '{name}' — see log for details."
def unload_module(self, name: str) -> tuple[bool, str]:
"""Unload a module by name. Calls ``on_unload()`` and removes commands."""
with self._mod_lock:
if name not in self._modules:
return False, f"'{name}' not loaded."
try:
self._modules[name].on_unload()
for cmd in [c for c, v in self._commands.items() if v[0] == name]:
del self._commands[cmd]
del self._modules[name]
log.info(f"Unloaded {name}")
return True, f"'{name}' unloaded."
except Exception as e:
log.error(f"Unload '{name}': {e}")
return False, f"Error unloading '{name}' — see log for details."
def reload_module(self, name: str) -> tuple[bool, str]:
"""Unload then reload a module. Returns ``(success, message)``."""
ok, msg = self.unload_module(name)
return (False, msg) if not ok else self.load_module(name)
def autoload_modules(self) -> None:
"""Load all modules listed in the ``autoload`` config setting."""
for name in AUTO_LOAD:
ok, msg = self.load_module(name)
(log.info if ok else log.warning)(msg)
# ── Admin / core commands (async) ──────────────────────────────────
def _require_admin(self, nick: str, reply_to: str) -> bool:
if not self.is_admin(nick):
self.preply(nick, reply_to, f"{nick}: auth first — /MSG {self._nick} AUTH <pw>")
return False
return True
async def cmd_auth(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Authenticate as bot admin. PM only. Brute-force lockout after 5 failures."""
h = _get_hash()
if not h:
self.preply(nick, reply_to, f"{nick}: no password_hash configured — run hashpw.py")
return
if not arg:
self.preply(nick, reply_to, f"{nick}: /MSG {self._nick} AUTH <password>")
return
if len(arg) > 128:
self.preply(nick, reply_to, f"{nick}: password too long.")
return
k = nick.lower()
now = time.time()
if len(self._auth_fails) > 50:
self._auth_fails = {
n: (f, t) for n, (f, t) in self._auth_fails.items()
if now - t < self._AUTH_LOCKOUT
}
fails, last_t = self._auth_fails.get(k, (0, 0))
if now - last_t > self._AUTH_LOCKOUT:
fails = 0
if fails >= self._AUTH_MAX_FAILS:
remaining = int(self._AUTH_LOCKOUT - (now - last_t))
self.preply(nick, reply_to,
f"{nick}: too many failed attempts — try again in {remaining}s")
log.warning(f"Auth lockout: {nick} ({fails} failures)")
return
try:
ok = await asyncio.to_thread(verify_password, arg.strip(), h)
except ValueError as e:
log.error(f"Auth config error for {nick}: {e}")
self.preply(nick, reply_to, f"{nick}: config error — see log for details.")
return
if ok:
self._auth_fails.pop(k, None)
self._authed.add(nick.lower())
self.preply(nick, reply_to, f"{nick}: authenticated.")
log.info(f"Auth granted: {nick}")
else:
self._auth_fails[k] = (fails + 1, now)
self.preply(nick, reply_to, f"{nick}: wrong password.")
log.warning(f"Failed auth: {nick} ({fails + 1}/{self._AUTH_MAX_FAILS})")
async def cmd_deauth(self, nick: str, reply_to: str, arg: str | None) -> None:
"""End the current admin session."""
if nick.lower() in self._authed:
self._authed.discard(nick.lower())
self.preply(nick, reply_to, f"{nick}: session ended.")
else:
self.preply(nick, reply_to, f"{nick}: not authenticated.")
async def cmd_help(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Display available commands. Admin commands visible only when authed."""
p = CMD_PREFIX
lines = [
f"── {self._nick} v{__version__} ──────────────────────────────────────────",
f" {p}help {p}modules {p}version {p}auth <pw>",
]
if self.is_admin(nick):
lines += [
f" {p}deauth {p}load/unload/reload <mod> {p}reloadall",
f" {p}restart {p}rehash {p}mode {p}snomask [admin]",
f" {p}shutdown [reason] / {p}die [reason] [admin]",
f" {p}loglevel [LEVEL | <logger> LEVEL] [admin]",
f" {p}debug [on|off|<subsystem> [off]] [admin]",
]
lines.append("────────────────────────────────────────────────────────────")
with self._mod_lock:
module_items = list(self._modules.items())
for name, inst in module_items:
hl = inst.help_lines(p)
if hl:
lines.append(f" [{name}]")
lines.extend(hl)
lines.append(f" In PM the '{p}' prefix is optional.")
for line in lines:
self.preply(nick, reply_to, line)
async def cmd_version(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Display bot version and repository URL."""
self.preply(nick, reply_to,
f"Internets {__version__} — async modular IRC bot "
f"https://github.com/brandontroidl/Internets")
async def cmd_modules(self, nick: str, reply_to: str, arg: str | None) -> None:
"""List loaded and available modules."""
with self._mod_lock:
loaded = list(self._modules)
self.preply(nick, reply_to,
f"Loaded: {', '.join(loaded)}" if loaded else "No modules loaded.")
avail = sorted(
p.stem for p in MODULES_DIR.glob("*.py")
if p.stem not in ("__init__", "base", "geocode", "units")
and p.stem not in loaded
)
if avail:
self.preply(nick, reply_to, f"Available: {', '.join(avail)}")
async def cmd_load(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Load a module by name. Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg:
self.preply(nick, reply_to, f"usage: {CMD_PREFIX}load <module>"); return
_, msg = self.load_module(arg.strip().lower())
self.preply(nick, reply_to, msg)
async def cmd_unload(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Unload a module by name. Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg:
self.preply(nick, reply_to, f"usage: {CMD_PREFIX}unload <module>"); return
_, msg = self.unload_module(arg.strip().lower())
self.preply(nick, reply_to, msg)
async def cmd_reload(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Reload a module (unload + load). Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg:
self.preply(nick, reply_to, f"usage: {CMD_PREFIX}reload <module>"); return
_, msg = self.reload_module(arg.strip().lower())
self.preply(nick, reply_to, msg)
async def cmd_reloadall(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Reload all currently loaded modules. Admin only."""
if not self._require_admin(nick, reply_to): return
with self._mod_lock:
names = list(self._modules)
if not names:
self.preply(nick, reply_to, "No modules loaded."); return
self.preply(nick, reply_to, f"Reloading: {', '.join(names)}")
ok, fail = [], []
for n in names:
(ok if self.reload_module(n)[0] else fail).append(n)
parts = ([f"OK: {', '.join(ok)}"] if ok else []) + \
([f"FAILED: {', '.join(fail)}"] if fail else [])
self.preply(nick, reply_to, " | ".join(parts))
async def cmd_restart(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Restart the bot process. Admin only."""
if not self._require_admin(nick, reply_to): return
self.preply(nick, reply_to, "Restarting ...")
log.info(f"Restart by {nick}")
self._restart_flag = True
self.request_shutdown("Restarting ...")
async def cmd_rehash(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Reload config.ini and clear admin sessions. Admin only."""
if not self._require_admin(nick, reply_to): return
try:
cfg.read(_CONFIG_PATH)
except Exception as e:
log.error(f"Rehash config read failed: {e}")
self.preply(nick, reply_to, f"{nick}: failed to read config — see log for details.")
return
new_level = cfg["logging"].get("level", "INFO").upper()
lvl = getattr(logging, new_level, None)
if lvl:
_log_filter.set_base_level(lvl)
_log_filter.global_debug = False
_log_filter.clear_subsystems()
self.preply(nick, reply_to, f"Log level: {new_level}")
h = _get_hash()
if not h:
self.preply(nick, reply_to, "Config reloaded — no password_hash set.")
else:
prefix = h.split("$")[0] if "$" in h else ""
if prefix not in ("scrypt", "bcrypt", "argon2"):
self.preply(nick, reply_to, f"Bad hash prefix '{prefix}' — run hashpw.py.")
return
self.preply(nick, reply_to, f"Config reloaded — {prefix} hash active.")
n = len(self._authed)
self._authed.clear()
if n:
self.preply(nick, reply_to, f"Cleared {n} admin session(s) — re-authenticate.")
log.info(f"Rehash by {nick}")
async def cmd_mode(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Set bot user modes (e.g. +ix). Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg:
self.preply(nick, reply_to, f"usage: {CMD_PREFIX}mode <+/-modes>"); return
mode_str = arg.strip()
if not re.match(r"^[a-zA-Z+\- ]+$", mode_str):
self.preply(nick, reply_to, f"{nick}: invalid mode string."); return
self.send(f"MODE {self._nick} {mode_str}")
self.preply(nick, reply_to, f"MODE {self._nick} {mode_str}")
log.info(f"Mode set by {nick}: {mode_str}")
async def cmd_snomask(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Set server notice mask (e.g. +cCkK). Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg:
self.preply(nick, reply_to, f"usage: {CMD_PREFIX}snomask <+/-flags>"); return
mask = arg.strip()
if not re.match(r"^[a-zA-Z+\-]+$", mask):
self.preply(nick, reply_to, f"{nick}: invalid snomask string."); return
self.send(f"MODE {self._nick} +s {mask}")
self.preply(nick, reply_to, f"MODE {self._nick} +s {mask}")
log.info(f"Snomask set by {nick}: {mask}")
_VALID_LEVELS: tuple[str, ...] = ("DEBUG", "INFO", "WARNING", "ERROR")
async def cmd_loglevel(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Show or change log output level. Admin only."""
if not self._require_admin(nick, reply_to): return
p = CMD_PREFIX
if not arg:
lvl_name = logging.getLevelName(_log_filter.base_level)
lines = [f" base level = {lvl_name}"]
if _log_filter.global_debug:
lines.append(" global debug = ON")
active = _log_filter.active_subsystems()
if active:
lines.append(f" debug subsystems: {', '.join(sorted(active))}")
if LOG_DEBUG:
lines.append(f" debug file = {LOG_DEBUG}")
self.preply(nick, reply_to, "Log levels:")
for line in lines:
self.preply(nick, reply_to, line)
return
parts = arg.strip().split()
if len(parts) == 1:
level = parts[0].upper()
if level not in self._VALID_LEVELS:
self.preply(nick, reply_to,
f"{nick}: invalid level — use: {', '.join(self._VALID_LEVELS)}")
return
_log_filter.set_base_level(getattr(logging, level))
_log_filter.global_debug = False
self.preply(nick, reply_to, f"Base level set to {level}")
log.info(f"Log level set to {level} by {nick}")
elif len(parts) == 2:
target, level = parts[0], parts[1].upper()
if not target.startswith("internets"):
self.preply(nick, reply_to, f"{nick}: logger must start with 'internets'")
return
if level == "DEBUG":
full = target if "." in target else f"internets.{target}"
logging.getLogger(full).setLevel(logging.DEBUG)
_log_filter.add_subsystem(full)
self.preply(nick, reply_to, f"{full} = DEBUG")
log.info(f"Log level {full} = DEBUG by {nick}")
elif level == "NOTSET":
full = target if "." in target else f"internets.{target}"
logging.getLogger(full).setLevel(logging.NOTSET)
_log_filter.remove_subsystem(full)
self.preply(nick, reply_to, f"{full} = NOTSET (inherits parent)")
log.info(f"Log level {full} = NOTSET by {nick}")
elif level in self._VALID_LEVELS:
logging.getLogger(target).setLevel(getattr(logging, level))
_log_filter.remove_subsystem(target)
self.preply(nick, reply_to, f"{target} = {level}")
log.info(f"Log level {target} = {level} by {nick}")
else:
self.preply(nick, reply_to,
f"{nick}: invalid level — use: {', '.join(self._VALID_LEVELS)} or NOTSET")
else:
self.preply(nick, reply_to, f"usage: {p}loglevel [LEVEL | <logger> <LEVEL>]")
async def cmd_debug(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Toggle debug output globally or per-subsystem. Admin only."""
if not self._require_admin(nick, reply_to): return
if not arg or arg.strip().lower() == "on":
_log_filter.global_debug = True
self.preply(nick, reply_to, "Debug output ON (all subsystems)")
log.info(f"Debug ON by {nick}")
return
parts = arg.strip().lower().split()
if parts[0] == "off":
_log_filter.global_debug = False
_log_filter.clear_subsystems()
self.preply(nick, reply_to, f"Debug output OFF (back to {LOG_LEVEL})")
log.info(f"Debug OFF by {nick}")
return
subsys = f"internets.{parts[0]}" if not parts[0].startswith("internets") else parts[0]
if len(parts) >= 2 and parts[1] == "off":
logging.getLogger(subsys).setLevel(logging.NOTSET)
_log_filter.remove_subsystem(subsys)
self.preply(nick, reply_to, f"{subsys} debug OFF")
log.info(f"Debug {subsys} OFF by {nick}")
else:
logging.getLogger(subsys).setLevel(logging.DEBUG)
_log_filter.add_subsystem(subsys)
self.preply(nick, reply_to, f"{subsys} debug ON")
log.info(f"Debug {subsys} ON by {nick}")
async def cmd_shutdown(self, nick: str, reply_to: str, arg: str | None) -> None:
"""Graceful shutdown: save state, unload modules, quit. Admin only."""
if not self._require_admin(nick, reply_to): return
reason = arg.strip() if arg else "Shutting down"
self.preply(nick, reply_to, f"Shutting down: {reason}")
log.info(f"Shutdown by {nick}: {reason}")
self.request_shutdown(reason)
# ── Shutdown coordination ────────────────────────────────────────
def request_shutdown(self, reason: str = "Shutting down") -> None:
"""Thread-safe: request the event loop to shut down cleanly."""
self._quit_msg = f"QUIT :{reason}"
if self._stop and self._loop:
self._loop.call_soon_threadsafe(self._stop.set)
async def graceful_shutdown(self) -> None:
"""Clean exit: save state, unload modules, send QUIT, close socket."""
log.info("Graceful shutdown initiated.")
try:
self._store.channels_save(self.active_channels.snapshot())
except Exception as e:
log.warning(f"Channel save failed: {e}")
with self._mod_lock:
names = list(self._modules)
for name in names:
try:
ok, msg = self.unload_module(name)
log.info(f"Unload {name}: {msg}")
except Exception as e:
log.warning(f"Unload {name} failed: {e}")
try:
self._store.stop()
log.info("Store flushed to disk.")
except Exception as e:
log.warning(f"Store flush failed: {e}")
try:
self.send(self._quit_msg, priority=0)
except Exception:
pass
# Give the sender time to flush QUIT.
await asyncio.sleep(2)
if self._sender:
await self._sender.stop()
if self._writer:
try:
self._writer.close()
await self._writer.wait_closed()
except Exception:
pass
# Cancel all running tasks.
for task in self._tasks:
task.cancel()
log.info("Shutdown complete.")
# ── Dispatch ─────────────────────────────────────────────────────
def _dispatch(self, nick: str, reply_to: str, cmd: str,
arg: str | None, is_pm: bool) -> None:
"""Create an async task to run a command handler.
Called from _process() which runs in the event loop thread, so
loop.create_task() is safe. All handlers are coroutines.
"""
if cmd in ("auth", "deauth") and not is_pm:
self.privmsg(reply_to, f"{nick}: {CMD_PREFIX}{cmd} must be used in PM.")
return
if self.flood_limited(nick):
self.notice(nick, f"{nick}: slow down ({FLOOD_CD}s cooldown)")
log.debug(f"Flood drop: {cmd!r} from {nick}")
return
# BUG-031: Cap argument length to prevent oversized input DoS.
if arg and len(arg) > self._MAX_ARG_LEN:
self.notice(nick, f"{nick}: input too long (max {self._MAX_ARG_LEN} chars).")
return
# BUG-030: Cap concurrent command tasks.
active_cmd_tasks = sum(1 for t in self._tasks
if not t.done() and (t.get_name() or "").startswith("cmd-"))
if active_cmd_tasks >= self._MAX_TASKS:
self.notice(nick, f"{nick}: bot is busy — try again shortly.")
log.warning(f"Task cap reached ({self._MAX_TASKS}), dropped {cmd!r} from {nick}")
return
handler = None
if cmd in self._CORE:
handler = getattr(self, self._CORE[cmd])
else:
with self._mod_lock:
entry = self._commands.get(cmd)
inst = self._modules.get(entry[0]) if entry else None
if inst and entry:
handler = getattr(inst, entry[1])
if handler and self._loop:
task = self._loop.create_task(
self._run_cmd(handler, nick, reply_to, arg, cmd),
name=f"cmd-{cmd}",
)
self._tasks.append(task)
task.add_done_callback(lambda t: t in self._tasks and self._tasks.remove(t))
async def _run_cmd(self, handler: Any, nick: str, reply_to: str,
arg: str | None, cmd: str) -> None:
"""Run an async command handler as a task."""
try:
await handler(nick, reply_to, arg)
except Exception as e:
log.error(f"Command {cmd!r} from {nick} crashed: {e}", exc_info=True)
self.notice(nick, f"{nick}: internal error processing '{cmd}' — see log for details.")
# ── Connection ───────────────────────────────────────────────────
async def _connect(self) -> None:
"""Open an async SSL/plain connection to the IRC server."""
use_ssl = cfg["irc"].getboolean("ssl", fallback=True)
verify = cfg["irc"].getboolean("ssl_verify", fallback=True)